file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
gsheets.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from typing import Optional
from sqlalchemy.engine.url import URL
from superset import security_manager
from superset.db_engine_specs.sqlite import SqliteEngineSpec
class GSheetsEngineSpec(SqliteEngineSpec):
"""Engine for Google spreadsheets"""
engine = "gsheets"
engine_name = "Google Sheets"
allows_joins = False
allows_subqueries = True
@classmethod
def | (
cls, url: URL, impersonate_user: bool, username: Optional[str]
) -> None:
if impersonate_user and username is not None:
user = security_manager.find_user(username=username)
if user and user.email:
url.query["subject"] = user.email
| modify_url_for_impersonation |
message.go | package crypto
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"io"
"io/ioutil"
"regexp"
"runtime"
"github.com/ProtonMail/gopenpgp/v2/armor"
"github.com/ProtonMail/gopenpgp/v2/constants"
"github.com/ProtonMail/gopenpgp/v2/internal"
"golang.org/x/crypto/openpgp/clearsign"
"golang.org/x/crypto/openpgp/packet"
)
// ---- MODELS -----
// PlainMessage stores a plain text / unencrypted message.
type PlainMessage struct {
// The content of the message
Data []byte
// if the content is text or binary
TextType bool
}
// PGPMessage stores a PGP-encrypted message.
type PGPMessage struct {
// The content of the message
Data []byte
}
// PGPSignature stores a PGP-encoded detached signature.
type PGPSignature struct {
// The content of the signature
Data []byte
}
// PGPSplitMessage contains a separate session key packet and symmetrically
// encrypted data packet.
type PGPSplitMessage struct {
DataPacket []byte
KeyPacket []byte
}
// A ClearTextMessage is a signed but not encrypted PGP message,
// i.e. the ones beginning with -----BEGIN PGP SIGNED MESSAGE-----.
type ClearTextMessage struct {
Data []byte
Signature []byte
}
// ---- GENERATORS -----
// NewPlainMessage generates a new binary PlainMessage ready for encryption,
// signature, or verification from the unencrypted binary data.
func NewPlainMessage(data []byte) *PlainMessage {
return &PlainMessage{
Data: clone(data),
TextType: false,
}
}
// NewPlainMessageFromString generates a new text PlainMessage,
// ready for encryption, signature, or verification from an unencrypted string.
func NewPlainMessageFromString(text string) *PlainMessage {
return &PlainMessage{
Data: []byte(text),
TextType: true,
}
}
// NewPGPMessage generates a new PGPMessage from the unarmored binary data.
func NewPGPMessage(data []byte) *PGPMessage {
return &PGPMessage{
Data: clone(data),
}
}
// NewPGPMessageFromArmored generates a new PGPMessage from an armored string ready for decryption.
func NewPGPMessageFromArmored(armored string) (*PGPMessage, error) {
encryptedIO, err := internal.Unarmor(armored)
if err != nil {
return nil, err
}
message, err := ioutil.ReadAll(encryptedIO.Body)
if err != nil {
return nil, err
}
return &PGPMessage{
Data: message,
}, nil
}
// NewPGPSplitMessage generates a new PGPSplitMessage from the binary unarmored keypacket,
// datapacket, and encryption algorithm.
func NewPGPSplitMessage(keyPacket []byte, dataPacket []byte) *PGPSplitMessage {
return &PGPSplitMessage{
KeyPacket: clone(keyPacket),
DataPacket: clone(dataPacket),
}
}
// NewPGPSplitMessageFromArmored generates a new PGPSplitMessage by splitting an armored message into its
// session key packet and symmetrically encrypted data packet.
func NewPGPSplitMessageFromArmored(encrypted string) (*PGPSplitMessage, error) {
message, err := NewPGPMessageFromArmored(encrypted)
if err != nil {
return nil, err
}
return message.SeparateKeyAndData(len(encrypted), -1)
}
// NewPGPSignature generates a new PGPSignature from the unarmored binary data.
func NewPGPSignature(data []byte) *PGPSignature {
return &PGPSignature{
Data: clone(data),
}
}
// NewPGPSignatureFromArmored generates a new PGPSignature from the armored
// string ready for verification.
func NewPGPSignatureFromArmored(armored string) (*PGPSignature, error) {
encryptedIO, err := internal.Unarmor(armored)
if err != nil {
return nil, err
}
signature, err := ioutil.ReadAll(encryptedIO.Body)
if err != nil {
return nil, err
}
return &PGPSignature{
Data: signature,
}, nil
}
// NewClearTextMessage generates a new ClearTextMessage from data and
// signature.
func NewClearTextMessage(data []byte, signature []byte) *ClearTextMessage {
return &ClearTextMessage{
Data: clone(data),
Signature: clone(signature),
}
}
// NewClearTextMessageFromArmored returns the message body and unarmored
// signature from a clearsigned message.
func NewClearTextMessageFromArmored(signedMessage string) (*ClearTextMessage, error) {
modulusBlock, rest := clearsign.Decode([]byte(signedMessage))
if len(rest) != 0 {
return nil, errors.New("gopenpgp: extra data after modulus")
}
signature, err := ioutil.ReadAll(modulusBlock.ArmoredSignature.Body)
if err != nil {
return nil, err
}
return NewClearTextMessage(modulusBlock.Bytes, signature), nil
}
// ---- MODEL METHODS -----
// GetBinary returns the binary content of the message as a []byte.
func (msg *PlainMessage) GetBinary() []byte {
return msg.Data
}
// GetString returns the content of the message as a string.
func (msg *PlainMessage) GetString() string {
return string(msg.Data)
}
// GetBase64 returns the base-64 encoded binary content of the message as a
// string.
func (msg *PlainMessage) GetBase64() string {
return base64.StdEncoding.EncodeToString(msg.Data)
}
// NewReader returns a New io.Reader for the binary data of the message.
func (msg *PlainMessage) NewReader() io.Reader {
return bytes.NewReader(msg.GetBinary())
}
// IsText returns whether the message is a text message.
func (msg *PlainMessage) IsText() bool {
return msg.TextType
}
// IsBinary returns whether the message is a binary message.
func (msg *PlainMessage) IsBinary() bool {
return !msg.TextType
}
// GetBinary returns the unarmored binary content of the message as a []byte.
func (msg *PGPMessage) GetBinary() []byte {
return msg.Data
}
// NewReader returns a New io.Reader for the unarmored binary data of the
// message.
func (msg *PGPMessage) NewReader() io.Reader {
return bytes.NewReader(msg.GetBinary())
}
// GetArmored returns the armored message as a string.
func (msg *PGPMessage) GetArmored() (string, error) {
return armor.ArmorWithType(msg.Data, constants.PGPMessageHeader)
}
// GetArmoredWithCustomHeaders returns the armored message as a string, with
// the given headers. Empty parameters are omitted from the headers.
func (msg *PGPMessage) GetArmoredWithCustomHeaders(comment, version string) (string, error) {
return armor.ArmorWithTypeAndCustomHeaders(msg.Data, constants.PGPMessageHeader, version, comment)
}
// getEncryptionKeyIds Returns the key IDs of the keys to which the session key is encrypted.
func (msg *PGPMessage) getEncryptionKeyIDs() ([]uint64, bool) {
packets := packet.NewReader(bytes.NewReader(msg.Data))
var err error
var ids []uint64
var encryptedKey *packet.EncryptedKey
Loop:
for {
var p packet.Packet
if p, err = packets.Next(); err == io.EOF {
break
}
switch p := p.(type) {
case *packet.EncryptedKey:
encryptedKey = p
ids = append(ids, encryptedKey.KeyId)
case *packet.SymmetricallyEncrypted,
*packet.AEADEncrypted,
*packet.Compressed,
*packet.LiteralData:
break Loop
}
}
if len(ids) > 0 {
return ids, true
}
return ids, false
}
// GetBinaryDataPacket returns the unarmored binary datapacket as a []byte.
func (msg *PGPSplitMessage) GetBinaryDataPacket() []byte {
return msg.DataPacket
}
// GetBinaryKeyPacket returns the unarmored binary keypacket as a []byte.
func (msg *PGPSplitMessage) GetBinaryKeyPacket() []byte {
return msg.KeyPacket
}
// GetBinary returns the unarmored binary joined packets as a []byte.
func (msg *PGPSplitMessage) GetBinary() []byte {
return append(msg.KeyPacket, msg.DataPacket...)
}
// GetArmored returns the armored message as a string, with joined data and key
// packets.
func (msg *PGPSplitMessage) GetArmored() (string, error) {
return armor.ArmorWithType(msg.GetBinary(), constants.PGPMessageHeader)
}
// GetPGPMessage joins asymmetric session key packet with the symmetric data
// packet to obtain a PGP message.
func (msg *PGPSplitMessage) GetPGPMessage() *PGPMessage {
return NewPGPMessage(append(msg.KeyPacket, msg.DataPacket...))
}
// SeparateKeyAndData returns the first keypacket and the (hopefully unique)
// dataPacket (not verified).
// * estimatedLength is the estimate length of the message.
// * garbageCollector > 0 activates the garbage collector.
func (msg *PGPMessage) SeparateKeyAndData(estimatedLength, garbageCollector int) (outSplit *PGPSplitMessage, err error) {
// For info on each, see: https://golang.org/pkg/runtime/#MemStats
packets := packet.NewReader(bytes.NewReader(msg.Data))
outSplit = &PGPSplitMessage{}
gcCounter := 0
// Store encrypted key and symmetrically encrypted packet separately
var encryptedKey *packet.EncryptedKey
for {
var p packet.Packet
if p, err = packets.Next(); err == io.EOF {
err = nil
break
}
switch p := p.(type) {
case *packet.EncryptedKey:
if encryptedKey != nil && encryptedKey.Key != nil {
break
}
encryptedKey = p
case *packet.SymmetricallyEncrypted:
// TODO: add support for multiple keypackets
var b bytes.Buffer
// 2^16 is an estimation of the size difference between input and output, the size difference is most probably
// 16 bytes at a maximum though.
// We need to avoid triggering a grow from the system as this will allocate too much memory causing problems
// in low-memory environments
b.Grow(1<<16 + estimatedLength)
// empty encoded length + start byte
if _, err := b.Write(make([]byte, 6)); err != nil {
return nil, err
}
if err := b.WriteByte(byte(1)); err != nil {
return nil, err
}
actualLength := 1
block := make([]byte, 128)
for {
n, err := p.Contents.Read(block)
if err == io.EOF |
if _, err := b.Write(block[:n]); err != nil {
return nil, err
}
actualLength += n
gcCounter += n
if gcCounter > garbageCollector && garbageCollector > 0 {
runtime.GC()
gcCounter = 0
}
}
// quick encoding
symEncryptedData := b.Bytes()
switch {
case actualLength < 192:
symEncryptedData[4] = byte(210)
symEncryptedData[5] = byte(actualLength)
symEncryptedData = symEncryptedData[4:]
case actualLength < 8384:
actualLength -= 192
symEncryptedData[3] = byte(210)
symEncryptedData[4] = 192 + byte(actualLength>>8)
symEncryptedData[5] = byte(actualLength)
symEncryptedData = symEncryptedData[3:]
default:
symEncryptedData[0] = byte(210)
symEncryptedData[1] = byte(255)
symEncryptedData[2] = byte(actualLength >> 24)
symEncryptedData[3] = byte(actualLength >> 16)
symEncryptedData[4] = byte(actualLength >> 8)
symEncryptedData[5] = byte(actualLength)
}
outSplit.DataPacket = symEncryptedData
}
}
if encryptedKey == nil {
return nil, errors.New("gopenpgp: packets don't include an encrypted key packet")
}
var buf bytes.Buffer
if err := encryptedKey.Serialize(&buf); err != nil {
return nil, fmt.Errorf("gopenpgp: cannot serialize encrypted key: %v", err)
}
outSplit.KeyPacket = buf.Bytes()
return outSplit, nil
}
// GetBinary returns the unarmored binary content of the signature as a []byte.
func (msg *PGPSignature) GetBinary() []byte {
return msg.Data
}
// GetArmored returns the armored signature as a string.
func (msg *PGPSignature) GetArmored() (string, error) {
return armor.ArmorWithType(msg.Data, constants.PGPSignatureHeader)
}
// GetBinary returns the unarmored signed data as a []byte.
func (msg *ClearTextMessage) GetBinary() []byte {
return msg.Data
}
// GetString returns the unarmored signed data as a string.
func (msg *ClearTextMessage) GetString() string {
return string(msg.Data)
}
// GetBinarySignature returns the unarmored binary signature as a []byte.
func (msg *ClearTextMessage) GetBinarySignature() []byte {
return msg.Signature
}
// GetArmored armors plaintext and signature with the PGP SIGNED MESSAGE
// armoring.
func (msg *ClearTextMessage) GetArmored() (string, error) {
armSignature, err := armor.ArmorWithType(msg.GetBinarySignature(), constants.PGPSignatureHeader)
if err != nil {
return "", err
}
str := "-----BEGIN PGP SIGNED MESSAGE-----\r\nHash: SHA512\r\n\r\n"
str += msg.GetString()
str += "\r\n"
str += armSignature
return str, nil
}
// ---- UTILS -----
// IsPGPMessage checks if data if has armored PGP message format.
func IsPGPMessage(data string) bool {
re := regexp.MustCompile("^-----BEGIN " + constants.PGPMessageHeader + "-----(?s:.+)-----END " +
constants.PGPMessageHeader + "-----")
return re.MatchString(data)
}
| {
break
} |
cri_attributes.rs | use crate::{
error::{X509Error, X509Result},
extensions::X509Extension,
};
use der_parser::der::{
der_read_element_header, parse_der_oid, parse_der_sequence_defined_g, DerTag,
};
use der_parser::error::BerError;
use der_parser::oid::Oid;
use nom::combinator::map_res;
use nom::Err;
use oid_registry::*;
use std::collections::HashMap;
/// Attributes for Certification Request
#[derive(Debug, PartialEq)]
pub struct X509CriAttribute<'a> {
pub oid: Oid<'a>,
pub value: &'a [u8],
pub(crate) parsed_attribute: ParsedCriAttribute<'a>,
}
impl<'a> X509CriAttribute<'a> {
pub fn from_der(i: &'a [u8]) -> X509Result<X509CriAttribute> {
parse_der_sequence_defined_g(|i, _| {
let (i, oid) = map_res(parse_der_oid, |x| x.as_oid_val())(i)?;
let value_start = i;
let (i, hdr) = der_read_element_header(i)?;
if hdr.tag != DerTag::Set {
return Err(Err::Error(BerError::BerTypeError));
};
let (i, parsed_attribute) = crate::cri_attributes::parser::parse_attribute(i, &oid)?;
let ext = X509CriAttribute {
oid,
value: &value_start[..value_start.len() - i.len()],
parsed_attribute,
};
Ok((i, ext))
})(i)
.map_err(|_| X509Error::InvalidAttributes.into())
}
} | pub struct ExtensionRequest<'a> {
pub extensions: HashMap<Oid<'a>, X509Extension<'a>>,
}
/// Attributes for Certification Request
#[derive(Debug, PartialEq)]
pub enum ParsedCriAttribute<'a> {
ExtensionRequest(ExtensionRequest<'a>),
UnsupportedAttribute,
}
pub(crate) mod parser {
use crate::cri_attributes::*;
use der_parser::error::BerError;
use der_parser::{oid::Oid, *};
use lazy_static::lazy_static;
use nom::{Err, IResult};
type AttrParser = fn(&[u8]) -> IResult<&[u8], ParsedCriAttribute, BerError>;
lazy_static! {
static ref ATTRIBUTE_PARSERS: HashMap<Oid<'static>, AttrParser> = {
macro_rules! add {
($m:ident, $oid:ident, $p:ident) => {
$m.insert($oid, $p as AttrParser);
};
}
let mut m = HashMap::new();
add!(m, OID_PKCS9_EXTENSION_REQUEST, parse_extension_request);
m
};
}
// look into the parser map if the extension is known, and parse it
// otherwise, leave it as UnsupportedExtension
pub(crate) fn parse_attribute<'a>(
i: &'a [u8],
oid: &Oid,
) -> IResult<&'a [u8], ParsedCriAttribute<'a>, BerError> {
if let Some(parser) = ATTRIBUTE_PARSERS.get(oid) {
parser(i)
} else {
Ok((i, ParsedCriAttribute::UnsupportedAttribute))
}
}
fn parse_extension_request<'a>(
i: &'a [u8],
) -> IResult<&'a [u8], ParsedCriAttribute<'a>, BerError> {
crate::extensions::parse_extension_sequence(i)
.and_then(|(i, extensions)| {
crate::extensions::extensions_sequence_to_map(i, extensions)
})
.map(|(i, extensions)| {
(
i,
ParsedCriAttribute::ExtensionRequest(ExtensionRequest { extensions }),
)
})
.map_err(|_| Err::Error(BerError::BerTypeError))
}
}
fn attributes_sequence_to_map<'a>(
i: &'a [u8],
v: Vec<X509CriAttribute<'a>>,
) -> X509Result<'a, HashMap<Oid<'a>, X509CriAttribute<'a>>> {
let mut attributes = HashMap::new();
for attr in v.into_iter() {
if attributes.insert(attr.oid.clone(), attr).is_some() {
// duplicate attributes are not allowed
return Err(Err::Failure(X509Error::DuplicateAttributes));
}
}
Ok((i, attributes))
}
pub(crate) fn parse_cri_attributes(i: &[u8]) -> X509Result<HashMap<Oid, X509CriAttribute>> {
let (i, hdr) = der_read_element_header(i).or(Err(Err::Error(X509Error::InvalidAttributes)))?;
if i.is_empty() {
return Ok((i, HashMap::new()));
}
(0..hdr.structured)
.into_iter()
.try_fold((i, Vec::new()), |(i, mut attrs), _| {
let (rem, attr) = X509CriAttribute::from_der(i)?;
attrs.push(attr);
Ok((rem, attrs))
})
.and_then(|(i, attrs)| attributes_sequence_to_map(i, attrs))
} |
/// Section 3.1 of rfc 5272
#[derive(Debug, PartialEq)] |
apply.go | package perf
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strconv"
"strings"
"github.com/asaskevich/govalidator"
"github.com/layer5io/meshery/mesheryctl/internal/cli/root/config"
"github.com/layer5io/meshery/mesheryctl/pkg/utils"
"github.com/layer5io/meshery/models"
log "github.com/sirupsen/logrus"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var (
profileName string
testURL string
testName string
testMesh string
qps string
concurrentRequests string
testDuration string
loadGenerator string
filePath string
)
var applyCmd = &cobra.Command{
Use: "apply",
Short: "Run a Performance test",
Long: `Run Performance test using existing profiles or using flags`,
Args: cobra.MinimumNArgs(0),
Example: `
Execute a Performance test with the specified performance profile
mesheryctl perf apply <profile name> --flags
Execute a Performance test without a specified performance profile
mesheryctl perf apply --profile <profile-name> --url <url>
Run Performance test using SMP compatible test configuration
mesheryctl perf apply -f <filepath>
`,
RunE: func(cmd *cobra.Command, args []string) error {
var req *http.Request
client := &http.Client{}
var profileID string
mctlCfg, err := config.GetMesheryCtl(viper.GetViper())
if err != nil {
return errors.Wrap(err, "error processing config")
}
// Importing SMP Configuration from the file
if filePath != "" {
smpConfig, err := ioutil.ReadFile(filePath)
if err != nil {
return err
}
req, err = http.NewRequest("POST", mctlCfg.GetBaseMesheryURL()+"/api/perf/load-test-smps", bytes.NewBuffer(smpConfig))
if err != nil {
return errors.Wrapf(err, utils.PerfError("Failed to invoke performance test"))
}
} else {
// Run test based on flags
if testName == "" {
log.Debug("Test Name not provided")
testName = utils.StringWithCharset(8)
log.Debug("Using random test name: ", testName)
}
// If a profile is not provided, then create a new profile
if len(args) == 0 { // First need to create a profile id
log.Debug("Creating new performance profile")
if profileName == "" {
return errors.New(utils.PerfError("please enter a profile-name"))
}
// ask for test url first
if testURL == "" {
return errors.New(utils.PerfError("please enter a test URL"))
}
// Method to check if the entered Test URL is valid or not
if validURL := govalidator.IsURL(testURL); !validURL {
return errors.New(utils.PerfError("please enter a valid test URL"))
}
convReq, err := strconv.Atoi(concurrentRequests)
if err != nil {
return errors.New("failed to convert concurrent-request")
}
convQPS, err := strconv.Atoi(qps)
if err != nil {
return errors.New("failed to convert qps")
}
values := map[string]interface{}{
"concurrent_request": convReq,
"duration": testDuration,
"endpoints": []string{testURL},
"load_generators": []string{loadGenerator},
"name": profileName,
"qps": convQPS,
"service_mesh": testMesh,
}
jsonValue, err := json.Marshal(values)
if err != nil {
return err
}
req, err = http.NewRequest("POST", mctlCfg.GetBaseMesheryURL()+"/api/user/performance/profiles", bytes.NewBuffer(jsonValue))
if err != nil {
return err
}
err = utils.AddAuthDetails(req, tokenPath)
if err != nil {
return errors.New("authentication token not found. please supply a valid user token with the --token (or -t) flag")
}
resp, err := client.Do(req)
if err != nil {
return err
}
var response *models.PerformanceProfile
// failsafe for the case when a valid uuid v4 is not an id of any pattern (bad api call)
if resp.StatusCode != 200 {
return errors.Errorf("Response Status Code %d, possible Server Error", resp.StatusCode)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return errors.Wrap(err, utils.PerfError("failed to read response body"))
}
err = json.Unmarshal(body, &response)
if err != nil {
return errors.Wrap(err, "failed to unmarshal response body")
}
profileID = response.ID.String() | // Merge args to get profile-name
profileName = strings.Join(args, "%20")
// search and fetch performance profile with profile-name
log.Debug("Fetching performance profile")
req, err = http.NewRequest("GET", mctlCfg.GetBaseMesheryURL()+"/api/user/performance/profiles?search="+profileName, nil)
if err != nil {
return err
}
err = utils.AddAuthDetails(req, tokenPath)
if err != nil {
return errors.New("authentication token not found. please supply a valid user token with the --token (or -t) flag")
}
resp, err := client.Do(req)
if err != nil {
return err
}
var response *models.PerformanceProfilesAPIResponse
// failsafe for the case when a valid uuid v4 is not an id of any pattern (bad api call)
if resp.StatusCode != 200 {
return errors.Errorf("Response Status Code %d, possible Server Error", resp.StatusCode)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return errors.Wrap(err, utils.PerfError("failed to read response body"))
}
err = json.Unmarshal(body, &response)
if err != nil {
return errors.Wrap(err, "failed to unmarshal response body")
}
index := 0
if len(response.Profiles) == 0 {
return errors.New("no profiles found with the given name")
} else if len(response.Profiles) == 1 {
profileID = response.Profiles[0].ID.String()
} else {
// Multiple profiles with same name
index = multipleProfileConfirmation(response.Profiles)
profileID = response.Profiles[index].ID.String()
}
// what if user passed profile-name but didn't passed the url
// we use url from performance profile
if testURL == "" {
testURL = response.Profiles[index].Endpoints[0]
}
// reset profile name without %20
profileName = response.Profiles[index].Name
}
if testURL == "" {
return errors.New(utils.PerfError("please enter a test URL"))
}
log.Debugf("performance profile is: %s", profileName)
log.Debugf("test-url set to %s", testURL)
// Method to check if the entered Test URL is valid or not
if validURL := govalidator.IsURL(testURL); !validURL {
return errors.New(utils.PerfError("please enter a valid test URL"))
}
req, err = http.NewRequest("GET", mctlCfg.GetBaseMesheryURL()+"/api/user/performance/profiles/"+profileID+"/run", nil)
if err != nil {
return err
}
q := req.URL.Query()
q.Add("name", testName)
q.Add("loadGenerator", loadGenerator)
q.Add("c", concurrentRequests)
q.Add("url", testURL)
q.Add("qps", qps)
durLen := len(testDuration)
q.Add("dur", string(testDuration[durLen-1]))
q.Add("t", string(testDuration[:durLen-1]))
if testMesh != "" {
q.Add("mesh", testMesh)
}
req.URL.RawQuery = q.Encode()
}
log.Info("Initiating Performance test ...")
err = utils.AddAuthDetails(req, tokenPath)
if err != nil {
return errors.New("authentication token not found. please supply a valid user token with the --token (or -t) flag")
}
resp, err := client.Do(req)
if err != nil {
return errors.Wrapf(err, utils.PerfError(fmt.Sprintf("failed to make request to %s", testURL)))
}
if utils.ContentTypeIsHTML(resp) {
return errors.New("failed to run test")
}
if resp.StatusCode != 200 {
return errors.Errorf("Response Status Code %d, possible Server Error", resp.StatusCode)
}
defer utils.SafeClose(resp.Body)
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return errors.Wrap(err, utils.PerfError("failed to read response body"))
}
log.Debug(string(data))
if err := utils.UpdateAuthDetails(tokenPath); err != nil {
return errors.Wrap(err, utils.PerfError("failed to update auth details"))
}
log.Info("Test Completed Successfully!")
return nil
},
}
func multipleProfileConfirmation(profiles []models.PerformanceProfile) int {
reader := bufio.NewReader(os.Stdin)
for index, a := range profiles {
fmt.Printf("Index: %v\n", index)
fmt.Printf("Name: %v\n", a.Name)
fmt.Printf("ID: %s\n", a.ID.String())
fmt.Printf("Endpoint: %v\n", a.Endpoints[0])
fmt.Printf("Load Generators: %v\n", a.LoadGenerators[0])
fmt.Println("---------------------")
}
for {
fmt.Printf("Enter the index of profile: ")
response, err := reader.ReadString('\n')
if err != nil {
log.Fatal(err)
}
response = strings.ToLower(strings.TrimSpace(response))
index, err := strconv.Atoi(response)
if err != nil {
log.Info(err)
}
if index < 0 || index >= len(profiles) {
log.Info("Invalid index")
} else {
return index
}
}
}
func init() {
applyCmd.Flags().StringVar(&testURL, "url", "", "(required/optional) Endpoint URL to test")
applyCmd.Flags().StringVar(&testName, "name", "", "(optional) Name of the Test")
applyCmd.Flags().StringVar(&profileName, "profile", "", "(required/optional) Name for the new Performance Profile")
applyCmd.Flags().StringVar(&testMesh, "mesh", "None", "(optional) Name of the Service Mesh")
applyCmd.Flags().StringVar(&qps, "qps", "0", "(optional) Queries per second")
applyCmd.Flags().StringVar(&concurrentRequests, "concurrent-requests", "1", "(optional) Number of Parallel Requests")
applyCmd.Flags().StringVar(&testDuration, "duration", "30s", "(optional) Length of test (e.g. 10s, 5m, 2h). For more, see https://golang.org/pkg/time/#ParseDuration")
applyCmd.Flags().StringVar(&loadGenerator, "load-generator", "fortio", "(optional) Load-Generator to be used (fortio/wrk2)")
applyCmd.Flags().StringVar(&filePath, "file", "", "(optional) file containing SMP-compatible test configuration. For more, see https://github.com/layer5io/service-mesh-performance-specification")
_ = listCmd.MarkFlagRequired("token")
} | profileName = response.Name
log.Debug("New profile created")
} else { // set profile-name from args |
boot.py | import axp192
import kv
try:
# for m5stack-core2 only
axp = axp192.Axp192()
axp.powerAll()
axp.setLCDBrightness(80) # 设置背光亮度 0~100
except OSError:
print("make sure axp192.py is in libs folder")
def _on_get_url(url):
kv.set('_amp_pyapp_url', url)
execfile('/lib/appOta.py')
| sta_if.active(True)
sta_if.scan()
sta_if.connect(ssid, passwd)
channel = kv.get('app_upgrade_channel')
if channel == "disable":
pass
else:
ssid = kv.get('_amp_wifi_ssid')
passwd = kv.get('_amp_wifi_passwd')
if isinstance(ssid, str) and isinstance(passwd, str):
_connect_wifi(ssid, passwd)
import online_upgrade
online_upgrade.on(_on_get_url) | def _connect_wifi(ssid, passwd):
import network
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected(): |
ofctl_v1_4.py | # Copyright (C) 2016 Nippon Telegraph and Telephone Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from ryu.ofproto import ether
from ryu.ofproto import ofproto_v1_4
from ryu.ofproto import ofproto_v1_4_parser
from ryu.lib import ofctl_utils
LOG = logging.getLogger(__name__)
DEFAULT_TIMEOUT = 1.0
UTIL = ofctl_utils.OFCtlUtil(ofproto_v1_4)
str_to_int = ofctl_utils.str_to_int
def to_action(dp, dic):
ofp = dp.ofproto
parser = dp.ofproto_parser
action_type = dic.get('type')
return ofctl_utils.to_action(dic, ofp, parser, action_type, UTIL)
def _get_actions(dp, dics):
actions = []
for d in dics:
action = to_action(dp, d)
if action is not None:
actions.append(action)
else:
LOG.error('Unknown action type: %s', d)
return actions
def to_instructions(dp, insts):
instructions = []
ofp = dp.ofproto
parser = dp.ofproto_parser
for i in insts:
inst_type = i.get('type')
if inst_type in ['APPLY_ACTIONS', 'WRITE_ACTIONS']:
dics = i.get('actions', [])
actions = _get_actions(dp, dics)
if actions:
if inst_type == 'APPLY_ACTIONS':
instructions.append(
parser.OFPInstructionActions(ofp.OFPIT_APPLY_ACTIONS,
actions))
else:
instructions.append(
parser.OFPInstructionActions(ofp.OFPIT_WRITE_ACTIONS,
actions))
elif inst_type == 'CLEAR_ACTIONS':
instructions.append(
parser.OFPInstructionActions(ofp.OFPIT_CLEAR_ACTIONS, []))
elif inst_type == 'GOTO_TABLE':
table_id = str_to_int(i.get('table_id'))
instructions.append(parser.OFPInstructionGotoTable(table_id))
elif inst_type == 'WRITE_METADATA':
metadata = str_to_int(i.get('metadata'))
metadata_mask = (str_to_int(i['metadata_mask'])
if 'metadata_mask' in i
else parser.UINT64_MAX)
instructions.append(
parser.OFPInstructionWriteMetadata(
metadata, metadata_mask))
elif inst_type == 'METER':
meter_id = str_to_int(i.get('meter_id'))
instructions.append(parser.OFPInstructionMeter(meter_id))
else:
LOG.error('Unknown instruction type: %s', inst_type)
return instructions
def action_to_str(act):
s = act.to_jsondict()[act.__class__.__name__]
t = UTIL.ofp_action_type_to_user(s['type'])
s['type'] = t if t != s['type'] else 'UNKNOWN'
if 'field' in s:
field = s.pop('field')
s['field'] = field['OXMTlv']['field']
s['mask'] = field['OXMTlv']['mask']
s['value'] = field['OXMTlv']['value']
return s
def instructions_to_str(instructions):
s = []
for i in instructions:
v = i.to_jsondict()[i.__class__.__name__]
t = UTIL.ofp_instruction_type_to_user(v['type'])
inst_type = t if t != v['type'] else 'UNKNOWN'
# apply/write/clear-action instruction
if isinstance(i, ofproto_v1_4_parser.OFPInstructionActions):
acts = []
for a in i.actions:
acts.append(action_to_str(a))
v['type'] = inst_type
v['actions'] = acts
s.append(v)
# others
else:
v['type'] = inst_type
s.append(v)
return s
def to_match(dp, attrs):
convert = {'in_port': UTIL.ofp_port_from_user,
'in_phy_port': str_to_int,
'metadata': ofctl_utils.to_match_masked_int,
'eth_dst': ofctl_utils.to_match_eth,
'eth_src': ofctl_utils.to_match_eth,
'eth_type': str_to_int,
'vlan_vid': to_match_vid,
'vlan_pcp': str_to_int,
'ip_dscp': str_to_int,
'ip_ecn': str_to_int,
'ip_proto': str_to_int,
'ipv4_src': ofctl_utils.to_match_ip,
'ipv4_dst': ofctl_utils.to_match_ip,
'tcp_src': str_to_int,
'tcp_dst': str_to_int,
'udp_src': str_to_int,
'udp_dst': str_to_int,
'sctp_src': str_to_int,
'sctp_dst': str_to_int,
'icmpv4_type': str_to_int,
'icmpv4_code': str_to_int,
'arp_op': str_to_int,
'arp_spa': ofctl_utils.to_match_ip,
'arp_tpa': ofctl_utils.to_match_ip,
'arp_sha': ofctl_utils.to_match_eth,
'arp_tha': ofctl_utils.to_match_eth,
'ipv6_src': ofctl_utils.to_match_ip,
'ipv6_dst': ofctl_utils.to_match_ip,
'ipv6_flabel': str_to_int,
'icmpv6_type': str_to_int,
'icmpv6_code': str_to_int,
'ipv6_nd_target': ofctl_utils.to_match_ip,
'ipv6_nd_sll': ofctl_utils.to_match_eth,
'ipv6_nd_tll': ofctl_utils.to_match_eth,
'mpls_label': str_to_int,
'mpls_tc': str_to_int,
'mpls_bos': str_to_int,
'pbb_isid': ofctl_utils.to_match_masked_int,
'tunnel_id': ofctl_utils.to_match_masked_int,
'ipv6_exthdr': ofctl_utils.to_match_masked_int,
'pbb_uca': str_to_int}
keys = {'dl_dst': 'eth_dst',
'dl_src': 'eth_src',
'dl_type': 'eth_type',
'dl_vlan': 'vlan_vid',
'nw_src': 'ipv4_src',
'nw_dst': 'ipv4_dst',
'nw_proto': 'ip_proto'}
if attrs.get('eth_type') == ether.ETH_TYPE_ARP:
if 'ipv4_src' in attrs and 'arp_spa' not in attrs:
attrs['arp_spa'] = attrs['ipv4_src']
del attrs['ipv4_src']
if 'ipv4_dst' in attrs and 'arp_tpa' not in attrs:
attrs['arp_tpa'] = attrs['ipv4_dst']
del attrs['ipv4_dst']
kwargs = {}
for key, value in attrs.items():
if key in keys:
# For old field name
key = keys[key]
if key in convert:
value = convert[key](value)
kwargs[key] = value
else:
LOG.error('Unknown match field: %s', key)
return dp.ofproto_parser.OFPMatch(**kwargs)
def to_match_vid(value):
return ofctl_utils.to_match_vid(value, ofproto_v1_4.OFPVID_PRESENT)
def match_to_str(ofmatch):
match = {}
ofmatch = ofmatch.to_jsondict()['OFPMatch']
ofmatch = ofmatch['oxm_fields']
for match_field in ofmatch:
key = match_field['OXMTlv']['field']
mask = match_field['OXMTlv']['mask']
value = match_field['OXMTlv']['value']
if key == 'vlan_vid':
value = match_vid_to_str(value, mask)
elif key == 'in_port':
value = UTIL.ofp_port_to_user(value)
else:
if mask is not None:
value = str(value) + '/' + str(mask)
match.setdefault(key, value)
return match
def match_vid_to_str(value, mask):
return ofctl_utils.match_vid_to_str(
value, mask, ofproto_v1_4.OFPVID_PRESENT)
def wrap_dpid_dict(dp, value, to_user=True):
if to_user:
return {str(dp.id): value}
return {dp.id: value}
def get_desc_stats(dp, waiters, to_user=True):
stats = dp.ofproto_parser.OFPDescStatsRequest(dp, 0)
msgs = []
ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG)
s = {}
for msg in msgs:
stats = msg.body
s = stats.to_jsondict()[stats.__class__.__name__]
return wrap_dpid_dict(dp, s, to_user)
def get_queue_stats(dp, waiters, port_no=None, queue_id=None, to_user=True):
if port_no is None:
port_no = dp.ofproto.OFPP_ANY
else:
port_no = UTIL.ofp_port_from_user(port_no)
if queue_id is None:
queue_id = dp.ofproto.OFPQ_ALL
else:
queue_id = UTIL.ofp_queue_from_user(queue_id)
stats = dp.ofproto_parser.OFPQueueStatsRequest(
dp, 0, port_no, queue_id)
msgs = []
ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG)
desc = []
for msg in msgs:
stats = msg.body
for stat in stats:
s = stat.to_jsondict()[stat.__class__.__name__]
properties = []
for prop in stat.properties:
p = prop.to_jsondict()[prop.__class__.__name__]
if to_user:
t = UTIL.ofp_queue_stats_prop_type_to_user(prop.type)
p['type'] = t if t != p['type'] else 'UNKNOWN'
properties.append(p)
s['properties'] = properties
desc.append(s)
return wrap_dpid_dict(dp, desc, to_user)
def get_queue_desc(dp, waiters, port_no=None, queue_id=None, to_user=True):
if port_no is None:
port_no = dp.ofproto.OFPP_ANY
else:
port_no = UTIL.ofp_port_from_user(port_no)
if queue_id is None:
queue_id = dp.ofproto.OFPQ_ALL
else:
queue_id = UTIL.ofp_queue_from_user(queue_id)
stats = dp.ofproto_parser.OFPQueueDescStatsRequest(
dp, 0, port_no, queue_id)
msgs = []
ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG)
configs = []
for msg in msgs:
for queue in msg.body:
q = queue.to_jsondict()[queue.__class__.__name__]
prop_list = []
for prop in queue.properties:
p = prop.to_jsondict()[prop.__class__.__name__]
if to_user:
t = UTIL.ofp_queue_desc_prop_type_to_user(prop.type)
p['type'] = t if t != prop.type else 'UNKNOWN'
prop_list.append(p)
q['properties'] = prop_list
configs.append(q)
return wrap_dpid_dict(dp, configs, to_user)
def get_flow_stats(dp, waiters, flow=None, to_user=True):
flow = flow if flow else {}
table_id = UTIL.ofp_table_from_user(
flow.get('table_id', dp.ofproto.OFPTT_ALL))
flags = str_to_int(flow.get('flags', 0))
out_port = UTIL.ofp_port_from_user(
flow.get('out_port', dp.ofproto.OFPP_ANY))
out_group = UTIL.ofp_group_from_user(
flow.get('out_group', dp.ofproto.OFPG_ANY))
cookie = str_to_int(flow.get('cookie', 0))
cookie_mask = str_to_int(flow.get('cookie_mask', 0))
match = to_match(dp, flow.get('match', {}))
# Note: OpenFlow does not allow to filter flow entries by priority,
# but for efficiency, ofctl provides the way to do it.
priority = str_to_int(flow.get('priority', -1))
stats = dp.ofproto_parser.OFPFlowStatsRequest(
dp, flags, table_id, out_port, out_group, cookie, cookie_mask,
match)
msgs = []
ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG)
flows = []
for msg in msgs:
for stats in msg.body:
if 0 <= priority != stats.priority:
continue
s = stats.to_jsondict()[stats.__class__.__name__]
s['instructions'] = instructions_to_str(stats.instructions)
s['match'] = match_to_str(stats.match)
flows.append(s)
return wrap_dpid_dict(dp, flows, to_user)
def get_aggregate_flow_stats(dp, waiters, flow=None, to_user=True):
flow = flow if flow else {}
table_id = UTIL.ofp_table_from_user(
flow.get('table_id', dp.ofproto.OFPTT_ALL))
flags = str_to_int(flow.get('flags', 0))
out_port = UTIL.ofp_port_from_user(
flow.get('out_port', dp.ofproto.OFPP_ANY))
out_group = UTIL.ofp_group_from_user(
flow.get('out_group', dp.ofproto.OFPG_ANY))
cookie = str_to_int(flow.get('cookie', 0))
cookie_mask = str_to_int(flow.get('cookie_mask', 0))
match = to_match(dp, flow.get('match', {}))
stats = dp.ofproto_parser.OFPAggregateStatsRequest(
dp, flags, table_id, out_port, out_group, cookie, cookie_mask,
match)
msgs = []
ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG)
flows = []
for msg in msgs:
stats = msg.body
s = stats.to_jsondict()[stats.__class__.__name__]
flows.append(s)
return wrap_dpid_dict(dp, flows, to_user)
def get_table_stats(dp, waiters, to_user=True):
stats = dp.ofproto_parser.OFPTableStatsRequest(dp, 0)
msgs = []
ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG)
tables = []
for msg in msgs:
stats = msg.body
for stat in stats:
s = stat.to_jsondict()[stat.__class__.__name__]
if to_user:
s['table_id'] = UTIL.ofp_table_to_user(stat.table_id)
tables.append(s)
return wrap_dpid_dict(dp, tables, to_user)
def get_table_features(dp, waiters, to_user=True):
stats = dp.ofproto_parser.OFPTableFeaturesStatsRequest(dp, 0, [])
msgs = []
ofproto = dp.ofproto
ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG)
p_type_instructions = [ofproto.OFPTFPT_INSTRUCTIONS,
ofproto.OFPTFPT_INSTRUCTIONS_MISS]
p_type_next_tables = [ofproto.OFPTFPT_NEXT_TABLES,
ofproto.OFPTFPT_NEXT_TABLES_MISS,
ofproto.OFPTFPT_TABLE_SYNC_FROM]
p_type_actions = [ofproto.OFPTFPT_WRITE_ACTIONS,
ofproto.OFPTFPT_WRITE_ACTIONS_MISS,
ofproto.OFPTFPT_APPLY_ACTIONS,
ofproto.OFPTFPT_APPLY_ACTIONS_MISS]
p_type_oxms = [ofproto.OFPTFPT_MATCH,
ofproto.OFPTFPT_WILDCARDS,
ofproto.OFPTFPT_WRITE_SETFIELD,
ofproto.OFPTFPT_WRITE_SETFIELD_MISS,
ofproto.OFPTFPT_APPLY_SETFIELD,
ofproto.OFPTFPT_APPLY_SETFIELD_MISS]
p_type_experimenter = [ofproto.OFPTFPT_EXPERIMENTER,
ofproto.OFPTFPT_EXPERIMENTER_MISS]
tables = []
for msg in msgs:
stats = msg.body
for stat in stats:
s = stat.to_jsondict()[stat.__class__.__name__]
properties = []
for prop in stat.properties:
p = {}
t = UTIL.ofp_table_feature_prop_type_to_user(prop.type)
p['type'] = t if t != prop.type else 'UNKNOWN'
if prop.type in p_type_instructions:
instruction_ids = []
for i in prop.instruction_ids:
inst = {'len': i.len,
'type': i.type}
instruction_ids.append(inst)
p['instruction_ids'] = instruction_ids
elif prop.type in p_type_next_tables:
table_ids = []
for i in prop.table_ids:
table_ids.append(i)
p['table_ids'] = table_ids
elif prop.type in p_type_actions:
action_ids = []
for i in prop.action_ids:
act = i.to_jsondict()[i.__class__.__name__]
action_ids.append(act)
p['action_ids'] = action_ids
elif prop.type in p_type_oxms:
oxm_ids = []
for i in prop.oxm_ids:
oxm = i.to_jsondict()[i.__class__.__name__]
oxm_ids.append(oxm)
p['oxm_ids'] = oxm_ids
elif prop.type in p_type_experimenter:
pass
properties.append(p)
s['name'] = stat.name.decode('utf-8')
s['properties'] = properties
if to_user:
s['table_id'] = UTIL.ofp_table_to_user(stat.table_id)
tables.append(s)
return wrap_dpid_dict(dp, tables, to_user)
def get_port_stats(dp, waiters, port_no=None, to_user=True):
if port_no is None:
port_no = dp.ofproto.OFPP_ANY
else:
port_no = UTIL.ofp_port_from_user(port_no)
stats = dp.ofproto_parser.OFPPortStatsRequest(dp, 0, port_no)
msgs = []
ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG)
ports = []
for msg in msgs:
for stats in msg.body:
s = stats.to_jsondict()[stats.__class__.__name__]
properties = []
for prop in stats.properties:
p = prop.to_jsondict()[prop.__class__.__name__]
t = UTIL.ofp_port_stats_prop_type_to_user(prop.type)
p['type'] = t if t != prop.type else 'UNKNOWN'
properties.append(p)
s['properties'] = properties
if to_user:
s['port_no'] = UTIL.ofp_port_to_user(stats.port_no)
ports.append(s)
return wrap_dpid_dict(dp, ports, to_user)
def get_meter_stats(dp, waiters, meter_id=None, to_user=True):
if meter_id is None:
meter_id = dp.ofproto.OFPM_ALL
else:
meter_id = UTIL.ofp_meter_from_user(meter_id)
stats = dp.ofproto_parser.OFPMeterStatsRequest(
dp, 0, meter_id)
msgs = []
ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG)
meters = []
for msg in msgs:
for stats in msg.body:
s = stats.to_jsondict()[stats.__class__.__name__]
bands = []
for band in stats.band_stats:
b = band.to_jsondict()[band.__class__.__name__]
bands.append(b)
s['band_stats'] = bands
if to_user:
s['meter_id'] = UTIL.ofp_meter_to_user(stats.meter_id)
meters.append(s)
return wrap_dpid_dict(dp, meters, to_user)
def get_meter_features(dp, waiters, to_user=True):
ofp = dp.ofproto
type_convert = {ofp.OFPMBT_DROP: 'DROP',
ofp.OFPMBT_DSCP_REMARK: 'DSCP_REMARK'}
capa_convert = {ofp.OFPMF_KBPS: 'KBPS',
ofp.OFPMF_PKTPS: 'PKTPS',
ofp.OFPMF_BURST: 'BURST',
ofp.OFPMF_STATS: 'STATS'}
stats = dp.ofproto_parser.OFPMeterFeaturesStatsRequest(dp, 0)
msgs = []
ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG)
features = []
for msg in msgs:
for feature in msg.body:
band_types = []
for k, v in type_convert.items():
if (1 << k) & feature.band_types:
if to_user:
band_types.append(v)
else:
band_types.append(k)
capabilities = []
for k, v in sorted(capa_convert.items()):
if k & feature.capabilities:
if to_user:
capabilities.append(v)
else:
capabilities.append(k)
f = {'max_meter': feature.max_meter,
'band_types': band_types,
'capabilities': capabilities,
'max_bands': feature.max_bands,
'max_color': feature.max_color}
features.append(f)
return wrap_dpid_dict(dp, features, to_user)
def get_meter_config(dp, waiters, meter_id=None, to_user=True):
flags = {dp.ofproto.OFPMF_KBPS: 'KBPS',
dp.ofproto.OFPMF_PKTPS: 'PKTPS',
dp.ofproto.OFPMF_BURST: 'BURST',
dp.ofproto.OFPMF_STATS: 'STATS'}
if meter_id is None:
meter_id = dp.ofproto.OFPM_ALL
else:
meter_id = UTIL.ofp_meter_from_user(meter_id)
stats = dp.ofproto_parser.OFPMeterConfigStatsRequest(
dp, 0, meter_id)
msgs = []
ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG)
configs = []
for msg in msgs:
for config in msg.body:
c = config.to_jsondict()[config.__class__.__name__]
bands = []
for band in config.bands:
b = band.to_jsondict()[band.__class__.__name__]
if to_user:
t = UTIL.ofp_meter_band_type_to_user(band.type)
b['type'] = t if t != band.type else 'UNKNOWN'
bands.append(b)
c_flags = []
for k, v in sorted(flags.items()):
if k & config.flags:
if to_user:
c_flags.append(v)
else:
c_flags.append(k)
c['flags'] = c_flags
c['bands'] = bands
if to_user:
c['meter_id'] = UTIL.ofp_meter_to_user(config.meter_id)
configs.append(c)
return wrap_dpid_dict(dp, configs, to_user)
def get_group_stats(dp, waiters, group_id=None, to_user=True):
if group_id is None:
group_id = dp.ofproto.OFPG_ALL
else:
group_id = UTIL.ofp_group_from_user(group_id)
stats = dp.ofproto_parser.OFPGroupStatsRequest(
dp, 0, group_id)
msgs = []
ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG)
groups = []
for msg in msgs:
for stats in msg.body:
g = stats.to_jsondict()[stats.__class__.__name__]
bucket_stats = []
for bucket_stat in stats.bucket_stats:
c = bucket_stat.to_jsondict()[bucket_stat.__class__.__name__]
bucket_stats.append(c)
g['bucket_stats'] = bucket_stats
if to_user:
g['group_id'] = UTIL.ofp_group_to_user(stats.group_id)
groups.append(g)
return wrap_dpid_dict(dp, groups, to_user)
def get_group_features(dp, waiters, to_user=True):
ofp = dp.ofproto
type_convert = {ofp.OFPGT_ALL: 'ALL',
ofp.OFPGT_SELECT: 'SELECT',
ofp.OFPGT_INDIRECT: 'INDIRECT',
ofp.OFPGT_FF: 'FF'}
cap_convert = {ofp.OFPGFC_SELECT_WEIGHT: 'SELECT_WEIGHT',
ofp.OFPGFC_SELECT_LIVENESS: 'SELECT_LIVENESS',
ofp.OFPGFC_CHAINING: 'CHAINING',
ofp.OFPGFC_CHAINING_CHECKS: 'CHAINING_CHECKS'}
act_convert = {ofp.OFPAT_OUTPUT: 'OUTPUT',
ofp.OFPAT_COPY_TTL_OUT: 'COPY_TTL_OUT',
ofp.OFPAT_COPY_TTL_IN: 'COPY_TTL_IN',
ofp.OFPAT_SET_MPLS_TTL: 'SET_MPLS_TTL',
ofp.OFPAT_DEC_MPLS_TTL: 'DEC_MPLS_TTL',
ofp.OFPAT_PUSH_VLAN: 'PUSH_VLAN',
ofp.OFPAT_POP_VLAN: 'POP_VLAN',
ofp.OFPAT_PUSH_MPLS: 'PUSH_MPLS',
ofp.OFPAT_POP_MPLS: 'POP_MPLS',
ofp.OFPAT_SET_QUEUE: 'SET_QUEUE',
ofp.OFPAT_GROUP: 'GROUP',
ofp.OFPAT_SET_NW_TTL: 'SET_NW_TTL',
ofp.OFPAT_DEC_NW_TTL: 'DEC_NW_TTL',
ofp.OFPAT_SET_FIELD: 'SET_FIELD',
ofp.OFPAT_PUSH_PBB: 'PUSH_PBB',
ofp.OFPAT_POP_PBB: 'POP_PBB',
ofp.OFPAT_EXPERIMENTER: 'EXPERIMENTER'}
stats = dp.ofproto_parser.OFPGroupFeaturesStatsRequest(dp, 0)
msgs = []
ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG)
features = []
for msg in msgs:
feature = msg.body
types = []
for k, v in type_convert.items():
if (1 << k) & feature.types:
if to_user:
types.append(v)
else:
types.append(k)
capabilities = []
for k, v in cap_convert.items():
if k & feature.capabilities:
if to_user:
capabilities.append(v)
else:
capabilities.append(k)
if to_user:
max_groups = []
for k, v in type_convert.items():
max_groups.append({v: feature.max_groups[k]})
else:
max_groups = feature.max_groups
actions = []
for k1, v1 in type_convert.items():
acts = []
for k2, v2 in act_convert.items():
if (1 << k2) & feature.actions[k1]:
if to_user:
acts.append(v2)
else:
acts.append(k2)
if to_user:
actions.append({v1: acts})
else:
actions.append({k1: acts})
f = {'types': types,
'capabilities': capabilities,
'max_groups': max_groups,
'actions': actions}
features.append(f)
return wrap_dpid_dict(dp, features, to_user)
def get_group_desc(dp, waiters, to_user=True):
stats = dp.ofproto_parser.OFPGroupDescStatsRequest(dp, 0)
msgs = []
ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG)
descs = []
for msg in msgs:
for stats in msg.body:
d = stats.to_jsondict()[stats.__class__.__name__]
buckets = []
for bucket in stats.buckets:
b = bucket.to_jsondict()[bucket.__class__.__name__]
actions = []
for action in bucket.actions:
if to_user:
actions.append(action_to_str(action))
else:
actions.append(action)
b['actions'] = actions
buckets.append(b)
d['buckets'] = buckets
if to_user:
d['group_id'] = UTIL.ofp_group_to_user(stats.group_id)
t = UTIL.ofp_group_type_to_user(stats.type)
d['type'] = t if t != stats.type else 'UNKNOWN'
descs.append(d)
return wrap_dpid_dict(dp, descs, to_user)
def get_port_desc(dp, waiters, port_no=None, to_user=True):
if port_no is None:
port_no = dp.ofproto.OFPP_ANY
else:
port_no = UTIL.ofp_port_from_user(port_no)
stats = dp.ofproto_parser.OFPPortDescStatsRequest(dp, 0, port_no)
msgs = []
ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG)
descs = []
for msg in msgs:
stats = msg.body
for stat in stats:
d = stat.to_jsondict()[stat.__class__.__name__]
properties = []
for prop in stat.properties:
p = prop.to_jsondict()[prop.__class__.__name__]
if to_user:
t = UTIL.ofp_port_desc_prop_type_to_user(prop.type)
p['type'] = t if t != prop.type else 'UNKNOWN'
properties.append(p)
d['name'] = stat.name.decode('utf-8')
d['properties'] = properties
if to_user:
d['port_no'] = UTIL.ofp_port_to_user(stat.port_no)
descs.append(d)
return wrap_dpid_dict(dp, descs, to_user)
def mod_flow_entry(dp, flow, cmd):
cookie = str_to_int(flow.get('cookie', 0))
cookie_mask = str_to_int(flow.get('cookie_mask', 0))
table_id = UTIL.ofp_table_from_user(flow.get('table_id', 0))
idle_timeout = str_to_int(flow.get('idle_timeout', 0))
hard_timeout = str_to_int(flow.get('hard_timeout', 0))
priority = str_to_int(flow.get('priority', 0))
buffer_id = UTIL.ofp_buffer_from_user(
flow.get('buffer_id', dp.ofproto.OFP_NO_BUFFER))
out_port = UTIL.ofp_port_from_user(
flow.get('out_port', dp.ofproto.OFPP_ANY))
out_group = UTIL.ofp_group_from_user(
flow.get('out_group', dp.ofproto.OFPG_ANY))
importance = str_to_int(flow.get('importance', 0))
flags = str_to_int(flow.get('flags', 0))
match = to_match(dp, flow.get('match', {}))
inst = to_instructions(dp, flow.get('instructions', []))
flow_mod = dp.ofproto_parser.OFPFlowMod(
dp, cookie, cookie_mask, table_id, cmd, idle_timeout,
hard_timeout, priority, buffer_id, out_port, out_group,
flags, importance, match, inst)
ofctl_utils.send_msg(dp, flow_mod, LOG)
def mod_meter_entry(dp, meter, cmd):
flags = 0
if 'flags' in meter:
meter_flags = meter['flags']
if not isinstance(meter_flags, list):
meter_flags = [meter_flags]
for flag in meter_flags:
t = UTIL.ofp_meter_flags_from_user(flag)
f = t if t != flag else None
if f is None:
LOG.error('Unknown meter flag: %s', flag)
continue
flags |= f
meter_id = UTIL.ofp_meter_from_user(meter.get('meter_id', 0))
bands = []
for band in meter.get('bands', []):
band_type = band.get('type')
rate = str_to_int(band.get('rate', 0))
burst_size = str_to_int(band.get('burst_size', 0))
if band_type == 'DROP':
bands.append(
dp.ofproto_parser.OFPMeterBandDrop(rate, burst_size))
elif band_type == 'DSCP_REMARK':
prec_level = str_to_int(band.get('prec_level', 0))
bands.append(
dp.ofproto_parser.OFPMeterBandDscpRemark(
rate, burst_size, prec_level))
elif band_type == 'EXPERIMENTER':
experimenter = str_to_int(band.get('experimenter', 0))
bands.append(
dp.ofproto_parser.OFPMeterBandExperimenter(
rate, burst_size, experimenter))
else:
LOG.error('Unknown band type: %s', band_type)
meter_mod = dp.ofproto_parser.OFPMeterMod(
dp, cmd, flags, meter_id, bands)
ofctl_utils.send_msg(dp, meter_mod, LOG)
def mod_group_entry(dp, group, cmd):
group_type = str(group.get('type', 'ALL'))
t = UTIL.ofp_group_type_from_user(group_type)
group_type = t if t != group_type else None
if group_type is None:
LOG.error('Unknown group type: %s', group.get('type'))
group_id = UTIL.ofp_group_from_user(group.get('group_id', 0))
buckets = []
for bucket in group.get('buckets', []):
weight = str_to_int(bucket.get('weight', 0))
watch_port = str_to_int(
bucket.get('watch_port', dp.ofproto.OFPP_ANY))
watch_group = str_to_int(
bucket.get('watch_group', dp.ofproto.OFPG_ANY))
actions = []
for dic in bucket.get('actions', []):
action = to_action(dp, dic)
if action is not None:
actions.append(action)
buckets.append(dp.ofproto_parser.OFPBucket(
weight, watch_port, watch_group, actions))
group_mod = dp.ofproto_parser.OFPGroupMod(
dp, cmd, group_type, group_id, buckets)
ofctl_utils.send_msg(dp, group_mod, LOG)
def mod_port_behavior(dp, port_config):
ofp = dp.ofproto
parser = dp.ofproto_parser
port_no = UTIL.ofp_port_from_user(port_config.get('port_no', 0))
hw_addr = str(port_config.get('hw_addr'))
config = str_to_int(port_config.get('config', 0))
mask = str_to_int(port_config.get('mask', 0))
properties = port_config.get('properties')
prop = []
for p in properties:
type_ = UTIL.ofp_port_mod_prop_type_from_user(p['type'])
length = None
if type_ == ofp.OFPPDPT_ETHERNET:
advertise = UTIL.ofp_port_features_from_user(p['advertise'])
prop.append(
parser.OFPPortModPropEthernet(type_, length, advertise))
elif type_ == ofp.OFPPDPT_OPTICAL:
prop.append(
parser.OFPPortModPropOptical(
type_, length, p['configure'], p['freq_lmda'],
p['fl_offset'], p['grid_span'], p['tx_pwr']))
elif type_ == ofp.OFPPDPT_EXPERIMENTER:
prop.append(
parser.OFPPortModPropExperimenter(
type_, length, p['experimenter'], p['exp_type'],
p['data']))
else:
LOG.error('Unknown port desc prop type: %s', type_)
port_mod = dp.ofproto_parser.OFPPortMod(
dp, port_no, hw_addr, config, mask, prop)
ofctl_utils.send_msg(dp, port_mod, LOG)
def set_role(dp, role):
|
# NOTE(jkoelker) Alias common funcitons
send_experimenter = ofctl_utils.send_experimenter
| r = UTIL.ofp_role_from_user(role.get('role', dp.ofproto.OFPCR_ROLE_EQUAL))
role_request = dp.ofproto_parser.OFPRoleRequest(dp, r, 0)
ofctl_utils.send_msg(dp, role_request, LOG) |
imports.py | from IPython.lib.deepreload import reload as dreload
import PIL, os, numpy as np, threading, json, bcolz, scipy
import pandas as pd, pickle, string, sys, re, time, shutil, copy
import seaborn as sns, matplotlib
from abc import abstractmethod
from functools import partial
from pandas_summary import DataFrameSummary
from IPython.lib.display import FileLink
from sklearn import metrics, ensemble, preprocessing
from operator import itemgetter, attrgetter
from matplotlib import pyplot as plt, rcParams, animation
matplotlib.rc('animation', html='html5')
np.set_printoptions(precision=5, linewidth=110, suppress=True)
from ipykernel.kernelapp import IPKernelApp
def in_notebook(): return IPKernelApp.initialized()
def in_ipynb():
try:
cls = get_ipython().__class__.__name__
return cls == 'ZMQInteractiveShell'
except NameError:
return False
import tqdm as tq
def clear_tqdm():
inst = getattr(tq.tqdm, '_instances', None)
if not inst: return
try:
for i in range(len(inst)): inst.pop().close()
except Exception:
pass
if in_notebook():
def tqdm(*args, **kwargs):
clear_tqdm()
return tq.tqdm(*args, file=sys.stdout, **kwargs)
| clear_tqdm()
return tq.trange(*args, file=sys.stdout, **kwargs)
else:
from tqdm import tqdm, trange
tnrange = trange
tqdm_notebook = tqdm | def trange(*args, **kwargs): |
Core.js | define(["esri/map",
"esri/arcgis/Portal",
"esri/arcgis/utils",
"storymaps/utils/Helper",
"esri/urlUtils",
// Core
"storymaps/maptour/core/Config",
"storymaps/maptour/core/TourData",
"storymaps/maptour/core/WebApplicationData",
"storymaps/maptour/core/TourPointAttributes",
"storymaps/maptour/core/MapTourHelper",
// Desktop/Mobile UI
"storymaps/ui/header/Header",
"storymaps/ui/mapCommand/MapCommand",
// Builder
"storymaps/maptour/builder/MapTourBuilderHelper",
// Utils
"dojo/has",
"esri/IdentityManager",
"esri/config",
"esri/tasks/GeometryService",
"esri/request",
"dojo/topic",
"dojo/on",
"dojo/_base/lang",
"dojo/Deferred",
"dojo/DeferredList",
"dojo/query",
"esri/geometry/Extent"],
function(
Map,
arcgisPortal,
arcgisUtils,
Helper,
urlUtils,
Config,
TourData,
WebApplicationData,
TourPointAttributes,
MapTourHelper,
Header,
MapCommand,
MapTourBuilderHelper,
has,
IdentityManager,
esriConfig,
GeometryService,
esriRequest,
topic,
on,
lang,
Deferred,
DeferredList,
query,
Extent)
{
/**
* Core
* @class Core
*
* MapTour viewer/builder Main class
* Handling of view mode UI
*/
// Development options
// Values are enforced at build time
var CONFIG = {
forcePreviewScreen: "TPL_PREVIEW_FALSE", // TPL_PREVIEW_FALSE || TPL_PREVIEW_TRUE
environment: "TPL_ENV_DEV" // TPL_ENV_DEV || TPL_ENV_PRODUCTION
};
var _mainView = null;
// IE8
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
if (!Date.now) {
Date.now = function() {
return new Date().valueOf();
};
}
//
// Initialization
//
function init(mainView, builder)
{
var urlParams = Helper.getUrlParams(),
isInBuilderMode = false,
isDirectCreation = false,
isGalleryCreation = false;
console.log("maptour.core.Core - init", builder);
_mainView = mainView;
initLocalization();
if( builder != null ) {
isDirectCreation = urlParams.fromScratch != null || urlParams.fromscratch != null;
isInBuilderMode = isDirectCreation || Helper.getAppID(isProd());
isGalleryCreation = urlParams.fromGallery != null;
}
// If browser doesn't support history and it's direct or gallery mode where the URL will have to be rewritten later
// Redirect to a URL that the browser will be able to overwrite
// And put a token so that we don't loop in here
if ( ! Helper.browserSupportHistory() && (isDirectCreation || isGalleryCreation) && urlParams.ieredirected == null ) {
window.location = document.location.protocol + "//" + document.location.host + document.location.pathname + "#" + document.location.search + "&ieredirected";
}
// Ignore index.html configuration on AGOL/Portal and development (except proxy/sharing URL)
if( Helper.isArcGISHosted() || ! isProd() )
configOptions = {
proxyurl: configOptions.proxyurl,
sharingurl: configOptions.sharingurl
};
if( ! Config.checkConfigFileIsOK() ) {
initError("invalidConfig");
return;
}
// Application global object
app = {
// esri/map
map: null,
// esri/arcgis/Portal
portal: null,
// Data model
data: new TourData(),
mapTips: null,
// Builder
builder: builder,
isInBuilderMode: isInBuilderMode,
isDirectCreation: isDirectCreation,
isGalleryCreation: isGalleryCreation,
isDirectCreationFirstSave: isDirectCreation,
builderMovableGraphic: null,
isCreatingFS: false,
// UI
mapCommand: null,
header: new Header("#header", isInBuilderMode),
// Flags
isLoading: true,
loadingTimeout: null,
isFirstUserAction: false,
filterMouseHoverEvent: false,
// Config
config: {
thumbnailMaxWidth: 140,
thumbnailMaxHeight: 93,
picRecommendedWidth: 1090,
picRecommendedHeight: 725
}
};
if ( ! _mainView.init(this) )
return;
startLoadingTimeout();
// Sharing URL
if ( ! configOptions.sharingurl ) {
// Determine if hosted or on a Portal
var appLocation = document.location.pathname.indexOf("/apps/");
if( appLocation == -1 )
appLocation = document.location.pathname.indexOf("/home/");
if( appLocation != -1 ) {
// Get the portal instance name
var instance = location.pathname.substr(0,appLocation);
configOptions.sharingurl = "//" + location.host + instance + "/sharing/content/items";
configOptions.proxyurl = "//" + location.host + instance + "/sharing/proxy";
}
else
configOptions.sharingurl = APPCFG.DEFAULT_SHARING_URL;
}
arcgisUtils.arcgisUrl = location.protocol + configOptions.sharingurl;
// Proxy URL
if( ! configOptions.proxyurl )
configOptions.proxyurl = APPCFG.DEFAULT_PROXY_URL;
esriConfig.defaults.io.proxyUrl = location.protocol + configOptions.proxyurl;
// Allow IE9 to save over HTTP
IdentityManager && IdentityManager.setProtocolErrorHandler(function(){ return true; });
// USE CORS to save the web app configuration during developement
if( isInBuilderMode && APPCFG.CORS_SERVER ) {
$.each(APPCFG.CORS_SERVER, function(i, server){
esriConfig.defaults.io.corsEnabledServers.push(server);
});
}
// Set timeout depending on the application mode
esriConfig.defaults.io.timeout = isInBuilderMode ? APPCFG.TIMEOUT_BUILDER_REQUEST : APPCFG.TIMEOUT_VIEWER_REQUEST;
// Fix for multiple twitter bootstrap popup to be open simultaneously
$.fn.modal.Constructor.prototype.enforceFocus = function () {};
// Run the app when jQuery is ready
$(document).ready( lang.hitch(this, initStep2) );
}
function initStep2()
{
console.log("maptour.core.Core - initStep2");
// Get portal info
// If geometry, geocode service or bing maps key are defined by portal,
// they override the configuration file values
esriRequest({
url: arcgisUtils.arcgisUrl.split('/sharing/')[0] + "/sharing/rest/portals/self",
content: {"f": "json"},
callbackParamName: "callback"
}).then(lang.hitch(this, function(response){
var geometryServiceURL, geocodeServices;
if (commonConfig && commonConfig.helperServices) {
if (commonConfig.helperServices.geometry && commonConfig.helperServices.geometry)
geometryServiceURL = location.protocol + commonConfig.helperServices.geometry.url;
if (commonConfig.helperServices.geocode && commonConfig.helperServices.geocode.length && commonConfig.helperServices.geocode[0].url)
geocodeServices = commonConfig.helperServices.geocode;
// Deprecated syntax
else if (commonConfig.helperServices.geocode && commonConfig.helperServices.geocode && commonConfig.helperServices.geocode.url)
geocodeServices = [{
name: "myGeocoder",
url: commonConfig.helperServices.geocode.url
}];
}
if (response.helperServices) {
if (response.helperServices.geometry && response.helperServices.geometry.url)
geometryServiceURL = response.helperServices.geometry.url;
if (response.helperServices.geocode && response.helperServices.geocode.length && response.helperServices.geocode[0].url )
geocodeServices = response.helperServices.geocode;
}
esriConfig.defaults.geometryService = new GeometryService(geometryServiceURL);
configOptions.geocodeServices = geocodeServices;
if( response.bingKey )
commonConfig.bingMapsKey = response.bingKey;
// Disable feature service creation as Portal for ArcGIS 10.2 doesn't support that yet
if( response.isPortal && APPCFG && APPCFG.AUTHORIZED_IMPORT_SOURCE )
APPCFG.AUTHORIZED_IMPORT_SOURCE.featureService = false;
app.isPortal = !! response.isPortal;
initStep3();
}), function(){
initError("portalSelf");
});
}
function initStep3()
{
console.log("maptour.core.Core - initStep3");
var appId = Helper.getAppID(isProd());
var webmapId = Helper.getWebmapID(isProd());
// Initialize localization
app.header.initLocalization();
_mainView.initLocalization();
$(window).resize(handleWindowResize);
// Disable form submit on enter key
$("form").bind("keydown", function(e) {
if (e.keyCode == 13)
return false;
});
// Basic styling in case something isn't public
on(IdentityManager, "dialog-create", styleIdentityManager);
topic.subscribe("CORE_UPDATE_UI", updateUI);
topic.subscribe("CORE_RESIZE", handleWindowResize);
loadingIndicator.setMessage(i18n.viewer.loading.step2);
// Mobile carousel and list view numbering
Helper.addCSSRule(".tpIcon {" + MapTourHelper.getSymbolMobileClip() + "}");
// Load using a Web Mapping Application item
if (appId)
loadWebMappingApp(appId);
// Load using a web map and is hosted on AGO -> template preview
else if( webmapId && (Helper.isArcGISHosted() || isPreviewForced()) )
showTemplatePreview();
// Load using a webmap -> user hosted
else if( webmapId )
loadWebMap(webmapId);
// Direct creation and not signed-in
else if ( app.isDirectCreation && isProd() && ! Helper.getPortalUser() )
| else if ( app.isDirectCreation )
portalLogin().then(function(){
loadWebMap(MapTourBuilderHelper.getBlankWebmapJSON());
});
else if( Helper.isArcGISHosted() )
showTemplatePreview();
else
initError("invalidConfigNoWebmap");
}
function loadWebMappingApp(appId)
{
console.log("maptour.core.Core - loadWebMappingApp - appId:", appId);
var urlParams = Helper.getUrlParams();
var forceLogin = urlParams.forceLogin !== undefined;
// If forceLogin parameter in URL OR builder
if ( forceLogin || app.isInBuilderMode )
portalLogin().then(
function() {
loadWebMappingAppStep2(appId);
},
function() {
initError("notAuthorized");
}
);
// Production in view mode
else
loadWebMappingAppStep2(appId);
}
function loadWebMappingAppStep2(appId)
{
// Get application item
var itemRq = esriRequest({
url: configOptions.sharingurl + "/" + appId + "",
content: {
f: "json"
},
callbackParamName: "callback",
load: function (response) {
app.data.setAppItem(response);
},
error: function() { }
});
// Get application config
var dataRq = esriRequest({
url: configOptions.sharingurl + "/" + appId + "/data",
content: {
f: "json"
},
callbackParamName: "callback",
load: function (response) {
WebApplicationData.set(response);
app.data.webAppData = WebApplicationData;
},
error: function(){ }
});
var appDeferedList = new DeferredList([itemRq, dataRq]);
appDeferedList.then(function(){
if (!dataRq.results || !dataRq.results[0] || !itemRq.results || !itemRq.results[0]) {
if( itemRq.results && itemRq.results[1] && itemRq.results[1] && itemRq.results[1].httpCode == 403 )
initError("notAuthorized");
else
initError("invalidApp");
return;
}
// If in builder, check that user is app owner or org admin
if (app.isInBuilderMode && isProd() && !app.data.userIsAppOwner()) {
initError("notAuthorized");
return;
}
var webmapId = WebApplicationData.getWebmap() || Helper.getWebmapID(isProd());
if (webmapId)
loadWebMap(webmapId);
// Come back from the redirect below, create a new webmap
else if (app.isGalleryCreation){
WebApplicationData.setTitle(app.data.getAppItem().title);
WebApplicationData.setSubtitle(app.data.getAppItem().description);
loadWebMap(MapTourBuilderHelper.getBlankWebmapJSON());
}
// ArcGIS Gallery page start the app with an appid that doesn't include a webmap
else if (Helper.getPortalUser() || ! isProd())
redirectToBuilderFromGallery();
else
initError("invalidApp");
});
}
function portalLogin()
{
var resultDeferred = new Deferred();
var portalUrl = configOptions.sharingurl.split('/sharing/')[0];
app.portal = new arcgisPortal.Portal(portalUrl);
on(IdentityManager, "dialog-create", styleIdentityManagerForLoad);
app.portal.on("load", function(){
app.portal.signIn().then(
function() {
resultDeferred.resolve();
},
function() {
resultDeferred.reject();
}
);
});
return resultDeferred;
}
function loadWebMap(webmapIdOrJSON)
{
console.log("maptour.core.Core - loadWebMap - webmapId:", webmapIdOrJSON);
// Fix a Chrome freeze when map have a large initial extent (level 16 and up)
// Set the zoomDuration to 50ms, set back to default in see MainView.displayApp
// Using a value of 0ms create tile loading issue for all app life, it
// looks like the API would not load all zoom level but resample lower level
if( has("chrome") ) {
esriConfig.defaults.map.zoomDuration = 50;
}
arcgisUtils.createMap(webmapIdOrJSON, "mainMap", {
mapOptions: {
slider: true,
autoResize: false,
// Force the web map extent to the world to get all data from the FS
extent : new Extent({
xmax: 180,
xmin: -180,
ymax: 90,
ymin: -90,
spatialReference: {
wkid:4326
}
}),
showAttribution: true
},
ignorePopups: true,
bingMapsKey: commonConfig.bingMapsKey
}).then(
lang.hitch(this, function(response){
webMapInitCallback(response);
}),
lang.hitch(this, function(){
initError("createMap");
})
);
}
function webMapInitCallback(response)
{
console.log("maptour.core.Core - webMapInitCallback");
if( configOptions.authorizedOwners && configOptions.authorizedOwners.length > 0 && configOptions.authorizedOwners[0] ) {
var ownerFound = false;
if( response.itemInfo.item.owner )
ownerFound = $.inArray(response.itemInfo.item.owner, configOptions.authorizedOwners) != -1;
if (!ownerFound) {
initError("invalidConfigOwner");
return;
}
}
app.map = response.map;
app.data.setWebMapItem(response.itemInfo);
app.map.disableKeyboardNavigation();
// Initialize header
// Title/subtitle are the first valid string from: index.html config object, web application data, web map data
var title = configOptions.title || WebApplicationData.getTitle() || response.itemInfo.item.title;
var subtitle = configOptions.subtitle || WebApplicationData.getSubtitle() || response.itemInfo.item.snippet;
applyUILayout(WebApplicationData.getLayout() || configOptions.layout);
var urlParams = Helper.getUrlParams();
var appColors = WebApplicationData.getColors();
var logoURL = WebApplicationData.getLogoURL() || APPCFG.HEADER_LOGO_URL;
var logoTarget = (logoURL == APPCFG.HEADER_LOGO_URL) ? APPCFG.HEADER_LOGO_TARGET : WebApplicationData.getLogoTarget();
app.header.init(
! app.isInBuilderMode && (APPCFG.EMBED || urlParams.embed || urlParams.embed === ''),
title,
subtitle,
appColors[0],
logoURL,
logoTarget,
! app.isInBuilderMode && (
(! isProd() && Helper.getAppID(isProd()))
|| isProd() && app.data.userIsAppOwner()),
WebApplicationData.getHeaderLinkText() === undefined ? APPCFG.HEADER_LINK_TEXT : WebApplicationData.getHeaderLinkText(),
WebApplicationData.getHeaderLinkURL() === undefined ? APPCFG.HEADER_LINK_URL : WebApplicationData.getHeaderLinkURL(),
WebApplicationData.getSocial()
);
document.title = title ? $('<div>' + title + '</div>').text() : 'Map Tour';
_mainView.webmapLoaded();
}
function appInitComplete()
{
console.log("maptour.core.Core - initMap");
// Map command buttons
app.mapCommand = new MapCommand(
app.map,
function(){
_mainView.setMapExtent(Helper.getWebMapExtentFromItem(app.data.getWebMapItem().item));
},
_mainView.zoomToDeviceLocation,
APPCFG.DISPLAY_LOCATE_BUTTON || WebApplicationData.getZoomLocationButton()
);
// Resize everything after picture has been set
handleWindowResize();
// On mobile, force start on the Map view except if it's the intro
if (location.hash && Helper.browserSupportHistory())
location.hash = "map";
// On mobile, change view based on browser history
window.onhashchange = function(){
// If no hash and there is intro data, it's init, so skip
if( (location.hash === "" || location.hash === "#") && app.data.getIntroData() )
return;
if ( app.data.getIntroData() && app.data.getCurrentIndex() == null )
topic.publish("PIC_PANEL_NEXT");
_mainView.prepareMobileViewSwitch();
if(location.hash == "#map") {
$("#mapViewLink").addClass("current");
showMobileViewMap();
}
else
_mainView.onHashChange();
};
_mainView.appInitComplete();
app.builder && app.builder.appInitComplete();
}
function displayApp()
{
$("#loadingOverlay").fadeOut();
loadingIndicator.stop();
setTimeout(function(){
app.isLoading = false;
}, 50);
}
function initError(error, message, noDisplay)
{
hideUI();
cleanLoadingTimeout();
loadingIndicator.stop();
if( error == "noLayerView" ) {
loadingIndicator.setMessage(i18n.viewer.errors[error], true);
return;
}
else if ( error != "initMobile" )
loadingIndicator.forceHide();
$("#fatalError .error-msg").html(i18n.viewer.errors[error]);
if( ! noDisplay )
$("#fatalError").show();
}
function replaceInitErrorMessage(error)
{
$("#fatalError .error-msg").html(i18n.viewer.errors[error]);
}
//
// UI
//
function applyUILayout(layout)
{
$("body").toggleClass("modern-layout", layout == "integrated");
}
/**
* Refresh the UI when tour points have changed
*/
function updateUI(params)
{
console.log("maptour.core.Core - updateUI");
var tourPoints = app.data.getTourPoints();
var appColors = WebApplicationData.getColors();
var editFirstRecord = params && params.editFirstRecord;
applyUILayout(WebApplicationData.getLayout());
app.header.setTitleAndSubtitle(
WebApplicationData.getTitle() || app.data.getWebMapItem().item.title,
WebApplicationData.getSubtitle() || app.data.getWebMapItem().item.snippet
);
app.header.setColor(appColors[0]);
var logoURL = WebApplicationData.getLogoURL() || APPCFG.HEADER_LOGO_URL;
app.header.setLogoInfo(
logoURL,
logoURL == APPCFG.HEADER_LOGO_URL ?
APPCFG.HEADER_LOGO_TARGET
: WebApplicationData.getLogoTarget()
);
app.header.setTopRightLink(
WebApplicationData.getHeaderLinkText() === undefined ? APPCFG.HEADER_LINK_TEXT : WebApplicationData.getHeaderLinkText(),
WebApplicationData.getHeaderLinkURL() === undefined ? APPCFG.HEADER_LINK_URL : WebApplicationData.getHeaderLinkURL()
);
app.header.setSocial(WebApplicationData.getSocial());
_mainView.updateUI(tourPoints, appColors, editFirstRecord);
handleWindowResize();
}
function handleWindowResize()
{
var isMobileView = MapTourHelper.isOnMobileView();
var isOnMobileMapView = $("#mapViewLink").hasClass("current");
if( isMobileView )
$("body").addClass("mobile-view");
else
$("body").removeClass("mobile-view");
var widthViewport = $("body").width();
var heightViewport = $("body").height();
var heightHeader = $("#header").height();
var heightFooter = $("#footer").height();
var heightMiddle = heightViewport - (heightHeader + heightFooter);
app.header.resize(widthViewport);
_mainView.resize({
isMobileView: isMobileView,
isOnMobileMapView: isOnMobileMapView,
width: widthViewport,
height: heightMiddle
});
if( ! app.initScreenIsOpen )
$("#contentPanel").height(heightMiddle + (isMobileView ? 0 : MapTourHelper.isModernLayout() ? heightFooter : 0));
$("#contentPanel").width(widthViewport);
// Force a browser reflow by reading #picturePanel width
// Using the value computed in desktopPicturePanel.resize doesn't works
$("#mapPanel").width( widthViewport - $("#picturePanel").width() );
if (app.isInBuilderMode){
app.builder.resize({
isMobileView: isMobileView
});
}
if (app.map && (! isMobileView || (isMobileView && isOnMobileMapView))){
try {
app.map.resize(true);
} catch( e ){ }
}
// Change esri logo size
if( isMobileView )
$("#mainMap .esriControlsBR > div").first().removeClass("logo-med").addClass("logo-sm");
else
$("#mainMap .esriControlsBR > div").first().removeClass("logo-sm").addClass("logo-med");
}
//
// Login in dev environnement
//
function styleIdentityManager()
{
// Override for bootstrap conflicts
$(".esriSignInDialog td label").siblings("br").css("display", "none");
$(".esriSignInDialog .dijitDialogPaneContentArea div:nth(1)").css("display", "none");
$(".esriSignInDialog .dijitReset.dijitInputInner").css("padding", "0px");
$(".esriSignInDialog .dijitReset.dijitInputInner").css("margin-bottom", "0px");
$(".esriSignInDialog .dijitReset.dijitInputInner").css("border", "none");
$(".esriSignInDialog .dijitReset.dijitInputInner").css("border-radius", "0px");
$(".esriSignInDialog .dijitReset.dijitInputInner").css("-webkit-border-radius", "0px");
$(".esriSignInDialog .dijitReset.dijitInputInner").css("-moz-border-radius", "0px");
$(".esriSignInDialog .dijitReset.dijitInputInner").css("box-shadow", "none");
$(".esriSignInDialog .dijitReset.dijitInputInner").css("-webkit-box-shadow", "none");
$(".esriSignInDialog .dijitReset.dijitInputInner").css("-moz-box-shadow", "none");
$(".esriSignInDialog .dijitReset.dijitValidationContainer").css("display", "none");
$(".esriSignInDialog .esriErrorMsg").css("margin-top", "10px");
// Edit title
$(".esriSignInDialog").find(".dijitDialogTitleBar").find(".dijitDialogTitle").first().html("Authentication is required");
// Hide default message
$(".esriSignInDialog").find(".dijitDialogPaneContentArea:first-child").find(":first-child").first().css("display", "none");
// Setup a more friendly text
$(".esriSignInDialog").find(".dijitDialogPaneContentArea:first-child").find(":first-child").first().after("<div id='dijitDialogPaneContentAreaLoginText'>Please sign in with an account on <a href='http://" + IdentityManager._arcgisUrl + "' title='" + IdentityManager._arcgisUrl + "' target='_blank'>" + IdentityManager._arcgisUrl + "</a> to access the application.</div>");
}
function styleIdentityManagerForLoad()
{
// Hide default message
$(".esriSignInDialog").find("#dijitDialogPaneContentAreaLoginText").css("display", "none");
// Setup a more friendly text
$(".esriSignInDialog").find(".dijitDialogPaneContentArea:first-child").find(":first-child").first().after("<div id='dijitDialogPaneContentAreaAtlasLoginText'>Please sign in with an account on <a href='http://" + IdentityManager._arcgisUrl + "' title='" + IdentityManager._arcgisUrl + "' target='_blank'>" + IdentityManager._arcgisUrl + "</a> to configure this application.</div>");
}
function prepareAppForWebmapReload()
{
$("#mainMap_root").remove();
$("#header").css("display", "inherit");
$(".mobileView").css("display", "inherit");
$("#footer").css("display", "inherit");
$("#fatalError").css("display", "none");
$("#loadingOverlay").css("top", "0px");
loadingIndicator.start();
loadingIndicator.setMessage(i18n.viewer.loading.step2);
startLoadingTimeout();
handleWindowResize();
}
function showTemplatePreview()
{
window.location = app.isPortal && APPCFG.HELP_URL_PORTAL ? APPCFG.HELP_URL_PORTAL : APPCFG.HELP_URL;
}
function redirectToSignIn()
{
loadingIndicator.setMessage(i18n.viewer.loading.redirectSignIn + "<br />" + i18n.viewer.loading.redirectSignIn2);
setTimeout(function(){
window.location = arcgisUtils.arcgisUrl.split('/sharing/')[0]
+ "/home/signin.html?returnUrl="
+ encodeURIComponent(document.location.href);
}, 2000);
}
function redirectToBuilderFromGallery()
{
// TODO display another redirect message
loadingIndicator.setMessage(i18n.viewer.loading.loadBuilder);
setTimeout(function(){
window.location = document.location.href + "&fromGallery";
}, 1200);
}
function hideUI()
{
$("#header").hide();
$(".mobileView").hide();
$("#footer").hide();
$(".modal").hide();
}
//
// Mobile
//
function showMobileViewMap()
{
$("#contentPanel").show();
$("#footerMobile").show();
$("#mapPanel").show();
app.mobileCarousel.setSelectedPoint(app.data.getCurrentIndex());
handleWindowResize();
}
//
// App init
//
function startLoadingTimeout()
{
// First view loading time before failure
app.loadingTimeout = setTimeout(appLoadingTimeout, APPCFG.TIMEOUT_VIEWER_LOAD);
}
function cleanLoadingTimeout()
{
if (typeof app != "undefined" && app.loadingTimeout) {
clearTimeout(app.loadingTimeout);
app.loadingTimeout = null;
}
}
function appLoadingTimeout()
{
// Restart the timeout if the dialog is shown or has been shown and the timeout hasn't been fired after it has been closed
if( IdentityManager && IdentityManager.dialog && IdentityManager.dialog._alreadyInitialized && ! IdentityManager.loadingTimeoutAlreadyFired) {
clearTimeout(app.loadingTimeout);
startLoadingTimeout();
// Set a flag only if the dialog isn't showned now, so next timeout will fail
if( ! IdentityManager._busy )
IdentityManager.loadingTimeoutAlreadyFired = true;
return;
}
loadingIndicator.stop();
loadingIndicator.setMessage(i18n.viewer.loading.fail + '<br /><button type="button" class="btn btn-medium btn-info" style="margin-top: 5px;" onclick="document.location.reload()">' + i18n.viewer.loading.failButton + '</button>', true);
app.map && app.map.destroy();
}
function initLocalization()
{
query('#fatalError .error-title')[0].innerHTML = i18n.viewer.errors.boxTitle;
}
function isProd()
{
// Prevent the string from being replaced
return CONFIG.environment != ['TPL','ENV','DEV'].join('_');
}
function isPreviewForced()
{
// Prevent the string from being replaced
return CONFIG.forcePreviewScreen == ['TPL','PREVIEW','TRUE'].join('_');
}
return {
init: init,
isProd: isProd,
appInitComplete: appInitComplete,
displayApp: displayApp,
cleanLoadingTimeout: cleanLoadingTimeout,
initError: initError,
handleWindowResize: handleWindowResize,
prepareAppForWebmapReload: prepareAppForWebmapReload,
loadWebMap: loadWebMap,
replaceInitErrorMessage: replaceInitErrorMessage,
portalLogin: portalLogin
};
}
); | redirectToSignIn();
// Direct creation and signed in
|
idmanuf.rs | #[doc = "Register `IDMANUF` reader"]
pub struct R(crate::R<IDMANUF_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<IDMANUF_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<IDMANUF_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<IDMANUF_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Field `DEPT` reader - Department Identification Number"]
pub struct DEPT_R(crate::FieldReader<u8, u8>);
impl DEPT_R {
pub(crate) fn new(bits: u8) -> Self {
DEPT_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for DEPT_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `MANUF` reader - Manufacturer Identification Number"]
pub struct MANUF_R(crate::FieldReader<u16, u16>);
impl MANUF_R {
pub(crate) fn new(bits: u16) -> Self {
MANUF_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for MANUF_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl R {
#[doc = "Bits 0:4 - Department Identification Number"]
#[inline(always)]
pub fn dept(&self) -> DEPT_R |
#[doc = "Bits 5:15 - Manufacturer Identification Number"]
#[inline(always)]
pub fn manuf(&self) -> MANUF_R {
MANUF_R::new(((self.bits >> 5) & 0x07ff) as u16)
}
}
#[doc = "Manufactory ID Register\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 [idmanuf](index.html) module"]
pub struct IDMANUF_SPEC;
impl crate::RegisterSpec for IDMANUF_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [idmanuf::R](R) reader structure"]
impl crate::Readable for IDMANUF_SPEC {
type Reader = R;
}
#[doc = "`reset()` method sets IDMANUF to value 0x1820"]
impl crate::Resettable for IDMANUF_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0x1820
}
}
| {
DEPT_R::new((self.bits & 0x1f) as u8)
} |
dma.rs | //! Direct Memory Access Engine
#![allow(dead_code)]
use core::fmt;
use core::marker::PhantomData;
use core::mem::MaybeUninit;
use core::ops::{Deref, DerefMut};
use core::ptr;
use core::slice;
use crate::rcc::AHB1;
use stable_deref_trait::StableDeref;
#[non_exhaustive]
#[derive(Debug)]
pub enum Error {
Overrun,
BufferError,
}
pub enum Event {
HalfTransfer,
TransferComplete,
}
#[derive(Clone, Copy, PartialEq)]
pub enum Half {
First,
Second,
}
/// Frame reader "worker", access and handling of frame reads is made through this structure.
pub struct FrameReader<BUFFER, CHANNEL, const N: usize>
where
BUFFER: Sized + StableDeref<Target = DMAFrame<N>> + DerefMut + 'static,
{
buffer: BUFFER,
channel: CHANNEL,
matching_character: u8,
}
impl<BUFFER, CHANNEL, const N: usize> FrameReader<BUFFER, CHANNEL, N>
where
BUFFER: Sized + StableDeref<Target = DMAFrame<N>> + DerefMut + 'static,
{
pub(crate) fn new(
buffer: BUFFER,
channel: CHANNEL,
matching_character: u8,
) -> FrameReader<BUFFER, CHANNEL, N> {
Self {
buffer,
channel,
matching_character,
}
}
}
/// Frame sender "worker", access and handling of frame transmissions is made through this
/// structure.
pub struct FrameSender<BUFFER, CHANNEL, const N: usize>
where
BUFFER: Sized + StableDeref<Target = DMAFrame<N>> + DerefMut + 'static,
{
buffer: Option<BUFFER>,
channel: CHANNEL,
}
impl<BUFFER, CHANNEL, const N: usize> FrameSender<BUFFER, CHANNEL, N>
where
BUFFER: Sized + StableDeref<Target = DMAFrame<N>> + DerefMut + 'static,
{
pub(crate) fn new(channel: CHANNEL) -> FrameSender<BUFFER, CHANNEL, N> {
Self {
buffer: None,
channel,
}
}
}
/// Data type for holding data frames for the Serial.
///
/// Internally used uninitialized storage, making this storage zero cost to create. It can also be
/// used with, for example, [`heapless::pool`] to create a pool of serial frames.
///
/// [`heapless::pool`]: https://docs.rs/heapless/0.5.3/heapless/pool/index.html
pub struct DMAFrame<const N: usize> {
len: u16,
buf: [MaybeUninit<u8>; N],
}
impl<const N: usize> fmt::Debug for DMAFrame<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.read())
}
}
impl<const N: usize> fmt::Write for DMAFrame<N> {
fn write_str(&mut self, s: &str) -> fmt::Result {
let free = self.free();
if s.len() > free {
Err(fmt::Error)
} else {
self.write_slice(s.as_bytes());
Ok(())
}
}
}
impl<const N: usize> Default for DMAFrame<N> {
fn default() -> Self {
Self::new()
}
}
impl<const N: usize> DMAFrame<N> {
const INIT: MaybeUninit<u8> = MaybeUninit::uninit();
/// Creates a new node for the Serial DMA
#[inline]
pub const fn new() -> Self {
// Create an uninitialized array of `MaybeUninit<u8>`.
Self {
len: 0,
buf: [Self::INIT; N],
}
}
/// Gives a `&mut [u8]` slice to write into with the maximum size, the `commit` method
/// must then be used to set the actual number of bytes written.
///
/// Note that this function internally first zeros the uninitialized part of the node's buffer.
pub fn write(&mut self) -> &mut [u8] {
// Initialize remaining memory with a safe value
for elem in &mut self.buf[self.len as usize..] {
*elem = MaybeUninit::new(0);
}
self.len = self.max_len() as u16;
// NOTE(unsafe): This is safe as the operation above set the entire buffer to a valid state
unsafe { slice::from_raw_parts_mut(self.buf.as_mut_ptr() as *mut _, self.max_len()) }
}
/// Used to shrink the current size of the frame, used in conjunction with `write`.
#[inline]
pub fn commit(&mut self, shrink_to: usize) {
// Only shrinking is allowed to remain safe with the `MaybeUninit`
if shrink_to < self.len as _ {
self.len = shrink_to as _;
}
}
/// Gives an uninitialized `&mut [MaybeUninit<u8>]` slice to write into, the `set_len` method
/// must then be used to set the actual number of bytes written.
#[inline]
pub fn write_uninit(&mut self) -> &mut [MaybeUninit<u8>; N] {
&mut self.buf
}
/// Used to set the current size of the frame, used in conjunction with `write_uninit` to have an
/// interface for uninitialized memory. Use with care!
///
/// # Safety
///
/// NOTE(unsafe): This must be set so that the final buffer is only referencing initialized
/// memory.
#[inline]
pub unsafe fn set_len(&mut self, len: usize) {
assert!(len <= self.max_len());
self.len = len as _;
}
/// Used to write data into the node, and returns how many bytes were written from `buf`.
///
/// If the node is already partially filled, this will continue filling the node.
pub fn write_slice(&mut self, buf: &[u8]) -> usize {
let count = buf.len().min(self.free());
// Used to write data into the `MaybeUninit`
// NOTE(unsafe): Safe based on the size check above
unsafe {
ptr::copy_nonoverlapping(
buf.as_ptr(),
(self.buf.as_mut_ptr() as *mut u8).add(self.len.into()),
count,
);
}
self.len += count as u16;
count
}
/// Clear the node of all data making it empty
#[inline]
pub fn clear(&mut self) {
self.len = 0;
}
/// Returns a readable slice which maps to the buffers internal data
#[inline]
pub fn read(&self) -> &[u8] {
// NOTE(unsafe): Safe as it uses the internal length of valid data
unsafe { slice::from_raw_parts(self.buf.as_ptr() as *const _, self.len as usize) }
}
/// Returns a readable mutable slice which maps to the buffers internal data
#[inline]
pub fn read_mut(&mut self) -> &mut [u8] {
// NOTE(unsafe): Safe as it uses the internal length of valid data
unsafe { slice::from_raw_parts_mut(self.buf.as_mut_ptr() as *mut _, self.len as usize) }
}
/// Reads how many bytes are available
#[inline]
pub fn len(&self) -> usize {
self.len as usize
}
/// Reads how many bytes are free
#[inline]
pub fn free(&self) -> usize {
self.max_len() - self.len as usize
}
/// Get the max length of the frame
#[inline]
pub fn max_len(&self) -> usize {
N
}
/// Checks if the frame is empty
#[inline]
pub fn is_empty(&self) -> bool {
self.len == 0
}
#[inline]
pub(crate) unsafe fn buffer_address_for_dma(&self) -> u32 {
self.buf.as_ptr() as u32
}
#[inline]
pub(crate) fn buffer_as_ptr(&self) -> *const MaybeUninit<u8> {
self.buf.as_ptr()
}
#[inline]
pub(crate) fn buffer_as_mut_ptr(&mut self) -> *mut MaybeUninit<u8> {
self.buf.as_mut_ptr()
}
}
impl<const N: usize> AsRef<[u8]> for DMAFrame<N> {
#[inline]
fn as_ref(&self) -> &[u8] {
self.read()
}
}
pub struct CircBuffer<BUFFER, CHANNEL>
where
BUFFER: 'static,
{
buffer: BUFFER,
channel: CHANNEL,
readable_half: Half,
consumed_offset: usize,
}
impl<BUFFER, CHANNEL> CircBuffer<BUFFER, CHANNEL> {
pub(crate) fn new<H>(buf: BUFFER, chan: CHANNEL) -> Self
where
BUFFER: StableDeref<Target = [H; 2]> + 'static,
{
CircBuffer {
buffer: buf,
channel: chan,
readable_half: Half::Second,
consumed_offset: 0,
}
}
}
#[cfg(feature = "bbqueue_serial_dma")]
pub use bbqueue::{Consumer, GrantR, ArrayLength};
#[cfg(feature = "bbqueue_serial_dma")]
pub struct TxContext<N: ArrayLength<u8>, CHANNEL> {
consumer: Consumer<'static, N>,
channel: CHANNEL,
read_grant: Option<GrantR<'static, N>>,
read_grant_length: usize,
}
pub trait DmaExt {
type Channels;
fn split(self, ahb: &mut AHB1) -> Self::Channels;
}
pub struct Transfer<MODE, BUFFER, CHANNEL, PAYLOAD> {
_mode: PhantomData<MODE>,
buffer: BUFFER,
channel: CHANNEL,
payload: PAYLOAD,
}
impl<BUFFER, CHANNEL, PAYLOAD> Transfer<R, BUFFER, CHANNEL, PAYLOAD>
where
BUFFER: StableDeref + 'static,
{
pub(crate) fn r(buffer: BUFFER, channel: CHANNEL, payload: PAYLOAD) -> Self {
Transfer {
_mode: PhantomData,
buffer,
channel,
payload,
}
}
}
impl<BUFFER, CHANNEL, PAYLOAD> Transfer<W, BUFFER, CHANNEL, PAYLOAD>
where
BUFFER: StableDeref + 'static,
{
pub(crate) fn w(buffer: BUFFER, channel: CHANNEL, payload: PAYLOAD) -> Self {
Transfer {
_mode: PhantomData,
buffer,
channel,
payload,
}
}
}
impl<BUFFER, CHANNEL, PAYLOAD> Deref for Transfer<R, BUFFER, CHANNEL, PAYLOAD> {
type Target = BUFFER;
fn deref(&self) -> &BUFFER {
&self.buffer
}
}
/// Read transfer
pub struct R;
/// Write transfer
pub struct W;
macro_rules! dma {
($($DMAX:ident: ($dmaX:ident, $dmaXen:ident, $dmaXrst:ident, {
$($CX:ident: (
$ccrX:ident,
$CCRX:ident,
$cndtrX:ident,
$CNDTRX:ident,
$cparX:ident,
$CPARX:ident,
$cmarX:ident,
$CMARX:ident,
$htifX:ident,
$tcifX:ident,
$chtifX:ident,
$ctcifX:ident,
$cgifX:ident,
$teifX:ident,
$cteifX:ident
),)+
}),)+) => {
$(
pub mod $dmaX {
use core::sync::atomic::{self, Ordering};
use crate::stm32::{$DMAX, dma1};
use core::ops::DerefMut;
use core::ptr;
use stable_deref_trait::StableDeref;
use crate::dma::{CircBuffer, FrameReader, FrameSender, DMAFrame, DmaExt, Error, Event, Half, Transfer, W};
use crate::rcc::AHB1;
use crate::dma::TxContext;
use bbqueue::{Consumer, ArrayLength};
#[allow(clippy::manual_non_exhaustive)]
pub struct Channels((), $(pub $CX),+);
$(
pub struct $CX;
impl $CX {
/// Associated peripheral `address`
///
/// `inc` indicates whether the address will be incremented after every byte transfer
#[inline]
pub fn set_peripheral_address(&mut self, address: u32, inc: bool) {
self.cpar().write(|w|
unsafe { w.pa().bits(address) }
);
self.ccr().modify(|_, w| w.pinc().bit(inc) );
}
/// `address` where from/to data will be read/write
///
/// `inc` indicates whether the address will be incremented after every byte transfer
#[inline]
pub fn set_memory_address(&mut self, address: u32, inc: bool) {
self.cmar().write(|w|
unsafe { w.ma().bits(address) }
);
self.ccr().modify(|_, w| w.minc().bit(inc) );
}
/// Number of bytes to transfer
#[inline]
pub fn set_transfer_length(&mut self, len: u16) {
self.cndtr().write(|w| w.ndt().bits(len));
}
/// Starts the DMA transfer
#[inline]
pub fn start(&mut self) {
self.ccr().modify(|_, w| w.en().set_bit() );
}
/// Returns true if the channel is enabled
#[inline]
pub fn is_started(&self) -> bool {
unsafe { (*$DMAX::ptr()).$ccrX.read().en().bit_is_set() }
}
/// Stops the DMA transfer
#[inline]
pub fn stop(&mut self) {
self.ifcr().write(|w| w.$cgifX().set_bit());
self.ccr().modify(|_, w| w.en().clear_bit() );
}
/// Returns `true` if there's a transfer in progress
#[inline]
pub fn in_progress(&self) -> bool {
self.isr().$tcifX().bit_is_clear()
}
#[inline]
pub fn listen(&mut self, event: Event) {
match event {
Event::HalfTransfer => self.ccr().modify(|_, w| w.htie().set_bit()),
Event::TransferComplete => {
self.ccr().modify(|_, w| w.tcie().set_bit())
}
}
}
#[inline]
pub fn unlisten(&mut self, event: Event) {
match event {
Event::HalfTransfer => {
self.ccr().modify(|_, w| w.htie().clear_bit())
},
Event::TransferComplete => {
self.ccr().modify(|_, w| w.tcie().clear_bit())
}
}
}
#[inline]
pub(crate) fn isr(&self) -> dma1::isr::R {
// NOTE(unsafe) atomic read with no side effects
unsafe { (*$DMAX::ptr()).isr.read() }
}
#[inline]
pub(crate) fn ifcr(&self) -> &dma1::IFCR {
unsafe { &(*$DMAX::ptr()).ifcr }
}
#[inline]
pub(crate) fn ccr(&mut self) -> &dma1::$CCRX {
unsafe { &(*$DMAX::ptr()).$ccrX }
}
#[inline]
pub(crate) fn cndtr(&mut self) -> &dma1::$CNDTRX {
unsafe { &(*$DMAX::ptr()).$cndtrX }
}
#[inline]
pub(crate) fn cpar(&mut self) -> &dma1::$CPARX {
unsafe { &(*$DMAX::ptr()).$cparX }
}
#[inline]
pub(crate) fn cmar(&mut self) -> &dma1::$CMARX {
unsafe { &(*$DMAX::ptr()).$cmarX }
}
#[inline]
pub(crate) fn cselr(&mut self) -> &dma1::CSELR {
unsafe { &(*$DMAX::ptr()).cselr }
}
#[inline]
pub(crate) fn get_cndtr(&self) -> u32 {
// NOTE(unsafe) atomic read with no side effects
unsafe { (*$DMAX::ptr()).$cndtrX.read().bits() }
}
}
impl<BUFFER, const N: usize> FrameSender<BUFFER, $CX, N>
where
BUFFER: Sized + StableDeref<Target = DMAFrame<N>> + DerefMut + 'static,
{
/// This method should be called in the transfer complete interrupt of the
/// DMA, will return the sent frame if the transfer was truly completed.
pub fn transfer_complete_interrupt(
&mut self,
) -> Option<BUFFER> {
// Clear ISR flag (Transfer Complete)
if !self.channel.in_progress() {
self.channel.ifcr().write(|w| w.$ctcifX().set_bit());
} else {
// The old transfer is not complete
return None;
}
self.channel.stop();
// NOTE(compiler_fence) operations on the DMA should not be reordered
// before the next statement, takes the buffer from the DMA transfer.
atomic::compiler_fence(Ordering::SeqCst);
// Return the old buffer for the user to do what they want with it
self.buffer.take()
}
/// Returns `true` if there is an ongoing transfer.
#[inline]
pub fn ongoing_transfer(&self) -> bool {
self.buffer.is_some()
}
/// Send a frame. Will return `Err(frame)` if there was already an ongoing
/// transaction or if the buffer has not been read out.
pub fn send(
&mut self,
frame: BUFFER,
) -> Result<(), BUFFER> {
if self.ongoing_transfer() {
// The old transfer is not complete
return Err(frame);
}
let new_buf = &*frame;
self.channel.set_memory_address(new_buf.buffer_as_ptr() as u32, true);
self.channel.set_transfer_length(new_buf.len() as u16);
// If there has been an error, clear the error flag to let the next
// transaction start
if self.channel.isr().$teifX().bit_is_set() {
self.channel.ifcr().write(|w| w.$cteifX().set_bit());
}
// NOTE(compiler_fence) operations on `buffer` should not be reordered after
// the next statement, which starts the DMA transfer
atomic::compiler_fence(Ordering::Release);
self.channel.start();
self.buffer = Some(frame);
Ok(())
}
}
impl<BUFFER, const N: usize> FrameReader<BUFFER, $CX, N>
where
BUFFER: Sized + StableDeref<Target = DMAFrame<N>> + DerefMut + 'static,
{
/// This function should be called from the transfer complete interrupt of
/// the corresponding DMA channel.
///
/// Returns the full buffer received by the USART.
#[inline]
pub fn transfer_complete_interrupt(&mut self, next_frame: BUFFER) -> BUFFER {
self.internal_interrupt(next_frame, false)
}
/// This function should be called from the character match interrupt of
/// the corresponding USART
///
/// Returns the buffer received by the USART, including the matching
/// character.
#[inline]
pub fn character_match_interrupt(&mut self, next_frame: BUFFER) -> BUFFER {
self.internal_interrupt(next_frame, true)
}
/// This function should be called from the receiver timeout interrupt of
/// the corresponding USART
///
/// Returns the buffer received by the USART.
#[inline]
pub fn receiver_timeout_interrupt(&mut self, next_frame: BUFFER) -> BUFFER {
self.internal_interrupt(next_frame, false)
}
fn internal_interrupt(
&mut self,
mut next_frame: BUFFER,
character_match_interrupt: bool,
) -> BUFFER {
let old_buf = &mut *self.buffer;
let new_buf = &mut *next_frame;
new_buf.clear();
// Clear ISR flag (Transfer Complete)
if !self.channel.in_progress() {
self.channel.ifcr().write(|w| w.$ctcifX().set_bit());
} else if character_match_interrupt {
// 1. If DMA not done and there was a character match interrupt,
// let the DMA flush a little and then halt transfer.
//
// This is to alleviate the race condition between the character
// match interrupt and the DMA memory transfer.
let left_in_buffer = self.channel.get_cndtr() as usize;
for _ in 0..5 {
let now_left = self.channel.get_cndtr() as usize;
if left_in_buffer - now_left >= 4 {
// We have gotten 4 extra characters flushed
break;
}
}
}
self.channel.stop();
// NOTE(compiler_fence) operations on `buffer` should not be reordered after
// the next statement, which starts a new DMA transfer
atomic::compiler_fence(Ordering::SeqCst);
let left_in_buffer = self.channel.get_cndtr() as usize;
let got_data_len = old_buf.max_len() - left_in_buffer; // How many bytes we got
unsafe {
old_buf.set_len(got_data_len);
}
// 2. Check DMA race condition by finding matched character, and that
// the length is larger than 0
let len = if character_match_interrupt && got_data_len > 0 {
let search_buf = old_buf.read();
// Search from the end
let ch = self.matching_character;
if let Some(pos) = search_buf.iter().rposition(|&x| x == ch) {
pos+1
} else {
// No character match found
0
}
} else {
old_buf.len()
};
// 3. Start DMA again
let diff = if len < got_data_len {
// We got some extra characters in the from the new frame, move
// them into the new buffer
let diff = got_data_len - len;
let new_buf_ptr = new_buf.buffer_as_mut_ptr();
let old_buf_ptr = old_buf.buffer_as_ptr();
// new_buf[0..diff].copy_from_slice(&old_buf[len..got_data_len]);
unsafe {
ptr::copy_nonoverlapping(old_buf_ptr.add(len), new_buf_ptr, diff);
}
diff
} else {
0
};
self.channel.set_memory_address(unsafe { new_buf.buffer_as_ptr().add(diff) } as u32, true);
self.channel.set_transfer_length((new_buf.max_len() - diff) as u16);
let received_buffer = core::mem::replace(&mut self.buffer, next_frame);
// NOTE(compiler_fence) operations on `buffer` should not be reordered after
// the next statement, which starts the DMA transfer
atomic::compiler_fence(Ordering::Release);
self.channel.start();
// 4. Return full frame
received_buffer
}
}
impl<B> CircBuffer<B, $CX> {
/// Return the partial contents of the buffer half being written
pub fn partial_peek<R, F, H, T>(&mut self, f: F) -> Result<R, Error>
where
F: FnOnce(&[T], Half) -> Result<(usize, R), ()>,
B: StableDeref<Target = [H; 2]> + 'static,
H: AsRef<[T]>,
{
// this inverts expectation and returns the half being _written_
let buf = match self.readable_half {
Half::First => &self.buffer[1],
Half::Second => &self.buffer[0],
};
// ,- half-buffer
// [ x x x x y y y y y z | z z z z z z z z z z ]
// ^- pending=11
let pending = self.channel.get_cndtr() as usize; // available bytes in _whole_ buffer
let slice = buf.as_ref();
let capacity = slice.len(); // capacity of _half_ a buffer
// <--- capacity=10 --->
// [ x x x x y y y y y z | z z z z z z z z z z ]
let pending = if pending > capacity {
pending - capacity
} else {
pending
};
// ,- half-buffer
// [ x x x x y y y y y z | z z z z z z z z z z ]
// ^- pending=1
let end = capacity - pending;
// [ x x x x y y y y y z | z z z z z z z z z z ]
// ^- end=9
// ^- consumed_offset=4
// [y y y y y] <-- slice
let slice = &buf.as_ref()[self.consumed_offset..end];
match f(slice, self.readable_half) {
Ok((l, r)) => { self.consumed_offset += l; Ok(r) },
Err(_) => Err(Error::BufferError),
}
}
/// Peeks into the readable half of the buffer
/// Returns the result of the closure
pub fn peek<R, F, H, T>(&mut self, f: F) -> Result<R, Error>
where
F: FnOnce(&[T], Half) -> R,
B: StableDeref<Target = [H; 2]> + 'static,
H: AsRef<[T]>,
{
let half_being_read = self.readable_half()?;
let buf = match half_being_read {
Half::First => &self.buffer[0],
Half::Second => &self.buffer[1],
};
let slice = &buf.as_ref()[self.consumed_offset..];
self.consumed_offset = 0;
Ok(f(slice, half_being_read))
}
/// Returns the `Half` of the buffer that can be read
pub fn readable_half(&mut self) -> Result<Half, Error> {
let isr = self.channel.isr();
let first_half_is_done = isr.$htifX().bit_is_set();
let second_half_is_done = isr.$tcifX().bit_is_set();
if first_half_is_done && second_half_is_done {
return Err(Error::Overrun);
}
let last_read_half = self.readable_half;
Ok(match last_read_half {
Half::First => {
if second_half_is_done {
self.channel.ifcr().write(|w| w.$ctcifX().set_bit());
self.readable_half = Half::Second;
Half::Second
} else {
last_read_half
}
}
Half::Second => {
if first_half_is_done {
self.channel.ifcr().write(|w| w.$chtifX().set_bit());
self.readable_half = Half::First;
Half::First
} else {
last_read_half
}
}
})
}
}
| #[cfg(feature = "bbqueue_serial_dma")]
impl<N: ArrayLength<u8>> TxContext<N, $CX> {
pub fn new(consumer: Consumer<'static, N>, channel: $CX) -> Self {
TxContext {
consumer,
channel,
read_grant: None, read_grant_length: 0,
}
}
pub fn handle_dma_irq(&mut self) {
// Clear ISR flag (Transfer Complete)
if !self.channel.in_progress() {
self.channel.ifcr().write(|w| w.$ctcifX().set_bit());
self.channel.stop();
}
if self.channel.is_started() {
return;
}
if self.read_grant.is_some() {
// transfer is now complete, release the buffer
// rtt_target::rprintln!(=>5, "{}DMA:tr.finished\n{}", colors::GREEN, colors::DEFAULT);
let read_grant = self.read_grant.take().unwrap();
read_grant.release(self.read_grant_length);
self.read_grant = None;
}
match self.consumer.read() { // send more
Ok(rgr) => {
let len = rgr.len();
self.channel.set_transfer_length(len as u16);
let mem_addr = rgr.as_ptr() as *const _ as u32;
self.channel.set_memory_address(mem_addr, true);
self.read_grant = Some(rgr);
self.read_grant_length = len;
// rtt_target::rprintln!(=>5, "{}DMA:send {}\n{}", colors::GREEN, len, colors::DEFAULT);
self.channel.start();
},
Err(_) => {} // nothing to send
}
}
}
impl<BUFFER, PAYLOAD, MODE> Transfer<MODE, BUFFER, $CX, PAYLOAD> {
pub fn is_done(&self) -> bool {
self.channel.isr().$tcifX().bit_is_set()
}
pub fn wait(mut self) -> (BUFFER, $CX, PAYLOAD) {
// XXX should we check for transfer errors here?
// The manual says "A DMA transfer error can be generated by reading
// from or writing to a reserved address space". I think it's impossible
// to get to that state with our type safe API and *safe* Rust.
while !self.is_done() {}
self.channel.ifcr().write(|w| w.$cgifX().set_bit());
self.channel.ccr().modify(|_, w| w.en().clear_bit());
// TODO can we weaken this compiler barrier?
// NOTE(compiler_fence) operations on `buffer` should not be reordered
// before the previous statement, which marks the DMA transfer as done
atomic::compiler_fence(Ordering::SeqCst);
(self.buffer, self.channel, self.payload)
}
}
impl<BUFFER, PAYLOAD> Transfer<W, &'static mut BUFFER, $CX, PAYLOAD> {
pub fn peek<T>(&self) -> &[T]
where
BUFFER: AsRef<[T]>
{
let pending = self.channel.get_cndtr() as usize;
let capacity = self.buffer.as_ref().len();
&self.buffer.as_ref()[..(capacity - pending)]
}
}
)+
impl DmaExt for $DMAX {
type Channels = Channels;
fn split(self, ahb: &mut AHB1) -> Channels {
ahb.enr().modify(|_, w| w.$dmaXen().set_bit());
// reset the DMA control registers (stops all on-going transfers)
$(
self.$ccrX.reset();
)+
Channels((), $($CX { }),+)
}
}
}
)+
}
}
dma! {
DMA1: (dma1, dma1en, dma1rst, {
C1: (
ccr1, CCR1,
cndtr1, CNDTR1,
cpar1, CPAR1,
cmar1, CMAR1,
htif1, tcif1,
chtif1, ctcif1, cgif1,
teif1, cteif1
),
C2: (
ccr2, CCR2,
cndtr2, CNDTR2,
cpar2, CPAR2,
cmar2, CMAR2,
htif2, tcif2,
chtif2, ctcif2, cgif2,
teif2, cteif2
),
C3: (
ccr3, CCR3,
cndtr3, CNDTR3,
cpar3, CPAR3,
cmar3, CMAR3,
htif3, tcif3,
chtif3, ctcif3, cgif3,
teif3, cteif3
),
C4: (
ccr4, CCR4,
cndtr4, CNDTR4,
cpar4, CPAR4,
cmar4, CMAR4,
htif4, tcif4,
chtif4, ctcif4, cgif4,
teif4, cteif4
),
C5: (
ccr5, CCR5,
cndtr5, CNDTR5,
cpar5, CPAR5,
cmar5, CMAR5,
htif5, tcif5,
chtif5, ctcif5, cgif5,
teif5, cteif5
),
C6: (
ccr6, CCR6,
cndtr6, CNDTR6,
cpar6, CPAR6,
cmar6, CMAR6,
htif6, tcif6,
chtif6, ctcif6, cgif6,
teif6, cteif6
),
C7: (
ccr7, CCR7,
cndtr7, CNDTR7,
cpar7, CPAR7,
cmar7, CMAR7,
htif7, tcif7,
chtif7, ctcif7, cgif7,
teif7, cteif7
),
}),
DMA2: (dma2, dma2en, dma2rst, {
C1: (
ccr1, CCR1,
cndtr1, CNDTR1,
cpar1, CPAR1,
cmar1, CMAR1,
htif1, tcif1,
chtif1, ctcif1, cgif1,
teif1, cteif1
),
C2: (
ccr2, CCR2,
cndtr2, CNDTR2,
cpar2, CPAR2,
cmar2, CMAR2,
htif2, tcif2,
chtif2, ctcif2, cgif2,
teif2, cteif2
),
C3: (
ccr3, CCR3,
cndtr3, CNDTR3,
cpar3, CPAR3,
cmar3, CMAR3,
htif3, tcif3,
chtif3, ctcif3, cgif3,
teif3, cteif3
),
C4: (
ccr4, CCR4,
cndtr4, CNDTR4,
cpar4, CPAR4,
cmar4, CMAR4,
htif4, tcif4,
chtif4, ctcif4, cgif4,
teif4, cteif4
),
C5: (
ccr5, CCR5,
cndtr5, CNDTR5,
cpar5, CPAR5,
cmar5, CMAR5,
htif5, tcif5,
chtif5, ctcif5, cgif5,
teif5, cteif5
),
C6: (
ccr6, CCR6,
cndtr6, CNDTR6,
cpar6, CPAR6,
cmar6, CMAR6,
htif6, tcif6,
chtif6, ctcif6, cgif6,
teif6, cteif6
),
C7: (
ccr7, CCR7,
cndtr7, CNDTR7,
cpar7, CPAR7,
cmar7, CMAR7,
htif7, tcif7,
chtif7, ctcif7, cgif7,
teif7, cteif7
),
}),
} | |
accountsign.go | // Copyright (c) 2019 IoTeX Foundation
// This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no
// warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent
// permitted by law, all liability for your use of the code is disclaimed. This source code is governed by Apache
// License 2.0 that can be found in the LICENSE file.
package account
import (
"github.com/spf13/cobra"
"github.com/MeshBoxFoundation/mesh-core/ioctl/config"
"github.com/MeshBoxFoundation/mesh-core/ioctl/output"
"github.com/MeshBoxFoundation/mesh-core/ioctl/util"
)
var signer string
// Multi-language support
var (
signCmdShorts = map[config.Language]string{
config.English: "Sign message with private key from wallet",
config.Chinese: "用钱包中的私钥对信息签名",
}
signCmdUses = map[config.Language]string{
config.English: "sign MESSAGE [-s SIGNER]",
config.Chinese: "sign 信息 [-s 签署人]",
}
flagSignerUsages = map[config.Language]string{
config.English: "choose a signing account",
config.Chinese: "选择一个签名账户",
}
)
// accountSignCmd represents the account sign command
var accountSignCmd = &cobra.Command{
Use: config.TranslateInLang(signCmdUses, config.UILanguage),
Short: config.TranslateInLang(signCmdShorts, config.UILanguage),
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cmd.SilenceUsage = true
err := accountSign(args[0])
return output.PrintError(err)
},
}
func init() {
accountSignCmd.Flags().StringVarP(&signe | signer", "s", "", config.TranslateInLang(flagSignerUsages, config.UILanguage))
}
func accountSign(msg string) error {
var (
addr string
err error
)
if util.AliasIsHdwalletKey(signer) {
addr = signer
} else {
addr, err = util.Address(signer)
if err != nil {
return output.NewError(output.AddressError, "failed to get address", err)
}
}
signedMessage, err := Sign(addr, "", msg)
if err != nil {
return output.NewError(output.KeystoreError, "failed to sign message", err)
}
output.PrintResult(signedMessage)
return nil
}
| r, " |
travel.rs | //! Photon movement function.
use crate::{
phys::{Local, Photon},
sim::mcrt::Output,
};
use physical_constants::SPEED_OF_LIGHT_IN_VACUUM;
/// Move the photon forward and record the flight.
#[inline]
pub fn travel(data: &mut Output, phot: &mut Photon, env: &Local, index: [usize; 3], dist: f64) | {
debug_assert!(dist > 0.0);
let weight_power_dist = phot.weight() * phot.power() * dist;
data.energy[index] += weight_power_dist * env.ref_index() / SPEED_OF_LIGHT_IN_VACUUM;
data.absorptions[index] += weight_power_dist * env.abs_coeff();
data.shifts[index] += weight_power_dist * env.shift_coeff();
phot.ray_mut().travel(dist);
} |
|
update_spu.rs | #![allow(clippy::assign_op_pattern)]
use dataplane::api::Request;
use dataplane::derive::Decoder;
use dataplane::derive::Encoder;
use fluvio_controlplane_metadata::spu::SpuSpec;
use crate::InternalSpuApi;
use super::ControlPlaneRequest;
pub type UpdateSpuRequest = ControlPlaneRequest<SpuSpec>; | type Response = UpdateSpuResponse;
}
#[derive(Decoder, Encoder, Default, Debug)]
pub struct UpdateSpuResponse {} |
impl Request for UpdateSpuRequest {
const API_KEY: u16 = InternalSpuApi::UpdateSpu as u16; |
relayer.rs | //! Task for starting the relayer
use std::time::Duration;
use abscissa_core::tracing::info;
use relayer::{
chain::{Chain, CosmosSDKChain},
client::LightClient,
config::Config,
};
use crate::prelude::*;
/// Start the relayer with the given config.
///
/// **Note:** The relayer loop is currently a no-op.
pub async fn start(config: &Config, chains: Vec<CosmosSDKChain>) -> Result<(), BoxError> {
for chain in &chains {
let light_client = chain.light_client().ok_or_else(|| {
format!( | chain.id()
)
})?;
if let Some(latest_trusted) = light_client.latest_trusted().await? {
info!(
chain.id = %chain.id(),
"latest trusted state is at height {:?}",
latest_trusted.height(),
);
} else {
warn!(
chain.id = %chain.id(),
"no latest trusted state",
);
}
}
let mut interval = tokio::time::interval(Duration::from_secs(2));
loop {
interval.tick().await;
}
} | "light client for chain {} has not been initialized", |
get_graph.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 14 15:47:45 2021
@author: xuery
"""
import cv2
import time
import numpy as np
import os
import copy
import pickle
import random
import math
import matplotlib.pyplot as plt
from scipy import spatial
from skimage import morphology
from sklearn.mixture import GaussianMixture
from shapely.geometry import LineString, Point
from mpl_toolkits.mplot3d import Axes3D
class get_graph():
def __init__(self, raw_img):
self.raw_img = cv2.resize(raw_img, (512,512))
self.stride = 30
self.all_centroids = []
def get_binary(self):
gray_img = cv2.cvtColor(self.raw_img, cv2.COLOR_RGB2GRAY)
_, binary_img = cv2.threshold(gray_img, 100, 255, cv2.THRESH_BINARY_INV)
return binary_img
def ske2point(self):
skeleton_img = self.get_binary()
img_w, img_h = skeleton_img.shape
for i in range(img_w//self.stride):
for j in range(img_h//self.stride):
small_img = skeleton_img[i*self.stride:(i+1)*self.stride, j*self.stride:(j+1)*self.stride]
x_idx, y_idx = small_img.nonzero()
if len(x_idx) == 0:
continue
x_center, y_center = sum(x_idx) / len(x_idx) + i * self.stride,\
sum(y_idx) / len(x_idx) + j * self.stride
#all_centorids stores the idx of points
self.all_centroids.append(np.array([int(x_center), int(y_center)]))
self.all_centroids = np.array(self.all_centroids)
self.centroids_copy = copy.deepcopy(self.all_centroids)
def optimization(self, save_path=None):
#for the points in all_centroid that don't belong to the rope, delete it
noise_idx = []
binary_img = self.get_binary()
for i in range(len(self.all_centroids)):
if binary_img[int(self.all_centroids[i][0])][int(self.all_centroids[i][1])] == 0:
noise_idx.append(i)
self.all_centroids = np.delete(self.all_centroids, noise_idx, axis=0)
if save_path != None:
self.img_point_write(save_path, all_centroids, binary_img)
def visualization(self):
self.optimization()
plt.plot(self.all_centroids[:,0], self.all_centroids[:,1], 'bo', ms=5)
plt.show()
def graph(self, num_neigh_points = 10):
self.ske2point()
self.visualization()
tree = spatial.KDTree(self.all_centroids)
start_point = [500, 0]
neigh_points_idx, neigh_points = self.find_neigh_points(tree, start_point, 2)
next_point = neigh_points[0]
query_pair = [start_point, next_point]
point_order = query_pair
while True:
if len(self.all_centroids) < num_neigh_points:
break
if len(self.all_centroids) == 30:
break
tree = spatial.KDTree(self.all_centroids)
neigh_points_idx, neigh_points = self.find_neigh_points(tree, query_pair[1], num_neigh_points)
idx, next_point = self.find_path(query_pair, neigh_points)
if idx == -99:
print("end of construction...")
return point_order
query_pair = [query_pair[1], next_point]
point_order.append(next_point)
#pop out the walked point
self.all_centroids = self.all_centroids.tolist()
self.all_centroids.pop(neigh_points_idx[idx])
self.all_centroids = np.array(self.all_centroids)
print("remain lens of points: ", len(self.all_centroids))
return point_order
def find_neigh_points(self, tree, centroid, num_points):
dist, near_points_idx = tree.query(centroid, k=num_points)
near_points = self.all_centroids[near_points_idx]
return near_points_idx[1:], near_points[1:]
def find_path(self, query_pair, neigh_points):
v_query = query_pair[1] - query_pair[0]
next_point = np.zeros_like(query_pair[0])
angle_diff = np.pi
next_idx = -99
for i in range(len(neigh_points)):
v_compare = query_pair[1] - neigh_points[i]
#if the dist of all neigh_points is more than 65, break. This setting is for noise
if np.linalg.norm(v_compare) >70:
continue
#calculate the angle of two vectors
unit_v1 = v_query / np.linalg.norm(v_query)
unit_v2 = v_compare / np.linalg.norm(v_compare)
dot_product = np.dot(unit_v1, unit_v2)
angle = np.arccos(dot_product) #radian
if np.pi - angle < angle_diff:
next_point = neigh_points[i]
angle_diff = np.pi - angle
next_idx = i
return next_idx, next_point
def find_crossing(self, point_order, visual=False):
#create lines
pairs = []
crossing = []
for i in range(len(point_order)-1):
new_pair = np.array([point_order[i], point_order[i+1]])
pairs.append(new_pair)
for i in range(len(pairs)):
for j in range(len(pairs)-i):
intersec = self.intersection(pairs[i], pairs[j+i])
if intersec is not False:
crossing.append([intersec, pairs[i][0], pairs[j+i][0]])
if visual == True:
self.visualization_final_graph(point_order, crossing)
return crossing
#if no intersection, return False, else return the value of intersection
def intersection(self, pair1, pair2):
#if two pairs has a same point, break
if np.all(pair1[0]-pair2[0]==0) or np.all(pair1[1]-pair2[0]==0) \
or np.all(pair1[0]-pair2[1]==0) or np.all(pair1[1]-pair2[1]==0): |
line1 = LineString([pair1[0], pair1[1]])
line2 = LineString([pair2[0], pair2[1]])
intersection_point = line1.intersection(line2)
#no intersection
if intersection_point.is_empty:
return False
else:
return np.array([intersection_point.x, intersection_point.y])
def visualization_final_graph(self, point_order, crossing):
x, y = zip(*point_order)
plt.plot(x, y, '-o', zorder=1)
crossing = np.array(crossing)
c_x = crossing[:,0,0]
c_y = crossing[:,0,1]
plt.scatter(c_x, c_y, 20, 'r', zorder=2)
plt.show()
def trajectory(self, env, sa, point_order, crossing, stride):
picker_pos, particle_pos = sa.action_space.Picker._get_pos()
print(particle_pos)
particle_dist_2d = np.linalg.norm(particle_pos[0] - particle_pos[1])
init_particle = particle_pos[random.randint(0,len(particle_pos))].tolist()
particle_list = []
particle_list.append(init_particle)
for i in range(len(point_order)-stride):
if i % stride != 0:
continue
curr_particle = particle_list[i//stride]
y_o = point_order[i+stride][1] - point_order[i][1]
x_o = point_order[i+stride][0] - point_order[i][0]
orientation = abs(y_o / x_o)
theta = math.atan(orientation)
if x_o == 0:
x_o = 0.1
if y_o == 0:
y_o = 0.1
x = curr_particle[0] + math.cos(theta) * particle_dist_2d * x_o / abs(x_o)
y = curr_particle[2] + math.sin(theta) * particle_dist_2d * y_o / abs(y_o)
next_particle = [x, curr_particle[1], y, curr_particle[3]]
particle_list.append(next_particle)
for i in range(len(particle_list)):
if i == 3:
particle_list[i][1] = 0.0145
if i == 4:
particle_list[i][1] = 0.0245
if i == 5:
particle_list[i][1] = 0.0145
if i == 9:
particle_list[i][1] = 0.0145
if i == 10:
particle_list[i][1] = 0.0245
if i == 11:
particle_list[i][1] = 0.0145
particle_list = np.array(particle_list)
particle_x = particle_list[:, 0]
particle_z = particle_list[:, 1]
particle_y = particle_list[:, 2]
fig=plt.figure()
ax2 = Axes3D(fig)
ax2.scatter3D(particle_x,particle_y,particle_z, cmap='Blues')
ax2.plot3D(particle_x,particle_y,particle_z,'gray')
plt.show()
return particle_list | return False |
pbifg.rs | #[doc = "Register `PBIFG` reader"]
pub struct R(crate::R<PBIFG_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<PBIFG_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::convert::From<crate::R<PBIFG_SPEC>> for R {
fn from(reader: crate::R<PBIFG_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `PBIFG` writer"]
pub struct W(crate::W<PBIFG_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<PBIFG_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target |
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl core::convert::From<crate::W<PBIFG_SPEC>> for W {
fn from(writer: crate::W<PBIFG_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `P3IFG` reader - Port 3 Interrupt Flag"]
pub struct P3IFG_R(crate::FieldReader<u8, u8>);
impl P3IFG_R {
pub(crate) fn new(bits: u8) -> Self {
P3IFG_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for P3IFG_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `P3IFG` writer - Port 3 Interrupt Flag"]
pub struct P3IFG_W<'a> {
w: &'a mut W,
}
impl<'a> P3IFG_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0xff) | (value as u16 & 0xff);
self.w
}
}
#[doc = "Field `P4IFG` reader - Port 4 Interrupt Flag"]
pub struct P4IFG_R(crate::FieldReader<u8, u8>);
impl P4IFG_R {
pub(crate) fn new(bits: u8) -> Self {
P4IFG_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for P4IFG_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `P4IFG` writer - Port 4 Interrupt Flag"]
pub struct P4IFG_W<'a> {
w: &'a mut W,
}
impl<'a> P4IFG_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u16 & 0xff) << 8);
self.w
}
}
impl R {
#[doc = "Bits 0:7 - Port 3 Interrupt Flag"]
#[inline(always)]
pub fn p3ifg(&self) -> P3IFG_R {
P3IFG_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bits 8:15 - Port 4 Interrupt Flag"]
#[inline(always)]
pub fn p4ifg(&self) -> P4IFG_R {
P4IFG_R::new(((self.bits >> 8) & 0xff) as u8)
}
}
impl W {
#[doc = "Bits 0:7 - Port 3 Interrupt Flag"]
#[inline(always)]
pub fn p3ifg(&mut self) -> P3IFG_W {
P3IFG_W { w: self }
}
#[doc = "Bits 8:15 - Port 4 Interrupt Flag"]
#[inline(always)]
pub fn p4ifg(&mut self) -> P4IFG_W {
P4IFG_W { w: self }
}
#[doc = "Writes raw bits to the register."]
pub unsafe fn bits(&mut self, bits: u16) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Port B Interrupt Flag\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pbifg](index.html) module"]
pub struct PBIFG_SPEC;
impl crate::RegisterSpec for PBIFG_SPEC {
type Ux = u16;
}
#[doc = "`read()` method returns [pbifg::R](R) reader structure"]
impl crate::Readable for PBIFG_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [pbifg::W](W) writer structure"]
impl crate::Writable for PBIFG_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets PBIFG to value 0"]
impl crate::Resettable for PBIFG_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| {
&self.0
} |
pigglywiggly.py | # -*- coding: utf-8 -*-
import scrapy
import json
import re
import logging
from locations.items import GeojsonPointItem
class PigglyWigglySpider(scrapy.Spider):
''' This spider scrapes from two different places, an api which has their stores in Wisconsin
and Illinois, and a page which has all of their other stores. Cookies are used for the
api request.
'''
name = "pigglywiggly"
allowed_domains = ["pigglywiggly.com"]
def start_requests(self):
url = 'https://www.shopthepig.com/api/m_store_location'
headers = {
'x-newrelic-id': 'XQYBWFVVGwAEVFNRBQcP',
'accept-encoding': 'gzip, deflate, br',
'x-csrf-token': 'eF2m10r8n51nsRgBSv1xSvhAGtCo8E84BExlmn54Vvc',
'accept-language': 'en-US,en;q=0.9',
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36',
'accept': 'application/json, text/plain, */*',
'referer': 'https://www.shopthepig.com/stores',
}
cookies = {
'__cfduid': 'db0a53231376d78a40dd7fd728fa896f51512948321',
'SESSb159e7a0d4a6fad9ba3abc7fadef99ec': 'h3o7xcjnfcERSRrqJVh0soQdUI5IFIBDIQlytOZkhIU',
'XSRF-TOKEN': 'eF2m10r8n51nsRgBSv1xSvhAGtCo8E84BExlmn54Vvc',
'has_js': 1,
}
yield scrapy.http.FormRequest(
url=url, headers=headers, callback=self.parse_wi, cookies=cookies
)
yield scrapy.Request(
'https://www.pigglywiggly.com/store-locations',
callback=self.parse_nonwi,
)
def parse_wi(self, response):
data = json.loads(response.body_as_unicode())
stores = data['stores']
for store in stores:
unp = {
'ref': store['storeID'],
'name': store['storeName'],
'addr_full': store['normalized_address'],
'city': store['normalized_city'],
'state': store['normalized_state'],
'postcode': store['normalized_zip'],
'lat': store['latitude'],
'lon': store['longitude'],
'phone': store['phone']
}
properties = {}
for key in unp:
if unp[key]: properties[key] = unp[key]
yield GeojsonPointItem(**properties)
def | (self, response):
for state_url in response.xpath('//div[@class="views-field-province-1"]/span[@class="field-content"]/a/@href').extract():
yield scrapy.Request(
response.urljoin(state_url),
callback=self.parse_state,
)
def parse_state(self, response):
for location in response.xpath('//li[contains(@class, "views-row")]'):
unp = {
'addr_full': location.xpath('.//div[@class="street-address"]/text()').extract_first(),
'city': location.xpath('.//span[@class="locality"]/text()').extract_first(),
'state': location.xpath('.//span[@class="region"]/text()').extract_first(),
'postcode': location.xpath('.//span[@class="postal-code"]/text()').extract_first(),
'phone': location.xpath('.//label[@class="views-label-field-phone-value"]/following-sibling::span[1]/text()').extract_first(),
'website': location.xpath('.//label[@class="views-label-field-website-value"]/following-sibling::span[1]/a/@href').extract_first(),
}
if unp['website']:
if 'google' in unp['website']:
unp['website'] = None
if unp['phone']:
unp['phone'] = unp['phone'].replace('.', '-')
properties = {}
for key in unp:
if unp[key]:
properties[key] = unp[key].strip()
ref = ''
if 'addr_full' in properties: ref += properties['addr_full']
if 'phone' in properties: ref += properties['phone']
properties['ref'] = ref
yield GeojsonPointItem(**properties)
| parse_nonwi |
cmd.go | /*
Copyright (c) 2019 Red Hat, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package tunnel
import (
"fmt"
"net"
"net/url"
"os"
"os/exec"
"regexp"
"strings"
c "github.com/openshift-online/ocm-cli/pkg/cluster"
"github.com/openshift-online/ocm-cli/pkg/ocm"
clustersmgmtv1 "github.com/openshift-online/ocm-sdk-go/clustersmgmt/v1"
"github.com/spf13/cobra"
)
var args struct {
useSubnets bool
}
var Cmd = &cobra.Command{
Use: "tunnel [flags] {CLUSTERID|CLUSTER_NAME|CLUSTER_NAME_SEARCH} -- [sshuttle arguments]",
Short: "tunnel to a cluster",
Long: "Use sshuttle to create a ssh tunnel to a cluster by ID or Name or" +
"cluster name search string according to the api: " +
"https://api.openshift.com/#/clusters/get_api_clusters_mgmt_v1_clusters",
Example: " ocm tunnel <cluster_id>\n ocm tunnel %test%",
RunE: run,
Hidden: true,
Args: cobra.ArbitraryArgs,
}
func init() |
func run(cmd *cobra.Command, argv []string) error {
// Check that the cluster key (name, identifier or external identifier) given by the user
// is reasonably safe so that there is no risk of SQL injection:
if len(argv) < 1 {
fmt.Fprintf(
os.Stderr,
"Expected exactly one cluster name, identifier or external identifier "+
"is required\n",
)
os.Exit(1)
}
clusterKey := argv[0]
if !c.IsValidClusterKey(clusterKey) {
return fmt.Errorf(
"cluster name, identifier or external identifier '%s' isn't valid: it "+
"must contain only letters, digits, dashes and underscores",
clusterKey,
)
}
path, err := exec.LookPath("sshuttle")
if err != nil {
return fmt.Errorf("to run this, you need install the sshuttle tool first")
}
// Create the client for the OCM API:
connection, err := ocm.NewConnection().Build()
if err != nil {
return fmt.Errorf("failed to create OCM connection: %v", err)
}
defer connection.Close()
cluster, err := c.GetCluster(connection, clusterKey)
if err != nil {
return fmt.Errorf("failed to get cluster '%s': %v", clusterKey, err)
}
fmt.Printf("Will create tunnel to cluster:\n Name: %s\n ID: %s\n", cluster.Name(), cluster.ID())
sshURL, err := generateSSHURI(cluster)
if err != nil {
return err
}
sshuttleArgs := []string{
"--remote", sshURL,
}
if args.useSubnets {
sshuttleArgs = append(sshuttleArgs,
cluster.Network().MachineCIDR(),
cluster.Network().ServiceCIDR(),
cluster.Network().PodCIDR())
} else {
consoleIPs, err := resolveURL(cluster.Console().URL())
if err != nil {
return fmt.Errorf("can't get console IPs: %s", err)
}
apiIPs, err := resolveURL(cluster.API().URL())
if err != nil {
return fmt.Errorf("can't get api server IPs: %s", err)
}
sshuttleArgs = append(sshuttleArgs, consoleIPs...)
sshuttleArgs = append(sshuttleArgs, apiIPs...)
}
sshuttleArgs = append(sshuttleArgs, argv[1:]...)
// Output sshuttle command execution string for review
fmt.Printf("\n# %s %s\n\n", path, strings.Join(sshuttleArgs, " "))
// #nosec G204
sshuttleCmd := exec.Command(path, sshuttleArgs...)
sshuttleCmd.Stderr = os.Stderr
sshuttleCmd.Stdin = os.Stdin
sshuttleCmd.Stdout = os.Stdout
err = sshuttleCmd.Run()
if err != nil {
return fmt.Errorf("failed to login to cluster: %s", err)
}
return nil
}
func generateSSHURI(cluster *clustersmgmtv1.Cluster) (string, error) {
r := regexp.MustCompile(`(?mi)^https:\/\/api\.(.*):6443`)
apiURL := cluster.API().URL()
if len(apiURL) == 0 {
return "", fmt.Errorf("cannot find the api URL for cluster: %s", cluster.Name())
}
base := r.FindStringSubmatch(apiURL)[1]
if len(base) == 0 {
return "", fmt.Errorf("unable to match api URL for cluster: %s", cluster.Name())
}
return "sre-user@rh-ssh." + base, nil
}
func resolveURL(rawurl string) ([]string, error) {
u, err := url.Parse(rawurl)
if err != nil {
return nil, fmt.Errorf("can't parse url: %s", err)
}
hostname := u.Hostname()
ips, err := net.LookupIP(hostname)
if err != nil {
return nil, fmt.Errorf("failed looking up %s: %s", hostname, err)
}
result := []string{}
for _, ip := range ips {
result = append(result, ip.String())
}
return result, nil
}
| {
flags := Cmd.Flags()
flags.BoolVarP(
&args.useSubnets,
"subnets",
"",
false,
"If specified, tunnel the entire subnets of MachineCIDR, ServiceCIDR and PodCIDR. "+
"Otherwise, only tunnel to the IPs of console and API Servers. ",
)
} |
html.go | // Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bufio"
"bytes"
"cmd/internal/browser"
"fmt"
"html/template"
"io"
"io/ioutil"
"math"
"os"
"path/filepath"
"strings"
)
// htmlOutput reads the profile data from profile and generates an HTML
// coverage report, writing it to outfile. If outfile is empty,
// it writes the report to a temporary file and opens it in a web browser.
func htmlOutput(profile, outfile string) error {
profiles, err := ParseProfiles(profile)
if err != nil {
return err
}
var d templateData
dirs, err := findPkgs(profiles)
if err != nil {
return err
}
for _, profile := range profiles {
fn := profile.FileName
if profile.Mode == "set" {
d.Set = true
}
file, err := findFile(dirs, fn)
if err != nil {
return err
}
src, err := ioutil.ReadFile(file)
if err != nil {
return fmt.Errorf("can't read %q: %v", fn, err)
}
var buf strings.Builder
err = htmlGen(&buf, src, profile.Boundaries(src))
if err != nil {
return err
}
d.Files = append(d.Files, &templateFile{
Name: fn,
Body: template.HTML(buf.String()),
Coverage: percentCovered(profile),
})
}
var out *os.File
if outfile == "" {
var dir string
dir, err = ioutil.TempDir("", "cover")
if err != nil {
return err
}
out, err = os.Create(filepath.Join(dir, "coverage.html"))
} else {
out, err = os.Create(outfile)
}
if err != nil {
return err
}
err = htmlTemplate.Execute(out, d)
if err2 := out.Close(); err == nil {
err = err2
}
if err != nil {
return err
}
if outfile == "" {
if !browser.Open("file://" + out.Name()) {
fmt.Fprintf(os.Stderr, "HTML output written to %s\n", out.Name())
}
}
return nil
}
// percentCovered returns, as a percentage, the fraction of the statements in
// the profile covered by the test run.
// In effect, it reports the coverage of a given source file.
func percentCovered(p *Profile) float64 |
// htmlGen generates an HTML coverage report with the provided filename,
// source code, and tokens, and writes it to the given Writer.
func htmlGen(w io.Writer, src []byte, boundaries []Boundary) error {
dst := bufio.NewWriter(w)
for i := range src {
for len(boundaries) > 0 && boundaries[0].Offset == i {
b := boundaries[0]
if b.Start {
n := 0
if b.Count > 0 {
n = int(math.Floor(b.Norm*9)) + 1
}
fmt.Fprintf(dst, `<span class="cov%v" title="%v">`, n, b.Count)
} else {
dst.WriteString("</span>")
}
boundaries = boundaries[1:]
}
switch b := src[i]; b {
case '>':
dst.WriteString(">")
case '<':
dst.WriteString("<")
case '&':
dst.WriteString("&")
case '\t':
dst.WriteString(" ")
default:
dst.WriteByte(b)
}
}
return dst.Flush()
}
// rgb returns an rgb value for the specified coverage value
// between 0 (no coverage) and 10 (max coverage).
func rgb(n int) string {
if n == 0 {
return "rgb(192, 0, 0)" // Red
}
// Gradient from gray to green.
r := 128 - 12*(n-1)
g := 128 + 12*(n-1)
b := 128 + 3*(n-1)
return fmt.Sprintf("rgb(%v, %v, %v)", r, g, b)
}
// colors generates the CSS rules for coverage colors.
func colors() template.CSS {
var buf bytes.Buffer
for i := 0; i < 11; i++ {
fmt.Fprintf(&buf, ".cov%v { color: %v }\n", i, rgb(i))
}
return template.CSS(buf.String())
}
var htmlTemplate = template.Must(template.New("html").Funcs(template.FuncMap{
"colors": colors,
}).Parse(tmplHTML))
type templateData struct {
Files []*templateFile
Set bool
}
// PackageName returns a name for the package being shown.
// It does this by choosing the penultimate element of the path
// name, so foo.bar/baz/foo.go chooses 'baz'. This is cheap
// and easy, avoids parsing the Go file, and gets a better answer
// for package main. It returns the empty string if there is
// a problem.
func (td templateData) PackageName() string {
if len(td.Files) == 0 {
return ""
}
fileName := td.Files[0].Name
elems := strings.Split(fileName, "/") // Package path is always slash-separated.
// Return the penultimate non-empty element.
for i := len(elems) - 2; i >= 0; i-- {
if elems[i] != "" {
return elems[i]
}
}
return ""
}
type templateFile struct {
Name string
Body template.HTML
Coverage float64
}
const tmplHTML = `
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>{{$pkg := .PackageName}}{{if $pkg}}{{$pkg}}: {{end}}Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
{{colors}}
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
{{range $i, $f := .Files}}
<option value="file{{$i}}">{{$f.Name}} ({{printf "%.1f" $f.Coverage}}%)</option>
{{end}}
</select>
</div>
<div id="legend">
<span>not tracked</span>
{{if .Set}}
<span class="cov0">not covered</span>
<span class="cov8">covered</span>
{{else}}
<span class="cov0">no coverage</span>
<span class="cov1">low coverage</span>
<span class="cov2">*</span>
<span class="cov3">*</span>
<span class="cov4">*</span>
<span class="cov5">*</span>
<span class="cov6">*</span>
<span class="cov7">*</span>
<span class="cov8">*</span>
<span class="cov9">*</span>
<span class="cov10">high coverage</span>
{{end}}
</div>
</div>
<div id="content">
{{range $i, $f := .Files}}
<pre class="file" id="file{{$i}}" style="display: none">{{$f.Body}}</pre>
{{end}}
</div>
</body>
<script>
(function() {
var files = document.getElementById('files');
var visible;
files.addEventListener('change', onChange, false);
function select(part) {
if (visible)
visible.style.display = 'none';
visible = document.getElementById(part);
if (!visible)
return;
files.value = part;
visible.style.display = 'block';
location.hash = part;
}
function onChange() {
select(files.value);
window.scrollTo(0, 0);
}
if (location.hash != "") {
select(location.hash.substr(1));
}
if (!visible) {
select("file0");
}
})();
</script>
</html>
`
| {
var total, covered int64
for _, b := range p.Blocks {
total += int64(b.NumStmt)
if b.Count > 0 {
covered += int64(b.NumStmt)
}
}
if total == 0 {
return 0
}
return float64(covered) / float64(total) * 100
} |
read_message.rs | use catenis_api_client::{
CatenisClient, ClientOptions, Environment, Result,
api::*,
};
fn main() -> Result<()> | {
let device_credentials = (
"dnN3Ea43bhMTHtTvpytS",
concat!(
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
"202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f",
),
).into();
let mut ctn_client = CatenisClient::new_with_options(
Some(device_credentials),
&[
ClientOptions::Environment(Environment::Sandbox),
],
)?;
let message_id = "oDWPuD5kjCsEiNEEWwrW";
let result = ctn_client.read_message(
message_id,
Some(ReadMessageOptions {
encoding: Some(Encoding::UTF8),
continuation_token: None,
data_chunk_size: None,
async_: None,
}),
)?;
println!("Read message: {}", result.msg_data.unwrap());
let msg_info = result.msg_info.unwrap();
if msg_info.action == RecordMessageAction::Send {
println!("Message sent from: {:?}", msg_info.from.unwrap());
}
Ok(())
} |
|
mempool.go | package collector
import (
"github.com/btcsuite/btcd/rpcclient"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"time"
)
type memPoolCollector struct {
client *rpcclient.Client
txnCount *prometheus.Desc
logger log.Logger
collector string
}
func | (rpcClient *rpcclient.Client, logger log.Logger) *memPoolCollector {
return &memPoolCollector{
client: rpcClient,
logger: logger,
collector: "mempool",
txnCount: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "mempool", "transactions_count"),
"Number of transactions in the mempool",
nil, nil),
}
}
func (c *memPoolCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- c.txnCount
}
func (c *memPoolCollector) Collect(ch chan<- prometheus.Metric) {
collectTime := time.Now()
getRawMemPool, err := c.client.GetRawMempool()
if err != nil {
level.Error(c.logger).Log("err", err)
ch <- prometheus.MustNewConstMetric(collectError, prometheus.GaugeValue, 1, c.collector)
return
}
ch <- prometheus.MustNewConstMetric(c.txnCount, prometheus.GaugeValue, float64(len(getRawMemPool)))
ch <- prometheus.MustNewConstMetric(collectError, prometheus.GaugeValue, 0, c.collector)
ch <- prometheus.MustNewConstMetric(collectDuration, prometheus.GaugeValue, time.Since(collectTime).Seconds(), c.collector)
}
| NewMemPoolCollector |
redirect_example.py | from sanic import Sanic
from sanic import response
app = Sanic(__name__)
@app.route('/')
def | (request):
return response.redirect('/redirect')
@app.route('/redirect')
async def test(request):
return response.json({"Redirected": True})
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8000) | handle_request |
reducer.ts | import { UpdateWizardConfiguration, WizardConfiguration } from "../../components/forms/wizards/types"; | import { _IWizardViewState } from "./types";
const getDefaultConfigurations = (create: WizardConfiguration<any>[], update: UpdateWizardConfiguration<any>[]) => {
let result: _IWizardViewState = {
createConfigurations: {},
updateConfigurations: {}
};
create.forEach((createConfig) => {
result = {
...result,
createConfigurations: {
...result.createConfigurations,
[createConfig.type]: createConfig
}
}
})
update.forEach((updateConfig) => {
result = {
...result,
updateConfigurations: {
...result.updateConfigurations,
[updateConfig.type]: updateConfig
}
}
})
return result;
}
export const _initialWizardViewContextState: _IWizardViewState = getDefaultConfigurations(_CREATE_WIZARD_CONFIGURATION_LIST, _UPDATE_WIZARD_CONFIGURATION_LIST); | import { _CREATE_WIZARD_CONFIGURATION_LIST, _UPDATE_WIZARD_CONFIGURATION_LIST } from "./configurations"; |
lockfreequeue.go | package eventloop
import (
"fmt"
"runtime"
"sync/atomic"
)
type esCache struct {
putNo uint32
getNo uint32
value interface{}
}
// EsQueue lock free queue
type EsQueue struct {
capacity uint32
capMod uint32
putPos uint32
getPos uint32
cache []esCache
}
func NewQueue(capacity uint32) *EsQueue |
func (q *EsQueue) String() string {
getPos := atomic.LoadUint32(&q.getPos)
putPos := atomic.LoadUint32(&q.putPos)
return fmt.Sprintf("Queue{capacity: %v, capMod: %v, putPos: %v, getPos: %v}",
q.capacity, q.capMod, putPos, getPos)
}
func (q *EsQueue) Capaciity() uint32 {
return q.capacity
}
func (q *EsQueue) Quantity() uint32 {
var putPos, getPos uint32
var quantity uint32
getPos = atomic.LoadUint32(&q.getPos)
putPos = atomic.LoadUint32(&q.putPos)
if putPos >= getPos {
quantity = putPos - getPos
} else {
quantity = q.capMod + (putPos - getPos)
}
return quantity
}
// put queue functions
func (q *EsQueue) Put(val interface{}) (ok bool, quantity uint32) {
var putPos, putPosNew, getPos, posCnt uint32
var cache *esCache
capMod := q.capMod
getPos = atomic.LoadUint32(&q.getPos)
putPos = atomic.LoadUint32(&q.putPos)
if putPos >= getPos {
posCnt = putPos - getPos
} else {
posCnt = capMod + (putPos - getPos)
}
if posCnt >= capMod-1 {
runtime.Gosched()
return false, posCnt
}
putPosNew = putPos + 1
if !atomic.CompareAndSwapUint32(&q.putPos, putPos, putPosNew) {
runtime.Gosched()
return false, posCnt
}
cache = &q.cache[putPosNew&capMod]
for {
getNo := atomic.LoadUint32(&cache.getNo)
putNo := atomic.LoadUint32(&cache.putNo)
if putPosNew == putNo && getNo == putNo {
cache.value = val
atomic.AddUint32(&cache.putNo, q.capacity)
return true, posCnt + 1
} else {
runtime.Gosched()
}
}
}
// Puts puts queue functions
func (q *EsQueue) Puts(values []interface{}) (puts, quantity uint32) {
var putPos, putPosNew, getPos, posCnt, putCnt uint32
capMod := q.capMod
getPos = atomic.LoadUint32(&q.getPos)
putPos = atomic.LoadUint32(&q.putPos)
if putPos >= getPos {
posCnt = putPos - getPos
} else {
posCnt = capMod + (putPos - getPos)
}
if posCnt >= capMod-1 {
runtime.Gosched()
return 0, posCnt
}
if capPuts, size := q.capacity-posCnt, uint32(len(values)); capPuts >= size {
putCnt = size
} else {
putCnt = capPuts
}
putPosNew = putPos + putCnt
if !atomic.CompareAndSwapUint32(&q.putPos, putPos, putPosNew) {
runtime.Gosched()
return 0, posCnt
}
for posNew, v := putPos+1, uint32(0); v < putCnt; posNew, v = posNew+1, v+1 {
cache := &q.cache[posNew&capMod]
for {
getNo := atomic.LoadUint32(&cache.getNo)
putNo := atomic.LoadUint32(&cache.putNo)
if posNew == putNo && getNo == putNo {
cache.value = values[v]
atomic.AddUint32(&cache.putNo, q.capacity)
break
} else {
runtime.Gosched()
}
}
}
return putCnt, posCnt + putCnt
}
// Get get queue functions
func (q *EsQueue) Get() (val interface{}, ok bool, quantity uint32) {
var putPos, getPos, getPosNew, posCnt uint32
var cache *esCache
capMod := q.capMod
putPos = atomic.LoadUint32(&q.putPos)
getPos = atomic.LoadUint32(&q.getPos)
if putPos >= getPos {
posCnt = putPos - getPos
} else {
posCnt = capMod + (putPos - getPos)
}
if posCnt < 1 {
runtime.Gosched()
return nil, false, posCnt
}
getPosNew = getPos + 1
if !atomic.CompareAndSwapUint32(&q.getPos, getPos, getPosNew) {
runtime.Gosched()
return nil, false, posCnt
}
cache = &q.cache[getPosNew&capMod]
for {
getNo := atomic.LoadUint32(&cache.getNo)
putNo := atomic.LoadUint32(&cache.putNo)
if getPosNew == getNo && getNo == putNo-q.capacity {
val = cache.value
cache.value = nil
atomic.AddUint32(&cache.getNo, q.capacity)
return val, true, posCnt - 1
} else {
runtime.Gosched()
}
}
}
// Gets gets queue functions
func (q *EsQueue) Gets(values []interface{}) (gets, quantity uint32) {
var putPos, getPos, getPosNew, posCnt, getCnt uint32
capMod := q.capMod
putPos = atomic.LoadUint32(&q.putPos)
getPos = atomic.LoadUint32(&q.getPos)
if putPos >= getPos {
posCnt = putPos - getPos
} else {
posCnt = capMod + (putPos - getPos)
}
if posCnt < 1 {
runtime.Gosched()
return 0, posCnt
}
if size := uint32(len(values)); posCnt >= size {
getCnt = size
} else {
getCnt = posCnt
}
getPosNew = getPos + getCnt
if !atomic.CompareAndSwapUint32(&q.getPos, getPos, getPosNew) {
runtime.Gosched()
return 0, posCnt
}
for posNew, v := getPos+1, uint32(0); v < getCnt; posNew, v = posNew+1, v+1 {
var cache *esCache = &q.cache[posNew&capMod]
for {
getNo := atomic.LoadUint32(&cache.getNo)
putNo := atomic.LoadUint32(&cache.putNo)
if posNew == getNo && getNo == putNo-q.capacity {
values[v] = cache.value
cache.value = nil
getNo = atomic.AddUint32(&cache.getNo, q.capacity)
break
} else {
runtime.Gosched()
}
}
}
return getCnt, posCnt - getCnt
}
// round 到最近的2的倍数
func minQuantity(v uint32) uint32 {
v--
v |= v >> 1
v |= v >> 2
v |= v >> 4
v |= v >> 8
v |= v >> 16
v++
return v
}
func Delay(z int) {
for x := z; x > 0; x-- {
}
}
| {
q := new(EsQueue)
q.capacity = minQuantity(capacity)
q.capMod = q.capacity - 1
q.putPos = 0
q.getPos = 0
q.cache = make([]esCache, q.capacity)
for i := range q.cache {
cache := &q.cache[i]
cache.getNo = uint32(i)
cache.putNo = uint32(i)
}
cache := &q.cache[0]
cache.getNo = q.capacity
cache.putNo = q.capacity
return q
} |
writeback.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.
// Type resolution: the phase that finds all the types in the AST with
// unresolved type variables and replaces "ty_var" types with their
// substitutions.
use middle::def;
use middle::pat_util;
use middle::ty;
use middle::ty_fold::{TypeFolder,TypeFoldable};
use middle::typeck::astconv::AstConv;
use middle::typeck::check::FnCtxt;
use middle::typeck::infer::{force_all, resolve_all, resolve_region};
use middle::typeck::infer::resolve_type;
use middle::typeck::infer;
use middle::typeck::{MethodCall, MethodCallee};
use middle::typeck::vtable_res;
use middle::typeck::write_substs_to_tcx;
use middle::typeck::write_ty_to_tcx;
use util::ppaux::Repr;
use std::cell::Cell;
use syntax::ast;
use syntax::codemap::{DUMMY_SP, Span};
use syntax::print::pprust::pat_to_string;
use syntax::visit;
use syntax::visit::Visitor;
///////////////////////////////////////////////////////////////////////////
// Entry point functions
pub fn resolve_type_vars_in_expr(fcx: &FnCtxt, e: &ast::Expr) {
assert_eq!(fcx.writeback_errors.get(), false);
let mut wbcx = WritebackCx::new(fcx);
wbcx.visit_expr(e, ());
wbcx.visit_upvar_borrow_map();
wbcx.visit_unboxed_closures();
}
pub fn resolve_type_vars_in_fn(fcx: &FnCtxt,
decl: &ast::FnDecl,
blk: &ast::Block) {
assert_eq!(fcx.writeback_errors.get(), false);
let mut wbcx = WritebackCx::new(fcx);
wbcx.visit_block(blk, ());
for arg in decl.inputs.iter() {
wbcx.visit_pat(&*arg.pat, ());
// Privacy needs the type for the whole pattern, not just each binding
if !pat_util::pat_is_binding(&fcx.tcx().def_map, &*arg.pat) {
wbcx.visit_node_id(ResolvingPattern(arg.pat.span),
arg.pat.id);
}
}
wbcx.visit_upvar_borrow_map();
wbcx.visit_unboxed_closures();
}
pub fn resolve_impl_res(infcx: &infer::InferCtxt,
span: Span,
vtable_res: &vtable_res)
-> vtable_res {
let errors = Cell::new(false); // nobody cares
let mut resolver = Resolver::from_infcx(infcx,
&errors,
ResolvingImplRes(span));
vtable_res.resolve_in(&mut resolver)
}
///////////////////////////////////////////////////////////////////////////
// The Writerback context. This visitor walks the AST, checking the
// fn-specific tables to find references to types or regions. It
// resolves those regions to remove inference variables and writes the
// final result back into the master tables in the tcx. Here and
// there, it applies a few ad-hoc checks that were not convenient to
// do elsewhere.
struct WritebackCx<'cx> {
fcx: &'cx FnCtxt<'cx>,
}
impl<'cx> WritebackCx<'cx> {
fn new(fcx: &'cx FnCtxt) -> WritebackCx<'cx> {
WritebackCx { fcx: fcx }
}
fn tcx(&self) -> &'cx ty::ctxt {
self.fcx.tcx()
}
}
///////////////////////////////////////////////////////////////////////////
// Impl of Visitor for Resolver
//
// This is the master code which walks the AST. It delegates most of
// the heavy lifting to the generic visit and resolve functions
// below. In general, a function is made into a `visitor` if it must
// traffic in node-ids or update tables in the type context etc.
impl<'cx> Visitor<()> for WritebackCx<'cx> {
fn visit_item(&mut self, _: &ast::Item, _: ()) {
// Ignore items
}
fn visit_stmt(&mut self, s: &ast::Stmt, _: ()) {
if self.fcx.writeback_errors.get() {
return;
}
self.visit_node_id(ResolvingExpr(s.span), ty::stmt_node_id(s));
visit::walk_stmt(self, s, ());
}
fn visit_expr(&mut self, e:&ast::Expr, _: ()) {
if self.fcx.writeback_errors.get() {
return;
}
self.visit_node_id(ResolvingExpr(e.span), e.id);
self.visit_method_map_entry(ResolvingExpr(e.span),
MethodCall::expr(e.id));
self.visit_vtable_map_entry(ResolvingExpr(e.span),
MethodCall::expr(e.id));
match e.node {
ast::ExprFnBlock(_, ref decl, _) |
ast::ExprProc(ref decl, _) |
ast::ExprUnboxedFn(_, _, ref decl, _) => {
for input in decl.inputs.iter() {
let _ = self.visit_node_id(ResolvingExpr(e.span),
input.id);
}
}
_ => {}
}
visit::walk_expr(self, e, ());
}
fn visit_block(&mut self, b: &ast::Block, _: ()) {
if self.fcx.writeback_errors.get() {
return;
}
self.visit_node_id(ResolvingExpr(b.span), b.id);
visit::walk_block(self, b, ());
}
fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
if self.fcx.writeback_errors.get() {
return;
}
self.visit_node_id(ResolvingPattern(p.span), p.id);
debug!("Type for pattern binding {} (id {}) resolved to {}",
pat_to_string(p),
p.id,
ty::node_id_to_type(self.tcx(), p.id).repr(self.tcx()));
visit::walk_pat(self, p, ());
}
fn visit_local(&mut self, l: &ast::Local, _: ()) {
if self.fcx.writeback_errors.get() {
return;
}
let var_ty = self.fcx.local_ty(l.span, l.id);
let var_ty = self.resolve(&var_ty, ResolvingLocal(l.span));
write_ty_to_tcx(self.tcx(), l.id, var_ty);
visit::walk_local(self, l, ());
}
fn visit_ty(&mut self, t: &ast::Ty, _: ()) {
match t.node {
ast::TyFixedLengthVec(ref ty, ref count_expr) => {
self.visit_ty(&**ty, ());
write_ty_to_tcx(self.tcx(), count_expr.id, ty::mk_uint());
}
_ => visit::walk_ty(self, t, ())
}
}
}
impl<'cx> WritebackCx<'cx> {
fn visit_upvar_borrow_map(&self) {
if self.fcx.writeback_errors.get() {
return;
}
for (upvar_id, upvar_borrow) in self.fcx.inh.upvar_borrow_map.borrow().iter() {
let r = upvar_borrow.region;
let r = self.resolve(&r, ResolvingUpvar(*upvar_id));
let new_upvar_borrow = ty::UpvarBorrow { kind: upvar_borrow.kind,
region: r };
debug!("Upvar borrow for {} resolved to {}",
upvar_id.repr(self.tcx()),
new_upvar_borrow.repr(self.tcx()));
self.fcx.tcx().upvar_borrow_map.borrow_mut().insert(
*upvar_id, new_upvar_borrow);
}
}
fn visit_unboxed_closures(&self) {
if self.fcx.writeback_errors.get() {
return
}
for (def_id, unboxed_closure) in self.fcx
.inh
.unboxed_closures
.borrow()
.iter() {
let closure_ty = self.resolve(&unboxed_closure.closure_type,
ResolvingUnboxedClosure(*def_id));
let unboxed_closure = ty::UnboxedClosure {
closure_type: closure_ty,
kind: unboxed_closure.kind,
};
self.fcx
.tcx()
.unboxed_closures
.borrow_mut()
.insert(*def_id, unboxed_closure);
}
}
fn visit_node_id(&self, reason: ResolveReason, id: ast::NodeId) {
// Resolve any borrowings for the node with id `id`
self.visit_adjustments(reason, id);
// Resolve the type of the node with id `id`
let n_ty = self.fcx.node_ty(id);
let n_ty = self.resolve(&n_ty, reason);
write_ty_to_tcx(self.tcx(), id, n_ty);
debug!("Node {} has type {}", id, n_ty.repr(self.tcx()));
// Resolve any substitutions
self.fcx.opt_node_ty_substs(id, |item_substs| {
write_substs_to_tcx(self.tcx(), id,
self.resolve(item_substs, reason));
});
}
fn visit_adjustments(&self, reason: ResolveReason, id: ast::NodeId) {
match self.fcx.inh.adjustments.borrow_mut().pop(&id) {
None => {
debug!("No adjustments for node {}", id);
}
Some(adjustment) => {
let adj_object = ty::adjust_is_object(&adjustment);
let resolved_adjustment = match adjustment {
ty::AutoAddEnv(store) => {
// FIXME(eddyb) #2190 Allow only statically resolved
// bare functions to coerce to a closure to avoid
// constructing (slower) indirect call wrappers.
match self.tcx().def_map.borrow().find(&id) {
Some(&def::DefFn(..)) |
Some(&def::DefStaticMethod(..)) |
Some(&def::DefVariant(..)) |
Some(&def::DefStruct(_)) => {
}
_ => {
span_err!(self.tcx().sess, reason.span(self.tcx()), E0100,
"cannot coerce non-statically resolved bare fn");
}
}
ty::AutoAddEnv(self.resolve(&store, reason))
}
ty::AutoDerefRef(adj) => {
for autoderef in range(0, adj.autoderefs) {
let method_call = MethodCall::autoderef(id, autoderef);
self.visit_method_map_entry(reason, method_call);
self.visit_vtable_map_entry(reason, method_call);
}
if adj_object {
let method_call = MethodCall::autoobject(id);
self.visit_method_map_entry(reason, method_call);
self.visit_vtable_map_entry(reason, method_call);
}
ty::AutoDerefRef(ty::AutoDerefRef {
autoderefs: adj.autoderefs,
autoref: self.resolve(&adj.autoref, reason),
})
}
};
debug!("Adjustments for node {}: {:?}", id, resolved_adjustment);
self.tcx().adjustments.borrow_mut().insert(
id, resolved_adjustment);
}
}
}
fn visit_method_map_entry(&self,
reason: ResolveReason,
method_call: MethodCall) {
// Resolve any method map entry
match self.fcx.inh.method_map.borrow_mut().pop(&method_call) {
Some(method) => {
debug!("writeback::resolve_method_map_entry(call={:?}, entry={})",
method_call,
method.repr(self.tcx()));
let new_method = MethodCallee {
origin: method.origin,
ty: self.resolve(&method.ty, reason),
substs: self.resolve(&method.substs, reason),
};
self.tcx().method_map.borrow_mut().insert(
method_call,
new_method);
}
None => {}
}
}
fn visit_vtable_map_entry(&self,
reason: ResolveReason,
vtable_key: MethodCall) {
// Resolve any vtable map entry
match self.fcx.inh.vtable_map.borrow_mut().pop(&vtable_key) {
Some(origins) => {
let r_origins = self.resolve(&origins, reason);
debug!("writeback::resolve_vtable_map_entry(\
vtable_key={}, vtables={:?})",
vtable_key, r_origins.repr(self.tcx()));
self.tcx().vtable_map.borrow_mut().insert(vtable_key, r_origins);
}
None => {}
}
}
fn resolve<T:ResolveIn>(&self, t: &T, reason: ResolveReason) -> T {
t.resolve_in(&mut Resolver::new(self.fcx, reason))
}
}
///////////////////////////////////////////////////////////////////////////
// Resolution reason.
enum ResolveReason {
ResolvingExpr(Span),
ResolvingLocal(Span),
ResolvingPattern(Span),
ResolvingUpvar(ty::UpvarId),
ResolvingImplRes(Span),
ResolvingUnboxedClosure(ast::DefId),
}
impl ResolveReason {
fn span(&self, tcx: &ty::ctxt) -> Span {
match *self {
ResolvingExpr(s) => s,
ResolvingLocal(s) => s,
ResolvingPattern(s) => s,
ResolvingUpvar(upvar_id) => {
ty::expr_span(tcx, upvar_id.closure_expr_id)
}
ResolvingImplRes(s) => s,
ResolvingUnboxedClosure(did) => {
if did.krate == ast::LOCAL_CRATE {
ty::expr_span(tcx, did.node)
} else {
DUMMY_SP
}
}
}
}
}
///////////////////////////////////////////////////////////////////////////
// Convenience methods for resolving different kinds of things.
trait ResolveIn {
fn resolve_in(&self, resolver: &mut Resolver) -> Self;
}
impl<T:TypeFoldable> ResolveIn for T {
fn resolve_in(&self, resolver: &mut Resolver) -> T {
self.fold_with(resolver)
}
}
///////////////////////////////////////////////////////////////////////////
// The Resolver. This is the type folding engine that detects
// unresolved types and so forth.
struct Resolver<'cx> {
tcx: &'cx ty::ctxt,
infcx: &'cx infer::InferCtxt<'cx>,
writeback_errors: &'cx Cell<bool>,
reason: ResolveReason,
}
impl<'cx> Resolver<'cx> {
fn new(fcx: &'cx FnCtxt<'cx>,
reason: ResolveReason)
-> Resolver<'cx>
{
Resolver { infcx: fcx.infcx(),
tcx: fcx.tcx(),
writeback_errors: &fcx.writeback_errors,
reason: reason }
}
fn from_infcx(infcx: &'cx infer::InferCtxt<'cx>,
writeback_errors: &'cx Cell<bool>,
reason: ResolveReason)
-> Resolver<'cx>
{
Resolver { infcx: infcx,
tcx: infcx.tcx,
writeback_errors: writeback_errors,
reason: reason }
}
fn | (&self, e: infer::fixup_err) {
self.writeback_errors.set(true);
if !self.tcx.sess.has_errors() {
match self.reason {
ResolvingExpr(span) => {
span_err!(self.tcx.sess, span, E0101,
"cannot determine a type for this expression: {}",
infer::fixup_err_to_string(e));
}
ResolvingLocal(span) => {
span_err!(self.tcx.sess, span, E0102,
"cannot determine a type for this local variable: {}",
infer::fixup_err_to_string(e));
}
ResolvingPattern(span) => {
span_err!(self.tcx.sess, span, E0103,
"cannot determine a type for this pattern binding: {}",
infer::fixup_err_to_string(e));
}
ResolvingUpvar(upvar_id) => {
let span = self.reason.span(self.tcx);
span_err!(self.tcx.sess, span, E0104,
"cannot resolve lifetime for captured variable `{}`: {}",
ty::local_var_name_str(self.tcx, upvar_id.var_id).get().to_string(),
infer::fixup_err_to_string(e));
}
ResolvingImplRes(span) => {
span_err!(self.tcx.sess, span, E0105,
"cannot determine a type for impl supertrait");
}
ResolvingUnboxedClosure(_) => {
let span = self.reason.span(self.tcx);
self.tcx.sess.span_err(span,
"cannot determine a type for this \
unboxed closure")
}
}
}
}
}
impl<'cx> TypeFolder for Resolver<'cx> {
fn tcx<'a>(&'a self) -> &'a ty::ctxt {
self.tcx
}
fn fold_ty(&mut self, t: ty::t) -> ty::t {
if !ty::type_needs_infer(t) {
return t;
}
match resolve_type(self.infcx, None, t, resolve_all | force_all) {
Ok(t) => t,
Err(e) => {
self.report_error(e);
ty::mk_err()
}
}
}
fn fold_region(&mut self, r: ty::Region) -> ty::Region {
match resolve_region(self.infcx, r, resolve_all | force_all) {
Ok(r) => r,
Err(e) => {
self.report_error(e);
ty::ReStatic
}
}
}
}
| report_error |
gatsby-node.js | /**
* Implement Gatsby's Node APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/node-apis/
*/
exports.onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
module: {
rules: [
{
test: /\.(graphql|gql)$/,
exclude: /node_modules/,
loader: "graphql-tag/loader",
},
],
},
}) | } |
|
40.js | (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[40],{
/***/ "./node_modules/@ionic/core/dist/esm/es5/build/chunk-6d7d2f8c.js":
/*!***********************************************************************!*\
!*** ./node_modules/@ionic/core/dist/esm/es5/build/chunk-6d7d2f8c.js ***!
\***********************************************************************/
/*! exports provided: a, b, c, d, e, f, g, h, i, j, k */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return rIC; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return now; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return hasShadowDom; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return findItemLabel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return renderHiddenInput; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return debounceEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return isEndSide; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return assert; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return clamp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return debounce; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return pointerCoord; });
function rIC(e){"requestIdleCallback"in window?window.requestIdleCallback(e):setTimeout(e,32)}function hasShadowDom(e){return!!e.shadowRoot&&!!e.attachShadow}function findItemLabel(e){var n=e.closest("ion-item");return n?n.querySelector("ion-label"):null}function renderHiddenInput(e,n,t,a,r){if(e||hasShadowDom(n)){var o=n.querySelector("input.aux-input");o||((o=n.ownerDocument.createElement("input")).type="hidden",o.classList.add("aux-input"),n.appendChild(o)),o.disabled=r,o.name=t,o.value=a||""}}function clamp(e,n,t){return Math.max(e,Math.min(n,t))}function assert(e,n){if(!e){var t="ASSERT: "+n;throw console.error(t),new Error(t)}}function now(e){return e.timeStamp||Date.now()}function pointerCoord(e){if(e){var n=e.changedTouches;if(n&&n.length>0){var t=n[0];return{x:t.clientX,y:t.clientY}}if(void 0!==e.pageX)return{x:e.pageX,y:e.pageY}}return{x:0,y:0}}function isEndSide(e,n){var t="rtl"===e.document.dir;switch(n){case"start":return t;case"end":return!t;default:throw new Error('"'+n+'" is not a valid value for [side]. Use "start" or "end" instead.')}}function debounceEvent(e,n){var t=e._original||e;return{_original:e,emit:debounce(t.emit.bind(t),n)}}function debounce(e,n){var t;return void 0===n&&(n=0),function(){for(var a=[],r=0;r<arguments.length;r++)a[r]=arguments[r];clearTimeout(t),t=setTimeout.apply(void 0,[e,n].concat(a))}}
/***/ }),
/***/ "./node_modules/@ionic/core/dist/esm/es5/build/chunk-7c632336.js":
/*!***********************************************************************!*\
!*** ./node_modules/@ionic/core/dist/esm/es5/build/chunk-7c632336.js ***!
\***********************************************************************/
/*! exports provided: a, b, c, d, e */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return getClassMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return openURL; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return createColorClasses; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return hostContext; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return createThemedClasses; });
/* harmony import */ var _polyfills_tslib_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../polyfills/tslib.js */ "./node_modules/@ionic/core/dist/esm/es5/polyfills/tslib.js");
function hostContext(t,e){return null!==e.closest(t)}function createColorClasses(t){var e;return"string"==typeof t&&t.length>0?((e={"ion-color":!0})["ion-color-"+t]=!0,e):void 0}function createThemedClasses(t,e){var r;return(r={})[e]=!0,r[e+"-"+t]=void 0!==t,r}function getClassList(t){return void 0!==t?(Array.isArray(t)?t:t.split(" ")).filter(function(t){return null!=t}).map(function(t){return t.trim()}).filter(function(t){return""!==t}):[]}function getClassMap(t){var e={};return getClassList(t).forEach(function(t){return e[t]=!0}),e}var SCHEME=/^[a-z][a-z0-9+\-.]*:/;function openURL(t,e,r,n){return _polyfills_tslib_js__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this,void 0,void 0,function(){var s;return _polyfills_tslib_js__WEBPACK_IMPORTED_MODULE_0__["__generator"](this,function(o){switch(o.label){case 0:return null==e||"#"===e[0]||SCHEME.test(e)?[3,2]:(s=t.document.querySelector("ion-router"))?(null!=r&&r.preventDefault(),[4,s.componentOnReady()]):[3,2];case 1:return o.sent(),[2,s.push(e,n)];case 2:return[2,!1]}})})}
/***/ }),
/***/ "./node_modules/@ionic/core/dist/esm/es5/build/odqmlmdd.entry.js":
/*!***********************************************************************!*\
!*** ./node_modules/@ionic/core/dist/esm/es5/build/odqmlmdd.entry.js ***!
\***********************************************************************/
/*! exports provided: IonTextarea */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IonTextarea", function() { return Textarea; });
/* harmony import */ var _ionic_core_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../ionic.core.js */ "./node_modules/@ionic/core/dist/esm/es5/ionic.core.js");
/* harmony import */ var _chunk_7c632336_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./chunk-7c632336.js */ "./node_modules/@ionic/core/dist/esm/es5/build/chunk-7c632336.js");
/* harmony import */ var _chunk_6d7d2f8c_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./chunk-6d7d2f8c.js */ "./node_modules/@ionic/core/dist/esm/es5/build/chunk-6d7d2f8c.js");
var Textarea=function(){function | (){var e=this;this.inputId="ion-input-"+textareaIds++,this.didBlurAfterEdit=!1,this.hasFocus=!1,this.autocapitalize="none",this.autofocus=!1,this.clearOnEdit=!1,this.debounce=0,this.disabled=!1,this.name=this.inputId,this.readonly=!1,this.required=!1,this.spellcheck=!1,this.value="",this.onInput=function(t){e.nativeInput&&(e.value=e.nativeInput.value),e.emitStyle(),e.ionInput.emit(t)},this.onFocus=function(){e.hasFocus=!0,e.focusChange(),e.ionFocus.emit()},this.onBlur=function(){e.hasFocus=!1,e.focusChange(),e.ionBlur.emit()},this.onKeyDown=function(){e.checkClearOnEdit()}}return e.prototype.debounceChanged=function(){this.ionChange=Object(_chunk_6d7d2f8c_js__WEBPACK_IMPORTED_MODULE_2__["f"])(this.ionChange,this.debounce)},e.prototype.disabledChanged=function(){this.emitStyle()},e.prototype.valueChanged=function(){var e=this.nativeInput,t=this.getValue();e&&e.value!==t&&(e.value=t),this.ionChange.emit({value:t})},e.prototype.componentWillLoad=function(){this.emitStyle()},e.prototype.componentDidLoad=function(){this.debounceChanged()},e.prototype.setFocus=function(){this.nativeInput&&this.nativeInput.focus()},e.prototype.getInputElement=function(){return Promise.resolve(this.nativeInput)},e.prototype.emitStyle=function(){this.ionStyle.emit({interactive:!0,textarea:!0,input:!0,"interactive-disabled":this.disabled,"has-placeholder":null!=this.placeholder,"has-value":this.hasValue(),"has-focus":this.hasFocus})},e.prototype.checkClearOnEdit=function(){this.clearOnEdit&&(this.didBlurAfterEdit&&this.hasValue()&&(this.value=""),this.didBlurAfterEdit=!1)},e.prototype.focusChange=function(){this.clearOnEdit&&!this.hasFocus&&this.hasValue()&&(this.didBlurAfterEdit=!0),this.emitStyle()},e.prototype.hasValue=function(){return""!==this.getValue()},e.prototype.getValue=function(){return this.value||""},e.prototype.hostData=function(){return{"aria-disabled":this.disabled?"true":null,class:Object(_chunk_7c632336_js__WEBPACK_IMPORTED_MODULE_1__["c"])(this.color)}},e.prototype.render=function(){var e=this,t=this.getValue(),n=this.inputId+"-lbl",a=Object(_chunk_6d7d2f8c_js__WEBPACK_IMPORTED_MODULE_2__["d"])(this.el);return a&&(a.id=n),Object(_ionic_core_js__WEBPACK_IMPORTED_MODULE_0__["h"])("textarea",{class:"native-textarea",ref:function(t){return e.nativeInput=t},autoCapitalize:this.autocapitalize,autoFocus:this.autofocus,disabled:this.disabled,maxLength:this.maxlength,minLength:this.minlength,name:this.name,placeholder:this.placeholder||"",readOnly:this.readonly,required:this.required,spellCheck:this.spellcheck,cols:this.cols,rows:this.rows,wrap:this.wrap,onInput:this.onInput,onBlur:this.onBlur,onFocus:this.onFocus,onKeyDown:this.onKeyDown},t)},Object.defineProperty(e,"is",{get:function(){return"ion-textarea"},enumerable:!0,configurable:!0}),Object.defineProperty(e,"encapsulation",{get:function(){return"scoped"},enumerable:!0,configurable:!0}),Object.defineProperty(e,"properties",{get:function(){return{autocapitalize:{type:String,attr:"autocapitalize"},autofocus:{type:Boolean,attr:"autofocus"},clearOnEdit:{type:Boolean,attr:"clear-on-edit",mutable:!0},color:{type:String,attr:"color"},cols:{type:Number,attr:"cols"},debounce:{type:Number,attr:"debounce",watchCallbacks:["debounceChanged"]},disabled:{type:Boolean,attr:"disabled",watchCallbacks:["disabledChanged"]},el:{elementRef:!0},getInputElement:{method:!0},hasFocus:{state:!0},maxlength:{type:Number,attr:"maxlength"},minlength:{type:Number,attr:"minlength"},mode:{type:String,attr:"mode"},name:{type:String,attr:"name"},placeholder:{type:String,attr:"placeholder"},readonly:{type:Boolean,attr:"readonly"},required:{type:Boolean,attr:"required"},rows:{type:Number,attr:"rows"},setFocus:{method:!0},spellcheck:{type:Boolean,attr:"spellcheck"},value:{type:String,attr:"value",mutable:!0,watchCallbacks:["valueChanged"]},wrap:{type:String,attr:"wrap"}}},enumerable:!0,configurable:!0}),Object.defineProperty(e,"events",{get:function(){return[{name:"ionChange",method:"ionChange",bubbles:!0,cancelable:!0,composed:!0},{name:"ionInput",method:"ionInput",bubbles:!0,cancelable:!0,composed:!0},{name:"ionStyle",method:"ionStyle",bubbles:!0,cancelable:!0,composed:!0},{name:"ionBlur",method:"ionBlur",bubbles:!0,cancelable:!0,composed:!0},{name:"ionFocus",method:"ionFocus",bubbles:!0,cancelable:!0,composed:!0}]},enumerable:!0,configurable:!0}),Object.defineProperty(e,"style",{get:function(){return".sc-ion-textarea-md-h{--background:initial;--color:initial;--placeholder-color:initial;--placeholder-font-style:initial;--placeholder-font-weight:initial;--placeholder-opacity:.5;--padding-top:0;--padding-bottom:0;--padding-start:0;--border-radius:0;display:block;position:relative;-ms-flex:1;flex:1;width:100%;-webkit-box-sizing:border-box;box-sizing:border-box;background:var(--background);color:var(--color);font-family:var(--ion-font-family,inherit);z-index:2}.ion-color.sc-ion-textarea-md-h{background:initial;color:var(--ion-color-base)}ion-item.sc-ion-textarea-md-h, ion-item .sc-ion-textarea-md-h{position:static}ion-item.sc-ion-textarea-md-h:not(.item-label), ion-item:not(.item-label) .sc-ion-textarea-md-h{--padding-start:0}.native-textarea.sc-ion-textarea-md{font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;letter-spacing:inherit;text-decoration:inherit;text-overflow:inherit;text-transform:inherit;text-align:inherit;white-space:inherit;color:inherit;border-radius:var(--border-radius);margin-left:0;margin-right:0;margin-top:0;margin-bottom:0;padding-left:var(--padding-start);padding-right:var(--padding-end);padding-top:var(--padding-top);padding-bottom:var(--padding-bottom);display:block;width:100%;height:100%;border:0;outline:none;background:transparent;-webkit-box-sizing:border-box;box-sizing:border-box;resize:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;white-space:pre-wrap}\@supports ((-webkit-margin-start:0) or (margin-inline-start:0)) or (-webkit-margin-start:0){.native-textarea.sc-ion-textarea-md{padding-left:unset;padding-right:unset;-webkit-padding-start:var(--padding-start);padding-inline-start:var(--padding-start);-webkit-padding-end:var(--padding-end);padding-inline-end:var(--padding-end)}}.native-textarea.sc-ion-textarea-md::-webkit-input-placeholder{color:var(--placeholder-color);font-family:inherit;font-style:var(--placeholder-font-style);font-weight:var(--placeholder-font-weight);opacity:var(--placeholder-opacity)}.native-textarea.sc-ion-textarea-md:-ms-input-placeholder{color:var(--placeholder-color);font-family:inherit;font-style:var(--placeholder-font-style);font-weight:var(--placeholder-font-weight);opacity:var(--placeholder-opacity)}.native-textarea.sc-ion-textarea-md::-ms-input-placeholder{color:var(--placeholder-color);font-family:inherit;font-style:var(--placeholder-font-style);font-weight:var(--placeholder-font-weight);opacity:var(--placeholder-opacity)}.native-textarea.sc-ion-textarea-md::placeholder{color:var(--placeholder-color);font-family:inherit;font-style:var(--placeholder-font-style);font-weight:var(--placeholder-font-weight);opacity:var(--placeholder-opacity)}.native-textarea[disabled].sc-ion-textarea-md{opacity:.4}.sc-ion-textarea-md-h{--padding-top:10px;--padding-end:0;--padding-bottom:11px;--padding-start:8px;font-size:inherit}.item-label-floating.sc-ion-textarea-md-h, .item-label-floating .sc-ion-textarea-md-h, .item-label-stacked.sc-ion-textarea-md-h, .item-label-stacked .sc-ion-textarea-md-h{--padding-top:8px;--padding-bottom:8px;--padding-start:0}"},enumerable:!0,configurable:!0}),Object.defineProperty(e,"styleMode",{get:function(){return"md"},enumerable:!0,configurable:!0}),e}(),textareaIds=0;
/***/ }),
/***/ "./node_modules/@ionic/core/dist/esm/es5/polyfills/tslib.js":
/*!******************************************************************!*\
!*** ./node_modules/@ionic/core/dist/esm/es5/polyfills/tslib.js ***!
\******************************************************************/
/*! exports provided: __extends, __assign, __rest, __decorate, __param, __metadata, __awaiter, __generator, __exportStar, __values, __read, __spread, __await, __makeTemplateObject, __importStar, __importDefault */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__extends", function() { return __extends; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__assign", function() { return __assign; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__rest", function() { return __rest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__decorate", function() { return __decorate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__param", function() { return __param; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__metadata", function() { return __metadata; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__awaiter", function() { return __awaiter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__generator", function() { return __generator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__exportStar", function() { return __exportStar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__values", function() { return __values; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__read", function() { return __read; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spread", function() { return __spread; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__await", function() { return __await; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__makeTemplateObject", function() { return __makeTemplateObject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importStar", function() { return __importStar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importDefault", function() { return __importDefault; });
// REV: 9dd9aa322c893e5e0b3f1609b1126314ccf37bbb
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
}
return __assign.apply(this, arguments);
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
t[p[i]] = s[p[i]];
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __exportStar(m, exports) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
function __values(o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result.default = mod;
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
/***/ })
}]);
//# sourceMappingURL=40.js.map | e |
stringRange1.js | /**
* A collection of useful functions.
*
* @author Mitt Namn
*/
"use strict";
module.exports = {
//"moped": stringRange,
"stringRange": stringRange,
// "function2": anotherFunction
};
/**
* Return the range between a and b as a string, separated by commas.
*
* @param {integer} a Start value.
* @param {integer} b Last included value.
* @param {string} sep Separator, defaults to ", ".
*
* @returns {string} A comma separated list of values.
*/
function stringRange(a, b, sep = ", ") {
let res = "";
let i = a;
while (i < b) {
res += i + sep;
i++;
} | res = res.substring(0, res.length - sep.length);
return res;
}
// console.log(stringRange(1, 10));
// console.log(stringRange(1, 10, "-")); | |
process.go | // Package process implements generic subprocess management functions.
package process
import (
"bytes"
"context"
"fmt"
"io"
"os"
"os/exec"
"sync"
"syscall"
"time"
"github.com/thought-machine/please/src/cli"
"github.com/thought-machine/please/src/cli/logging"
)
var log = logging.Log
type NamespacingPolicy string
const (
NamespaceAlways NamespacingPolicy = "always"
NamespaceNever NamespacingPolicy = "never"
NamespaceSandbox NamespacingPolicy = "sandbox"
)
// An Executor handles starting, running and monitoring a set of subprocesses.
// It registers as a signal handler to attempt to terminate them all at process exit.
type Executor struct {
// Whether we should set up linux namespaces at all
namespace NamespacingPolicy
// The tool that will do the network/mount sandboxing
sandboxTool string
usePleaseSandbox bool
processes map[*exec.Cmd]<-chan error
mutex sync.Mutex
}
func NewSandboxingExecutor(usePleaseSandbox bool, namespace NamespacingPolicy, sandboxTool string) *Executor {
o := &Executor{
namespace: namespace,
usePleaseSandbox: usePleaseSandbox,
sandboxTool: sandboxTool,
processes: map[*exec.Cmd]<-chan error{},
}
cli.AtExit(o.killAll) // Kill any subprocess if we are ourselves killed
return o
}
// New returns a new Executor.
func New() *Executor {
return NewSandboxingExecutor(false, NamespaceNever, "")
}
// SandboxConfig contains what namespaces should be sandboxed
type SandboxConfig struct {
Network, Mount, Fakeroot bool
}
// NoSandbox represents a no-sandbox value
var NoSandbox = SandboxConfig{}
// NewSandboxConfig creates a new SandboxConfig
func NewSandboxConfig(network, mount bool) SandboxConfig {
return SandboxConfig{Network: network, Mount: mount}
}
// A Target is a minimal interface of what we need from a BuildTarget.
// It's here to avoid a hard dependency on the core package.
type Target interface {
// String returns a string representation of this target.
String() string
// ShouldShowProgress returns true if the target should display progress.
ShouldShowProgress() bool
// SetProgress sets the current progress of the target.
SetProgress(float32)
// ProgressDescription returns a description of what the target is doing as it runs.
ProgressDescription() string
// ShouldExitOnError returns true if the executed process should exit if an error occurs.
ShouldExitOnError() bool
}
// ExecWithTimeout runs an external command with a timeout.
// If the command times out the returned error will be a context.DeadlineExceeded error.
// If showOutput is true then output will be printed to stderr as well as returned.
// It returns the stdout only, combined stdout and stderr and any error that occurred.
func (e *Executor) ExecWithTimeout(ctx context.Context, target Target, dir string, env []string, timeout time.Duration, showOutput, attachStdin, attachStdout, foreground bool, sandbox SandboxConfig, argv []string) ([]byte, []byte, error) {
// We deliberately don't attach this context to the command, so we have better
// control over how the process gets terminated.
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
cmd := e.ExecCommand(sandbox, foreground, argv[0], argv[1:]...)
cmd.Dir = dir
cmd.Env = append(cmd.Env, env...)
var out bytes.Buffer
var outerr safeBuffer
var progress *float32
if showOutput {
cmd.Stdout = io.MultiWriter(os.Stderr, &out, &outerr)
cmd.Stderr = io.MultiWriter(os.Stderr, &outerr)
} else {
cmd.Stdout = io.MultiWriter(&out, &outerr)
cmd.Stderr = &outerr
}
if target != nil && target.ShouldShowProgress() {
progress = new(float32)
cmd.Stdout = newProgressWriter(target, progress, cmd.Stdout)
cmd.Stderr = newProgressWriter(target, progress, cmd.Stderr)
}
if attachStdin {
cmd.Stdin = os.Stdin
}
if attachStdout {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
}
if target != nil {
go logProgress(ctx, target, progress)
}
// Start the command, wait for the timeout & then kill it.
// We deliberately don't use CommandContext because it will only send SIGKILL which
// child processes can't handle themselves.
err := cmd.Start()
if err != nil {
return nil, nil, err
}
ch := make(chan error)
e.registerProcess(cmd, ch)
defer e.removeProcess(cmd)
go runCommand(cmd, ch)
select {
case err = <-ch:
// Do nothing.
case <-ctx.Done():
err = ctx.Err()
e.KillProcess(cmd)
}
return out.Bytes(), outerr.Bytes(), err
}
// runCommand runs a command and signals on the given channel when it's done.
func runCommand(cmd *exec.Cmd, ch chan<- error) {
ch <- cmd.Wait()
}
// ExecWithTimeoutShell runs an external command within a Bash shell.
// Other arguments are as ExecWithTimeout.
// Note that the command is deliberately a single string.
func (e *Executor) ExecWithTimeoutShell(target Target, dir string, env []string, timeout time.Duration, showOutput, foreground bool, sandbox SandboxConfig, cmd string) ([]byte, []byte, error) {
return e.ExecWithTimeoutShellStdStreams(target, dir, env, timeout, showOutput, foreground, sandbox, cmd, false)
}
// ExecWithTimeoutShellStdStreams is as ExecWithTimeoutShell but optionally attaches stdin to the subprocess.
func (e *Executor) ExecWithTimeoutShellStdStreams(target Target, dir string, env []string, timeout time.Duration, showOutput, foreground bool, sandbox SandboxConfig, cmd string, attachStdStreams bool) ([]byte, []byte, error) {
c := BashCommand("bash", cmd, target.ShouldExitOnError())
return e.ExecWithTimeout(context.Background(), target, dir, env, timeout, showOutput, attachStdStreams, attachStdStreams, foreground, sandbox, c)
}
// KillProcess kills a process, attempting to send it a SIGTERM first followed by a SIGKILL
// shortly after if it hasn't exited.
func (e *Executor) KillProcess(cmd *exec.Cmd) {
e.killProcess(cmd, e.processChan(cmd))
}
func (e *Executor) killProcess(cmd *exec.Cmd, ch <-chan error) {
success := sendSignal(cmd, ch, syscall.SIGTERM, 30*time.Millisecond)
if !sendSignal(cmd, ch, syscall.SIGKILL, time.Second) && !success {
log.Error("Failed to kill inferior process")
}
e.removeProcess(cmd)
}
func (e *Executor) removeProcess(cmd *exec.Cmd) {
e.mutex.Lock()
defer e.mutex.Unlock()
delete(e.processes, cmd)
}
// registerProcess stores the given process in this executor's map.
func (e *Executor) registerProcess(cmd *exec.Cmd, ch <-chan error) {
e.mutex.Lock()
defer e.mutex.Unlock()
e.processes[cmd] = ch
}
// processChan returns the error channel for a process.
func (e *Executor) processChan(cmd *exec.Cmd) <-chan error {
e.mutex.Lock()
defer e.mutex.Unlock()
return e.processes[cmd]
}
// sendSignal sends a single signal to the process in an attempt to stop it.
// It returns true if the process exited within the timeout.
func sendSignal(cmd *exec.Cmd, ch <-chan error, sig syscall.Signal, timeout time.Duration) bool {
if cmd.Process == nil {
log.Debug("Not terminating process, it seems to have not started yet")
return false
}
// This is a bit of a fiddle. We want to wait for the process to exit but only for just so
// long (we do not want to get hung up if it ignores our SIGTERM).
log.Debug("Sending signal %s to -%d", sig, cmd.Process.Pid)
syscall.Kill(-cmd.Process.Pid, sig) // Kill the group - we always set one in ExecCommand.
select {
case <-ch:
return true
case <-time.After(timeout):
return false
}
}
// LogProgress logs a message once a minute until the given context has expired.
// Used to provide some notion of progress while waiting for external commands.
func (e *Executor) LogProgress(ctx context.Context, target Target) {
logProgress(ctx, target, nil)
}
func logProgress(ctx context.Context, target Target, progress *float32) {
name := target.String()
msg := target.ProgressDescription()
t := time.NewTicker(1 * time.Minute)
defer t.Stop()
for i := 1; i < 1000000; i++ {
select {
case <-ctx.Done():
return
case <-t.C:
if i == 1 {
log.Notice("%s still %s after 1 minute %s", name, msg, progressMessage(progress))
} else {
log.Notice("%s still %s after %d minutes %s", name, msg, i, progressMessage(progress))
}
}
}
}
// safeBuffer is an io.Writer that ensures that only one thread writes to it at a time.
// This is important because we potentially have both stdout and stderr writing to the same
// buffer, and os.exec only guarantees goroutine-safety if both are the same writer, which in
// our case they're not (but are both ultimately causing writes to the same buffer)
type safeBuffer struct {
sync.Mutex
buf bytes.Buffer
}
func (sb *safeBuffer) Write(b []byte) (int, error) {
sb.Lock()
defer sb.Unlock()
return sb.buf.Write(b)
}
func (sb *safeBuffer) Bytes() []byte {
return sb.buf.Bytes()
}
func (sb *safeBuffer) String() string {
return sb.buf.String()
}
// progressMessage displays a progress message, if it is being tracked.
func progressMessage(progress *float32) string {
if progress != nil {
return fmt.Sprintf("(%0.1f%% done)", *progress)
}
return "" | e.mutex.Lock()
var wg sync.WaitGroup
wg.Add(len(e.processes))
defer wg.Wait()
defer e.mutex.Unlock()
for proc, ch := range e.processes {
go func(proc *exec.Cmd, ch <-chan error) {
e.killProcess(proc, ch)
wg.Done()
}(proc, ch)
}
}
// ExecCommand is a utility function that runs the given command with few options.
func ExecCommand(args ...string) ([]byte, error) {
e := New()
cmd := e.ExecCommand(NoSandbox, false, args[0], args[1:]...)
return cmd.CombinedOutput()
}
// BashCommand returns the command that we'd use to execute a subprocess in a shell with.
func BashCommand(binary, command string, exitOnError bool) []string {
if exitOnError {
return []string{binary, "--noprofile", "--norc", "-e", "-u", "-o", "pipefail", "-c", command}
}
return []string{binary, "--noprofile", "--norc", "-u", "-o", "pipefail", "-c", command}
} | }
// killAll kills all subprocesses of this executor.
func (e *Executor) killAll() { |
shift.go | package transform
import (
"encoding/json"
"fmt"
"strconv"
"strings"
)
// Shift moves values from one provided json path to another in raw []byte.
func Shift(spec *Config, data []byte) ([]byte, error) {
var outData []byte
if spec.InPlace {
outData = data
} else {
outData = []byte(`{}`)
}
for k, v := range *spec.Spec {
array := true
var keyList []string
// check if `v` is a string or list and build a list of keys to evaluate
switch v.(type) {
case string:
keyList = append(keyList, v.(string))
array = false
case []interface{}:
for _, vItem := range v.([]interface{}) {
vItemStr, found := vItem.(string)
if !found {
return nil, ParseError(fmt.Sprintf("Warn: Unable to coerce element to json string: %v", vItem))
}
keyList = append(keyList, vItemStr)
}
default:
return nil, ParseError(fmt.Sprintf("Warn: Unknown type in message for key: %s", k))
}
// iterate over keys to evaluate
// Note: this could be sped up significantly (especially for large shift transforms)
// by using `jsonparser.EachKey()` to iterate through data once and pick up all the
// needed underlying data. It would be a non-trivial update since you'd have to make
// recursive calls and keep track of all the key paths at each level.
// Currently we iterate at worst once per key in spec, with a better design it would be once
// per spec.
for _, v := range keyList {
//Special case, N:N array copy, can't be handled by normal value insertion, we need to create a lot of manual insertions like [0]:[0] [1]:[1],...
if strings.Contains(v, "[*]") && strings.Count(v, "[*]") == strings.Count(k, "[*]") {
//now in recursive way we use the length for each N to replace it and do copy
outData, _ = insertArrayDataRecursively("", strings.Split(v, "."), 0, v, k, data, spec, array, outData)
} else {
outData, _ = insertShiftData(v, k, data, spec, array, outData)
}
}
}
return outData, nil
}
func insertArrayDataRecursively(lookPath string, replacementArray []string, level int, v, k string, data []byte, spec *Config, array bool, outData []byte) ([]byte, error) {
var err error
originalK := k
originalV := v
if level != 0 {
lookPath += "."
}
lookPath += replacementArray[level]
var tempArray []interface{}
rawTempJson, err := getJSONRaw(data, lookPath, false)
if err != nil {
return nil, err
}
json.Unmarshal(rawTempJson, &tempArray)
totalToIterate := len(tempArray)
if totalToIterate == 0 && level < (len(replacementArray)-1) {
//goto next level directly
outData, _ = insertArrayDataRecursively(lookPath, replacementArray, level+1, v, k, data, spec, array, outData)
}
for i := 0; i < totalToIterate; i++ {
k = strings.Replace(originalK, "[*]", "["+strconv.Itoa(i)+"]", 1)
v = strings.Replace(originalV, "[*]", "["+strconv.Itoa(i)+"]", 1)
if level == (len(replacementArray)-1) || !strings.Contains(v, "[*]") {
outData, err = insertShiftData(v, k, data, spec, array, outData)
} else {
nextLevelLookPath := strings.Replace(lookPath, "[*]", "["+strconv.Itoa(i)+"]", 1)
outData, err = insertArrayDataRecursively(nextLevelLookPath, replacementArray, level+1, v, k, data, spec, array, outData)
}
}
return outData, err
}
func | (v, k string, data []byte, spec *Config, array bool, outData []byte) ([]byte, error) {
var dataForV []byte
var err error
// grab the data
if v == "$" {
dataForV = data
} else {
dataForV, err = getJSONRaw(data, v, spec.Require)
if err != nil {
return nil, err
}
}
// if array flag set, encapsulate data
if array {
// bookend() is destructive to underlying slice, need to copy.
// extra capacity saves an allocation and copy during bookend.
tmp := make([]byte, len(dataForV), len(dataForV)+2)
copy(tmp, dataForV)
dataForV = bookend(tmp, '[', ']')
}
// Note: following pattern from current Shift() - if multiple elements are included in an array,
// they will each successively overwrite each other and only the last element will be included
// in the transformed data.
outData, err = setJSONRaw(outData, dataForV, k)
if err != nil {
return nil, err
}
return outData, nil
}
| insertShiftData |
ed25519.go | /*
Copyright ArxanFintech Technology Ltd. 2017 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ed25519
import (
"crypto/rand"
"fmt"
logging "github.com/op/go-logging"
edAlg "golang.org/x/crypto/ed25519"
)
const (
// KeyType_PubRSA public key of rsa
KeyType_PubRSA = "RsaPublicKey"
// KeyType_PriRSA private key of rsa
KeyType_PriRSA = "RsaPrivateKey"
// KeyType_PubED25119 public key of ed25519
KeyType_PubED25119 = "EdDsaPublicKey"
// KeyType_PriED25119 private key of ed25519
KeyType_PriED25119 = "EdDsaPrivateKey"
)
const (
// Usage_EncDec used for encrypt and decrypt
Usage_EncDec = "EncryptDecrypt"
// Usage_SignVerify used for signature and verify
Usage_SignVerify = "SignVerify"
// Usage_Other used for all other unused crypto option
Usage_Other = "Other"
)
const (
// PublicKeySize is the size, in bytes, of public keys as used in this package.
PublicKeySize = 32
// PrivateKeySize is the size, in bytes, of private keys as used in this package.
PrivateKeySize = 64
// SignatureSize is the size, in bytes, of signatures generated and verified by this package.
SignatureSize = 64
)
var (
logger = logging.MustGetLogger("ed25519")
)
// PublicKey store public key and its information
type PublicKey struct {
Usage string `json:"usage"`
KeyType string `json:"key_type"`
PublicKeyData []byte `json:"public_key_data"`
}
//PrivateKey store private key and its information
type PrivateKey struct {
Usage string `json:"usage"`
KeyType string `json:"key_type"`
PrivateKeyData []byte `json:"private_key_data"`
}
// KeyPair generate keypair of ed25519
func | () (pub *PublicKey, pri *PrivateKey, err error) {
publicKey, privateKey, err := edAlg.GenerateKey(rand.Reader)
if nil != err {
logger.Errorf("Failed to generate ed25519 keypair: %v", err)
return pub, pri, err
}
pub = &PublicKey{
PublicKeyData: publicKey,
}
pri = &PrivateKey{
PrivateKeyData: privateKey,
}
return pub, pri, nil
}
// GetUsage return usage of the key
func (privateKey *PrivateKey) GetUsage() string {
return privateKey.Usage
}
// GetType return type of the key
func (privateKey *PrivateKey) GetType() string {
return privateKey.KeyType
}
// GetRawData return the key
func (privateKey *PrivateKey) GetRawData() []byte {
return privateKey.PrivateKeyData
}
// Sign data with the privateKey
func (privateKey *PrivateKey) Sign(message []byte) ([]byte, error) {
return edAlg.Sign(privateKey.PrivateKeyData, message), nil
}
// GetUsage return usage of the key
func (publicKey *PublicKey) GetUsage() string {
return publicKey.Usage
}
// GetType return type of the key
func (publicKey *PublicKey) GetType() string {
return publicKey.KeyType
}
// GetRawData return the key
func (publicKey *PublicKey) GetRawData() []byte {
return publicKey.PublicKeyData
}
// Verify signature with the publicKey
func (publicKey *PublicKey) Verify(message []byte, signedMessage []byte) error {
if len(signedMessage) != SignatureSize || signedMessage[63]&224 != 0 {
logger.Error("signedMessage is wrong format")
return fmt.Errorf("signedMessage is wrong format")
}
result := edAlg.Verify(publicKey.PublicKeyData, message, signedMessage)
if !result {
logger.Error("Failed to verify the signature")
return fmt.Errorf("failed to verify the signature")
}
return nil
}
| Keypair |
models.py | from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse
# Create your models here.
class Snack(models.Model):
title = models.CharField(max_length=64)
purchaser = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
description = models.TextField()
def __str__(self) -> str:
return self.title
def get_absolute_url(self):
| return reverse("snack_detail", args=[str(self.pk)]) |
|
set1_challenge8.rs | use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
use std::collections::HashMap;
extern crate rustc_serialize;
use rustc_serialize::hex::FromHex;
fn main() {
let lines = load_from_file();
let mut max_duplicates = 0;
let mut line_with_max_duplicates = String::new();
for line in lines {
let decoded = line.from_hex().unwrap();
let duplicates = find_duplicates_substrings(decoded);
if duplicates > max_duplicates {
max_duplicates = duplicates;
line_with_max_duplicates = line;
}
}
println!("Max duplicates: {}", max_duplicates);
println!("{}", line_with_max_duplicates);
}
fn load_from_file() -> Vec<String> {
let file = File::open("data/set1_challenge8.txt").unwrap();
let reader = BufReader::new(file);
let mut lines = Vec::<String>::new();
for line in reader.lines() {
lines.push(line.unwrap());
}
lines
}
fn find_duplicates_substrings(string: Vec<u8>) -> u32 {
let mut substrings = HashMap::<Vec<u8>, u32>::new();
let block_count = string.len() / 16;
for i in 0..block_count {
let slice = &string[i*16..(i+1)*16];
let count = match substrings.get(slice) {
Some(c) => c + 1,
None => 0,
};
let mut v = Vec::new();
v.extend(slice.iter().map(|&i| i));
substrings.insert(v, count); | } | }
substrings.values().fold(0, |total, &value| total + value) |
lib.rs | #![allow(unused_imports)]
#![allow(clippy::must_use_candidate)]
#![allow(clippy::too_many_lines)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::cast_precision_loss)]
#![allow(clippy::cast_sign_loss)]
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::cast_possible_wrap)]
#![allow(clippy::similar_names)]
#![allow(clippy::shadow_unrelated)]
#![allow(clippy::pub_enum_variant_names)]
#![allow(clippy::missing_errors_doc)]
//! This crate extends [Rusoto's](https://crates.io/crates/rusoto) existing authentication infrastructure to support this feature.
use dirs::home_dir;
use lazy_static::lazy_static;
use regex::Regex;
use rusoto_core::{request::TlsError, Client, HttpClient, Region, RusotoError};
use rusoto_credential::{
AutoRefreshingProvider, CredentialsError, DefaultCredentialsProvider, StaticProvider,
};
use rusoto_sts::{
GetCallerIdentityError, GetCallerIdentityRequest, GetCallerIdentityResponse, Sts as _,
StsAssumeRoleSessionCredentialsProvider, StsClient,
};
use std::{
collections::HashMap,
env::{var, var_os, VarError},
fmt::Display,
fs::File,
io::{BufRead, BufReader},
path::{Path, PathBuf},
};
use thiserror::Error;
lazy_static! {
static ref PROFILE_REGEX: Regex =
Regex::new(r"^\[(profile )?([^\]]+)\]$").expect("Failed to compile regex");
}
type StsAuthProvider = AutoRefreshingProvider<StsAssumeRoleSessionCredentialsProvider>;
fn get_sts_auth_provider(
client: StsClient,
role_arn: &str,
) -> Result<StsAuthProvider, StsClientError> {
let provider = StsAssumeRoleSessionCredentialsProvider::new(
client,
role_arn.to_string(),
"default".to_string(),
None,
None,
None,
None,
);
AutoRefreshingProvider::new(provider).map_err(Into::into)
}
#[derive(Debug, Error)]
pub enum StsClientError {
#[error("HttpClient init failed")]
TlsError(#[from] TlsError),
#[error("Profile {0} is not available")]
StsProfileError(String),
#[error("No HOME directory")]
NoHomeError,
#[error("Error obtaining STS Credentials {0}")]
CredentialsError(#[from] CredentialsError),
#[error("GetCallerIdentityError {0}")]
GetCallerIdentityError(#[from] GetCallerIdentityError),
#[error("RusotoError {0}")]
RusotoError(String),
}
impl<T: std::error::Error + 'static> From<RusotoError<T>> for StsClientError {
fn from(item: RusotoError<T>) -> Self {
Self::RusotoError(item.to_string())
}
}
#[doc(hidden)]
#[macro_export]
macro_rules! get_client_sts_region_profile {
($T:ty, $region:expr, $profile:expr) => {
$crate::StsInstance::new($profile).and_then(|sts| {
let client = sts.get_client()?;
let region = if let Some(r) = $region {
r
} else {
sts.get_region()
};
Ok(<$T>::new_with_client(client, region))
})
};
}
/// Macro to return a profile authenticated client
///
/// This macro takes two arguments:
/// 1. A Rusoto client type (e.g. Ec2Client) which has the `new_with_client`
/// method 2. A Rusoto Region (optional)
/// 3. A Profile Name (optional)
///
/// It will return an instance of the provided client (e.g. Ec2Client) which
/// will use either the default profile or the profile specified by the
/// AWS_PROFILE env variable when authenticating.
///
/// The macro `get_client_sts_with_profile` accepts a client and a profile name
/// but no region.
///
/// # Example usage:
/// ```
/// use rusoto_core::Region;
/// use rusoto_ec2::Ec2Client;
/// use sts_profile_auth::get_client_sts;
/// use sts_profile_auth::StsClientError;
///
/// # fn main() -> Result<(), StsClientError> {
/// let ec2 = get_client_sts!(Ec2Client)?;
/// let ec2 = get_client_sts!(Ec2Client, Region::default())?;
/// let ec2 = get_client_sts!(Ec2Client, Region::default(), "default")?;
/// # Ok(())
/// # }
/// ```
#[macro_export]
macro_rules! get_client_sts {
($T:ty) => {
$crate::get_client_sts_region_profile!($T, None, None)
};
($T:ty, $region:expr) => {
$crate::get_client_sts_region_profile!($T, Some($region), None)
};
($T:ty, $region:expr, $profile:expr) => {
$crate::get_client_sts_region_profile!($T, Some($region), Some($profile))
};
}
/// Macro to return a profile authenticated client
///
/// This macro takes two arguments:
/// 1. A Rusoto client type (e.g. Ec2Client) which has the `new_with_client`
/// method 2. A Profile Name
///
/// It will return an instance of the provided client (e.g. Ec2Client) which
/// will use the specified profile when authenticating.
///
/// # Example usage:
/// ```
/// use rusoto_core::Region;
/// use rusoto_ec2::Ec2Client;
/// use sts_profile_auth::get_client_sts_with_profile;
/// use sts_profile_auth::StsClientError;
///
/// # fn main() -> Result<(), StsClientError> {
/// let ec2 = get_client_sts_with_profile!(Ec2Client, "default")?;
/// # Ok(())
/// # }
/// ```
#[macro_export]
macro_rules! get_client_sts_with_profile {
($T:ty, $profile:expr) => {
$crate::get_client_sts_region_profile!($T, None, Some($profile))
};
}
/// `StsInstance` contains an `StsClient` instance, and metadata used to create
/// it (region, keys, role arn)
#[derive(Clone)]
pub struct StsInstance {
sts_client: StsClient,
region: Region,
aws_access_key_id: String,
aws_secret_access_key: String,
aws_session_token: Option<String>,
role_arn: Option<String>,
}
impl Default for StsInstance {
fn default() -> Self {
Self {
sts_client: StsClient::new(Region::default()),
region: Region::default(),
aws_access_key_id: "".to_string(),
aws_secret_access_key: "".to_string(),
aws_session_token: None,
role_arn: None,
}
}
}
impl StsInstance {
/// Create a new `StsInstance`, either specifying a profile name, using the
/// `AWS_PROFILE` environment variable, or using default
pub fn new(profile: Option<&str>) -> Result<Self, StsClientError> {
let profiles = AwsProfileInfo::fill_profile_map()?;
let profile_name = match profile {
Some(n) => n.to_string(),
None => var("AWS_PROFILE")
.ok()
.unwrap_or_else(|| "default".to_string()),
};
let current_profile = match profiles.get(&profile_name) {
Some(p) => p,
None => {
if profile.is_none() {
return Ok(Self::default());
} else {
return Err(StsClientError::StsProfileError(profile_name));
}
}
};
let region: Region = current_profile.region.parse().ok().unwrap_or_default();
let (key, secret, token) = match current_profile.source_profile.as_ref() {
Some(prof) => {
let source_profile = profiles
.get(prof)
.ok_or_else(|| StsClientError::StsProfileError(prof.to_string()))?;
(
source_profile.aws_access_key_id.to_string(),
source_profile.aws_secret_access_key.to_string(),
source_profile.aws_session_token.clone(),
)
}
None => (
current_profile.aws_access_key_id.to_string(),
current_profile.aws_secret_access_key.to_string(),
current_profile.aws_session_token.clone(),
),
};
let provider = StaticProvider::new(key.to_string(), secret.to_string(), token, None);
Ok(Self {
sts_client: StsClient::new_with(HttpClient::new()?, provider, region.clone()),
region,
aws_access_key_id: key,
aws_secret_access_key: secret,
role_arn: current_profile.role_arn.clone(),
aws_session_token: current_profile.aws_session_token.clone(),
})
}
/// Get an auto-refreshing credential provider
pub fn get_provider(&self) -> Result<Option<StsAuthProvider>, StsClientError> {
match &self.role_arn {
Some(role_arn) => {
let provider = get_sts_auth_provider(self.sts_client.clone(), role_arn)?;
Ok(Some(provider))
}
None => Ok(None),
}
}
/// Get an instance of `rusoto_core::Client` which can be used to
/// instantiate any other rusoto client type.
pub fn get_client(&self) -> Result<Client, StsClientError> {
let client = match self.get_provider()? {
Some(provider) => Client::new_with(provider, rusoto_core::HttpClient::new()?),
None => Client::new_with(
DefaultCredentialsProvider::new()?,
rusoto_core::HttpClient::new()?,
),
};
Ok(client)
}
pub fn get_region(&self) -> Region |
pub async fn get_user_id(&self) -> Result<GetCallerIdentityResponse, StsClientError> {
self.sts_client
.get_caller_identity(GetCallerIdentityRequest {})
.await
.map_err(Into::into)
}
}
/// Profile meta-data, representing either a profile with an access key, or a
/// profile utilizing sts.
#[derive(Default, Clone, Debug)]
pub struct AwsProfileInfo {
pub name: String,
pub region: String,
pub aws_access_key_id: String,
pub aws_secret_access_key: String,
pub aws_session_token: Option<String>,
pub role_arn: Option<String>,
pub source_profile: Option<String>,
}
impl AwsProfileInfo {
/// This function fills an instance of `AwsProfileInfo` using a hashmap
/// generated by `fill_profile_map` It will return None if all required
/// information cannot be found.
pub fn from_hashmap(
profile_name: &str,
profile_map: &HashMap<String, HashMap<String, String>>,
) -> Option<Self> {
let name = profile_name.to_string();
let prof_map = match profile_map.get(profile_name) {
Some(p) => p,
None => return None,
};
let region = prof_map
.get("region")
.cloned()
.unwrap_or_else(|| "us-east-1".to_string());
let source_profile = prof_map.get("source_profile").map(ToString::to_string);
let role_arn = prof_map.get("role_arn").map(ToString::to_string);
let mut access_key = prof_map.get("aws_access_key_id").map(ToString::to_string);
let mut access_secret = prof_map
.get("aws_secret_access_key")
.map(ToString::to_string);
let aws_session_token = prof_map.get("aws_session_token").map(ToString::to_string);
if let Some(s) = source_profile.as_ref() {
let pmap = match profile_map.get(s) {
Some(p) => p,
None => return None,
};
pmap.get("aws_access_key_id")
.map(|a| access_key.replace(a.to_string()));
pmap.get("aws_secret_access_key")
.map(|a| access_secret.replace(a.to_string()));
}
let aws_access_key_id = match access_key {
Some(a) => a,
None => return None,
};
let aws_secret_access_key = match access_secret {
Some(a) => a,
None => return None,
};
Some(Self {
name,
region,
aws_access_key_id,
aws_secret_access_key,
aws_session_token,
role_arn,
source_profile,
})
}
/// Extract profile information hashmap from `${HOME}/.aws/config` and
/// `${HOME}/.aws/credentials`
pub fn fill_profile_map() -> Result<HashMap<String, Self>, StsClientError> {
let config_dir = if let Some(s) = var_os("AWS_CONFIG_FILE") {
PathBuf::from(s)
} else if let Some(h) = home_dir() {
h.join(".aws")
} else {
return Err(StsClientError::NoHomeError);
};
let config_file = config_dir.join("config");
let credential_file = config_dir.join("credentials");
let mut profile_map: HashMap<String, HashMap<String, String>> = HashMap::new();
for fname in &[config_file, credential_file] {
if !Path::new(fname).exists() {
continue;
}
if let Some(p) = parse_config_file(fname) {
if profile_map.is_empty() {
profile_map = p;
} else {
for (k, v) in p {
if let Some(pm) = profile_map.get_mut(&k) {
for (k_, v_) in v {
pm.insert(k_, v_);
}
} else {
profile_map.insert(k, v);
}
}
}
}
}
let profile_map: HashMap<_, _> = profile_map
.keys()
.filter_map(|k| Self::from_hashmap(k, &profile_map).map(|p| (k.to_string(), p)))
.collect();
Ok(profile_map)
}
}
/// Stolen from rusoto credential's profile.rs
/// Parses an aws credentials config file and returns a hashmap of hashmaps.
fn parse_config_file<P>(file_path: P) -> Option<HashMap<String, HashMap<String, String>>>
where
P: AsRef<Path>,
{
if !file_path.as_ref().exists() || !file_path.as_ref().is_file() {
return None;
}
let file = File::open(file_path).expect("expected file");
let file_lines = BufReader::new(&file);
let result: (HashMap<String, HashMap<String, String>>, Option<String>) = file_lines
.lines()
.filter_map(|line| {
line.ok()
.map(|l| l.trim_matches(' ').to_owned())
.into_iter()
.find(|l| !l.starts_with('#') && !l.is_empty())
})
.fold(Default::default(), |(mut result, profile), line| {
if PROFILE_REGEX.is_match(&line) {
let caps = PROFILE_REGEX.captures(&line).unwrap();
let next_profile = caps.get(2).map(|value| value.as_str().to_string());
(result, next_profile)
} else {
match &line
.splitn(2, '=')
.map(|value| value.trim_matches(' '))
.collect::<Vec<&str>>()[..]
{
[key, value] if !key.is_empty() && !value.is_empty() => {
if let Some(current) = profile.clone() {
let values = result.entry(current).or_insert_with(HashMap::new);
(*values).insert((*key).to_string(), (*value).to_string());
}
(result, profile)
}
_ => (result, profile),
}
}
});
Some(result.0)
}
#[cfg(test)]
mod tests {
use rusoto_core::Region;
use rusoto_ec2::{DescribeInstancesRequest, Ec2, Ec2Client};
use crate::{AwsProfileInfo, StsClientError, StsInstance};
#[tokio::test]
async fn test_get_user_id() -> Result<(), StsClientError> {
let sts = StsInstance::new(None)?;
let user = sts.get_user_id().await?;
println!("{:?}", user);
assert!(user.user_id.is_some());
Ok(())
}
#[test]
fn test_fill_profile_map() -> Result<(), StsClientError> {
let prof_map = AwsProfileInfo::fill_profile_map()?;
for (k, v) in &prof_map {
println!("{} {:?}", k, v);
}
assert!(prof_map.len() > 0);
assert!(prof_map.contains_key("default"));
Ok(())
}
#[tokio::test]
async fn test_get_client_sts() -> Result<(), StsClientError> {
let ec2 = get_client_sts!(Ec2Client)?;
let instances: Vec<_> = ec2
.describe_instances(DescribeInstancesRequest::default())
.await
.map(|instances| {
instances
.reservations
.unwrap_or_else(Vec::new)
.into_iter()
.filter_map(|res| {
res.instances.map(|instances| {
instances
.into_iter()
.filter_map(|inst| inst.instance_id)
.collect::<Vec<_>>()
})
})
.flatten()
.collect()
})?;
println!("{:?}", instances);
assert!(instances.len() > 0);
Ok(())
}
}
| {
self.region.clone()
} |
error.rs | //! Errors encountered during desugaring to and processing core
use crate::common::sourcemap::SourceMap;
use crate::common::sourcemap::{HasSmid, Smid};
use crate::syntax::input::Input;
use codespan_reporting::diagnostic::Diagnostic;
use thiserror::Error;
#[derive(Eq, PartialEq, Debug, Clone, Error)]
pub enum CoreError {
#[error("invalid metadata")]
InvalidMetadataDesugarPhase(Smid),
#[error("unknown embedding: {0}")]
UnknownEmbedding(String),
#[error("invalid embedding - {0}")]
InvalidEmbedding(String, Smid),
#[error("no parsed AST found for input {0}")]
NoParsedAstFor(Input),
#[error("too few operands available for operator")]
TooFewOperands(Smid),
#[error("cannot mix anaphora types (numberless, numbered and section)")]
MixedAnaphora(Smid),
#[error("found temporary pseudo-operators remaining in evaluand")]
UneliminatedPseudoOperators,
#[error("found operator soup within unresolved precedence")]
UneliminatedSoup(Smid),
#[error("found eliminated code markers remaining in evaluand")]
UnprunedEliminations,
#[error("unresolved variable: {1}")]
UnresolvedVariable(Smid, String),
#[error("variable redeclared: {1}")]
RedeclaredVariable(Smid, String),
#[error("empty merge")]
EmptyMerge(),
#[error("merge base was not valid for merge")]
InvalidMergeBase(),
#[error("target {0} not found")]
TargetNotFound(String),
#[error("target {0} could not be referenced")]
BadTarget(String),
}
impl HasSmid for CoreError {
fn | (&self) -> Smid {
use self::CoreError::*;
match *self {
InvalidMetadataDesugarPhase(s) => s,
InvalidEmbedding(_, s) => s,
TooFewOperands(s) => s,
MixedAnaphora(s) => s,
UnresolvedVariable(s, _) => s,
RedeclaredVariable(s, _) => s,
_ => Smid::default(),
}
}
}
impl CoreError {
pub fn to_diagnostic(&self, source_map: &SourceMap) -> Diagnostic<usize> {
match self {
CoreError::InvalidMergeBase() => {
source_map.diagnostic(self).with_notes(vec![
"some input formats (csv, text, etc.) that read as lists need to be assigned names".to_string(),
"perhaps you need to name one or more of your inputs (<name>=<input>)".to_string()])
}
_ => source_map.diagnostic(self),
}
}
}
| smid |
deserializers.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package directconnect
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws/protocol/restjson"
"github.com/aws/aws-sdk-go-v2/service/directconnect/types"
smithy "github.com/aws/smithy-go"
smithyio "github.com/aws/smithy-go/io"
"github.com/aws/smithy-go/middleware"
"github.com/aws/smithy-go/ptr"
smithytime "github.com/aws/smithy-go/time"
smithyhttp "github.com/aws/smithy-go/transport/http"
"io"
"strings"
)
type awsAwsjson11_deserializeOpAcceptDirectConnectGatewayAssociationProposal struct {
}
func (*awsAwsjson11_deserializeOpAcceptDirectConnectGatewayAssociationProposal) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpAcceptDirectConnectGatewayAssociationProposal) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorAcceptDirectConnectGatewayAssociationProposal(response, &metadata)
}
output := &AcceptDirectConnectGatewayAssociationProposalOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentAcceptDirectConnectGatewayAssociationProposalOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorAcceptDirectConnectGatewayAssociationProposal(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpAllocateConnectionOnInterconnect struct {
}
func (*awsAwsjson11_deserializeOpAllocateConnectionOnInterconnect) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpAllocateConnectionOnInterconnect) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorAllocateConnectionOnInterconnect(response, &metadata)
}
output := &AllocateConnectionOnInterconnectOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentAllocateConnectionOnInterconnectOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorAllocateConnectionOnInterconnect(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpAllocateHostedConnection struct {
}
func (*awsAwsjson11_deserializeOpAllocateHostedConnection) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpAllocateHostedConnection) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorAllocateHostedConnection(response, &metadata)
}
output := &AllocateHostedConnectionOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentAllocateHostedConnectionOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorAllocateHostedConnection(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
case strings.EqualFold("DuplicateTagKeysException", errorCode):
return awsAwsjson11_deserializeErrorDuplicateTagKeysException(response, errorBody)
case strings.EqualFold("TooManyTagsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyTagsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpAllocatePrivateVirtualInterface struct {
}
func (*awsAwsjson11_deserializeOpAllocatePrivateVirtualInterface) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpAllocatePrivateVirtualInterface) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorAllocatePrivateVirtualInterface(response, &metadata)
}
output := &AllocatePrivateVirtualInterfaceOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentAllocatePrivateVirtualInterfaceOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorAllocatePrivateVirtualInterface(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
case strings.EqualFold("DuplicateTagKeysException", errorCode):
return awsAwsjson11_deserializeErrorDuplicateTagKeysException(response, errorBody)
case strings.EqualFold("TooManyTagsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyTagsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpAllocatePublicVirtualInterface struct {
}
func (*awsAwsjson11_deserializeOpAllocatePublicVirtualInterface) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpAllocatePublicVirtualInterface) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorAllocatePublicVirtualInterface(response, &metadata)
}
output := &AllocatePublicVirtualInterfaceOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentAllocatePublicVirtualInterfaceOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorAllocatePublicVirtualInterface(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
case strings.EqualFold("DuplicateTagKeysException", errorCode):
return awsAwsjson11_deserializeErrorDuplicateTagKeysException(response, errorBody)
case strings.EqualFold("TooManyTagsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyTagsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpAllocateTransitVirtualInterface struct {
}
func (*awsAwsjson11_deserializeOpAllocateTransitVirtualInterface) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpAllocateTransitVirtualInterface) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorAllocateTransitVirtualInterface(response, &metadata)
}
output := &AllocateTransitVirtualInterfaceOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentAllocateTransitVirtualInterfaceOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorAllocateTransitVirtualInterface(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
case strings.EqualFold("DuplicateTagKeysException", errorCode):
return awsAwsjson11_deserializeErrorDuplicateTagKeysException(response, errorBody)
case strings.EqualFold("TooManyTagsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyTagsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpAssociateConnectionWithLag struct {
}
func (*awsAwsjson11_deserializeOpAssociateConnectionWithLag) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpAssociateConnectionWithLag) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorAssociateConnectionWithLag(response, &metadata)
}
output := &AssociateConnectionWithLagOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentAssociateConnectionWithLagOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorAssociateConnectionWithLag(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpAssociateHostedConnection struct {
}
func (*awsAwsjson11_deserializeOpAssociateHostedConnection) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpAssociateHostedConnection) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorAssociateHostedConnection(response, &metadata)
}
output := &AssociateHostedConnectionOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentAssociateHostedConnectionOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorAssociateHostedConnection(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpAssociateMacSecKey struct {
}
func (*awsAwsjson11_deserializeOpAssociateMacSecKey) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpAssociateMacSecKey) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorAssociateMacSecKey(response, &metadata)
}
output := &AssociateMacSecKeyOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentAssociateMacSecKeyOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorAssociateMacSecKey(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpAssociateVirtualInterface struct {
}
func (*awsAwsjson11_deserializeOpAssociateVirtualInterface) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpAssociateVirtualInterface) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorAssociateVirtualInterface(response, &metadata)
}
output := &AssociateVirtualInterfaceOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentAssociateVirtualInterfaceOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorAssociateVirtualInterface(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpConfirmConnection struct {
}
func (*awsAwsjson11_deserializeOpConfirmConnection) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpConfirmConnection) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorConfirmConnection(response, &metadata)
}
output := &ConfirmConnectionOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentConfirmConnectionOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorConfirmConnection(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpConfirmPrivateVirtualInterface struct {
}
func (*awsAwsjson11_deserializeOpConfirmPrivateVirtualInterface) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpConfirmPrivateVirtualInterface) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorConfirmPrivateVirtualInterface(response, &metadata)
}
output := &ConfirmPrivateVirtualInterfaceOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentConfirmPrivateVirtualInterfaceOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorConfirmPrivateVirtualInterface(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpConfirmPublicVirtualInterface struct {
}
func (*awsAwsjson11_deserializeOpConfirmPublicVirtualInterface) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpConfirmPublicVirtualInterface) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorConfirmPublicVirtualInterface(response, &metadata)
}
output := &ConfirmPublicVirtualInterfaceOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentConfirmPublicVirtualInterfaceOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorConfirmPublicVirtualInterface(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpConfirmTransitVirtualInterface struct {
}
func (*awsAwsjson11_deserializeOpConfirmTransitVirtualInterface) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpConfirmTransitVirtualInterface) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorConfirmTransitVirtualInterface(response, &metadata)
}
output := &ConfirmTransitVirtualInterfaceOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentConfirmTransitVirtualInterfaceOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorConfirmTransitVirtualInterface(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpCreateBGPPeer struct {
}
func (*awsAwsjson11_deserializeOpCreateBGPPeer) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpCreateBGPPeer) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorCreateBGPPeer(response, &metadata)
}
output := &CreateBGPPeerOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentCreateBGPPeerOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorCreateBGPPeer(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpCreateConnection struct {
}
func (*awsAwsjson11_deserializeOpCreateConnection) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpCreateConnection) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorCreateConnection(response, &metadata)
}
output := &CreateConnectionOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentCreateConnectionOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorCreateConnection(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
case strings.EqualFold("DuplicateTagKeysException", errorCode):
return awsAwsjson11_deserializeErrorDuplicateTagKeysException(response, errorBody)
case strings.EqualFold("TooManyTagsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyTagsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpCreateDirectConnectGateway struct {
}
func (*awsAwsjson11_deserializeOpCreateDirectConnectGateway) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpCreateDirectConnectGateway) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorCreateDirectConnectGateway(response, &metadata)
}
output := &CreateDirectConnectGatewayOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentCreateDirectConnectGatewayOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorCreateDirectConnectGateway(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpCreateDirectConnectGatewayAssociation struct {
}
func (*awsAwsjson11_deserializeOpCreateDirectConnectGatewayAssociation) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpCreateDirectConnectGatewayAssociation) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorCreateDirectConnectGatewayAssociation(response, &metadata)
}
output := &CreateDirectConnectGatewayAssociationOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentCreateDirectConnectGatewayAssociationOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorCreateDirectConnectGatewayAssociation(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpCreateDirectConnectGatewayAssociationProposal struct {
}
func (*awsAwsjson11_deserializeOpCreateDirectConnectGatewayAssociationProposal) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpCreateDirectConnectGatewayAssociationProposal) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorCreateDirectConnectGatewayAssociationProposal(response, &metadata)
}
output := &CreateDirectConnectGatewayAssociationProposalOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentCreateDirectConnectGatewayAssociationProposalOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorCreateDirectConnectGatewayAssociationProposal(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpCreateInterconnect struct {
}
func (*awsAwsjson11_deserializeOpCreateInterconnect) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpCreateInterconnect) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorCreateInterconnect(response, &metadata)
}
output := &CreateInterconnectOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentCreateInterconnectOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorCreateInterconnect(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
case strings.EqualFold("DuplicateTagKeysException", errorCode):
return awsAwsjson11_deserializeErrorDuplicateTagKeysException(response, errorBody)
case strings.EqualFold("TooManyTagsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyTagsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpCreateLag struct {
}
func (*awsAwsjson11_deserializeOpCreateLag) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpCreateLag) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorCreateLag(response, &metadata)
}
output := &CreateLagOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentCreateLagOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorCreateLag(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
case strings.EqualFold("DuplicateTagKeysException", errorCode):
return awsAwsjson11_deserializeErrorDuplicateTagKeysException(response, errorBody)
case strings.EqualFold("TooManyTagsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyTagsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpCreatePrivateVirtualInterface struct {
}
func (*awsAwsjson11_deserializeOpCreatePrivateVirtualInterface) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpCreatePrivateVirtualInterface) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorCreatePrivateVirtualInterface(response, &metadata)
}
output := &CreatePrivateVirtualInterfaceOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentCreatePrivateVirtualInterfaceOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorCreatePrivateVirtualInterface(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
case strings.EqualFold("DuplicateTagKeysException", errorCode):
return awsAwsjson11_deserializeErrorDuplicateTagKeysException(response, errorBody)
case strings.EqualFold("TooManyTagsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyTagsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpCreatePublicVirtualInterface struct {
}
func (*awsAwsjson11_deserializeOpCreatePublicVirtualInterface) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpCreatePublicVirtualInterface) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorCreatePublicVirtualInterface(response, &metadata)
}
output := &CreatePublicVirtualInterfaceOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentCreatePublicVirtualInterfaceOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorCreatePublicVirtualInterface(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
case strings.EqualFold("DuplicateTagKeysException", errorCode):
return awsAwsjson11_deserializeErrorDuplicateTagKeysException(response, errorBody)
case strings.EqualFold("TooManyTagsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyTagsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpCreateTransitVirtualInterface struct {
}
func (*awsAwsjson11_deserializeOpCreateTransitVirtualInterface) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpCreateTransitVirtualInterface) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorCreateTransitVirtualInterface(response, &metadata)
}
output := &CreateTransitVirtualInterfaceOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentCreateTransitVirtualInterfaceOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorCreateTransitVirtualInterface(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
case strings.EqualFold("DuplicateTagKeysException", errorCode):
return awsAwsjson11_deserializeErrorDuplicateTagKeysException(response, errorBody)
case strings.EqualFold("TooManyTagsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyTagsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDeleteBGPPeer struct {
}
func (*awsAwsjson11_deserializeOpDeleteBGPPeer) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDeleteBGPPeer) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDeleteBGPPeer(response, &metadata)
}
output := &DeleteBGPPeerOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDeleteBGPPeerOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDeleteBGPPeer(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDeleteConnection struct {
}
func (*awsAwsjson11_deserializeOpDeleteConnection) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDeleteConnection) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDeleteConnection(response, &metadata)
}
output := &DeleteConnectionOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDeleteConnectionOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDeleteConnection(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDeleteDirectConnectGateway struct {
}
func (*awsAwsjson11_deserializeOpDeleteDirectConnectGateway) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDeleteDirectConnectGateway) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDeleteDirectConnectGateway(response, &metadata)
}
output := &DeleteDirectConnectGatewayOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDeleteDirectConnectGatewayOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDeleteDirectConnectGateway(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDeleteDirectConnectGatewayAssociation struct {
}
func (*awsAwsjson11_deserializeOpDeleteDirectConnectGatewayAssociation) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDeleteDirectConnectGatewayAssociation) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDeleteDirectConnectGatewayAssociation(response, &metadata)
}
output := &DeleteDirectConnectGatewayAssociationOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDeleteDirectConnectGatewayAssociationOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDeleteDirectConnectGatewayAssociation(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDeleteDirectConnectGatewayAssociationProposal struct {
}
func (*awsAwsjson11_deserializeOpDeleteDirectConnectGatewayAssociationProposal) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDeleteDirectConnectGatewayAssociationProposal) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDeleteDirectConnectGatewayAssociationProposal(response, &metadata)
}
output := &DeleteDirectConnectGatewayAssociationProposalOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDeleteDirectConnectGatewayAssociationProposalOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDeleteDirectConnectGatewayAssociationProposal(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDeleteInterconnect struct {
}
func (*awsAwsjson11_deserializeOpDeleteInterconnect) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDeleteInterconnect) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDeleteInterconnect(response, &metadata)
}
output := &DeleteInterconnectOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDeleteInterconnectOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDeleteInterconnect(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDeleteLag struct {
}
func (*awsAwsjson11_deserializeOpDeleteLag) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDeleteLag) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDeleteLag(response, &metadata)
}
output := &DeleteLagOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDeleteLagOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDeleteLag(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDeleteVirtualInterface struct {
}
func (*awsAwsjson11_deserializeOpDeleteVirtualInterface) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDeleteVirtualInterface) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDeleteVirtualInterface(response, &metadata)
}
output := &DeleteVirtualInterfaceOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDeleteVirtualInterfaceOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDeleteVirtualInterface(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDescribeConnectionLoa struct {
}
func (*awsAwsjson11_deserializeOpDescribeConnectionLoa) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDescribeConnectionLoa) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDescribeConnectionLoa(response, &metadata)
}
output := &DescribeConnectionLoaOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDescribeConnectionLoaOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDescribeConnectionLoa(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDescribeConnections struct {
}
func (*awsAwsjson11_deserializeOpDescribeConnections) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDescribeConnections) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDescribeConnections(response, &metadata)
}
output := &DescribeConnectionsOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDescribeConnectionsOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDescribeConnections(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDescribeConnectionsOnInterconnect struct {
}
func (*awsAwsjson11_deserializeOpDescribeConnectionsOnInterconnect) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDescribeConnectionsOnInterconnect) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDescribeConnectionsOnInterconnect(response, &metadata)
}
output := &DescribeConnectionsOnInterconnectOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDescribeConnectionsOnInterconnectOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDescribeConnectionsOnInterconnect(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDescribeDirectConnectGatewayAssociationProposals struct {
}
func (*awsAwsjson11_deserializeOpDescribeDirectConnectGatewayAssociationProposals) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDescribeDirectConnectGatewayAssociationProposals) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDescribeDirectConnectGatewayAssociationProposals(response, &metadata)
}
output := &DescribeDirectConnectGatewayAssociationProposalsOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDescribeDirectConnectGatewayAssociationProposalsOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDescribeDirectConnectGatewayAssociationProposals(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDescribeDirectConnectGatewayAssociations struct {
}
func (*awsAwsjson11_deserializeOpDescribeDirectConnectGatewayAssociations) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDescribeDirectConnectGatewayAssociations) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDescribeDirectConnectGatewayAssociations(response, &metadata)
}
output := &DescribeDirectConnectGatewayAssociationsOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDescribeDirectConnectGatewayAssociationsOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDescribeDirectConnectGatewayAssociations(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDescribeDirectConnectGatewayAttachments struct {
}
func (*awsAwsjson11_deserializeOpDescribeDirectConnectGatewayAttachments) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDescribeDirectConnectGatewayAttachments) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDescribeDirectConnectGatewayAttachments(response, &metadata)
}
output := &DescribeDirectConnectGatewayAttachmentsOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDescribeDirectConnectGatewayAttachmentsOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDescribeDirectConnectGatewayAttachments(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDescribeDirectConnectGateways struct {
}
func (*awsAwsjson11_deserializeOpDescribeDirectConnectGateways) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDescribeDirectConnectGateways) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDescribeDirectConnectGateways(response, &metadata)
}
output := &DescribeDirectConnectGatewaysOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDescribeDirectConnectGatewaysOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDescribeDirectConnectGateways(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDescribeHostedConnections struct {
}
func (*awsAwsjson11_deserializeOpDescribeHostedConnections) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDescribeHostedConnections) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDescribeHostedConnections(response, &metadata)
}
output := &DescribeHostedConnectionsOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDescribeHostedConnectionsOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDescribeHostedConnections(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDescribeInterconnectLoa struct {
}
func (*awsAwsjson11_deserializeOpDescribeInterconnectLoa) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDescribeInterconnectLoa) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDescribeInterconnectLoa(response, &metadata)
}
output := &DescribeInterconnectLoaOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDescribeInterconnectLoaOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDescribeInterconnectLoa(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDescribeInterconnects struct {
}
func (*awsAwsjson11_deserializeOpDescribeInterconnects) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDescribeInterconnects) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDescribeInterconnects(response, &metadata)
}
output := &DescribeInterconnectsOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDescribeInterconnectsOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDescribeInterconnects(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDescribeLags struct {
}
func (*awsAwsjson11_deserializeOpDescribeLags) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDescribeLags) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDescribeLags(response, &metadata)
}
output := &DescribeLagsOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDescribeLagsOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDescribeLags(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDescribeLoa struct {
}
func (*awsAwsjson11_deserializeOpDescribeLoa) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDescribeLoa) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDescribeLoa(response, &metadata)
}
output := &DescribeLoaOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDescribeLoaOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDescribeLoa(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDescribeLocations struct {
}
func (*awsAwsjson11_deserializeOpDescribeLocations) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDescribeLocations) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDescribeLocations(response, &metadata)
}
output := &DescribeLocationsOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDescribeLocationsOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDescribeLocations(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDescribeTags struct {
}
func (*awsAwsjson11_deserializeOpDescribeTags) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDescribeTags) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDescribeTags(response, &metadata)
}
output := &DescribeTagsOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDescribeTagsOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDescribeTags(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDescribeVirtualGateways struct {
}
func (*awsAwsjson11_deserializeOpDescribeVirtualGateways) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDescribeVirtualGateways) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDescribeVirtualGateways(response, &metadata)
}
output := &DescribeVirtualGatewaysOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDescribeVirtualGatewaysOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDescribeVirtualGateways(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDescribeVirtualInterfaces struct {
}
func (*awsAwsjson11_deserializeOpDescribeVirtualInterfaces) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDescribeVirtualInterfaces) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDescribeVirtualInterfaces(response, &metadata)
}
output := &DescribeVirtualInterfacesOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDescribeVirtualInterfacesOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDescribeVirtualInterfaces(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDisassociateConnectionFromLag struct {
}
func (*awsAwsjson11_deserializeOpDisassociateConnectionFromLag) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDisassociateConnectionFromLag) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDisassociateConnectionFromLag(response, &metadata)
}
output := &DisassociateConnectionFromLagOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDisassociateConnectionFromLagOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDisassociateConnectionFromLag(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDisassociateMacSecKey struct {
}
func (*awsAwsjson11_deserializeOpDisassociateMacSecKey) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDisassociateMacSecKey) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDisassociateMacSecKey(response, &metadata)
}
output := &DisassociateMacSecKeyOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDisassociateMacSecKeyOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDisassociateMacSecKey(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpListVirtualInterfaceTestHistory struct {
}
func (*awsAwsjson11_deserializeOpListVirtualInterfaceTestHistory) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpListVirtualInterfaceTestHistory) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorListVirtualInterfaceTestHistory(response, &metadata)
}
output := &ListVirtualInterfaceTestHistoryOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentListVirtualInterfaceTestHistoryOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorListVirtualInterfaceTestHistory(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpStartBgpFailoverTest struct {
}
func (*awsAwsjson11_deserializeOpStartBgpFailoverTest) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpStartBgpFailoverTest) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorStartBgpFailoverTest(response, &metadata)
}
output := &StartBgpFailoverTestOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentStartBgpFailoverTestOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorStartBgpFailoverTest(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpStopBgpFailoverTest struct {
}
func (*awsAwsjson11_deserializeOpStopBgpFailoverTest) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpStopBgpFailoverTest) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorStopBgpFailoverTest(response, &metadata)
}
output := &StopBgpFailoverTestOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentStopBgpFailoverTestOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorStopBgpFailoverTest(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpTagResource struct {
}
func (*awsAwsjson11_deserializeOpTagResource) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpTagResource) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorTagResource(response, &metadata)
}
output := &TagResourceOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentTagResourceOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorTagResource(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
case strings.EqualFold("DuplicateTagKeysException", errorCode):
return awsAwsjson11_deserializeErrorDuplicateTagKeysException(response, errorBody)
case strings.EqualFold("TooManyTagsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyTagsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpUntagResource struct {
}
func (*awsAwsjson11_deserializeOpUntagResource) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpUntagResource) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorUntagResource(response, &metadata)
}
output := &UntagResourceOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentUntagResourceOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorUntagResource(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpUpdateConnection struct {
}
func (*awsAwsjson11_deserializeOpUpdateConnection) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpUpdateConnection) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorUpdateConnection(response, &metadata)
}
output := &UpdateConnectionOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentUpdateConnectionOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorUpdateConnection(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpUpdateDirectConnectGatewayAssociation struct {
}
func (*awsAwsjson11_deserializeOpUpdateDirectConnectGatewayAssociation) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpUpdateDirectConnectGatewayAssociation) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorUpdateDirectConnectGatewayAssociation(response, &metadata)
}
output := &UpdateDirectConnectGatewayAssociationOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentUpdateDirectConnectGatewayAssociationOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorUpdateDirectConnectGatewayAssociation(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpUpdateLag struct {
}
func (*awsAwsjson11_deserializeOpUpdateLag) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpUpdateLag) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorUpdateLag(response, &metadata)
}
output := &UpdateLagOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentUpdateLagOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorUpdateLag(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpUpdateVirtualInterfaceAttributes struct {
}
func (*awsAwsjson11_deserializeOpUpdateVirtualInterfaceAttributes) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpUpdateVirtualInterfaceAttributes) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorUpdateVirtualInterfaceAttributes(response, &metadata)
}
output := &UpdateVirtualInterfaceAttributesOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentUpdateVirtualInterfaceAttributesOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorUpdateVirtualInterfaceAttributes(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("DirectConnectClientException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectClientException(response, errorBody)
case strings.EqualFold("DirectConnectServerException", errorCode):
return awsAwsjson11_deserializeErrorDirectConnectServerException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
func awsAwsjson11_deserializeErrorDirectConnectClientException(response *smithyhttp.Response, errorBody *bytes.Reader) error {
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
output := &types.DirectConnectClientException{}
err := awsAwsjson11_deserializeDocumentDirectConnectClientException(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
return output
}
func awsAwsjson11_deserializeErrorDirectConnectServerException(response *smithyhttp.Response, errorBody *bytes.Reader) error {
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
output := &types.DirectConnectServerException{}
err := awsAwsjson11_deserializeDocumentDirectConnectServerException(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
return output
}
func awsAwsjson11_deserializeErrorDuplicateTagKeysException(response *smithyhttp.Response, errorBody *bytes.Reader) error {
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
output := &types.DuplicateTagKeysException{}
err := awsAwsjson11_deserializeDocumentDuplicateTagKeysException(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
return output
}
func awsAwsjson11_deserializeErrorTooManyTagsException(response *smithyhttp.Response, errorBody *bytes.Reader) error {
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
output := &types.TooManyTagsException{}
err := awsAwsjson11_deserializeDocumentTooManyTagsException(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
return output
}
func awsAwsjson11_deserializeDocumentAssociatedGateway(v **types.AssociatedGateway, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.AssociatedGateway
if *v == nil {
sv = &types.AssociatedGateway{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "id":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected GatewayIdentifier to be of type string, got %T instead", value)
}
sv.Id = ptr.String(jtv)
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "type":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected GatewayType to be of type string, got %T instead", value)
}
sv.Type = types.GatewayType(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentAvailableMacSecPortSpeeds(v *[]string, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []string
if *v == nil {
cv = []string{}
} else {
cv = *v
}
for _, value := range shape {
var col string
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PortSpeed to be of type string, got %T instead", value)
}
col = jtv
}
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentAvailablePortSpeeds(v *[]string, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []string
if *v == nil {
cv = []string{}
} else {
cv = *v
}
for _, value := range shape {
var col string
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PortSpeed to be of type string, got %T instead", value)
}
col = jtv
}
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentBGPPeer(v **types.BGPPeer, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.BGPPeer
if *v == nil {
sv = &types.BGPPeer{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "addressFamily":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AddressFamily to be of type string, got %T instead", value)
}
sv.AddressFamily = types.AddressFamily(jtv)
}
case "amazonAddress":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AmazonAddress to be of type string, got %T instead", value)
}
sv.AmazonAddress = ptr.String(jtv)
}
case "asn":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected ASN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Asn = int32(i64)
}
case "authKey":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected BGPAuthKey to be of type string, got %T instead", value)
}
sv.AuthKey = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "bgpPeerId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected BGPPeerId to be of type string, got %T instead", value)
}
sv.BgpPeerId = ptr.String(jtv)
}
case "bgpPeerState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected BGPPeerState to be of type string, got %T instead", value)
}
sv.BgpPeerState = types.BGPPeerState(jtv)
}
case "bgpStatus":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected BGPStatus to be of type string, got %T instead", value)
}
sv.BgpStatus = types.BGPStatus(jtv)
}
case "customerAddress":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected CustomerAddress to be of type string, got %T instead", value)
}
sv.CustomerAddress = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentBGPPeerIdList(v *[]string, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []string
if *v == nil {
cv = []string{}
} else {
cv = *v
}
for _, value := range shape {
var col string
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected BGPPeerId to be of type string, got %T instead", value)
}
col = jtv
}
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentBGPPeerList(v *[]types.BGPPeer, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []types.BGPPeer
if *v == nil {
cv = []types.BGPPeer{}
} else {
cv = *v
}
for _, value := range shape {
var col types.BGPPeer
destAddr := &col
if err := awsAwsjson11_deserializeDocumentBGPPeer(&destAddr, value); err != nil {
return err
}
col = *destAddr
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentConnection(v **types.Connection, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.Connection
if *v == nil {
sv = &types.Connection{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "awsDevice":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDevice to be of type string, got %T instead", value)
}
sv.AwsDevice = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "bandwidth":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Bandwidth to be of type string, got %T instead", value)
}
sv.Bandwidth = ptr.String(jtv)
}
case "connectionId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionId to be of type string, got %T instead", value)
}
sv.ConnectionId = ptr.String(jtv)
}
case "connectionName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionName to be of type string, got %T instead", value)
}
sv.ConnectionName = ptr.String(jtv)
}
case "connectionState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionState to be of type string, got %T instead", value)
}
sv.ConnectionState = types.ConnectionState(jtv)
}
case "encryptionMode":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EncryptionMode to be of type string, got %T instead", value)
}
sv.EncryptionMode = ptr.String(jtv)
}
case "hasLogicalRedundancy":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected HasLogicalRedundancy to be of type string, got %T instead", value)
}
sv.HasLogicalRedundancy = types.HasLogicalRedundancy(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "lagId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagId to be of type string, got %T instead", value)
}
sv.LagId = ptr.String(jtv)
}
case "loaIssueTime":
if value != nil {
switch jtv := value.(type) {
case json.Number:
f64, err := jtv.Float64()
if err != nil {
return err
}
sv.LoaIssueTime = ptr.Time(smithytime.ParseEpochSeconds(f64))
default:
return fmt.Errorf("expected LoaIssueTime to be a JSON Number, got %T instead", value)
}
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "macSecCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected MacSecCapable to be of type *bool, got %T instead", value)
}
sv.MacSecCapable = ptr.Bool(jtv)
}
case "macSecKeys":
if err := awsAwsjson11_deserializeDocumentMacSecKeyList(&sv.MacSecKeys, value); err != nil {
return err
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "partnerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PartnerName to be of type string, got %T instead", value)
}
sv.PartnerName = ptr.String(jtv)
}
case "portEncryptionStatus":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PortEncryptionStatus to be of type string, got %T instead", value)
}
sv.PortEncryptionStatus = ptr.String(jtv)
}
case "providerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ProviderName to be of type string, got %T instead", value)
}
sv.ProviderName = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
case "vlan":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected VLAN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Vlan = int32(i64)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentConnectionList(v *[]types.Connection, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []types.Connection
if *v == nil {
cv = []types.Connection{}
} else {
cv = *v
}
for _, value := range shape {
var col types.Connection
destAddr := &col
if err := awsAwsjson11_deserializeDocumentConnection(&destAddr, value); err != nil {
return err
}
col = *destAddr
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentDirectConnectClientException(v **types.DirectConnectClientException, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.DirectConnectClientException
if *v == nil {
sv = &types.DirectConnectClientException{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "message":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value)
}
sv.Message = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentDirectConnectGateway(v **types.DirectConnectGateway, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.DirectConnectGateway
if *v == nil {
sv = &types.DirectConnectGateway{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "amazonSideAsn":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected LongAsn to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.AmazonSideAsn = ptr.Int64(i64)
}
case "directConnectGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected DirectConnectGatewayId to be of type string, got %T instead", value)
}
sv.DirectConnectGatewayId = ptr.String(jtv)
}
case "directConnectGatewayName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected DirectConnectGatewayName to be of type string, got %T instead", value)
}
sv.DirectConnectGatewayName = ptr.String(jtv)
}
case "directConnectGatewayState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected DirectConnectGatewayState to be of type string, got %T instead", value)
}
sv.DirectConnectGatewayState = types.DirectConnectGatewayState(jtv)
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "stateChangeError":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected StateChangeError to be of type string, got %T instead", value)
}
sv.StateChangeError = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentDirectConnectGatewayAssociation(v **types.DirectConnectGatewayAssociation, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.DirectConnectGatewayAssociation
if *v == nil {
sv = &types.DirectConnectGatewayAssociation{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "allowedPrefixesToDirectConnectGateway":
if err := awsAwsjson11_deserializeDocumentRouteFilterPrefixList(&sv.AllowedPrefixesToDirectConnectGateway, value); err != nil {
return err
}
case "associatedGateway":
if err := awsAwsjson11_deserializeDocumentAssociatedGateway(&sv.AssociatedGateway, value); err != nil {
return err
}
case "associationId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected DirectConnectGatewayAssociationId to be of type string, got %T instead", value)
}
sv.AssociationId = ptr.String(jtv)
}
case "associationState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected DirectConnectGatewayAssociationState to be of type string, got %T instead", value)
}
sv.AssociationState = types.DirectConnectGatewayAssociationState(jtv)
}
case "directConnectGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected DirectConnectGatewayId to be of type string, got %T instead", value)
}
sv.DirectConnectGatewayId = ptr.String(jtv)
}
case "directConnectGatewayOwnerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.DirectConnectGatewayOwnerAccount = ptr.String(jtv)
}
case "stateChangeError":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected StateChangeError to be of type string, got %T instead", value)
}
sv.StateChangeError = ptr.String(jtv)
}
case "virtualGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualGatewayId to be of type string, got %T instead", value)
}
sv.VirtualGatewayId = ptr.String(jtv)
}
case "virtualGatewayOwnerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.VirtualGatewayOwnerAccount = ptr.String(jtv)
}
case "virtualGatewayRegion":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualGatewayRegion to be of type string, got %T instead", value)
}
sv.VirtualGatewayRegion = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentDirectConnectGatewayAssociationList(v *[]types.DirectConnectGatewayAssociation, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []types.DirectConnectGatewayAssociation
if *v == nil {
cv = []types.DirectConnectGatewayAssociation{}
} else {
cv = *v
}
for _, value := range shape {
var col types.DirectConnectGatewayAssociation
destAddr := &col
if err := awsAwsjson11_deserializeDocumentDirectConnectGatewayAssociation(&destAddr, value); err != nil {
return err
}
col = *destAddr
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentDirectConnectGatewayAssociationProposal(v **types.DirectConnectGatewayAssociationProposal, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.DirectConnectGatewayAssociationProposal
if *v == nil {
sv = &types.DirectConnectGatewayAssociationProposal{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "associatedGateway":
if err := awsAwsjson11_deserializeDocumentAssociatedGateway(&sv.AssociatedGateway, value); err != nil {
return err
}
case "directConnectGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected DirectConnectGatewayId to be of type string, got %T instead", value)
}
sv.DirectConnectGatewayId = ptr.String(jtv)
}
case "directConnectGatewayOwnerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.DirectConnectGatewayOwnerAccount = ptr.String(jtv)
}
case "existingAllowedPrefixesToDirectConnectGateway":
if err := awsAwsjson11_deserializeDocumentRouteFilterPrefixList(&sv.ExistingAllowedPrefixesToDirectConnectGateway, value); err != nil {
return err
}
case "proposalId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected DirectConnectGatewayAssociationProposalId to be of type string, got %T instead", value)
}
sv.ProposalId = ptr.String(jtv)
}
case "proposalState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected DirectConnectGatewayAssociationProposalState to be of type string, got %T instead", value)
}
sv.ProposalState = types.DirectConnectGatewayAssociationProposalState(jtv)
}
case "requestedAllowedPrefixesToDirectConnectGateway":
if err := awsAwsjson11_deserializeDocumentRouteFilterPrefixList(&sv.RequestedAllowedPrefixesToDirectConnectGateway, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentDirectConnectGatewayAssociationProposalList(v *[]types.DirectConnectGatewayAssociationProposal, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []types.DirectConnectGatewayAssociationProposal
if *v == nil {
cv = []types.DirectConnectGatewayAssociationProposal{}
} else {
cv = *v
}
for _, value := range shape {
var col types.DirectConnectGatewayAssociationProposal
destAddr := &col
if err := awsAwsjson11_deserializeDocumentDirectConnectGatewayAssociationProposal(&destAddr, value); err != nil {
return err
}
col = *destAddr
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentDirectConnectGatewayAttachment(v **types.DirectConnectGatewayAttachment, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.DirectConnectGatewayAttachment
if *v == nil {
sv = &types.DirectConnectGatewayAttachment{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "attachmentState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected DirectConnectGatewayAttachmentState to be of type string, got %T instead", value)
}
sv.AttachmentState = types.DirectConnectGatewayAttachmentState(jtv)
}
case "attachmentType":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected DirectConnectGatewayAttachmentType to be of type string, got %T instead", value)
}
sv.AttachmentType = types.DirectConnectGatewayAttachmentType(jtv)
}
case "directConnectGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected DirectConnectGatewayId to be of type string, got %T instead", value)
}
sv.DirectConnectGatewayId = ptr.String(jtv)
}
case "stateChangeError":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected StateChangeError to be of type string, got %T instead", value)
}
sv.StateChangeError = ptr.String(jtv)
}
case "virtualInterfaceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceId to be of type string, got %T instead", value)
}
sv.VirtualInterfaceId = ptr.String(jtv)
}
case "virtualInterfaceOwnerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.VirtualInterfaceOwnerAccount = ptr.String(jtv)
}
case "virtualInterfaceRegion":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceRegion to be of type string, got %T instead", value)
}
sv.VirtualInterfaceRegion = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentDirectConnectGatewayAttachmentList(v *[]types.DirectConnectGatewayAttachment, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []types.DirectConnectGatewayAttachment
if *v == nil {
cv = []types.DirectConnectGatewayAttachment{}
} else {
cv = *v
}
for _, value := range shape {
var col types.DirectConnectGatewayAttachment
destAddr := &col
if err := awsAwsjson11_deserializeDocumentDirectConnectGatewayAttachment(&destAddr, value); err != nil {
return err
}
col = *destAddr
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentDirectConnectGatewayList(v *[]types.DirectConnectGateway, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []types.DirectConnectGateway
if *v == nil {
cv = []types.DirectConnectGateway{}
} else {
cv = *v
}
for _, value := range shape {
var col types.DirectConnectGateway
destAddr := &col
if err := awsAwsjson11_deserializeDocumentDirectConnectGateway(&destAddr, value); err != nil {
return err
}
col = *destAddr
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentDirectConnectServerException(v **types.DirectConnectServerException, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.DirectConnectServerException
if *v == nil {
sv = &types.DirectConnectServerException{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "message":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value)
}
sv.Message = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentDuplicateTagKeysException(v **types.DuplicateTagKeysException, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.DuplicateTagKeysException
if *v == nil {
sv = &types.DuplicateTagKeysException{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "message":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value)
}
sv.Message = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentInterconnect(v **types.Interconnect, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.Interconnect
if *v == nil {
sv = &types.Interconnect{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "awsDevice":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDevice to be of type string, got %T instead", value)
}
sv.AwsDevice = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "bandwidth":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Bandwidth to be of type string, got %T instead", value)
}
sv.Bandwidth = ptr.String(jtv)
}
case "hasLogicalRedundancy":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected HasLogicalRedundancy to be of type string, got %T instead", value)
}
sv.HasLogicalRedundancy = types.HasLogicalRedundancy(jtv)
}
case "interconnectId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected InterconnectId to be of type string, got %T instead", value)
}
sv.InterconnectId = ptr.String(jtv)
}
case "interconnectName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected InterconnectName to be of type string, got %T instead", value)
}
sv.InterconnectName = ptr.String(jtv)
}
case "interconnectState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected InterconnectState to be of type string, got %T instead", value)
}
sv.InterconnectState = types.InterconnectState(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "lagId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagId to be of type string, got %T instead", value)
}
sv.LagId = ptr.String(jtv)
}
case "loaIssueTime":
if value != nil {
switch jtv := value.(type) {
case json.Number:
f64, err := jtv.Float64()
if err != nil {
return err
}
sv.LoaIssueTime = ptr.Time(smithytime.ParseEpochSeconds(f64))
default:
return fmt.Errorf("expected LoaIssueTime to be a JSON Number, got %T instead", value)
}
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "providerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ProviderName to be of type string, got %T instead", value)
}
sv.ProviderName = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentInterconnectList(v *[]types.Interconnect, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []types.Interconnect
if *v == nil {
cv = []types.Interconnect{}
} else {
cv = *v
}
for _, value := range shape {
var col types.Interconnect
destAddr := &col
if err := awsAwsjson11_deserializeDocumentInterconnect(&destAddr, value); err != nil {
return err
}
col = *destAddr
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentLag(v **types.Lag, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.Lag
if *v == nil {
sv = &types.Lag{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "allowsHostedConnections":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected BooleanFlag to be of type *bool, got %T instead", value)
}
sv.AllowsHostedConnections = jtv
}
case "awsDevice":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDevice to be of type string, got %T instead", value)
}
sv.AwsDevice = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "connections":
if err := awsAwsjson11_deserializeDocumentConnectionList(&sv.Connections, value); err != nil {
return err
}
case "connectionsBandwidth":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Bandwidth to be of type string, got %T instead", value)
}
sv.ConnectionsBandwidth = ptr.String(jtv)
}
case "encryptionMode":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EncryptionMode to be of type string, got %T instead", value)
}
sv.EncryptionMode = ptr.String(jtv)
}
case "hasLogicalRedundancy":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected HasLogicalRedundancy to be of type string, got %T instead", value)
}
sv.HasLogicalRedundancy = types.HasLogicalRedundancy(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "lagId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagId to be of type string, got %T instead", value)
}
sv.LagId = ptr.String(jtv)
}
case "lagName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagName to be of type string, got %T instead", value)
}
sv.LagName = ptr.String(jtv)
}
case "lagState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagState to be of type string, got %T instead", value)
}
sv.LagState = types.LagState(jtv)
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "macSecCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected MacSecCapable to be of type *bool, got %T instead", value)
}
sv.MacSecCapable = ptr.Bool(jtv)
}
case "macSecKeys":
if err := awsAwsjson11_deserializeDocumentMacSecKeyList(&sv.MacSecKeys, value); err != nil {
return err
}
case "minimumLinks":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected Count to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.MinimumLinks = int32(i64)
}
case "numberOfConnections":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected Count to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.NumberOfConnections = int32(i64)
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "providerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ProviderName to be of type string, got %T instead", value)
}
sv.ProviderName = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentLagList(v *[]types.Lag, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []types.Lag
if *v == nil {
cv = []types.Lag{}
} else {
cv = *v
}
for _, value := range shape {
var col types.Lag
destAddr := &col
if err := awsAwsjson11_deserializeDocumentLag(&destAddr, value); err != nil {
return err
}
col = *destAddr
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentLoa(v **types.Loa, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.Loa
if *v == nil {
sv = &types.Loa{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "loaContent":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LoaContent to be []byte, got %T instead", value)
}
dv, err := base64.StdEncoding.DecodeString(jtv)
if err != nil {
return fmt.Errorf("failed to base64 decode LoaContent, %w", err)
}
sv.LoaContent = dv
}
case "loaContentType":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LoaContentType to be of type string, got %T instead", value)
}
sv.LoaContentType = types.LoaContentType(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentLocation(v **types.Location, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.Location
if *v == nil {
sv = &types.Location{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "availableMacSecPortSpeeds":
if err := awsAwsjson11_deserializeDocumentAvailableMacSecPortSpeeds(&sv.AvailableMacSecPortSpeeds, value); err != nil {
return err
}
case "availablePortSpeeds":
if err := awsAwsjson11_deserializeDocumentAvailablePortSpeeds(&sv.AvailablePortSpeeds, value); err != nil {
return err
}
case "availableProviders":
if err := awsAwsjson11_deserializeDocumentProviderList(&sv.AvailableProviders, value); err != nil {
return err
}
case "locationCode":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.LocationCode = ptr.String(jtv)
}
case "locationName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationName to be of type string, got %T instead", value)
}
sv.LocationName = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentLocationList(v *[]types.Location, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []types.Location
if *v == nil {
cv = []types.Location{}
} else {
cv = *v
}
for _, value := range shape {
var col types.Location
destAddr := &col
if err := awsAwsjson11_deserializeDocumentLocation(&destAddr, value); err != nil {
return err
}
col = *destAddr
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentMacSecKey(v **types.MacSecKey, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.MacSecKey
if *v == nil {
sv = &types.MacSecKey{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "ckn":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Ckn to be of type string, got %T instead", value)
}
sv.Ckn = ptr.String(jtv)
}
case "secretARN":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected SecretARN to be of type string, got %T instead", value)
}
sv.SecretARN = ptr.String(jtv)
}
case "startOn":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected StartOnDate to be of type string, got %T instead", value)
}
sv.StartOn = ptr.String(jtv)
}
case "state":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected State to be of type string, got %T instead", value)
}
sv.State = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentMacSecKeyList(v *[]types.MacSecKey, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []types.MacSecKey
if *v == nil {
cv = []types.MacSecKey{}
} else {
cv = *v
}
for _, value := range shape {
var col types.MacSecKey
destAddr := &col
if err := awsAwsjson11_deserializeDocumentMacSecKey(&destAddr, value); err != nil {
return err
}
col = *destAddr
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentProviderList(v *[]string, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []string
if *v == nil {
cv = []string{}
} else {
cv = *v
}
for _, value := range shape {
var col string
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ProviderName to be of type string, got %T instead", value)
}
col = jtv
}
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentResourceTag(v **types.ResourceTag, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.ResourceTag
if *v == nil {
sv = &types.ResourceTag{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "resourceArn":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ResourceArn to be of type string, got %T instead", value)
}
sv.ResourceArn = ptr.String(jtv)
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentResourceTagList(v *[]types.ResourceTag, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []types.ResourceTag
if *v == nil {
cv = []types.ResourceTag{}
} else {
cv = *v
}
for _, value := range shape {
var col types.ResourceTag
destAddr := &col
if err := awsAwsjson11_deserializeDocumentResourceTag(&destAddr, value); err != nil {
return err
}
col = *destAddr
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentRouteFilterPrefix(v **types.RouteFilterPrefix, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.RouteFilterPrefix
if *v == nil {
sv = &types.RouteFilterPrefix{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "cidr":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected CIDR to be of type string, got %T instead", value)
}
sv.Cidr = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentRouteFilterPrefixList(v *[]types.RouteFilterPrefix, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []types.RouteFilterPrefix
if *v == nil {
cv = []types.RouteFilterPrefix{}
} else {
cv = *v
}
for _, value := range shape {
var col types.RouteFilterPrefix
destAddr := &col
if err := awsAwsjson11_deserializeDocumentRouteFilterPrefix(&destAddr, value); err != nil {
return err
}
col = *destAddr
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentTag(v **types.Tag, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.Tag
if *v == nil {
sv = &types.Tag{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "key":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected TagKey to be of type string, got %T instead", value)
}
sv.Key = ptr.String(jtv)
}
case "value":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected TagValue to be of type string, got %T instead", value)
}
sv.Value = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentTagList(v *[]types.Tag, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []types.Tag
if *v == nil {
cv = []types.Tag{}
} else {
cv = *v
}
for _, value := range shape {
var col types.Tag
destAddr := &col
if err := awsAwsjson11_deserializeDocumentTag(&destAddr, value); err != nil {
return err
}
col = *destAddr
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentTooManyTagsException(v **types.TooManyTagsException, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.TooManyTagsException
if *v == nil {
sv = &types.TooManyTagsException{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "message":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value)
}
sv.Message = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentVirtualGateway(v **types.VirtualGateway, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.VirtualGateway
if *v == nil {
sv = &types.VirtualGateway{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "virtualGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualGatewayId to be of type string, got %T instead", value)
}
sv.VirtualGatewayId = ptr.String(jtv)
}
case "virtualGatewayState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualGatewayState to be of type string, got %T instead", value)
}
sv.VirtualGatewayState = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentVirtualGatewayList(v *[]types.VirtualGateway, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []types.VirtualGateway
if *v == nil {
cv = []types.VirtualGateway{}
} else {
cv = *v
}
for _, value := range shape {
var col types.VirtualGateway
destAddr := &col
if err := awsAwsjson11_deserializeDocumentVirtualGateway(&destAddr, value); err != nil {
return err
}
col = *destAddr
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentVirtualInterface(v **types.VirtualInterface, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.VirtualInterface
if *v == nil {
sv = &types.VirtualInterface{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "addressFamily":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AddressFamily to be of type string, got %T instead", value)
}
sv.AddressFamily = types.AddressFamily(jtv)
}
case "amazonAddress":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AmazonAddress to be of type string, got %T instead", value)
}
sv.AmazonAddress = ptr.String(jtv)
}
case "amazonSideAsn":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected LongAsn to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.AmazonSideAsn = ptr.Int64(i64)
}
case "asn":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected ASN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Asn = int32(i64)
}
case "authKey":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected BGPAuthKey to be of type string, got %T instead", value)
}
sv.AuthKey = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "bgpPeers":
if err := awsAwsjson11_deserializeDocumentBGPPeerList(&sv.BgpPeers, value); err != nil {
return err
}
case "connectionId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionId to be of type string, got %T instead", value)
}
sv.ConnectionId = ptr.String(jtv)
}
case "customerAddress":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected CustomerAddress to be of type string, got %T instead", value)
}
sv.CustomerAddress = ptr.String(jtv)
}
case "customerRouterConfig":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected RouterConfig to be of type string, got %T instead", value)
}
sv.CustomerRouterConfig = ptr.String(jtv)
}
case "directConnectGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected DirectConnectGatewayId to be of type string, got %T instead", value)
}
sv.DirectConnectGatewayId = ptr.String(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "mtu":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected MTU to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Mtu = ptr.Int32(int32(i64))
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "routeFilterPrefixes":
if err := awsAwsjson11_deserializeDocumentRouteFilterPrefixList(&sv.RouteFilterPrefixes, value); err != nil {
return err
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
case "virtualGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualGatewayId to be of type string, got %T instead", value)
}
sv.VirtualGatewayId = ptr.String(jtv)
}
case "virtualInterfaceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceId to be of type string, got %T instead", value)
}
sv.VirtualInterfaceId = ptr.String(jtv)
}
case "virtualInterfaceName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceName to be of type string, got %T instead", value)
}
sv.VirtualInterfaceName = ptr.String(jtv)
}
case "virtualInterfaceState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceState to be of type string, got %T instead", value)
}
sv.VirtualInterfaceState = types.VirtualInterfaceState(jtv)
}
case "virtualInterfaceType":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceType to be of type string, got %T instead", value)
}
sv.VirtualInterfaceType = ptr.String(jtv)
}
case "vlan":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected VLAN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Vlan = int32(i64)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentVirtualInterfaceList(v *[]types.VirtualInterface, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []types.VirtualInterface
if *v == nil {
cv = []types.VirtualInterface{}
} else {
cv = *v
}
for _, value := range shape {
var col types.VirtualInterface
destAddr := &col
if err := awsAwsjson11_deserializeDocumentVirtualInterface(&destAddr, value); err != nil {
return err
}
col = *destAddr
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentVirtualInterfaceTestHistory(v **types.VirtualInterfaceTestHistory, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.VirtualInterfaceTestHistory
if *v == nil {
sv = &types.VirtualInterfaceTestHistory{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "bgpPeers":
if err := awsAwsjson11_deserializeDocumentBGPPeerIdList(&sv.BgpPeers, value); err != nil {
return err
}
case "endTime":
if value != nil {
switch jtv := value.(type) {
case json.Number:
f64, err := jtv.Float64()
if err != nil {
return err
}
sv.EndTime = ptr.Time(smithytime.ParseEpochSeconds(f64))
default:
return fmt.Errorf("expected EndTime to be a JSON Number, got %T instead", value)
}
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "startTime":
if value != nil {
switch jtv := value.(type) {
case json.Number:
f64, err := jtv.Float64()
if err != nil {
return err
}
sv.StartTime = ptr.Time(smithytime.ParseEpochSeconds(f64))
default:
return fmt.Errorf("expected StartTime to be a JSON Number, got %T instead", value)
}
}
case "status":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected FailureTestHistoryStatus to be of type string, got %T instead", value)
}
sv.Status = ptr.String(jtv)
}
case "testDurationInMinutes":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected TestDuration to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.TestDurationInMinutes = ptr.Int32(int32(i64))
}
case "testId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected TestId to be of type string, got %T instead", value)
}
sv.TestId = ptr.String(jtv)
}
case "virtualInterfaceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceId to be of type string, got %T instead", value)
}
sv.VirtualInterfaceId = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentVirtualInterfaceTestHistoryList(v *[]types.VirtualInterfaceTestHistory, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []types.VirtualInterfaceTestHistory
if *v == nil {
cv = []types.VirtualInterfaceTestHistory{}
} else {
cv = *v
}
for _, value := range shape {
var col types.VirtualInterfaceTestHistory
destAddr := &col
if err := awsAwsjson11_deserializeDocumentVirtualInterfaceTestHistory(&destAddr, value); err != nil {
return err
}
col = *destAddr
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeOpDocumentAcceptDirectConnectGatewayAssociationProposalOutput(v **AcceptDirectConnectGatewayAssociationProposalOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *AcceptDirectConnectGatewayAssociationProposalOutput
if *v == nil {
sv = &AcceptDirectConnectGatewayAssociationProposalOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "directConnectGatewayAssociation":
if err := awsAwsjson11_deserializeDocumentDirectConnectGatewayAssociation(&sv.DirectConnectGatewayAssociation, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentAllocateConnectionOnInterconnectOutput(v **AllocateConnectionOnInterconnectOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *AllocateConnectionOnInterconnectOutput
if *v == nil {
sv = &AllocateConnectionOnInterconnectOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "awsDevice":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDevice to be of type string, got %T instead", value)
}
sv.AwsDevice = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "bandwidth":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Bandwidth to be of type string, got %T instead", value)
}
sv.Bandwidth = ptr.String(jtv)
}
case "connectionId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionId to be of type string, got %T instead", value)
}
sv.ConnectionId = ptr.String(jtv)
}
case "connectionName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionName to be of type string, got %T instead", value)
}
sv.ConnectionName = ptr.String(jtv)
}
case "connectionState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionState to be of type string, got %T instead", value)
}
sv.ConnectionState = types.ConnectionState(jtv)
}
case "encryptionMode":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EncryptionMode to be of type string, got %T instead", value)
}
sv.EncryptionMode = ptr.String(jtv)
}
case "hasLogicalRedundancy":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected HasLogicalRedundancy to be of type string, got %T instead", value)
}
sv.HasLogicalRedundancy = types.HasLogicalRedundancy(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "lagId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagId to be of type string, got %T instead", value)
}
sv.LagId = ptr.String(jtv)
}
case "loaIssueTime":
if value != nil {
switch jtv := value.(type) {
case json.Number:
f64, err := jtv.Float64()
if err != nil {
return err
}
sv.LoaIssueTime = ptr.Time(smithytime.ParseEpochSeconds(f64))
default:
return fmt.Errorf("expected LoaIssueTime to be a JSON Number, got %T instead", value)
}
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "macSecCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected MacSecCapable to be of type *bool, got %T instead", value)
}
sv.MacSecCapable = ptr.Bool(jtv)
}
case "macSecKeys":
if err := awsAwsjson11_deserializeDocumentMacSecKeyList(&sv.MacSecKeys, value); err != nil {
return err
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "partnerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PartnerName to be of type string, got %T instead", value)
}
sv.PartnerName = ptr.String(jtv)
}
case "portEncryptionStatus":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PortEncryptionStatus to be of type string, got %T instead", value)
}
sv.PortEncryptionStatus = ptr.String(jtv)
}
case "providerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ProviderName to be of type string, got %T instead", value)
}
sv.ProviderName = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
case "vlan":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected VLAN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Vlan = int32(i64)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentAllocateHostedConnectionOutput(v **AllocateHostedConnectionOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *AllocateHostedConnectionOutput
if *v == nil {
sv = &AllocateHostedConnectionOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "awsDevice":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDevice to be of type string, got %T instead", value)
}
sv.AwsDevice = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "bandwidth":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Bandwidth to be of type string, got %T instead", value)
}
sv.Bandwidth = ptr.String(jtv)
}
case "connectionId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionId to be of type string, got %T instead", value)
}
sv.ConnectionId = ptr.String(jtv)
}
case "connectionName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionName to be of type string, got %T instead", value)
}
sv.ConnectionName = ptr.String(jtv)
}
case "connectionState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionState to be of type string, got %T instead", value)
}
sv.ConnectionState = types.ConnectionState(jtv)
}
case "encryptionMode":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EncryptionMode to be of type string, got %T instead", value)
}
sv.EncryptionMode = ptr.String(jtv)
}
case "hasLogicalRedundancy":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected HasLogicalRedundancy to be of type string, got %T instead", value)
}
sv.HasLogicalRedundancy = types.HasLogicalRedundancy(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "lagId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagId to be of type string, got %T instead", value)
}
sv.LagId = ptr.String(jtv)
}
case "loaIssueTime":
if value != nil {
switch jtv := value.(type) {
case json.Number:
f64, err := jtv.Float64()
if err != nil {
return err
}
sv.LoaIssueTime = ptr.Time(smithytime.ParseEpochSeconds(f64))
default:
return fmt.Errorf("expected LoaIssueTime to be a JSON Number, got %T instead", value)
}
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "macSecCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected MacSecCapable to be of type *bool, got %T instead", value)
}
sv.MacSecCapable = ptr.Bool(jtv)
}
case "macSecKeys":
if err := awsAwsjson11_deserializeDocumentMacSecKeyList(&sv.MacSecKeys, value); err != nil {
return err
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "partnerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PartnerName to be of type string, got %T instead", value)
}
sv.PartnerName = ptr.String(jtv)
}
case "portEncryptionStatus":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PortEncryptionStatus to be of type string, got %T instead", value)
}
sv.PortEncryptionStatus = ptr.String(jtv)
}
case "providerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ProviderName to be of type string, got %T instead", value)
}
sv.ProviderName = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
case "vlan":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected VLAN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Vlan = int32(i64)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentAllocatePrivateVirtualInterfaceOutput(v **AllocatePrivateVirtualInterfaceOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *AllocatePrivateVirtualInterfaceOutput
if *v == nil {
sv = &AllocatePrivateVirtualInterfaceOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "addressFamily":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AddressFamily to be of type string, got %T instead", value)
}
sv.AddressFamily = types.AddressFamily(jtv)
}
case "amazonAddress":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AmazonAddress to be of type string, got %T instead", value)
}
sv.AmazonAddress = ptr.String(jtv)
}
case "amazonSideAsn":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected LongAsn to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.AmazonSideAsn = ptr.Int64(i64)
}
case "asn":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected ASN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Asn = int32(i64)
}
case "authKey":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected BGPAuthKey to be of type string, got %T instead", value)
}
sv.AuthKey = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "bgpPeers":
if err := awsAwsjson11_deserializeDocumentBGPPeerList(&sv.BgpPeers, value); err != nil {
return err
}
case "connectionId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionId to be of type string, got %T instead", value)
}
sv.ConnectionId = ptr.String(jtv)
}
case "customerAddress":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected CustomerAddress to be of type string, got %T instead", value)
}
sv.CustomerAddress = ptr.String(jtv)
}
case "customerRouterConfig":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected RouterConfig to be of type string, got %T instead", value)
}
sv.CustomerRouterConfig = ptr.String(jtv)
}
case "directConnectGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected DirectConnectGatewayId to be of type string, got %T instead", value)
}
sv.DirectConnectGatewayId = ptr.String(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "mtu":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected MTU to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Mtu = ptr.Int32(int32(i64))
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "routeFilterPrefixes":
if err := awsAwsjson11_deserializeDocumentRouteFilterPrefixList(&sv.RouteFilterPrefixes, value); err != nil {
return err
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
case "virtualGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualGatewayId to be of type string, got %T instead", value)
}
sv.VirtualGatewayId = ptr.String(jtv)
}
case "virtualInterfaceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceId to be of type string, got %T instead", value)
}
sv.VirtualInterfaceId = ptr.String(jtv)
}
case "virtualInterfaceName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceName to be of type string, got %T instead", value)
}
sv.VirtualInterfaceName = ptr.String(jtv)
}
case "virtualInterfaceState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceState to be of type string, got %T instead", value)
}
sv.VirtualInterfaceState = types.VirtualInterfaceState(jtv)
}
case "virtualInterfaceType":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceType to be of type string, got %T instead", value)
}
sv.VirtualInterfaceType = ptr.String(jtv)
}
case "vlan":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected VLAN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Vlan = int32(i64)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentAllocatePublicVirtualInterfaceOutput(v **AllocatePublicVirtualInterfaceOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *AllocatePublicVirtualInterfaceOutput
if *v == nil {
sv = &AllocatePublicVirtualInterfaceOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "addressFamily":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AddressFamily to be of type string, got %T instead", value)
}
sv.AddressFamily = types.AddressFamily(jtv)
}
case "amazonAddress":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AmazonAddress to be of type string, got %T instead", value)
}
sv.AmazonAddress = ptr.String(jtv)
}
case "amazonSideAsn":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected LongAsn to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.AmazonSideAsn = ptr.Int64(i64)
}
case "asn":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected ASN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Asn = int32(i64)
}
case "authKey":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected BGPAuthKey to be of type string, got %T instead", value)
}
sv.AuthKey = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "bgpPeers":
if err := awsAwsjson11_deserializeDocumentBGPPeerList(&sv.BgpPeers, value); err != nil {
return err
}
case "connectionId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionId to be of type string, got %T instead", value)
}
sv.ConnectionId = ptr.String(jtv)
}
case "customerAddress":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected CustomerAddress to be of type string, got %T instead", value)
}
sv.CustomerAddress = ptr.String(jtv)
}
case "customerRouterConfig":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected RouterConfig to be of type string, got %T instead", value)
}
sv.CustomerRouterConfig = ptr.String(jtv)
}
case "directConnectGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected DirectConnectGatewayId to be of type string, got %T instead", value)
}
sv.DirectConnectGatewayId = ptr.String(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "mtu":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected MTU to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Mtu = ptr.Int32(int32(i64))
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "routeFilterPrefixes":
if err := awsAwsjson11_deserializeDocumentRouteFilterPrefixList(&sv.RouteFilterPrefixes, value); err != nil {
return err
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
case "virtualGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualGatewayId to be of type string, got %T instead", value)
}
sv.VirtualGatewayId = ptr.String(jtv)
}
case "virtualInterfaceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceId to be of type string, got %T instead", value)
}
sv.VirtualInterfaceId = ptr.String(jtv)
}
case "virtualInterfaceName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceName to be of type string, got %T instead", value)
}
sv.VirtualInterfaceName = ptr.String(jtv)
}
case "virtualInterfaceState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceState to be of type string, got %T instead", value)
}
sv.VirtualInterfaceState = types.VirtualInterfaceState(jtv)
}
case "virtualInterfaceType":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceType to be of type string, got %T instead", value)
}
sv.VirtualInterfaceType = ptr.String(jtv)
}
case "vlan":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected VLAN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Vlan = int32(i64)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentAllocateTransitVirtualInterfaceOutput(v **AllocateTransitVirtualInterfaceOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *AllocateTransitVirtualInterfaceOutput
if *v == nil {
sv = &AllocateTransitVirtualInterfaceOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "virtualInterface":
if err := awsAwsjson11_deserializeDocumentVirtualInterface(&sv.VirtualInterface, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentAssociateConnectionWithLagOutput(v **AssociateConnectionWithLagOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *AssociateConnectionWithLagOutput
if *v == nil {
sv = &AssociateConnectionWithLagOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "awsDevice":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDevice to be of type string, got %T instead", value)
}
sv.AwsDevice = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "bandwidth":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Bandwidth to be of type string, got %T instead", value)
}
sv.Bandwidth = ptr.String(jtv)
}
case "connectionId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionId to be of type string, got %T instead", value)
}
sv.ConnectionId = ptr.String(jtv)
}
case "connectionName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionName to be of type string, got %T instead", value)
}
sv.ConnectionName = ptr.String(jtv)
}
case "connectionState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionState to be of type string, got %T instead", value)
}
sv.ConnectionState = types.ConnectionState(jtv)
}
case "encryptionMode":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EncryptionMode to be of type string, got %T instead", value)
}
sv.EncryptionMode = ptr.String(jtv)
}
case "hasLogicalRedundancy":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected HasLogicalRedundancy to be of type string, got %T instead", value)
}
sv.HasLogicalRedundancy = types.HasLogicalRedundancy(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "lagId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagId to be of type string, got %T instead", value)
}
sv.LagId = ptr.String(jtv)
}
case "loaIssueTime":
if value != nil {
switch jtv := value.(type) {
case json.Number:
f64, err := jtv.Float64()
if err != nil {
return err
}
sv.LoaIssueTime = ptr.Time(smithytime.ParseEpochSeconds(f64))
default:
return fmt.Errorf("expected LoaIssueTime to be a JSON Number, got %T instead", value)
}
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "macSecCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected MacSecCapable to be of type *bool, got %T instead", value)
}
sv.MacSecCapable = ptr.Bool(jtv)
}
case "macSecKeys":
if err := awsAwsjson11_deserializeDocumentMacSecKeyList(&sv.MacSecKeys, value); err != nil {
return err
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "partnerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PartnerName to be of type string, got %T instead", value)
}
sv.PartnerName = ptr.String(jtv)
}
case "portEncryptionStatus":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PortEncryptionStatus to be of type string, got %T instead", value)
}
sv.PortEncryptionStatus = ptr.String(jtv)
}
case "providerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ProviderName to be of type string, got %T instead", value)
}
sv.ProviderName = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
case "vlan":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected VLAN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Vlan = int32(i64)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentAssociateHostedConnectionOutput(v **AssociateHostedConnectionOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *AssociateHostedConnectionOutput
if *v == nil {
sv = &AssociateHostedConnectionOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "awsDevice":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDevice to be of type string, got %T instead", value)
}
sv.AwsDevice = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "bandwidth":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Bandwidth to be of type string, got %T instead", value)
}
sv.Bandwidth = ptr.String(jtv)
}
case "connectionId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionId to be of type string, got %T instead", value)
}
sv.ConnectionId = ptr.String(jtv)
}
case "connectionName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionName to be of type string, got %T instead", value)
}
sv.ConnectionName = ptr.String(jtv)
}
case "connectionState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionState to be of type string, got %T instead", value)
}
sv.ConnectionState = types.ConnectionState(jtv)
}
case "encryptionMode":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EncryptionMode to be of type string, got %T instead", value)
}
sv.EncryptionMode = ptr.String(jtv)
}
case "hasLogicalRedundancy":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected HasLogicalRedundancy to be of type string, got %T instead", value)
}
sv.HasLogicalRedundancy = types.HasLogicalRedundancy(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "lagId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagId to be of type string, got %T instead", value)
}
sv.LagId = ptr.String(jtv)
}
case "loaIssueTime":
if value != nil {
switch jtv := value.(type) {
case json.Number:
f64, err := jtv.Float64()
if err != nil {
return err
}
sv.LoaIssueTime = ptr.Time(smithytime.ParseEpochSeconds(f64))
default:
return fmt.Errorf("expected LoaIssueTime to be a JSON Number, got %T instead", value)
}
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "macSecCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected MacSecCapable to be of type *bool, got %T instead", value)
}
sv.MacSecCapable = ptr.Bool(jtv)
}
case "macSecKeys":
if err := awsAwsjson11_deserializeDocumentMacSecKeyList(&sv.MacSecKeys, value); err != nil {
return err
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "partnerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PartnerName to be of type string, got %T instead", value)
}
sv.PartnerName = ptr.String(jtv)
}
case "portEncryptionStatus":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PortEncryptionStatus to be of type string, got %T instead", value)
}
sv.PortEncryptionStatus = ptr.String(jtv)
}
case "providerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ProviderName to be of type string, got %T instead", value)
}
sv.ProviderName = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
case "vlan":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected VLAN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Vlan = int32(i64)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentAssociateMacSecKeyOutput(v **AssociateMacSecKeyOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *AssociateMacSecKeyOutput
if *v == nil {
sv = &AssociateMacSecKeyOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "connectionId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionId to be of type string, got %T instead", value)
}
sv.ConnectionId = ptr.String(jtv)
}
case "macSecKeys":
if err := awsAwsjson11_deserializeDocumentMacSecKeyList(&sv.MacSecKeys, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentAssociateVirtualInterfaceOutput(v **AssociateVirtualInterfaceOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *AssociateVirtualInterfaceOutput
if *v == nil {
sv = &AssociateVirtualInterfaceOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "addressFamily":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AddressFamily to be of type string, got %T instead", value)
}
sv.AddressFamily = types.AddressFamily(jtv)
}
case "amazonAddress":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AmazonAddress to be of type string, got %T instead", value)
}
sv.AmazonAddress = ptr.String(jtv)
}
case "amazonSideAsn":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected LongAsn to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.AmazonSideAsn = ptr.Int64(i64)
}
case "asn":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected ASN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Asn = int32(i64)
}
case "authKey":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected BGPAuthKey to be of type string, got %T instead", value)
}
sv.AuthKey = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "bgpPeers":
if err := awsAwsjson11_deserializeDocumentBGPPeerList(&sv.BgpPeers, value); err != nil {
return err
}
case "connectionId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionId to be of type string, got %T instead", value)
}
sv.ConnectionId = ptr.String(jtv)
}
case "customerAddress":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected CustomerAddress to be of type string, got %T instead", value)
}
sv.CustomerAddress = ptr.String(jtv)
}
case "customerRouterConfig":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected RouterConfig to be of type string, got %T instead", value)
}
sv.CustomerRouterConfig = ptr.String(jtv)
}
case "directConnectGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected DirectConnectGatewayId to be of type string, got %T instead", value)
}
sv.DirectConnectGatewayId = ptr.String(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "mtu":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected MTU to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Mtu = ptr.Int32(int32(i64))
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "routeFilterPrefixes":
if err := awsAwsjson11_deserializeDocumentRouteFilterPrefixList(&sv.RouteFilterPrefixes, value); err != nil {
return err
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
case "virtualGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualGatewayId to be of type string, got %T instead", value)
}
sv.VirtualGatewayId = ptr.String(jtv)
}
case "virtualInterfaceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceId to be of type string, got %T instead", value)
}
sv.VirtualInterfaceId = ptr.String(jtv)
}
case "virtualInterfaceName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceName to be of type string, got %T instead", value)
}
sv.VirtualInterfaceName = ptr.String(jtv)
}
case "virtualInterfaceState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceState to be of type string, got %T instead", value)
}
sv.VirtualInterfaceState = types.VirtualInterfaceState(jtv)
}
case "virtualInterfaceType":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceType to be of type string, got %T instead", value)
}
sv.VirtualInterfaceType = ptr.String(jtv)
}
case "vlan":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected VLAN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Vlan = int32(i64)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentConfirmConnectionOutput(v **ConfirmConnectionOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *ConfirmConnectionOutput
if *v == nil {
sv = &ConfirmConnectionOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "connectionState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionState to be of type string, got %T instead", value)
}
sv.ConnectionState = types.ConnectionState(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentConfirmPrivateVirtualInterfaceOutput(v **ConfirmPrivateVirtualInterfaceOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *ConfirmPrivateVirtualInterfaceOutput
if *v == nil {
sv = &ConfirmPrivateVirtualInterfaceOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "virtualInterfaceState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceState to be of type string, got %T instead", value)
}
sv.VirtualInterfaceState = types.VirtualInterfaceState(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentConfirmPublicVirtualInterfaceOutput(v **ConfirmPublicVirtualInterfaceOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *ConfirmPublicVirtualInterfaceOutput
if *v == nil {
sv = &ConfirmPublicVirtualInterfaceOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "virtualInterfaceState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceState to be of type string, got %T instead", value)
}
sv.VirtualInterfaceState = types.VirtualInterfaceState(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentConfirmTransitVirtualInterfaceOutput(v **ConfirmTransitVirtualInterfaceOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *ConfirmTransitVirtualInterfaceOutput
if *v == nil {
sv = &ConfirmTransitVirtualInterfaceOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "virtualInterfaceState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceState to be of type string, got %T instead", value)
}
sv.VirtualInterfaceState = types.VirtualInterfaceState(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentCreateBGPPeerOutput(v **CreateBGPPeerOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *CreateBGPPeerOutput
if *v == nil {
sv = &CreateBGPPeerOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "virtualInterface":
if err := awsAwsjson11_deserializeDocumentVirtualInterface(&sv.VirtualInterface, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentCreateConnectionOutput(v **CreateConnectionOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *CreateConnectionOutput
if *v == nil {
sv = &CreateConnectionOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "awsDevice":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDevice to be of type string, got %T instead", value)
}
sv.AwsDevice = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "bandwidth":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Bandwidth to be of type string, got %T instead", value)
}
sv.Bandwidth = ptr.String(jtv)
}
case "connectionId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionId to be of type string, got %T instead", value)
}
sv.ConnectionId = ptr.String(jtv)
}
case "connectionName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionName to be of type string, got %T instead", value)
}
sv.ConnectionName = ptr.String(jtv)
}
case "connectionState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionState to be of type string, got %T instead", value)
}
sv.ConnectionState = types.ConnectionState(jtv)
}
case "encryptionMode":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EncryptionMode to be of type string, got %T instead", value)
}
sv.EncryptionMode = ptr.String(jtv)
}
case "hasLogicalRedundancy":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected HasLogicalRedundancy to be of type string, got %T instead", value)
}
sv.HasLogicalRedundancy = types.HasLogicalRedundancy(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "lagId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagId to be of type string, got %T instead", value)
}
sv.LagId = ptr.String(jtv)
}
case "loaIssueTime":
if value != nil {
switch jtv := value.(type) {
case json.Number:
f64, err := jtv.Float64()
if err != nil {
return err
}
sv.LoaIssueTime = ptr.Time(smithytime.ParseEpochSeconds(f64))
default:
return fmt.Errorf("expected LoaIssueTime to be a JSON Number, got %T instead", value)
}
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "macSecCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected MacSecCapable to be of type *bool, got %T instead", value)
}
sv.MacSecCapable = ptr.Bool(jtv)
}
case "macSecKeys":
if err := awsAwsjson11_deserializeDocumentMacSecKeyList(&sv.MacSecKeys, value); err != nil {
return err
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "partnerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PartnerName to be of type string, got %T instead", value)
}
sv.PartnerName = ptr.String(jtv)
}
case "portEncryptionStatus":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PortEncryptionStatus to be of type string, got %T instead", value)
}
sv.PortEncryptionStatus = ptr.String(jtv)
}
case "providerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ProviderName to be of type string, got %T instead", value)
}
sv.ProviderName = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
case "vlan":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected VLAN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Vlan = int32(i64)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentCreateDirectConnectGatewayAssociationOutput(v **CreateDirectConnectGatewayAssociationOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *CreateDirectConnectGatewayAssociationOutput
if *v == nil {
sv = &CreateDirectConnectGatewayAssociationOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "directConnectGatewayAssociation":
if err := awsAwsjson11_deserializeDocumentDirectConnectGatewayAssociation(&sv.DirectConnectGatewayAssociation, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentCreateDirectConnectGatewayAssociationProposalOutput(v **CreateDirectConnectGatewayAssociationProposalOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *CreateDirectConnectGatewayAssociationProposalOutput
if *v == nil {
sv = &CreateDirectConnectGatewayAssociationProposalOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "directConnectGatewayAssociationProposal":
if err := awsAwsjson11_deserializeDocumentDirectConnectGatewayAssociationProposal(&sv.DirectConnectGatewayAssociationProposal, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentCreateDirectConnectGatewayOutput(v **CreateDirectConnectGatewayOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *CreateDirectConnectGatewayOutput
if *v == nil {
sv = &CreateDirectConnectGatewayOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "directConnectGateway":
if err := awsAwsjson11_deserializeDocumentDirectConnectGateway(&sv.DirectConnectGateway, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentCreateInterconnectOutput(v **CreateInterconnectOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *CreateInterconnectOutput
if *v == nil {
sv = &CreateInterconnectOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "awsDevice":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDevice to be of type string, got %T instead", value)
}
sv.AwsDevice = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "bandwidth":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Bandwidth to be of type string, got %T instead", value)
}
sv.Bandwidth = ptr.String(jtv)
}
case "hasLogicalRedundancy":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected HasLogicalRedundancy to be of type string, got %T instead", value)
}
sv.HasLogicalRedundancy = types.HasLogicalRedundancy(jtv)
}
case "interconnectId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected InterconnectId to be of type string, got %T instead", value)
}
sv.InterconnectId = ptr.String(jtv)
}
case "interconnectName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected InterconnectName to be of type string, got %T instead", value)
}
sv.InterconnectName = ptr.String(jtv)
}
case "interconnectState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected InterconnectState to be of type string, got %T instead", value)
}
sv.InterconnectState = types.InterconnectState(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "lagId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagId to be of type string, got %T instead", value)
}
sv.LagId = ptr.String(jtv)
}
case "loaIssueTime":
if value != nil {
switch jtv := value.(type) {
case json.Number:
f64, err := jtv.Float64()
if err != nil {
return err
}
sv.LoaIssueTime = ptr.Time(smithytime.ParseEpochSeconds(f64))
default:
return fmt.Errorf("expected LoaIssueTime to be a JSON Number, got %T instead", value)
}
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "providerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ProviderName to be of type string, got %T instead", value)
}
sv.ProviderName = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentCreateLagOutput(v **CreateLagOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *CreateLagOutput
if *v == nil {
sv = &CreateLagOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "allowsHostedConnections":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected BooleanFlag to be of type *bool, got %T instead", value)
}
sv.AllowsHostedConnections = jtv
}
case "awsDevice":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDevice to be of type string, got %T instead", value)
}
sv.AwsDevice = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "connections":
if err := awsAwsjson11_deserializeDocumentConnectionList(&sv.Connections, value); err != nil {
return err
}
case "connectionsBandwidth":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Bandwidth to be of type string, got %T instead", value)
}
sv.ConnectionsBandwidth = ptr.String(jtv)
}
case "encryptionMode":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EncryptionMode to be of type string, got %T instead", value)
}
sv.EncryptionMode = ptr.String(jtv)
}
case "hasLogicalRedundancy":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected HasLogicalRedundancy to be of type string, got %T instead", value)
}
sv.HasLogicalRedundancy = types.HasLogicalRedundancy(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "lagId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagId to be of type string, got %T instead", value)
}
sv.LagId = ptr.String(jtv)
}
case "lagName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagName to be of type string, got %T instead", value)
}
sv.LagName = ptr.String(jtv)
}
case "lagState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagState to be of type string, got %T instead", value)
}
sv.LagState = types.LagState(jtv)
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "macSecCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected MacSecCapable to be of type *bool, got %T instead", value)
}
sv.MacSecCapable = ptr.Bool(jtv)
}
case "macSecKeys":
if err := awsAwsjson11_deserializeDocumentMacSecKeyList(&sv.MacSecKeys, value); err != nil {
return err
}
case "minimumLinks":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected Count to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.MinimumLinks = int32(i64)
}
case "numberOfConnections":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected Count to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.NumberOfConnections = int32(i64)
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "providerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ProviderName to be of type string, got %T instead", value)
}
sv.ProviderName = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentCreatePrivateVirtualInterfaceOutput(v **CreatePrivateVirtualInterfaceOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *CreatePrivateVirtualInterfaceOutput
if *v == nil {
sv = &CreatePrivateVirtualInterfaceOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "addressFamily":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AddressFamily to be of type string, got %T instead", value)
}
sv.AddressFamily = types.AddressFamily(jtv)
}
case "amazonAddress":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AmazonAddress to be of type string, got %T instead", value)
}
sv.AmazonAddress = ptr.String(jtv)
}
case "amazonSideAsn":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected LongAsn to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.AmazonSideAsn = ptr.Int64(i64)
}
case "asn":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected ASN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Asn = int32(i64)
}
case "authKey":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected BGPAuthKey to be of type string, got %T instead", value)
}
sv.AuthKey = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "bgpPeers":
if err := awsAwsjson11_deserializeDocumentBGPPeerList(&sv.BgpPeers, value); err != nil {
return err
}
case "connectionId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionId to be of type string, got %T instead", value)
}
sv.ConnectionId = ptr.String(jtv)
}
case "customerAddress":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected CustomerAddress to be of type string, got %T instead", value)
}
sv.CustomerAddress = ptr.String(jtv)
}
case "customerRouterConfig":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected RouterConfig to be of type string, got %T instead", value)
}
sv.CustomerRouterConfig = ptr.String(jtv)
}
case "directConnectGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected DirectConnectGatewayId to be of type string, got %T instead", value)
}
sv.DirectConnectGatewayId = ptr.String(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "mtu":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected MTU to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Mtu = ptr.Int32(int32(i64))
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "routeFilterPrefixes":
if err := awsAwsjson11_deserializeDocumentRouteFilterPrefixList(&sv.RouteFilterPrefixes, value); err != nil {
return err
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
case "virtualGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualGatewayId to be of type string, got %T instead", value)
}
sv.VirtualGatewayId = ptr.String(jtv)
}
case "virtualInterfaceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceId to be of type string, got %T instead", value)
}
sv.VirtualInterfaceId = ptr.String(jtv)
}
case "virtualInterfaceName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceName to be of type string, got %T instead", value)
}
sv.VirtualInterfaceName = ptr.String(jtv)
}
case "virtualInterfaceState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceState to be of type string, got %T instead", value)
}
sv.VirtualInterfaceState = types.VirtualInterfaceState(jtv)
}
case "virtualInterfaceType":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceType to be of type string, got %T instead", value)
}
sv.VirtualInterfaceType = ptr.String(jtv)
}
case "vlan":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected VLAN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Vlan = int32(i64)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentCreatePublicVirtualInterfaceOutput(v **CreatePublicVirtualInterfaceOutput, value interface{}) error |
func awsAwsjson11_deserializeOpDocumentCreateTransitVirtualInterfaceOutput(v **CreateTransitVirtualInterfaceOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *CreateTransitVirtualInterfaceOutput
if *v == nil {
sv = &CreateTransitVirtualInterfaceOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "virtualInterface":
if err := awsAwsjson11_deserializeDocumentVirtualInterface(&sv.VirtualInterface, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDeleteBGPPeerOutput(v **DeleteBGPPeerOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DeleteBGPPeerOutput
if *v == nil {
sv = &DeleteBGPPeerOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "virtualInterface":
if err := awsAwsjson11_deserializeDocumentVirtualInterface(&sv.VirtualInterface, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDeleteConnectionOutput(v **DeleteConnectionOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DeleteConnectionOutput
if *v == nil {
sv = &DeleteConnectionOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "awsDevice":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDevice to be of type string, got %T instead", value)
}
sv.AwsDevice = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "bandwidth":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Bandwidth to be of type string, got %T instead", value)
}
sv.Bandwidth = ptr.String(jtv)
}
case "connectionId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionId to be of type string, got %T instead", value)
}
sv.ConnectionId = ptr.String(jtv)
}
case "connectionName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionName to be of type string, got %T instead", value)
}
sv.ConnectionName = ptr.String(jtv)
}
case "connectionState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionState to be of type string, got %T instead", value)
}
sv.ConnectionState = types.ConnectionState(jtv)
}
case "encryptionMode":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EncryptionMode to be of type string, got %T instead", value)
}
sv.EncryptionMode = ptr.String(jtv)
}
case "hasLogicalRedundancy":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected HasLogicalRedundancy to be of type string, got %T instead", value)
}
sv.HasLogicalRedundancy = types.HasLogicalRedundancy(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "lagId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagId to be of type string, got %T instead", value)
}
sv.LagId = ptr.String(jtv)
}
case "loaIssueTime":
if value != nil {
switch jtv := value.(type) {
case json.Number:
f64, err := jtv.Float64()
if err != nil {
return err
}
sv.LoaIssueTime = ptr.Time(smithytime.ParseEpochSeconds(f64))
default:
return fmt.Errorf("expected LoaIssueTime to be a JSON Number, got %T instead", value)
}
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "macSecCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected MacSecCapable to be of type *bool, got %T instead", value)
}
sv.MacSecCapable = ptr.Bool(jtv)
}
case "macSecKeys":
if err := awsAwsjson11_deserializeDocumentMacSecKeyList(&sv.MacSecKeys, value); err != nil {
return err
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "partnerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PartnerName to be of type string, got %T instead", value)
}
sv.PartnerName = ptr.String(jtv)
}
case "portEncryptionStatus":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PortEncryptionStatus to be of type string, got %T instead", value)
}
sv.PortEncryptionStatus = ptr.String(jtv)
}
case "providerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ProviderName to be of type string, got %T instead", value)
}
sv.ProviderName = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
case "vlan":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected VLAN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Vlan = int32(i64)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDeleteDirectConnectGatewayAssociationOutput(v **DeleteDirectConnectGatewayAssociationOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DeleteDirectConnectGatewayAssociationOutput
if *v == nil {
sv = &DeleteDirectConnectGatewayAssociationOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "directConnectGatewayAssociation":
if err := awsAwsjson11_deserializeDocumentDirectConnectGatewayAssociation(&sv.DirectConnectGatewayAssociation, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDeleteDirectConnectGatewayAssociationProposalOutput(v **DeleteDirectConnectGatewayAssociationProposalOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DeleteDirectConnectGatewayAssociationProposalOutput
if *v == nil {
sv = &DeleteDirectConnectGatewayAssociationProposalOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "directConnectGatewayAssociationProposal":
if err := awsAwsjson11_deserializeDocumentDirectConnectGatewayAssociationProposal(&sv.DirectConnectGatewayAssociationProposal, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDeleteDirectConnectGatewayOutput(v **DeleteDirectConnectGatewayOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DeleteDirectConnectGatewayOutput
if *v == nil {
sv = &DeleteDirectConnectGatewayOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "directConnectGateway":
if err := awsAwsjson11_deserializeDocumentDirectConnectGateway(&sv.DirectConnectGateway, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDeleteInterconnectOutput(v **DeleteInterconnectOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DeleteInterconnectOutput
if *v == nil {
sv = &DeleteInterconnectOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "interconnectState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected InterconnectState to be of type string, got %T instead", value)
}
sv.InterconnectState = types.InterconnectState(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDeleteLagOutput(v **DeleteLagOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DeleteLagOutput
if *v == nil {
sv = &DeleteLagOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "allowsHostedConnections":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected BooleanFlag to be of type *bool, got %T instead", value)
}
sv.AllowsHostedConnections = jtv
}
case "awsDevice":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDevice to be of type string, got %T instead", value)
}
sv.AwsDevice = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "connections":
if err := awsAwsjson11_deserializeDocumentConnectionList(&sv.Connections, value); err != nil {
return err
}
case "connectionsBandwidth":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Bandwidth to be of type string, got %T instead", value)
}
sv.ConnectionsBandwidth = ptr.String(jtv)
}
case "encryptionMode":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EncryptionMode to be of type string, got %T instead", value)
}
sv.EncryptionMode = ptr.String(jtv)
}
case "hasLogicalRedundancy":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected HasLogicalRedundancy to be of type string, got %T instead", value)
}
sv.HasLogicalRedundancy = types.HasLogicalRedundancy(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "lagId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagId to be of type string, got %T instead", value)
}
sv.LagId = ptr.String(jtv)
}
case "lagName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagName to be of type string, got %T instead", value)
}
sv.LagName = ptr.String(jtv)
}
case "lagState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagState to be of type string, got %T instead", value)
}
sv.LagState = types.LagState(jtv)
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "macSecCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected MacSecCapable to be of type *bool, got %T instead", value)
}
sv.MacSecCapable = ptr.Bool(jtv)
}
case "macSecKeys":
if err := awsAwsjson11_deserializeDocumentMacSecKeyList(&sv.MacSecKeys, value); err != nil {
return err
}
case "minimumLinks":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected Count to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.MinimumLinks = int32(i64)
}
case "numberOfConnections":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected Count to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.NumberOfConnections = int32(i64)
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "providerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ProviderName to be of type string, got %T instead", value)
}
sv.ProviderName = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDeleteVirtualInterfaceOutput(v **DeleteVirtualInterfaceOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DeleteVirtualInterfaceOutput
if *v == nil {
sv = &DeleteVirtualInterfaceOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "virtualInterfaceState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceState to be of type string, got %T instead", value)
}
sv.VirtualInterfaceState = types.VirtualInterfaceState(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDescribeConnectionLoaOutput(v **DescribeConnectionLoaOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DescribeConnectionLoaOutput
if *v == nil {
sv = &DescribeConnectionLoaOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "loa":
if err := awsAwsjson11_deserializeDocumentLoa(&sv.Loa, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDescribeConnectionsOnInterconnectOutput(v **DescribeConnectionsOnInterconnectOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DescribeConnectionsOnInterconnectOutput
if *v == nil {
sv = &DescribeConnectionsOnInterconnectOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "connections":
if err := awsAwsjson11_deserializeDocumentConnectionList(&sv.Connections, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDescribeConnectionsOutput(v **DescribeConnectionsOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DescribeConnectionsOutput
if *v == nil {
sv = &DescribeConnectionsOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "connections":
if err := awsAwsjson11_deserializeDocumentConnectionList(&sv.Connections, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDescribeDirectConnectGatewayAssociationProposalsOutput(v **DescribeDirectConnectGatewayAssociationProposalsOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DescribeDirectConnectGatewayAssociationProposalsOutput
if *v == nil {
sv = &DescribeDirectConnectGatewayAssociationProposalsOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "directConnectGatewayAssociationProposals":
if err := awsAwsjson11_deserializeDocumentDirectConnectGatewayAssociationProposalList(&sv.DirectConnectGatewayAssociationProposals, value); err != nil {
return err
}
case "nextToken":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PaginationToken to be of type string, got %T instead", value)
}
sv.NextToken = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDescribeDirectConnectGatewayAssociationsOutput(v **DescribeDirectConnectGatewayAssociationsOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DescribeDirectConnectGatewayAssociationsOutput
if *v == nil {
sv = &DescribeDirectConnectGatewayAssociationsOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "directConnectGatewayAssociations":
if err := awsAwsjson11_deserializeDocumentDirectConnectGatewayAssociationList(&sv.DirectConnectGatewayAssociations, value); err != nil {
return err
}
case "nextToken":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PaginationToken to be of type string, got %T instead", value)
}
sv.NextToken = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDescribeDirectConnectGatewayAttachmentsOutput(v **DescribeDirectConnectGatewayAttachmentsOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DescribeDirectConnectGatewayAttachmentsOutput
if *v == nil {
sv = &DescribeDirectConnectGatewayAttachmentsOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "directConnectGatewayAttachments":
if err := awsAwsjson11_deserializeDocumentDirectConnectGatewayAttachmentList(&sv.DirectConnectGatewayAttachments, value); err != nil {
return err
}
case "nextToken":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PaginationToken to be of type string, got %T instead", value)
}
sv.NextToken = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDescribeDirectConnectGatewaysOutput(v **DescribeDirectConnectGatewaysOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DescribeDirectConnectGatewaysOutput
if *v == nil {
sv = &DescribeDirectConnectGatewaysOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "directConnectGateways":
if err := awsAwsjson11_deserializeDocumentDirectConnectGatewayList(&sv.DirectConnectGateways, value); err != nil {
return err
}
case "nextToken":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PaginationToken to be of type string, got %T instead", value)
}
sv.NextToken = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDescribeHostedConnectionsOutput(v **DescribeHostedConnectionsOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DescribeHostedConnectionsOutput
if *v == nil {
sv = &DescribeHostedConnectionsOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "connections":
if err := awsAwsjson11_deserializeDocumentConnectionList(&sv.Connections, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDescribeInterconnectLoaOutput(v **DescribeInterconnectLoaOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DescribeInterconnectLoaOutput
if *v == nil {
sv = &DescribeInterconnectLoaOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "loa":
if err := awsAwsjson11_deserializeDocumentLoa(&sv.Loa, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDescribeInterconnectsOutput(v **DescribeInterconnectsOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DescribeInterconnectsOutput
if *v == nil {
sv = &DescribeInterconnectsOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "interconnects":
if err := awsAwsjson11_deserializeDocumentInterconnectList(&sv.Interconnects, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDescribeLagsOutput(v **DescribeLagsOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DescribeLagsOutput
if *v == nil {
sv = &DescribeLagsOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "lags":
if err := awsAwsjson11_deserializeDocumentLagList(&sv.Lags, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDescribeLoaOutput(v **DescribeLoaOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DescribeLoaOutput
if *v == nil {
sv = &DescribeLoaOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "loaContent":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LoaContent to be []byte, got %T instead", value)
}
dv, err := base64.StdEncoding.DecodeString(jtv)
if err != nil {
return fmt.Errorf("failed to base64 decode LoaContent, %w", err)
}
sv.LoaContent = dv
}
case "loaContentType":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LoaContentType to be of type string, got %T instead", value)
}
sv.LoaContentType = types.LoaContentType(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDescribeLocationsOutput(v **DescribeLocationsOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DescribeLocationsOutput
if *v == nil {
sv = &DescribeLocationsOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "locations":
if err := awsAwsjson11_deserializeDocumentLocationList(&sv.Locations, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDescribeTagsOutput(v **DescribeTagsOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DescribeTagsOutput
if *v == nil {
sv = &DescribeTagsOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "resourceTags":
if err := awsAwsjson11_deserializeDocumentResourceTagList(&sv.ResourceTags, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDescribeVirtualGatewaysOutput(v **DescribeVirtualGatewaysOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DescribeVirtualGatewaysOutput
if *v == nil {
sv = &DescribeVirtualGatewaysOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "virtualGateways":
if err := awsAwsjson11_deserializeDocumentVirtualGatewayList(&sv.VirtualGateways, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDescribeVirtualInterfacesOutput(v **DescribeVirtualInterfacesOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DescribeVirtualInterfacesOutput
if *v == nil {
sv = &DescribeVirtualInterfacesOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "virtualInterfaces":
if err := awsAwsjson11_deserializeDocumentVirtualInterfaceList(&sv.VirtualInterfaces, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDisassociateConnectionFromLagOutput(v **DisassociateConnectionFromLagOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DisassociateConnectionFromLagOutput
if *v == nil {
sv = &DisassociateConnectionFromLagOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "awsDevice":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDevice to be of type string, got %T instead", value)
}
sv.AwsDevice = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "bandwidth":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Bandwidth to be of type string, got %T instead", value)
}
sv.Bandwidth = ptr.String(jtv)
}
case "connectionId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionId to be of type string, got %T instead", value)
}
sv.ConnectionId = ptr.String(jtv)
}
case "connectionName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionName to be of type string, got %T instead", value)
}
sv.ConnectionName = ptr.String(jtv)
}
case "connectionState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionState to be of type string, got %T instead", value)
}
sv.ConnectionState = types.ConnectionState(jtv)
}
case "encryptionMode":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EncryptionMode to be of type string, got %T instead", value)
}
sv.EncryptionMode = ptr.String(jtv)
}
case "hasLogicalRedundancy":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected HasLogicalRedundancy to be of type string, got %T instead", value)
}
sv.HasLogicalRedundancy = types.HasLogicalRedundancy(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "lagId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagId to be of type string, got %T instead", value)
}
sv.LagId = ptr.String(jtv)
}
case "loaIssueTime":
if value != nil {
switch jtv := value.(type) {
case json.Number:
f64, err := jtv.Float64()
if err != nil {
return err
}
sv.LoaIssueTime = ptr.Time(smithytime.ParseEpochSeconds(f64))
default:
return fmt.Errorf("expected LoaIssueTime to be a JSON Number, got %T instead", value)
}
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "macSecCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected MacSecCapable to be of type *bool, got %T instead", value)
}
sv.MacSecCapable = ptr.Bool(jtv)
}
case "macSecKeys":
if err := awsAwsjson11_deserializeDocumentMacSecKeyList(&sv.MacSecKeys, value); err != nil {
return err
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "partnerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PartnerName to be of type string, got %T instead", value)
}
sv.PartnerName = ptr.String(jtv)
}
case "portEncryptionStatus":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PortEncryptionStatus to be of type string, got %T instead", value)
}
sv.PortEncryptionStatus = ptr.String(jtv)
}
case "providerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ProviderName to be of type string, got %T instead", value)
}
sv.ProviderName = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
case "vlan":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected VLAN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Vlan = int32(i64)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDisassociateMacSecKeyOutput(v **DisassociateMacSecKeyOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DisassociateMacSecKeyOutput
if *v == nil {
sv = &DisassociateMacSecKeyOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "connectionId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionId to be of type string, got %T instead", value)
}
sv.ConnectionId = ptr.String(jtv)
}
case "macSecKeys":
if err := awsAwsjson11_deserializeDocumentMacSecKeyList(&sv.MacSecKeys, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentListVirtualInterfaceTestHistoryOutput(v **ListVirtualInterfaceTestHistoryOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *ListVirtualInterfaceTestHistoryOutput
if *v == nil {
sv = &ListVirtualInterfaceTestHistoryOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "nextToken":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PaginationToken to be of type string, got %T instead", value)
}
sv.NextToken = ptr.String(jtv)
}
case "virtualInterfaceTestHistory":
if err := awsAwsjson11_deserializeDocumentVirtualInterfaceTestHistoryList(&sv.VirtualInterfaceTestHistory, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentStartBgpFailoverTestOutput(v **StartBgpFailoverTestOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *StartBgpFailoverTestOutput
if *v == nil {
sv = &StartBgpFailoverTestOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "virtualInterfaceTest":
if err := awsAwsjson11_deserializeDocumentVirtualInterfaceTestHistory(&sv.VirtualInterfaceTest, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentStopBgpFailoverTestOutput(v **StopBgpFailoverTestOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *StopBgpFailoverTestOutput
if *v == nil {
sv = &StopBgpFailoverTestOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "virtualInterfaceTest":
if err := awsAwsjson11_deserializeDocumentVirtualInterfaceTestHistory(&sv.VirtualInterfaceTest, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentTagResourceOutput(v **TagResourceOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *TagResourceOutput
if *v == nil {
sv = &TagResourceOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentUntagResourceOutput(v **UntagResourceOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *UntagResourceOutput
if *v == nil {
sv = &UntagResourceOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentUpdateConnectionOutput(v **UpdateConnectionOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *UpdateConnectionOutput
if *v == nil {
sv = &UpdateConnectionOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "awsDevice":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDevice to be of type string, got %T instead", value)
}
sv.AwsDevice = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "bandwidth":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Bandwidth to be of type string, got %T instead", value)
}
sv.Bandwidth = ptr.String(jtv)
}
case "connectionId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionId to be of type string, got %T instead", value)
}
sv.ConnectionId = ptr.String(jtv)
}
case "connectionName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionName to be of type string, got %T instead", value)
}
sv.ConnectionName = ptr.String(jtv)
}
case "connectionState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionState to be of type string, got %T instead", value)
}
sv.ConnectionState = types.ConnectionState(jtv)
}
case "encryptionMode":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EncryptionMode to be of type string, got %T instead", value)
}
sv.EncryptionMode = ptr.String(jtv)
}
case "hasLogicalRedundancy":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected HasLogicalRedundancy to be of type string, got %T instead", value)
}
sv.HasLogicalRedundancy = types.HasLogicalRedundancy(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "lagId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagId to be of type string, got %T instead", value)
}
sv.LagId = ptr.String(jtv)
}
case "loaIssueTime":
if value != nil {
switch jtv := value.(type) {
case json.Number:
f64, err := jtv.Float64()
if err != nil {
return err
}
sv.LoaIssueTime = ptr.Time(smithytime.ParseEpochSeconds(f64))
default:
return fmt.Errorf("expected LoaIssueTime to be a JSON Number, got %T instead", value)
}
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "macSecCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected MacSecCapable to be of type *bool, got %T instead", value)
}
sv.MacSecCapable = ptr.Bool(jtv)
}
case "macSecKeys":
if err := awsAwsjson11_deserializeDocumentMacSecKeyList(&sv.MacSecKeys, value); err != nil {
return err
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "partnerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PartnerName to be of type string, got %T instead", value)
}
sv.PartnerName = ptr.String(jtv)
}
case "portEncryptionStatus":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected PortEncryptionStatus to be of type string, got %T instead", value)
}
sv.PortEncryptionStatus = ptr.String(jtv)
}
case "providerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ProviderName to be of type string, got %T instead", value)
}
sv.ProviderName = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
case "vlan":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected VLAN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Vlan = int32(i64)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentUpdateDirectConnectGatewayAssociationOutput(v **UpdateDirectConnectGatewayAssociationOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *UpdateDirectConnectGatewayAssociationOutput
if *v == nil {
sv = &UpdateDirectConnectGatewayAssociationOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "directConnectGatewayAssociation":
if err := awsAwsjson11_deserializeDocumentDirectConnectGatewayAssociation(&sv.DirectConnectGatewayAssociation, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentUpdateLagOutput(v **UpdateLagOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *UpdateLagOutput
if *v == nil {
sv = &UpdateLagOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "allowsHostedConnections":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected BooleanFlag to be of type *bool, got %T instead", value)
}
sv.AllowsHostedConnections = jtv
}
case "awsDevice":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDevice to be of type string, got %T instead", value)
}
sv.AwsDevice = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "connections":
if err := awsAwsjson11_deserializeDocumentConnectionList(&sv.Connections, value); err != nil {
return err
}
case "connectionsBandwidth":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Bandwidth to be of type string, got %T instead", value)
}
sv.ConnectionsBandwidth = ptr.String(jtv)
}
case "encryptionMode":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EncryptionMode to be of type string, got %T instead", value)
}
sv.EncryptionMode = ptr.String(jtv)
}
case "hasLogicalRedundancy":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected HasLogicalRedundancy to be of type string, got %T instead", value)
}
sv.HasLogicalRedundancy = types.HasLogicalRedundancy(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "lagId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagId to be of type string, got %T instead", value)
}
sv.LagId = ptr.String(jtv)
}
case "lagName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagName to be of type string, got %T instead", value)
}
sv.LagName = ptr.String(jtv)
}
case "lagState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LagState to be of type string, got %T instead", value)
}
sv.LagState = types.LagState(jtv)
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "macSecCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected MacSecCapable to be of type *bool, got %T instead", value)
}
sv.MacSecCapable = ptr.Bool(jtv)
}
case "macSecKeys":
if err := awsAwsjson11_deserializeDocumentMacSecKeyList(&sv.MacSecKeys, value); err != nil {
return err
}
case "minimumLinks":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected Count to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.MinimumLinks = int32(i64)
}
case "numberOfConnections":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected Count to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.NumberOfConnections = int32(i64)
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "providerName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ProviderName to be of type string, got %T instead", value)
}
sv.ProviderName = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentUpdateVirtualInterfaceAttributesOutput(v **UpdateVirtualInterfaceAttributesOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *UpdateVirtualInterfaceAttributesOutput
if *v == nil {
sv = &UpdateVirtualInterfaceAttributesOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "addressFamily":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AddressFamily to be of type string, got %T instead", value)
}
sv.AddressFamily = types.AddressFamily(jtv)
}
case "amazonAddress":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AmazonAddress to be of type string, got %T instead", value)
}
sv.AmazonAddress = ptr.String(jtv)
}
case "amazonSideAsn":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected LongAsn to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.AmazonSideAsn = ptr.Int64(i64)
}
case "asn":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected ASN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Asn = int32(i64)
}
case "authKey":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected BGPAuthKey to be of type string, got %T instead", value)
}
sv.AuthKey = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "bgpPeers":
if err := awsAwsjson11_deserializeDocumentBGPPeerList(&sv.BgpPeers, value); err != nil {
return err
}
case "connectionId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionId to be of type string, got %T instead", value)
}
sv.ConnectionId = ptr.String(jtv)
}
case "customerAddress":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected CustomerAddress to be of type string, got %T instead", value)
}
sv.CustomerAddress = ptr.String(jtv)
}
case "customerRouterConfig":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected RouterConfig to be of type string, got %T instead", value)
}
sv.CustomerRouterConfig = ptr.String(jtv)
}
case "directConnectGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected DirectConnectGatewayId to be of type string, got %T instead", value)
}
sv.DirectConnectGatewayId = ptr.String(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "mtu":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected MTU to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Mtu = ptr.Int32(int32(i64))
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "routeFilterPrefixes":
if err := awsAwsjson11_deserializeDocumentRouteFilterPrefixList(&sv.RouteFilterPrefixes, value); err != nil {
return err
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
case "virtualGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualGatewayId to be of type string, got %T instead", value)
}
sv.VirtualGatewayId = ptr.String(jtv)
}
case "virtualInterfaceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceId to be of type string, got %T instead", value)
}
sv.VirtualInterfaceId = ptr.String(jtv)
}
case "virtualInterfaceName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceName to be of type string, got %T instead", value)
}
sv.VirtualInterfaceName = ptr.String(jtv)
}
case "virtualInterfaceState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceState to be of type string, got %T instead", value)
}
sv.VirtualInterfaceState = types.VirtualInterfaceState(jtv)
}
case "virtualInterfaceType":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceType to be of type string, got %T instead", value)
}
sv.VirtualInterfaceType = ptr.String(jtv)
}
case "vlan":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected VLAN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Vlan = int32(i64)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
| {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *CreatePublicVirtualInterfaceOutput
if *v == nil {
sv = &CreatePublicVirtualInterfaceOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "addressFamily":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AddressFamily to be of type string, got %T instead", value)
}
sv.AddressFamily = types.AddressFamily(jtv)
}
case "amazonAddress":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AmazonAddress to be of type string, got %T instead", value)
}
sv.AmazonAddress = ptr.String(jtv)
}
case "amazonSideAsn":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected LongAsn to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.AmazonSideAsn = ptr.Int64(i64)
}
case "asn":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected ASN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Asn = int32(i64)
}
case "authKey":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected BGPAuthKey to be of type string, got %T instead", value)
}
sv.AuthKey = ptr.String(jtv)
}
case "awsDeviceV2":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsDeviceV2 to be of type string, got %T instead", value)
}
sv.AwsDeviceV2 = ptr.String(jtv)
}
case "awsLogicalDeviceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected AwsLogicalDeviceId to be of type string, got %T instead", value)
}
sv.AwsLogicalDeviceId = ptr.String(jtv)
}
case "bgpPeers":
if err := awsAwsjson11_deserializeDocumentBGPPeerList(&sv.BgpPeers, value); err != nil {
return err
}
case "connectionId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionId to be of type string, got %T instead", value)
}
sv.ConnectionId = ptr.String(jtv)
}
case "customerAddress":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected CustomerAddress to be of type string, got %T instead", value)
}
sv.CustomerAddress = ptr.String(jtv)
}
case "customerRouterConfig":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected RouterConfig to be of type string, got %T instead", value)
}
sv.CustomerRouterConfig = ptr.String(jtv)
}
case "directConnectGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected DirectConnectGatewayId to be of type string, got %T instead", value)
}
sv.DirectConnectGatewayId = ptr.String(jtv)
}
case "jumboFrameCapable":
if value != nil {
jtv, ok := value.(bool)
if !ok {
return fmt.Errorf("expected JumboFrameCapable to be of type *bool, got %T instead", value)
}
sv.JumboFrameCapable = ptr.Bool(jtv)
}
case "location":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected LocationCode to be of type string, got %T instead", value)
}
sv.Location = ptr.String(jtv)
}
case "mtu":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected MTU to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Mtu = ptr.Int32(int32(i64))
}
case "ownerAccount":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected OwnerAccount to be of type string, got %T instead", value)
}
sv.OwnerAccount = ptr.String(jtv)
}
case "region":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Region to be of type string, got %T instead", value)
}
sv.Region = ptr.String(jtv)
}
case "routeFilterPrefixes":
if err := awsAwsjson11_deserializeDocumentRouteFilterPrefixList(&sv.RouteFilterPrefixes, value); err != nil {
return err
}
case "tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
case "virtualGatewayId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualGatewayId to be of type string, got %T instead", value)
}
sv.VirtualGatewayId = ptr.String(jtv)
}
case "virtualInterfaceId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceId to be of type string, got %T instead", value)
}
sv.VirtualInterfaceId = ptr.String(jtv)
}
case "virtualInterfaceName":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceName to be of type string, got %T instead", value)
}
sv.VirtualInterfaceName = ptr.String(jtv)
}
case "virtualInterfaceState":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceState to be of type string, got %T instead", value)
}
sv.VirtualInterfaceState = types.VirtualInterfaceState(jtv)
}
case "virtualInterfaceType":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected VirtualInterfaceType to be of type string, got %T instead", value)
}
sv.VirtualInterfaceType = ptr.String(jtv)
}
case "vlan":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected VLAN to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Vlan = int32(i64)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
} |
create_ipv6_gateway.go | package vpc
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// CreateIpv6Gateway invokes the vpc.CreateIpv6Gateway API synchronously
// api document: https://help.aliyun.com/api/vpc/createipv6gateway.html
func (client *Client) CreateIpv6Gateway(request *CreateIpv6GatewayRequest) (response *CreateIpv6GatewayResponse, err error) {
response = CreateCreateIpv6GatewayResponse()
err = client.DoAction(request, response)
return
}
// CreateIpv6GatewayWithChan invokes the vpc.CreateIpv6Gateway API asynchronously
// api document: https://help.aliyun.com/api/vpc/createipv6gateway.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateIpv6GatewayWithChan(request *CreateIpv6GatewayRequest) (<-chan *CreateIpv6GatewayResponse, <-chan error) {
responseChan := make(chan *CreateIpv6GatewayResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateIpv6Gateway(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateIpv6GatewayWithCallback invokes the vpc.CreateIpv6Gateway API asynchronously
// api document: https://help.aliyun.com/api/vpc/createipv6gateway.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateIpv6GatewayWithCallback(request *CreateIpv6GatewayRequest, callback func(response *CreateIpv6GatewayResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateIpv6GatewayResponse
var err error
defer close(result)
response, err = client.CreateIpv6Gateway(request)
callback(response, err)
result <- 1 | if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateIpv6GatewayRequest is the request struct for api CreateIpv6Gateway
type CreateIpv6GatewayRequest struct {
*requests.RpcRequest
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
ClientToken string `position:"Query" name:"ClientToken"`
Description string `position:"Query" name:"Description"`
Spec string `position:"Query" name:"Spec"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
VpcId string `position:"Query" name:"VpcId"`
Name string `position:"Query" name:"Name"`
}
// CreateIpv6GatewayResponse is the response struct for api CreateIpv6Gateway
type CreateIpv6GatewayResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
Ipv6GatewayId string `json:"Ipv6GatewayId" xml:"Ipv6GatewayId"`
}
// CreateCreateIpv6GatewayRequest creates a request to invoke CreateIpv6Gateway API
func CreateCreateIpv6GatewayRequest() (request *CreateIpv6GatewayRequest) {
request = &CreateIpv6GatewayRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Vpc", "2016-04-28", "CreateIpv6Gateway", "vpc", "openAPI")
return
}
// CreateCreateIpv6GatewayResponse creates a response to parse from CreateIpv6Gateway response
func CreateCreateIpv6GatewayResponse() (response *CreateIpv6GatewayResponse) {
response = &CreateIpv6GatewayResponse{
BaseResponse: &responses.BaseResponse{},
}
return
} | }) |
ewo_CM.go | package ewo_CM
import (
"math"
"strconv"
"time"
"github.com/go-playground/locales"
"github.com/go-playground/locales/currency"
)
type ewo_CM struct {
locale string
pluralsCardinal []locales.PluralRule
pluralsOrdinal []locales.PluralRule
pluralsRange []locales.PluralRule
decimal string
group string
minus string
percent string
perMille string
timeSeparator string
inifinity string
currencies []string // idx = enum of currency code
currencyPositiveSuffix string
currencyNegativeSuffix string
monthsAbbreviated []string
monthsNarrow []string
monthsWide []string
daysAbbreviated []string
daysNarrow []string
daysShort []string
daysWide []string
periodsAbbreviated []string
periodsNarrow []string
periodsShort []string
periodsWide []string
erasAbbreviated []string
erasNarrow []string
erasWide []string
timezones map[string]string
}
// New returns a new instance of translator for the 'ewo_CM' locale
func New() locales.Translator {
return &ewo_CM{
locale: "ewo_CM",
pluralsCardinal: nil,
pluralsOrdinal: nil,
pluralsRange: nil,
decimal: ",",
group: " ",
timeSeparator: ":",
currencies: []string{"ADP", "AED", "AFA", "AFN", "ALK", "ALL", "AMD", "ANG", "AOA", "AOK", "AON", "AOR", "ARA", "ARL", "ARM", "ARP", "ARS", "ATS", "AUD", "AWG", "AZM", "AZN", "BAD", "BAM", "BAN", "BBD", "BDT", "BEC", "BEF", "BEL", "BGL", "BGM", "BGN", "BGO", "BHD", "BIF", "BMD", "BND", "BOB", "BOL", "BOP", "BOV", "BRB", "BRC", "BRE", "BRL", "BRN", "BRR", "BRZ", "BSD", "BTN", "BUK", "BWP", "BYB", "BYN", "BYR", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLE", "CLF", "CLP", "CNX", "CNY", "COP", "COU", "CRC", "CSD", "CSK", "CUC", "CUP", "CVE", "CYP", "CZK", "DDM", "DEM", "DJF", "DKK", "DOP", "DZD", "ECS", "ECV", "EEK", "EGP", "ERN", "ESA", "ESB", "ESP", "ETB", "EUR", "FIM", "FJD", "FKP", "FRF", "GBP", "GEK", "GEL", "GHC", "GHS", "GIP", "GMD", "GNF", "GNS", "GQE", "GRD", "GTQ", "GWE", "GWP", "GYD", "HKD", "HNL", "HRD", "HRK", "HTG", "HUF", "IDR", "IEP", "ILP", "ILR", "ILS", "INR", "IQD", "IRR", "ISJ", "ISK", "ITL", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRH", "KRO", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LTL", "LTT", "LUC", "LUF", "LUL", "LVL", "LVR", "LYD", "MAD", "MAF", "MCF", "MDC", "MDL", "MGA", "MGF", "MKD", "MKN", "MLF", "MMK", "MNT", "MOP", "MRO", "MTL", "MTP", "MUR", "MVP", "MVR", "MWK", "MXN", "MXP", "MXV", "MYR", "MZE", "MZM", "MZN", "NAD", "NGN", "NIC", "NIO", "NLG", "NOK", "NPR", "NZD", "OMR", "PAB", "PEI", "PEN", "PES", "PGK", "PHP", "PKR", "PLN", "PLZ", "PTE", "PYG", "QAR", "RHD", "ROL", "RON", "RSD", "RUB", "RUR", "RWF", "SAR", "SBD", "SCR", "SDD", "SDG", "SDP", "SEK", "SGD", "SHP", "SIT", "SKK", "SLL", "SOS", "SRD", "SRG", "SSP", "STD", "SUR", "SVC", "SYP", "SZL", "THB", "TJR", "TJS", "TMM", "TMT", "TND", "TOP", "TPE", "TRL", "TRY", "TTD", "TWD", "TZS", "UAH", "UAK", "UGS", "UGX", "USD", "USN", "USS", "UYI", "UYP", "UYU", "UZS", "VEB", "VEF", "VND", "VNN", "VUV", "WST", "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XEU", "XFO", "XFU", "XOF", "XPD", "XPF", "XPT", "XRE", "XSU", "XTS", "XUA", "XXX", "YDD", "YER", "YUD", "YUM", "YUN", "YUR", "ZAL", "ZAR", "ZMK", "ZMW", "ZRN", "ZRZ", "ZWD", "ZWL", "ZWR"},
currencyPositiveSuffix: " ",
currencyNegativeSuffix: " ",
monthsAbbreviated: []string{"", "ngo", "ngb", "ngl", "ngn", "ngt", "ngs", "ngz", "ngm", "nge", "nga", "ngad", "ngab"},
monthsNarrow: []string{"", "o", "b", "l", "n", "t", "s", "z", "m", "e", "a", "d", "b"},
monthsWide: []string{"", "ngɔn osú", "ngɔn bɛ̌", "ngɔn lála", "ngɔn nyina", "ngɔn tána", "ngɔn saməna", "ngɔn zamgbála", "ngɔn mwom", "ngɔn ebulú", "ngɔn awóm", "ngɔn awóm ai dziá", "ngɔn awóm ai bɛ̌"},
daysAbbreviated: []string{"sɔ́n", "mɔ́n", "smb", "sml", "smn", "fúl", "sér"},
daysNarrow: []string{"s", "m", "s", "s", "s", "f", "s"},
daysWide: []string{"sɔ́ndɔ", "mɔ́ndi", "sɔ́ndɔ məlú mə́bɛ̌", "sɔ́ndɔ məlú mə́lɛ́", "sɔ́ndɔ məlú mə́nyi", "fúladé", "séradé"},
periodsAbbreviated: []string{"kíkíríg", "ngəgógəle"},
periodsWide: []string{"kíkíríg", "ngəgógəle"},
erasAbbreviated: []string{"oyk", "ayk"},
erasNarrow: []string{"", ""},
erasWide: []string{"osúsúa Yésus kiri", "ámvus Yésus Kirís"},
timezones: map[string]string{"HENOMX": "HENOMX", "WITA": "WITA", "OEZ": "OEZ", "MDT": "MDT", "HEOG": "HEOG", "COST": "COST", "CLT": "CLT", "TMST": "TMST", "LHDT": "LHDT", "AST": "AST", "AEST": "AEST", "ART": "ART", "PST": "PST", "PDT": "PDT", "MYT": "MYT", "VET": "VET", "EAT": "EAT", "WAT": "WAT", "ACST": "ACST", "HNPMX": "HNPMX", "BOT": "BOT", "WART": "WART", "CHADT": "CHADT", "AWDT": "AWDT", "HNOG": "HNOG", "BT": "BT", "SRT": "SRT", "HNNOMX": "HNNOMX", "LHST": "LHST", "AEDT": "AEDT", "HNCU": "HNCU", "UYST": "UYST", "SAST": "SAST", "WAST": "WAST", "COT": "COT", "EST": "EST", "ECT": "ECT", "CDT": "CDT", "HAST": "HAST", "AKST": "AKST", "ACDT": "ACDT", "CAT": "CAT", "CHAST": "CHAST", "NZST": "NZST", "EDT": "EDT", "AKDT": "AKDT", "GMT": "GMT", "HECU": "HECU", "JDT": "JDT", "HNEG": "HNEG", "HAT": "HAT", "HKT": "HKT", "CLST": "CLST", "HADT": "HADT", "HEEG": "HEEG", "WEZ": "WEZ", "HNPM": "HNPM", "AWST": "AWST", "IST": "IST", "OESZ": "OESZ", "MST": "MST", "GYT": "GYT", "CST": "CST", "WARST": "WARST", "ARST": "ARST", "HKST": "HKST", "NZDT": "NZDT", "MEZ": "MEZ", "GFT": "GFT", "ChST": "ChST", "HEPMX": "HEPMX", "HEPM": "HEPM", "ACWST": "ACWST", "WIB": "WIB", "WIT": "WIT", "UYT": "UYT", "TMT": "TMT", "MESZ": "MESZ", "JST": "JST", "∅∅∅": "∅∅∅", "ADT": "ADT", "HNT": "HNT", "ACWDT": "ACWDT", "SGT": "SGT", "WESZ": "WESZ"},
}
}
// Locale returns the current translators string locale
func (ewo *ewo_CM) Locale() string {
return ewo.locale
}
// PluralsCardinal returns the list of cardinal plural rules associated with 'ewo_CM'
func (ewo *ewo_CM) PluralsCardinal() []locales.PluralRule {
return ewo.pluralsCardinal
}
// PluralsOrdinal returns the list of ordinal plural rules associated with 'ewo_CM'
func (ewo *ewo_CM) PluralsOrdinal() []locales.PluralRule {
return ewo.pluralsOrdinal
}
// PluralsRange returns the list of range plural rules associated with 'ewo_CM'
func (ewo *ewo_CM) PluralsRange() []locales.PluralRule {
return ewo.pluralsRange
}
// CardinalPluralRule returns the cardinal PluralRule given 'num' and digits/precision of 'v' for 'ewo_CM'
func (ewo *ewo_CM) CardinalPluralRule(num float64, v uint64) locales.PluralRule {
return locales.PluralRuleUnknown
}
// OrdinalPluralRule returns the ordinal PluralRule given 'num' and digits/precision of 'v' for 'ewo_CM'
func (ewo *ewo_CM) OrdinalPluralRule(num float64, v uint64) locales.PluralRule {
return locales.PluralRuleUnknown
}
// RangePluralRule returns the ordinal PluralRule given 'num1', 'num2' and digits/precision of 'v1' and 'v2' for 'ewo_CM'
func (ewo *ewo_CM) RangePluralRule(num1 float64, v1 uint64, num2 float64, v2 uint64) locales.PluralRule {
return locales.PluralRuleUnknown
}
// MonthAbbreviated returns the locales abbreviated month given the 'month' provided
func (ewo *ewo_CM) MonthAbbreviated(month time.Month) string {
return ewo.monthsAbbreviated[month]
}
// MonthsAbbreviated returns the locales abbreviated months
func (ewo *ewo_CM) MonthsAbbreviated() []string {
return ewo.monthsAbbreviated[1:]
}
// MonthNarrow returns the locales narrow month given the 'month' provided
func (ewo *ewo_CM) MonthNarrow(month time.Month) string {
return ewo.monthsNarrow[month]
}
// MonthsNarrow returns the locales narrow months
func (ewo *ewo_CM) MonthsNarrow() []string {
return ewo.monthsNarrow[1:]
}
// MonthWide returns the locales wide month given the 'month' provided
func (ewo *ewo_CM) MonthWide(month time.Month) string {
return ewo.monthsWide[month]
}
// MonthsWide returns the locales wide months
func (ewo *ewo_CM) MonthsWide() []string {
return ewo.monthsWide[1:]
}
// WeekdayAbbreviated returns the locales abbreviated weekday given the 'weekday' provided
func (ewo *ewo_CM) WeekdayAbbreviated(weekday time.Weekday) string {
return ewo.daysAbbreviated[weekday]
}
// WeekdaysAbbreviated returns the locales abbreviated weekdays
func (ewo *ewo_CM) WeekdaysAbbreviated() []string {
return ewo.daysAbbreviated
}
// WeekdayNarrow returns the locales narrow weekday given the 'weekday' provided
func (ewo *ewo_CM) WeekdayNarrow(weekday time.Weekday) string {
return ewo.daysNarrow[weekday]
}
// WeekdaysNarrow returns the locales narrow weekdays
func (ewo *ewo_CM) WeekdaysNarrow() []string {
return ewo.daysNarrow
}
// WeekdayShort returns the locales short weekday given the 'weekday' provided
func (ewo *ewo_CM) WeekdayShort(weekday time.Weekday) string {
return ewo.daysShort[weekday]
}
// WeekdaysShort returns the locales short weekdays
func (ewo *ewo_CM) WeekdaysShort() []string {
return ewo.daysShort
}
// WeekdayWide returns the locales wide weekday given the 'weekday' provided
func (ewo *ewo_CM) WeekdayWide(weekday time.Weekday) string {
return ewo.daysWide[weekday]
}
// WeekdaysWide returns the locales wide weekdays
func (ewo *ewo_CM) WeekdaysWide() []string {
return ewo.daysWide
}
// Decimal returns the decimal point of number
func (ewo *ewo_CM) Decimal() string {
return ewo.decimal
}
// Group returns the group of number
func (ewo *ewo_CM) Group() string {
return ewo.group
}
// Group returns the minus sign of number
func (ewo *ewo_CM) Minus() string {
return ewo.minus
}
// FmtNumber returns 'num' with digits/precision of 'v' for 'ewo_CM' and handles both Whole and Real numbers based on 'v'
func (ewo *ewo_CM) FmtNumber(num float64, v uint64) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
l := len(s) + 1 + 2*len(s[:len(s)-int(v)-1])/3
count := 0
inWhole := v == 0
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
b = append(b, ewo.decimal[0])
inWhole = true
continue
}
if inWhole {
if count == 3 {
for j := len(ewo.group) - 1; j >= 0; j-- {
b = append(b, ewo.group[j])
}
count = 1
} else {
count++
}
}
b = append(b, s[i])
}
if num < 0 {
b = append(b, ewo.minus[0])
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
return string(b)
}
// FmtPercent returns 'num' with digits/precision of 'v' for 'ewo_CM' and handles both Whole and Real numbers based on 'v'
// NOTE: 'num' passed into FmtPercent is assumed to be in percent already
func (ewo *ewo_CM) FmtPercent(num float64, v uint64) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
l := len(s) + 1
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
b = append(b, ewo.decimal[0])
continue
}
b = append(b, s[i])
}
if num < 0 {
b = append(b, ewo.minus[0])
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
b = append(b, ewo.percent...)
return string(b)
}
// FmtCurrency returns the currency representation of 'num' with digits/precision of 'v' for 'ewo_CM'
func (ewo *ewo_CM) FmtCurrency(num float64, v uint64, currency currency.Type) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
symbol := ewo.currencies[currency]
l := len(s) + len(symbol) + 3 + 2*len(s[:len(s)-int(v)-1])/3
count := 0
inWhole := v == 0
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
b = append(b, ewo.decimal[0])
inWhole = true
continue
}
if inWhole {
if count == 3 {
for j := len(ewo.group) - 1; j >= 0; j-- {
b = append(b, ewo.group[j])
}
count = 1
} else {
count++
}
}
b = append(b, s[i])
}
if num < 0 {
b = append(b, ewo.minus[0])
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
| int(v) < 2 {
if v == 0 {
b = append(b, ewo.decimal...)
}
for i := 0; i < 2-int(v); i++ {
b = append(b, '0')
}
}
b = append(b, ewo.currencyPositiveSuffix...)
b = append(b, symbol...)
return string(b)
}
// FmtAccounting returns the currency representation of 'num' with digits/precision of 'v' for 'ewo_CM'
// in accounting notation.
func (ewo *ewo_CM) FmtAccounting(num float64, v uint64, currency currency.Type) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
symbol := ewo.currencies[currency]
l := len(s) + len(symbol) + 3 + 2*len(s[:len(s)-int(v)-1])/3
count := 0
inWhole := v == 0
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
b = append(b, ewo.decimal[0])
inWhole = true
continue
}
if inWhole {
if count == 3 {
for j := len(ewo.group) - 1; j >= 0; j-- {
b = append(b, ewo.group[j])
}
count = 1
} else {
count++
}
}
b = append(b, s[i])
}
if num < 0 {
b = append(b, ewo.minus[0])
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
if int(v) < 2 {
if v == 0 {
b = append(b, ewo.decimal...)
}
for i := 0; i < 2-int(v); i++ {
b = append(b, '0')
}
}
if num < 0 {
b = append(b, ewo.currencyNegativeSuffix...)
b = append(b, symbol...)
} else {
b = append(b, ewo.currencyPositiveSuffix...)
b = append(b, symbol...)
}
return string(b)
}
// FmtDateShort returns the short date representation of 't' for 'ewo_CM'
func (ewo *ewo_CM) FmtDateShort(t time.Time) string {
b := make([]byte, 0, 32)
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x2f}...)
b = strconv.AppendInt(b, int64(t.Month()), 10)
b = append(b, []byte{0x2f}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(-t.Year()), 10)
}
return string(b)
}
// FmtDateMedium returns the medium date representation of 't' for 'ewo_CM'
func (ewo *ewo_CM) FmtDateMedium(t time.Time) string {
b := make([]byte, 0, 32)
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x20}...)
b = append(b, ewo.monthsAbbreviated[t.Month()]...)
b = append(b, []byte{0x20}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(-t.Year()), 10)
}
return string(b)
}
// FmtDateLong returns the long date representation of 't' for 'ewo_CM'
func (ewo *ewo_CM) FmtDateLong(t time.Time) string {
b := make([]byte, 0, 32)
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x20}...)
b = append(b, ewo.monthsWide[t.Month()]...)
b = append(b, []byte{0x20}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(-t.Year()), 10)
}
return string(b)
}
// FmtDateFull returns the full date representation of 't' for 'ewo_CM'
func (ewo *ewo_CM) FmtDateFull(t time.Time) string {
b := make([]byte, 0, 32)
b = append(b, ewo.daysWide[t.Weekday()]...)
b = append(b, []byte{0x20}...)
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x20}...)
b = append(b, ewo.monthsWide[t.Month()]...)
b = append(b, []byte{0x20}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(-t.Year()), 10)
}
return string(b)
}
// FmtTimeShort returns the short time representation of 't' for 'ewo_CM'
func (ewo *ewo_CM) FmtTimeShort(t time.Time) string {
b := make([]byte, 0, 32)
if t.Hour() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, ewo.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
return string(b)
}
// FmtTimeMedium returns the medium time representation of 't' for 'ewo_CM'
func (ewo *ewo_CM) FmtTimeMedium(t time.Time) string {
b := make([]byte, 0, 32)
if t.Hour() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, ewo.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, ewo.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
return string(b)
}
// FmtTimeLong returns the long time representation of 't' for 'ewo_CM'
func (ewo *ewo_CM) FmtTimeLong(t time.Time) string {
b := make([]byte, 0, 32)
if t.Hour() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, ewo.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, ewo.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
b = append(b, []byte{0x20}...)
tz, _ := t.Zone()
b = append(b, tz...)
return string(b)
}
// FmtTimeFull returns the full time representation of 't' for 'ewo_CM'
func (ewo *ewo_CM) FmtTimeFull(t time.Time) string {
b := make([]byte, 0, 32)
if t.Hour() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, ewo.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, ewo.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
b = append(b, []byte{0x20}...)
tz, _ := t.Zone()
if btz, ok := ewo.timezones[tz]; ok {
b = append(b, btz...)
} else {
b = append(b, tz...)
}
return string(b)
}
| b[i], b[j] = b[j], b[i]
}
if |
main.go | package main
import (
"flag"
"log"
"os"
"os/signal"
"syscall"
"github.com/AlexanderBrese/gomon/pkg/configuration"
"github.com/AlexanderBrese/gomon/pkg/surveillance"
"github.com/AlexanderBrese/gomon/pkg/utils"
)
var cfgPath string
func init() |
func main() {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
defer _recover()
cfg, err := parse(cfgPath)
if err != nil {
log.Fatalf("error: during configuration parsing: %s", err)
}
gomon := surveillance.NewGomon(cfg)
if gomon == nil {
return
}
go func() {
<-sigs
gomon.Stop()
}()
gomon.Start()
}
func _recover() {
if e := recover(); e != nil {
log.Fatalf("PANIC: %+v", e)
}
}
func parse(cfgPath string) (*configuration.Configuration, error) {
absPath := ""
if cfgPath != "" {
var err error
absPath, err = utils.CurrentAbsolutePath(cfgPath)
if err != nil {
return nil, err
}
}
cfg, err := configuration.ParsedConfiguration(absPath)
if err != nil {
return nil, err
}
return cfg, nil
}
| {
flag.StringVar(&cfgPath, "c", "", "relative config path")
flag.Parse()
} |
views.py | import requests
from allauth.socialaccount.helpers import render_authentication_error
from allauth.socialaccount.models import SocialLogin, SocialAccount
from allauth.socialaccount.providers.base import ProviderException
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.orcid.provider import OrcidProvider
from allauth.socialaccount.providers.orcid.views import OrcidOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import (
OAuth2Error,
OAuth2Client
)
from allauth.socialaccount.providers.oauth2.views import (
AuthError,
OAuth2LoginView,
OAuth2CallbackView,
PermissionDenied,
RequestException
)
from allauth.utils import (
get_request_param,
)
from allauth.account.signals import user_signed_up, user_logged_in
from allauth.account import app_settings
from rest_auth.registration.views import SocialLoginView
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from django.dispatch import receiver
from mailchimp_marketing import Client
from oauth.serializers import SocialLoginSerializer
from oauth.adapters import GoogleOAuth2AdapterIdToken
from oauth.helpers import complete_social_login
from oauth.exceptions import LoginError
from oauth.utils import get_orcid_names
from researchhub.settings import (
GOOGLE_REDIRECT_URL,
GOOGLE_YOLO_REDIRECT_URL,
keys,
MAILCHIMP_SERVER,
MAILCHIMP_LIST_ID,
RECAPTCHA_SECRET_KEY,
RECAPTCHA_VERIFY_URL
)
from user.models import Author
from user.utils import merge_author_profiles
from utils import sentry
from utils.http import http_request, RequestMethods
from utils.throttles import captcha_unlock
from utils.siftscience import events_api
@api_view([RequestMethods.POST])
@permission_classes([AllowAny])
def captcha_verify(request):
verify_request = requests.post(
RECAPTCHA_VERIFY_URL,
{
'secret': RECAPTCHA_SECRET_KEY,
'response': request.data.get('response')
}
)
status = verify_request.status_code
req_json = verify_request.json()
data = {'success': req_json.get('success')}
if req_json.get("error-codes"):
data['errors'] = req_json.get('error-codes')
if data['success']:
# turn off throttling
captcha_unlock(request)
return Response(data, status=status)
class GoogleLogin(SocialLoginView):
adapter_class = GoogleOAuth2Adapter
callback_url = GOOGLE_REDIRECT_URL
client_class = OAuth2Client
serializer_class = SocialLoginSerializer
class GoogleYoloLogin(SocialLoginView):
adapter_class = GoogleOAuth2AdapterIdToken
callback_url = GOOGLE_YOLO_REDIRECT_URL
client_class = OAuth2Client
serializer_class = SocialLoginSerializer
class CallbackView(OAuth2CallbackView):
"""
This class is copied from allauth/socialaccount/providers/oauth2/views.py
but uses a custom method for `complete_social_login`
"""
permission_classes = (AllowAny,)
def dispatch(self, request, *args, **kwargs):
if 'error' in request.GET or 'code' not in request.GET:
# Distinguish cancel from error
auth_error = request.GET.get('error', None)
if auth_error == self.adapter.login_cancelled_error:
error = AuthError.CANCELLED
else:
error = AuthError.UNKNOWN
return render_authentication_error(
request,
self.adapter.provider_id,
error=error)
app = self.adapter.get_provider().get_app(self.request)
client = self.get_client(request, app)
try:
try:
access_token = client.get_access_token(request.GET['code'])
except Exception:
access_token = client.get_access_token(
request.GET['credential']
)
token = self.adapter.parse_token(access_token)
token.app = app
login = self.adapter.complete_login(request,
app,
token,
response=access_token)
login.token = token
if self.adapter.provider_id != OrcidProvider.id:
if self.adapter.supports_state:
login.state = SocialLogin \
.verify_and_unstash_state(
request,
get_request_param(request, 'state'))
else:
login.state = SocialLogin.unstash_state(request)
return complete_social_login(request, login)
except (PermissionDenied,
OAuth2Error,
RequestException,
ProviderException) as e:
return render_authentication_error(
request,
self.adapter.provider_id,
exception=e
)
google_callback = CallbackView.adapter_view(GoogleOAuth2Adapter)
google_yolo_login = OAuth2LoginView.adapter_view(GoogleOAuth2AdapterIdToken)
google_yolo_callback = CallbackView.adapter_view(GoogleOAuth2AdapterIdToken)
orcid_callback = CallbackView.adapter_view(OrcidOAuth2Adapter)
@api_view([RequestMethods.POST])
@permission_classes([IsAuthenticated])
def orcid_connect(request):
success = False
status = 400
try:
orcid = request.data.get('orcid')
access_token = request.data.get('access_token')
url = f'https://pub.orcid.org/v3.0/{orcid}/record'
headers = {
'Accept': 'application/json',
'Authorization': f'Bearer {access_token}'
}
# Raise for status because we need to make sure we can authenticate
# correctly with orcid. Without this check, anyone could make a post
# request to connect any other orcid account to their own.
response = http_request(RequestMethods.GET, url=url, headers=headers)
response.raise_for_status()
user = request.user
save_orcid_author(user, orcid, response.json())
events_api.track_account(user, request, update=True)
success = True
status = 201
data = {
'success': success,
'orcid_profile': f'https://orcid.org/{orcid}'
}
except Exception as e:
data = str(e)
sentry.log_error(e)
print(e)
return Response(data, status=status)
def save_orcid_author(user, orcid_id, orcid_data):
orcid_account = SocialAccount.objects.create(
user=user,
uid=orcid_id,
provider=OrcidProvider.id,
extra_data=orcid_data
)
update_author_profile(user, orcid_id, orcid_data, orcid_account)
def update_author_profile(user, orcid_id, orcid_data, orcid_account):
first_name, last_name = get_orcid_names(orcid_data)
try:
author = Author.objects.get(orcid_id=orcid_id)
except Author.DoesNotExist:
user.author_profile.orcid_id = orcid_id
else:
user.author_profile = merge_author_profiles(
author,
user.author_profile
)
user.author_profile.orcid_account = orcid_account
user.author_profile.first_name = first_name
user.author_profile.last_name = last_name
user.author_profile.save()
user.save()
@receiver(user_signed_up)
@receiver(user_logged_in)
def user_signed_up_(request, user, **kwargs):
"""
After a user signs up with social account, set their profile image.
"""
queryset = SocialAccount.objects.filter(
provider='google',
user=user
)
if queryset.exists():
if queryset.count() > 1:
raise Exception(
f'Expected 1 item in the queryset. Found {queryset.count()}.'
)
google_account = queryset.first()
url = google_account.extra_data.get('picture', None)
if user.author_profile and not user.author_profile.profile_image:
user.author_profile.profile_image = url
user.author_profile.save() |
@receiver(user_signed_up)
def mailchimp_add_user(request, user, **kwargs):
"""Adds user email to MailChimp"""
mailchimp = Client()
mailchimp.set_config({
'api_key': keys.MAILCHIMP_KEY,
'server': MAILCHIMP_SERVER
})
try:
member_info = {'email_address': user.email, 'status': 'subscribed'}
mailchimp.lists.add_list_member(MAILCHIMP_LIST_ID, member_info)
except Exception as error:
sentry.log_error(error, message=error.text) | return None
else:
return None |
tracers.py | # coding=utf-8
# Copyright 2020 The Edward2 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.
"""Tracing operations.
This file collects common tracing operations, i.e., traces that each control the
execution of programs in a specific manner. For example, 'condition' traces a
program and fixes the value of random variables; and 'tape' traces the program
and records the executed random variables onto an ordered dictionary.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import contextlib
from edward2.trace import trace
from edward2.trace import traceable
@contextlib.contextmanager
def condition(**model_kwargs):
"""Context manager for setting the values of random variables.
Args:
**model_kwargs: dict of str to Tensor. Keys are the names of random variable
in the model. Values are Tensors to set their corresponding value to.
Yields:
None.
#### Examples
`condition` is typically used for binding observations to random variables
in the model, or equivalently binding posterior samples to random variables
in the model. This lets one compute likelihoods or prior densities.
```python
import edward2 as ed
def probabilistic_matrix_factorization():
users = ed.Normal(0., 1., sample_shape=[5000, 128], name="users")
items = ed.Normal(0., 1., sample_shape=[7500, 128], name="items")
ratings = ed.Normal(loc=tf.matmul(users, items, transpose_b=True),
scale=0.1,
name="ratings")
return ratings
users = tf.zeros([5000, 128])
items = tf.zeros([7500, 128])
with ed.condition(users=users, items=items):
ratings = probabilistic_matrix_factorization()
# Compute the likelihood given latent user preferences and item attributes set
# to zero matrices, p(data | users=0, items=0).
ratings.distribution.log_prob(data)
```
"""
def _condition(f, *args, **kwargs):
"""Sets random variable values to its aligned value."""
name = kwargs.get("name")
if name in model_kwargs:
kwargs["value"] = model_kwargs[name]
return traceable(f)(*args, **kwargs)
with trace(_condition):
yield
@contextlib.contextmanager
def tape():
"""Context manager for recording traceable executions onto a tape.
Similar to `tf.GradientTape`, operations are recorded if they are executed
within this context manager. In addition, the operation must be registered
(decorated) as `ed.traceable`.
Yields:
tape: OrderedDict where operations are recorded in sequence. Keys are
the `name` keyword argument to the operation (typically, a random
variable's `name`) and values are the corresponding output of the
operation. If the operation has no name, it is not recorded.
#### Examples
```python
import edward2 as ed
def probabilistic_matrix_factorization():
users = ed.Normal(0., 1., sample_shape=[5000, 128], name="users")
items = ed.Normal(0., 1., sample_shape=[7500, 128], name="items")
ratings = ed.Normal(loc=tf.matmul(users, items, transpose_b=True),
scale=0.1,
name="ratings")
return ratings
with ed.tape() as model_tape:
ratings = probabilistic_matrix_factorization()
assert model_tape["users"].shape == (5000, 128)
assert model_tape["items"].shape == (7500, 128)
assert model_tape["ratings"] == ratings
```
"""
tape_data = collections.OrderedDict({})
def | (f, *args, **kwargs):
"""Records execution to a tape."""
name = kwargs.get("name")
output = traceable(f)(*args, **kwargs)
if name:
tape_data[name] = output
return output
with trace(record):
yield tape_data
| record |
camera_test.go | package sonycrapi | import "testing"
func TestCamera(t *testing.T) {
} | |
Bricks.js | /**
* Bricks Manager
*/
class Bricks {
/**
* Bricks Manager constructor
*/
constructor() {
this.container = document.querySelector(".bricks");
this.elements = [];
this.horizBricks = 5;
this.vertBricks = 4;
this.brickHeight = 2.5;
this.brickWidth = 4.6;
this.bottom = 0;
this.create();
}
/**
* Destroys the bricks
*/
destroy() {
this.removeContent();
}
/**
* Creates the bricks
*/
create() {
for (let i = 0; i < this.vertBricks; i += 1) {
for (let j = 0; j < this.horizBricks; j += 1) {
this.createBrick(i, j);
}
}
this.elements.reverse();
this.bottom = this.elements[0].height * this.vertBricks;
this.container.classList.add("fade");
window.setTimeout(() => {
this.container.classList.remove("fade");
}, 1000);
}
/**
* Creates a single brick
* @param {number} row
* @param {number} column
*/
createBrick(row, column) {
let data = { element : document.createElement("DIV") };
data.element.style.top = (this.brickHeight * row) + "em";
data.element.style.left = (this.brickWidth * column) + "em";
this.container.appendChild(data.element);
data.top = data.element.offsetTop;
data.left = data.element.offsetLeft;
data.width = data.element.offsetWidth;
data.height = data.element.offsetHeight;
this.elements.push(data);
}
| * @return {boolean} True if the ball crashed a brick
*/
crash(ball) {
if (ball.getPosition().top > this.bottom) {
return false;
}
return this.elements.some((element, index) => {
if (this.bottomCrash(ball, element) ||
this.leftCrash(ball, element) ||
this.rightCrash(ball, element) ||
this.topCrash(ball, element)) {
this.remove(element, index);
return true;
}
return false;
});
}
/**
* If the ball crashed the bottom part of the brick, change the ball direction
* @param {Ball} ball
* @param {{element: DOM, top: number, left: number}} brick
* @return {boolean} True if the ball crashed the bottom part of the brick
*/
bottomCrash(ball, brick) {
let pos = ball.getPosition();
if (this.isPointInElement(pos.top, pos.left + ball.getSize() / 2, brick)) {
ball.setDirTop(1);
return true;
}
return false;
}
/**
* If the ball crashed the left part of the brick, change the ball direction
* @param {Ball} ball
* @param {{element: DOM, top: number, left: number}} brick
* @return {boolean} True if the ball crashed the left part of the brick
*/
leftCrash(ball, brick) {
let pos = ball.getPosition(),
top = pos.top + ball.getSize() / 2,
left = pos.left + ball.getSize();
if (this.isPointInElement(top, left, brick)) {
ball.setDirLeft(-1);
return true;
}
return false;
}
/**
* If the ball crashed the right part of the brick, change the ball direction
* @param {Ball} ball
* @param {{element: DOM, top: number, left: number}} brick
* @return {boolean} True if the ball crashed the right part of the brick
*/
rightCrash(ball, brick) {
let pos = ball.getPosition();
if (this.isPointInElement(pos.top + ball.getSize() / 2, pos.left, brick)) {
ball.setDirLeft(-1);
return true;
}
return false;
}
/**
* If the ball crashed the top part of the brick, change the ball direction
* @param {Ball} ball
* @param {{element: DOM, top: number, left: number}} brick
* @return {boolean} True if the ball crashed the top part of the brick
*/
topCrash(ball, brick) {
let pos = ball.getPosition(),
top = pos.top + ball.getSize(),
left = pos.left + ball.getSize() / 2;
if (this.isPointInElement(top, left, brick)) {
ball.setDirTop(-1);
return true;
}
return false;
}
/**
* Destroys a Brick at the given index
* @param {{element: DOM, top: number, left: number}} element
* @param {number} index
*/
remove(element, index) {
this.elements.splice(index, 1);
let el = element.element;
el.style.borderWidth = "1.5em";
window.setTimeout(() => {
if (el) {
Utils.removeElement(el);
}
}, 500);
}
/**
* Recreate the bricks and reduce the ship width
* @return {boolean}
*/
restart() {
if (this.elements.length === 0) {
this.removeContent();
this.create();
return true;
}
return false;
}
/**
* Destroys all the bricks
*/
removeContent() {
this.container.innerHTML = "";
}
/**
* Check if the given position is inside the given element
* @param {number} top
* @param {number} left
* @param {{element: DOM, top: number, left: number}} element
* @return {boolean}
*/
isPointInElement(top, left, element) {
return (
top >= element.top && top <= element.top + element.height &&
left >= element.left && left <= element.left + element.width
);
}
} | /**
* Check if the Ball crashed any brick and remove it when it did
* @param {Ball} ball
|
gradient_check.py | import numpy as np
from random import randrange
def eval_numerical_gradient(f, x, verbose=True, h=0.00001):
"""
a naive implementation of numerical gradient of f at x
- f should be a function that takes a single argument
- x is the point (numpy array) to evaluate the gradient at
"""
fx = f(x) # evaluate function value at original point
grad = np.zeros_like(x)
# iterate over all indexes in x
it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
# evaluate function at x+h
ix = it.multi_index
oldval = x[ix]
x[ix] = oldval + h # increment by h
fxph = f(x) # evalute f(x + h)
x[ix] = oldval - h
fxmh = f(x) # evaluate f(x - h)
x[ix] = oldval # restore
# compute the partial derivative with centered formula
grad[ix] = (fxph - fxmh) / (2 * h) # the slope
if verbose:
print(ix, grad[ix])
it.iternext() # step to next dimension
return grad
def eval_numerical_gradient_array(f, x, df, h=1e-5):
"""
Evaluate a numeric gradient for a function that accepts a numpy
array and returns a numpy array.
"""
grad = np.zeros_like(x)
it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
ix = it.multi_index
oldval = x[ix]
x[ix] = oldval + h
pos = f(x).copy()
x[ix] = oldval - h
neg = f(x).copy()
x[ix] = oldval
grad[ix] = np.sum((pos - neg) * df) / (2 * h)
it.iternext()
return grad
def eval_numerical_gradient_blobs(f, inputs, output, h=1e-5):
"""
Compute numeric gradients for a function that operates on input
and output blobs.
We assume that f accepts several input blobs as arguments, followed by a blob
into which outputs will be written. For example, f might be called like this:
f(x, w, out)
where x and w are input Blobs, and the result of f will be written to out.
Inputs:
- f: function
- inputs: tuple of input blobs
- output: output blob
- h: step size
"""
numeric_diffs = []
for input_blob in inputs:
diff = np.zeros_like(input_blob.diffs)
it = np.nditer(input_blob.vals, flags=['multi_index'],
op_flags=['readwrite'])
while not it.finished:
idx = it.multi_index
orig = input_blob.vals[idx]
input_blob.vals[idx] = orig + h
f(*(inputs + (output,)))
pos = np.copy(output.vals)
input_blob.vals[idx] = orig - h
f(*(inputs + (output,)))
neg = np.copy(output.vals)
input_blob.vals[idx] = orig | diff[idx] = np.sum((pos - neg) * output.diffs) / (2.0 * h)
it.iternext()
numeric_diffs.append(diff)
return numeric_diffs
def eval_numerical_gradient_net(net, inputs, output, h=1e-5):
return eval_numerical_gradient_blobs(lambda *args: net.forward(),
inputs, output, h=h)
def grad_check_sparse(f, x, analytic_grad, num_checks=10, h=1e-5):
"""
sample a few random elements and only return numerical
in this dimensions.
"""
for i in range(num_checks):
ix = tuple([randrange(m) for m in x.shape])
oldval = x[ix]
x[ix] = oldval + h # increment by h
fxph = f(x) # evaluate f(x + h)
x[ix] = oldval - h # increment by h
fxmh = f(x) # evaluate f(x - h)
x[ix] = oldval # reset
grad_numerical = (fxph - fxmh) / (2 * h)
grad_analytic = analytic_grad[ix]
rel_error = abs(grad_numerical - grad_analytic) / (abs(grad_numerical) + abs(grad_analytic))
print('numerical: %f analytic: %f, relative error: %e' % (grad_numerical, grad_analytic, rel_error)) | |
RegisteredTypeInfo.py | # encoding: utf-8
# module gi._gi
# from /usr/lib/python3/dist-packages/gi/_gi.cpython-35m-x86_64-linux-gnu.so
# by generator 1.145
# no doc
# imports
import _gobject as _gobject # <module '_gobject'>
import _glib as _glib # <module '_glib'>
import gi as __gi
import gobject as __gobject
class RegisteredTypeInfo(__gi.BaseInfo):
# no doc
def get_g_type(self, *args, **kwargs): # real signature unknown
pass
def get_type_init(self, *args, **kwargs): # real signature unknown | pass
def get_type_name(self, *args, **kwargs): # real signature unknown
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass | |
main.go | package main
import (
"fmt"
"github.com/ascode/rset/collection"
"github.com/ascode/rset/test_data"
)
func main() {
// 新建一个RSet
rset := collection.NewSet(test_data.StudentsGood, test_data.StudentsBad)
printSet(rset)
fmt.Println("---------------")
rset.SortDescDowngradeBy("Id") // 集合按照排序字段顺次降级排序
printSet(rset)
fmt.Println("---------------")
rset.SortAscDowngradeBy("Id") // 集合按照排序字段顺次升级排序
printSet(rset)
fmt.Println("")
fmt.Println("----------------------------------------------")
s := rset.SkipReturn(1).LimitReturn(2) // 留下第1个开始连续2个元素
printSet(&s)
fmt.Println("----------------------------------------------")
std1 := test_data.Student{
Id:5,
Name:"小金李",
Age:0,
IsNewbie:true,
}
rset.Add(std1) // 添加一个元素
printSet(rset)
fmt.Println("----------------------------------------------")
var newStudentCanInterface interface{} = []test_data.Student{} // 新建一个装载结果的interface{}容器
fmt.Println("fill前的newStudentCanInterface", newStudentCanInterface)
rset.Fill(&newStudentCanInterface) // 将rset填充到容器
fmt.Println("fill之后的newStudentCanInterface", newStudentCanInterface)
newStudentCan := newStudentCanInterface.([]test_data.Student) // 将interface{}转换成其原始类型
fmt.Println("强转对象之后的newStudentCan:", newStudentCan)
}
func printSet(rset *collection.RSet) {
for _, obj := range rset.Set {
fmt.Printf("%d,%s,%d,%-v\n", obj["Id"], obj["Name"], obj["Age"], obj["IsNewbie"])
}
}
| ||
test_local_storage.py | """
Unit test for custom wrapper around local storage
"""
import unittest
import sys
import json
from pathlib import Path
BASE_DIR = Path(__file__).parent.parent
sys.path.append(str(BASE_DIR.resolve()))
#pylint: disable=wrong-import-position
from core.local_storage_wrapper import LocalStorage
import testutil
class TestLocalStorage(unittest.TestCase):
"""Testing getting, putting, deleting and listing operations of a test file
"""
def | (self):
"""Initial setup
"""
root = testutil.set_up_test_local_directory()
self.storage = LocalStorage(root)
def test_get_file(self):
"""Can read contents of a file given its key?
"""
key = 'patents/US7654321B2.json'
contents = self.storage.get(key)
self.assertIsInstance(contents, bytes)
self.assertGreater(len(contents), 0)
data = json.loads(contents)
self.assertEqual(data['publicationNumber'], 'US7654321B2')
def test_error_when_reading_non_existing_file(self):
"""Raises exception when reading a non existing file?
"""
invalid_key = 'patents/arbitrary.json'
attempt = lambda: self.storage.get(invalid_key)
self.assertRaises(FileNotFoundError, attempt)
def test_put_and_delete_file(self):
"""Can create new files, read them back, and delete them?
"""
key = 'patents/US7654321B2.json'
contents = self.storage.get(key)
new_key = 'patents/new.json'
self.storage.put(new_key, contents)
retrieved = self.storage.get(new_key)
self.assertEqual(retrieved, contents)
self.storage.delete(new_key)
attempt = lambda: self.storage.get(new_key)
self.assertRaises(FileNotFoundError, attempt)
def test_list_files(self):
"""Can list files?
"""
prefix = 'patents/US'
matches = self.storage.list(prefix)
self.assertIs(type(matches), list)
self.assertGreater(len(matches), 0)
key = 'patents/notexist'
output = self.storage.list(key)
self.assertEqual(len(output), 0)
if __name__ == "__main__":
unittest.main()
| setUp |
PopulateTripEndTime.go | package main
import (
_ "github.com/go-sql-driver/mysql"
"database/sql"
"log"
"encoding/json"
"math"
"github.com/remeh/sizedwaitgroup"
)
type TripBasic struct {
id int
polyline string
tripInSeconds uint64
}
func main() {
totalRows := 1710589
rowsPerThread := 4000
//totalRows := 41
rowsCount := int(math.Ceil(float64(totalRows)/float64(rowsPerThread)))
swg := sizedwaitgroup.New(25)
for i:=0;i<rowsCount;i++ {
swg.Add()
go performGetAndUpdateRows(i, rowsPerThread, &swg)
}
swg.Wait()
}
func performGetAndUpdateRows(i, rowsPerThread int, wg *sizedwaitgroup.SizedWaitGroup) |
func updateTripTime(tripId int, lengthInSeconds int, db *sql.DB) {
query, err := db.Prepare("UPDATE trip set trip_time_seconds = ? where id = ?")
if err != nil {
panic(err.Error())
}
defer query.Close()
_, err = query.Exec(lengthInSeconds, tripId)
if err != nil {
log.Fatal(err)
}
}
/**
Function is final and tested
*/
func getTrips(startId, endId int, db *sql.DB) []TripBasic{
var trips []TripBasic
query, err := db.Prepare("SELECT t.id, polyline from trip t where t.id >= ? and t.id < ?")
if err != nil {
panic(err.Error())
}
defer query.Close()
rows, err := query.Query(startId, endId)
if err != nil {
panic (err.Error())
}
defer rows.Close()
for rows.Next() {
var tripBasic TripBasic
err := rows.Scan(&tripBasic.id, &tripBasic.polyline)
if err != nil {
log.Println(rows)
log.Fatal(err)
}
trips = append(trips, tripBasic)
}
return trips;
}
| {
db, err := sql.Open("mysql", "root:123@/thesis")
if err != nil {
panic(err.Error()) // Just for example purpose. You should use proper error handling instead of panic
}
defer db.Close()
log.Println("Performing Update for", i, rowsPerThread)
trips := getTrips(i*rowsPerThread, (i+1)*rowsPerThread, db)
for _, trip := range trips {
var polyline [][]float64
polylineBytes := []byte(trip.polyline)
if !json.Valid(polylineBytes) {
continue
}
json.Unmarshal(polylineBytes, &polyline)
updateTripTime(trip.id, 15*len(polyline), db)
}
log.Println("Performed Update for", i, rowsPerThread)
wg.Done()
} |
levenshtein.go | package levenshtein
import (
"math"
"strings"
)
// DamerauLevenshteinDistance calculates the damerau-levenshtein distance between s1 and s2.
// Reference: [Damerau-Levenshtein Distance](http://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)
// Note that this calculation's result isn't normalized. (not between 0 and 1.)
// and if s1 and s2 are exactly the same, the result is 0.
func DamerauLevenshteinDistance(s1, s2 string) int {
if s1 == s2 {
return 0
}
s1Array := strings.Split(s1, "")
s2Array := strings.Split(s2, "")
lenS1Array := len(s1Array)
lenS2Array := len(s2Array)
m := make([][]int, lenS1Array+1)
var cost int
for i := range m {
m[i] = make([]int, lenS2Array+1)
}
for i := 0; i < lenS1Array+1; i++ {
for j := 0; j < lenS2Array+1; j++ {
if i == 0 {
m[i][j] = j
} else if j == 0 {
m[i][j] = i
} else {
cost = 0
if s1Array[i-1] != s2Array[j-1] {
cost = 1
}
m[i][j] = min(m[i-1][j]+1, m[i][j-1]+1, m[i-1][j-1]+cost)
if i > 1 && j > 1 && s1Array[i-1] == s2Array[j-2] && s1Array[i-2] == s2Array[j-1] {
m[i][j] = min(m[i][j], m[i-2][j-2]+cost)
}
}
}
}
return m[lenS1Array][lenS2Array]
}
// min returns the minimum number of passed int slices.
func min(is ...int) int | {
min := math.MaxInt32
for _, v := range is {
if min > v {
min = v
}
}
return min
} |
|
crashing.py | #!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Votes according to components stability (crashes vs time)
:author: Thomas Calmant
:license: Apache Software License 2.0
:version: 3.0.0
..
Copyright 2014 isandlaTech
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.
"""
# Standard library
import logging
import operator
import time
# iPOPO Decorators
from pelix.ipopo.decorators import ComponentFactory, Provides, Instantiate, \
Invalidate, Validate
# Composer
import cohorte.composer
# ------------------------------------------------------------------------------
# Bundle version
import cohorte.version
__version__=cohorte.version.__version__
# ------------------------------------------------------------------------------
_logger = logging.getLogger(__name__)
# ------------------------------------------------------------------------------
@ComponentFactory()
@Provides(cohorte.composer.SERVICE_NODE_CRITERION_RELIABILITY)
@Instantiate('cohorte-composer-node-criterion-crash')
class CrashCriterion(object):
"""
Votes for the isolate that will host a component according to the
configuration
"""
def __init__(self):
"""
Sets up members
"""
# Component name -> Rating
self._ratings = {}
# Component name -> Time of last crash
self._last_crash = {}
# Unstable components names
self._unstable = set()
def | (self):
"""
String representation
"""
return "Components reliability rating"
@Validate
def validate(self, context):
"""
Component validated
"""
# TODO: load initial ratings
self._ratings.clear()
@Invalidate
def invalidate(self, context):
"""
Component invalidated
"""
self._ratings.clear()
self._last_crash.clear()
self._unstable.clear()
def _update_rating(self, component, delta):
"""
Updates the rating of the component with the given delta
:param component: A component name
:param delta: Rating modification
"""
# Normalize the new rating
new_rating = self._ratings.setdefault(component, 50) + delta
if new_rating < 0:
new_rating = 0
elif new_rating > 100:
new_rating = 100
# Store it
self._ratings[component] = new_rating
if new_rating < 5:
# Lower threshold reached: components are incompatible
self._unstable.add(component)
def handle_event(self, event):
"""
Does nothing: this elector only cares about what is written in
configuration files
"""
# Get the implicated components
components = sorted(set(component.name
for component in event.components))
if event.kind == 'timer':
self.on_timer(components)
elif event.kind == 'isolate.lost':
self.on_crash(components)
def on_crash(self, components):
"""
An isolate has been lost
:param components: Names of the components in the crashed isolate
"""
# Get the time of the crash
now = time.time()
# Update their stability ratings
for name in components:
if name not in self._unstable:
# Get the last crash information
last_crash = self._last_crash.get(name, 0)
time_since_crash = now - last_crash
if time_since_crash < 60:
# Less than 60s since the last crash
self._update_rating(name, -10)
else:
# More than 60s
self._update_rating(name, -5)
# Update the last crash information
self._last_crash[name] = now
def on_timer(self, components):
"""
The timer ticks: some components have been OK before last tick and now
:param components: Names of the components that well behaved
"""
# Get the tick time
now = time.time()
# Update their stability ratings
for name in components:
if name not in self._unstable:
# Get the last crash information
last_crash = self._last_crash.get(name, 0)
time_since_crash = now - last_crash
if time_since_crash > 120:
# More than 120s since the last crash
self._update_rating(name, +8)
elif time_since_crash > 60:
# More than 60s since the last crash
self._update_rating(name, +4)
# do nothing the minute right after a crash
def compute_stats(self, components):
"""
Computes statistics about the components of an isolate
:param components: Components already assigned to the isolate
"""
# Get the components names
names = set(component.name for component in components)
# TODO: compute variance too ?
# Mean rating
return sum(self._ratings.setdefault(name, 90)
for name in names) / len(names)
def vote(self, candidates, subject, ballot):
"""
Votes the isolate that matches the best the stability of the given
component
:param candidates: Isolates to vote for
:param subject: The component to place
:param ballot: The vote ballot
"""
# Get/Set the rating of the component
rating = self._ratings.setdefault(subject.name, 50.0)
# Distance with other components
distances = []
for candidate in candidates:
if candidate.components:
if len(candidate.components) == 1 \
and subject in candidate.components:
# Single one in the isolate where we were
distances.append((0, candidate))
elif subject.name in self._unstable:
# Don't try to go with other components...
ballot.append_against(candidate)
elif rating > 20:
# Only accept to work with other components if the given
# one is stable enough (> 20% stability rating)
# Compute the mean and variance of the current components
# ratings
mean = self.compute_stats(candidate.components)
distance = abs(mean - rating)
if distance < 20:
# Prefer small distances
distances.append((distance, candidate))
else:
# Prefer non-"neutral" isolates
if not candidate.name:
distances.append((20, candidate))
else:
# First component of this isolate
distances.append((5, candidate))
# Sort computed distances (lower is better)
distances.sort(key=operator.itemgetter(0))
# Use them as our vote
ballot.set_for(distance[1] for distance in distances)
ballot.lock()
| __str__ |
etcdv3.go | package serverplugin
import (
"errors"
"fmt"
"net"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/docker/libkv"
"github.com/docker/libkv/store"
metrics "github.com/rcrowley/go-metrics"
etcd "github.com/smallnest/libkv-etcdv3-store"
"github.com/smallnest/rpcx/log"
)
func init() |
// EtcdV3RegisterPlugin implements etcd registry.
type EtcdV3RegisterPlugin struct {
// service address, for example, [email protected]:8972, [email protected]:1234
ServiceAddress string
// etcd addresses
EtcdServers []string
// base path for rpcx server, for example com/example/rpcx
BasePath string
Metrics metrics.Registry
// Registered services
Services []string
metasLock sync.RWMutex
metas map[string]string
UpdateInterval time.Duration
Options *store.Config
kv store.Store
dying chan struct{}
done chan struct{}
}
// Start starts to connect etcd cluster
func (p *EtcdV3RegisterPlugin) Start() error {
if p.done == nil {
p.done = make(chan struct{})
}
if p.dying == nil {
p.dying = make(chan struct{})
}
if p.kv == nil {
kv, err := libkv.NewStore(etcd.ETCDV3, p.EtcdServers, p.Options)
if err != nil {
log.Errorf("cannot create etcd registry: %v", err)
return err
}
p.kv = kv
}
err := p.kv.Put(p.BasePath, []byte("rpcx_path"), &store.WriteOptions{IsDir: true})
if err != nil && !strings.Contains(err.Error(), "Not a file") {
log.Errorf("cannot create etcd path %s: %v", p.BasePath, err)
return err
}
if p.UpdateInterval > 0 {
ticker := time.NewTicker(p.UpdateInterval)
go func() {
defer p.kv.Close()
// refresh service TTL
for {
select {
case <-p.dying:
close(p.done)
return
case <-ticker.C:
var data []byte
if p.Metrics != nil {
clientMeter := metrics.GetOrRegisterMeter("clientMeter", p.Metrics)
data = []byte(strconv.FormatInt(clientMeter.Count()/60, 10))
}
//set this same metrics for all services at this server
for _, name := range p.Services {
nodePath := fmt.Sprintf("%s/%s/%s", p.BasePath, name, p.ServiceAddress)
kvPair, err := p.kv.Get(nodePath)
if err != nil {
log.Infof("can't get data of node: %s, because of %v", nodePath, err.Error())
p.metasLock.RLock()
meta := p.metas[name]
p.metasLock.RUnlock()
err = p.kv.Put(nodePath, []byte(meta), &store.WriteOptions{TTL: p.UpdateInterval * 2})
if err != nil {
log.Errorf("cannot re-create etcd path %s: %v", nodePath, err)
}
} else {
v, _ := url.ParseQuery(string(kvPair.Value))
v.Set("tps", string(data))
p.kv.Put(nodePath, []byte(v.Encode()), &store.WriteOptions{TTL: p.UpdateInterval * 2})
}
}
}
}
}()
}
return nil
}
// Stop unregister all services.
func (p *EtcdV3RegisterPlugin) Stop() error {
if p.kv == nil {
kv, err := libkv.NewStore(etcd.ETCDV3, p.EtcdServers, p.Options)
if err != nil {
log.Errorf("cannot create etcd registry: %v", err)
return err
}
p.kv = kv
}
for _, name := range p.Services {
nodePath := fmt.Sprintf("%s/%s/%s", p.BasePath, name, p.ServiceAddress)
exist, err := p.kv.Exists(nodePath)
if err != nil {
log.Errorf("cannot delete path %s: %v", nodePath, err)
continue
}
if exist {
p.kv.Delete(nodePath)
log.Infof("delete path %s", nodePath, err)
}
}
close(p.dying)
<-p.done
return nil
}
// HandleConnAccept handles connections from clients
func (p *EtcdV3RegisterPlugin) HandleConnAccept(conn net.Conn) (net.Conn, bool) {
if p.Metrics != nil {
clientMeter := metrics.GetOrRegisterMeter("clientMeter", p.Metrics)
clientMeter.Mark(1)
}
return conn, true
}
// Register handles registering event.
// this service is registered at BASE/serviceName/thisIpAddress node
func (p *EtcdV3RegisterPlugin) Register(name string, rcvr interface{}, metadata string) (err error) {
if strings.TrimSpace(name) == "" {
err = errors.New("Register service `name` can't be empty")
return
}
if p.kv == nil {
etcd.Register()
kv, err := libkv.NewStore(etcd.ETCDV3, p.EtcdServers, nil)
if err != nil {
log.Errorf("cannot create etcd registry: %v", err)
return err
}
p.kv = kv
}
err = p.kv.Put(p.BasePath, []byte("rpcx_path"), &store.WriteOptions{IsDir: true})
if err != nil && !strings.Contains(err.Error(), "Not a file") {
log.Errorf("cannot create etcd path %s: %v", p.BasePath, err)
return err
}
nodePath := fmt.Sprintf("%s/%s", p.BasePath, name)
err = p.kv.Put(nodePath, []byte(name), &store.WriteOptions{IsDir: true})
if err != nil && !strings.Contains(err.Error(), "Not a file") {
log.Errorf("cannot create etcd path %s: %v", nodePath, err)
return err
}
nodePath = fmt.Sprintf("%s/%s/%s", p.BasePath, name, p.ServiceAddress)
err = p.kv.Put(nodePath, []byte(metadata), &store.WriteOptions{TTL: p.UpdateInterval * 2})
if err != nil {
log.Errorf("cannot create etcd path %s: %v", nodePath, err)
return err
}
p.Services = append(p.Services, name)
p.metasLock.Lock()
if p.metas == nil {
p.metas = make(map[string]string)
}
p.metas[name] = metadata
p.metasLock.Unlock()
return
}
func (p *EtcdV3RegisterPlugin) RegisterFunction(serviceName, fname string, fn interface{}, metadata string) error {
return p.Register(serviceName, fn, metadata)
}
func (p *EtcdV3RegisterPlugin) Unregister(name string) (err error) {
if strings.TrimSpace(name) == "" {
err = errors.New("Register service `name` can't be empty")
return
}
if p.kv == nil {
etcd.Register()
kv, err := libkv.NewStore(etcd.ETCDV3, p.EtcdServers, nil)
if err != nil {
log.Errorf("cannot create etcd registry: %v", err)
return err
}
p.kv = kv
}
err = p.kv.Put(p.BasePath, []byte("rpcx_path"), &store.WriteOptions{IsDir: true})
if err != nil && !strings.Contains(err.Error(), "Not a file") {
log.Errorf("cannot create etcd path %s: %v", p.BasePath, err)
return err
}
nodePath := fmt.Sprintf("%s/%s", p.BasePath, name)
err = p.kv.Put(nodePath, []byte(name), &store.WriteOptions{IsDir: true})
if err != nil && !strings.Contains(err.Error(), "Not a file") {
log.Errorf("cannot create etcd path %s: %v", nodePath, err)
return err
}
nodePath = fmt.Sprintf("%s/%s/%s", p.BasePath, name, p.ServiceAddress)
err = p.kv.Delete(nodePath)
if err != nil {
log.Errorf("cannot create consul path %s: %v", nodePath, err)
return err
}
var services = make([]string, 0, len(p.Services)-1)
for _, s := range p.Services {
if s != name {
services = append(services, s)
}
}
p.Services = services
p.metasLock.Lock()
if p.metas == nil {
p.metas = make(map[string]string)
}
delete(p.metas, name)
p.metasLock.Unlock()
return
}
| {
etcd.Register()
} |
inventory_slot.rs | use crate::{Item, ItemStack};
use core::mem;
use serde::{Deserialize, Serialize};
/// Represents an Inventory slot. May be empty
/// or filled (contains an `ItemStack`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum InventorySlot {
Filled(ItemStack),
Empty,
}
impl Default for InventorySlot {
fn default() -> Self {
Self::Empty
}
}
impl From<Option<ItemStack>> for InventorySlot {
fn from(it: Option<ItemStack>) -> Self {
it.map(Self::Filled).unwrap_or_default()
}
}
impl From<InventorySlot> for Option<ItemStack> {
fn from(it: InventorySlot) -> Self {
it.into_option()
}
}
impl InventorySlot {
/// Creates a new instance with the type `kind` and `count` items
#[must_use]
#[allow(clippy::missing_panics_doc)]
pub fn new(kind: Item, count: u32) -> Self {
ItemStack::new(kind, count)
.map(Self::Filled)
.unwrap_or_default()
}
/// If instace of `Self::Filled`, then it returns `Some(stack_size)`
/// where `stack_size` is the biggest number of items allowable
/// for the given item in a stack.
/// If instance of `Self::Empty`, then we can't know the stack
/// size and None is returned.
#[must_use]
pub fn stack_size(&self) -> Option<u32> {
self.map_ref(ItemStack::stack_size)
}
/// Takes all items and makes self empty.
pub fn take_all(&mut self) -> Self {
mem::take(self)
}
/// Takes half (rounded down) of the items in self.
pub fn take_half(&mut self) -> Self {
let half = (self.count() + 1) / 2;
self.try_take(half)
}
/// Tries to take the specified amount from 'self'
/// and put it into the output. If amount is bigger
/// then what self can provide then this is the same
/// as calling take.
#[allow(clippy::missing_panics_doc)]
pub fn try_take(&mut self, amount: u32) -> Self {
if amount == 0 {
return Self::Empty;
}
if let Self::Filled(stack) = self {
if stack.count() <= amount {
// We take all and set self to empty
mem::take(self)
} else {
// We take some of self.
let mut out = stack.clone();
// `amount` != 0
out.set_count(amount).unwrap();
// `stack.count` > amount
stack.remove(amount).unwrap();
Self::Filled(out)
}
} else {
Self::Empty
}
}
/// Tries to take the exact specified amount from 'self',
/// but if that is not possible then it returns None.
pub fn take(&mut self, amount: u32) -> Option<Self> {
if amount <= self.count() {
Some(self.try_take(amount))
} else {
None
}
}
/// Returns the number of items stored in the inventory slot.
#[must_use]
pub fn count(&self) -> u32 {
self.map_ref(ItemStack::count).unwrap_or(0)
}
/// Should only be called if the caller can guarantee that there is space
/// such that the new could is not greater then `self.stack_size`().
/// And that the slot actually contains an item.
fn add_count(&mut self, n: u32) {
self.option_mut()
.expect("add count called on empty inventory slot!")
.add(n)
.expect("new item count exceeds stack size");
}
/// Transfers up to `n` items from 'self' to `other`.
#[allow(clippy::missing_panics_doc)]
pub fn transfer_to(&mut self, n: u32, other: &mut Self) {
if !self.is_mergable(other) {
return;
}
match (self.is_filled(), other.is_filled()) {
(true, true) => {
// `other` is guaranteed to be `Filled`
let space_in_other = other.stack_size().unwrap() - other.count();
let moving = n.min(space_in_other).min(self.count());
let taken = self.try_take(moving);
other.add_count(taken.count());
}
(true, false) => |
(false, _) => {} // No items to move
}
}
/// Checks if the `InventorySlot` is empty.
#[must_use]
pub const fn is_empty(&self) -> bool {
matches!(self, Self::Empty)
}
/// Checks if the `InventorySlot` is filled.
#[must_use]
pub const fn is_filled(&self) -> bool {
!self.is_empty()
}
/// Returns the number of items moved from other to self.
#[allow(clippy::missing_panics_doc)]
pub fn merge(&mut self, other: &mut Self) -> u32 {
if !self.is_mergable(other) {
return 0;
}
match (self.is_filled(), other.is_filled()) {
(true, true) => {
// `self` is `Filled`
let moving = (self.stack_size().unwrap() - self.count()).min(other.count());
let taken = other.try_take(moving);
self.add_count(taken.count());
taken.count()
}
(_, false) => 0,
(false, true) => {
mem::swap(self, other);
self.count()
}
}
}
/// Returns true if either one is empty, or they
/// contain the same `ItemStack` type. Does *not* consider
/// if there is space enough for the move to happen.
#[must_use]
pub fn is_mergable(&self, other: &Self) -> bool {
match (self, other) {
(InventorySlot::Filled(a), InventorySlot::Filled(b)) => a.stackable_types(b),
(InventorySlot::Empty, _) | (_, InventorySlot::Empty) => true,
}
}
/// Returns the item kind of the inventory slot if it is filled,
/// otherwise it returns None.
#[must_use]
pub fn item_kind(&self) -> Option<Item> {
self.map_ref(ItemStack::item)
}
/// Convert `self` into an `Option<ItemStack>`
#[must_use]
pub fn into_option(self) -> Option<ItemStack> {
match self {
InventorySlot::Filled(f) => Some(f),
InventorySlot::Empty => None,
}
}
/// Convert a reference to `self` into an `Option<&ItemStack>`
#[must_use]
pub const fn option_ref(&self) -> Option<&ItemStack> {
match self {
InventorySlot::Filled(f) => Some(f),
InventorySlot::Empty => None,
}
}
/// Convert a mutable reference to `self` into an `Option<&mut ItemStack>`
#[must_use]
pub fn option_mut(&mut self) -> Option<&mut ItemStack> {
match self {
InventorySlot::Filled(f) => Some(f),
InventorySlot::Empty => None,
}
}
/// Map `f` over the inner item stack, optionally returning the resulting value.
#[must_use]
pub fn map<F: FnOnce(ItemStack) -> U, U>(self, f: F) -> Option<U> {
self.into_option().map(f)
}
/// Map `f` over the inner item stack, optionally returning the resulting value.
#[must_use]
pub fn map_ref<F: FnOnce(&ItemStack) -> U, U>(&self, f: F) -> Option<U> {
self.option_ref().map(f)
}
/// Map `f` over the inner item stack, optionally returning the resulting value.
#[must_use]
pub fn map_mut<F: FnOnce(&mut ItemStack) -> U, U>(&mut self, f: F) -> Option<U> {
self.option_mut().map(f)
}
}
impl IntoIterator for InventorySlot {
type Item = ItemStack;
type IntoIter = std::option::IntoIter<ItemStack>;
fn into_iter(self) -> Self::IntoIter {
self.into_option().into_iter()
}
}
impl<'a> IntoIterator for &'a InventorySlot {
type Item = &'a ItemStack;
type IntoIter = std::option::IntoIter<&'a ItemStack>;
fn into_iter(self) -> Self::IntoIter {
self.option_ref().into_iter()
}
}
impl<'a> IntoIterator for &'a mut InventorySlot {
type Item = &'a mut ItemStack;
type IntoIter = std::option::IntoIter<&'a mut ItemStack>;
fn into_iter(self) -> Self::IntoIter {
self.option_mut().into_iter()
}
}
#[cfg(test)]
mod test {
use crate::{InventorySlot, Item};
#[test]
fn test_merge() {
let mut a = InventorySlot::new(Item::Stone, 5);
let mut b = InventorySlot::new(Item::Stone, 30);
a.merge(&mut b);
println!("{:?}", a);
assert!(a.is_mergable(&b));
assert_eq!(a.count(), 35);
assert!(b.is_empty());
a = InventorySlot::new(Item::Stone, 60);
b = InventorySlot::new(Item::Stone, 10);
assert_eq!(a.merge(&mut b), 4);
assert_eq!(b.count(), 6);
a = InventorySlot::new(Item::AcaciaDoor, 1);
b = InventorySlot::new(Item::AcaciaButton, 1);
assert_eq!(a.merge(&mut b), 0);
a = InventorySlot::new(Item::Stone, 1);
b = InventorySlot::Empty;
assert_eq!(a.merge(&mut b), 0);
a = InventorySlot::Empty;
b = InventorySlot::new(Item::Stone, 10);
assert_eq!(a.merge(&mut b), 10);
assert!(b.is_empty());
}
#[test]
fn take_half() {
let mut a = InventorySlot::new(Item::Stone, 5);
let b = a.take_half();
assert_eq!(a.count() + b.count(), 5);
assert_eq!(a.count(), 2);
a = InventorySlot::new(Item::Stone, 1);
let b = a.take_half();
assert_eq!(a.count(), 0);
assert_eq!(b.count(), 1);
a = InventorySlot::Empty;
let b = a.take_half();
assert!(a.is_empty() && b.is_empty());
}
#[test]
fn transfer_to() {
let mut a = InventorySlot::new(Item::Stone, 5);
let mut b = InventorySlot::new(Item::Stone, 2);
a.transfer_to(2, &mut b);
assert_eq!(a.count(), 3);
assert_eq!(b.count(), 4);
a = InventorySlot::new(Item::AcaciaDoor, 3);
b = InventorySlot::new(Item::AcaciaButton, 5);
a.transfer_to(1, &mut b);
assert_eq!(a.count(), 3);
assert_eq!(b.count(), 5);
a = InventorySlot::new(Item::Stone, 3);
b = InventorySlot::new(Item::Stone, 5);
a.transfer_to(10, &mut b);
assert_eq!(a.count(), 0);
assert_eq!(b.count(), 8);
a = InventorySlot::new(Item::Stone, 10);
b = InventorySlot::new(Item::Stone, 60);
a.transfer_to(20, &mut b);
assert_eq!(a.count(), 6);
assert_eq!(b.count(), 64);
a = InventorySlot::new(Item::Stone, 5);
b = InventorySlot::Empty;
a.transfer_to(2, &mut b);
assert_eq!(a.count(), 3);
assert_eq!(b.count(), 2);
a = InventorySlot::Empty;
b = InventorySlot::new(Item::Stone, 5);
a.transfer_to(2, &mut b);
assert_eq!(a.count(), 0);
assert_eq!(b.count(), 5);
}
#[test]
fn try_take() {
let mut a = InventorySlot::new(Item::Stone, 64);
assert_eq!(a.try_take(16), InventorySlot::new(Item::Stone, 16));
assert_eq!(a.try_take(0), InventorySlot::Empty);
assert_eq!(a.try_take(50), InventorySlot::new(Item::Stone, 48));
assert_eq!(a.try_take(2), InventorySlot::Empty);
a = InventorySlot::new(Item::Stone, 5);
assert_eq!(a.try_take(u32::MAX), InventorySlot::new(Item::Stone, 5));
}
#[test]
fn take() {
let mut a = InventorySlot::new(Item::Stone, 64);
assert_eq!(a.take(16), Some(InventorySlot::new(Item::Stone, 16)));
assert_eq!(a.take(0), Some(InventorySlot::Empty));
assert_eq!(a.take(50), None);
assert_eq!(a.take(48), Some(InventorySlot::new(Item::Stone, 48)));
assert_eq!(a.take(1), None);
}
}
| {
let taken = self.try_take(n);
*other = taken;
} |
filemanager.py | # Credits to Userge for Remove and Rename
import io
import os
import os.path
import re
import shutil
import time
from datetime import datetime
from os.path import basename, dirname, exists, isdir, isfile, join, relpath
from shutil import rmtree
from tarfile import TarFile, is_tarfile
from zipfile import ZIP_DEFLATED, BadZipFile, ZipFile, is_zipfile
from natsort import os_sorted
from rarfile import BadRarFile, RarFile, is_rarfile
from userbot import CMD_HANDLER as cmd
from userbot import CMD_HELP, TEMP_DOWNLOAD_DIRECTORY, bot
from userbot.events import geez_cmd
from userbot.utils import humanbytes
MAX_MESSAGE_SIZE_LIMIT = 4095
@bot.on(geez_cmd(outgoing=True, pattern=r"ls(?: |$)(.*)"))
async def lst(event):
if event.fwd_from:
return
cat = event.pattern_match.group(1)
path = cat or os.getcwd()
if not exists(path):
await event.edit(
f"Tidak ada direktori atau file dengan nama `{cat}` coba check lagi!"
)
return
if isdir(path):
if cat:
msg = "**Folder dan File di `{}`** :\n\n".format(path)
else:
msg = "**Folder dan File di Direktori Saat Ini** :\n\n"
lists = os.listdir(path)
files = ""
folders = ""
for contents in os_sorted(lists):
catpath = path + "/" + contents
if not isdir(catpath):
size = os.stat(catpath).st_size
if contents.endswith((".mp3", ".flac", ".wav", ".m4a")):
files += "🎵 "
elif contents.endswith((".opus")):
files += "🎙 "
elif contents.endswith(
(".mkv", ".mp4", ".webm", ".avi", ".mov", ".flv")
):
files += "🎞 "
elif contents.endswith(
(".zip", ".tar", ".tar.gz", ".rar", ".7z", ".xz")
):
files += "🗜 "
elif contents.endswith(
(".jpg", ".jpeg", ".png", ".gif", ".bmp", ".ico", ".webp")
):
files += "🖼 "
elif contents.endswith((".exe", ".deb")):
files += "⚙️ "
elif contents.endswith((".iso", ".img")):
files += "💿 "
elif contents.endswith((".apk", ".xapk")):
files += "📱 "
elif contents.endswith((".py")):
files += "🐍 "
else:
files += "📄 "
files += f"`{contents}` (__{humanbytes(size)}__)\n"
else:
folders += f"📁 `{contents}`\n"
msg = msg + folders + files if files or folders else msg + "__empty path__"
else:
size = os.stat(path).st_size
msg = "Rincian file yang diberikan:\n\n"
if path.endswith((".mp3", ".flac", ".wav", ".m4a")):
mode = "🎵 "
elif path.endswith((".opus")):
mode = "🎙 "
elif path.endswith((".mkv", ".mp4", ".webm", ".avi", ".mov", ".flv")):
mode = "🎞 "
elif path.endswith((".zip", ".tar", ".tar.gz", ".rar", ".7z", ".xz")):
mode = "🗜 "
elif path.endswith((".jpg", ".jpeg", ".png", ".gif", ".bmp", ".ico", ".webp")):
mode = "🖼 "
elif path.endswith((".exe", ".deb")):
mode = "⚙️ "
elif path.endswith((".iso", ".img")):
mode = "💿 "
elif path.endswith((".apk", ".xapk")):
mode = "📱 "
elif path.endswith((".py")):
mode = "🐍 "
else:
mode = "📄 "
time.ctime(os.path.getctime(path))
time2 = time.ctime(os.path.getmtime(path))
time3 = time.ctime(os.path.getatime(path))
msg += f"**Location :** `{path}`\n"
msg += f"**Icon :** `{mode}`\n"
msg += f"**Size :** `{humanbytes(size)}`\n"
msg += f"**Last Modified Time:** `{time2}`\n"
msg += f"**Last Accessed Time:** `{time3}`"
if len(msg) > MAX_MESSAGE_SIZE_LIMIT:
with io.BytesIO(str.encode(msg)) as out_file:
out_file.name = "ls.txt"
await event.client.send_file(
event.chat_id,
out_file,
force_document=True,
allow_cache=False,
caption=path,
)
await event.delete()
else:
await event.edit(msg)
@bot.on(geez_cmd(outgoing=True, pattern=r"rm(?: |$)(.*)"))
async def rmove(event):
"""Removing Directory/File"""
cat = event.pattern_match.group(1)
if not cat:
await event.edit("`Lokasi file tidak ada!`")
return
if not exists(cat):
await event.edit("`Lokasi file tidak ada!`")
return
if isfile(cat):
os.remove(cat)
else:
rmtree(cat)
await event.edit(f"Dihapus `{cat}`")
@bot.on(geez_cmd(outgoing=True, pattern=r"rn ([^|]+)\|([^|]+)"))
async def rname(event):
"""Renaming Directory/File"""
cat = str(event.pattern_match.group(1)).strip()
new_name = str(event.pattern_match.group(2)).strip()
if not exists(cat):
await event.edit(f"file path : {cat} tidak ada!")
return
new_path = join(dirname(cat), new_name)
shutil.move(cat, new_path)
await event.edit(f"Diganti nama dari `{cat}` ke `{new_path}`")
@bot.on(geez_cmd(outgoing=True, pattern=r"zip (.*)"))
async def zip_file(event):
if event.fwd_from:
return
if not exists(TEMP_DOWNLOAD_DIRECTORY):
os.makedirs(TEMP_DOWNLOAD_DIRECTORY)
input_str = event.pattern_match.group(1)
path = input_str
zip_name = ""
if "|" in input_str:
path, zip_name = path.split("|")
path = path.strip()
zip_name = zip_name.strip()
if exists(path):
await event.edit("`Zipping...`")
start_time = datetime.now()
if isdir(path):
dir_path = path.split("/")[-1]
if path.endswith("/"):
dir_path = path.split("/")[-2]
zip_path = join(TEMP_DOWNLOAD_DIRECTORY, dir_path) + ".zip"
if zip_name:
zip_path = join(TEMP_DOWNLOAD_DIRECTORY, zip_name)
if not zip_name.endswith(".zip"):
zip_path += ".zip"
with ZipFile(zip_path, "w", ZIP_DEFLATED) as zip_obj:
for roots, _, files in os.walk(path):
for file in files:
files_path = join(roots, file)
arc_path = join(dir_path, relpath(files_path, path))
zip_obj.write(files_path, arc_path)
end_time = (datetime.now() - start_time).seconds
await event.edit(
f"Zipped `{path}` ke `{zip_path}` dalam `{end_time}` detik."
)
elif isfile(path):
file_name = basename(path)
zip_path = join(TEMP_DOWNLOAD_DIRECTORY, file_name) + ".zip"
if zip_name:
zip_path = join(TEMP_DOWNLOAD_DIRECTORY, zip_name)
if not zip_name.endswith(".zip"):
zip_path += ".zip"
with ZipFile(zip_path, "w", ZIP_DEFLATED) as zip_obj:
zip_obj.write(path, file_name)
await event.edit(f"Zipped `{path}` ke `{zip_path}`")
else:
await event.edit("`404: Not Found`")
@bot.on(geez_cmd(outgoing=True, pattern=r"unzip (.*)"))
async def unzip_file(event):
if event.fwd_from:
return
if not exists(TEMP_DOWNLO | le`\
\n\n 𝘾𝙤𝙢𝙢𝙖𝙣𝙙 :** `{cmd}ls`\
\n ❍▸ : **Untuk Melihat Daftar file di dalam direktori server\
\n\n 𝘾𝙤𝙢𝙢𝙖𝙣𝙙 :** `{cmd}rm` <directory/file>\
\n ❍▸ : **Untuk Menghapus File atau folder yg tersimpan di server\
\n\n 𝘾𝙤𝙢𝙢𝙖𝙣𝙙 :** `{cmd}rn` <directory/file> | <nama baru>\
\n ❍▸ : **Untuk Mengubah nama file atau direktori\
\n\n 𝘾𝙤𝙢𝙢𝙖𝙣𝙙 :** `{cmd}zip` <file/folder path> | <nama zip> (optional)\
\n ❍▸ : **Untuk mengcompress file atau folder.\
\n\n 𝘾𝙤𝙢𝙢𝙖𝙣𝙙 :** `{cmd}unzip` <path ke zip file>\
\n ❍▸ : **Untuk mengekstrak file arsip.\
\n • **NOTE : **Hanya bisa untuk file ZIP, RAR dan TAR!\
"
}
)
| AD_DIRECTORY):
os.makedirs(TEMP_DOWNLOAD_DIRECTORY)
input_str = event.pattern_match.group(1)
file_name = basename(input_str)
output_path = TEMP_DOWNLOAD_DIRECTORY + re.split("(.zip|.rar|.tar)", file_name)[0]
if exists(input_str):
start_time = datetime.now()
await event.edit("`Unzipping...`")
if is_zipfile(input_str):
zip_type = ZipFile
elif is_rarfile(input_str):
zip_type = RarFile
elif is_tarfile(input_str):
zip_type = TarFile
else:
return await event.edit(
"`Jenis file tidak didukung!`\n`Hanya Bisa ZIP, RAR dan TAR`"
)
try:
with zip_type(input_str, "r") as zip_obj:
zip_obj.extractall(output_path)
except BadRarFile:
return await event.edit("**Error:** `File RAR Rusak`")
except BadZipFile:
return await event.edit("**Error:** `File ZIP Rusak`")
except BaseException as err:
return await event.edit(f"**Error:** `{err}`")
end_time = (datetime.now() - start_time).seconds
await event.edit(
f"Unzipped `{input_str}` ke `{output_path}` dalam `{end_time}` detik."
)
else:
await event.edit("`404: Not Found`")
CMD_HELP.update(
{
"file": f"**Plugin : **`fi |
object_formatting_test_cases.py | from functools import partial
from typing import NamedTuple, Union
from flake8_annotations import Argument, Function
from flake8_annotations.enums import AnnotationType
class | (NamedTuple):
"""Named tuple for representing our test cases."""
test_object: Union[Argument, Function]
str_output: str
repr_output: str
# Define partial functions to simplify object creation
arg = partial(Argument, lineno=0, col_offset=0, annotation_type=AnnotationType.ARGS)
func = partial(Function, name="test_func", lineno=0, col_offset=0, decorator_list=[])
formatting_test_cases = {
"arg": FormatTestCase(
test_object=arg(argname="test_arg"),
str_output="<Argument: test_arg, Annotated: False>",
repr_output=(
"Argument("
"argname='test_arg', "
"lineno=0, "
"col_offset=0, "
"annotation_type=AnnotationType.ARGS, "
"has_type_annotation=False, "
"has_3107_annotation=False, "
"has_type_comment=False"
")"
),
),
"func_no_args": FormatTestCase(
test_object=func(args=[arg(argname="return")]),
str_output="<Function: test_func, Args: [<Argument: return, Annotated: False>]>",
repr_output=(
"Function("
"name='test_func', "
"lineno=0, "
"col_offset=0, "
"function_type=FunctionType.PUBLIC, "
"is_class_method=False, "
"class_decorator_type=None, "
"is_return_annotated=False, "
"has_type_comment=False, "
"has_only_none_returns=True, "
"is_nested=False, "
"decorator_list=[], "
"args=[Argument(argname='return', lineno=0, col_offset=0, annotation_type=AnnotationType.ARGS, " # noqa: E501
"has_type_annotation=False, has_3107_annotation=False, has_type_comment=False)]"
")"
),
),
"func_has_arg": FormatTestCase(
test_object=func(args=[arg(argname="foo"), arg(argname="return")]),
str_output="<Function: test_func, Args: [<Argument: foo, Annotated: False>, <Argument: return, Annotated: False>]>", # noqa: E501
repr_output=(
"Function("
"name='test_func', "
"lineno=0, "
"col_offset=0, "
"function_type=FunctionType.PUBLIC, "
"is_class_method=False, "
"class_decorator_type=None, "
"is_return_annotated=False, "
"has_type_comment=False, "
"has_only_none_returns=True, "
"is_nested=False, "
"decorator_list=[], "
"args=[Argument(argname='foo', lineno=0, col_offset=0, annotation_type=AnnotationType.ARGS, " # noqa: E501
"has_type_annotation=False, has_3107_annotation=False, has_type_comment=False), "
"Argument(argname='return', lineno=0, col_offset=0, annotation_type=AnnotationType.ARGS, " # noqa: E501
"has_type_annotation=False, has_3107_annotation=False, has_type_comment=False)]"
")"
),
),
}
| FormatTestCase |
reporting-page.component.ts | import {Component, OnInit} from "@angular/core";
import {ReportingService} from "../../services/reporting.service";
import {ActivatedRoute, Router} from "@angular/router";
import "rxjs/add/operator/switchMap";
@Component({
selector: 'reporting-page',
templateUrl: './reporting-page.component.html'
})
export class ReportingPage implements OnInit{
reportingOptions = [
{
value: 'TOP_5',
label: 'Top 5 languages'
},
{
value: 'LAST_10_YEAR',
label: 'Last 10 albums by year'
},
{
value: 'TOP_10_AREA',
label: 'Top 10 area'
}
];
selectedReportOption = null;
reportingResults = null;
sourceURL = null; | constructor(
private activatedRoute: ActivatedRoute,
private router: Router,
private reportingService: ReportingService
) {
}
ngOnInit(): void {
this.activatedRoute.queryParams
.switchMap(({report = 'TOP_5'}) => {
this.selectedReportOption = report;
this.sourceURL = this.reportingService.getReportsURL(report);
return this.reportingService.getReports(report)
})
.subscribe((reportResults) => {
this.reportingResults = reportResults;
});
}
onSelectReportOption(event, optionValue) {
event.preventDefault();
const queryParams = {
report: optionValue
};
this.router.navigate(['reporting'], {queryParams});
}
} | |
proof.rs | use crate::std::*;
use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream};
#[derive(Clone)]
#[cfg_attr(feature = "std", derive(Debug, PartialEq))]
pub struct Proof {
pub nodes: Vec<Vec<u8>>
}
impl Proof {
pub fn to_rlp(&self) -> Vec<u8> {
rlp::encode(self)
}
pub fn len(&self) -> usize {
self.nodes.len()
}
}
impl From<Vec<Vec<u8>>> for Proof {
fn from(data: Vec<Vec<u8>>) -> Proof {
Proof {
nodes: data
}
}
}
impl Decodable for Proof {
fn decode(r: &Rlp) -> Result<Self, DecoderError> {
Ok(Proof{
nodes: r.list_at(0)?,
})
}
}
impl Encodable for Proof {
fn rlp_append(&self, s: &mut RlpStream) {
s.begin_list(1);
s.append_list::<Vec<u8>, Vec<u8>>(&self.nodes);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_encode_decode() |
} | {
let nodes = vec![vec![0u8], vec![1], vec![2]];
let expected = Proof{
nodes: nodes,
};
let rlp_proof = rlp::encode(&expected);
let out_proof:Proof = rlp::decode(&rlp_proof).unwrap();
println!("{:?}", out_proof);
assert_eq!(expected, out_proof);
} |
quickstart.js | // Copyright 2017, Google, 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.
'use strict';
async function main( | ) {
// [START compute_engine_quickstart]
// Imports the Google Cloud client library
const Compute = require('@google-cloud/compute');
// Creates a client
const compute = new Compute();
async function quickstart() {
// Create a new VM using the latest OS image of your choice.
const zone = compute.zone('us-central1-c');
// TODO(developer): choose a name for the VM
// const vmName = 'vm-name';
// Start the VM create task
const [vm, operation] = await zone.createVM(vmName, {os: 'ubuntu'});
console.log(vm);
// `operation` lets you check the status of long-running tasks.
await operation.promise();
// Complete!
console.log('Virtual machine created!');
}
quickstart();
// [END compute_engine_quickstart]
}
main(...process.argv.slice(2)); | vmName = 'new_virtual_machine' // VM name of your choice |
drain.go | package action
import (
"errors"
boshas "github.com/cloudfoundry/bosh-agent/agent/applier/applyspec"
boshscript "github.com/cloudfoundry/bosh-agent/agent/script"
boshdrain "github.com/cloudfoundry/bosh-agent/agent/script/drain"
boshjobsuper "github.com/cloudfoundry/bosh-agent/jobsupervisor"
boshnotif "github.com/cloudfoundry/bosh-agent/notification"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
)
type DrainAction struct {
jobScriptProvider boshscript.JobScriptProvider
notifier boshnotif.Notifier
specService boshas.V1Service
jobSupervisor boshjobsuper.JobSupervisor
logTag string
logger boshlog.Logger
cancelCh chan struct{}
}
type DrainType string
const (
DrainTypeUpdate DrainType = "update"
DrainTypeStatus DrainType = "status"
DrainTypeShutdown DrainType = "shutdown"
)
func | (
notifier boshnotif.Notifier,
specService boshas.V1Service,
jobScriptProvider boshscript.JobScriptProvider,
jobSupervisor boshjobsuper.JobSupervisor,
logger boshlog.Logger,
) DrainAction {
return DrainAction{
notifier: notifier,
specService: specService,
jobScriptProvider: jobScriptProvider,
jobSupervisor: jobSupervisor,
logTag: "Drain Action",
logger: logger,
cancelCh: make(chan struct{}, 1),
}
}
func (a DrainAction) IsAsynchronous(_ ProtocolVersion) bool {
return true
}
func (a DrainAction) IsPersistent() bool {
return false
}
func (a DrainAction) IsLoggable() bool {
return true
}
func (a DrainAction) Run(drainType DrainType, newSpecs ...boshas.V1ApplySpec) (int, error) {
currentSpec, err := a.specService.Get()
if err != nil {
return 0, bosherr.WrapError(err, "Getting current spec")
}
params, err := a.determineParams(drainType, currentSpec, newSpecs)
if err != nil {
return 0, err
}
a.logger.Debug(a.logTag, "Unmonitoring")
err = a.jobSupervisor.Unmonitor()
if err != nil {
return 0, bosherr.WrapError(err, "Unmonitoring services")
}
var scripts []boshscript.Script
for _, job := range currentSpec.Jobs() {
script := a.jobScriptProvider.NewDrainScript(job.BundleName(), params)
scripts = append(scripts, script)
}
script := a.jobScriptProvider.NewParallelScript("drain", scripts)
resultsCh := make(chan error, 1)
go func() { resultsCh <- script.Run() }()
select {
case result := <-resultsCh:
a.logger.Debug(a.logTag, "Got a result")
return 0, result
case <-a.cancelCh:
a.logger.Debug(a.logTag, "Got a cancel request")
return 0, script.Cancel()
}
}
func (a DrainAction) determineParams(drainType DrainType, currentSpec boshas.V1ApplySpec, newSpecs []boshas.V1ApplySpec) (boshdrain.ScriptParams, error) {
var newSpec *boshas.V1ApplySpec
var params boshdrain.ScriptParams
if len(newSpecs) > 0 {
newSpec = &newSpecs[0]
}
switch drainType {
case DrainTypeStatus:
// Status was used in the past when dynamic drain was implemented in the Director.
// Now that we implement it in the agent, we should never get a call for this type.
return params, bosherr.Error("Unexpected call with drain type 'status'")
case DrainTypeUpdate:
if newSpec == nil {
return params, bosherr.Error("Drain update requires new spec")
}
params = boshdrain.NewUpdateParams(currentSpec, *newSpec)
case DrainTypeShutdown:
err := a.notifier.NotifyShutdown()
if err != nil {
return params, bosherr.WrapError(err, "Notifying shutdown")
}
params = boshdrain.NewShutdownParams(currentSpec, newSpec)
}
return params, nil
}
func (a DrainAction) Resume() (interface{}, error) {
return nil, errors.New("not supported")
}
func (a DrainAction) Cancel() error {
a.logger.Debug(a.logTag, "Cancelling drain action")
select {
case a.cancelCh <- struct{}{}:
default:
}
return nil
}
| NewDrain |
vue-router-tab.common.js | module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "fb15");
/******/ })
/************************************************************************/
/******/ ({
/***/ "0d3e":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ({
tab: {
untitled: '无标题'
},
contextmenu: {
refresh: '刷新',
refreshAll: '刷新全部',
close: '关闭',
closeLefts: '关闭左侧',
closeRights: '关闭右侧',
closeOthers: '关闭其他'
},
msg: {
keepLastTab: '至少应保留1个页签',
i18nProp: '请提供“i18n”方法以处理国际化内容'
}
});
/***/ }),
/***/ "3dec":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ({
tab: {
untitled: 'Untitled'
},
contextmenu: {
refresh: 'Refresh',
refreshAll: 'Refresh All',
close: 'Close',
closeLefts: 'Close to the Left',
closeRights: 'Close to the Right',
closeOthers: 'Close Others'
},
msg: {
keepLastTab: 'Keep at least 1 tab',
i18nProp: 'Method "i18n" is not defined on the instance'
}
});
/***/ }),
/***/ "751c":
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "8875":
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// addapted from the document.currentScript polyfill by Adam Miller
// MIT license
// source: https://github.com/amiller-gh/currentScript-polyfill
// added support for Firefox https://bugzilla.mozilla.org/show_bug.cgi?id=1620505
(function (root, factory) {
if (true) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}(typeof self !== 'undefined' ? self : this, function () {
function getCurrentScript () {
var descriptor = Object.getOwnPropertyDescriptor(document, 'currentScript')
// for chrome
if (!descriptor && 'currentScript' in document && document.currentScript) {
return document.currentScript
}
// for other browsers with native support for currentScript
if (descriptor && descriptor.get !== getCurrentScript && document.currentScript) {
return document.currentScript
}
// IE 8-10 support script readyState
// IE 11+ & Firefox support stack trace
try {
throw new Error();
}
catch (err) {
// Find the second match for the "at" string to get file src url from stack.
var ieStackRegExp = /.*at [^(]*\((.*):(.+):(.+)\)$/ig,
ffStackRegExp = /@([^@]*):(\d+):(\d+)\s*$/ig,
stackDetails = ieStackRegExp.exec(err.stack) || ffStackRegExp.exec(err.stack),
scriptLocation = (stackDetails && stackDetails[1]) || false,
line = (stackDetails && stackDetails[2]) || false,
currentLocation = document.location.href.replace(document.location.hash, ''),
pageSource,
inlineScriptSourceRegExp,
inlineScriptSource,
scripts = document.getElementsByTagName('script'); // Live NodeList collection
if (scriptLocation === currentLocation) {
pageSource = document.documentElement.outerHTML;
inlineScriptSourceRegExp = new RegExp('(?:[^\\n]+?\\n){0,' + (line - 2) + '}[^<]*<script>([\\d\\D]*?)<\\/script>[\\d\\D]*', 'i');
inlineScriptSource = pageSource.replace(inlineScriptSourceRegExp, '$1').trim();
}
for (var i = 0; i < scripts.length; i++) {
// If ready state is interactive, return the script tag
if (scripts[i].readyState === 'interactive') {
return scripts[i];
}
// If src matches, return the script tag
if (scripts[i].src === scriptLocation) {
return scripts[i];
}
// If inline source matches, return the script tag
if (
scriptLocation === currentLocation &&
scripts[i].innerHTML &&
scripts[i].innerHTML.trim() === inlineScriptSource
) {
return scripts[i];
}
}
// If no match, return null
return null;
}
};
return getCurrentScript
}));
/***/ }),
/***/ "96cf":
/***/ (function(module, exports, __webpack_require__) {
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var runtime = (function (exports) {
"use strict";
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var undefined; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function define(obj, key, value) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
return obj[key];
}
try {
// IE 8 has a broken Object.defineProperty that only works on DOM objects.
define({}, "");
} catch (err) {
define = function(obj, key, value) {
return obj[key] = value;
};
}
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator;
}
exports.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) {
return { type: "throw", arg: err };
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
// This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype = {};
IteratorPrototype[iteratorSymbol] = function () {
return this;
};
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype &&
NativeIteratorPrototype !== Op &&
hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
// This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
IteratorPrototype = NativeIteratorPrototype;
}
var Gp = GeneratorFunctionPrototype.prototype =
Generator.prototype = Object.create(IteratorPrototype);
GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
GeneratorFunctionPrototype.constructor = GeneratorFunction;
GeneratorFunction.displayName = define(
GeneratorFunctionPrototype,
toStringTagSymbol,
"GeneratorFunction"
);
// Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function(method) {
define(prototype, method, function(arg) {
return this._invoke(method, arg);
});
});
}
exports.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor
? ctor === GeneratorFunction ||
// For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction"
: false;
};
exports.mark = function(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
define(genFun, toStringTagSymbol, "GeneratorFunction");
}
genFun.prototype = Object.create(Gp);
return genFun;
};
// Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
exports.awrap = function(arg) {
return { __await: arg };
};
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") {
reject(record.arg);
} else {
var result = record.arg;
var value = result.value;
if (value &&
typeof value === "object" &&
hasOwn.call(value, "__await")) {
return PromiseImpl.resolve(value.__await).then(function(value) {
invoke("next", value, resolve, reject);
}, function(err) {
invoke("throw", err, resolve, reject);
});
}
return PromiseImpl.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration.
result.value = unwrapped;
resolve(result);
}, function(error) {
// If a rejected Promise was yielded, throw the rejection back
// into the async generator function so it can be handled there.
return invoke("throw", error, resolve, reject);
});
}
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function(resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise =
// If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
) : callInvokeWithMethodAndArg();
}
// Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
AsyncIterator.prototype[asyncIteratorSymbol] = function () {
return this;
};
exports.AsyncIterator = AsyncIterator;
// Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
if (PromiseImpl === void 0) PromiseImpl = Promise;
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList),
PromiseImpl
);
return exports.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
}
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
context.method = method;
context.arg = arg;
while (true) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if (context.method === "next") {
// Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = context.arg;
} else if (context.method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw context.arg;
}
context.dispatchException(context.arg);
} else if (context.method === "return") {
context.abrupt("return", context.arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
if (record.arg === ContinueSentinel) {
continue;
}
return {
value: record.arg,
done: context.done
};
} else if (record.type === "throw") {
state = GenStateCompleted;
// Dispatch the exception by looping back around to the
// context.dispatchException(context.arg) call above.
context.method = "throw";
context.arg = record.arg;
}
}
};
}
// Call delegate.iterator[context.method](context.arg) and handle the
// result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (method === undefined) {
// A .throw or .return when the delegate iterator has no .throw
// method always terminates the yield* loop.
context.delegate = null;
if (context.method === "throw") {
// Note: ["return"] must be used for ES3 parsing compatibility.
if (delegate.iterator["return"]) {
// If the delegate iterator has a return method, give it a
// chance to clean up.
context.method = "return";
context.arg = undefined;
maybeInvokeDelegate(delegate, context);
if (context.method === "throw") {
// If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below.
return ContinueSentinel;
}
}
context.method = "throw";
context.arg = new TypeError(
"The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if (record.type === "throw") {
context.method = "throw";
context.arg = record.arg;
context.delegate = null;
return ContinueSentinel;
}
var info = record.arg;
if (! info) {
context.method = "throw";
context.arg = new TypeError("iterator result is not an object");
context.delegate = null;
return ContinueSentinel;
}
if (info.done) {
// Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value;
// Resume execution at the desired location (see delegateYield).
context.next = delegate.nextLoc;
// If context.method was "throw" but the delegate handled the
// exception, let the outer generator proceed normally. If
// context.method was "next", forget context.arg since it has been
// "consumed" by the delegate iterator. If context.method was
// "return", allow the original .return call to continue in the
// outer generator.
if (context.method !== "return") {
context.method = "next";
context.arg = undefined;
}
} else {
// Re-yield the result returned by the delegate method.
return info;
}
// The delegate iterator is finished, so forget it and continue with
// the outer generator.
context.delegate = null;
return ContinueSentinel;
}
// Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
define(Gp, toStringTagSymbol, "Generator");
// A Generator should always return itself as the iterator object when the
// @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details.
Gp[iteratorSymbol] = function() {
return this;
};
Gp.toString = function() {
return "[object Generator]";
};
function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] };
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
exports.keys = function(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined;
next.done = true;
return next;
};
return next.next = next;
}
}
// Return an iterator with no values.
return { next: doneResult };
}
exports.values = values;
function doneResult() {
return { value: undefined, done: true };
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
// Resetting context._sent for legacy support of Babel's
// function.sent implementation.
this.sent = this._sent = undefined;
this.done = false;
this.delegate = null;
this.method = "next";
this.arg = undefined;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" &&
hasOwn.call(this, name) &&
!isNaN(+name.slice(1))) {
this[name] = undefined;
}
}
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
if (caught) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
context.method = "next";
context.arg = undefined;
}
return !! caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry &&
(type === "break" ||
type === "continue") &&
finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.method = "next";
this.next = finallyEntry.finallyLoc;
return ContinueSentinel;
}
return this.complete(record);
},
complete: function(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
return ContinueSentinel;
},
finish: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
if (this.method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
this.arg = undefined;
}
return ContinueSentinel;
}
};
// Regardless of whether this script is executing as a CommonJS module
// or not, return the runtime object so that we can declare the variable
// regeneratorRuntime in the outer scope, which allows this module to be
// injected easily by `bin/regenerator --include-runtime script.js`.
return exports;
}(
// If this script is executing as a CommonJS module, use module.exports
// as the regeneratorRuntime namespace. Otherwise create a new empty
// object. Either way, the resulting object will be used to initialize
// the regeneratorRuntime variable at the top of this file.
true ? module.exports : undefined
));
try {
regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
// This module should not be running in strict mode, so the above
// assignment should always work unless something is misconfigured. Just
// in case runtime.js accidentally runs in strict mode, we can escape
// strict mode using a global Function call. This could conceivably fail
// if a Content Security Policy forbids using Function, but in that case
// the proper solution is to fix the accidental strict mode problem. If
// you've misconfigured your bundler to force strict mode and applied a
// CSP to forbid Function, and you're not willing to fix either of those
// problems, please detail your unique predicament in a GitHub issue.
Function("r", "regeneratorRuntime = r")(runtime);
}
/***/ }),
/***/ "a34a":
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__("96cf");
/***/ }),
/***/ "b13e":
/***/ (function(module, exports, __webpack_require__) {
var map = {
"./en.js": "3dec",
"./zh.js": "0d3e"
};
function webpackContext(req) {
var id = webpackContextResolve(req);
return __webpack_require__(id);
}
function webpackContextResolve(req) {
if(!__webpack_require__.o(map, req)) {
var e = new Error("Cannot find module '" + req + "'");
e.code = 'MODULE_NOT_FOUND';
throw e;
}
return map[req];
}
webpackContext.keys = function webpackContextKeys() {
return Object.keys(map);
};
webpackContext.resolve = webpackContextResolve;
module.exports = webpackContext;
webpackContext.id = "b13e";
/***/ }),
/***/ "fb15":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, "RouterAlive", function() { return /* reexport */ RouterAlive; });
__webpack_require__.d(__webpack_exports__, "RouterTabRoutes", function() { return /* reexport */ routes; });
__webpack_require__.d(__webpack_exports__, "Iframe", function() { return /* reexport */ Iframe; });
// CONCATENATED MODULE: ./node_modules/@vue/cli-service/lib/commands/build/setPublicPath.js
// This file is imported into lib/wc client bundles.
if (typeof window !== 'undefined') {
var currentScript = window.document.currentScript
if (true) {
var getCurrentScript = __webpack_require__("8875")
currentScript = getCurrentScript()
// for backward compatibility, because previously we directly included the polyfill
if (!('currentScript' in document)) {
Object.defineProperty(document, 'currentScript', { get: getCurrentScript })
}
}
var src = currentScript && currentScript.src.match(/(.+\/)[^/]+\.js(\?.*)?$/)
if (src) {
__webpack_require__.p = src[1] // eslint-disable-line
}
}
// Indicate to webpack that this file can be concatenated
/* harmony default export */ var setPublicPath = (null);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"47deaf46-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./lib/RouterTab.vue?vue&type=template&id=a1ddc568&
var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"router-tab"},[_c('header',{ref:"header",staticClass:"router-tab__header"},[_c('div',{staticClass:"router-tab__slot-start"},[_vm._t("start")],2),_c('tab-scroll',{ref:"scroll"},[_c('transition-group',_vm._b({staticClass:"router-tab__nav",attrs:{"tag":"ul"},on:{"after-enter":_vm.onTabTrans,"after-leave":_vm.onTabTrans}},'transition-group',_vm.tabTrans,false),_vm._l((_vm.items),function(item,index){return _c('tab-item',{key:item.id || item.to,ref:"tab",refInFor:true,attrs:{"data":item,"index":index},nativeOn:{"contextmenu":function($event){$event.preventDefault();return (function (e) { return _vm.showContextmenu(item.id, index, e); })($event)}},scopedSlots:_vm._u([(_vm.$scopedSlots.default)?{key:"default",fn:function(scope){return [_vm._t("default",null,null,scope)]}}:null],null,true)})}),1)],1),_c('div',{staticClass:"router-tab__slot-end"},[_vm._t("end")],2)],1),_c('div',{staticClass:"router-tab__container"},[_c('router-alive',{attrs:{"page-class":"router-tab-page","keep-alive":_vm.keepAlive,"reuse":_vm.reuse,"max":_vm.maxAlive,"transition":_vm.pageTrans},on:{"ready":_vm.onAliveReady,"change":_vm.onAliveChange}}),_c('transition-group',_vm._b({staticClass:"router-tab__iframes",attrs:{"tag":"div"}},'transition-group',_vm.pageTrans,false),_vm._l((_vm.iframes),function(url){return _c('iframe',{directives:[{name:"show",rawName:"v-show",value:(url === _vm.currentIframe),expression:"url === currentIframe"}],key:url,staticClass:"router-tab__iframe",attrs:{"src":url,"name":_vm.iframeNamePrefix + url,"frameborder":"0"},on:{"load":function($event){return _vm.iframeLoaded(url)}}})}),0)],1),_c('transition',{attrs:{"name":"router-tab-zoom"}},[(_vm.contextmenu !== false && _vm.contextData.index > -1)?_c('tab-contextmenu',{attrs:{"data":_vm.contextData,"menu":_vm.contextMenu}}):_vm._e()],1)],1)}
var staticRenderFns = []
// CONCATENATED MODULE: ./lib/RouterTab.vue?vue&type=template&id=a1ddc568&
// EXTERNAL MODULE: ./node_modules/@babel/runtime/regenerator/index.js
var regenerator = __webpack_require__("a34a");
var regenerator_default = /*#__PURE__*/__webpack_require__.n(regenerator);
// CONCATENATED MODULE: ./lib/util/index.js
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
// 空对象和数组
var emptyObj = Object.create(null);
var emptyArray = []; // 从数组删除项
function util_remove(arr, item) {
if (arr.length) {
var index = arr.indexOf(item);
if (index > -1) {
return arr.splice(index, 1);
}
}
}
/**
* 滚动到指定位置
* @export
* @param {Element} wrap 滚动区域
* @param {number} [left=0]
* @param {number} [top=0]
*/
function util_scrollTo(_ref) {
var wrap = _ref.wrap,
_ref$left = _ref.left,
left = _ref$left === void 0 ? 0 : _ref$left,
_ref$top = _ref.top,
top = _ref$top === void 0 ? 0 : _ref$top,
_ref$smooth = _ref.smooth,
smooth = _ref$smooth === void 0 ? true : _ref$smooth;
if (!wrap) return;
if (wrap.scrollTo) {
wrap.scrollTo({
left: left,
top: top,
behavior: smooth ? 'smooth' : 'auto'
});
} else {
wrap.scrollLeft = left;
wrap.scrollTop = top;
}
}
/**
* 指定元素滚动到可视区域
* @export
* @param {Element} el 目标元素
* @param {Element} wrap 滚动区域
* @param {String} block 垂直方向的对齐,可选:'start', 'center', 'end', 或 'nearest'
* @param {String} inline 水平方向的对齐,可选值同上
*/
function util_scrollIntoView(_ref2) {
var el = _ref2.el,
wrap = _ref2.wrap,
_ref2$block = _ref2.block,
block = _ref2$block === void 0 ? 'start' : _ref2$block,
_ref2$inline = _ref2.inline,
inline = _ref2$inline === void 0 ? 'nearest' : _ref2$inline;
if (!el || !wrap) return;
if (el.scrollIntoView) {
el.scrollIntoView({
behavior: 'smooth',
block: block,
inline: inline
});
} else {
var offsetLeft = el.offsetLeft,
offsetTop = el.offsetTop;
var left, top;
if (block === 'center') {
top = offsetTop + (el.clientHeight - wrap.clientHeight) / 2;
} else {
top = offsetTop;
}
if (inline === 'center') {
left = offsetLeft + (el.clientWidth - wrap.clientWidth) / 2;
} else {
left = offsetLeft;
}
util_scrollTo({
wrap: wrap,
left: left,
top: top
});
}
}
/**
* 提取计算属性
* @export
* @param {String} origin 来源属性
* @param {Array|Object} props 需要提取的计算属性
* @param {String} context 来源选项为 function 时的入参
* @returns {Object}
*/
function mapGetters(origin, props, context) {
var map = {};
var each = function each(prop, option) {
if (option === null || _typeof(option) !== 'object') {
option = {
default: option
};
}
var _option = option,
def = _option.default,
alias = _option.alias;
map[alias || prop] = function () {
var val = this[origin][prop];
if (context && typeof val === 'function') {
// 函数返回
return val(this[context]);
} else if (def !== undefined && val === undefined) {
// 默认值
if (typeof def === 'function') {
return def.bind(this)();
}
return def;
}
return val;
};
};
if (Array.isArray(props)) {
props.forEach(function (prop) {
return each(prop);
});
} else {
Object.entries(props).forEach(function (_ref3) {
var _ref4 = _slicedToArray(_ref3, 2),
prop = _ref4[0],
def = _ref4[1];
return each(prop, def);
});
}
return map;
} // 去除路径中的 hash
var prunePath = function prunePath(path) {
return path.split('#')[0];
}; // 解析过渡配置
function getTransOpt(trans) {
return typeof trans === 'string' ? {
name: trans
} : trans;
}
// CONCATENATED MODULE: ./lib/mixins/contextmenu.js
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
// 右键菜单
/* harmony default export */ var contextmenu = ({
data: function data() {
return {
// 右键菜单
contextData: {
id: null,
index: -1,
left: 0,
top: 0
}
};
},
computed: {
// 菜单配置
contextMenu: function contextMenu() {
return Array.isArray(this.contextmenu) ? this.contextmenu : undefined;
}
},
watch: {
// 路由切换隐藏右键菜单
$route: function $route() {
this.hideContextmenu();
},
// 拖拽排序隐藏右键菜单
onDragSort: function onDragSort() {
this.hideContextmenu();
}
},
mounted: function mounted() {
// 显示右键菜单,绑定点击关闭事件
document.addEventListener('click', this.contextmenuClickOutSide);
},
destroyed: function destroyed() {
// 隐藏右键菜单,移除点击关闭事件
document.removeEventListener('click', this.contextmenuClickOutSide);
},
methods: {
// 显示页签右键菜单
showContextmenu: function showContextmenu(id, index, e) {
var _this = this;
return _asyncToGenerator( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
var _ref, top, left;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!(id !== null && _this.contextData.id !== null)) {
_context.next = 4;
break;
}
_this.hideContextmenu();
_context.next = 4;
return _this.$nextTick();
case 4:
// 菜单定位
_ref = e || emptyObj, top = _ref.clientY, left = _ref.clientX;
Object.assign(_this.contextData, {
id: id,
index: index,
top: top,
left: left
});
case 6:
case "end":
return _context.stop();
}
}
}, _callee);
}))();
},
// 关闭页签右键菜单
hideContextmenu: function hideContextmenu() {
this.showContextmenu(null, -1);
},
// 菜单外部点击关闭
contextmenuClickOutSide: function contextmenuClickOutSide(e) {
if (e.target !== this.$el.querySelector('.router-tab-contextmenu')) {
this.hideContextmenu();
}
}
}
});
// CONCATENATED MODULE: ./lib/config/lang/index.js
function lang_slicedToArray(arr, i) { return lang_arrayWithHoles(arr) || lang_iterableToArrayLimit(arr, i) || lang_unsupportedIterableToArray(arr, i) || lang_nonIterableRest(); }
function lang_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function lang_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return lang_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return lang_arrayLikeToArray(o, minLen); }
function lang_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function lang_iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function lang_arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
// 引入目录下语言配置
var context = __webpack_require__("b13e"); // 语言配置
/* harmony default export */ var config_lang = (context.keys().reduce(function (map, path) {
var _$exec = /\.\/(.*).js/g.exec(path),
_$exec2 = lang_slicedToArray(_$exec, 2),
key = _$exec2[1];
map[key] = context(path).default;
return map;
}, {}));
// CONCATENATED MODULE: ./lib/util/warn.js
var prefix = '[Vue Router Tab]'; // 错误
function assert(condition, message) {
if (!condition) {
throw new Error("".concat(prefix, " ").concat(message));
}
} // 警告
function warn(condition, message) {
if (!condition) {
typeof console !== 'undefined' && console.warn("".concat(prefix, " ").concat(message));
}
} // 常用消息
var messages = {
renamed: function renamed(newName) {
var target = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '方法';
return "\u8BE5".concat(target, "\u5DF2\u66F4\u540D\u4E3A\u201C").concat(newName, "\u201D\uFF0C\u8BF7\u4FEE\u6539\u540E\u4F7F\u7528");
}
};
// CONCATENATED MODULE: ./lib/mixins/i18n.js
function _toArray(arr) { return i18n_arrayWithHoles(arr) || _iterableToArray(arr) || i18n_unsupportedIterableToArray(arr) || i18n_nonIterableRest(); }
function i18n_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function i18n_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return i18n_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return i18n_arrayLikeToArray(o, minLen); }
function i18n_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }
function i18n_arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
// 语言配置
// 国际化
/* harmony default export */ var i18n = ({
computed: {
// 语言内容
langs: function langs() {
var lang = this.lang;
if (typeof lang === 'string') {
lang = config_lang[lang];
} // 找不到语言配置,则使用英文
if (!lang) lang = config_lang['en'];
return lang;
}
},
methods: {
// 获取国际化内容
i18nText: function i18nText(text) {
var _this$i18nParse = this.i18nParse(text),
key = _this$i18nParse.key,
params = _this$i18nParse.params;
if (key) {
var hasI18nProp = typeof this.i18n === 'function'; // 未配置 i18n 方法则警告
if (!this._hasI18nPropWarn) {
warn(hasI18nProp, this.langs.msg.i18nProp);
this._hasI18nPropWarn = true;
}
if (hasI18nProp) {
return this.i18n(key, params);
}
}
return text;
},
// 解析国际化
i18nParse: function i18nParse(text) {
var key;
var params; // 获取国际化配置
if (typeof text === 'string') {
// 字符串方式配置:'i18n:custom.lang.key'
var res = /^i18n:([^\s]+)$/.exec(text);
if (res) {
key = res[1];
params = [];
}
} else if (Array.isArray(text)) {
// 数组方式配置:['tab.i18n.key', 'param1', 'param2', ...]
;
var _text = _toArray(text);
key = _text[0];
params = _text.slice(1);
}
return {
key: key,
params: params
};
}
}
});
// CONCATENATED MODULE: ./lib/mixins/iframe.js
// Iframe 页签
/* harmony default export */ var iframe = ({
data: function data() {
return {
iframes: [],
currentIframe: null,
iframeNamePrefix: 'RouterTabIframe-'
};
},
methods: {
// 获取 Iframe 页签路由路径
getIframePath: function getIframePath(src) {
var title = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var icon = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var path = "".concat(this.basePath, "/iframe/").replace(/\/+/g, '/') + encodeURIComponent(src);
if (title) {
path += '/' + title;
if (icon) path += '/' + icon;
}
return path;
},
// 打开 Iframe 页签
openIframe: function openIframe(src, title, icon) {
var path = this.getIframePath(src, title, icon);
this.$router.push(path);
},
// 关闭 Iframe 页签
closeIframe: function closeIframe(src) {
var path = this.getIframePath(src);
this.close({
path: path,
match: false
});
},
// 刷新 Iframe 页签
refreshIframe: function refreshIframe(src) {
var path = this.getIframePath(src);
this.refresh(path, false);
},
// 根据 url 获取 iframe 节点
getIframeEl: function getIframeEl(url) {
var name = this.iframeNamePrefix + url;
return document.getElementsByName(name)[0];
},
// iframe 节点 mounted
iframeMounted: function iframeMounted(url) {
var iframe = this.getIframeEl(url);
this.$emit('iframe-mounted', url, iframe);
},
// iframe 加载成功
iframeLoaded: function iframeLoaded(url) {
var iframe = this.getIframeEl(url);
this.$emit('iframe-loaded', url, iframe);
}
}
});
// CONCATENATED MODULE: ./lib/mixins/operate.js
function operate_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function operate_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { operate_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { operate_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function operate_slicedToArray(arr, i) { return operate_arrayWithHoles(arr) || operate_iterableToArrayLimit(arr, i) || operate_unsupportedIterableToArray(arr, i) || operate_nonIterableRest(); }
function operate_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function operate_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return operate_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return operate_arrayLikeToArray(o, minLen); }
function operate_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function operate_iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function operate_arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function operate_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { operate_typeof = function _typeof(obj) { return typeof obj; }; } else { operate_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return operate_typeof(obj); }
// 获取关闭参数
function getCloseArgs(args) {
args = Array.from(args);
var argsLen = args.length;
var arg = args[0]; // 首个选项
if (!argsLen) {
// close()
return {};
} else if (arg && operate_typeof(arg) === 'object' && !arg.name && !arg.fullPath && !arg.params && !arg.query && !arg.hash) {
// close({id, path, match, force, to, refresh})
return arg;
} else {
// close(path, to)
var _args = args,
_args2 = operate_slicedToArray(_args, 2),
path = _args2[0],
to = _args2[1];
return {
path: path,
to: to
};
}
} // 路径是否一致
function equalPath(path1, path2) {
var reg = /\/$/;
return path1.replace(reg, '') === path2.replace(reg, '');
} // 页签操作
/* harmony default export */ var operate = ({
methods: {
/**
* 打开页签(默认全新打开)
* @param {location} path 页签路径
* @param {Boolean} [isReplace = false] 是否 replace 方式替换当前路由
* @param {Boolean | String} [refresh = true] 是否全新打开,如果为 `sameTab` 则仅同一个页签才全新打开
*/
open: function open(path) {
var _arguments = arguments,
_this = this;
return operate_asyncToGenerator( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
var isReplace, refresh, curId, tarId, isSameTab;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
isReplace = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : false;
refresh = _arguments.length > 2 && _arguments[2] !== undefined ? _arguments[2] : true;
curId = _this.activeTabId;
tarId = _this.getRouteKey(path);
isSameTab = equalPath(curId, tarId); // 打开路由与当前路由相同页签才刷新
refresh === 'sameTab' && (refresh = isSameTab);
refresh && _this.refresh(path, false);
_context.prev = 7;
_context.next = 10;
return _this.$router[isReplace ? 'replace' : 'push'](path);
case 10:
_context.next = 14;
break;
case 12:
_context.prev = 12;
_context.t0 = _context["catch"](7);
case 14:
_context.prev = 14;
isSameTab && _this.reload();
return _context.finish(14);
case 17:
case "end":
return _context.stop();
}
}
}, _callee, null, [[7, 12, 14, 17]]);
}))();
},
// 移除 tab 项
removeTab: function removeTab(id) {
var _arguments2 = arguments,
_this2 = this;
return operate_asyncToGenerator( /*#__PURE__*/regenerator_default.a.mark(function _callee2() {
var force, items, idx;
return regenerator_default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
force = _arguments2.length > 1 && _arguments2[1] !== undefined ? _arguments2[1] : false;
items = _this2.items;
idx = items.findIndex(function (item) {
return item.id === id;
}); // 最后一个页签不允许关闭
if (!(!force && _this2.keepLastTab && items.length === 1)) {
_context2.next = 5;
break;
}
throw new Error(_this2.langs.msg.keepLastTab);
case 5:
if (force) {
_context2.next = 8;
break;
}
_context2.next = 8;
return _this2.leavePage(id, 'close');
case 8:
// 承诺关闭后移除页签和缓存
_this2.$alive.remove(id);
idx > -1 && items.splice(idx, 1);
case 10:
case "end":
return _context2.stop();
}
}
}, _callee2);
}))();
},
/**
* 关闭页签
* 支持以下方式调用:
* 1. this.$tabs.close({id, path, match, force, to, refresh})
* 2. this.$tabs.close(path, to)
* @param {String} id 通过页签 id 关闭
* @param {location} path 通过路由路径关闭页签,如果未配置 id 和 path 则关闭当前页签
* @param {Boolean} [match = true] path 方式关闭时,是否匹配 path 完整路径
* @param {Boolean} [force = true] 是否强制关闭
* @param {location} to 关闭后跳转的地址,为 null 则不跳转
* @param {Boolean} [refresh = false] 是否全新打开跳转地址
*/
close: function close() {
var _arguments3 = arguments,
_this3 = this;
return operate_asyncToGenerator( /*#__PURE__*/regenerator_default.a.mark(function _callee3() {
var _getCloseArgs, id, path, _getCloseArgs$match, match, _getCloseArgs$force, force, to, _getCloseArgs$refresh, refresh, activeTabId, items, idx, nextTab;
return regenerator_default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
// 解析参数
_getCloseArgs = getCloseArgs(_arguments3), id = _getCloseArgs.id, path = _getCloseArgs.path, _getCloseArgs$match = _getCloseArgs.match, match = _getCloseArgs$match === void 0 ? true : _getCloseArgs$match, _getCloseArgs$force = _getCloseArgs.force, force = _getCloseArgs$force === void 0 ? true : _getCloseArgs$force, to = _getCloseArgs.to, _getCloseArgs$refresh = _getCloseArgs.refresh, refresh = _getCloseArgs$refresh === void 0 ? false : _getCloseArgs$refresh;
activeTabId = _this3.activeTabId, items = _this3.items; // 根据 path 获取 id
if (!(!id && path)) {
_context3.next = 6;
break;
}
id = _this3.getIdByPath(path, match);
if (id) {
_context3.next = 6;
break;
}
return _context3.abrupt("return");
case 6:
// 默认当前页签
if (!id) id = activeTabId;
_context3.prev = 7;
idx = items.findIndex(function (item) {
return item.id === id;
}); // 移除页签
_context3.next = 11;
return _this3.removeTab(id, force);
case 11:
if (!(to === null)) {
_context3.next = 13;
break;
}
return _context3.abrupt("return");
case 13:
// 如果关闭当前页签,则打开后一个页签
if (!to && activeTabId === id) {
nextTab = items[idx] || items[idx - 1];
to = nextTab ? nextTab.to : _this3.defaultPath;
}
if (to) {
_this3.open(to, true, refresh === false ? 'sameTab' : true);
}
_context3.next = 20;
break;
case 17:
_context3.prev = 17;
_context3.t0 = _context3["catch"](7);
warn(false, _context3.t0);
case 20:
case "end":
return _context3.stop();
}
}
}, _callee3, null, [[7, 17]]);
}))();
},
// 通过页签 id 关闭页签
closeTab: function closeTab() {
var _arguments4 = arguments,
_this4 = this;
return operate_asyncToGenerator( /*#__PURE__*/regenerator_default.a.mark(function _callee4() {
var id, to, force;
return regenerator_default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
id = _arguments4.length > 0 && _arguments4[0] !== undefined ? _arguments4[0] : _this4.activeTabId;
to = _arguments4.length > 1 ? _arguments4[1] : undefined;
force = _arguments4.length > 2 && _arguments4[2] !== undefined ? _arguments4[2] : false;
_this4.close({
id: id,
to: to,
force: force
});
case 4:
case "end":
return _context4.stop();
}
}
}, _callee4);
}))();
},
/**
* 通过路由地址刷新页签
* @param {location} path 需要刷新的地址
* @param {Boolean} [match = true] 是否匹配 target 完整路径
* @param {Boolean} [force = true] 是否强制刷新
*/
refresh: function refresh(path) {
var match = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var id = path && this.getIdByPath(path, match) || undefined;
this.refreshTab(id, force);
},
// 刷新指定页签
refreshTab: function refreshTab() {
var _arguments5 = arguments,
_this5 = this;
return operate_asyncToGenerator( /*#__PURE__*/regenerator_default.a.mark(function _callee5() {
var id, force;
return regenerator_default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
id = _arguments5.length > 0 && _arguments5[0] !== undefined ? _arguments5[0] : _this5.activeTabId;
force = _arguments5.length > 1 && _arguments5[1] !== undefined ? _arguments5[1] : false;
_context5.prev = 2;
if (force) {
_context5.next = 6;
break;
}
_context5.next = 6;
return _this5.leavePage(id, 'refresh');
case 6:
_this5.$alive.refresh(id);
_context5.next = 12;
break;
case 9:
_context5.prev = 9;
_context5.t0 = _context5["catch"](2);
warn(false, _context5.t0);
case 12:
case "end":
return _context5.stop();
}
}
}, _callee5, null, [[2, 9]]);
}))();
},
/**
* 刷新所有页签
* @param {Boolean} [force = false] 是否强制刷新,如果强制则忽略页面 beforePageLeave
*/
refreshAll: function refreshAll() {
var _arguments6 = arguments,
_this6 = this;
return operate_asyncToGenerator( /*#__PURE__*/regenerator_default.a.mark(function _callee6() {
var force, cache, id;
return regenerator_default.a.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
force = _arguments6.length > 0 && _arguments6[0] !== undefined ? _arguments6[0] : false;
cache = _this6.$alive.cache;
_context6.t0 = regenerator_default.a.keys(cache);
case 3:
if ((_context6.t1 = _context6.t0()).done) {
_context6.next = 16;
break;
}
id = _context6.t1.value;
_context6.prev = 5;
if (force) {
_context6.next = 9;
break;
}
_context6.next = 9;
return _this6.leavePage(id, 'refresh');
case 9:
_this6.$alive.refresh(id);
_context6.next = 14;
break;
case 12:
_context6.prev = 12;
_context6.t2 = _context6["catch"](5);
case 14:
_context6.next = 3;
break;
case 16:
case "end":
return _context6.stop();
}
}
}, _callee6, null, [[5, 12]]);
}))();
},
/**
* 重置 RouterTab 到默认状态,关闭所有页签并清理缓存页签数据
* @param {location} [to = this.defaultPath] 重置后跳转页面
*/
reset: function reset() {
var _this7 = this;
var to = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.defaultPath;
// 遍历删除缓存
this.items.forEach(function (_ref) {
var id = _ref.id;
return _this7.$alive.remove(id);
}); // 清除缓存页签
this.clearTabsStore(); // 初始页签数据
this.initTabs();
this.open(to, true, true);
}
}
});
// CONCATENATED MODULE: ./lib/mixins/pageLeave.js
function pageLeave_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function pageLeave_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { pageLeave_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { pageLeave_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
// 路由导航守卫
var pageLeave_leaveGuard = function leaveGuard(router) {
return function (to, from, next) {
var $tabs = router.app.$tabs;
if (!$tabs) {
next();
return;
}
var toId = $tabs.getRouteKey(to);
var $alive = $tabs.$alive;
var _ref = $alive && $alive.cache[toId] || emptyObj,
alivePath = _ref.alivePath;
var matched = $tabs.matchRoute(to);
var id, type;
if (alivePath && alivePath !== matched.alivePath) {
// 页签地址被替换:to 存在缓存但缓存路由不一致
type = 'replace';
id = toId;
} else if ($alive.basePath !== matched.basePath) {
// 离开页签组件:to 不在当前页签组件路由下
type = 'leave';
id = $tabs.activeTabId;
}
if (type) {
$tabs.leavePage(id, type).then(next).catch(function () {
return next(false);
});
} else {
next();
}
};
}; // 页面离开
/* harmony default export */ var mixins_pageLeave = ({
created: function created() {
var $router = this.$router;
if ($router._RouterTabInit) return; // 初始化路由导航守卫
$router.beforeEach(pageLeave_leaveGuard($router));
$router._RouterTabInit = true;
},
methods: {
// 页面离开 Promise
leavePage: function leavePage(id, type) {
var _this = this;
return pageLeave_asyncToGenerator( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
var tab, _ref2, vm, pageLeave;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
tab = _this.items.find(function (item) {
return item.id === id;
}); // 当前页签
_ref2 = _this.$alive.cache[id] || emptyObj, vm = _ref2.vm; // 缓存数据
pageLeave = vm && vm.$vnode.componentOptions.Ctor.options.beforePageLeave;
if (!(typeof pageLeave === 'function')) {
_context.next = 5;
break;
}
return _context.abrupt("return", pageLeave.bind(vm)(tab, type));
case 5:
case "end":
return _context.stop();
}
}
}, _callee);
}))();
}
}
});
// CONCATENATED MODULE: ./lib/util/decorator.js
/* 装饰器 */
/**
* 防抖
* @param {number} [delay=200] 延迟
*/
var debounce = function debounce() {
var delay = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 200;
return function (target, name, desc) {
var fn = desc.value;
var timeout = null;
desc.value = function () {
for (var _len = arguments.length, rest = new Array(_len), _key = 0; _key < _len; _key++) {
rest[_key] = arguments[_key];
}
var context = this;
clearTimeout(timeout);
timeout = setTimeout(function () {
fn.call.apply(fn, [context].concat(rest));
}, delay);
};
};
};
// CONCATENATED MODULE: ./lib/mixins/scroll.js
var _dec, _obj;
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object.keys(descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object.defineProperty(target, property, desc); desc = null; } return desc; }
function scroll_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function scroll_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { scroll_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { scroll_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
// 页签滚动
/* harmony default export */ var mixins_scroll = ({
watch: {
activeTabId: {
handler: function handler() {
var _this = this;
return scroll_asyncToGenerator( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (_this.$el) {
_context.next = 2;
break;
}
return _context.abrupt("return");
case 2:
_context.next = 4;
return _this.$nextTick();
case 4:
_this.adjust();
case 5:
case "end":
return _context.stop();
}
}
}, _callee);
}))();
},
immediate: true
}
},
mounted: function mounted() {
// 浏览器窗口大小改变时调整Tab滚动显示
window.addEventListener('resize', this.adjust);
},
destroyed: function destroyed() {
// 销毁后移除监听事件
window.removeEventListener('resize', this.adjust);
},
methods: (_dec = debounce(), (_obj = {
adjust: function adjust() {
if (!this.$el) return;
var scroll = this.$refs.scroll;
var cur = this.$el.querySelector('.router-tab__item.is-active');
if (scroll && !scroll.isInView(cur)) scroll.scrollIntoView(cur); // 关闭右键菜单
this.hideContextmenu();
},
// 页签过渡
onTabTrans: function onTabTrans() {
this.adjust();
}
}, (_applyDecoratedDescriptor(_obj, "adjust", [_dec], Object.getOwnPropertyDescriptor(_obj, "adjust"), _obj)), _obj))
});
// CONCATENATED MODULE: ./lib/mixins/restore.js
// 页签刷新后还原
/* harmony default export */ var restore = ({
computed: {
// 刷新还原存储 key
restoreKey: function restoreKey() {
var restore = this.restore,
basePath = this.basePath;
if (!restore || typeof sessionStorage === 'undefined') return '';
var key = "RouterTab:restore:".concat(basePath);
typeof restore === 'string' && (key += ":".concat(restore));
return key;
}
},
mounted: function mounted() {
// 页面重载前保存页签数据
window.addEventListener('beforeunload', this.saveTabs);
},
destroyed: function destroyed() {
window.removeEventListener('beforeunload', this.saveTabs);
},
watch: {
// 监听 restoreKey 变化自动还原页签
restoreKey: function restoreKey() {
if (this.restoreWatch) {
var activeTab = this.activeTab;
this.initTabs();
if (!this.activeTab) {
this.items.push(activeTab);
}
}
}
},
methods: {
// 保存页签数据
saveTabs: function saveTabs() {
this.restoreKey && sessionStorage.setItem(this.restoreKey, JSON.stringify(this.items));
},
// 清除页签缓存数据
clearTabsStore: function clearTabsStore() {
this.restoreKey && sessionStorage.removeItem(this.restoreKey);
},
// 从缓存读取页签
restoreTabs: function restoreTabs() {
if (!this.restoreKey) return false;
var tabs = sessionStorage.getItem(this.restoreKey);
var hasStore = false;
try {
tabs = JSON.parse(tabs);
if (Array.isArray(tabs) && tabs.length) {
hasStore = true;
this.presetTabs(tabs);
}
} catch (e) {}
return hasStore;
}
}
});
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"47deaf46-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./lib/components/RouterAlive.vue?vue&type=template&id=0d380a4a&
var RouterAlivevue_type_template_id_0d380a4a_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"router-alive"},[_c('transition',_vm._b({attrs:{"appear":""},on:{"after-enter":_vm.onTrans,"after-leave":_vm.onTrans}},'transition',_vm.pageTrans,false),[_c('keep-alive',{attrs:{"max":_vm.max}},[(_vm.alive && !_vm.onRefresh)?_c('router-view',_vm._g({key:_vm.key,ref:"page",class:_vm.pageClass},_vm.hooks)):_vm._e()],1)],1),_c('transition',_vm._b({attrs:{"appear":""},on:{"after-enter":_vm.onTrans,"after-leave":_vm.onTrans}},'transition',_vm.pageTrans,false),[(!_vm.alive && !_vm.onRefresh)?_c('router-view',{key:_vm.key,ref:"page",class:_vm.pageClass}):_vm._e()],1)],1)}
var RouterAlivevue_type_template_id_0d380a4a_staticRenderFns = []
// CONCATENATED MODULE: ./lib/components/RouterAlive.vue?vue&type=template&id=0d380a4a&
// CONCATENATED MODULE: ./lib/config/rules.js
// 内置规则
/* harmony default export */ var rules = ({
// 地址,params 不一致则独立缓存
path: function path(route) {
return route.path;
},
// 完整地址 (忽略 hash),params 或 query 不一致则独立缓存
fullpath: function fullpath(route) {
return prunePath(route.fullPath);
}
});
// CONCATENATED MODULE: ./lib/util/RouteMatch.js
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
// 解析路由 key
function parseRouteKey($route, route, key) {
var defaultKey = route.path;
if (!key) return defaultKey;
if (typeof key === 'string') {
// 规则
var rule = rules[key.toLowerCase()];
return rule ? rule($route) : key;
}
if (typeof key === 'function') {
return parseRouteKey($route, route, key($route));
}
return defaultKey;
} // 解析匹配的路径
function parsePath(path, params) {
for (var key in params) {
path = path.replace(':' + key, params[key]);
}
return path;
} // 匹配路由数据
var RouteMatch_RouteMatch = /*#__PURE__*/function () {
function RouteMatch(vm, $route) {
_classCallCheck(this, RouteMatch);
this.vm = vm;
this.$route = $route;
} // 设置路由
_createClass(RouteMatch, [{
key: "$route",
set: function set($route) {
if ($route && !$route.matched) {
var $router = this.vm.$router;
$route = $router.match($route, $router.currentRoute);
}
this._$route = $route;
} // 获取路由
,
get: function get() {
return this._$route || this.vm.$route;
} // 页面路由索引
}, {
key: "routeIndex",
get: function get() {
return this.vm.routeIndex;
} // 下级路由
}, {
key: "route",
get: function get() {
return this.$route.matched[this.routeIndex];
} // 根路径
}, {
key: "basePath",
get: function get() {
if (!this.routeIndex) return '/';
var baseRoute = this.$route.matched[this.routeIndex - 1];
var path = baseRoute.path;
return path && parsePath(path, this.$route.params);
} // 缓存路径,用于判断是否复用
}, {
key: "alivePath",
get: function get() {
var $route = this.$route; // 嵌套路由
if (this.nest) {
return parsePath(this.route.path, $route.params);
}
return prunePath($route.fullPath);
} // 路由元
}, {
key: "meta",
get: function get() {
var route = this.route,
$nuxt = this.vm.$nuxt; // Nuxt 优先从页面配置获取 meta
if ($nuxt) {
try {
var _$nuxt$context$route$ = $nuxt.context.route.meta,
metas = _$nuxt$context$route$ === void 0 ? [] : _$nuxt$context$route$;
var meta = metas[this.routeIndex];
if (meta && Object.keys(meta).length) {
return meta;
}
} catch (e) {
console.error(e);
}
}
return route && route.meta || {};
} // 是否嵌套路由
}, {
key: "nest",
get: function get() {
return this.$route.matched.length > this.routeIndex + 1;
} // 路由 key
}, {
key: "key",
get: function get() {
if (!this.route) return '';
return parseRouteKey(this.$route, this.route, this.meta.key);
} // 是否缓存
}, {
key: "alive",
get: function get() {
var keepAlive = this.meta.keepAlive;
return typeof keepAlive === 'boolean' ? keepAlive : this.vm.keepAlive;
} // 是否复用组件
}, {
key: "reusable",
get: function get() {
var reuse = this.meta.reuse;
return typeof reuse === 'boolean' ? reuse : this.vm.reuse;
}
}]);
return RouteMatch;
}();
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./lib/components/RouterAlive.vue?vue&type=script&lang=js&
function RouterAlivevue_type_script_lang_js_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function RouterAlivevue_type_script_lang_js_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { RouterAlivevue_type_script_lang_js_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { RouterAlivevue_type_script_lang_js_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function RouterAlivevue_type_script_lang_js_slicedToArray(arr, i) { return RouterAlivevue_type_script_lang_js_arrayWithHoles(arr) || RouterAlivevue_type_script_lang_js_iterableToArrayLimit(arr, i) || RouterAlivevue_type_script_lang_js_unsupportedIterableToArray(arr, i) || RouterAlivevue_type_script_lang_js_nonIterableRest(); }
function RouterAlivevue_type_script_lang_js_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function RouterAlivevue_type_script_lang_js_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return RouterAlivevue_type_script_lang_js_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return RouterAlivevue_type_script_lang_js_arrayLikeToArray(o, minLen); }
function RouterAlivevue_type_script_lang_js_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function RouterAlivevue_type_script_lang_js_iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function RouterAlivevue_type_script_lang_js_arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/**
* 路由缓存控件
*/
/* harmony default export */ var RouterAlivevue_type_script_lang_js_ = ({
name: 'RouterAlive',
provide: function provide() {
// 提供实例给子组件调用
return {
RouterAlive: this
};
},
props: {
// 默认是否开启缓存
keepAlive: {
type: Boolean,
default: false
},
// 是否复用路由组件
reuse: {
type: Boolean,
default: false
},
// 最大缓存数,0 则不限制
max: {
type: Number,
default: 0
},
// 页面 class
pageClass: {
type: [Array, Object, String],
default: 'router-alive-page'
},
// 过渡效果
transition: {
type: [String, Object]
}
},
data: function data() {
// 缓存记录
this.cache = {};
return {
// 路由匹配信息
routeMatch: new RouteMatch_RouteMatch(this),
// 页面路由索引
routeIndex: this.getRouteIndex(),
// 是否正在更新
onRefresh: false
};
},
computed: _objectSpread(_objectSpread({}, mapGetters('routeMatch', ['key', 'meta', 'nest', 'alive', 'reusable', 'basePath', 'alivePath'])), {}, {
// 监听子页面钩子
hooks: function hooks() {
var _this = this;
var events = {};
var hooks = ['created', 'mounted', 'activated', 'destroyed'];
hooks.forEach(function (hook) {
events['hook:' + hook] = function () {
return _this.pageHook(hook);
};
});
return events;
},
// 页面过渡
pageTrans: function pageTrans() {
return getTransOpt(this.transition);
}
}),
watch: {
// 监听路由
$route: {
handler: function handler($route, old) {
// 组件就绪
if (!old) this.$emit('ready', this);
if (!$route.matched.length) return;
var key = this.key,
alive = this.alive,
reusable = this.reusable,
alivePath = this.alivePath,
nest = this.nest;
var cacheItem = this.cache[key] || {};
var cacheAlivePath = cacheItem.alivePath,
cacheFullPath = cacheItem.fullPath,
cacheVM = cacheItem.vm; // 不复用且路由改变则清理组件缓存
if (cacheAlivePath && !reusable && cacheAlivePath !== alivePath) {
cacheAlivePath = '';
this.refresh(key);
} // 嵌套路由,地址跟缓存不一致
if (nest && cacheVM && $route.fullPath !== cacheFullPath) {
var oldKey = this.matchRoute(old).key;
if (oldKey !== key) {
this.nestForceUpdate = true;
}
} // 类型:更新或者新建缓存
var type = cacheAlivePath ? 'update' : 'create';
this.$emit('change', type, this.routeMatch); // 更新缓存路径
if (alive) {
cacheItem.fullPath = $route.fullPath;
}
},
immediate: true
}
},
mounted: function mounted() {
// 获取 keepAlive 组件实例
this.$refs.alive = this._vnode.children[0].child._vnode.componentInstance;
},
// 销毁后清理
destroyed: function destroyed() {
this.cache = null;
this.routeMatch = null;
this._match = null;
this.$refs.alive = null;
},
methods: {
// 获取页面路由索引
getRouteIndex: function getRouteIndex() {
var cur = this;
var depth = -1; // 路由深度
while (cur && depth < 0) {
var _ref = cur.$vnode || {},
data = _ref.data;
if (data && data.routerView) {
depth = data.routerViewDepth;
} else {
cur = cur.$parent;
}
}
return depth + 1;
},
// 移除缓存
remove: function remove() {
var key = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.key;
var $alive = this.$refs.alive;
if (!$alive) return;
var cacheItem = this.cache[key];
var cache = $alive.cache,
keys = $alive.keys; // 销毁缓存组件实例,清理 RouterAlive 缓存记录
if (cacheItem) {
cacheItem.vm.$destroy();
cacheItem.vm = null;
this.cache[key] = null;
} // 清理 keepAlive 缓存记录
Object.entries(cache).find(function (_ref2) {
var _ref3 = RouterAlivevue_type_script_lang_js_slicedToArray(_ref2, 2),
id = _ref3[0],
item = _ref3[1];
if (item && item.data.key === key) {
// 销毁组件实例
item.componentInstance && item.componentInstance.$destroy();
cache[id] = null;
util_remove(keys, id);
return true;
}
});
},
// 刷新
refresh: function refresh() {
var key = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.key;
this.remove(key); // 非当前缓存,直接移除
if (key === this.key) {
this.reload();
}
},
// 重新加载
reload: function reload() {
if (this.onRefresh) return;
this.onRefresh = true;
},
// 缓存页面组件钩子
pageHook: function pageHook(hook) {
var handler = this["pageHook:".concat(hook)];
if (typeof handler === 'function') handler();
},
// 页面创建
'pageHook:created': function pageHookCreated() {
this.cache[this.key] = {
alivePath: this.alivePath,
fullPath: this.$route.fullPath
};
},
// 页面挂载
'pageHook:mounted': function pageHookMounted() {
var page = this.$refs.page;
this.cache[this.key].vm = page;
},
// 页面激活
'pageHook:activated': function pageHookActivated() {
// 嵌套路由缓存导致页面不匹配时强制更新
if (this.nestForceUpdate) {
delete this.nestForceUpdate;
this.$refs.page.$forceUpdate();
}
},
// 页面销毁后清理 cache
'pageHook:destroyed': function pageHookDestroyed() {
var _this2 = this;
return RouterAlivevue_type_script_lang_js_asyncToGenerator( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return _this2.$nextTick();
case 2:
if (_this2.cache) {
_context.next = 4;
break;
}
return _context.abrupt("return");
case 4:
// 清理已销毁页面的缓存信息 | item = _ref5[1];
var _ref6 = item || {},
vm = _ref6.vm;
if (vm && vm._isDestroyed) {
_this2.remove(key);
}
});
case 5:
case "end":
return _context.stop();
}
}
}, _callee);
}))();
},
// 页面过渡后结束刷新状态
onTrans: function onTrans() {
if (this.onRefresh) {
this.onRefresh = false;
this.$emit('change', 'create', this.routeMatch);
}
},
// 匹配路由信息
matchRoute: function matchRoute($route) {
var matched = this._match; // 当前路由
if ($route === this.$route || $route.fullPath === this.$route.fullPath || $route === this.$route.fullPath) {
return this.routeMatch;
}
if (matched) {
matched.$route = $route;
return matched;
}
return this._match = new RouteMatch_RouteMatch(this, $route);
}
}
});
// CONCATENATED MODULE: ./lib/components/RouterAlive.vue?vue&type=script&lang=js&
/* harmony default export */ var components_RouterAlivevue_type_script_lang_js_ = (RouterAlivevue_type_script_lang_js_);
// CONCATENATED MODULE: ./node_modules/vue-loader/lib/runtime/componentNormalizer.js
/* globals __VUE_SSR_CONTEXT__ */
// IMPORTANT: Do NOT use ES2015 features in this file (except for modules).
// This module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle.
function normalizeComponent (
scriptExports,
render,
staticRenderFns,
functionalTemplate,
injectStyles,
scopeId,
moduleIdentifier, /* server only */
shadowMode /* vue-cli only */
) {
// Vue.extend constructor export interop
var options = typeof scriptExports === 'function'
? scriptExports.options
: scriptExports
// render functions
if (render) {
options.render = render
options.staticRenderFns = staticRenderFns
options._compiled = true
}
// functional template
if (functionalTemplate) {
options.functional = true
}
// scopedId
if (scopeId) {
options._scopeId = 'data-v-' + scopeId
}
var hook
if (moduleIdentifier) { // server build
hook = function (context) {
// 2.3 injection
context =
context || // cached call
(this.$vnode && this.$vnode.ssrContext) || // stateful
(this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__
}
// inject component styles
if (injectStyles) {
injectStyles.call(this, context)
}
// register component module identifier for async chunk inferrence
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier)
}
}
// used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook
} else if (injectStyles) {
hook = shadowMode
? function () {
injectStyles.call(
this,
(options.functional ? this.parent : this).$root.$options.shadowRoot
)
}
: injectStyles
}
if (hook) {
if (options.functional) {
// for template-only hot-reload because in that case the render fn doesn't
// go through the normalizer
options._injectStyles = hook
// register for functional component in vue file
var originalRender = options.render
options.render = function renderWithStyleInjection (h, context) {
hook.call(context)
return originalRender(h, context)
}
} else {
// inject component registration as beforeCreate hook
var existing = options.beforeCreate
options.beforeCreate = existing
? [].concat(existing, hook)
: [hook]
}
}
return {
exports: scriptExports,
options: options
}
}
// CONCATENATED MODULE: ./lib/components/RouterAlive.vue
/* normalize component */
var component = normalizeComponent(
components_RouterAlivevue_type_script_lang_js_,
RouterAlivevue_type_template_id_0d380a4a_render,
RouterAlivevue_type_template_id_0d380a4a_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var RouterAlive = (component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"47deaf46-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./lib/components/TabItem.vue?vue&type=template&id=21e0a679&
var TabItemvue_type_template_id_21e0a679_render = function () {
var _obj;
var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('router-link',{class:( _obj = {
'router-tab__item': true
}, _obj[_vm.tabClass || ''] = true, _obj['is-active'] = _vm.$tabs.activeTabId === _vm.id, _obj['is-closable'] = _vm.closable, _obj['is-contextmenu'] = _vm.$tabs.contextData.id === _vm.id, _obj['is-drag-over'] = _vm.isDragOver && !_vm.onDragSort, _obj ),attrs:{"tag":"li","to":_vm.to,"draggable":_vm.$tabs.dragsort},nativeOn:{"dragstart":function($event){return _vm.onDragStart($event)},"dragend":function($event){return _vm.onDragEnd($event)},"dragover":function($event){$event.preventDefault();_vm.isDragOver = true},"dragleave":function($event){$event.preventDefault();_vm.isDragOver = false},"drop":function($event){return _vm.onDrop($event)}}},[_vm._t("default",[(_vm.icon)?_c('i',{staticClass:"router-tab__item-icon",class:_vm.icon}):_vm._e(),_c('span',{staticClass:"router-tab__item-title",attrs:{"title":_vm.tips}},[_vm._v(_vm._s(_vm.title))]),(_vm.closable)?_c('i',{staticClass:"router-tab__item-close",on:{"click":function($event){$event.preventDefault();$event.stopPropagation();return _vm.close($event)}}}):_vm._e()],null,this)],2)}
var TabItemvue_type_template_id_21e0a679_staticRenderFns = []
// CONCATENATED MODULE: ./lib/components/TabItem.vue?vue&type=template&id=21e0a679&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./lib/components/TabItem.vue?vue&type=script&lang=js&
function TabItemvue_type_script_lang_js_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function TabItemvue_type_script_lang_js_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { TabItemvue_type_script_lang_js_ownKeys(Object(source), true).forEach(function (key) { TabItemvue_type_script_lang_js_defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { TabItemvue_type_script_lang_js_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function TabItemvue_type_script_lang_js_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
// 页签项
/* harmony default export */ var TabItemvue_type_script_lang_js_ = ({
name: 'TabItem',
inject: ['$tabs'],
props: {
// 页签原始数据,方便 slot 插槽自定义数据
data: {
type: Object,
required: true
},
// 页签项索引
index: Number
},
data: function data() {
return {
onDragSort: false,
// 是否正在拖拽
isDragOver: false // 是否拖拽经过
};
},
computed: TabItemvue_type_script_lang_js_objectSpread(TabItemvue_type_script_lang_js_objectSpread({}, mapGetters('data', ['id', 'to', 'icon', 'tabClass', 'target', 'href'])), {}, {
// 国际化
i18nText: function i18nText() {
return this.$tabs.i18nText;
},
// 未命名页签
untitled: function untitled() {
return this.$tabs.langs.tab.untitled;
},
// 页签标题
title: function title() {
return this.i18nText(this.data.title) || this.untitled;
},
// 页签提示
tips: function tips() {
return this.i18nText(this.data.tips || this.data.title) || this.untitled;
},
// 是否可关闭
closable: function closable() {
var _this$$tabs = this.$tabs,
keepLastTab = _this$$tabs.keepLastTab,
items = _this$$tabs.items;
return this.data.closable !== false && !(keepLastTab && items.length < 2);
}
}),
methods: {
// 关闭当前页签
close: function close() {
this.$tabs.closeTab(this.id);
},
// 拖拽
onDragStart: function onDragStart(e) {
this.onDragSort = this.$tabs.onDragSort = true;
e.dataTransfer.dropEffect = 'move';
e.dataTransfer.setData('text', this.index + '');
},
// 拖拽结束
onDragEnd: function onDragEnd() {
this.onDragSort = this.$tabs.onDragSort = false;
},
// 释放后排序
onDrop: function onDrop(e) {
var items = this.$tabs.items;
var fromIndex = +e.dataTransfer.getData('text');
var tab = items[fromIndex];
items.splice(fromIndex, 1);
items.splice(this.index, 0, tab);
this.isDragOver = false;
}
}
});
// CONCATENATED MODULE: ./lib/components/TabItem.vue?vue&type=script&lang=js&
/* harmony default export */ var components_TabItemvue_type_script_lang_js_ = (TabItemvue_type_script_lang_js_);
// CONCATENATED MODULE: ./lib/components/TabItem.vue
/* normalize component */
var TabItem_component = normalizeComponent(
components_TabItemvue_type_script_lang_js_,
TabItemvue_type_template_id_21e0a679_render,
TabItemvue_type_template_id_21e0a679_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var TabItem = (TabItem_component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"47deaf46-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./lib/components/TabScroll.vue?vue&type=template&id=559a731b&
var TabScrollvue_type_template_id_559a731b_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"router-tab__scroll",on:{"wheel":function($event){$event.preventDefault();return _vm.onWheel($event)},"mouseenter":_vm.update}},[_c('div',{ref:"container",staticClass:"router-tab__scroll-container",class:{ 'is-mobile': _vm.isMobile },on:{"scroll":_vm.update}},[_vm._t("default")],2),_c('div',{directives:[{name:"show",rawName:"v-show",value:(_vm.hasScroller),expression:"hasScroller"}],ref:"bar",staticClass:"router-tab__scrollbar",class:{ 'is-dragging': _vm.dragData }},[_c('div',{ref:"thumb",staticClass:"router-tab__scrollbar-thumb",style:({
width: (_vm.thumbWidth + "px"),
transform: ("translateX(" + _vm.thumbLeft + "px")
}),on:{"mousedown":function($event){$event.preventDefault();return _vm.onDragStart($event)}}})])])}
var TabScrollvue_type_template_id_559a731b_staticRenderFns = []
// CONCATENATED MODULE: ./lib/components/TabScroll.vue?vue&type=template&id=559a731b&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./lib/components/TabScroll.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
// 滚动条
/* harmony default export */ var TabScrollvue_type_script_lang_js_ = ({
name: 'TabScroll',
props: {
// 每次滚动距离
space: {
type: Number,
default: 300
}
},
data: function data() {
return {
isMobile: false,
// 是否移动端
scrollData: {
clientWidth: 0,
scrollWidth: 0,
scrollLeft: 0
},
dragData: null
};
},
computed: {
// 是否拥有滚动条
hasScroller: function hasScroller() {
return !this.isMobile && !this.$tabs.onDragSort && this.scrollData.scrollWidth > this.scrollData.clientWidth;
},
// 滑块宽度
thumbWidth: function thumbWidth() {
if (!this.hasScroller) return;
var _this$scrollData = this.scrollData,
clientWidth = _this$scrollData.clientWidth,
scrollWidth = _this$scrollData.scrollWidth;
return clientWidth / scrollWidth * clientWidth;
},
// 滑块 left
thumbLeft: function thumbLeft() {
if (!this.hasScroller) return; // 拖拽滚动
if (this.dragData) {
return this.dragData.thumbLeft;
}
var _this$scrollData2 = this.scrollData,
clientWidth = _this$scrollData2.clientWidth,
scrollWidth = _this$scrollData2.scrollWidth,
scrollLeft = _this$scrollData2.scrollLeft;
return (clientWidth - this.thumbWidth) * (scrollLeft / (scrollWidth - clientWidth));
}
},
mounted: function mounted() {
this.update();
},
methods: {
// 更新滚动数据
update: function update() {
var _this$$refs$container = this.$refs.container,
clientWidth = _this$$refs$container.clientWidth,
scrollWidth = _this$$refs$container.scrollWidth,
scrollLeft = _this$$refs$container.scrollLeft; // 是否移动端
this.isMobile = /mobile/i.test(navigator.userAgent);
Object.assign(this.scrollData, {
clientWidth: clientWidth,
scrollWidth: scrollWidth,
scrollLeft: scrollLeft
});
},
// 滚动到指定位置
scrollTo: function scrollTo(left) {
var smooth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
util_scrollTo({
wrap: this.$refs.container,
left: left,
smooth: smooth
});
},
// 滚动到元素
scrollIntoView: function scrollIntoView(el) {
util_scrollIntoView({
el: el,
wrap: this.$refs.container,
inline: 'center'
});
},
// 判断子节点是否完全在可视区域
isInView: function isInView(el) {
var container = this.$refs.container;
var offsetLeft = el.offsetLeft;
var scrollLeft = container.scrollLeft;
if (offsetLeft < scrollLeft || offsetLeft + el.clientWidth > scrollLeft + container.clientWidth) {
return false;
}
return true;
},
// 页签鼠标滚动
onWheel: function onWheel(e) {
var now = +new Date();
var enable = now - (this.lastWheel || 0) > 100;
if (!enable) return;
this.lastWheel = now;
var space = this.space;
var isWheelUp = e.deltaY < 0;
this.scrollTo(this.$refs.container.scrollLeft + (isWheelUp ? -space : space));
},
// 拖拽
onDragStart: function onDragStart(e) {
var thumbLeft = this.thumbLeft;
this.dragData = {
startPageX: e.pageX,
startScrollLeft: this.$refs.container.scrollLeft,
startThumbLeft: thumbLeft,
thumbLeft: thumbLeft
};
document.addEventListener('mousemove', this.onDragMove);
document.addEventListener('mouseup', this.onDragEnd);
},
// 拖拽移动
onDragMove: function onDragMove(e) {
var dragData = this.dragData,
thumbWidth = this.thumbWidth;
var _this$scrollData3 = this.scrollData,
clientWidth = _this$scrollData3.clientWidth,
scrollWidth = _this$scrollData3.scrollWidth;
var thumbLeft = dragData.startThumbLeft + e.pageX - dragData.startPageX;
var maxThumbLeft = clientWidth - thumbWidth;
if (thumbLeft < 0) {
thumbLeft = 0;
} else if (thumbLeft > maxThumbLeft) {
thumbLeft = maxThumbLeft;
} // 更新滑块定位
dragData.thumbLeft = thumbLeft; // 滚动
this.scrollTo(thumbLeft * (scrollWidth - clientWidth) / (clientWidth - thumbWidth), false);
e.preventDefault();
},
// 拖拽结束
onDragEnd: function onDragEnd(e) {
this.dragData = null;
document.removeEventListener('mousemove', this.onDragMove);
document.removeEventListener('mouseup', this.onDragEnd);
e.preventDefault();
}
}
});
// CONCATENATED MODULE: ./lib/components/TabScroll.vue?vue&type=script&lang=js&
/* harmony default export */ var components_TabScrollvue_type_script_lang_js_ = (TabScrollvue_type_script_lang_js_);
// CONCATENATED MODULE: ./lib/components/TabScroll.vue
/* normalize component */
var TabScroll_component = normalizeComponent(
components_TabScrollvue_type_script_lang_js_,
TabScrollvue_type_template_id_559a731b_render,
TabScrollvue_type_template_id_559a731b_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var TabScroll = (TabScroll_component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"47deaf46-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./lib/components/Contextmenu.vue?vue&type=template&id=d5b676dc&
var Contextmenuvue_type_template_id_d5b676dc_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"router-tab__contextmenu",class:{ 'has-icon': _vm.hasIcon },style:({
left: ((_vm.data.left) + "px"),
top: ((_vm.data.top) + "px")
})},_vm._l((_vm.menuList),function(item){return _c('tab-contextmenu-item',{key:item.id,attrs:{"data":item}})}),1)}
var Contextmenuvue_type_template_id_d5b676dc_staticRenderFns = []
// CONCATENATED MODULE: ./lib/components/Contextmenu.vue?vue&type=template&id=d5b676dc&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"47deaf46-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./lib/components/ContextmenuItem.vue?vue&type=template&id=85c9e580&
var ContextmenuItemvue_type_template_id_85c9e580_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return (_vm.visible)?_c('a',{staticClass:"router-tab__contextmenu-item",class:_vm.menuClass,attrs:{"data-action":_vm.id,"disabled":!_vm.enable,"title":_vm.tips},on:{"click":function($event){_vm.enable && _vm.data.handler(_vm.context)}}},[(_vm.icon)?_c('i',{staticClass:"router-tab__contextmenu-icon",class:_vm.icon}):_vm._e(),_vm._v(" "+_vm._s(_vm.title)+" ")]):_vm._e()}
var ContextmenuItemvue_type_template_id_85c9e580_staticRenderFns = []
// CONCATENATED MODULE: ./lib/components/ContextmenuItem.vue?vue&type=template&id=85c9e580&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./lib/components/ContextmenuItem.vue?vue&type=script&lang=js&
function ContextmenuItemvue_type_script_lang_js_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function ContextmenuItemvue_type_script_lang_js_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ContextmenuItemvue_type_script_lang_js_ownKeys(Object(source), true).forEach(function (key) { ContextmenuItemvue_type_script_lang_js_defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ContextmenuItemvue_type_script_lang_js_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function ContextmenuItemvue_type_script_lang_js_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ var ContextmenuItemvue_type_script_lang_js_ = ({
name: 'ContextmenuItem',
inject: ['$tabs'],
props: {
// 菜单数据
data: {
type: Object,
required: true
}
},
computed: ContextmenuItemvue_type_script_lang_js_objectSpread({
// 参数
context: function context() {
var $tabs = this.$tabs,
$menu = this.$parent;
var target = $menu.target,
data = $menu.data;
return {
$tabs: $tabs,
$menu: $menu,
target: target,
data: data
};
}
}, mapGetters('data', {
id: '',
// 菜单标题
title: function title() {
return this.$tabs.langs.contextmenu[this.id];
},
icon: '',
tips: '',
class: {
default: '',
alias: 'menuClass'
},
visible: true,
// 是否显示
enable: true // 是否启用
}, 'context'))
});
// CONCATENATED MODULE: ./lib/components/ContextmenuItem.vue?vue&type=script&lang=js&
/* harmony default export */ var components_ContextmenuItemvue_type_script_lang_js_ = (ContextmenuItemvue_type_script_lang_js_);
// CONCATENATED MODULE: ./lib/components/ContextmenuItem.vue
/* normalize component */
var ContextmenuItem_component = normalizeComponent(
components_ContextmenuItemvue_type_script_lang_js_,
ContextmenuItemvue_type_template_id_85c9e580_render,
ContextmenuItemvue_type_template_id_85c9e580_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var ContextmenuItem = (ContextmenuItem_component.exports);
// CONCATENATED MODULE: ./lib/config/contextmenu.js
function contextmenu_slicedToArray(arr, i) { return contextmenu_arrayWithHoles(arr) || contextmenu_iterableToArrayLimit(arr, i) || contextmenu_unsupportedIterableToArray(arr, i) || contextmenu_nonIterableRest(); }
function contextmenu_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function contextmenu_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return contextmenu_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return contextmenu_arrayLikeToArray(o, minLen); }
function contextmenu_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function contextmenu_iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function contextmenu_arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
// 菜单数据
var menuMap = {
// 刷新
refresh: {
handler: function handler(_ref) {
var data = _ref.data,
$tabs = _ref.$tabs;
$tabs.refreshTab(data.id);
}
},
// 刷新全部
refreshAll: {
handler: function handler(_ref2) {
var $tabs = _ref2.$tabs;
$tabs.refreshAll();
}
},
// 关闭
close: {
enable: function enable(_ref3) {
var target = _ref3.target;
return target.closable;
},
handler: function handler(_ref4) {
var data = _ref4.data,
$tabs = _ref4.$tabs;
$tabs.closeTab(data.id);
}
},
// 关闭左侧
closeLefts: {
enable: function enable(_ref5) {
var $menu = _ref5.$menu;
return $menu.lefts.length;
},
handler: function handler(_ref6) {
var $menu = _ref6.$menu;
$menu.closeMulti($menu.lefts);
}
},
// 关闭右侧
closeRights: {
enable: function enable(_ref7) {
var $menu = _ref7.$menu;
return $menu.rights.length;
},
handler: function handler(_ref8) {
var $menu = _ref8.$menu;
$menu.closeMulti($menu.rights);
}
},
// 关闭其他
closeOthers: {
enable: function enable(_ref9) {
var $menu = _ref9.$menu;
return $menu.others.length;
},
handler: function handler(_ref10) {
var $menu = _ref10.$menu;
$menu.closeMulti($menu.others);
}
}
}; // 遍历填充 id
Object.entries(menuMap).forEach(function (_ref11) {
var _ref12 = contextmenu_slicedToArray(_ref11, 2),
id = _ref12[0],
item = _ref12[1];
return item.id = id;
});
/* harmony default export */ var config_contextmenu = (menuMap); // 默认菜单
var defaultMenu = ['refresh', 'refreshAll', 'close', 'closeLefts', 'closeRights', 'closeOthers'];
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./lib/components/Contextmenu.vue?vue&type=script&lang=js&
function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = Contextmenuvue_type_script_lang_js_unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function Contextmenuvue_type_script_lang_js_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return Contextmenuvue_type_script_lang_js_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return Contextmenuvue_type_script_lang_js_arrayLikeToArray(o, minLen); }
function Contextmenuvue_type_script_lang_js_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function Contextmenuvue_type_script_lang_js_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function Contextmenuvue_type_script_lang_js_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { Contextmenuvue_type_script_lang_js_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { Contextmenuvue_type_script_lang_js_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function Contextmenuvue_type_script_lang_js_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function Contextmenuvue_type_script_lang_js_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { Contextmenuvue_type_script_lang_js_ownKeys(Object(source), true).forEach(function (key) { Contextmenuvue_type_script_lang_js_defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { Contextmenuvue_type_script_lang_js_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function Contextmenuvue_type_script_lang_js_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ var Contextmenuvue_type_script_lang_js_ = ({
name: 'TabContextmenu',
inject: ['$tabs'],
components: {
TabContextmenuItem: ContextmenuItem
},
props: {
// 右键数据
data: {
type: [Boolean, Object]
},
// 菜单配置
menu: {
type: Array,
default: function _default() {
return defaultMenu;
}
}
},
computed: {
// 激活菜单的页签
target: function target() {
return this.tabMap[this.data.id];
},
// 菜单选项
menuList: function menuList() {
return this.menu.map(function (item) {
if (typeof item === 'string') {
// 内置菜单
return config_contextmenu[item];
} else if (item && item.id) {
// 扩展内置菜单
var origin = config_contextmenu[item.id];
return origin ? Contextmenuvue_type_script_lang_js_objectSpread(Contextmenuvue_type_script_lang_js_objectSpread({}, origin), item) : item;
}
}).filter(function (item) {
return item;
});
},
// 是否显示图标
hasIcon: function hasIcon() {
return this.menuList.some(function (item) {
return item.icon;
});
},
// 页签 map
tabMap: function tabMap() {
return this.$tabs.$refs.tab.reduce(function (map, item) {
map[item.id] = item;
return map;
}, {});
},
// 页签组件列表
tabs: function tabs() {
var _this = this;
return this.$tabs.items.map(function (item) {
return _this.tabMap[item.id];
});
},
// 左侧可关闭的页签
lefts: function lefts() {
return this.tabs.slice(0, this.data.index).filter(function (item) {
return item.closable;
});
},
// 左侧可关闭的页签
rights: function rights() {
return this.tabs.slice(this.data.index + 1).filter(function (item) {
return item.closable;
});
},
// 其他可关闭的页签
others: function others() {
var _this2 = this;
return this.tabs.filter(function (item) {
return item.closable && _this2.data.id !== item.id;
});
}
},
mounted: function mounted() {
this.adjust();
},
methods: {
// 关闭多个页签
closeMulti: function closeMulti(tabs) {
var _this3 = this;
return Contextmenuvue_type_script_lang_js_asyncToGenerator( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
var _iterator, _step, id;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_iterator = _createForOfIteratorHelper(tabs);
_context.prev = 1;
_iterator.s();
case 3:
if ((_step = _iterator.n()).done) {
_context.next = 14;
break;
}
id = _step.value.id;
_context.prev = 5;
_context.next = 8;
return _this3.$tabs.removeTab(id);
case 8:
_context.next = 12;
break;
case 10:
_context.prev = 10;
_context.t0 = _context["catch"](5);
case 12:
_context.next = 3;
break;
case 14:
_context.next = 19;
break;
case 16:
_context.prev = 16;
_context.t1 = _context["catch"](1);
_iterator.e(_context.t1);
case 19:
_context.prev = 19;
_iterator.f();
return _context.finish(19);
case 22:
// 当前页签如已关闭,则打开右键选中页签
if (!_this3.$tabs.activeTab) {
_this3.$router.replace(_this3.target.to);
}
case 23:
case "end":
return _context.stop();
}
}
}, _callee, null, [[1, 16, 19, 22], [5, 10]]);
}))();
},
// 适应边界位置
adjust: function adjust() {
var clientWidth = this.$el.clientWidth;
var winWidth = window.innerWidth;
if (this.data.left + clientWidth > winWidth) {
this.data.left = winWidth - clientWidth - 5;
}
}
}
});
// CONCATENATED MODULE: ./lib/components/Contextmenu.vue?vue&type=script&lang=js&
/* harmony default export */ var components_Contextmenuvue_type_script_lang_js_ = (Contextmenuvue_type_script_lang_js_);
// CONCATENATED MODULE: ./lib/components/Contextmenu.vue
/* normalize component */
var Contextmenu_component = normalizeComponent(
components_Contextmenuvue_type_script_lang_js_,
Contextmenuvue_type_template_id_d5b676dc_render,
Contextmenuvue_type_template_id_d5b676dc_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var Contextmenu = (Contextmenu_component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/eslint-loader??ref--13-0!./lib/RouterTab.js?vue&type=script&lang=js&
function RouterTabvue_type_script_lang_js_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function RouterTabvue_type_script_lang_js_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { RouterTabvue_type_script_lang_js_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { RouterTabvue_type_script_lang_js_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function RouterTabvue_type_script_lang_js_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function RouterTabvue_type_script_lang_js_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { RouterTabvue_type_script_lang_js_ownKeys(Object(source), true).forEach(function (key) { RouterTabvue_type_script_lang_js_defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { RouterTabvue_type_script_lang_js_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function RouterTabvue_type_script_lang_js_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
// 方法
// 功能模块混入
// 子组件
// RouterTab 组件
var RouterTab = {
name: 'RouterTab',
mixins: [contextmenu, i18n, iframe, operate, mixins_pageLeave, mixins_scroll, restore],
components: {
RouterAlive: RouterAlive,
TabItem: TabItem,
TabScroll: TabScroll,
TabContextmenu: Contextmenu
},
// 注入子组件
provide: function provide() {
return {
$tabs: this
};
},
props: {
// 初始页签数据
tabs: {
type: Array,
default: function _default() {
return [];
}
},
// 页面刷新后是否恢复页签
restore: {
type: [Boolean, String],
default: false
},
// 是否监听 restoreKey 变化自动还原页签
restoreWatch: {
type: Boolean,
default: false
},
// 默认页面
defaultPage: [String, Object],
// 页签过渡效果
tabTransition: {
type: [String, Object],
default: 'router-tab-zoom'
},
// 页面过渡效果
pageTransition: {
type: [String, Object],
default: function _default() {
return {
name: 'router-tab-swap',
mode: 'out-in'
};
}
},
/**
* 自定义右键菜单
* 1. 为 false 时禁用
* 2. 为数组时可自定义右键菜单
*/
contextmenu: {
type: [Boolean, Array],
default: true
},
// 是否支持页签拖拽排序
dragsort: {
type: Boolean,
default: true
},
// 新页签插入位置,last 末尾,next 下一个
append: {
type: String,
default: 'last'
},
// 是否保留最后一个页签不被关闭
keepLastTab: {
type: Boolean,
default: true
},
// 默认是否缓存,可通过路由 meta.keepAlive 重置
keepAlive: {
type: Boolean,
default: true
},
// 最大缓存数,0 则不限制
maxAlive: {
type: Number,
default: 0
},
// 是否复用路由组件,可通过路由 meta.reuse 重置
reuse: {
type: Boolean,
default: false
},
// 页签国际化配置 i18n (key, [args])
i18n: Function,
/**
* 组件语言
* - 为字符串时,可以设置为内置的语言 'zh' (默认) 和 'en'
* - 为对象时,可设置自定义的语言
*/
lang: {
type: [String, Object],
default: 'zh'
}
},
data: function data() {
return {
items: [],
// 页签项
onDragSort: false,
// 拖拽排序中
aliveReady: false // RouterAlive 初始化
};
},
computed: {
// routerAlive
$alive: function $alive() {
return this.aliveReady ? this.$refs.routerAlive : null;
},
// 当前激活的页签 id
activeTabId: function activeTabId() {
return this.$alive ? this.$alive.key : null;
},
// 当前激活的页签索引
activeTabIndex: function activeTabIndex() {
var _this = this;
return this.items.findIndex(function (item) {
return item.id === _this.activeTabId;
});
},
// 当前激活的页签
activeTab: function activeTab() {
return this.items[this.activeTabIndex];
},
// 根路径
basePath: function basePath() {
return this.$alive ? this.$alive.basePath : '/';
},
// 默认路径
defaultPath: function defaultPath() {
return this.defaultPage || this.basePath || '/';
},
// 页签过渡
tabTrans: function tabTrans() {
return getTransOpt(this.tabTransition);
},
// 页面过渡
pageTrans: function pageTrans() {
return getTransOpt(this.pageTransition);
}
},
created: function created() {
// 添加到原型链
RouterTab.Vue.prototype.$tabs = this;
},
destroyed: function destroyed() {
var proto = RouterTab.Vue.prototype; // 取消原型挂载
if (proto.$tabs === this) {
proto.$tabs = null;
}
},
methods: {
// RouterAlive 组件就绪
onAliveReady: function onAliveReady($alive) {
// 获取 keepAlive 组件实例
this.$refs.routerAlive = $alive;
this.aliveReady = true;
this.initTabs();
},
// 初始页签数据
initTabs: function initTabs() {
if (this.restoreTabs()) return;
this.presetTabs();
},
// 预设页签
presetTabs: function presetTabs() {
var _this2 = this;
var tabs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.tabs;
var ids = {};
this.items = tabs.map(function (item) {
item = typeof item === 'string' ? {
to: item
} : item || emptyObj;
var matched = item.to && _this2.matchRoute(item.to);
if (matched) {
var tab = _this2.getRouteTab(matched);
var id = tab.id; // 根据 id 去重
if (!ids[id]) {
// id 不允许更改
delete item.id; // 初始 tab 数据
return ids[id] = Object.assign(tab, item);
}
}
}).filter(function (item) {
return !!item;
});
},
// RouterAlive 缓存更新时同步更改页签
onAliveChange: function onAliveChange(type, matched) {
var items = this.items,
lastMatchedKey = this.lastMatchedKey;
var key = matched.key;
var matchIdx = items.findIndex(function (_ref) {
var id = _ref.id;
return id === key;
});
var item = this.getRouteTab(matched); // 页签已存在
if (matchIdx > -1) {
if (type === 'create' || // 创建缓存
type === 'update' && items[matchIdx].to !== matched.$route.fullPath // 更新缓存且地址更改
) {
// 替换原页签
this.$set(items, matchIdx, item);
}
} else {
// 新增页签
if (this.append === 'next' && lastMatchedKey !== undefined) {
var lastIndex = this.items.findIndex(function (item) {
return item.id === lastMatchedKey;
});
items.splice(lastIndex + 1, 0, item);
} else {
items.push(item);
}
} // 上次缓存 key
this.lastMatchedKey = key;
},
// 从 route 中获取 tab 配置
getRouteTab: function getRouteTab(_ref2) {
var key = _ref2.key,
$route = _ref2.$route,
meta = _ref2.meta;
var tab = RouterTabvue_type_script_lang_js_objectSpread({}, meta); // 支持根据路由函数返回的页签属性
var props = ['title', 'tips', 'icon', 'closable'];
for (var i in tab) {
if (props.includes(i)) {
var val = tab[i];
if (typeof val === 'function') {
tab[i] = val($route);
}
}
}
return Object.assign(tab, {
id: key,
to: $route.fullPath
});
},
// 重载路由视图
reload: function reload() {
var _this3 = this;
return RouterTabvue_type_script_lang_js_asyncToGenerator( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_this3.$alive.reload();
case 1:
case "end":
return _context.stop();
}
}
}, _callee);
}))();
},
// 匹配路由信息
matchRoute: function matchRoute($route) {
return this.$alive.matchRoute($route);
},
// 获取路由缓存 key
getRouteKey: function getRouteKey() {
var route = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.$route;
return this.matchRoute(route).key;
},
// 从路由地址匹配页签 id
getIdByPath: function getIdByPath(path) {
var match = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
if (!path) return;
var matched = this.matchRoute(path);
var key = matched.key;
if (match) {
// 路由地址精确匹配页签
var matchTab = this.items.find(function (_ref3) {
var to = _ref3.to;
return prunePath(to) === prunePath(matched.$route.fullPath);
});
if (matchTab) {
return key;
}
}
return key;
}
}
};
/* harmony default export */ var RouterTabvue_type_script_lang_js_ = (RouterTab);
// CONCATENATED MODULE: ./lib/RouterTab.js?vue&type=script&lang=js&
/* harmony default export */ var lib_RouterTabvue_type_script_lang_js_ = (RouterTabvue_type_script_lang_js_);
// CONCATENATED MODULE: ./lib/RouterTab.vue
/* normalize component */
var RouterTab_component = normalizeComponent(
lib_RouterTabvue_type_script_lang_js_,
render,
staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var lib_RouterTab = (RouterTab_component.exports);
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"47deaf46-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./lib/page/Iframe.vue?vue&type=template&id=31382aae&
var Iframevue_type_template_id_31382aae_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"router-tab-iframe-fake"})}
var Iframevue_type_template_id_31382aae_staticRenderFns = []
// CONCATENATED MODULE: ./lib/page/Iframe.vue?vue&type=template&id=31382aae&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./lib/page/Iframe.vue?vue&type=script&lang=js&
function Iframevue_type_script_lang_js_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function Iframevue_type_script_lang_js_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { Iframevue_type_script_lang_js_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { Iframevue_type_script_lang_js_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
//
//
//
//
// Iframe 路由元
var iframeMeta = {
key: function key(route) {
return "iframe-".concat(route.params.src);
},
title: function title(route) {
return route.params.title;
},
icon: function icon(route) {
return route.params.icon;
}
}; // Iframe 页签页面
/* harmony default export */ var Iframevue_type_script_lang_js_ = ({
name: 'Iframe',
inject: ['$tabs'],
meta: iframeMeta,
// Nuxt 页面路由元
props: {
src: String,
title: String,
icon: String
},
computed: {
// 链接安全过滤,避免执行js
url: function url() {
var src = this.src; // XSS 攻击链接返回空白页
if (/^javascript:/.test(src)) {
return 'about:blank';
}
return src;
}
},
mounted: function mounted() {
var _this = this;
return Iframevue_type_script_lang_js_asyncToGenerator( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
var url, $tabs, iframes;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
url = _this.url, $tabs = _this.$tabs;
iframes = $tabs.iframes;
if (!iframes.includes(url)) {
iframes.push(url);
}
$tabs.currentIframe = url;
_context.next = 6;
return _this.$nextTick();
case 6:
_this.$tabs.iframeMounted(url);
case 7:
case "end":
return _context.stop();
}
}
}, _callee);
}))();
},
activated: function activated() {
this.$tabs.currentIframe = this.url;
},
deactivated: function deactivated() {
this.$tabs.currentIframe = null;
},
// 组件销毁后移除 iframe
destroyed: function destroyed() {
var url = this.url;
var iframes = this.$tabs.iframes;
var index = iframes.indexOf(url);
if (index > -1) {
iframes.splice(index, 1);
}
}
});
// CONCATENATED MODULE: ./lib/page/Iframe.vue?vue&type=script&lang=js&
/* harmony default export */ var page_Iframevue_type_script_lang_js_ = (Iframevue_type_script_lang_js_);
// CONCATENATED MODULE: ./lib/page/Iframe.vue
/* normalize component */
var Iframe_component = normalizeComponent(
page_Iframevue_type_script_lang_js_,
Iframevue_type_template_id_31382aae_render,
Iframevue_type_template_id_31382aae_staticRenderFns,
false,
null,
null,
null
)
/* harmony default export */ var Iframe = (Iframe_component.exports);
// CONCATENATED MODULE: ./lib/config/routes.js
// 注入的路由
/* harmony default export */ var routes = ([{
// iframe 路由
path: 'iframe/:src/:title?/:icon?',
component: Iframe,
props: true,
meta: iframeMeta
}]);
// CONCATENATED MODULE: ./lib/mixins/routerPage.js
// 浏览器窗口关闭或者刷新
var beforeunload = function beforeunload($tabs, tabId, beforePageLeave) {
return function (e) {
if (!$tabs && $tabs._isDestroyed) return;
var tab = $tabs.items.find(function (item) {
return item.id === tabId;
});
var msg = beforePageLeave(tab, 'unload');
if (msg && typeof msg === 'string') {
e.preventDefault();
e.returnValue = msg; // 非当前页签则切换
if ($tabs.activeTabId !== tabId) {
$tabs.open(tab.to, false, false);
}
return msg;
}
};
}; // 路由页面混入
/* harmony default export */ var routerPage = ({
watch: {
// 监听 routerTab 字段,更新页签信息
routeTab: {
handler: function handler(val) {
if (!val) return;
var tab = typeof val === 'string' ? {
title: val
} : val;
var _ref = this.$tabs || emptyObj,
activeTab = _ref.activeTab;
if (tab && activeTab) {
for (var key in tab) {
if (!['id', 'to'].includes(key)) {
this.$set(activeTab, key, tab[key]);
}
}
}
},
deep: true,
immediate: true
}
},
// 创建前记录缓存
mounted: function mounted() {
var $tabs = this.$tabs;
var _ref2 = this.$vnode && this.$vnode.componentOptions.Ctor.options || emptyObj,
beforePageLeave = _ref2.beforePageLeave; // 页面离开确认
if ($tabs && beforePageLeave) {
window.addEventListener('beforeunload', this._beforeunload = beforeunload($tabs, $tabs.activeTabId, beforePageLeave.bind(this)));
}
},
destroyed: function destroyed() {
if (this._beforeunload) {
window.removeEventListener('beforeunload', this._beforeunload);
}
}
});
// EXTERNAL MODULE: ./lib/scss/routerTab.scss
var routerTab = __webpack_require__("751c");
// CONCATENATED MODULE: ./lib/index.js
// 安装
lib_RouterTab.install = function install(Vue) {
if (install.installed) return;
lib_RouterTab.Vue = Vue;
install.installed = true;
Vue.component(lib_RouterTab.name, lib_RouterTab);
Vue.mixin(routerPage);
}; // 如果浏览器环境且拥有全局Vue,则自动安装组件
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(lib_RouterTab);
}
/* harmony default export */ var lib = (lib_RouterTab); // 导出
// CONCATENATED MODULE: ./node_modules/@vue/cli-service/lib/commands/build/entry-lib.js
/* harmony default export */ var entry_lib = __webpack_exports__["default"] = (lib);
/***/ })
/******/ });
//# sourceMappingURL=vue-router-tab.common.js.map | Object.entries(_this2.cache).forEach(function (_ref4) {
var _ref5 = RouterAlivevue_type_script_lang_js_slicedToArray(_ref4, 2),
key = _ref5[0], |
librapay_transaction.rs | use crate::librapay_instruction;
use log::*;
use solana_move_loader_program::{
account_state::{pubkey_to_address, LibraAccountState},
data_store::DataStore,
};
use solana_sdk::{
client::Client,
commitment_config::CommitmentConfig,
hash::Hash,
pubkey::Pubkey,
signature::{Keypair, Signer},
system_instruction,
transaction::Transaction,
};
use std::{boxed::Box, error, fmt};
pub fn create_genesis(keypair: &Keypair, microlibras: u64, recent_blockhash: Hash) -> Transaction {
let ix = librapay_instruction::genesis(&keypair.pubkey(), microlibras);
Transaction::new_signed_with_payer(
vec![ix],
Some(&keypair.pubkey()),
&[keypair],
recent_blockhash,
)
}
pub fn mint_tokens(
script_pubkey: &Pubkey,
payer_keypair: &Keypair,
genesis_keypair: &Keypair,
to_pubkey: &Pubkey,
microlibras: u64,
recent_blockhash: Hash,
) -> Transaction {
let ix = librapay_instruction::mint(
script_pubkey,
&genesis_keypair.pubkey(),
to_pubkey,
microlibras,
);
Transaction::new_signed_with_payer(
vec![ix],
Some(&payer_keypair.pubkey()),
&[payer_keypair, genesis_keypair],
recent_blockhash,
)
}
pub fn transfer(
script_pubkey: &Pubkey,
genesis_pubkey: &Pubkey,
payer_keypair: &Keypair,
from_keypair: &Keypair,
to_pubkey: &Pubkey,
microlibras: u64,
recent_blockhash: Hash,
) -> Transaction {
let ix = librapay_instruction::transfer(
script_pubkey,
genesis_pubkey,
&from_keypair.pubkey(),
to_pubkey,
microlibras,
);
Transaction::new_signed_with_payer(
vec![ix],
Some(&payer_keypair.pubkey()),
&[payer_keypair, from_keypair],
recent_blockhash,
)
}
pub fn create_accounts(
from_keypair: &Keypair,
to_keypair: &[&Keypair],
lamports: u64,
recent_blockhash: Hash,
) -> Transaction {
let instructions = to_keypair
.iter()
.map(|keypair| {
system_instruction::create_account(
&from_keypair.pubkey(),
&keypair.pubkey(),
lamports,
400,
&solana_sdk::move_loader::id(),
)
})
.collect();
let mut from_signers = vec![from_keypair];
from_signers.extend_from_slice(to_keypair);
Transaction::new_signed_instructions(&from_signers, instructions, recent_blockhash)
}
pub fn create_account(
from_keypair: &Keypair,
to_keypair: &Keypair,
lamports: u64,
recent_blockhash: Hash,
) -> Transaction {
create_accounts(from_keypair, &[to_keypair], lamports, recent_blockhash)
}
#[derive(Debug)]
enum LibrapayError {
UnknownAccountState,
}
impl fmt::Display for LibrapayError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl error::Error for LibrapayError {}
pub fn get_libra_balance<T: Client>(
client: &T,
pubkey: &Pubkey,
) -> Result<u64, Box<dyn error::Error>> {
if let Some(account) =
client.get_account_with_commitment(&pubkey, CommitmentConfig::recent())?
{
let mut data_store = DataStore::default();
match bincode::deserialize(&account.data)? {
LibraAccountState::User(_, write_set) => {
data_store.apply_write_set(&write_set);
}
LibraAccountState::Unallocated => |
state => {
info!("Unknown account state: {:?}", state);
return Err(LibrapayError::UnknownAccountState.into());
}
}
let resource = data_store
.read_account_resource(&pubkey_to_address(pubkey))
.unwrap();
let res = resource.balance();
Ok(res)
} else {
Ok(0)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{create_genesis, upload_mint_script, upload_payment_script};
use solana_runtime::bank::Bank;
use solana_runtime::bank_client::BankClient;
use solana_sdk::genesis_config::create_genesis_config;
use solana_sdk::signature::{Keypair, Signer};
use std::sync::Arc;
fn create_bank(lamports: u64) -> (Arc<Bank>, Keypair, Keypair, Pubkey, Pubkey) {
let (mut genesis_config, mint) = create_genesis_config(lamports);
genesis_config.rent.lamports_per_byte_year = 0;
let bank = Bank::new(&genesis_config);
bank.register_native_instruction_processor(
"solana_move_loader_program",
&solana_sdk::move_loader::id(),
);
let shared_bank = Arc::new(bank);
let bank_client = BankClient::new_shared(&shared_bank);
let genesis_pubkey = create_genesis(&mint, &bank_client, 1_000_000);
let mint_script_pubkey = upload_mint_script(&mint, &bank_client);
let script_pubkey = upload_payment_script(&mint, &bank_client);
(
shared_bank,
mint,
genesis_pubkey,
mint_script_pubkey,
script_pubkey,
)
}
#[test]
fn test_transfer() {
solana_logger::setup();
let (bank, mint, genesis_keypair, mint_script_pubkey, payment_script_pubkey) =
create_bank(10_000);
let from_keypair = Keypair::new();
let to_keypair = Keypair::new();
let tx = create_accounts(
&mint,
&[&from_keypair, &to_keypair],
1,
bank.last_blockhash(),
);
bank.process_transaction(&tx).unwrap();
info!(
"created accounts: mint: {} genesis_pubkey: {}",
mint.pubkey(),
genesis_keypair.pubkey()
);
info!(
" from: {} to: {}",
from_keypair.pubkey(),
to_keypair.pubkey()
);
let tx = mint_tokens(
&mint_script_pubkey,
&mint,
&genesis_keypair,
&from_keypair.pubkey(),
1,
bank.last_blockhash(),
);
bank.process_transaction(&tx).unwrap();
let client = BankClient::new_shared(&bank);
assert_eq!(
1,
get_libra_balance(&client, &from_keypair.pubkey()).unwrap()
);
info!("passed mint... doing another transfer..");
let tx = transfer(
&payment_script_pubkey,
&genesis_keypair.pubkey(),
&mint,
&from_keypair,
&to_keypair.pubkey(),
1,
bank.last_blockhash(),
);
bank.process_transaction(&tx).unwrap();
assert_eq!(1, get_libra_balance(&client, &to_keypair.pubkey()).unwrap());
}
}
| {
return Ok(0);
} |
network_scraper.go | // Copyright The OpenTelemetry 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 networkscraper // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/networkscraper"
import (
"context"
"fmt"
"time"
"github.com/shirou/gopsutil/v3/host"
"github.com/shirou/gopsutil/v3/net"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/pmetric"
"go.opentelemetry.io/collector/receiver/scrapererror"
"github.com/open-telemetry/opentelemetry-collector-contrib/internal/coreinternal/processor/filterset"
"github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/networkscraper/internal/metadata"
)
const (
networkMetricsLen = 4
connectionsMetricsLen = 1
)
// scraper for Network Metrics
type scraper struct {
settings component.ReceiverCreateSettings
config *Config
mb *metadata.MetricsBuilder
startTime pcommon.Timestamp
includeFS filterset.FilterSet
excludeFS filterset.FilterSet
// for mocking
bootTime func() (uint64, error)
ioCounters func(bool) ([]net.IOCountersStat, error)
connections func(string) ([]net.ConnectionStat, error)
}
// newNetworkScraper creates a set of Network related metrics
func newNetworkScraper(_ context.Context, settings component.ReceiverCreateSettings, cfg *Config) (*scraper, error) {
scraper := &scraper{settings: settings, config: cfg, bootTime: host.BootTime, ioCounters: net.IOCounters, connections: net.Connections}
var err error
if len(cfg.Include.Interfaces) > 0 {
scraper.includeFS, err = filterset.CreateFilterSet(cfg.Include.Interfaces, &cfg.Include.Config)
if err != nil {
return nil, fmt.Errorf("error creating network interface include filters: %w", err)
}
}
if len(cfg.Exclude.Interfaces) > 0 {
scraper.excludeFS, err = filterset.CreateFilterSet(cfg.Exclude.Interfaces, &cfg.Exclude.Config)
if err != nil {
return nil, fmt.Errorf("error creating network interface exclude filters: %w", err)
}
}
return scraper, nil
}
func (s *scraper) start(context.Context, component.Host) error {
bootTime, err := s.bootTime()
if err != nil {
return err
}
s.startTime = pcommon.Timestamp(bootTime * 1e9)
s.mb = metadata.NewMetricsBuilder(s.config.Metrics, s.settings.BuildInfo, metadata.WithStartTime(pcommon.Timestamp(bootTime*1e9)))
return nil
}
func (s *scraper) scrape(_ context.Context) (pmetric.Metrics, error) {
var errors scrapererror.ScrapeErrors
err := s.recordNetworkCounterMetrics()
if err != nil {
errors.AddPartial(networkMetricsLen, err)
}
err = s.recordNetworkConnectionsMetrics()
if err != nil {
errors.AddPartial(connectionsMetricsLen, err)
}
return s.mb.Emit(), errors.Combine()
}
func (s *scraper) recordNetworkCounterMetrics() error {
now := pcommon.NewTimestampFromTime(time.Now())
// get total stats only
ioCounters, err := s.ioCounters( /*perNetworkInterfaceController=*/ true)
if err != nil {
return fmt.Errorf("failed to read network IO stats: %w", err)
}
// filter network interfaces by name
ioCounters = s.filterByInterface(ioCounters)
if len(ioCounters) > 0 {
s.recordNetworkPacketsMetric(now, ioCounters)
s.recordNetworkDroppedPacketsMetric(now, ioCounters)
s.recordNetworkErrorPacketsMetric(now, ioCounters)
s.recordNetworkIOMetric(now, ioCounters)
}
return nil
}
func (s *scraper) recordNetworkPacketsMetric(now pcommon.Timestamp, ioCountersSlice []net.IOCountersStat) {
for _, ioCounters := range ioCountersSlice {
s.mb.RecordSystemNetworkPacketsDataPoint(now, int64(ioCounters.PacketsSent), ioCounters.Name, metadata.AttributeDirectionTransmit)
s.mb.RecordSystemNetworkPacketsDataPoint(now, int64(ioCounters.PacketsRecv), ioCounters.Name, metadata.AttributeDirectionReceive)
}
}
func (s *scraper) recordNetworkDroppedPacketsMetric(now pcommon.Timestamp, ioCountersSlice []net.IOCountersStat) {
for _, ioCounters := range ioCountersSlice {
s.mb.RecordSystemNetworkDroppedDataPoint(now, int64(ioCounters.Dropout), ioCounters.Name, metadata.AttributeDirectionTransmit)
s.mb.RecordSystemNetworkDroppedDataPoint(now, int64(ioCounters.Dropin), ioCounters.Name, metadata.AttributeDirectionReceive)
}
}
func (s *scraper) recordNetworkErrorPacketsMetric(now pcommon.Timestamp, ioCountersSlice []net.IOCountersStat) {
for _, ioCounters := range ioCountersSlice {
s.mb.RecordSystemNetworkErrorsDataPoint(now, int64(ioCounters.Errout), ioCounters.Name, metadata.AttributeDirectionTransmit)
s.mb.RecordSystemNetworkErrorsDataPoint(now, int64(ioCounters.Errin), ioCounters.Name, metadata.AttributeDirectionReceive)
}
}
func (s *scraper) recordNetworkIOMetric(now pcommon.Timestamp, ioCountersSlice []net.IOCountersStat) {
for _, ioCounters := range ioCountersSlice {
s.mb.RecordSystemNetworkIoDataPoint(now, int64(ioCounters.BytesSent), ioCounters.Name, metadata.AttributeDirectionTransmit)
s.mb.RecordSystemNetworkIoDataPoint(now, int64(ioCounters.BytesRecv), ioCounters.Name, metadata.AttributeDirectionReceive)
}
}
func (s *scraper) recordNetworkConnectionsMetrics() error {
now := pcommon.NewTimestampFromTime(time.Now())
connections, err := s.connections("tcp")
if err != nil {
return fmt.Errorf("failed to read TCP connections: %w", err)
}
tcpConnectionStatusCounts := getTCPConnectionStatusCounts(connections)
s.recordNetworkConnectionsMetric(now, tcpConnectionStatusCounts)
return nil
}
func getTCPConnectionStatusCounts(connections []net.ConnectionStat) map[string]int64 {
tcpStatuses := make(map[string]int64, len(allTCPStates))
for _, state := range allTCPStates {
tcpStatuses[state] = 0
}
for _, connection := range connections {
tcpStatuses[connection.Status]++
}
return tcpStatuses
}
func (s *scraper) recordNetworkConnectionsMetric(now pcommon.Timestamp, connectionStateCounts map[string]int64) {
for connectionState, count := range connectionStateCounts {
s.mb.RecordSystemNetworkConnectionsDataPoint(now, count, metadata.AttributeProtocolTcp, connectionState)
}
}
func (s *scraper) filterByInterface(ioCounters []net.IOCountersStat) []net.IOCountersStat {
if s.includeFS == nil && s.excludeFS == nil {
return ioCounters
}
filteredIOCounters := make([]net.IOCountersStat, 0, len(ioCounters))
for _, io := range ioCounters {
if s.includeInterface(io.Name) |
}
return filteredIOCounters
}
func (s *scraper) includeInterface(interfaceName string) bool {
return (s.includeFS == nil || s.includeFS.Matches(interfaceName)) &&
(s.excludeFS == nil || !s.excludeFS.Matches(interfaceName))
}
| {
filteredIOCounters = append(filteredIOCounters, io)
} |
jobs-gen.go | // Copyright 2021 Google LLC.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Code generated file. DO NOT EDIT.
// Package jobs provides access to the Cloud Talent Solution API.
//
// For product documentation, see: https://cloud.google.com/talent-solution/job-search/docs/
//
// Creating a client
//
// Usage example:
//
// import "google.golang.org/api/jobs/v3"
// ...
// ctx := context.Background()
// jobsService, err := jobs.NewService(ctx)
//
// In this example, Google Application Default Credentials are used for authentication.
//
// For information on how to create and obtain Application Default Credentials, see https://developers.google.com/identity/protocols/application-default-credentials.
//
// Other authentication options
//
// By default, all available scopes (see "Constants") are used to authenticate. To restrict scopes, use option.WithScopes:
//
// jobsService, err := jobs.NewService(ctx, option.WithScopes(jobs.JobsScope))
//
// To use an API key for authentication (note: some APIs do not support API keys), use option.WithAPIKey:
//
// jobsService, err := jobs.NewService(ctx, option.WithAPIKey("AIza..."))
//
// To use an OAuth token (e.g., a user token obtained via a three-legged OAuth flow), use option.WithTokenSource:
//
// config := &oauth2.Config{...}
// // ...
// token, err := config.Exchange(ctx, ...)
// jobsService, err := jobs.NewService(ctx, option.WithTokenSource(config.TokenSource(ctx, token)))
//
// See https://godoc.org/google.golang.org/api/option/ for details on options.
package jobs // import "google.golang.org/api/jobs/v3"
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
googleapi "google.golang.org/api/googleapi"
gensupport "google.golang.org/api/internal/gensupport"
option "google.golang.org/api/option"
internaloption "google.golang.org/api/option/internaloption"
htransport "google.golang.org/api/transport/http"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = gensupport.MarshalJSON
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
var _ = context.Canceled
var _ = internaloption.WithDefaultEndpoint
const apiId = "jobs:v3"
const apiName = "jobs"
const apiVersion = "v3"
const basePath = "https://jobs.googleapis.com/"
const mtlsBasePath = "https://jobs.mtls.googleapis.com/"
// OAuth2 scopes used by this API.
const (
// See, edit, configure, and delete your Google Cloud data and see the
// email address for your Google Account.
CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform"
// Manage job postings
JobsScope = "https://www.googleapis.com/auth/jobs"
)
// NewService creates a new Service.
func NewService(ctx context.Context, opts ...option.ClientOption) (*Service, error) {
scopesOption := option.WithScopes(
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/jobs",
)
// NOTE: prepend, so we don't override user-specified scopes.
opts = append([]option.ClientOption{scopesOption}, opts...)
opts = append(opts, internaloption.WithDefaultEndpoint(basePath))
opts = append(opts, internaloption.WithDefaultMTLSEndpoint(mtlsBasePath))
client, endpoint, err := htransport.NewClient(ctx, opts...)
if err != nil {
return nil, err
}
s, err := New(client)
if err != nil {
return nil, err
}
if endpoint != "" {
s.BasePath = endpoint
}
return s, nil
}
// New creates a new Service. It uses the provided http.Client for requests.
//
// Deprecated: please use NewService instead.
// To provide a custom HTTP client, use option.WithHTTPClient.
// If you are using google.golang.org/api/googleapis/transport.APIKey, use option.WithAPIKey with NewService instead.
func | (client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client, BasePath: basePath}
s.Projects = NewProjectsService(s)
return s, nil
}
type Service struct {
client *http.Client
BasePath string // API endpoint base URL
UserAgent string // optional additional User-Agent fragment
Projects *ProjectsService
}
func (s *Service) userAgent() string {
if s.UserAgent == "" {
return googleapi.UserAgent
}
return googleapi.UserAgent + " " + s.UserAgent
}
func NewProjectsService(s *Service) *ProjectsService {
rs := &ProjectsService{s: s}
rs.ClientEvents = NewProjectsClientEventsService(s)
rs.Companies = NewProjectsCompaniesService(s)
rs.Jobs = NewProjectsJobsService(s)
return rs
}
type ProjectsService struct {
s *Service
ClientEvents *ProjectsClientEventsService
Companies *ProjectsCompaniesService
Jobs *ProjectsJobsService
}
func NewProjectsClientEventsService(s *Service) *ProjectsClientEventsService {
rs := &ProjectsClientEventsService{s: s}
return rs
}
type ProjectsClientEventsService struct {
s *Service
}
func NewProjectsCompaniesService(s *Service) *ProjectsCompaniesService {
rs := &ProjectsCompaniesService{s: s}
return rs
}
type ProjectsCompaniesService struct {
s *Service
}
func NewProjectsJobsService(s *Service) *ProjectsJobsService {
rs := &ProjectsJobsService{s: s}
return rs
}
type ProjectsJobsService struct {
s *Service
}
// ApplicationInfo: Application related details of a job posting.
type ApplicationInfo struct {
// Emails: Optional but at least one of uris, emails or instruction must
// be specified. Use this field to specify email address(es) to which
// resumes or applications can be sent. The maximum number of allowed
// characters for each entry is 255.
Emails []string `json:"emails,omitempty"`
// Instruction: Optional but at least one of uris, emails or instruction
// must be specified. Use this field to provide instructions, such as
// "Mail your application to ...", that a candidate can follow to apply
// for the job. This field accepts and sanitizes HTML input, and also
// accepts bold, italic, ordered list, and unordered list markup tags.
// The maximum number of allowed characters is 3,000.
Instruction string `json:"instruction,omitempty"`
// Uris: Optional but at least one of uris, emails or instruction must
// be specified. Use this URI field to direct an applicant to a website,
// for example to link to an online application form. The maximum number
// of allowed characters for each entry is 2,000.
Uris []string `json:"uris,omitempty"`
// ForceSendFields is a list of field names (e.g. "Emails") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Emails") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ApplicationInfo) MarshalJSON() ([]byte, error) {
type NoMethod ApplicationInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BatchDeleteJobsRequest: Input only. Batch delete jobs request.
type BatchDeleteJobsRequest struct {
// Filter: Required. The filter string specifies the jobs to be deleted.
// Supported operator: =, AND The fields eligible for filtering are: *
// `companyName` (Required) * `requisitionId` (Required) Sample Query:
// companyName = "projects/api-test-project/companies/123" AND
// requisitionId = "req-1"
Filter string `json:"filter,omitempty"`
// ForceSendFields is a list of field names (e.g. "Filter") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Filter") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BatchDeleteJobsRequest) MarshalJSON() ([]byte, error) {
type NoMethod BatchDeleteJobsRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketRange: Represents starting and ending value of a range in
// double.
type BucketRange struct {
// From: Starting value of the bucket range.
From float64 `json:"from,omitempty"`
// To: Ending value of the bucket range.
To float64 `json:"to,omitempty"`
// ForceSendFields is a list of field names (e.g. "From") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "From") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketRange) MarshalJSON() ([]byte, error) {
type NoMethod BucketRange
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *BucketRange) UnmarshalJSON(data []byte) error {
type NoMethod BucketRange
var s1 struct {
From gensupport.JSONFloat64 `json:"from"`
To gensupport.JSONFloat64 `json:"to"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.From = float64(s1.From)
s.To = float64(s1.To)
return nil
}
// BucketizedCount: Represents count of jobs within one bucket.
type BucketizedCount struct {
// Count: Number of jobs whose numeric field value fall into `range`.
Count int64 `json:"count,omitempty"`
// Range: Bucket range on which histogram was performed for the numeric
// field, that is, the count represents number of jobs in this range.
Range *BucketRange `json:"range,omitempty"`
// ForceSendFields is a list of field names (e.g. "Count") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Count") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketizedCount) MarshalJSON() ([]byte, error) {
type NoMethod BucketizedCount
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ClientEvent: An event issued when an end user interacts with the
// application that implements Cloud Talent Solution. Providing this
// information improves the quality of search and recommendation for the
// API clients, enabling the service to perform optimally. The number of
// events sent must be consistent with other calls, such as job
// searches, issued to the service by the client.
type ClientEvent struct {
// CreateTime: Required. The timestamp of the event.
CreateTime string `json:"createTime,omitempty"`
// EventId: Required. A unique identifier, generated by the client
// application. This `event_id` is used to establish the relationship
// between different events (see parent_event_id).
EventId string `json:"eventId,omitempty"`
// ExtraInfo: Optional. Extra information about this event. Used for
// storing information with no matching field in event payload, for
// example, user application specific context or details. At most 20
// keys are supported. The maximum total size of all keys and values is
// 2 KB.
ExtraInfo map[string]string `json:"extraInfo,omitempty"`
// JobEvent: A event issued when a job seeker interacts with the
// application that implements Cloud Talent Solution.
JobEvent *JobEvent `json:"jobEvent,omitempty"`
// ParentEventId: Optional. The event_id of an event that resulted in
// the current event. For example, a Job view event usually follows a
// parent impression event: A job seeker first does a search where a
// list of jobs appears (impression). The job seeker then selects a
// result and views the description of a particular job (Job view).
ParentEventId string `json:"parentEventId,omitempty"`
// RequestId: Required. A unique ID generated in the API responses. It
// can be found in ResponseMetadata.request_id.
RequestId string `json:"requestId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "CreateTime") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CreateTime") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ClientEvent) MarshalJSON() ([]byte, error) {
type NoMethod ClientEvent
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CommuteFilter: Input only. Parameters needed for commute search.
type CommuteFilter struct {
// AllowImpreciseAddresses: Optional. If true, jobs without "precise"
// addresses (street level addresses or GPS coordinates) might also be
// returned. For city and coarser level addresses, text matching is
// used. If this field is set to false or is not specified, only jobs
// that include precise addresses are returned by Commute Search. Note:
// If `allow_imprecise_addresses` is set to true, Commute Search is not
// able to calculate accurate commute times to jobs with city level and
// coarser address information. Jobs with imprecise addresses will
// return a `travel_duration` time of 0 regardless of distance from the
// job seeker.
AllowImpreciseAddresses bool `json:"allowImpreciseAddresses,omitempty"`
// CommuteMethod: Required. The method of transportation for which to
// calculate the commute time.
//
// Possible values:
// "COMMUTE_METHOD_UNSPECIFIED" - Commute method is not specified.
// "DRIVING" - Commute time is calculated based on driving time.
// "TRANSIT" - Commute time is calculated based on public transit
// including bus, metro, subway, etc.
CommuteMethod string `json:"commuteMethod,omitempty"`
// DepartureTime: Optional. The departure time used to calculate traffic
// impact, represented as google.type.TimeOfDay in local time zone.
// Currently traffic model is restricted to hour level resolution.
DepartureTime *TimeOfDay `json:"departureTime,omitempty"`
// RoadTraffic: Optional. Specifies the traffic density to use when
// calculating commute time.
//
// Possible values:
// "ROAD_TRAFFIC_UNSPECIFIED" - Road traffic situation is not
// specified.
// "TRAFFIC_FREE" - Optimal commute time without considering any
// traffic impact.
// "BUSY_HOUR" - Commute time calculation takes in account the peak
// traffic impact.
RoadTraffic string `json:"roadTraffic,omitempty"`
// StartCoordinates: Required. The latitude and longitude of the
// location from which to calculate the commute time.
StartCoordinates *LatLng `json:"startCoordinates,omitempty"`
// TravelDuration: Required. The maximum travel time in seconds. The
// maximum allowed value is `3600s` (one hour). Format is `123s`.
TravelDuration string `json:"travelDuration,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "AllowImpreciseAddresses") to unconditionally include in API
// requests. By default, fields with empty or default values are omitted
// from API requests. However, any non-pointer, non-interface field
// appearing in ForceSendFields will be sent to the server regardless of
// whether the field is empty or not. This may be used to include empty
// fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AllowImpreciseAddresses")
// to include in API requests with the JSON null value. By default,
// fields with empty values are omitted from API requests. However, any
// field with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *CommuteFilter) MarshalJSON() ([]byte, error) {
type NoMethod CommuteFilter
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CommuteInfo: Output only. Commute details related to this job.
type CommuteInfo struct {
// JobLocation: Location used as the destination in the commute
// calculation.
JobLocation *Location `json:"jobLocation,omitempty"`
// TravelDuration: The number of seconds required to travel to the job
// location from the query location. A duration of 0 seconds indicates
// that the job is not reachable within the requested duration, but was
// returned as part of an expanded query.
TravelDuration string `json:"travelDuration,omitempty"`
// ForceSendFields is a list of field names (e.g. "JobLocation") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "JobLocation") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CommuteInfo) MarshalJSON() ([]byte, error) {
type NoMethod CommuteInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Company: A Company resource represents a company in the service. A
// company is the entity that owns job postings, that is, the hiring
// entity responsible for employing applicants for the job position.
type Company struct {
// CareerSiteUri: Optional. The URI to employer's career site or careers
// page on the employer's web site, for example,
// "https://careers.google.com".
CareerSiteUri string `json:"careerSiteUri,omitempty"`
// DerivedInfo: Output only. Derived details about the company.
DerivedInfo *CompanyDerivedInfo `json:"derivedInfo,omitempty"`
// DisplayName: Required. The display name of the company, for example,
// "Google LLC".
DisplayName string `json:"displayName,omitempty"`
// EeoText: Optional. Equal Employment Opportunity legal disclaimer text
// to be associated with all jobs, and typically to be displayed in all
// roles. The maximum number of allowed characters is 500.
EeoText string `json:"eeoText,omitempty"`
// ExternalId: Required. Client side company identifier, used to
// uniquely identify the company. The maximum number of allowed
// characters is 255.
ExternalId string `json:"externalId,omitempty"`
// HeadquartersAddress: Optional. The street address of the company's
// main headquarters, which may be different from the job location. The
// service attempts to geolocate the provided address, and populates a
// more specific location wherever possible in
// DerivedInfo.headquarters_location.
HeadquartersAddress string `json:"headquartersAddress,omitempty"`
// HiringAgency: Optional. Set to true if it is the hiring agency that
// post jobs for other employers. Defaults to false if not provided.
HiringAgency bool `json:"hiringAgency,omitempty"`
// ImageUri: Optional. A URI that hosts the employer's company logo.
ImageUri string `json:"imageUri,omitempty"`
// KeywordSearchableJobCustomAttributes: Optional. A list of keys of
// filterable Job.custom_attributes, whose corresponding `string_values`
// are used in keyword search. Jobs with `string_values` under these
// specified field keys are returned if any of the values matches the
// search keyword. Custom field values with parenthesis, brackets and
// special symbols won't be properly searchable, and those keyword
// queries need to be surrounded by quotes.
KeywordSearchableJobCustomAttributes []string `json:"keywordSearchableJobCustomAttributes,omitempty"`
// Name: Required during company update. The resource name for a
// company. This is generated by the service when a company is created.
// The format is "projects/{project_id}/companies/{company_id}", for
// example, "projects/api-test-project/companies/foo".
Name string `json:"name,omitempty"`
// Size: Optional. The employer's company size.
//
// Possible values:
// "COMPANY_SIZE_UNSPECIFIED" - Default value if the size is not
// specified.
// "MINI" - The company has less than 50 employees.
// "SMALL" - The company has between 50 and 99 employees.
// "SMEDIUM" - The company has between 100 and 499 employees.
// "MEDIUM" - The company has between 500 and 999 employees.
// "BIG" - The company has between 1,000 and 4,999 employees.
// "BIGGER" - The company has between 5,000 and 9,999 employees.
// "GIANT" - The company has 10,000 or more employees.
Size string `json:"size,omitempty"`
// Suspended: Output only. Indicates whether a company is flagged to be
// suspended from public availability by the service when job content
// appears suspicious, abusive, or spammy.
Suspended bool `json:"suspended,omitempty"`
// WebsiteUri: Optional. The URI representing the company's primary web
// site or home page, for example, "https://www.google.com". The maximum
// number of allowed characters is 255.
WebsiteUri string `json:"websiteUri,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "CareerSiteUri") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CareerSiteUri") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Company) MarshalJSON() ([]byte, error) {
type NoMethod Company
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CompanyDerivedInfo: Derived details about the company.
type CompanyDerivedInfo struct {
// HeadquartersLocation: A structured headquarters location of the
// company, resolved from Company.hq_location if provided.
HeadquartersLocation *Location `json:"headquartersLocation,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "HeadquartersLocation") to unconditionally include in API requests.
// By default, fields with empty or default values are omitted from API
// requests. However, any non-pointer, non-interface field appearing in
// ForceSendFields will be sent to the server regardless of whether the
// field is empty or not. This may be used to include empty fields in
// Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "HeadquartersLocation") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *CompanyDerivedInfo) MarshalJSON() ([]byte, error) {
type NoMethod CompanyDerivedInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CompensationEntry: A compensation entry that represents one component
// of compensation, such as base pay, bonus, or other compensation type.
// Annualization: One compensation entry can be annualized if - it
// contains valid amount or range. - and its expected_units_per_year is
// set or can be derived. Its annualized range is determined as (amount
// or range) times expected_units_per_year.
type CompensationEntry struct {
// Amount: Optional. Compensation amount.
Amount *Money `json:"amount,omitempty"`
// Description: Optional. Compensation description. For example, could
// indicate equity terms or provide additional context to an estimated
// bonus.
Description string `json:"description,omitempty"`
// ExpectedUnitsPerYear: Optional. Expected number of units paid each
// year. If not specified, when Job.employment_types is FULLTIME, a
// default value is inferred based on unit. Default values: - HOURLY:
// 2080 - DAILY: 260 - WEEKLY: 52 - MONTHLY: 12 - ANNUAL: 1
ExpectedUnitsPerYear float64 `json:"expectedUnitsPerYear,omitempty"`
// Range: Optional. Compensation range.
Range *CompensationRange `json:"range,omitempty"`
// Type: Optional. Compensation type. Default is
// CompensationUnit.COMPENSATION_TYPE_UNSPECIFIED.
//
// Possible values:
// "COMPENSATION_TYPE_UNSPECIFIED" - Default value.
// "BASE" - Base compensation: Refers to the fixed amount of money
// paid to an employee by an employer in return for work performed. Base
// compensation does not include benefits, bonuses or any other
// potential compensation from an employer.
// "BONUS" - Bonus.
// "SIGNING_BONUS" - Signing bonus.
// "EQUITY" - Equity.
// "PROFIT_SHARING" - Profit sharing.
// "COMMISSIONS" - Commission.
// "TIPS" - Tips.
// "OTHER_COMPENSATION_TYPE" - Other compensation type.
Type string `json:"type,omitempty"`
// Unit: Optional. Frequency of the specified amount. Default is
// CompensationUnit.COMPENSATION_UNIT_UNSPECIFIED.
//
// Possible values:
// "COMPENSATION_UNIT_UNSPECIFIED" - Default value.
// "HOURLY" - Hourly.
// "DAILY" - Daily.
// "WEEKLY" - Weekly
// "MONTHLY" - Monthly.
// "YEARLY" - Yearly.
// "ONE_TIME" - One time.
// "OTHER_COMPENSATION_UNIT" - Other compensation units.
Unit string `json:"unit,omitempty"`
// ForceSendFields is a list of field names (e.g. "Amount") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Amount") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CompensationEntry) MarshalJSON() ([]byte, error) {
type NoMethod CompensationEntry
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *CompensationEntry) UnmarshalJSON(data []byte) error {
type NoMethod CompensationEntry
var s1 struct {
ExpectedUnitsPerYear gensupport.JSONFloat64 `json:"expectedUnitsPerYear"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.ExpectedUnitsPerYear = float64(s1.ExpectedUnitsPerYear)
return nil
}
// CompensationFilter: Input only. Filter on job compensation type and
// amount.
type CompensationFilter struct {
// IncludeJobsWithUnspecifiedCompensationRange: Optional. If set to
// true, jobs with unspecified compensation range fields are included.
IncludeJobsWithUnspecifiedCompensationRange bool `json:"includeJobsWithUnspecifiedCompensationRange,omitempty"`
// Range: Optional. Compensation range.
Range *CompensationRange `json:"range,omitempty"`
// Type: Required. Type of filter.
//
// Possible values:
// "FILTER_TYPE_UNSPECIFIED" - Filter type unspecified. Position
// holder, INVALID, should never be used.
// "UNIT_ONLY" - Filter by `base compensation entry's` unit. A job is
// a match if and only if the job contains a base CompensationEntry and
// the base CompensationEntry's unit matches provided units. Populate
// one or more units. See CompensationInfo.CompensationEntry for
// definition of base compensation entry.
// "UNIT_AND_AMOUNT" - Filter by `base compensation entry's` unit and
// amount / range. A job is a match if and only if the job contains a
// base CompensationEntry, and the base entry's unit matches provided
// compensation_units and amount or range overlaps with provided
// compensation_range. See CompensationInfo.CompensationEntry for
// definition of base compensation entry. Set exactly one units and
// populate range.
// "ANNUALIZED_BASE_AMOUNT" - Filter by annualized base compensation
// amount and `base compensation entry's` unit. Populate range and zero
// or more units.
// "ANNUALIZED_TOTAL_AMOUNT" - Filter by annualized total compensation
// amount and `base compensation entry's` unit . Populate range and zero
// or more units.
Type string `json:"type,omitempty"`
// Units: Required. Specify desired `base compensation entry's`
// CompensationInfo.CompensationUnit.
//
// Possible values:
// "COMPENSATION_UNIT_UNSPECIFIED" - Default value.
// "HOURLY" - Hourly.
// "DAILY" - Daily.
// "WEEKLY" - Weekly
// "MONTHLY" - Monthly.
// "YEARLY" - Yearly.
// "ONE_TIME" - One time.
// "OTHER_COMPENSATION_UNIT" - Other compensation units.
Units []string `json:"units,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "IncludeJobsWithUnspecifiedCompensationRange") to unconditionally
// include in API requests. By default, fields with empty or default
// values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g.
// "IncludeJobsWithUnspecifiedCompensationRange") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CompensationFilter) MarshalJSON() ([]byte, error) {
type NoMethod CompensationFilter
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CompensationHistogramRequest: Input only. Compensation based
// histogram request.
type CompensationHistogramRequest struct {
// BucketingOption: Required. Numeric histogram options, like buckets,
// whether include min or max value.
BucketingOption *NumericBucketingOption `json:"bucketingOption,omitempty"`
// Type: Required. Type of the request, representing which field the
// histogramming should be performed over. A single request can only
// specify one histogram of each `CompensationHistogramRequestType`.
//
// Possible values:
// "COMPENSATION_HISTOGRAM_REQUEST_TYPE_UNSPECIFIED" - Default value.
// Invalid.
// "BASE" - Histogram by job's base compensation. See
// CompensationEntry for definition of base compensation.
// "ANNUALIZED_BASE" - Histogram by job's annualized base
// compensation. See CompensationEntry for definition of annualized base
// compensation.
// "ANNUALIZED_TOTAL" - Histogram by job's annualized total
// compensation. See CompensationEntry for definition of annualized
// total compensation.
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "BucketingOption") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BucketingOption") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *CompensationHistogramRequest) MarshalJSON() ([]byte, error) {
type NoMethod CompensationHistogramRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CompensationHistogramResult: Output only. Compensation based
// histogram result.
type CompensationHistogramResult struct {
// Result: Histogram result.
Result *NumericBucketingResult `json:"result,omitempty"`
// Type: Type of the request, corresponding to
// CompensationHistogramRequest.type.
//
// Possible values:
// "COMPENSATION_HISTOGRAM_REQUEST_TYPE_UNSPECIFIED" - Default value.
// Invalid.
// "BASE" - Histogram by job's base compensation. See
// CompensationEntry for definition of base compensation.
// "ANNUALIZED_BASE" - Histogram by job's annualized base
// compensation. See CompensationEntry for definition of annualized base
// compensation.
// "ANNUALIZED_TOTAL" - Histogram by job's annualized total
// compensation. See CompensationEntry for definition of annualized
// total compensation.
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "Result") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Result") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CompensationHistogramResult) MarshalJSON() ([]byte, error) {
type NoMethod CompensationHistogramResult
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CompensationInfo: Job compensation details.
type CompensationInfo struct {
// AnnualizedBaseCompensationRange: Output only. Annualized base
// compensation range. Computed as base compensation entry's
// CompensationEntry.compensation times
// CompensationEntry.expected_units_per_year. See CompensationEntry for
// explanation on compensation annualization.
AnnualizedBaseCompensationRange *CompensationRange `json:"annualizedBaseCompensationRange,omitempty"`
// AnnualizedTotalCompensationRange: Output only. Annualized total
// compensation range. Computed as all compensation entries'
// CompensationEntry.compensation times
// CompensationEntry.expected_units_per_year. See CompensationEntry for
// explanation on compensation annualization.
AnnualizedTotalCompensationRange *CompensationRange `json:"annualizedTotalCompensationRange,omitempty"`
// Entries: Optional. Job compensation information. At most one entry
// can be of type CompensationInfo.CompensationType.BASE, which is
// referred as ** base compensation entry ** for the job.
Entries []*CompensationEntry `json:"entries,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "AnnualizedBaseCompensationRange") to unconditionally include in API
// requests. By default, fields with empty or default values are omitted
// from API requests. However, any non-pointer, non-interface field
// appearing in ForceSendFields will be sent to the server regardless of
// whether the field is empty or not. This may be used to include empty
// fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g.
// "AnnualizedBaseCompensationRange") to include in API requests with
// the JSON null value. By default, fields with empty values are omitted
// from API requests. However, any field with an empty value appearing
// in NullFields will be sent to the server as null. It is an error if a
// field in this list has a non-empty value. This may be used to include
// null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CompensationInfo) MarshalJSON() ([]byte, error) {
type NoMethod CompensationInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CompensationRange: Compensation range.
type CompensationRange struct {
// MaxCompensation: Optional. The maximum amount of compensation. If
// left empty, the value is set to a maximal compensation value and the
// currency code is set to match the currency code of min_compensation.
MaxCompensation *Money `json:"maxCompensation,omitempty"`
// MinCompensation: Optional. The minimum amount of compensation. If
// left empty, the value is set to zero and the currency code is set to
// match the currency code of max_compensation.
MinCompensation *Money `json:"minCompensation,omitempty"`
// ForceSendFields is a list of field names (e.g. "MaxCompensation") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "MaxCompensation") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *CompensationRange) MarshalJSON() ([]byte, error) {
type NoMethod CompensationRange
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CompleteQueryResponse: Output only. Response of auto-complete query.
type CompleteQueryResponse struct {
// CompletionResults: Results of the matching job/company candidates.
CompletionResults []*CompletionResult `json:"completionResults,omitempty"`
// Metadata: Additional information for the API invocation, such as the
// request tracking id.
Metadata *ResponseMetadata `json:"metadata,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "CompletionResults")
// to unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CompletionResults") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *CompleteQueryResponse) MarshalJSON() ([]byte, error) {
type NoMethod CompleteQueryResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CompletionResult: Output only. Resource that represents completion
// results.
type CompletionResult struct {
// ImageUri: The URI of the company image for
// CompletionType.COMPANY_NAME.
ImageUri string `json:"imageUri,omitempty"`
// Suggestion: The suggestion for the query.
Suggestion string `json:"suggestion,omitempty"`
// Type: The completion topic.
//
// Possible values:
// "COMPLETION_TYPE_UNSPECIFIED" - Default value.
// "JOB_TITLE" - Only suggest job titles.
// "COMPANY_NAME" - Only suggest company names.
// "COMBINED" - Suggest both job titles and company names.
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "ImageUri") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ImageUri") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CompletionResult) MarshalJSON() ([]byte, error) {
type NoMethod CompletionResult
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CreateClientEventRequest: The report event request.
type CreateClientEventRequest struct {
// ClientEvent: Required. Events issued when end user interacts with
// customer's application that uses Cloud Talent Solution.
ClientEvent *ClientEvent `json:"clientEvent,omitempty"`
// ForceSendFields is a list of field names (e.g. "ClientEvent") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ClientEvent") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CreateClientEventRequest) MarshalJSON() ([]byte, error) {
type NoMethod CreateClientEventRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CreateCompanyRequest: Input only. The Request of the CreateCompany
// method.
type CreateCompanyRequest struct {
// Company: Required. The company to be created.
Company *Company `json:"company,omitempty"`
// ForceSendFields is a list of field names (e.g. "Company") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Company") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CreateCompanyRequest) MarshalJSON() ([]byte, error) {
type NoMethod CreateCompanyRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CreateJobRequest: Input only. Create job request.
type CreateJobRequest struct {
// Job: Required. The Job to be created.
Job *Job `json:"job,omitempty"`
// ForceSendFields is a list of field names (e.g. "Job") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Job") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CreateJobRequest) MarshalJSON() ([]byte, error) {
type NoMethod CreateJobRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CustomAttribute: Custom attribute values that are either filterable
// or non-filterable.
type CustomAttribute struct {
// Filterable: Optional. If the `filterable` flag is true, the custom
// field values may be used for custom attribute filters
// JobQuery.custom_attribute_filter. If false, these values may not be
// used for custom attribute filters. Default is false.
Filterable bool `json:"filterable,omitempty"`
// LongValues: Optional but exactly one of string_values or long_values
// must be specified. This field is used to perform number range search.
// (`EQ`, `GT`, `GE`, `LE`, `LT`) over filterable `long_value`.
// Currently at most 1 long_values is supported.
LongValues googleapi.Int64s `json:"longValues,omitempty"`
// StringValues: Optional but exactly one of string_values or
// long_values must be specified. This field is used to perform a string
// match (`CASE_SENSITIVE_MATCH` or `CASE_INSENSITIVE_MATCH`) search.
// For filterable `string_value`s, a maximum total number of 200 values
// is allowed, with each `string_value` has a byte size of no more than
// 500B. For unfilterable `string_values`, the maximum total byte size
// of unfilterable `string_values` is 50KB. Empty string is not allowed.
StringValues []string `json:"stringValues,omitempty"`
// ForceSendFields is a list of field names (e.g. "Filterable") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Filterable") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CustomAttribute) MarshalJSON() ([]byte, error) {
type NoMethod CustomAttribute
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CustomAttributeHistogramRequest: Custom attributes histogram request.
// An error is thrown if neither string_value_histogram or
// long_value_histogram_bucketing_option has been defined.
type CustomAttributeHistogramRequest struct {
// Key: Required. Specifies the custom field key to perform a histogram
// on. If specified without `long_value_histogram_bucketing_option`,
// histogram on string values of the given `key` is triggered, otherwise
// histogram is performed on long values.
Key string `json:"key,omitempty"`
// LongValueHistogramBucketingOption: Optional. Specifies buckets used
// to perform a range histogram on Job's filterable long custom field
// values, or min/max value requirements.
LongValueHistogramBucketingOption *NumericBucketingOption `json:"longValueHistogramBucketingOption,omitempty"`
// StringValueHistogram: Optional. If set to true, the response includes
// the histogram value for each key as a string.
StringValueHistogram bool `json:"stringValueHistogram,omitempty"`
// ForceSendFields is a list of field names (e.g. "Key") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Key") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CustomAttributeHistogramRequest) MarshalJSON() ([]byte, error) {
type NoMethod CustomAttributeHistogramRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CustomAttributeHistogramResult: Output only. Custom attribute
// histogram result.
type CustomAttributeHistogramResult struct {
// Key: Stores the key of custom attribute the histogram is performed
// on.
Key string `json:"key,omitempty"`
// LongValueHistogramResult: Stores bucketed histogram counting result
// or min/max values for custom attribute long values associated with
// `key`.
LongValueHistogramResult *NumericBucketingResult `json:"longValueHistogramResult,omitempty"`
// StringValueHistogramResult: Stores a map from the values of string
// custom field associated with `key` to the number of jobs with that
// value in this histogram result.
StringValueHistogramResult map[string]int64 `json:"stringValueHistogramResult,omitempty"`
// ForceSendFields is a list of field names (e.g. "Key") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Key") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CustomAttributeHistogramResult) MarshalJSON() ([]byte, error) {
type NoMethod CustomAttributeHistogramResult
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// DeviceInfo: Device information collected from the job seeker,
// candidate, or other entity conducting the job search. Providing this
// information improves the quality of the search results across
// devices.
type DeviceInfo struct {
// DeviceType: Optional. Type of the device.
//
// Possible values:
// "DEVICE_TYPE_UNSPECIFIED" - The device type isn't specified.
// "WEB" - A desktop web browser, such as, Chrome, Firefox, Safari, or
// Internet Explorer)
// "MOBILE_WEB" - A mobile device web browser, such as a phone or
// tablet with a Chrome browser.
// "ANDROID" - An Android device native application.
// "IOS" - An iOS device native application.
// "BOT" - A bot, as opposed to a device operated by human beings,
// such as a web crawler.
// "OTHER" - Other devices types.
DeviceType string `json:"deviceType,omitempty"`
// Id: Optional. A device-specific ID. The ID must be a unique
// identifier that distinguishes the device from other devices.
Id string `json:"id,omitempty"`
// ForceSendFields is a list of field names (e.g. "DeviceType") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DeviceType") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *DeviceInfo) MarshalJSON() ([]byte, error) {
type NoMethod DeviceInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Empty: A generic empty message that you can re-use to avoid defining
// duplicated empty messages in your APIs. A typical example is to use
// it as the request or the response type of an API method. For
// instance: service Foo { rpc Bar(google.protobuf.Empty) returns
// (google.protobuf.Empty); } The JSON representation for `Empty` is
// empty JSON object `{}`.
type Empty struct {
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
}
// HistogramFacets: Input only. Histogram facets to be specified in
// SearchJobsRequest.
type HistogramFacets struct {
// CompensationHistogramFacets: Optional. Specifies compensation
// field-based histogram requests. Duplicate values of
// CompensationHistogramRequest.type are not allowed.
CompensationHistogramFacets []*CompensationHistogramRequest `json:"compensationHistogramFacets,omitempty"`
// CustomAttributeHistogramFacets: Optional. Specifies the custom
// attributes histogram requests. Duplicate values of
// CustomAttributeHistogramRequest.key are not allowed.
CustomAttributeHistogramFacets []*CustomAttributeHistogramRequest `json:"customAttributeHistogramFacets,omitempty"`
// SimpleHistogramFacets: Optional. Specifies the simple type of
// histogram facets, for example, `COMPANY_SIZE`, `EMPLOYMENT_TYPE` etc.
//
// Possible values:
// "SEARCH_TYPE_UNSPECIFIED" - The default value if search type is not
// specified.
// "COMPANY_ID" - Filter by the company id field.
// "EMPLOYMENT_TYPE" - Filter by the employment type field, such as
// `FULL_TIME` or `PART_TIME`.
// "COMPANY_SIZE" - Filter by the company size type field, such as
// `BIG`, `SMALL` or `BIGGER`.
// "DATE_PUBLISHED" - Filter by the date published field. Possible
// return values are: * PAST_24_HOURS (The past 24 hours) * PAST_3_DAYS
// (The past 3 days) * PAST_WEEK (The past 7 days) * PAST_MONTH (The
// past 30 days) * PAST_YEAR (The past 365 days)
// "EDUCATION_LEVEL" - Filter by the required education level of the
// job.
// "EXPERIENCE_LEVEL" - Filter by the required experience level of the
// job.
// "ADMIN_1" - Filter by Admin1, which is a global placeholder for
// referring to state, province, or the particular term a country uses
// to define the geographic structure below the country level. Examples
// include states codes such as "CA", "IL", "NY", and provinces, such as
// "BC".
// "COUNTRY" - Filter by the country code of job, such as US, JP, FR.
// "CITY" - Filter by the "city name", "Admin1 code", for example,
// "Mountain View, CA" or "New York, NY".
// "LOCALE" - Filter by the locale field of a job, such as "en-US",
// "fr-FR". This is the BCP-47 language code, such as "en-US" or
// "sr-Latn". For more information, see [Tags for Identifying
// Languages](https://tools.ietf.org/html/bcp47).
// "LANGUAGE" - Filter by the language code portion of the locale
// field, such as "en" or "fr".
// "CATEGORY" - Filter by the Category.
// "CITY_COORDINATE" - Filter by the city center GPS coordinate
// (latitude and longitude), for example, 37.4038522,-122.0987765. Since
// the coordinates of a city center can change, clients may need to
// refresh them periodically.
// "ADMIN_1_COUNTRY" - A combination of state or province code with a
// country code. This field differs from `JOB_ADMIN1`, which can be used
// in multiple countries.
// "COMPANY_DISPLAY_NAME" - Company display name.
// "BASE_COMPENSATION_UNIT" - Base compensation unit.
SimpleHistogramFacets []string `json:"simpleHistogramFacets,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "CompensationHistogramFacets") to unconditionally include in API
// requests. By default, fields with empty or default values are omitted
// from API requests. However, any non-pointer, non-interface field
// appearing in ForceSendFields will be sent to the server regardless of
// whether the field is empty or not. This may be used to include empty
// fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g.
// "CompensationHistogramFacets") to include in API requests with the
// JSON null value. By default, fields with empty values are omitted
// from API requests. However, any field with an empty value appearing
// in NullFields will be sent to the server as null. It is an error if a
// field in this list has a non-empty value. This may be used to include
// null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *HistogramFacets) MarshalJSON() ([]byte, error) {
type NoMethod HistogramFacets
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// HistogramResult: Output only. Result of a histogram call. The
// response contains the histogram map for the search type specified by
// HistogramResult.field. The response is a map of each filter value to
// the corresponding count of jobs for that filter.
type HistogramResult struct {
// SearchType: The Histogram search filters.
//
// Possible values:
// "SEARCH_TYPE_UNSPECIFIED" - The default value if search type is not
// specified.
// "COMPANY_ID" - Filter by the company id field.
// "EMPLOYMENT_TYPE" - Filter by the employment type field, such as
// `FULL_TIME` or `PART_TIME`.
// "COMPANY_SIZE" - Filter by the company size type field, such as
// `BIG`, `SMALL` or `BIGGER`.
// "DATE_PUBLISHED" - Filter by the date published field. Possible
// return values are: * PAST_24_HOURS (The past 24 hours) * PAST_3_DAYS
// (The past 3 days) * PAST_WEEK (The past 7 days) * PAST_MONTH (The
// past 30 days) * PAST_YEAR (The past 365 days)
// "EDUCATION_LEVEL" - Filter by the required education level of the
// job.
// "EXPERIENCE_LEVEL" - Filter by the required experience level of the
// job.
// "ADMIN_1" - Filter by Admin1, which is a global placeholder for
// referring to state, province, or the particular term a country uses
// to define the geographic structure below the country level. Examples
// include states codes such as "CA", "IL", "NY", and provinces, such as
// "BC".
// "COUNTRY" - Filter by the country code of job, such as US, JP, FR.
// "CITY" - Filter by the "city name", "Admin1 code", for example,
// "Mountain View, CA" or "New York, NY".
// "LOCALE" - Filter by the locale field of a job, such as "en-US",
// "fr-FR". This is the BCP-47 language code, such as "en-US" or
// "sr-Latn". For more information, see [Tags for Identifying
// Languages](https://tools.ietf.org/html/bcp47).
// "LANGUAGE" - Filter by the language code portion of the locale
// field, such as "en" or "fr".
// "CATEGORY" - Filter by the Category.
// "CITY_COORDINATE" - Filter by the city center GPS coordinate
// (latitude and longitude), for example, 37.4038522,-122.0987765. Since
// the coordinates of a city center can change, clients may need to
// refresh them periodically.
// "ADMIN_1_COUNTRY" - A combination of state or province code with a
// country code. This field differs from `JOB_ADMIN1`, which can be used
// in multiple countries.
// "COMPANY_DISPLAY_NAME" - Company display name.
// "BASE_COMPENSATION_UNIT" - Base compensation unit.
SearchType string `json:"searchType,omitempty"`
// Values: A map from the values of field to the number of jobs with
// that value in this search result. Key: search type (filter names,
// such as the companyName). Values: the count of jobs that match the
// filter for this search.
Values map[string]int64 `json:"values,omitempty"`
// ForceSendFields is a list of field names (e.g. "SearchType") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "SearchType") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *HistogramResult) MarshalJSON() ([]byte, error) {
type NoMethod HistogramResult
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// HistogramResults: Output only. Histogram results that match
// HistogramFacets specified in SearchJobsRequest.
type HistogramResults struct {
// CompensationHistogramResults: Specifies compensation field-based
// histogram results that match
// HistogramFacets.compensation_histogram_requests.
CompensationHistogramResults []*CompensationHistogramResult `json:"compensationHistogramResults,omitempty"`
// CustomAttributeHistogramResults: Specifies histogram results for
// custom attributes that match
// HistogramFacets.custom_attribute_histogram_facets.
CustomAttributeHistogramResults []*CustomAttributeHistogramResult `json:"customAttributeHistogramResults,omitempty"`
// SimpleHistogramResults: Specifies histogram results that matches
// HistogramFacets.simple_histogram_facets.
SimpleHistogramResults []*HistogramResult `json:"simpleHistogramResults,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "CompensationHistogramResults") to unconditionally include in API
// requests. By default, fields with empty or default values are omitted
// from API requests. However, any non-pointer, non-interface field
// appearing in ForceSendFields will be sent to the server regardless of
// whether the field is empty or not. This may be used to include empty
// fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g.
// "CompensationHistogramResults") to include in API requests with the
// JSON null value. By default, fields with empty values are omitted
// from API requests. However, any field with an empty value appearing
// in NullFields will be sent to the server as null. It is an error if a
// field in this list has a non-empty value. This may be used to include
// null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *HistogramResults) MarshalJSON() ([]byte, error) {
type NoMethod HistogramResults
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Job: A Job resource represents a job posting (also referred to as a
// "job listing" or "job requisition"). A job belongs to a Company,
// which is the hiring entity responsible for the job.
type Job struct {
// Addresses: Optional but strongly recommended for the best service
// experience. Location(s) where the employer is looking to hire for
// this job posting. Specifying the full street address(es) of the
// hiring location enables better API results, especially job searches
// by commute time. At most 50 locations are allowed for best search
// performance. If a job has more locations, it is suggested to split it
// into multiple jobs with unique requisition_ids (e.g. 'ReqA' becomes
// 'ReqA-1', 'ReqA-2', etc.) as multiple jobs with the same
// company_name, language_code and requisition_id are not allowed. If
// the original requisition_id must be preserved, a custom field should
// be used for storage. It is also suggested to group the locations that
// close to each other in the same job for better search experience.
// Jobs with multiple addresses must have their addresses with the same
// LocationType to allow location filtering to work properly. (For
// example, a Job with addresses "1600 Amphitheatre Parkway, Mountain
// View, CA, USA" and "London, UK" may not have location filters applied
// correctly at search time since the first is a
// LocationType.STREET_ADDRESS and the second is a
// LocationType.LOCALITY.) If a job needs to have multiple addresses, it
// is suggested to split it into multiple jobs with same LocationTypes.
// The maximum number of allowed characters is 500.
Addresses []string `json:"addresses,omitempty"`
// ApplicationInfo: Required. At least one field within ApplicationInfo
// must be specified. Job application information.
ApplicationInfo *ApplicationInfo `json:"applicationInfo,omitempty"`
// CompanyDisplayName: Output only. Display name of the company listing
// the job.
CompanyDisplayName string `json:"companyDisplayName,omitempty"`
// CompanyName: Required. The resource name of the company listing the
// job, such as "projects/api-test-project/companies/foo".
CompanyName string `json:"companyName,omitempty"`
// CompensationInfo: Optional. Job compensation information.
CompensationInfo *CompensationInfo `json:"compensationInfo,omitempty"`
// CustomAttributes: Optional. A map of fields to hold both filterable
// and non-filterable custom job attributes that are not covered by the
// provided structured fields. The keys of the map are strings up to 64
// bytes and must match the pattern: a-zA-Z*. For example, key0LikeThis
// or KEY_1_LIKE_THIS. At most 100 filterable and at most 100
// unfilterable keys are supported. For filterable `string_values`,
// across all keys at most 200 values are allowed, with each string no
// more than 255 characters. For unfilterable `string_values`, the
// maximum total size of `string_values` across all keys is 50KB.
CustomAttributes map[string]CustomAttribute `json:"customAttributes,omitempty"`
// DegreeTypes: Optional. The desired education degrees for the job,
// such as Bachelors, Masters.
//
// Possible values:
// "DEGREE_TYPE_UNSPECIFIED" - Default value. Represents no degree, or
// early childhood education. Maps to ISCED code 0. Ex) Kindergarten
// "PRIMARY_EDUCATION" - Primary education which is typically the
// first stage of compulsory education. ISCED code 1. Ex) Elementary
// school
// "LOWER_SECONDARY_EDUCATION" - Lower secondary education; First
// stage of secondary education building on primary education, typically
// with a more subject-oriented curriculum. ISCED code 2. Ex) Middle
// school
// "UPPER_SECONDARY_EDUCATION" - Middle education; Second/final stage
// of secondary education preparing for tertiary education and/or
// providing skills relevant to employment. Usually with an increased
// range of subject options and streams. ISCED code 3. Ex) High school
// "ADULT_REMEDIAL_EDUCATION" - Adult Remedial Education; Programmes
// providing learning experiences that build on secondary education and
// prepare for labour market entry and/or tertiary education. The
// content is broader than secondary but not as complex as tertiary
// education. ISCED code 4.
// "ASSOCIATES_OR_EQUIVALENT" - Associate's or equivalent; Short first
// tertiary programmes that are typically practically-based,
// occupationally-specific and prepare for labour market entry. These
// programmes may also provide a pathway to other tertiary programmes.
// ISCED code 5.
// "BACHELORS_OR_EQUIVALENT" - Bachelor's or equivalent; Programmes
// designed to provide intermediate academic and/or professional
// knowledge, skills and competencies leading to a first tertiary degree
// or equivalent qualification. ISCED code 6.
// "MASTERS_OR_EQUIVALENT" - Master's or equivalent; Programmes
// designed to provide advanced academic and/or professional knowledge,
// skills and competencies leading to a second tertiary degree or
// equivalent qualification. ISCED code 7.
// "DOCTORAL_OR_EQUIVALENT" - Doctoral or equivalent; Programmes
// designed primarily to lead to an advanced research qualification,
// usually concluding with the submission and defense of a substantive
// dissertation of publishable quality based on original research. ISCED
// code 8.
DegreeTypes []string `json:"degreeTypes,omitempty"`
// Department: Optional. The department or functional area within the
// company with the open position. The maximum number of allowed
// characters is 255.
Department string `json:"department,omitempty"`
// DerivedInfo: Output only. Derived details about the job posting.
DerivedInfo *JobDerivedInfo `json:"derivedInfo,omitempty"`
// Description: Required. The description of the job, which typically
// includes a multi-paragraph description of the company and related
// information. Separate fields are provided on the job object for
// responsibilities, qualifications, and other job characteristics. Use
// of these separate job fields is recommended. This field accepts and
// sanitizes HTML input, and also accepts bold, italic, ordered list,
// and unordered list markup tags. The maximum number of allowed
// characters is 100,000.
Description string `json:"description,omitempty"`
// EmploymentTypes: Optional. The employment type(s) of a job, for
// example, full time or part time.
//
// Possible values:
// "EMPLOYMENT_TYPE_UNSPECIFIED" - The default value if the employment
// type is not specified.
// "FULL_TIME" - The job requires working a number of hours that
// constitute full time employment, typically 40 or more hours per week.
// "PART_TIME" - The job entails working fewer hours than a full time
// job, typically less than 40 hours a week.
// "CONTRACTOR" - The job is offered as a contracted, as opposed to a
// salaried employee, position.
// "CONTRACT_TO_HIRE" - The job is offered as a contracted position
// with the understanding that it's converted into a full-time position
// at the end of the contract. Jobs of this type are also returned by a
// search for EmploymentType.CONTRACTOR jobs.
// "TEMPORARY" - The job is offered as a temporary employment
// opportunity, usually a short-term engagement.
// "INTERN" - The job is a fixed-term opportunity for students or
// entry-level job seekers to obtain on-the-job training, typically
// offered as a summer position.
// "VOLUNTEER" - The is an opportunity for an individual to volunteer,
// where there's no expectation of compensation for the provided
// services.
// "PER_DIEM" - The job requires an employee to work on an as-needed
// basis with a flexible schedule.
// "FLY_IN_FLY_OUT" - The job involves employing people in remote
// areas and flying them temporarily to the work site instead of
// relocating employees and their families permanently.
// "OTHER_EMPLOYMENT_TYPE" - The job does not fit any of the other
// listed types.
EmploymentTypes []string `json:"employmentTypes,omitempty"`
// Incentives: Optional. A description of bonus, commission, and other
// compensation incentives associated with the job not including salary
// or pay. The maximum number of allowed characters is 10,000.
Incentives string `json:"incentives,omitempty"`
// JobBenefits: Optional. The benefits included with the job.
//
// Possible values:
// "JOB_BENEFIT_UNSPECIFIED" - Default value if the type is not
// specified.
// "CHILD_CARE" - The job includes access to programs that support
// child care, such as daycare.
// "DENTAL" - The job includes dental services covered by a dental
// insurance plan.
// "DOMESTIC_PARTNER" - The job offers specific benefits to domestic
// partners.
// "FLEXIBLE_HOURS" - The job allows for a flexible work schedule.
// "MEDICAL" - The job includes health services covered by a medical
// insurance plan.
// "LIFE_INSURANCE" - The job includes a life insurance plan provided
// by the employer or available for purchase by the employee.
// "PARENTAL_LEAVE" - The job allows for a leave of absence to a
// parent to care for a newborn child.
// "RETIREMENT_PLAN" - The job includes a workplace retirement plan
// provided by the employer or available for purchase by the employee.
// "SICK_DAYS" - The job allows for paid time off due to illness.
// "VACATION" - The job includes paid time off for vacation.
// "VISION" - The job includes vision services covered by a vision
// insurance plan.
JobBenefits []string `json:"jobBenefits,omitempty"`
// JobEndTime: Optional. The end timestamp of the job. Typically this
// field is used for contracting engagements. Invalid timestamps are
// ignored.
JobEndTime string `json:"jobEndTime,omitempty"`
// JobLevel: Optional. The experience level associated with the job,
// such as "Entry Level".
//
// Possible values:
// "JOB_LEVEL_UNSPECIFIED" - The default value if the level is not
// specified.
// "ENTRY_LEVEL" - Entry-level individual contributors, typically with
// less than 2 years of experience in a similar role. Includes interns.
// "EXPERIENCED" - Experienced individual contributors, typically with
// 2+ years of experience in a similar role.
// "MANAGER" - Entry- to mid-level managers responsible for managing a
// team of people.
// "DIRECTOR" - Senior-level managers responsible for managing teams
// of managers.
// "EXECUTIVE" - Executive-level managers and above, including C-level
// positions.
JobLevel string `json:"jobLevel,omitempty"`
// JobStartTime: Optional. The start timestamp of the job in UTC time
// zone. Typically this field is used for contracting engagements.
// Invalid timestamps are ignored.
JobStartTime string `json:"jobStartTime,omitempty"`
// LanguageCode: Optional. The language of the posting. This field is
// distinct from any requirements for fluency that are associated with
// the job. Language codes must be in BCP-47 format, such as "en-US" or
// "sr-Latn". For more information, see Tags for Identifying Languages
// (https://tools.ietf.org/html/bcp47){: class="external"
// target="_blank" }. If this field is unspecified and Job.description
// is present, detected language code based on Job.description is
// assigned, otherwise defaults to 'en_US'.
LanguageCode string `json:"languageCode,omitempty"`
// Name: Required during job update. The resource name for the job. This
// is generated by the service when a job is created. The format is
// "projects/{project_id}/jobs/{job_id}", for example,
// "projects/api-test-project/jobs/1234". Use of this field in job
// queries and API calls is preferred over the use of requisition_id
// since this value is unique.
Name string `json:"name,omitempty"`
// PostingCreateTime: Output only. The timestamp when this job posting
// was created.
PostingCreateTime string `json:"postingCreateTime,omitempty"`
// PostingExpireTime: Optional but strongly recommended for the best
// service experience. The expiration timestamp of the job. After this
// timestamp, the job is marked as expired, and it no longer appears in
// search results. The expired job can't be deleted or listed by the
// DeleteJob and ListJobs APIs, but it can be retrieved with the GetJob
// API or updated with the UpdateJob API. An expired job can be updated
// and opened again by using a future expiration timestamp. Updating an
// expired job fails if there is another existing open job with same
// company_name, language_code and requisition_id. The expired jobs are
// retained in our system for 90 days. However, the overall expired job
// count cannot exceed 3 times the maximum of open jobs count over the
// past week, otherwise jobs with earlier expire time are cleaned first.
// Expired jobs are no longer accessible after they are cleaned out.
// Invalid timestamps are ignored, and treated as expire time not
// provided. Timestamp before the instant request is made is considered
// valid, the job will be treated as expired immediately. If this value
// is not provided at the time of job creation or is invalid, the job
// posting expires after 30 days from the job's creation time. For
// example, if the job was created on 2017/01/01 13:00AM UTC with an
// unspecified expiration date, the job expires after 2017/01/31 13:00AM
// UTC. If this value is not provided on job update, it depends on the
// field masks set by UpdateJobRequest.update_mask. If the field masks
// include expiry_time, or the masks are empty meaning that every field
// is updated, the job posting expires after 30 days from the job's last
// update time. Otherwise the expiration date isn't updated.
PostingExpireTime string `json:"postingExpireTime,omitempty"`
// PostingPublishTime: Optional. The timestamp this job posting was most
// recently published. The default value is the time the request arrives
// at the server. Invalid timestamps are ignored.
PostingPublishTime string `json:"postingPublishTime,omitempty"`
// PostingRegion: Optional. The job PostingRegion (for example, state,
// country) throughout which the job is available. If this field is set,
// a LocationFilter in a search query within the job region finds this
// job posting if an exact location match isn't specified. If this field
// is set to PostingRegion.NATION or PostingRegion.ADMINISTRATIVE_AREA,
// setting job Job.addresses to the same location level as this field is
// strongly recommended.
//
// Possible values:
// "POSTING_REGION_UNSPECIFIED" - If the region is unspecified, the
// job is only returned if it matches the LocationFilter.
// "ADMINISTRATIVE_AREA" - In addition to exact location matching, job
// posting is returned when the LocationFilter in the search query is in
// the same administrative area as the returned job posting. For
// example, if a `ADMINISTRATIVE_AREA` job is posted in "CA, USA", it's
// returned if LocationFilter has "Mountain View". Administrative area
// refers to top-level administrative subdivision of this country. For
// example, US state, IT region, UK constituent nation and JP
// prefecture.
// "NATION" - In addition to exact location matching, job is returned
// when LocationFilter in search query is in the same country as this
// job. For example, if a `NATION_WIDE` job is posted in "USA", it's
// returned if LocationFilter has 'Mountain View'.
// "TELECOMMUTE" - Job allows employees to work remotely
// (telecommute). If locations are provided with this value, the job is
// considered as having a location, but telecommuting is allowed.
PostingRegion string `json:"postingRegion,omitempty"`
// PostingUpdateTime: Output only. The timestamp when this job posting
// was last updated.
PostingUpdateTime string `json:"postingUpdateTime,omitempty"`
// ProcessingOptions: Optional. Options for job processing.
ProcessingOptions *ProcessingOptions `json:"processingOptions,omitempty"`
// PromotionValue: Optional. A promotion value of the job, as determined
// by the client. The value determines the sort order of the jobs
// returned when searching for jobs using the featured jobs search call,
// with higher promotional values being returned first and ties being
// resolved by relevance sort. Only the jobs with a promotionValue >0
// are returned in a FEATURED_JOB_SEARCH. Default value is 0, and
// negative values are treated as 0.
PromotionValue int64 `json:"promotionValue,omitempty"`
// Qualifications: Optional. A description of the qualifications
// required to perform the job. The use of this field is recommended as
// an alternative to using the more general description field. This
// field accepts and sanitizes HTML input, and also accepts bold,
// italic, ordered list, and unordered list markup tags. The maximum
// number of allowed characters is 10,000.
Qualifications string `json:"qualifications,omitempty"`
// RequisitionId: Required. The requisition ID, also referred to as the
// posting ID, assigned by the client to identify a job. This field is
// intended to be used by clients for client identification and tracking
// of postings. A job is not allowed to be created if there is another
// job with the same [company_name], language_code and requisition_id.
// The maximum number of allowed characters is 255.
RequisitionId string `json:"requisitionId,omitempty"`
// Responsibilities: Optional. A description of job responsibilities.
// The use of this field is recommended as an alternative to using the
// more general description field. This field accepts and sanitizes HTML
// input, and also accepts bold, italic, ordered list, and unordered
// list markup tags. The maximum number of allowed characters is 10,000.
Responsibilities string `json:"responsibilities,omitempty"`
// Title: Required. The title of the job, such as "Software Engineer"
// The maximum number of allowed characters is 500.
Title string `json:"title,omitempty"`
// Visibility: Deprecated. The job is only visible to the owner. The
// visibility of the job. Defaults to Visibility.ACCOUNT_ONLY if not
// specified.
//
// Possible values:
// "VISIBILITY_UNSPECIFIED" - Default value.
// "ACCOUNT_ONLY" - The resource is only visible to the GCP account
// who owns it.
// "SHARED_WITH_GOOGLE" - The resource is visible to the owner and may
// be visible to other applications and processes at Google.
// "SHARED_WITH_PUBLIC" - The resource is visible to the owner and may
// be visible to all other API clients.
Visibility string `json:"visibility,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Addresses") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Addresses") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Job) MarshalJSON() ([]byte, error) {
type NoMethod Job
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// JobDerivedInfo: Output only. Derived details about the job posting.
type JobDerivedInfo struct {
// JobCategories: Job categories derived from Job.title and
// Job.description.
//
// Possible values:
// "JOB_CATEGORY_UNSPECIFIED" - The default value if the category
// isn't specified.
// "ACCOUNTING_AND_FINANCE" - An accounting and finance job, such as
// an Accountant.
// "ADMINISTRATIVE_AND_OFFICE" - An administrative and office job,
// such as an Administrative Assistant.
// "ADVERTISING_AND_MARKETING" - An advertising and marketing job,
// such as Marketing Manager.
// "ANIMAL_CARE" - An animal care job, such as Veterinarian.
// "ART_FASHION_AND_DESIGN" - An art, fashion, or design job, such as
// Designer.
// "BUSINESS_OPERATIONS" - A business operations job, such as Business
// Operations Manager.
// "CLEANING_AND_FACILITIES" - A cleaning and facilities job, such as
// Custodial Staff.
// "COMPUTER_AND_IT" - A computer and IT job, such as Systems
// Administrator.
// "CONSTRUCTION" - A construction job, such as General Laborer.
// "CUSTOMER_SERVICE" - A customer service job, such s Cashier.
// "EDUCATION" - An education job, such as School Teacher.
// "ENTERTAINMENT_AND_TRAVEL" - An entertainment and travel job, such
// as Flight Attendant.
// "FARMING_AND_OUTDOORS" - A farming or outdoor job, such as Park
// Ranger.
// "HEALTHCARE" - A healthcare job, such as Registered Nurse.
// "HUMAN_RESOURCES" - A human resources job, such as Human Resources
// Director.
// "INSTALLATION_MAINTENANCE_AND_REPAIR" - An installation,
// maintenance, or repair job, such as Electrician.
// "LEGAL" - A legal job, such as Law Clerk.
// "MANAGEMENT" - A management job, often used in conjunction with
// another category, such as Store Manager.
// "MANUFACTURING_AND_WAREHOUSE" - A manufacturing or warehouse job,
// such as Assembly Technician.
// "MEDIA_COMMUNICATIONS_AND_WRITING" - A media, communications, or
// writing job, such as Media Relations.
// "OIL_GAS_AND_MINING" - An oil, gas or mining job, such as Offshore
// Driller.
// "PERSONAL_CARE_AND_SERVICES" - A personal care and services job,
// such as Hair Stylist.
// "PROTECTIVE_SERVICES" - A protective services job, such as Security
// Guard.
// "REAL_ESTATE" - A real estate job, such as Buyer's Agent.
// "RESTAURANT_AND_HOSPITALITY" - A restaurant and hospitality job,
// such as Restaurant Server.
// "SALES_AND_RETAIL" - A sales and/or retail job, such Sales
// Associate.
// "SCIENCE_AND_ENGINEERING" - A science and engineering job, such as
// Lab Technician.
// "SOCIAL_SERVICES_AND_NON_PROFIT" - A social services or non-profit
// job, such as Case Worker.
// "SPORTS_FITNESS_AND_RECREATION" - A sports, fitness, or recreation
// job, such as Personal Trainer.
// "TRANSPORTATION_AND_LOGISTICS" - A transportation or logistics job,
// such as Truck Driver.
JobCategories []string `json:"jobCategories,omitempty"`
// Locations: Structured locations of the job, resolved from
// Job.addresses. locations are exactly matched to Job.addresses in the
// same order.
Locations []*Location `json:"locations,omitempty"`
// ForceSendFields is a list of field names (e.g. "JobCategories") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "JobCategories") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *JobDerivedInfo) MarshalJSON() ([]byte, error) {
type NoMethod JobDerivedInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// JobEvent: An event issued when a job seeker interacts with the
// application that implements Cloud Talent Solution.
type JobEvent struct {
// Jobs: Required. The job name(s) associated with this event. For
// example, if this is an impression event, this field contains the
// identifiers of all jobs shown to the job seeker. If this was a view
// event, this field contains the identifier of the viewed job.
Jobs []string `json:"jobs,omitempty"`
// Type: Required. The type of the event (see JobEventType).
//
// Possible values:
// "JOB_EVENT_TYPE_UNSPECIFIED" - The event is unspecified by other
// provided values.
// "IMPRESSION" - The job seeker or other entity interacting with the
// service has had a job rendered in their view, such as in a list of
// search results in a compressed or clipped format. This event is
// typically associated with the viewing of a jobs list on a single page
// by a job seeker.
// "VIEW" - The job seeker, or other entity interacting with the
// service, has viewed the details of a job, including the full
// description. This event doesn't apply to the viewing a snippet of a
// job appearing as a part of the job search results. Viewing a snippet
// is associated with an impression).
// "VIEW_REDIRECT" - The job seeker or other entity interacting with
// the service performed an action to view a job and was redirected to a
// different website for job.
// "APPLICATION_START" - The job seeker or other entity interacting
// with the service began the process or demonstrated the intention of
// applying for a job.
// "APPLICATION_FINISH" - The job seeker or other entity interacting
// with the service submitted an application for a job.
// "APPLICATION_QUICK_SUBMISSION" - The job seeker or other entity
// interacting with the service submitted an application for a job with
// a single click without entering information. If a job seeker performs
// this action, send only this event to the service. Do not also send
// JobEventType.APPLICATION_START or JobEventType.APPLICATION_FINISH
// events.
// "APPLICATION_REDIRECT" - The job seeker or other entity interacting
// with the service performed an action to apply to a job and was
// redirected to a different website to complete the application.
// "APPLICATION_START_FROM_SEARCH" - The job seeker or other entity
// interacting with the service began the process or demonstrated the
// intention of applying for a job from the search results page without
// viewing the details of the job posting. If sending this event,
// JobEventType.VIEW event shouldn't be sent.
// "APPLICATION_REDIRECT_FROM_SEARCH" - The job seeker, or other
// entity interacting with the service, performs an action with a single
// click from the search results page to apply to a job (without viewing
// the details of the job posting), and is redirected to a different
// website to complete the application. If a candidate performs this
// action, send only this event to the service. Do not also send
// JobEventType.APPLICATION_START, JobEventType.APPLICATION_FINISH or
// JobEventType.VIEW events.
// "APPLICATION_COMPANY_SUBMIT" - This event should be used when a
// company submits an application on behalf of a job seeker. This event
// is intended for use by staffing agencies attempting to place
// candidates.
// "BOOKMARK" - The job seeker or other entity interacting with the
// service demonstrated an interest in a job by bookmarking or saving
// it.
// "NOTIFICATION" - The job seeker or other entity interacting with
// the service was sent a notification, such as an email alert or device
// notification, containing one or more jobs listings generated by the
// service.
// "HIRED" - The job seeker or other entity interacting with the
// service was employed by the hiring entity (employer). Send this event
// only if the job seeker was hired through an application that was
// initiated by a search conducted through the Cloud Talent Solution
// service.
// "SENT_CV" - A recruiter or staffing agency submitted an application
// on behalf of the candidate after interacting with the service to
// identify a suitable job posting.
// "INTERVIEW_GRANTED" - The entity interacting with the service (for
// example, the job seeker), was granted an initial interview by the
// hiring entity (employer). This event should only be sent if the job
// seeker was granted an interview as part of an application that was
// initiated by a search conducted through / recommendation provided by
// the Cloud Talent Solution service.
// "NOT_INTERESTED" - The job seeker or other entity interacting with
// the service showed no interest in the job.
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "Jobs") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Jobs") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *JobEvent) MarshalJSON() ([]byte, error) {
type NoMethod JobEvent
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// JobQuery: Input only. The query required to perform a search query.
type JobQuery struct {
// CommuteFilter: Optional. Allows filtering jobs by commute time with
// different travel methods (for example, driving or public transit).
// Note: This only works with COMMUTE MODE. When specified,
// [JobQuery.location_filters] is ignored. Currently we don't support
// sorting by commute time.
CommuteFilter *CommuteFilter `json:"commuteFilter,omitempty"`
// CompanyDisplayNames: Optional. This filter specifies the exact
// company display name of the jobs to search against. If a value isn't
// specified, jobs within the search results are associated with any
// company. If multiple values are specified, jobs within the search
// results may be associated with any of the specified companies. At
// most 20 company display name filters are allowed.
CompanyDisplayNames []string `json:"companyDisplayNames,omitempty"`
// CompanyNames: Optional. This filter specifies the company entities to
// search against. If a value isn't specified, jobs are searched for
// against all companies. If multiple values are specified, jobs are
// searched against the companies specified. The format is
// "projects/{project_id}/companies/{company_id}", for example,
// "projects/api-test-project/companies/foo". At most 20 company filters
// are allowed.
CompanyNames []string `json:"companyNames,omitempty"`
// CompensationFilter: Optional. This search filter is applied only to
// Job.compensation_info. For example, if the filter is specified as
// "Hourly job with per-hour compensation > $15", only jobs meeting
// these criteria are searched. If a filter isn't defined, all open jobs
// are searched.
CompensationFilter *CompensationFilter `json:"compensationFilter,omitempty"`
// CustomAttributeFilter: Optional. This filter specifies a structured
// syntax to match against the Job.custom_attributes marked as
// `filterable`. The syntax for this expression is a subset of SQL
// syntax. Supported operators are: `=`, `!=`, `<`, `<=`, `>`, and `>=`
// where the left of the operator is a custom field key and the right of
// the operator is a number or a quoted string. You must escape
// backslash (\\) and quote (\") characters. Supported functions are
// `LOWER([field_name])` to perform a case insensitive match and
// `EMPTY([field_name])` to filter on the existence of a key. Boolean
// expressions (AND/OR/NOT) are supported up to 3 levels of nesting (for
// example, "((A AND B AND C) OR NOT D) AND E"), a maximum of 100
// comparisons or functions are allowed in the expression. The
// expression must be < 10000 bytes in length. Sample Query:
// `(LOWER(driving_license)="class \"a\"" OR EMPTY(driving_license)) AND
// driving_years > 10`
CustomAttributeFilter string `json:"customAttributeFilter,omitempty"`
// DisableSpellCheck: Optional. This flag controls the spell-check
// feature. If false, the service attempts to correct a misspelled
// query, for example, "enginee" is corrected to "engineer". Defaults to
// false: a spell check is performed.
DisableSpellCheck bool `json:"disableSpellCheck,omitempty"`
// EmploymentTypes: Optional. The employment type filter specifies the
// employment type of jobs to search against, such as
// EmploymentType.FULL_TIME. If a value is not specified, jobs in the
// search results includes any employment type. If multiple values are
// specified, jobs in the search results include any of the specified
// employment types.
//
// Possible values:
// "EMPLOYMENT_TYPE_UNSPECIFIED" - The default value if the employment
// type is not specified.
// "FULL_TIME" - The job requires working a number of hours that
// constitute full time employment, typically 40 or more hours per week.
// "PART_TIME" - The job entails working fewer hours than a full time
// job, typically less than 40 hours a week.
// "CONTRACTOR" - The job is offered as a contracted, as opposed to a
// salaried employee, position.
// "CONTRACT_TO_HIRE" - The job is offered as a contracted position
// with the understanding that it's converted into a full-time position
// at the end of the contract. Jobs of this type are also returned by a
// search for EmploymentType.CONTRACTOR jobs.
// "TEMPORARY" - The job is offered as a temporary employment
// opportunity, usually a short-term engagement.
// "INTERN" - The job is a fixed-term opportunity for students or
// entry-level job seekers to obtain on-the-job training, typically
// offered as a summer position.
// "VOLUNTEER" - The is an opportunity for an individual to volunteer,
// where there's no expectation of compensation for the provided
// services.
// "PER_DIEM" - The job requires an employee to work on an as-needed
// basis with a flexible schedule.
// "FLY_IN_FLY_OUT" - The job involves employing people in remote
// areas and flying them temporarily to the work site instead of
// relocating employees and their families permanently.
// "OTHER_EMPLOYMENT_TYPE" - The job does not fit any of the other
// listed types.
EmploymentTypes []string `json:"employmentTypes,omitempty"`
// JobCategories: Optional. The category filter specifies the categories
// of jobs to search against. See Category for more information. If a
// value is not specified, jobs from any category are searched against.
// If multiple values are specified, jobs from any of the specified
// categories are searched against.
//
// Possible values:
// "JOB_CATEGORY_UNSPECIFIED" - The default value if the category
// isn't specified.
// "ACCOUNTING_AND_FINANCE" - An accounting and finance job, such as
// an Accountant.
// "ADMINISTRATIVE_AND_OFFICE" - An administrative and office job,
// such as an Administrative Assistant.
// "ADVERTISING_AND_MARKETING" - An advertising and marketing job,
// such as Marketing Manager.
// "ANIMAL_CARE" - An animal care job, such as Veterinarian.
// "ART_FASHION_AND_DESIGN" - An art, fashion, or design job, such as
// Designer.
// "BUSINESS_OPERATIONS" - A business operations job, such as Business
// Operations Manager.
// "CLEANING_AND_FACILITIES" - A cleaning and facilities job, such as
// Custodial Staff.
// "COMPUTER_AND_IT" - A computer and IT job, such as Systems
// Administrator.
// "CONSTRUCTION" - A construction job, such as General Laborer.
// "CUSTOMER_SERVICE" - A customer service job, such s Cashier.
// "EDUCATION" - An education job, such as School Teacher.
// "ENTERTAINMENT_AND_TRAVEL" - An entertainment and travel job, such
// as Flight Attendant.
// "FARMING_AND_OUTDOORS" - A farming or outdoor job, such as Park
// Ranger.
// "HEALTHCARE" - A healthcare job, such as Registered Nurse.
// "HUMAN_RESOURCES" - A human resources job, such as Human Resources
// Director.
// "INSTALLATION_MAINTENANCE_AND_REPAIR" - An installation,
// maintenance, or repair job, such as Electrician.
// "LEGAL" - A legal job, such as Law Clerk.
// "MANAGEMENT" - A management job, often used in conjunction with
// another category, such as Store Manager.
// "MANUFACTURING_AND_WAREHOUSE" - A manufacturing or warehouse job,
// such as Assembly Technician.
// "MEDIA_COMMUNICATIONS_AND_WRITING" - A media, communications, or
// writing job, such as Media Relations.
// "OIL_GAS_AND_MINING" - An oil, gas or mining job, such as Offshore
// Driller.
// "PERSONAL_CARE_AND_SERVICES" - A personal care and services job,
// such as Hair Stylist.
// "PROTECTIVE_SERVICES" - A protective services job, such as Security
// Guard.
// "REAL_ESTATE" - A real estate job, such as Buyer's Agent.
// "RESTAURANT_AND_HOSPITALITY" - A restaurant and hospitality job,
// such as Restaurant Server.
// "SALES_AND_RETAIL" - A sales and/or retail job, such Sales
// Associate.
// "SCIENCE_AND_ENGINEERING" - A science and engineering job, such as
// Lab Technician.
// "SOCIAL_SERVICES_AND_NON_PROFIT" - A social services or non-profit
// job, such as Case Worker.
// "SPORTS_FITNESS_AND_RECREATION" - A sports, fitness, or recreation
// job, such as Personal Trainer.
// "TRANSPORTATION_AND_LOGISTICS" - A transportation or logistics job,
// such as Truck Driver.
JobCategories []string `json:"jobCategories,omitempty"`
// LanguageCodes: Optional. This filter specifies the locale of jobs to
// search against, for example, "en-US". If a value isn't specified, the
// search results can contain jobs in any locale. Language codes should
// be in BCP-47 format, such as "en-US" or "sr-Latn". For more
// information, see Tags for Identifying Languages
// (https://tools.ietf.org/html/bcp47). At most 10 language code filters
// are allowed.
LanguageCodes []string `json:"languageCodes,omitempty"`
// LocationFilters: Optional. The location filter specifies geo-regions
// containing the jobs to search against. See LocationFilter for more
// information. If a location value isn't specified, jobs fitting the
// other search criteria are retrieved regardless of where they're
// located. If multiple values are specified, jobs are retrieved from
// any of the specified locations. If different values are specified for
// the LocationFilter.distance_in_miles parameter, the maximum provided
// distance is used for all locations. At most 5 location filters are
// allowed.
LocationFilters []*LocationFilter `json:"locationFilters,omitempty"`
// PublishTimeRange: Optional. Jobs published within a range specified
// by this filter are searched against.
PublishTimeRange *TimestampRange `json:"publishTimeRange,omitempty"`
// Query: Optional. The query string that matches against the job title,
// description, and location fields. The maximum number of allowed
// characters is 255.
Query string `json:"query,omitempty"`
// QueryLanguageCode: The language code of query. For example, "en-US".
// This field helps to better interpret the query. If a value isn't
// specified, the query language code is automatically detected, which
// may not be accurate. Language code should be in BCP-47 format, such
// as "en-US" or "sr-Latn". For more information, see Tags for
// Identifying Languages (https://tools.ietf.org/html/bcp47).
QueryLanguageCode string `json:"queryLanguageCode,omitempty"`
// ForceSendFields is a list of field names (e.g. "CommuteFilter") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CommuteFilter") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *JobQuery) MarshalJSON() ([]byte, error) {
type NoMethod JobQuery
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// LatLng: An object that represents a latitude/longitude pair. This is
// expressed as a pair of doubles to represent degrees latitude and
// degrees longitude. Unless specified otherwise, this object must
// conform to the WGS84 standard. Values must be within normalized
// ranges.
type LatLng struct {
// Latitude: The latitude in degrees. It must be in the range [-90.0,
// +90.0].
Latitude float64 `json:"latitude,omitempty"`
// Longitude: The longitude in degrees. It must be in the range [-180.0,
// +180.0].
Longitude float64 `json:"longitude,omitempty"`
// ForceSendFields is a list of field names (e.g. "Latitude") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Latitude") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LatLng) MarshalJSON() ([]byte, error) {
type NoMethod LatLng
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *LatLng) UnmarshalJSON(data []byte) error {
type NoMethod LatLng
var s1 struct {
Latitude gensupport.JSONFloat64 `json:"latitude"`
Longitude gensupport.JSONFloat64 `json:"longitude"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Latitude = float64(s1.Latitude)
s.Longitude = float64(s1.Longitude)
return nil
}
// ListCompaniesResponse: Output only. The List companies response
// object.
type ListCompaniesResponse struct {
// Companies: Companies for the current client.
Companies []*Company `json:"companies,omitempty"`
// Metadata: Additional information for the API invocation, such as the
// request tracking id.
Metadata *ResponseMetadata `json:"metadata,omitempty"`
// NextPageToken: A token to retrieve the next page of results.
NextPageToken string `json:"nextPageToken,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Companies") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Companies") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ListCompaniesResponse) MarshalJSON() ([]byte, error) {
type NoMethod ListCompaniesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ListJobsResponse: Output only. List jobs response.
type ListJobsResponse struct {
// Jobs: The Jobs for a given company. The maximum number of items
// returned is based on the limit field provided in the request.
Jobs []*Job `json:"jobs,omitempty"`
// Metadata: Additional information for the API invocation, such as the
// request tracking id.
Metadata *ResponseMetadata `json:"metadata,omitempty"`
// NextPageToken: A token to retrieve the next page of results.
NextPageToken string `json:"nextPageToken,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Jobs") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Jobs") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ListJobsResponse) MarshalJSON() ([]byte, error) {
type NoMethod ListJobsResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Location: Output only. A resource that represents a location with
// full geographic information.
type Location struct {
// LatLng: An object representing a latitude/longitude pair.
LatLng *LatLng `json:"latLng,omitempty"`
// LocationType: The type of a location, which corresponds to the
// address lines field of PostalAddress. For example, "Downtown,
// Atlanta, GA, USA" has a type of LocationType#NEIGHBORHOOD, and
// "Kansas City, KS, USA" has a type of LocationType#LOCALITY.
//
// Possible values:
// "LOCATION_TYPE_UNSPECIFIED" - Default value if the type is not
// specified.
// "COUNTRY" - A country level location.
// "ADMINISTRATIVE_AREA" - A state or equivalent level location.
// "SUB_ADMINISTRATIVE_AREA" - A county or equivalent level location.
// "LOCALITY" - A city or equivalent level location.
// "POSTAL_CODE" - A postal code level location.
// "SUB_LOCALITY" - A sublocality is a subdivision of a locality, for
// example a city borough, ward, or arrondissement. Sublocalities are
// usually recognized by a local political authority. For example,
// Manhattan and Brooklyn are recognized as boroughs by the City of New
// York, and are therefore modeled as sublocalities.
// "SUB_LOCALITY_1" - A district or equivalent level location.
// "SUB_LOCALITY_2" - A smaller district or equivalent level display.
// "NEIGHBORHOOD" - A neighborhood level location.
// "STREET_ADDRESS" - A street address level location.
LocationType string `json:"locationType,omitempty"`
// PostalAddress: Postal address of the location that includes human
// readable information, such as postal delivery and payments addresses.
// Given a postal address, a postal service can deliver items to a
// premises, P.O. Box, or other delivery location.
PostalAddress *PostalAddress `json:"postalAddress,omitempty"`
// RadiusInMiles: Radius in miles of the job location. This value is
// derived from the location bounding box in which a circle with the
// specified radius centered from LatLng covers the area associated with
// the job location. For example, currently, "Mountain View, CA, USA"
// has a radius of 6.17 miles.
RadiusInMiles float64 `json:"radiusInMiles,omitempty"`
// ForceSendFields is a list of field names (e.g. "LatLng") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "LatLng") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Location) MarshalJSON() ([]byte, error) {
type NoMethod Location
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *Location) UnmarshalJSON(data []byte) error {
type NoMethod Location
var s1 struct {
RadiusInMiles gensupport.JSONFloat64 `json:"radiusInMiles"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.RadiusInMiles = float64(s1.RadiusInMiles)
return nil
}
// LocationFilter: Input only. Geographic region of the search.
type LocationFilter struct {
// Address: Optional. The address name, such as "Mountain View" or "Bay
// Area".
Address string `json:"address,omitempty"`
// DistanceInMiles: Optional. The distance_in_miles is applied when the
// location being searched for is identified as a city or smaller. When
// the location being searched for is a state or larger, this field is
// ignored.
DistanceInMiles float64 `json:"distanceInMiles,omitempty"`
// LatLng: Optional. The latitude and longitude of the geographic center
// from which to search. This field's ignored if `address` is provided.
LatLng *LatLng `json:"latLng,omitempty"`
// RegionCode: Optional. CLDR region code of the country/region. This
// field may be used in two ways: 1) If telecommute preference is not
// set, this field is used address ambiguity of the user-input address.
// For example, "Liverpool" may refer to "Liverpool, NY, US" or
// "Liverpool, UK". This region code biases the address resolution
// toward a specific country or territory. If this field is not set,
// address resolution is biased toward the United States by default. 2)
// If telecommute preference is set to TELECOMMUTE_ALLOWED, the
// telecommute location filter will be limited to the region specified
// in this field. If this field is not set, the telecommute job
// locations will not be limited. See
// https://unicode-org.github.io/cldr-staging/charts/latest/supplemental/territory_information.html
// for details. Example: "CH" for Switzerland.
RegionCode string `json:"regionCode,omitempty"`
// TelecommutePreference: Optional. Allows the client to return jobs
// without a set location, specifically, telecommuting jobs
// (telecommuting is considered by the service as a special location.
// Job.posting_region indicates if a job permits telecommuting. If this
// field is set to TelecommutePreference.TELECOMMUTE_ALLOWED,
// telecommuting jobs are searched, and address and lat_lng are ignored.
// If not set or set to TelecommutePreference.TELECOMMUTE_EXCLUDED,
// telecommute job are not searched. This filter can be used by itself
// to search exclusively for telecommuting jobs, or it can be combined
// with another location filter to search for a combination of job
// locations, such as "Mountain View" or "telecommuting" jobs. However,
// when used in combination with other location filters, telecommuting
// jobs can be treated as less relevant than other jobs in the search
// response.
//
// Possible values:
// "TELECOMMUTE_PREFERENCE_UNSPECIFIED" - Default value if the
// telecommute preference is not specified.
// "TELECOMMUTE_EXCLUDED" - Exclude telecommute jobs.
// "TELECOMMUTE_ALLOWED" - Allow telecommute jobs.
TelecommutePreference string `json:"telecommutePreference,omitempty"`
// ForceSendFields is a list of field names (e.g. "Address") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Address") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LocationFilter) MarshalJSON() ([]byte, error) {
type NoMethod LocationFilter
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *LocationFilter) UnmarshalJSON(data []byte) error {
type NoMethod LocationFilter
var s1 struct {
DistanceInMiles gensupport.JSONFloat64 `json:"distanceInMiles"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.DistanceInMiles = float64(s1.DistanceInMiles)
return nil
}
// MatchingJob: Output only. Job entry with metadata inside
// SearchJobsResponse.
type MatchingJob struct {
// CommuteInfo: Commute information which is generated based on
// specified CommuteFilter.
CommuteInfo *CommuteInfo `json:"commuteInfo,omitempty"`
// Job: Job resource that matches the specified SearchJobsRequest.
Job *Job `json:"job,omitempty"`
// JobSummary: A summary of the job with core information that's
// displayed on the search results listing page.
JobSummary string `json:"jobSummary,omitempty"`
// JobTitleSnippet: Contains snippets of text from the Job.job_title
// field most closely matching a search query's keywords, if available.
// The matching query keywords are enclosed in HTML bold tags.
JobTitleSnippet string `json:"jobTitleSnippet,omitempty"`
// SearchTextSnippet: Contains snippets of text from the Job.description
// and similar fields that most closely match a search query's keywords,
// if available. All HTML tags in the original fields are stripped when
// returned in this field, and matching query keywords are enclosed in
// HTML bold tags.
SearchTextSnippet string `json:"searchTextSnippet,omitempty"`
// ForceSendFields is a list of field names (e.g. "CommuteInfo") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CommuteInfo") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *MatchingJob) MarshalJSON() ([]byte, error) {
type NoMethod MatchingJob
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// MendelDebugInput: Message representing input to a Mendel server for
// debug forcing. See go/mendel-debug-forcing for more details. Next ID:
// 2
type MendelDebugInput struct {
// NamespacedDebugInput: When a request spans multiple servers, a
// MendelDebugInput may travel with the request and take effect in all
// the servers. This field is a map of namespaces to
// NamespacedMendelDebugInput protos. In a single server, up to two
// NamespacedMendelDebugInput protos are applied: 1.
// NamespacedMendelDebugInput with the global namespace (key == ""). 2.
// NamespacedMendelDebugInput with the server's namespace. When both
// NamespacedMendelDebugInput protos are present, they are merged. See
// go/mendel-debug-forcing for more details.
NamespacedDebugInput map[string]NamespacedDebugInput `json:"namespacedDebugInput,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "NamespacedDebugInput") to unconditionally include in API requests.
// By default, fields with empty or default values are omitted from API
// requests. However, any non-pointer, non-interface field appearing in
// ForceSendFields will be sent to the server regardless of whether the
// field is empty or not. This may be used to include empty fields in
// Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NamespacedDebugInput") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *MendelDebugInput) MarshalJSON() ([]byte, error) {
type NoMethod MendelDebugInput
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Money: Represents an amount of money with its currency type.
type Money struct {
// CurrencyCode: The three-letter currency code defined in ISO 4217.
CurrencyCode string `json:"currencyCode,omitempty"`
// Nanos: Number of nano (10^-9) units of the amount. The value must be
// between -999,999,999 and +999,999,999 inclusive. If `units` is
// positive, `nanos` must be positive or zero. If `units` is zero,
// `nanos` can be positive, zero, or negative. If `units` is negative,
// `nanos` must be negative or zero. For example $-1.75 is represented
// as `units`=-1 and `nanos`=-750,000,000.
Nanos int64 `json:"nanos,omitempty"`
// Units: The whole units of the amount. For example if `currencyCode`
// is "USD", then 1 unit is one US dollar.
Units int64 `json:"units,omitempty,string"`
// ForceSendFields is a list of field names (e.g. "CurrencyCode") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CurrencyCode") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Money) MarshalJSON() ([]byte, error) {
type NoMethod Money
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// NamespacedDebugInput: Next ID: 15
type NamespacedDebugInput struct {
// AbsolutelyForcedExpNames: Set of experiment names to be absolutely
// forced. These experiments will be forced without evaluating the
// conditions.
AbsolutelyForcedExpNames []string `json:"absolutelyForcedExpNames,omitempty"`
// AbsolutelyForcedExpTags: Set of experiment tags to be absolutely
// forced. The experiments with these tags will be forced without
// evaluating the conditions.
AbsolutelyForcedExpTags []string `json:"absolutelyForcedExpTags,omitempty"`
// AbsolutelyForcedExps: Set of experiment ids to be absolutely forced.
// These ids will be forced without evaluating the conditions.
AbsolutelyForcedExps []int64 `json:"absolutelyForcedExps,omitempty"`
// ConditionallyForcedExpNames: Set of experiment names to be
// conditionally forced. These experiments will be forced only if their
// conditions and their parent domain's conditions are true.
ConditionallyForcedExpNames []string `json:"conditionallyForcedExpNames,omitempty"`
// ConditionallyForcedExpTags: Set of experiment tags to be
// conditionally forced. The experiments with these tags will be forced
// only if their conditions and their parent domain's conditions are
// true.
ConditionallyForcedExpTags []string `json:"conditionallyForcedExpTags,omitempty"`
// ConditionallyForcedExps: Set of experiment ids to be conditionally
// forced. These ids will be forced only if their conditions and their
// parent domain's conditions are true.
ConditionallyForcedExps []int64 `json:"conditionallyForcedExps,omitempty"`
// DisableAutomaticEnrollmentSelection: If true, disable automatic
// enrollment selection (at all diversion points). Automatic enrollment
// selection means experiment selection process based on the
// experiment's automatic enrollment condition. This does not disable
// selection of forced experiments.
DisableAutomaticEnrollmentSelection bool `json:"disableAutomaticEnrollmentSelection,omitempty"`
// DisableExpNames: Set of experiment names to be disabled. If an
// experiment is disabled, it is never selected nor forced. If an
// aggregate experiment is disabled, its partitions are disabled
// together. If an experiment with an enrollment is disabled, the
// enrollment is disabled together. If a name corresponds to a domain,
// the domain itself and all descendant experiments and domains are
// disabled together.
DisableExpNames []string `json:"disableExpNames,omitempty"`
// DisableExpTags: Set of experiment tags to be disabled. All
// experiments that are tagged with one or more of these tags are
// disabled. If an experiment is disabled, it is never selected nor
// forced. If an aggregate experiment is disabled, its partitions are
// disabled together. If an experiment with an enrollment is disabled,
// the enrollment is disabled together.
DisableExpTags []string `json:"disableExpTags,omitempty"`
// DisableExps: Set of experiment ids to be disabled. If an experiment
// is disabled, it is never selected nor forced. If an aggregate
// experiment is disabled, its partitions are disabled together. If an
// experiment with an enrollment is disabled, the enrollment is disabled
// together. If an ID corresponds to a domain, the domain itself and all
// descendant experiments and domains are disabled together.
DisableExps []int64 `json:"disableExps,omitempty"`
// DisableManualEnrollmentSelection: If true, disable manual enrollment
// selection (at all diversion points). Manual enrollment selection
// means experiment selection process based on the request's manual
// enrollment states (a.k.a. opt-in experiments). This does not disable
// selection of forced experiments.
DisableManualEnrollmentSelection bool `json:"disableManualEnrollmentSelection,omitempty"`
// DisableOrganicSelection: If true, disable organic experiment
// selection (at all diversion points). Organic selection means
// experiment selection process based on traffic allocation and
// diversion condition evaluation. This does not disable selection of
// forced experiments. This is useful in cases when it is not known
// whether experiment selection behavior is responsible for a error or
// breakage. Disabling organic selection may help to isolate the cause
// of a given problem.
DisableOrganicSelection bool `json:"disableOrganicSelection,omitempty"`
// ForcedFlags: Flags to force in a particular experiment state. Map
// from flag name to flag value.
ForcedFlags map[string]string `json:"forcedFlags,omitempty"`
// ForcedRollouts: Rollouts to force in a particular experiment state.
// Map from rollout name to rollout value.
ForcedRollouts map[string]bool `json:"forcedRollouts,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "AbsolutelyForcedExpNames") to unconditionally include in API
// requests. By default, fields with empty or default values are omitted
// from API requests. However, any non-pointer, non-interface field
// appearing in ForceSendFields will be sent to the server regardless of
// whether the field is empty or not. This may be used to include empty
// fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AbsolutelyForcedExpNames")
// to include in API requests with the JSON null value. By default,
// fields with empty values are omitted from API requests. However, any
// field with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *NamespacedDebugInput) MarshalJSON() ([]byte, error) {
type NoMethod NamespacedDebugInput
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// NumericBucketingOption: Input only. Use this field to specify
// bucketing option for the histogram search response.
type NumericBucketingOption struct {
// BucketBounds: Required. Two adjacent values form a histogram bucket.
// Values should be in ascending order. For example, if [5, 10, 15] are
// provided, four buckets are created: (-inf, 5), 5, 10), [10, 15), [15,
// inf). At most 20 [buckets_bound is supported.
BucketBounds []float64 `json:"bucketBounds,omitempty"`
// RequiresMinMax: Optional. If set to true, the histogram result
// includes minimum/maximum value of the numeric field.
RequiresMinMax bool `json:"requiresMinMax,omitempty"`
// ForceSendFields is a list of field names (e.g. "BucketBounds") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BucketBounds") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *NumericBucketingOption) MarshalJSON() ([]byte, error) {
type NoMethod NumericBucketingOption
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// NumericBucketingResult: Output only. Custom numeric bucketing result.
type NumericBucketingResult struct {
// Counts: Count within each bucket. Its size is the length of
// NumericBucketingOption.bucket_bounds plus 1.
Counts []*BucketizedCount `json:"counts,omitempty"`
// MaxValue: Stores the maximum value of the numeric field. Is populated
// only if [NumericBucketingOption.requires_min_max] is set to true.
MaxValue float64 `json:"maxValue,omitempty"`
// MinValue: Stores the minimum value of the numeric field. Will be
// populated only if [NumericBucketingOption.requires_min_max] is set to
// true.
MinValue float64 `json:"minValue,omitempty"`
// ForceSendFields is a list of field names (e.g. "Counts") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Counts") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *NumericBucketingResult) MarshalJSON() ([]byte, error) {
type NoMethod NumericBucketingResult
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *NumericBucketingResult) UnmarshalJSON(data []byte) error {
type NoMethod NumericBucketingResult
var s1 struct {
MaxValue gensupport.JSONFloat64 `json:"maxValue"`
MinValue gensupport.JSONFloat64 `json:"minValue"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.MaxValue = float64(s1.MaxValue)
s.MinValue = float64(s1.MinValue)
return nil
}
// PostalAddress: Represents a postal address, e.g. for postal delivery
// or payments addresses. Given a postal address, a postal service can
// deliver items to a premise, P.O. Box or similar. It is not intended
// to model geographical locations (roads, towns, mountains). In typical
// usage an address would be created via user input or from importing
// existing data, depending on the type of process. Advice on address
// input / editing: - Use an i18n-ready address widget such as
// https://github.com/google/libaddressinput) - Users should not be
// presented with UI elements for input or editing of fields outside
// countries where that field is used. For more guidance on how to use
// this schema, please see:
// https://support.google.com/business/answer/6397478
type PostalAddress struct {
// AddressLines: Unstructured address lines describing the lower levels
// of an address. Because values in address_lines do not have type
// information and may sometimes contain multiple values in a single
// field (e.g. "Austin, TX"), it is important that the line order is
// clear. The order of address lines should be "envelope order" for the
// country/region of the address. In places where this can vary (e.g.
// Japan), address_language is used to make it explicit (e.g. "ja" for
// large-to-small ordering and "ja-Latn" or "en" for small-to-large).
// This way, the most specific line of an address can be selected based
// on the language. The minimum permitted structural representation of
// an address consists of a region_code with all remaining information
// placed in the address_lines. It would be possible to format such an
// address very approximately without geocoding, but no semantic
// reasoning could be made about any of the address components until it
// was at least partially resolved. Creating an address only containing
// a region_code and address_lines, and then geocoding is the
// recommended way to handle completely unstructured addresses (as
// opposed to guessing which parts of the address should be localities
// or administrative areas).
AddressLines []string `json:"addressLines,omitempty"`
// AdministrativeArea: Optional. Highest administrative subdivision
// which is used for postal addresses of a country or region. For
// example, this can be a state, a province, an oblast, or a prefecture.
// Specifically, for Spain this is the province and not the autonomous
// community (e.g. "Barcelona" and not "Catalonia"). Many countries
// don't use an administrative area in postal addresses. E.g. in
// Switzerland this should be left unpopulated.
AdministrativeArea string `json:"administrativeArea,omitempty"`
// LanguageCode: Optional. BCP-47 language code of the contents of this
// address (if known). This is often the UI language of the input form
// or is expected to match one of the languages used in the address'
// country/region, or their transliterated equivalents. This can affect
// formatting in certain countries, but is not critical to the
// correctness of the data and will never affect any validation or other
// non-formatting related operations. If this value is not known, it
// should be omitted (rather than specifying a possibly incorrect
// default). Examples: "zh-Hant", "ja", "ja-Latn", "en".
LanguageCode string `json:"languageCode,omitempty"`
// Locality: Optional. Generally refers to the city/town portion of the
// address. Examples: US city, IT comune, UK post town. In regions of
// the world where localities are not well defined or do not fit into
// this structure well, leave locality empty and use address_lines.
Locality string `json:"locality,omitempty"`
// Organization: Optional. The name of the organization at the address.
Organization string `json:"organization,omitempty"`
// PostalCode: Optional. Postal code of the address. Not all countries
// use or require postal codes to be present, but where they are used,
// they may trigger additional validation with other parts of the
// address (e.g. state/zip validation in the U.S.A.).
PostalCode string `json:"postalCode,omitempty"`
// Recipients: Optional. The recipient at the address. This field may,
// under certain circumstances, contain multiline information. For
// example, it might contain "care of" information.
Recipients []string `json:"recipients,omitempty"`
// RegionCode: Required. CLDR region code of the country/region of the
// address. This is never inferred and it is up to the user to ensure
// the value is correct. See http://cldr.unicode.org/ and
// http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html
// for details. Example: "CH" for Switzerland.
RegionCode string `json:"regionCode,omitempty"`
// Revision: The schema revision of the `PostalAddress`. This must be
// set to 0, which is the latest revision. All new revisions **must** be
// backward compatible with old revisions.
Revision int64 `json:"revision,omitempty"`
// SortingCode: Optional. Additional, country-specific, sorting code.
// This is not used in most regions. Where it is used, the value is
// either a string like "CEDEX", optionally followed by a number (e.g.
// "CEDEX 7"), or just a number alone, representing the "sector code"
// (Jamaica), "delivery area indicator" (Malawi) or "post office
// indicator" (e.g. Côte d'Ivoire).
SortingCode string `json:"sortingCode,omitempty"`
// Sublocality: Optional. Sublocality of the address. For example, this
// can be neighborhoods, boroughs, districts.
Sublocality string `json:"sublocality,omitempty"`
// ForceSendFields is a list of field names (e.g. "AddressLines") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AddressLines") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *PostalAddress) MarshalJSON() ([]byte, error) {
type NoMethod PostalAddress
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ProcessingOptions: Input only. Options for job processing.
type ProcessingOptions struct {
// DisableStreetAddressResolution: Optional. If set to `true`, the
// service does not attempt to resolve a more precise address for the
// job.
DisableStreetAddressResolution bool `json:"disableStreetAddressResolution,omitempty"`
// HtmlSanitization: Optional. Option for job HTML content sanitization.
// Applied fields are: * description * applicationInfo.instruction *
// incentives * qualifications * responsibilities HTML tags in these
// fields may be stripped if sanitiazation is not disabled. Defaults to
// HtmlSanitization.SIMPLE_FORMATTING_ONLY.
//
// Possible values:
// "HTML_SANITIZATION_UNSPECIFIED" - Default value.
// "HTML_SANITIZATION_DISABLED" - Disables sanitization on HTML input.
// "SIMPLE_FORMATTING_ONLY" - Sanitizes HTML input, only accepts bold,
// italic, ordered list, and unordered list markup tags.
HtmlSanitization string `json:"htmlSanitization,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "DisableStreetAddressResolution") to unconditionally include in API
// requests. By default, fields with empty or default values are omitted
// from API requests. However, any non-pointer, non-interface field
// appearing in ForceSendFields will be sent to the server regardless of
// whether the field is empty or not. This may be used to include empty
// fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g.
// "DisableStreetAddressResolution") to include in API requests with the
// JSON null value. By default, fields with empty values are omitted
// from API requests. However, any field with an empty value appearing
// in NullFields will be sent to the server as null. It is an error if a
// field in this list has a non-empty value. This may be used to include
// null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ProcessingOptions) MarshalJSON() ([]byte, error) {
type NoMethod ProcessingOptions
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// RequestMetadata: Input only. Meta information related to the job
// searcher or entity conducting the job search. This information is
// used to improve the performance of the service.
type RequestMetadata struct {
// DeviceInfo: Optional. The type of device used by the job seeker at
// the time of the call to the service.
DeviceInfo *DeviceInfo `json:"deviceInfo,omitempty"`
// Domain: Required. The client-defined scope or source of the service
// call, which typically is the domain on which the service has been
// implemented and is currently being run. For example, if the service
// is being run by client *Foo, Inc.*, on job board www.foo.com and
// career site www.bar.com, then this field is set to "foo.com" for use
// on the job board, and "bar.com" for use on the career site. If this
// field isn't available for some reason, send "UNKNOWN". Any
// improvements to the model for a particular tenant site rely on this
// field being set correctly to a domain. The maximum number of allowed
// characters is 255.
Domain string `json:"domain,omitempty"`
// SessionId: Required. A unique session identification string. A
// session is defined as the duration of an end user's interaction with
// the service over a certain period. Obfuscate this field for privacy
// concerns before providing it to the service. If this field is not
// available for some reason, send "UNKNOWN". Note that any improvements
// to the model for a particular tenant site, rely on this field being
// set correctly to some unique session_id. The maximum number of
// allowed characters is 255.
SessionId string `json:"sessionId,omitempty"`
// UserId: Required. A unique user identification string, as determined
// by the client. To have the strongest positive impact on search
// quality make sure the client-level is unique. Obfuscate this field
// for privacy concerns before providing it to the service. If this
// field is not available for some reason, send "UNKNOWN". Note that any
// improvements to the model for a particular tenant site, rely on this
// field being set correctly to a unique user_id. The maximum number of
// allowed characters is 255.
UserId string `json:"userId,omitempty"`
// ForceSendFields is a list of field names (e.g. "DeviceInfo") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DeviceInfo") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *RequestMetadata) MarshalJSON() ([]byte, error) {
type NoMethod RequestMetadata
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ResponseMetadata: Output only. Additional information returned to
// client, such as debugging information.
type ResponseMetadata struct {
// RequestId: A unique id associated with this call. This id is logged
// for tracking purposes.
RequestId string `json:"requestId,omitempty"`
// ForceSendFields is a list of field names (e.g. "RequestId") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "RequestId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ResponseMetadata) MarshalJSON() ([]byte, error) {
type NoMethod ResponseMetadata
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// SearchJobsRequest: Input only. The Request body of the `SearchJobs`
// call.
type SearchJobsRequest struct {
// DisableKeywordMatch: Optional. Controls whether to disable exact
// keyword match on Job.job_title, Job.description,
// Job.company_display_name, Job.locations, Job.qualifications. When
// disable keyword match is turned off, a keyword match returns jobs
// that do not match given category filters when there are matching
// keywords. For example, the query "program manager," a result is
// returned even if the job posting has the title "software developer,"
// which does not fall into "program manager" ontology, but does have
// "program manager" appearing in its description. For queries like
// "cloud" that does not contain title or location specific ontology,
// jobs with "cloud" keyword matches are returned regardless of this
// flag's value. Please use Company.keyword_searchable_custom_fields or
// Company.keyword_searchable_custom_attributes if company specific
// globally matched custom field/attribute string values is needed.
// Enabling keyword match improves recall of subsequent search requests.
// Defaults to false.
DisableKeywordMatch bool `json:"disableKeywordMatch,omitempty"`
// DiversificationLevel: Optional. Controls whether highly similar jobs
// are returned next to each other in the search results. Jobs are
// identified as highly similar based on their titles, job categories,
// and locations. Highly similar results are clustered so that only one
// representative job of the cluster is displayed to the job seeker
// higher up in the results, with the other jobs being displayed lower
// down in the results. Defaults to DiversificationLevel.SIMPLE if no
// value is specified.
//
// Possible values:
// "DIVERSIFICATION_LEVEL_UNSPECIFIED" - The diversification level
// isn't specified. By default, jobs with this enum are ordered
// according to SIMPLE diversifying behavior.
// "DISABLED" - Disables diversification. Jobs that would normally be
// pushed to the last page would not have their positions altered. This
// may result in highly similar jobs appearing in sequence in the search
// results.
// "SIMPLE" - Default diversifying behavior. The result list is
// ordered so that highly similar results are pushed to the end of the
// last page of search results.
DiversificationLevel string `json:"diversificationLevel,omitempty"`
// EnableBroadening: Optional. Controls whether to broaden the search
// when it produces sparse results. Broadened queries append results to
// the end of the matching results list. Defaults to false.
EnableBroadening bool `json:"enableBroadening,omitempty"`
// HistogramFacets: Optional. Histogram requests for jobs matching
// JobQuery.
HistogramFacets *HistogramFacets `json:"histogramFacets,omitempty"`
// JobQuery: Optional. Query used to search against jobs, such as
// keyword, location filters, etc.
JobQuery *JobQuery `json:"jobQuery,omitempty"`
// JobView: Optional. The desired job attributes returned for jobs in
// the search response. Defaults to JobView.SMALL if no value is
// specified.
//
// Possible values:
// "JOB_VIEW_UNSPECIFIED" - Default value.
// "JOB_VIEW_ID_ONLY" - A ID only view of job, with following
// attributes: Job.name, Job.requisition_id, Job.language_code.
// "JOB_VIEW_MINIMAL" - A minimal view of the job, with the following
// attributes: Job.name, Job.requisition_id, Job.title,
// Job.company_name, Job.DerivedInfo.locations, Job.language_code.
// "JOB_VIEW_SMALL" - A small view of the job, with the following
// attributes in the search results: Job.name, Job.requisition_id,
// Job.title, Job.company_name, Job.DerivedInfo.locations,
// Job.visibility, Job.language_code, Job.description.
// "JOB_VIEW_FULL" - All available attributes are included in the
// search results.
JobView string `json:"jobView,omitempty"`
// Offset: Optional. An integer that specifies the current offset (that
// is, starting result location, amongst the jobs deemed by the API as
// relevant) in search results. This field is only considered if
// page_token is unset. The maximum allowed value is 5000. Otherwise an
// error is thrown. For example, 0 means to return results starting from
// the first matching job, and 10 means to return from the 11th job.
// This can be used for pagination, (for example, pageSize = 10 and
// offset = 10 means to return from the second page).
Offset int64 `json:"offset,omitempty"`
// OrderBy: Optional. The criteria determining how search results are
// sorted. Default is "relevance desc". Supported options are: *
// "relevance desc": By relevance descending, as determined by the API
// algorithms. Relevance thresholding of query results is only available
// with this ordering. * "posting_publish_time desc": By
// Job.posting_publish_time descending. * "posting_update_time desc":
// By Job.posting_update_time descending. * "title": By Job.title
// ascending. * "title desc": By Job.title descending. *
// "annualized_base_compensation": By job's
// CompensationInfo.annualized_base_compensation_range ascending. Jobs
// whose annualized base compensation is unspecified are put at the end
// of search results. * "annualized_base_compensation desc": By job's
// CompensationInfo.annualized_base_compensation_range descending. Jobs
// whose annualized base compensation is unspecified are put at the end
// of search results. * "annualized_total_compensation": By job's
// CompensationInfo.annualized_total_compensation_range ascending. Jobs
// whose annualized base compensation is unspecified are put at the end
// of search results. * "annualized_total_compensation desc": By job's
// CompensationInfo.annualized_total_compensation_range descending. Jobs
// whose annualized base compensation is unspecified are put at the end
// of search results.
OrderBy string `json:"orderBy,omitempty"`
// PageSize: Optional. A limit on the number of jobs returned in the
// search results. Increasing this value above the default value of 10
// can increase search response time. The value can be between 1 and
// 100.
PageSize int64 `json:"pageSize,omitempty"`
// PageToken: Optional. The token specifying the current offset within
// search results. See SearchJobsResponse.next_page_token for an
// explanation of how to obtain the next set of query results.
PageToken string `json:"pageToken,omitempty"`
// RequestMetadata: Required. The meta information collected about the
// job searcher, used to improve the search quality of the service. The
// identifiers (such as `user_id`) are provided by users, and must be
// unique and consistent.
RequestMetadata *RequestMetadata `json:"requestMetadata,omitempty"`
// RequirePreciseResultSize: This field is deprecated.
RequirePreciseResultSize bool `json:"requirePreciseResultSize,omitempty"`
// SearchMode: Optional. Mode of a search. Defaults to
// SearchMode.JOB_SEARCH.
//
// Possible values:
// "SEARCH_MODE_UNSPECIFIED" - The mode of the search method isn't
// specified. The default search behavior is identical to JOB_SEARCH
// search behavior.
// "JOB_SEARCH" - The job search matches against all jobs, and
// featured jobs (jobs with promotionValue > 0) are not specially
// handled.
// "FEATURED_JOB_SEARCH" - The job search matches only against
// featured jobs (jobs with a promotionValue > 0). This method doesn't
// return any jobs having a promotionValue <= 0. The search results
// order is determined by the promotionValue (jobs with a higher
// promotionValue are returned higher up in the search results), with
// relevance being used as a tiebreaker.
SearchMode string `json:"searchMode,omitempty"`
// ForceSendFields is a list of field names (e.g. "DisableKeywordMatch")
// to unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DisableKeywordMatch") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *SearchJobsRequest) MarshalJSON() ([]byte, error) {
type NoMethod SearchJobsRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// SearchJobsResponse: Output only. Response for SearchJob method.
type SearchJobsResponse struct {
// BroadenedQueryJobsCount: If query broadening is enabled, we may
// append additional results from the broadened query. This number
// indicates how many of the jobs returned in the jobs field are from
// the broadened query. These results are always at the end of the jobs
// list. In particular, a value of 0, or if the field isn't set, all the
// jobs in the jobs list are from the original (without broadening)
// query. If this field is non-zero, subsequent requests with offset
// after this result set should contain all broadened results.
BroadenedQueryJobsCount int64 `json:"broadenedQueryJobsCount,omitempty"`
// EstimatedTotalSize: An estimation of the number of jobs that match
// the specified query. This number is not guaranteed to be accurate.
// For accurate results, see SearchJobsResponse.total_size.
EstimatedTotalSize int64 `json:"estimatedTotalSize,omitempty"`
// HistogramResults: The histogram results that match specified
// SearchJobsRequest.histogram_facets.
HistogramResults *HistogramResults `json:"histogramResults,omitempty"`
// LocationFilters: The location filters that the service applied to the
// specified query. If any filters are lat-lng based, the
// JobLocation.location_type is
// JobLocation.LocationType#LOCATION_TYPE_UNSPECIFIED.
LocationFilters []*Location `json:"locationFilters,omitempty"`
// MatchingJobs: The Job entities that match the specified
// SearchJobsRequest.
MatchingJobs []*MatchingJob `json:"matchingJobs,omitempty"`
// Metadata: Additional information for the API invocation, such as the
// request tracking id.
Metadata *ResponseMetadata `json:"metadata,omitempty"`
// NextPageToken: The token that specifies the starting position of the
// next page of results. This field is empty if there are no more
// results.
NextPageToken string `json:"nextPageToken,omitempty"`
// SpellCorrection: The spell checking result, and correction.
SpellCorrection *SpellingCorrection `json:"spellCorrection,omitempty"`
// TotalSize: The precise result count with limit 100,000.
TotalSize int64 `json:"totalSize,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g.
// "BroadenedQueryJobsCount") to unconditionally include in API
// requests. By default, fields with empty or default values are omitted
// from API requests. However, any non-pointer, non-interface field
// appearing in ForceSendFields will be sent to the server regardless of
// whether the field is empty or not. This may be used to include empty
// fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BroadenedQueryJobsCount")
// to include in API requests with the JSON null value. By default,
// fields with empty values are omitted from API requests. However, any
// field with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *SearchJobsResponse) MarshalJSON() ([]byte, error) {
type NoMethod SearchJobsResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// SpellingCorrection: Output only. Spell check result.
type SpellingCorrection struct {
// Corrected: Indicates if the query was corrected by the spell checker.
Corrected bool `json:"corrected,omitempty"`
// CorrectedText: Correction output consisting of the corrected keyword
// string.
CorrectedText string `json:"correctedText,omitempty"`
// ForceSendFields is a list of field names (e.g. "Corrected") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Corrected") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *SpellingCorrection) MarshalJSON() ([]byte, error) {
type NoMethod SpellingCorrection
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// TimeOfDay: Represents a time of day. The date and time zone are
// either not significant or are specified elsewhere. An API may choose
// to allow leap seconds. Related types are google.type.Date and
// `google.protobuf.Timestamp`.
type TimeOfDay struct {
// Hours: Hours of day in 24 hour format. Should be from 0 to 23. An API
// may choose to allow the value "24:00:00" for scenarios like business
// closing time.
Hours int64 `json:"hours,omitempty"`
// Minutes: Minutes of hour of day. Must be from 0 to 59.
Minutes int64 `json:"minutes,omitempty"`
// Nanos: Fractions of seconds in nanoseconds. Must be from 0 to
// 999,999,999.
Nanos int64 `json:"nanos,omitempty"`
// Seconds: Seconds of minutes of the time. Must normally be from 0 to
// 59. An API may allow the value 60 if it allows leap-seconds.
Seconds int64 `json:"seconds,omitempty"`
// ForceSendFields is a list of field names (e.g. "Hours") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Hours") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *TimeOfDay) MarshalJSON() ([]byte, error) {
type NoMethod TimeOfDay
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// TimestampRange: Message representing a period of time between two
// timestamps.
type TimestampRange struct {
// EndTime: End of the period.
EndTime string `json:"endTime,omitempty"`
// StartTime: Begin of the period.
StartTime string `json:"startTime,omitempty"`
// ForceSendFields is a list of field names (e.g. "EndTime") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "EndTime") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *TimestampRange) MarshalJSON() ([]byte, error) {
type NoMethod TimestampRange
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// UpdateCompanyRequest: Input only. Request for updating a specified
// company.
type UpdateCompanyRequest struct {
// Company: Required. The company resource to replace the current
// resource in the system.
Company *Company `json:"company,omitempty"`
// UpdateMask: Optional but strongly recommended for the best service
// experience. If update_mask is provided, only the specified fields in
// company are updated. Otherwise all the fields are updated. A field
// mask to specify the company fields to be updated. Only top level
// fields of Company are supported.
UpdateMask string `json:"updateMask,omitempty"`
// ForceSendFields is a list of field names (e.g. "Company") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Company") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *UpdateCompanyRequest) MarshalJSON() ([]byte, error) {
type NoMethod UpdateCompanyRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// UpdateJobRequest: Input only. Update job request.
type UpdateJobRequest struct {
// Job: Required. The Job to be updated.
Job *Job `json:"job,omitempty"`
// UpdateMask: Optional but strongly recommended to be provided for the
// best service experience. If update_mask is provided, only the
// specified fields in job are updated. Otherwise all the fields are
// updated. A field mask to restrict the fields that are updated. Only
// top level fields of Job are supported.
UpdateMask string `json:"updateMask,omitempty"`
// ForceSendFields is a list of field names (e.g. "Job") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Job") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *UpdateJobRequest) MarshalJSON() ([]byte, error) {
type NoMethod UpdateJobRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// method id "jobs.projects.complete":
type ProjectsCompleteCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Complete: Completes the specified prefix with keyword suggestions.
// Intended for use by a job search auto-complete search box.
//
// - name: Resource name of project the completion is performed within.
// The format is "projects/{project_id}", for example,
// "projects/api-test-project".
func (r *ProjectsService) Complete(name string) *ProjectsCompleteCall {
c := &ProjectsCompleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// CompanyName sets the optional parameter "companyName": If provided,
// restricts completion to specified company. The format is
// "projects/{project_id}/companies/{company_id}", for example,
// "projects/api-test-project/companies/foo".
func (c *ProjectsCompleteCall) CompanyName(companyName string) *ProjectsCompleteCall {
c.urlParams_.Set("companyName", companyName)
return c
}
// LanguageCode sets the optional parameter "languageCode": Deprecated.
// Use language_codes instead. The language of the query. This is the
// BCP-47 language code, such as "en-US" or "sr-Latn". For more
// information, see Tags for Identifying Languages
// (https://tools.ietf.org/html/bcp47). For CompletionType.JOB_TITLE
// type, only open jobs with the same language_code are returned. For
// CompletionType.COMPANY_NAME type, only companies having open jobs
// with the same language_code are returned. For CompletionType.COMBINED
// type, only open jobs with the same language_code or companies having
// open jobs with the same language_code are returned. The maximum
// number of allowed characters is 255.
func (c *ProjectsCompleteCall) LanguageCode(languageCode string) *ProjectsCompleteCall {
c.urlParams_.Set("languageCode", languageCode)
return c
}
// LanguageCodes sets the optional parameter "languageCodes": The list
// of languages of the query. This is the BCP-47 language code, such as
// "en-US" or "sr-Latn". For more information, see Tags for Identifying
// Languages (https://tools.ietf.org/html/bcp47). For
// CompletionType.JOB_TITLE type, only open jobs with the same
// language_codes are returned. For CompletionType.COMPANY_NAME type,
// only companies having open jobs with the same language_codes are
// returned. For CompletionType.COMBINED type, only open jobs with the
// same language_codes or companies having open jobs with the same
// language_codes are returned. The maximum number of allowed characters
// is 255.
func (c *ProjectsCompleteCall) LanguageCodes(languageCodes ...string) *ProjectsCompleteCall {
c.urlParams_.SetMulti("languageCodes", append([]string{}, languageCodes...))
return c
}
// PageSize sets the optional parameter "pageSize": Required. Completion
// result count. The maximum allowed page size is 10.
func (c *ProjectsCompleteCall) PageSize(pageSize int64) *ProjectsCompleteCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// Query sets the optional parameter "query": Required. The query used
// to generate suggestions. The maximum number of allowed characters is
// 255.
func (c *ProjectsCompleteCall) Query(query string) *ProjectsCompleteCall {
c.urlParams_.Set("query", query)
return c
}
// Scope sets the optional parameter "scope": The scope of the
// completion. The defaults is CompletionScope.PUBLIC.
//
// Possible values:
// "COMPLETION_SCOPE_UNSPECIFIED" - Default value.
// "TENANT" - Suggestions are based only on the data provided by the
// client.
// "PUBLIC" - Suggestions are based on all jobs data in the system
// that's visible to the client
func (c *ProjectsCompleteCall) Scope(scope string) *ProjectsCompleteCall {
c.urlParams_.Set("scope", scope)
return c
}
// Type sets the optional parameter "type": The completion topic. The
// default is CompletionType.COMBINED.
//
// Possible values:
// "COMPLETION_TYPE_UNSPECIFIED" - Default value.
// "JOB_TITLE" - Only suggest job titles.
// "COMPANY_NAME" - Only suggest company names.
// "COMBINED" - Suggest both job titles and company names.
func (c *ProjectsCompleteCall) Type(type_ string) *ProjectsCompleteCall {
c.urlParams_.Set("type", type_)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsCompleteCall) Fields(s ...googleapi.Field) *ProjectsCompleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsCompleteCall) IfNoneMatch(entityTag string) *ProjectsCompleteCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsCompleteCall) Context(ctx context.Context) *ProjectsCompleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsCompleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsCompleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v3/{+name}:complete")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "jobs.projects.complete" call.
// Exactly one of *CompleteQueryResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *CompleteQueryResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsCompleteCall) Do(opts ...googleapi.CallOption) (*CompleteQueryResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &CompleteQueryResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Completes the specified prefix with keyword suggestions. Intended for use by a job search auto-complete search box.",
// "flatPath": "v3/projects/{projectsId}:complete",
// "httpMethod": "GET",
// "id": "jobs.projects.complete",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "companyName": {
// "description": "Optional. If provided, restricts completion to specified company. The format is \"projects/{project_id}/companies/{company_id}\", for example, \"projects/api-test-project/companies/foo\".",
// "location": "query",
// "type": "string"
// },
// "languageCode": {
// "description": "Deprecated. Use language_codes instead. Optional. The language of the query. This is the BCP-47 language code, such as \"en-US\" or \"sr-Latn\". For more information, see [Tags for Identifying Languages](https://tools.ietf.org/html/bcp47). For CompletionType.JOB_TITLE type, only open jobs with the same language_code are returned. For CompletionType.COMPANY_NAME type, only companies having open jobs with the same language_code are returned. For CompletionType.COMBINED type, only open jobs with the same language_code or companies having open jobs with the same language_code are returned. The maximum number of allowed characters is 255.",
// "location": "query",
// "type": "string"
// },
// "languageCodes": {
// "description": "Optional. The list of languages of the query. This is the BCP-47 language code, such as \"en-US\" or \"sr-Latn\". For more information, see [Tags for Identifying Languages](https://tools.ietf.org/html/bcp47). For CompletionType.JOB_TITLE type, only open jobs with the same language_codes are returned. For CompletionType.COMPANY_NAME type, only companies having open jobs with the same language_codes are returned. For CompletionType.COMBINED type, only open jobs with the same language_codes or companies having open jobs with the same language_codes are returned. The maximum number of allowed characters is 255.",
// "location": "query",
// "repeated": true,
// "type": "string"
// },
// "name": {
// "description": "Required. Resource name of project the completion is performed within. The format is \"projects/{project_id}\", for example, \"projects/api-test-project\".",
// "location": "path",
// "pattern": "^projects/[^/]+$",
// "required": true,
// "type": "string"
// },
// "pageSize": {
// "description": "Required. Completion result count. The maximum allowed page size is 10.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "query": {
// "description": "Required. The query used to generate suggestions. The maximum number of allowed characters is 255.",
// "location": "query",
// "type": "string"
// },
// "scope": {
// "description": "Optional. The scope of the completion. The defaults is CompletionScope.PUBLIC.",
// "enum": [
// "COMPLETION_SCOPE_UNSPECIFIED",
// "TENANT",
// "PUBLIC"
// ],
// "enumDescriptions": [
// "Default value.",
// "Suggestions are based only on the data provided by the client.",
// "Suggestions are based on all jobs data in the system that's visible to the client"
// ],
// "location": "query",
// "type": "string"
// },
// "type": {
// "description": "Optional. The completion topic. The default is CompletionType.COMBINED.",
// "enum": [
// "COMPLETION_TYPE_UNSPECIFIED",
// "JOB_TITLE",
// "COMPANY_NAME",
// "COMBINED"
// ],
// "enumDescriptions": [
// "Default value.",
// "Only suggest job titles.",
// "Only suggest company names.",
// "Suggest both job titles and company names."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "v3/{+name}:complete",
// "response": {
// "$ref": "CompleteQueryResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/jobs"
// ]
// }
}
// method id "jobs.projects.clientEvents.create":
type ProjectsClientEventsCreateCall struct {
s *Service
parent string
createclienteventrequest *CreateClientEventRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: Report events issued when end user interacts with customer's
// application that uses Cloud Talent Solution. You may inspect the
// created events in self service tools
// (https://console.cloud.google.com/talent-solution/overview). Learn
// more (https://cloud.google.com/talent-solution/docs/management-tools)
// about self service tools.
//
// - parent: Parent project name.
func (r *ProjectsClientEventsService) Create(parent string, createclienteventrequest *CreateClientEventRequest) *ProjectsClientEventsCreateCall {
c := &ProjectsClientEventsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.createclienteventrequest = createclienteventrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsClientEventsCreateCall) Fields(s ...googleapi.Field) *ProjectsClientEventsCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsClientEventsCreateCall) Context(ctx context.Context) *ProjectsClientEventsCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsClientEventsCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsClientEventsCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.createclienteventrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v3/{+parent}/clientEvents")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "jobs.projects.clientEvents.create" call.
// Exactly one of *ClientEvent or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *ClientEvent.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsClientEventsCreateCall) Do(opts ...googleapi.CallOption) (*ClientEvent, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ClientEvent{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Report events issued when end user interacts with customer's application that uses Cloud Talent Solution. You may inspect the created events in [self service tools](https://console.cloud.google.com/talent-solution/overview). [Learn more](https://cloud.google.com/talent-solution/docs/management-tools) about self service tools.",
// "flatPath": "v3/projects/{projectsId}/clientEvents",
// "httpMethod": "POST",
// "id": "jobs.projects.clientEvents.create",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Parent project name.",
// "location": "path",
// "pattern": "^projects/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v3/{+parent}/clientEvents",
// "request": {
// "$ref": "CreateClientEventRequest"
// },
// "response": {
// "$ref": "ClientEvent"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/jobs"
// ]
// }
}
// method id "jobs.projects.companies.create":
type ProjectsCompaniesCreateCall struct {
s *Service
parent string
createcompanyrequest *CreateCompanyRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: Creates a new company entity.
//
// - parent: Resource name of the project under which the company is
// created. The format is "projects/{project_id}", for example,
// "projects/api-test-project".
func (r *ProjectsCompaniesService) Create(parent string, createcompanyrequest *CreateCompanyRequest) *ProjectsCompaniesCreateCall {
c := &ProjectsCompaniesCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.createcompanyrequest = createcompanyrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsCompaniesCreateCall) Fields(s ...googleapi.Field) *ProjectsCompaniesCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsCompaniesCreateCall) Context(ctx context.Context) *ProjectsCompaniesCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsCompaniesCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsCompaniesCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.createcompanyrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v3/{+parent}/companies")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "jobs.projects.companies.create" call.
// Exactly one of *Company or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Company.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsCompaniesCreateCall) Do(opts ...googleapi.CallOption) (*Company, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Company{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a new company entity.",
// "flatPath": "v3/projects/{projectsId}/companies",
// "httpMethod": "POST",
// "id": "jobs.projects.companies.create",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Required. Resource name of the project under which the company is created. The format is \"projects/{project_id}\", for example, \"projects/api-test-project\".",
// "location": "path",
// "pattern": "^projects/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v3/{+parent}/companies",
// "request": {
// "$ref": "CreateCompanyRequest"
// },
// "response": {
// "$ref": "Company"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/jobs"
// ]
// }
}
// method id "jobs.projects.companies.delete":
type ProjectsCompaniesDeleteCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes specified company. Prerequisite: The company has no
// jobs associated with it.
//
// - name: The resource name of the company to be deleted. The format is
// "projects/{project_id}/companies/{company_id}", for example,
// "projects/api-test-project/companies/foo".
func (r *ProjectsCompaniesService) Delete(name string) *ProjectsCompaniesDeleteCall {
c := &ProjectsCompaniesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsCompaniesDeleteCall) Fields(s ...googleapi.Field) *ProjectsCompaniesDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsCompaniesDeleteCall) Context(ctx context.Context) *ProjectsCompaniesDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsCompaniesDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsCompaniesDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v3/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "jobs.projects.companies.delete" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsCompaniesDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes specified company. Prerequisite: The company has no jobs associated with it.",
// "flatPath": "v3/projects/{projectsId}/companies/{companiesId}",
// "httpMethod": "DELETE",
// "id": "jobs.projects.companies.delete",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. The resource name of the company to be deleted. The format is \"projects/{project_id}/companies/{company_id}\", for example, \"projects/api-test-project/companies/foo\".",
// "location": "path",
// "pattern": "^projects/[^/]+/companies/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v3/{+name}",
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/jobs"
// ]
// }
}
// method id "jobs.projects.companies.get":
type ProjectsCompaniesGetCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Retrieves specified company.
//
// - name: The resource name of the company to be retrieved. The format
// is "projects/{project_id}/companies/{company_id}", for example,
// "projects/api-test-project/companies/foo".
func (r *ProjectsCompaniesService) Get(name string) *ProjectsCompaniesGetCall {
c := &ProjectsCompaniesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsCompaniesGetCall) Fields(s ...googleapi.Field) *ProjectsCompaniesGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsCompaniesGetCall) IfNoneMatch(entityTag string) *ProjectsCompaniesGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsCompaniesGetCall) Context(ctx context.Context) *ProjectsCompaniesGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsCompaniesGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsCompaniesGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v3/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "jobs.projects.companies.get" call.
// Exactly one of *Company or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Company.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsCompaniesGetCall) Do(opts ...googleapi.CallOption) (*Company, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Company{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves specified company.",
// "flatPath": "v3/projects/{projectsId}/companies/{companiesId}",
// "httpMethod": "GET",
// "id": "jobs.projects.companies.get",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. The resource name of the company to be retrieved. The format is \"projects/{project_id}/companies/{company_id}\", for example, \"projects/api-test-project/companies/foo\".",
// "location": "path",
// "pattern": "^projects/[^/]+/companies/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v3/{+name}",
// "response": {
// "$ref": "Company"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/jobs"
// ]
// }
}
// method id "jobs.projects.companies.list":
type ProjectsCompaniesListCall struct {
s *Service
parent string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists all companies associated with the service account.
//
// - parent: Resource name of the project under which the company is
// created. The format is "projects/{project_id}", for example,
// "projects/api-test-project".
func (r *ProjectsCompaniesService) List(parent string) *ProjectsCompaniesListCall {
c := &ProjectsCompaniesListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
return c
}
// PageSize sets the optional parameter "pageSize": The maximum number
// of companies to be returned, at most 100. Default is 100 if a
// non-positive number is provided.
func (c *ProjectsCompaniesListCall) PageSize(pageSize int64) *ProjectsCompaniesListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": The starting
// indicator from which to return results.
func (c *ProjectsCompaniesListCall) PageToken(pageToken string) *ProjectsCompaniesListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// RequireOpenJobs sets the optional parameter "requireOpenJobs": Set to
// true if the companies requested must have open jobs. Defaults to
// false. If true, at most page_size of companies are fetched, among
// which only those with open jobs are returned.
func (c *ProjectsCompaniesListCall) RequireOpenJobs(requireOpenJobs bool) *ProjectsCompaniesListCall {
c.urlParams_.Set("requireOpenJobs", fmt.Sprint(requireOpenJobs))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsCompaniesListCall) Fields(s ...googleapi.Field) *ProjectsCompaniesListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsCompaniesListCall) IfNoneMatch(entityTag string) *ProjectsCompaniesListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsCompaniesListCall) Context(ctx context.Context) *ProjectsCompaniesListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsCompaniesListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsCompaniesListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v3/{+parent}/companies")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "jobs.projects.companies.list" call.
// Exactly one of *ListCompaniesResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ListCompaniesResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsCompaniesListCall) Do(opts ...googleapi.CallOption) (*ListCompaniesResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ListCompaniesResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists all companies associated with the service account.",
// "flatPath": "v3/projects/{projectsId}/companies",
// "httpMethod": "GET",
// "id": "jobs.projects.companies.list",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "pageSize": {
// "description": "Optional. The maximum number of companies to be returned, at most 100. Default is 100 if a non-positive number is provided.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "Optional. The starting indicator from which to return results.",
// "location": "query",
// "type": "string"
// },
// "parent": {
// "description": "Required. Resource name of the project under which the company is created. The format is \"projects/{project_id}\", for example, \"projects/api-test-project\".",
// "location": "path",
// "pattern": "^projects/[^/]+$",
// "required": true,
// "type": "string"
// },
// "requireOpenJobs": {
// "description": "Optional. Set to true if the companies requested must have open jobs. Defaults to false. If true, at most page_size of companies are fetched, among which only those with open jobs are returned.",
// "location": "query",
// "type": "boolean"
// }
// },
// "path": "v3/{+parent}/companies",
// "response": {
// "$ref": "ListCompaniesResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/jobs"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ProjectsCompaniesListCall) Pages(ctx context.Context, f func(*ListCompaniesResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "jobs.projects.companies.patch":
type ProjectsCompaniesPatchCall struct {
s *Service
name string
updatecompanyrequest *UpdateCompanyRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates specified company. Company names can't be updated. To
// update a company name, delete the company and all jobs associated
// with it, and only then re-create them.
//
// - name: Required during company update. The resource name for a
// company. This is generated by the service when a company is
// created. The format is
// "projects/{project_id}/companies/{company_id}", for example,
// "projects/api-test-project/companies/foo".
func (r *ProjectsCompaniesService) Patch(name string, updatecompanyrequest *UpdateCompanyRequest) *ProjectsCompaniesPatchCall {
c := &ProjectsCompaniesPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
c.updatecompanyrequest = updatecompanyrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsCompaniesPatchCall) Fields(s ...googleapi.Field) *ProjectsCompaniesPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsCompaniesPatchCall) Context(ctx context.Context) *ProjectsCompaniesPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsCompaniesPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsCompaniesPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.updatecompanyrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v3/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PATCH", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "jobs.projects.companies.patch" call.
// Exactly one of *Company or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Company.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsCompaniesPatchCall) Do(opts ...googleapi.CallOption) (*Company, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Company{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates specified company. Company names can't be updated. To update a company name, delete the company and all jobs associated with it, and only then re-create them.",
// "flatPath": "v3/projects/{projectsId}/companies/{companiesId}",
// "httpMethod": "PATCH",
// "id": "jobs.projects.companies.patch",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required during company update. The resource name for a company. This is generated by the service when a company is created. The format is \"projects/{project_id}/companies/{company_id}\", for example, \"projects/api-test-project/companies/foo\".",
// "location": "path",
// "pattern": "^projects/[^/]+/companies/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v3/{+name}",
// "request": {
// "$ref": "UpdateCompanyRequest"
// },
// "response": {
// "$ref": "Company"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/jobs"
// ]
// }
}
// method id "jobs.projects.jobs.batchDelete":
type ProjectsJobsBatchDeleteCall struct {
s *Service
parent string
batchdeletejobsrequest *BatchDeleteJobsRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// BatchDelete: Deletes a list of Jobs by filter.
//
// - parent: The resource name of the project under which the job is
// created. The format is "projects/{project_id}", for example,
// "projects/api-test-project".
func (r *ProjectsJobsService) BatchDelete(parent string, batchdeletejobsrequest *BatchDeleteJobsRequest) *ProjectsJobsBatchDeleteCall {
c := &ProjectsJobsBatchDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.batchdeletejobsrequest = batchdeletejobsrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsJobsBatchDeleteCall) Fields(s ...googleapi.Field) *ProjectsJobsBatchDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsJobsBatchDeleteCall) Context(ctx context.Context) *ProjectsJobsBatchDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsJobsBatchDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsJobsBatchDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.batchdeletejobsrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v3/{+parent}/jobs:batchDelete")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "jobs.projects.jobs.batchDelete" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsJobsBatchDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes a list of Jobs by filter.",
// "flatPath": "v3/projects/{projectsId}/jobs:batchDelete",
// "httpMethod": "POST",
// "id": "jobs.projects.jobs.batchDelete",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Required. The resource name of the project under which the job is created. The format is \"projects/{project_id}\", for example, \"projects/api-test-project\".",
// "location": "path",
// "pattern": "^projects/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v3/{+parent}/jobs:batchDelete",
// "request": {
// "$ref": "BatchDeleteJobsRequest"
// },
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/jobs"
// ]
// }
}
// method id "jobs.projects.jobs.create":
type ProjectsJobsCreateCall struct {
s *Service
parent string
createjobrequest *CreateJobRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: Creates a new job. Typically, the job becomes searchable
// within 10 seconds, but it may take up to 5 minutes.
//
// - parent: The resource name of the project under which the job is
// created. The format is "projects/{project_id}", for example,
// "projects/api-test-project".
func (r *ProjectsJobsService) Create(parent string, createjobrequest *CreateJobRequest) *ProjectsJobsCreateCall {
c := &ProjectsJobsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.createjobrequest = createjobrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsJobsCreateCall) Fields(s ...googleapi.Field) *ProjectsJobsCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsJobsCreateCall) Context(ctx context.Context) *ProjectsJobsCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsJobsCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsJobsCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.createjobrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v3/{+parent}/jobs")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "jobs.projects.jobs.create" call.
// Exactly one of *Job or error will be non-nil. Any non-2xx status code
// is an error. Response headers are in either
// *Job.ServerResponse.Header or (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *ProjectsJobsCreateCall) Do(opts ...googleapi.CallOption) (*Job, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Job{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a new job. Typically, the job becomes searchable within 10 seconds, but it may take up to 5 minutes.",
// "flatPath": "v3/projects/{projectsId}/jobs",
// "httpMethod": "POST",
// "id": "jobs.projects.jobs.create",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Required. The resource name of the project under which the job is created. The format is \"projects/{project_id}\", for example, \"projects/api-test-project\".",
// "location": "path",
// "pattern": "^projects/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v3/{+parent}/jobs",
// "request": {
// "$ref": "CreateJobRequest"
// },
// "response": {
// "$ref": "Job"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/jobs"
// ]
// }
}
// method id "jobs.projects.jobs.delete":
type ProjectsJobsDeleteCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes the specified job. Typically, the job becomes
// unsearchable within 10 seconds, but it may take up to 5 minutes.
//
// - name: The resource name of the job to be deleted. The format is
// "projects/{project_id}/jobs/{job_id}", for example,
// "projects/api-test-project/jobs/1234".
func (r *ProjectsJobsService) Delete(name string) *ProjectsJobsDeleteCall {
c := &ProjectsJobsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsJobsDeleteCall) Fields(s ...googleapi.Field) *ProjectsJobsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsJobsDeleteCall) Context(ctx context.Context) *ProjectsJobsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsJobsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsJobsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v3/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "jobs.projects.jobs.delete" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsJobsDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes the specified job. Typically, the job becomes unsearchable within 10 seconds, but it may take up to 5 minutes.",
// "flatPath": "v3/projects/{projectsId}/jobs/{jobsId}",
// "httpMethod": "DELETE",
// "id": "jobs.projects.jobs.delete",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. The resource name of the job to be deleted. The format is \"projects/{project_id}/jobs/{job_id}\", for example, \"projects/api-test-project/jobs/1234\".",
// "location": "path",
// "pattern": "^projects/[^/]+/jobs/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v3/{+name}",
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/jobs"
// ]
// }
}
// method id "jobs.projects.jobs.get":
type ProjectsJobsGetCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Retrieves the specified job, whose status is OPEN or recently
// EXPIRED within the last 90 days.
//
// - name: The resource name of the job to retrieve. The format is
// "projects/{project_id}/jobs/{job_id}", for example,
// "projects/api-test-project/jobs/1234".
func (r *ProjectsJobsService) Get(name string) *ProjectsJobsGetCall {
c := &ProjectsJobsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsJobsGetCall) Fields(s ...googleapi.Field) *ProjectsJobsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsJobsGetCall) IfNoneMatch(entityTag string) *ProjectsJobsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsJobsGetCall) Context(ctx context.Context) *ProjectsJobsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsJobsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsJobsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v3/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "jobs.projects.jobs.get" call.
// Exactly one of *Job or error will be non-nil. Any non-2xx status code
// is an error. Response headers are in either
// *Job.ServerResponse.Header or (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *ProjectsJobsGetCall) Do(opts ...googleapi.CallOption) (*Job, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Job{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves the specified job, whose status is OPEN or recently EXPIRED within the last 90 days.",
// "flatPath": "v3/projects/{projectsId}/jobs/{jobsId}",
// "httpMethod": "GET",
// "id": "jobs.projects.jobs.get",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. The resource name of the job to retrieve. The format is \"projects/{project_id}/jobs/{job_id}\", for example, \"projects/api-test-project/jobs/1234\".",
// "location": "path",
// "pattern": "^projects/[^/]+/jobs/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v3/{+name}",
// "response": {
// "$ref": "Job"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/jobs"
// ]
// }
}
// method id "jobs.projects.jobs.list":
type ProjectsJobsListCall struct {
s *Service
parent string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists jobs by filter.
//
// - parent: The resource name of the project under which the job is
// created. The format is "projects/{project_id}", for example,
// "projects/api-test-project".
func (r *ProjectsJobsService) List(parent string) *ProjectsJobsListCall {
c := &ProjectsJobsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
return c
}
// Filter sets the optional parameter "filter": Required. The filter
// string specifies the jobs to be enumerated. Supported operator: =,
// AND The fields eligible for filtering are: * `companyName` *
// `requisitionId` * `status` Available values: OPEN, EXPIRED, ALL.
// Defaults to OPEN if no value is specified. At least one of
// `companyName` and `requisitionId` must present or an INVALID_ARGUMENT
// error is thrown. Sample Query: * companyName =
// "projects/api-test-project/companies/123" * companyName =
// "projects/api-test-project/companies/123" AND requisitionId = "req-1"
// * companyName = "projects/api-test-project/companies/123" AND status
// = "EXPIRED" * requisitionId = "req-1" * requisitionId = "req-1" AND
// status = "EXPIRED"
func (c *ProjectsJobsListCall) Filter(filter string) *ProjectsJobsListCall {
c.urlParams_.Set("filter", filter)
return c
}
// JobView sets the optional parameter "jobView": The desired job
// attributes returned for jobs in the search response. Defaults to
// JobView.JOB_VIEW_FULL if no value is specified.
//
// Possible values:
// "JOB_VIEW_UNSPECIFIED" - Default value.
// "JOB_VIEW_ID_ONLY" - A ID only view of job, with following
// attributes: Job.name, Job.requisition_id, Job.language_code.
// "JOB_VIEW_MINIMAL" - A minimal view of the job, with the following
// attributes: Job.name, Job.requisition_id, Job.title,
// Job.company_name, Job.DerivedInfo.locations, Job.language_code.
// "JOB_VIEW_SMALL" - A small view of the job, with the following
// attributes in the search results: Job.name, Job.requisition_id,
// Job.title, Job.company_name, Job.DerivedInfo.locations,
// Job.visibility, Job.language_code, Job.description.
// "JOB_VIEW_FULL" - All available attributes are included in the
// search results.
func (c *ProjectsJobsListCall) JobView(jobView string) *ProjectsJobsListCall {
c.urlParams_.Set("jobView", jobView)
return c
}
// PageSize sets the optional parameter "pageSize": The maximum number
// of jobs to be returned per page of results. If job_view is set to
// JobView.JOB_VIEW_ID_ONLY, the maximum allowed page size is 1000.
// Otherwise, the maximum allowed page size is 100. Default is 100 if
// empty or a number < 1 is specified.
func (c *ProjectsJobsListCall) PageSize(pageSize int64) *ProjectsJobsListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": The starting point
// of a query result.
func (c *ProjectsJobsListCall) PageToken(pageToken string) *ProjectsJobsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsJobsListCall) Fields(s ...googleapi.Field) *ProjectsJobsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsJobsListCall) IfNoneMatch(entityTag string) *ProjectsJobsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsJobsListCall) Context(ctx context.Context) *ProjectsJobsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsJobsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsJobsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v3/{+parent}/jobs")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "jobs.projects.jobs.list" call.
// Exactly one of *ListJobsResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ListJobsResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsJobsListCall) Do(opts ...googleapi.CallOption) (*ListJobsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ListJobsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists jobs by filter.",
// "flatPath": "v3/projects/{projectsId}/jobs",
// "httpMethod": "GET",
// "id": "jobs.projects.jobs.list",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "filter": {
// "description": "Required. The filter string specifies the jobs to be enumerated. Supported operator: =, AND The fields eligible for filtering are: * `companyName` * `requisitionId` * `status` Available values: OPEN, EXPIRED, ALL. Defaults to OPEN if no value is specified. At least one of `companyName` and `requisitionId` must present or an INVALID_ARGUMENT error is thrown. Sample Query: * companyName = \"projects/api-test-project/companies/123\" * companyName = \"projects/api-test-project/companies/123\" AND requisitionId = \"req-1\" * companyName = \"projects/api-test-project/companies/123\" AND status = \"EXPIRED\" * requisitionId = \"req-1\" * requisitionId = \"req-1\" AND status = \"EXPIRED\"",
// "location": "query",
// "type": "string"
// },
// "jobView": {
// "description": "Optional. The desired job attributes returned for jobs in the search response. Defaults to JobView.JOB_VIEW_FULL if no value is specified.",
// "enum": [
// "JOB_VIEW_UNSPECIFIED",
// "JOB_VIEW_ID_ONLY",
// "JOB_VIEW_MINIMAL",
// "JOB_VIEW_SMALL",
// "JOB_VIEW_FULL"
// ],
// "enumDescriptions": [
// "Default value.",
// "A ID only view of job, with following attributes: Job.name, Job.requisition_id, Job.language_code.",
// "A minimal view of the job, with the following attributes: Job.name, Job.requisition_id, Job.title, Job.company_name, Job.DerivedInfo.locations, Job.language_code.",
// "A small view of the job, with the following attributes in the search results: Job.name, Job.requisition_id, Job.title, Job.company_name, Job.DerivedInfo.locations, Job.visibility, Job.language_code, Job.description.",
// "All available attributes are included in the search results."
// ],
// "location": "query",
// "type": "string"
// },
// "pageSize": {
// "description": "Optional. The maximum number of jobs to be returned per page of results. If job_view is set to JobView.JOB_VIEW_ID_ONLY, the maximum allowed page size is 1000. Otherwise, the maximum allowed page size is 100. Default is 100 if empty or a number \u003c 1 is specified.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "Optional. The starting point of a query result.",
// "location": "query",
// "type": "string"
// },
// "parent": {
// "description": "Required. The resource name of the project under which the job is created. The format is \"projects/{project_id}\", for example, \"projects/api-test-project\".",
// "location": "path",
// "pattern": "^projects/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v3/{+parent}/jobs",
// "response": {
// "$ref": "ListJobsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/jobs"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ProjectsJobsListCall) Pages(ctx context.Context, f func(*ListJobsResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "jobs.projects.jobs.patch":
type ProjectsJobsPatchCall struct {
s *Service
name string
updatejobrequest *UpdateJobRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates specified job. Typically, updated contents become
// visible in search results within 10 seconds, but it may take up to 5
// minutes.
//
// - name: Required during job update. The resource name for the job.
// This is generated by the service when a job is created. The format
// is "projects/{project_id}/jobs/{job_id}", for example,
// "projects/api-test-project/jobs/1234". Use of this field in job
// queries and API calls is preferred over the use of requisition_id
// since this value is unique.
func (r *ProjectsJobsService) Patch(name string, updatejobrequest *UpdateJobRequest) *ProjectsJobsPatchCall {
c := &ProjectsJobsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
c.updatejobrequest = updatejobrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsJobsPatchCall) Fields(s ...googleapi.Field) *ProjectsJobsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsJobsPatchCall) Context(ctx context.Context) *ProjectsJobsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsJobsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsJobsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.updatejobrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v3/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PATCH", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "jobs.projects.jobs.patch" call.
// Exactly one of *Job or error will be non-nil. Any non-2xx status code
// is an error. Response headers are in either
// *Job.ServerResponse.Header or (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *ProjectsJobsPatchCall) Do(opts ...googleapi.CallOption) (*Job, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Job{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates specified job. Typically, updated contents become visible in search results within 10 seconds, but it may take up to 5 minutes.",
// "flatPath": "v3/projects/{projectsId}/jobs/{jobsId}",
// "httpMethod": "PATCH",
// "id": "jobs.projects.jobs.patch",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required during job update. The resource name for the job. This is generated by the service when a job is created. The format is \"projects/{project_id}/jobs/{job_id}\", for example, \"projects/api-test-project/jobs/1234\". Use of this field in job queries and API calls is preferred over the use of requisition_id since this value is unique.",
// "location": "path",
// "pattern": "^projects/[^/]+/jobs/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v3/{+name}",
// "request": {
// "$ref": "UpdateJobRequest"
// },
// "response": {
// "$ref": "Job"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/jobs"
// ]
// }
}
// method id "jobs.projects.jobs.search":
type ProjectsJobsSearchCall struct {
s *Service
parent string
searchjobsrequest *SearchJobsRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Search: Searches for jobs using the provided SearchJobsRequest. This
// call constrains the visibility of jobs present in the database, and
// only returns jobs that the caller has permission to search against.
//
// - parent: The resource name of the project to search within. The
// format is "projects/{project_id}", for example,
// "projects/api-test-project".
func (r *ProjectsJobsService) Search(parent string, searchjobsrequest *SearchJobsRequest) *ProjectsJobsSearchCall {
c := &ProjectsJobsSearchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.searchjobsrequest = searchjobsrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsJobsSearchCall) Fields(s ...googleapi.Field) *ProjectsJobsSearchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsJobsSearchCall) Context(ctx context.Context) *ProjectsJobsSearchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsJobsSearchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsJobsSearchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.searchjobsrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v3/{+parent}/jobs:search")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "jobs.projects.jobs.search" call.
// Exactly one of *SearchJobsResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *SearchJobsResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsJobsSearchCall) Do(opts ...googleapi.CallOption) (*SearchJobsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &SearchJobsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Searches for jobs using the provided SearchJobsRequest. This call constrains the visibility of jobs present in the database, and only returns jobs that the caller has permission to search against.",
// "flatPath": "v3/projects/{projectsId}/jobs:search",
// "httpMethod": "POST",
// "id": "jobs.projects.jobs.search",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Required. The resource name of the project to search within. The format is \"projects/{project_id}\", for example, \"projects/api-test-project\".",
// "location": "path",
// "pattern": "^projects/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v3/{+parent}/jobs:search",
// "request": {
// "$ref": "SearchJobsRequest"
// },
// "response": {
// "$ref": "SearchJobsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/jobs"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ProjectsJobsSearchCall) Pages(ctx context.Context, f func(*SearchJobsResponse) error) error {
c.ctx_ = ctx
defer func(pt string) { c.searchjobsrequest.PageToken = pt }(c.searchjobsrequest.PageToken) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.searchjobsrequest.PageToken = x.NextPageToken
}
}
// method id "jobs.projects.jobs.searchForAlert":
type ProjectsJobsSearchForAlertCall struct {
s *Service
parent string
searchjobsrequest *SearchJobsRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// SearchForAlert: Searches for jobs using the provided
// SearchJobsRequest. This API call is intended for the use case of
// targeting passive job seekers (for example, job seekers who have
// signed up to receive email alerts about potential job opportunities),
// and has different algorithmic adjustments that are targeted to
// passive job seekers. This call constrains the visibility of jobs
// present in the database, and only returns jobs the caller has
// permission to search against.
//
// - parent: The resource name of the project to search within. The
// format is "projects/{project_id}", for example,
// "projects/api-test-project".
func (r *ProjectsJobsService) SearchForAlert(parent string, searchjobsrequest *SearchJobsRequest) *ProjectsJobsSearchForAlertCall {
c := &ProjectsJobsSearchForAlertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.searchjobsrequest = searchjobsrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsJobsSearchForAlertCall) Fields(s ...googleapi.Field) *ProjectsJobsSearchForAlertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsJobsSearchForAlertCall) Context(ctx context.Context) *ProjectsJobsSearchForAlertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsJobsSearchForAlertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsJobsSearchForAlertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.searchjobsrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v3/{+parent}/jobs:searchForAlert")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "jobs.projects.jobs.searchForAlert" call.
// Exactly one of *SearchJobsResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *SearchJobsResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsJobsSearchForAlertCall) Do(opts ...googleapi.CallOption) (*SearchJobsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &SearchJobsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Searches for jobs using the provided SearchJobsRequest. This API call is intended for the use case of targeting passive job seekers (for example, job seekers who have signed up to receive email alerts about potential job opportunities), and has different algorithmic adjustments that are targeted to passive job seekers. This call constrains the visibility of jobs present in the database, and only returns jobs the caller has permission to search against.",
// "flatPath": "v3/projects/{projectsId}/jobs:searchForAlert",
// "httpMethod": "POST",
// "id": "jobs.projects.jobs.searchForAlert",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Required. The resource name of the project to search within. The format is \"projects/{project_id}\", for example, \"projects/api-test-project\".",
// "location": "path",
// "pattern": "^projects/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v3/{+parent}/jobs:searchForAlert",
// "request": {
// "$ref": "SearchJobsRequest"
// },
// "response": {
// "$ref": "SearchJobsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/jobs"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ProjectsJobsSearchForAlertCall) Pages(ctx context.Context, f func(*SearchJobsResponse) error) error {
c.ctx_ = ctx
defer func(pt string) { c.searchjobsrequest.PageToken = pt }(c.searchjobsrequest.PageToken) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.searchjobsrequest.PageToken = x.NextPageToken
}
}
| New |
image.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 TImage struct {
IControl
instance uintptr
// 特殊情况下使用,主要应对Go的GC问题,与LCL没有太多关系。
ptr unsafe.Pointer
}
// 创建一个新的对象。
//
// Create a new object.
func NewImage(owner IComponent) *TImage {
i := new(TImage)
i.instance = Image_Create(CheckPtr(owner))
i.ptr = unsafe.Pointer(i.instance)
// 不是TComponent应该是可以考虑加上的
// runtime.SetFinalizer(i, (*TImage).Free)
return i
}
// 动态转换一个已存在的对象实例。
//
// Dynamically convert an existing object instance.
func AsImage(obj interface{}) *TImage {
instance, ptr := getInstance(obj)
if instance == 0 { return nil }
return &TImage{instance: instance, ptr: ptr}
}
// -------------------------- Deprecated begin --------------------------
// 新建一个对象来自已经存在的对象实例指针。
//
// Create a new object from an existing object instance pointer.
// Deprecated: use AsImage.
func ImageFromInst(inst uintptr) *TImage {
return AsImage(inst)
}
// 新建一个对象来自已经存在的对象实例。
//
// Create a new object from an existing object instance.
// Deprecated: use AsImage.
func ImageFromObj(obj IObject) *TImage {
return AsImage(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 AsImage.
func ImageFromUnsafePointer(ptr unsafe.Pointer) *TImage {
return AsImage(ptr)
}
// -------------------------- Deprecated end --------------------------
// 释放对象。
//
// Free object.
func (i *TImage) Free() {
if i.instance != 0 {
Image_Free(i.instance)
| nullptr
}
}
// 返回对象实例指针。
//
// Return object instance pointer.
func (i *TImage) Instance() uintptr {
return i.instance
}
// 获取一个不安全的地址。
//
// Get an unsafe address.
func (i *TImage) UnsafeAddr() unsafe.Pointer {
return i.ptr
}
// 检测地址是否为空。
//
// Check if the address is empty.
func (i *TImage) IsValid() bool {
return i.instance != 0
}
// 检测当前对象是否继承自目标对象。
//
// Checks whether the current object is inherited from the target object.
func (i *TImage) Is() TIs {
return TIs(i.instance)
}
// 动态转换当前对象为目标对象。
//
// Dynamically convert the current object to the target object.
//func (i *TImage) As() TAs {
// return TAs(i.instance)
//}
// 获取类信息指针。
//
// Get class information pointer.
func TImageClass() TClass {
return Image_StaticClassType()
}
// 将控件置于最前。
//
// Bring the control to the front.
func (i *TImage) BringToFront() {
Image_BringToFront(i.instance)
}
// 将客户端坐标转为绝对的屏幕坐标。
//
// Convert client coordinates to absolute screen coordinates.
func (i *TImage) ClientToScreen(Point TPoint) TPoint {
return Image_ClientToScreen(i.instance, Point)
}
// 将客户端坐标转为父容器坐标。
//
// Convert client coordinates to parent container coordinates.
func (i *TImage) ClientToParent(Point TPoint, AParent IWinControl) TPoint {
return Image_ClientToParent(i.instance, Point , CheckPtr(AParent))
}
// 是否在拖拽中。
//
// Is it in the middle of dragging.
func (i *TImage) Dragging() bool {
return Image_Dragging(i.instance)
}
// 是否有父容器。
//
// Is there a parent container.
func (i *TImage) HasParent() bool {
return Image_HasParent(i.instance)
}
// 隐藏控件。
//
// Hidden control.
func (i *TImage) Hide() {
Image_Hide(i.instance)
}
// 要求重绘。
//
// Redraw.
func (i *TImage) Invalidate() {
Image_Invalidate(i.instance)
}
// 发送一个消息。
//
// Send a message.
func (i *TImage) Perform(Msg uint32, WParam uintptr, LParam int) int {
return Image_Perform(i.instance, Msg , WParam , LParam)
}
// 刷新控件。
//
// Refresh control.
func (i *TImage) Refresh() {
Image_Refresh(i.instance)
}
// 重绘。
//
// Repaint.
func (i *TImage) Repaint() {
Image_Repaint(i.instance)
}
// 将屏幕坐标转为客户端坐标。
//
// Convert screen coordinates to client coordinates.
func (i *TImage) ScreenToClient(Point TPoint) TPoint {
return Image_ScreenToClient(i.instance, Point)
}
// 将父容器坐标转为客户端坐标。
//
// Convert parent container coordinates to client coordinates.
func (i *TImage) ParentToClient(Point TPoint, AParent IWinControl) TPoint {
return Image_ParentToClient(i.instance, Point , CheckPtr(AParent))
}
// 控件至于最后面。
//
// The control is placed at the end.
func (i *TImage) SendToBack() {
Image_SendToBack(i.instance)
}
// 设置组件边界。
//
// Set component boundaries.
func (i *TImage) SetBounds(ALeft int32, ATop int32, AWidth int32, AHeight int32) {
Image_SetBounds(i.instance, ALeft , ATop , AWidth , AHeight)
}
// 显示控件。
//
// Show control.
func (i *TImage) Show() {
Image_Show(i.instance)
}
// 控件更新。
//
// Update.
func (i *TImage) Update() {
Image_Update(i.instance)
}
// 获取控件的字符,如果有。
//
// Get the characters of the control, if any.
func (i *TImage) GetTextBuf(Buffer *string, BufSize int32) int32 {
return Image_GetTextBuf(i.instance, Buffer , BufSize)
}
// 获取控件的字符长,如果有。
//
// Get the character length of the control, if any.
func (i *TImage) GetTextLen() int32 {
return Image_GetTextLen(i.instance)
}
// 设置控件字符,如果有。
//
// Set control characters, if any.
func (i *TImage) SetTextBuf(Buffer string) {
Image_SetTextBuf(i.instance, Buffer)
}
// 查找指定名称的组件。
//
// Find the component with the specified name.
func (i *TImage) FindComponent(AName string) *TComponent {
return AsComponent(Image_FindComponent(i.instance, AName))
}
// 获取类名路径。
//
// Get the class name path.
func (i *TImage) GetNamePath() string {
return Image_GetNamePath(i.instance)
}
// 复制一个对象,如果对象实现了此方法的话。
//
// Copy an object, if the object implements this method.
func (i *TImage) Assign(Source IObject) {
Image_Assign(i.instance, CheckPtr(Source))
}
// 获取类的类型信息。
//
// Get class type information.
func (i *TImage) ClassType() TClass {
return Image_ClassType(i.instance)
}
// 获取当前对象类名称。
//
// Get the current object class name.
func (i *TImage) ClassName() string {
return Image_ClassName(i.instance)
}
// 获取当前对象实例大小。
//
// Get the current object instance size.
func (i *TImage) InstanceSize() int32 {
return Image_InstanceSize(i.instance)
}
// 判断当前类是否继承自指定类。
//
// Determine whether the current class inherits from the specified class.
func (i *TImage) InheritsFrom(AClass TClass) bool {
return Image_InheritsFrom(i.instance, AClass)
}
// 与一个对象进行比较。
//
// Compare with an object.
func (i *TImage) Equals(Obj IObject) bool {
return Image_Equals(i.instance, CheckPtr(Obj))
}
// 获取类的哈希值。
//
// Get the hash value of the class.
func (i *TImage) GetHashCode() int32 {
return Image_GetHashCode(i.instance)
}
// 文本类信息。
//
// Text information.
func (i *TImage) ToString() string {
return Image_ToString(i.instance)
}
func (i *TImage) AnchorToNeighbour(ASide TAnchorKind, ASpace int32, ASibling IControl) {
Image_AnchorToNeighbour(i.instance, ASide , ASpace , CheckPtr(ASibling))
}
func (i *TImage) AnchorParallel(ASide TAnchorKind, ASpace int32, ASibling IControl) {
Image_AnchorParallel(i.instance, ASide , ASpace , CheckPtr(ASibling))
}
// 置于指定控件的横向中心。
func (i *TImage) AnchorHorizontalCenterTo(ASibling IControl) {
Image_AnchorHorizontalCenterTo(i.instance, CheckPtr(ASibling))
}
// 置于指定控件的纵向中心。
func (i *TImage) AnchorVerticalCenterTo(ASibling IControl) {
Image_AnchorVerticalCenterTo(i.instance, CheckPtr(ASibling))
}
func (i *TImage) AnchorAsAlign(ATheAlign TAlign, ASpace int32) {
Image_AnchorAsAlign(i.instance, ATheAlign , ASpace)
}
func (i *TImage) AnchorClient(ASpace int32) {
Image_AnchorClient(i.instance, ASpace)
}
func (i *TImage) AntialiasingMode() TAntialiasingMode {
return Image_GetAntialiasingMode(i.instance)
}
func (i *TImage) SetAntialiasingMode(value TAntialiasingMode) {
Image_SetAntialiasingMode(i.instance, value)
}
func (i *TImage) KeepOriginXWhenClipped() bool {
return Image_GetKeepOriginXWhenClipped(i.instance)
}
func (i *TImage) SetKeepOriginXWhenClipped(value bool) {
Image_SetKeepOriginXWhenClipped(i.instance, value)
}
func (i *TImage) KeepOriginYWhenClipped() bool {
return Image_GetKeepOriginYWhenClipped(i.instance)
}
func (i *TImage) SetKeepOriginYWhenClipped(value bool) {
Image_SetKeepOriginYWhenClipped(i.instance, value)
}
func (i *TImage) StretchInEnabled() bool {
return Image_GetStretchInEnabled(i.instance)
}
func (i *TImage) SetStretchInEnabled(value bool) {
Image_SetStretchInEnabled(i.instance, value)
}
func (i *TImage) StretchOutEnabled() bool {
return Image_GetStretchOutEnabled(i.instance)
}
func (i *TImage) SetStretchOutEnabled(value bool) {
Image_SetStretchOutEnabled(i.instance, value)
}
// 获取画布。
func (i *TImage) Canvas() *TCanvas {
return AsCanvas(Image_GetCanvas(i.instance))
}
// 获取控件自动调整。
//
// Get Control automatically adjusts.
func (i *TImage) Align() TAlign {
return Image_GetAlign(i.instance)
}
// 设置控件自动调整。
//
// Set Control automatically adjusts.
func (i *TImage) SetAlign(value TAlign) {
Image_SetAlign(i.instance, value)
}
// 获取四个角位置的锚点。
func (i *TImage) Anchors() TAnchors {
return Image_GetAnchors(i.instance)
}
// 设置四个角位置的锚点。
func (i *TImage) SetAnchors(value TAnchors) {
Image_SetAnchors(i.instance, value)
}
// 获取自动调整大小。
func (i *TImage) AutoSize() bool {
return Image_GetAutoSize(i.instance)
}
// 设置自动调整大小。
func (i *TImage) SetAutoSize(value bool) {
Image_SetAutoSize(i.instance, value)
}
func (i *TImage) Center() bool {
return Image_GetCenter(i.instance)
}
func (i *TImage) SetCenter(value bool) {
Image_SetCenter(i.instance, value)
}
// 获取约束控件大小。
func (i *TImage) Constraints() *TSizeConstraints {
return AsSizeConstraints(Image_GetConstraints(i.instance))
}
// 设置约束控件大小。
func (i *TImage) SetConstraints(value *TSizeConstraints) {
Image_SetConstraints(i.instance, CheckPtr(value))
}
// 获取设置控件拖拽时的光标。
//
// Get Set the cursor when the control is dragged.
func (i *TImage) DragCursor() TCursor {
return Image_GetDragCursor(i.instance)
}
// 设置设置控件拖拽时的光标。
//
// Set Set the cursor when the control is dragged.
func (i *TImage) SetDragCursor(value TCursor) {
Image_SetDragCursor(i.instance, value)
}
// 获取拖拽模式。
//
// Get Drag mode.
func (i *TImage) DragMode() TDragMode {
return Image_GetDragMode(i.instance)
}
// 设置拖拽模式。
//
// Set Drag mode.
func (i *TImage) SetDragMode(value TDragMode) {
Image_SetDragMode(i.instance, value)
}
// 获取控件启用。
//
// Get the control enabled.
func (i *TImage) Enabled() bool {
return Image_GetEnabled(i.instance)
}
// 设置控件启用。
//
// Set the control enabled.
func (i *TImage) SetEnabled(value bool) {
Image_SetEnabled(i.instance, value)
}
// 获取以父容器的ShowHint属性为准。
func (i *TImage) ParentShowHint() bool {
return Image_GetParentShowHint(i.instance)
}
// 设置以父容器的ShowHint属性为准。
func (i *TImage) SetParentShowHint(value bool) {
Image_SetParentShowHint(i.instance, value)
}
// 获取图片。
func (i *TImage) Picture() *TPicture {
return AsPicture(Image_GetPicture(i.instance))
}
// 设置图片。
func (i *TImage) SetPicture(value *TPicture) {
Image_SetPicture(i.instance, CheckPtr(value))
}
// 获取右键菜单。
//
// Get Right click menu.
func (i *TImage) PopupMenu() *TPopupMenu {
return AsPopupMenu(Image_GetPopupMenu(i.instance))
}
// 设置右键菜单。
//
// Set Right click menu.
func (i *TImage) SetPopupMenu(value IComponent) {
Image_SetPopupMenu(i.instance, CheckPtr(value))
}
// 获取等比缩放。
func (i *TImage) Proportional() bool {
return Image_GetProportional(i.instance)
}
// 设置等比缩放。
func (i *TImage) SetProportional(value bool) {
Image_SetProportional(i.instance, value)
}
// 获取显示鼠标悬停提示。
//
// Get Show mouseover tips.
func (i *TImage) ShowHint() bool {
return Image_GetShowHint(i.instance)
}
// 设置显示鼠标悬停提示。
//
// Set Show mouseover tips.
func (i *TImage) SetShowHint(value bool) {
Image_SetShowHint(i.instance, value)
}
// 获取拉伸缩放。
func (i *TImage) Stretch() bool {
return Image_GetStretch(i.instance)
}
// 设置拉伸缩放。
func (i *TImage) SetStretch(value bool) {
Image_SetStretch(i.instance, value)
}
// 获取透明。
//
// Get transparent.
func (i *TImage) Transparent() bool {
return Image_GetTransparent(i.instance)
}
// 设置透明。
//
// Set transparent.
func (i *TImage) SetTransparent(value bool) {
Image_SetTransparent(i.instance, value)
}
// 获取控件可视。
//
// Get the control visible.
func (i *TImage) Visible() bool {
return Image_GetVisible(i.instance)
}
// 设置控件可视。
//
// Set the control visible.
func (i *TImage) SetVisible(value bool) {
Image_SetVisible(i.instance, value)
}
// 设置控件单击事件。
//
// Set control click event.
func (i *TImage) SetOnClick(fn TNotifyEvent) {
Image_SetOnClick(i.instance, fn)
}
// 设置双击事件。
func (i *TImage) SetOnDblClick(fn TNotifyEvent) {
Image_SetOnDblClick(i.instance, fn)
}
// 设置拖拽下落事件。
//
// Set Drag and drop event.
func (i *TImage) SetOnDragDrop(fn TDragDropEvent) {
Image_SetOnDragDrop(i.instance, fn)
}
// 设置拖拽完成事件。
//
// Set Drag and drop completion event.
func (i *TImage) SetOnDragOver(fn TDragOverEvent) {
Image_SetOnDragOver(i.instance, fn)
}
// 设置拖拽结束。
//
// Set End of drag.
func (i *TImage) SetOnEndDrag(fn TEndDragEvent) {
Image_SetOnEndDrag(i.instance, fn)
}
// 设置鼠标按下事件。
//
// Set Mouse down event.
func (i *TImage) SetOnMouseDown(fn TMouseEvent) {
Image_SetOnMouseDown(i.instance, fn)
}
// 设置鼠标进入事件。
//
// Set Mouse entry event.
func (i *TImage) SetOnMouseEnter(fn TNotifyEvent) {
Image_SetOnMouseEnter(i.instance, fn)
}
// 设置鼠标离开事件。
//
// Set Mouse leave event.
func (i *TImage) SetOnMouseLeave(fn TNotifyEvent) {
Image_SetOnMouseLeave(i.instance, fn)
}
// 设置鼠标移动事件。
func (i *TImage) SetOnMouseMove(fn TMouseMoveEvent) {
Image_SetOnMouseMove(i.instance, fn)
}
// 设置鼠标抬起事件。
//
// Set Mouse lift event.
func (i *TImage) SetOnMouseUp(fn TMouseEvent) {
Image_SetOnMouseUp(i.instance, fn)
}
func (i *TImage) Action() *TAction {
return AsAction(Image_GetAction(i.instance))
}
func (i *TImage) SetAction(value IComponent) {
Image_SetAction(i.instance, CheckPtr(value))
}
func (i *TImage) BiDiMode() TBiDiMode {
return Image_GetBiDiMode(i.instance)
}
func (i *TImage) SetBiDiMode(value TBiDiMode) {
Image_SetBiDiMode(i.instance, value)
}
func (i *TImage) BoundsRect() TRect {
return Image_GetBoundsRect(i.instance)
}
func (i *TImage) SetBoundsRect(value TRect) {
Image_SetBoundsRect(i.instance, value)
}
// 获取客户区高度。
//
// Get client height.
func (i *TImage) ClientHeight() int32 {
return Image_GetClientHeight(i.instance)
}
// 设置客户区高度。
//
// Set client height.
func (i *TImage) SetClientHeight(value int32) {
Image_SetClientHeight(i.instance, value)
}
func (i *TImage) ClientOrigin() TPoint {
return Image_GetClientOrigin(i.instance)
}
// 获取客户区矩形。
//
// Get client rectangle.
func (i *TImage) ClientRect() TRect {
return Image_GetClientRect(i.instance)
}
// 获取客户区宽度。
//
// Get client width.
func (i *TImage) ClientWidth() int32 {
return Image_GetClientWidth(i.instance)
}
// 设置客户区宽度。
//
// Set client width.
func (i *TImage) SetClientWidth(value int32) {
Image_SetClientWidth(i.instance, value)
}
// 获取控件状态。
//
// Get control state.
func (i *TImage) ControlState() TControlState {
return Image_GetControlState(i.instance)
}
// 设置控件状态。
//
// Set control state.
func (i *TImage) SetControlState(value TControlState) {
Image_SetControlState(i.instance, value)
}
// 获取控件样式。
//
// Get control style.
func (i *TImage) ControlStyle() TControlStyle {
return Image_GetControlStyle(i.instance)
}
// 设置控件样式。
//
// Set control style.
func (i *TImage) SetControlStyle(value TControlStyle) {
Image_SetControlStyle(i.instance, value)
}
func (i *TImage) Floating() bool {
return Image_GetFloating(i.instance)
}
// 获取控件父容器。
//
// Get control parent container.
func (i *TImage) Parent() *TWinControl {
return AsWinControl(Image_GetParent(i.instance))
}
// 设置控件父容器。
//
// Set control parent container.
func (i *TImage) SetParent(value IWinControl) {
Image_SetParent(i.instance, CheckPtr(value))
}
// 获取左边位置。
//
// Get Left position.
func (i *TImage) Left() int32 {
return Image_GetLeft(i.instance)
}
// 设置左边位置。
//
// Set Left position.
func (i *TImage) SetLeft(value int32) {
Image_SetLeft(i.instance, value)
}
// 获取顶边位置。
//
// Get Top position.
func (i *TImage) Top() int32 {
return Image_GetTop(i.instance)
}
// 设置顶边位置。
//
// Set Top position.
func (i *TImage) SetTop(value int32) {
Image_SetTop(i.instance, value)
}
// 获取宽度。
//
// Get width.
func (i *TImage) Width() int32 {
return Image_GetWidth(i.instance)
}
// 设置宽度。
//
// Set width.
func (i *TImage) SetWidth(value int32) {
Image_SetWidth(i.instance, value)
}
// 获取高度。
//
// Get height.
func (i *TImage) Height() int32 {
return Image_GetHeight(i.instance)
}
// 设置高度。
//
// Set height.
func (i *TImage) SetHeight(value int32) {
Image_SetHeight(i.instance, value)
}
// 获取控件光标。
//
// Get control cursor.
func (i *TImage) Cursor() TCursor {
return Image_GetCursor(i.instance)
}
// 设置控件光标。
//
// Set control cursor.
func (i *TImage) SetCursor(value TCursor) {
Image_SetCursor(i.instance, value)
}
// 获取组件鼠标悬停提示。
//
// Get component mouse hints.
func (i *TImage) Hint() string {
return Image_GetHint(i.instance)
}
// 设置组件鼠标悬停提示。
//
// Set component mouse hints.
func (i *TImage) SetHint(value string) {
Image_SetHint(i.instance, value)
}
// 获取组件总数。
//
// Get the total number of components.
func (i *TImage) ComponentCount() int32 {
return Image_GetComponentCount(i.instance)
}
// 获取组件索引。
//
// Get component index.
func (i *TImage) ComponentIndex() int32 {
return Image_GetComponentIndex(i.instance)
}
// 设置组件索引。
//
// Set component index.
func (i *TImage) SetComponentIndex(value int32) {
Image_SetComponentIndex(i.instance, value)
}
// 获取组件所有者。
//
// Get component owner.
func (i *TImage) Owner() *TComponent {
return AsComponent(Image_GetOwner(i.instance))
}
// 获取组件名称。
//
// Get the component name.
func (i *TImage) Name() string {
return Image_GetName(i.instance)
}
// 设置组件名称。
//
// Set the component name.
func (i *TImage) SetName(value string) {
Image_SetName(i.instance, value)
}
// 获取对象标记。
//
// Get the control tag.
func (i *TImage) Tag() int {
return Image_GetTag(i.instance)
}
// 设置对象标记。
//
// Set the control tag.
func (i *TImage) SetTag(value int) {
Image_SetTag(i.instance, value)
}
// 获取左边锚点。
func (i *TImage) AnchorSideLeft() *TAnchorSide {
return AsAnchorSide(Image_GetAnchorSideLeft(i.instance))
}
// 设置左边锚点。
func (i *TImage) SetAnchorSideLeft(value *TAnchorSide) {
Image_SetAnchorSideLeft(i.instance, CheckPtr(value))
}
// 获取顶边锚点。
func (i *TImage) AnchorSideTop() *TAnchorSide {
return AsAnchorSide(Image_GetAnchorSideTop(i.instance))
}
// 设置顶边锚点。
func (i *TImage) SetAnchorSideTop(value *TAnchorSide) {
Image_SetAnchorSideTop(i.instance, CheckPtr(value))
}
// 获取右边锚点。
func (i *TImage) AnchorSideRight() *TAnchorSide {
return AsAnchorSide(Image_GetAnchorSideRight(i.instance))
}
// 设置右边锚点。
func (i *TImage) SetAnchorSideRight(value *TAnchorSide) {
Image_SetAnchorSideRight(i.instance, CheckPtr(value))
}
// 获取底边锚点。
func (i *TImage) AnchorSideBottom() *TAnchorSide {
return AsAnchorSide(Image_GetAnchorSideBottom(i.instance))
}
// 设置底边锚点。
func (i *TImage) SetAnchorSideBottom(value *TAnchorSide) {
Image_SetAnchorSideBottom(i.instance, CheckPtr(value))
}
// 获取边框间距。
func (i *TImage) BorderSpacing() *TControlBorderSpacing {
return AsControlBorderSpacing(Image_GetBorderSpacing(i.instance))
}
// 设置边框间距。
func (i *TImage) SetBorderSpacing(value *TControlBorderSpacing) {
Image_SetBorderSpacing(i.instance, CheckPtr(value))
}
// 获取指定索引组件。
//
// Get the specified index component.
func (i *TImage) Components(AIndex int32) *TComponent {
return AsComponent(Image_GetComponents(i.instance, AIndex))
}
// 获取锚侧面。
func (i *TImage) AnchorSide(AKind TAnchorKind) *TAnchorSide {
return AsAnchorSide(Image_GetAnchorSide(i.instance, AKind))
}
| i.instance, i.ptr = 0, |
formatters.py | # encoding: utf-8
import datetime
import pytz
from babel import numbers
import ckan.lib.i18n as i18n
from ckan.common import _, ungettext
##################################################
# #
# Month translations #
# #
##################################################
def _month_jan():
|
def _month_feb():
return _('February')
def _month_mar():
return _('March')
def _month_apr():
return _('April')
def _month_may():
return _('May')
def _month_june():
return _('June')
def _month_july():
return _('July')
def _month_aug():
return _('August')
def _month_sept():
return _('September')
def _month_oct():
return _('October')
def _month_nov():
return _('November')
def _month_dec():
return _('December')
# _MONTH_FUNCTIONS provides an easy way to get a localised month via
# _MONTH_FUNCTIONS[month]() where months are zero based ie jan = 0, dec = 11
_MONTH_FUNCTIONS = [_month_jan, _month_feb, _month_mar, _month_apr,
_month_may, _month_june, _month_july, _month_aug,
_month_sept, _month_oct, _month_nov, _month_dec]
def localised_nice_date(datetime_, show_date=False, with_hours=False):
''' Returns a friendly localised unicode representation of a datetime.
:param datetime_: The date to format
:type datetime_: datetime
:param show_date: Show date not 2 days ago etc
:type show_date: bool
:param with_hours: should the `hours:mins` be shown for dates
:type with_hours: bool
:rtype: sting
'''
def months_between(date1, date2):
if date1 > date2:
date1, date2 = date2, date1
m1 = date1.year * 12 + date1.month
m2 = date2.year * 12 + date2.month
months = m2 - m1
if date1.day > date2.day:
months -= 1
elif date1.day == date2.day:
seconds1 = date1.hour * 3600 + date1.minute + date1.second
seconds2 = date2.hour * 3600 + date2.minute + date2.second
if seconds1 > seconds2:
months -= 1
return months
if not show_date:
now = datetime.datetime.utcnow()
if datetime_.tzinfo is not None:
now = now.replace(tzinfo=datetime_.tzinfo)
else:
now = now.replace(tzinfo=pytz.utc)
datetime_ = datetime_.replace(tzinfo=pytz.utc)
date_diff = now - datetime_
days = date_diff.days
if days < 1 and now > datetime_:
# less than one day
seconds = date_diff.seconds
if seconds < 3600:
# less than one hour
if seconds < 60:
return _('Just now')
else:
return ungettext('{mins} minute ago', '{mins} minutes ago',
seconds / 60).format(mins=seconds / 60)
else:
return ungettext('{hours} hour ago', '{hours} hours ago',
seconds / 3600).format(hours=seconds / 3600)
# more than one day
months = months_between(datetime_, now)
if months < 1:
return ungettext('{days} day ago', '{days} days ago',
days).format(days=days)
if months < 13:
return ungettext('{months} month ago', '{months} months ago',
months).format(months=months)
return ungettext('over {years} year ago', 'over {years} years ago',
months / 12).format(years=months / 12)
# actual date
details = {
'min': datetime_.minute,
'hour': datetime_.hour,
'day': datetime_.day,
'year': datetime_.year,
'month': _MONTH_FUNCTIONS[datetime_.month - 1](),
'timezone': datetime_.tzname(),
}
if with_hours:
return (
# NOTE: This is for translating dates like `April 24, 2013, 10:45 (Europe/Zurich)`
_('{month} {day}, {year}, {hour:02}:{min:02} ({timezone})') \
.format(**details))
else:
return (
# NOTE: This is for translating dates like `April 24, 2013`
_('{month} {day}, {year}').format(**details))
def localised_number(number):
''' Returns a localised unicode representation of number '''
return numbers.format_number(number, locale=i18n.get_lang())
def localised_filesize(number):
''' Returns a localised unicode representation of a number in bytes, MiB
etc '''
def rnd(number, divisor):
# round to 1 decimal place
return localised_number(float(number * 10 / divisor) / 10)
if number < 1024:
return _('{bytes} bytes').format(bytes=localised_number(number))
elif number < 1024 ** 2:
return _('{kibibytes} KiB').format(kibibytes=rnd(number, 1024))
elif number < 1024 ** 3:
return _('{mebibytes} MiB').format(mebibytes=rnd(number, 1024 ** 2))
elif number < 1024 ** 4:
return _('{gibibytes} GiB').format(gibibytes=rnd(number, 1024 ** 3))
else:
return _('{tebibytes} TiB').format(tebibytes=rnd(number, 1024 ** 4))
def localised_SI_number(number):
''' Returns a localised unicode representation of a number in SI format
eg 14700 becomes 14.7k '''
def rnd(number, divisor):
# round to 1 decimal place
return localised_number(float(number * 10 / divisor) / 10)
if number < 1000:
return _('{n}').format(n=localised_number(number))
elif number < 1000 ** 2:
return _('{k}k').format(k=rnd(number, 1000))
elif number < 1000 ** 3:
return _('{m}M').format(m=rnd(number, 1000 ** 2))
elif number < 1000 ** 4:
return _('{g}G').format(g=rnd(number, 1000 ** 3))
elif number < 1000 ** 5:
return _('{t}T').format(t=rnd(number, 1000 ** 4))
elif number < 1000 ** 6:
return _('{p}P').format(p=rnd(number, 1000 ** 5))
elif number < 1000 ** 7:
return _('{e}E').format(e=rnd(number, 1000 ** 6))
elif number < 1000 ** 8:
return _('{z}Z').format(z=rnd(number, 1000 ** 7))
else:
return _('{y}Y').format(y=rnd(number, 1000 ** 8))
| return _('January') |
BsStarFill.d.ts | // THIS FILE IS AUTO GENERATED
import { IconTree, IconType } from '../lib' | export declare const BsStarFill: IconType; |
|
profiles.go | package billing
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// ProfilesClient is the billing client provides access to billing resources for Azure subscriptions.
type ProfilesClient struct {
BaseClient
}
// NewProfilesClient creates an instance of the ProfilesClient client.
func | (subscriptionID string) ProfilesClient {
return NewProfilesClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewProfilesClientWithBaseURI creates an instance of the ProfilesClient client using a custom endpoint. Use this
// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack).
func NewProfilesClientWithBaseURI(baseURI string, subscriptionID string) ProfilesClient {
return ProfilesClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// Create the operation to create a BillingProfile.
// Parameters:
// billingAccountName - billing Account Id.
// parameters - parameters supplied to the Create BillingProfile operation.
func (client ProfilesClient) Create(ctx context.Context, billingAccountName string, parameters ProfileCreationParameters) (result ProfilesCreateFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.Create")
defer func() {
sc := -1
if result.FutureAPI != nil && result.FutureAPI.Response() != nil {
sc = result.FutureAPI.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.CreatePreparer(ctx, billingAccountName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.ProfilesClient", "Create", nil, "Failure preparing request")
return
}
result, err = client.CreateSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.ProfilesClient", "Create", nil, "Failure sending request")
return
}
return
}
// CreatePreparer prepares the Create request.
func (client ProfilesClient) CreatePreparer(ctx context.Context, billingAccountName string, parameters ProfileCreationParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"billingAccountName": autorest.Encode("path", billingAccountName),
}
const APIVersion = "2018-11-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateSender sends the Create request. The method will close the
// http.Response Body if it receives an error.
func (client ProfilesClient) CreateSender(req *http.Request) (future ProfilesCreateFuture, err error) {
var resp *http.Response
resp, err = client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = func(client ProfilesClient) (p Profile, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.ProfilesCreateFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
err = azure.NewAsyncOpIncompleteError("billing.ProfilesCreateFuture")
return
}
sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
p.Response.Response, err = future.GetResult(sender)
if p.Response.Response == nil && err == nil {
err = autorest.NewErrorWithError(err, "billing.ProfilesCreateFuture", "Result", nil, "received nil response and error")
}
if err == nil && p.Response.Response.StatusCode != http.StatusNoContent {
p, err = client.CreateResponder(p.Response.Response)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.ProfilesCreateFuture", "Result", p.Response.Response, "Failure responding to request")
}
}
return
}
return
}
// CreateResponder handles the response to the Create request. The method always
// closes the http.Response Body.
func (client ProfilesClient) CreateResponder(resp *http.Response) (result Profile, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Get get the billing profile by id.
// Parameters:
// billingAccountName - billing Account Id.
// billingProfileName - billing Profile Id.
// expand - may be used to expand the invoiceSections.
func (client ProfilesClient) Get(ctx context.Context, billingAccountName string, billingProfileName string, expand string) (result Profile, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.Get")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.GetPreparer(ctx, billingAccountName, billingProfileName, expand)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.ProfilesClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "billing.ProfilesClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.ProfilesClient", "Get", resp, "Failure responding to request")
return
}
return
}
// GetPreparer prepares the Get request.
func (client ProfilesClient) GetPreparer(ctx context.Context, billingAccountName string, billingProfileName string, expand string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"billingAccountName": autorest.Encode("path", billingAccountName),
"billingProfileName": autorest.Encode("path", billingProfileName),
}
const APIVersion = "2018-11-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
if len(expand) > 0 {
queryParameters["$expand"] = autorest.Encode("query", expand)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client ProfilesClient) GetSender(req *http.Request) (*http.Response, error) {
return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client ProfilesClient) GetResponder(resp *http.Response) (result Profile, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListByBillingAccountName lists all billing profiles for a user which that user has access to.
// Parameters:
// billingAccountName - billing Account Id.
// expand - may be used to expand the invoiceSections.
func (client ProfilesClient) ListByBillingAccountName(ctx context.Context, billingAccountName string, expand string) (result ProfileListResultPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.ListByBillingAccountName")
defer func() {
sc := -1
if result.plr.Response.Response != nil {
sc = result.plr.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.fn = client.listByBillingAccountNameNextResults
req, err := client.ListByBillingAccountNamePreparer(ctx, billingAccountName, expand)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.ProfilesClient", "ListByBillingAccountName", nil, "Failure preparing request")
return
}
resp, err := client.ListByBillingAccountNameSender(req)
if err != nil {
result.plr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "billing.ProfilesClient", "ListByBillingAccountName", resp, "Failure sending request")
return
}
result.plr, err = client.ListByBillingAccountNameResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.ProfilesClient", "ListByBillingAccountName", resp, "Failure responding to request")
return
}
if result.plr.hasNextLink() && result.plr.IsEmpty() {
err = result.NextWithContext(ctx)
return
}
return
}
// ListByBillingAccountNamePreparer prepares the ListByBillingAccountName request.
func (client ProfilesClient) ListByBillingAccountNamePreparer(ctx context.Context, billingAccountName string, expand string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"billingAccountName": autorest.Encode("path", billingAccountName),
}
const APIVersion = "2018-11-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
if len(expand) > 0 {
queryParameters["$expand"] = autorest.Encode("query", expand)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByBillingAccountNameSender sends the ListByBillingAccountName request. The method will close the
// http.Response Body if it receives an error.
func (client ProfilesClient) ListByBillingAccountNameSender(req *http.Request) (*http.Response, error) {
return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// ListByBillingAccountNameResponder handles the response to the ListByBillingAccountName request. The method always
// closes the http.Response Body.
func (client ProfilesClient) ListByBillingAccountNameResponder(resp *http.Response) (result ProfileListResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listByBillingAccountNameNextResults retrieves the next set of results, if any.
func (client ProfilesClient) listByBillingAccountNameNextResults(ctx context.Context, lastResults ProfileListResult) (result ProfileListResult, err error) {
req, err := lastResults.profileListResultPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "billing.ProfilesClient", "listByBillingAccountNameNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListByBillingAccountNameSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "billing.ProfilesClient", "listByBillingAccountNameNextResults", resp, "Failure sending next results request")
}
result, err = client.ListByBillingAccountNameResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.ProfilesClient", "listByBillingAccountNameNextResults", resp, "Failure responding to next results request")
}
return
}
// ListByBillingAccountNameComplete enumerates all values, automatically crossing page boundaries as required.
func (client ProfilesClient) ListByBillingAccountNameComplete(ctx context.Context, billingAccountName string, expand string) (result ProfileListResultIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.ListByBillingAccountName")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.ListByBillingAccountName(ctx, billingAccountName, expand)
return
}
// Update the operation to update a billing profile.
// Parameters:
// billingAccountName - billing Account Id.
// billingProfileName - billing Profile Id.
// parameters - parameters supplied to the update billing profile operation.
func (client ProfilesClient) Update(ctx context.Context, billingAccountName string, billingProfileName string, parameters Profile) (result ProfilesUpdateFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.Update")
defer func() {
sc := -1
if result.FutureAPI != nil && result.FutureAPI.Response() != nil {
sc = result.FutureAPI.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.UpdatePreparer(ctx, billingAccountName, billingProfileName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.ProfilesClient", "Update", nil, "Failure preparing request")
return
}
result, err = client.UpdateSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.ProfilesClient", "Update", nil, "Failure sending request")
return
}
return
}
// UpdatePreparer prepares the Update request.
func (client ProfilesClient) UpdatePreparer(ctx context.Context, billingAccountName string, billingProfileName string, parameters Profile) (*http.Request, error) {
pathParameters := map[string]interface{}{
"billingAccountName": autorest.Encode("path", billingAccountName),
"billingProfileName": autorest.Encode("path", billingProfileName),
}
const APIVersion = "2018-11-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client ProfilesClient) UpdateSender(req *http.Request) (future ProfilesUpdateFuture, err error) {
var resp *http.Response
resp, err = client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = func(client ProfilesClient) (p Profile, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.ProfilesUpdateFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
err = azure.NewAsyncOpIncompleteError("billing.ProfilesUpdateFuture")
return
}
sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
p.Response.Response, err = future.GetResult(sender)
if p.Response.Response == nil && err == nil {
err = autorest.NewErrorWithError(err, "billing.ProfilesUpdateFuture", "Result", nil, "received nil response and error")
}
if err == nil && p.Response.Response.StatusCode != http.StatusNoContent {
p, err = client.UpdateResponder(p.Response.Response)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.ProfilesUpdateFuture", "Result", p.Response.Response, "Failure responding to request")
}
}
return
}
return
}
// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client ProfilesClient) UpdateResponder(resp *http.Response) (result Profile, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
| NewProfilesClient |
differential.rs | // Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
//! Logging dataflows for events generated by differential dataflow.
use std::collections::HashMap;
use std::time::Duration;
use differential_dataflow::collection::AsCollection;
use differential_dataflow::logging::DifferentialEvent;
use differential_dataflow::operators::arrange::arrangement::Arrange;
use expr::{permutation_for_arrangement, MirScalarExpr};
use timely::communication::Allocate;
use timely::dataflow::channels::pact::Pipeline;
use timely::dataflow::operators::capture::EventLink;
use timely::dataflow::operators::generic::builder_rc::OperatorBuilder;
use timely::logging::WorkerIdentifier;
use super::{DifferentialLog, LogVariant};
use crate::activator::RcActivator;
use crate::arrangement::manager::RowSpine;
use crate::arrangement::KeysValsHandle;
use crate::logging::ConsolidateBuffer;
use crate::replay::MzReplay;
use repr::{Datum, DatumVec, Row, Timestamp};
/// Constructs the logging dataflow for differential logs.
///
/// Params
/// * `worker`: The Timely worker hosting the log analysis dataflow.
/// * `config`: Logging configuration
/// * `linked`: The source to read log events from.
/// * `activator`: A handle to acknowledge activations.
///
/// Returns a map from log variant to a tuple of a trace handle and a permutation to reconstruct
/// the original rows.
pub fn construct<A: Allocate>(
worker: &mut timely::worker::Worker<A>,
config: &dataflow_types::logging::LoggingConfig,
linked: std::rc::Rc<EventLink<Timestamp, (Duration, WorkerIdentifier, DifferentialEvent)>>,
activator: RcActivator,
) -> HashMap<LogVariant, KeysValsHandle> | {
let granularity_ms = std::cmp::max(1, config.granularity_ns / 1_000_000) as Timestamp;
let traces = worker.dataflow_named("Dataflow: differential logging", move |scope| {
let logs = Some(linked).mz_replay(
scope,
"differential logs",
Duration::from_nanos(config.granularity_ns as u64),
activator,
);
let mut demux =
OperatorBuilder::new("Differential Logging Demux".to_string(), scope.clone());
let mut input = demux.new_input(&logs, Pipeline);
let (mut arrangement_batches_out, arrangement_batches) = demux.new_output();
let (mut arrangement_records_out, arrangement_records) = demux.new_output();
let (mut sharing_out, sharing) = demux.new_output();
let mut demux_buffer = Vec::new();
demux.build(move |_capability| {
move |_frontiers| {
let arrangement_batches = arrangement_batches_out.activate();
let arrangement_records = arrangement_records_out.activate();
let sharing = sharing_out.activate();
let mut arrangement_batches_session =
ConsolidateBuffer::new(arrangement_batches, 0);
let mut arrangement_records_session =
ConsolidateBuffer::new(arrangement_records, 1);
let mut sharing_session = ConsolidateBuffer::new(sharing, 2);
input.for_each(|cap, data| {
data.swap(&mut demux_buffer);
for (time, worker, datum) in demux_buffer.drain(..) {
let time_ms = (((time.as_millis() as Timestamp / granularity_ms) + 1)
* granularity_ms) as Timestamp;
match datum {
DifferentialEvent::Batch(event) => {
arrangement_batches_session
.give(&cap, ((event.operator, worker), time_ms, 1));
arrangement_records_session.give(
&cap,
((event.operator, worker), time_ms, event.length as isize),
);
}
DifferentialEvent::Merge(event) => {
if let Some(done) = event.complete {
arrangement_batches_session
.give(&cap, ((event.operator, worker), time_ms, -1));
let diff = (done as isize)
- ((event.length1 + event.length2) as isize);
arrangement_records_session
.give(&cap, ((event.operator, worker), time_ms, diff));
}
}
DifferentialEvent::Drop(event) => {
arrangement_batches_session
.give(&cap, ((event.operator, worker), time_ms, -1));
arrangement_records_session.give(
&cap,
((event.operator, worker), time_ms, -(event.length as isize)),
);
}
DifferentialEvent::MergeShortfall(_) => {}
DifferentialEvent::TraceShare(event) => {
sharing_session
.give(&cap, ((event.operator, worker), time_ms, event.diff));
}
}
}
});
}
});
let arrangement_batches = arrangement_batches.as_collection().map({
move |(op, worker)| {
Row::pack_slice(&[Datum::Int64(op as i64), Datum::Int64(worker as i64)])
}
});
let arrangement_records = arrangement_records.as_collection().map({
move |(op, worker)| {
Row::pack_slice(&[Datum::Int64(op as i64), Datum::Int64(worker as i64)])
}
});
// Duration statistics derive from the non-rounded event times.
let sharing = sharing.as_collection().map({
move |(op, worker)| {
Row::pack_slice(&[Datum::Int64(op as i64), Datum::Int64(worker as i64)])
}
});
let logs = vec![
(
LogVariant::Differential(DifferentialLog::ArrangementBatches),
arrangement_batches,
),
(
LogVariant::Differential(DifferentialLog::ArrangementRecords),
arrangement_records,
),
(LogVariant::Differential(DifferentialLog::Sharing), sharing),
];
let mut result = std::collections::HashMap::new();
for (variant, collection) in logs {
if config.active_logs.contains_key(&variant) {
let key = variant.index_by();
let (_, value) = permutation_for_arrangement::<HashMap<_, _>>(
&key.iter()
.cloned()
.map(MirScalarExpr::Column)
.collect::<Vec<_>>(),
variant.desc().arity(),
);
let trace = collection
.map({
let mut row_packer = Row::default();
let mut datums = DatumVec::new();
move |row| {
let datums = datums.borrow_with(&row);
row_packer.extend(key.iter().map(|k| datums[*k]));
let row_key = row_packer.finish_and_reuse();
row_packer.extend(value.iter().map(|c| datums[*c]));
(row_key, row_packer.finish_and_reuse())
}
})
.arrange_named::<RowSpine<_, _, _, _>>(&format!("ArrangeByKey {:?}", variant))
.trace;
result.insert(variant, trace);
}
}
result
});
traces
} |
|
configuration.js | const DEFAULT_CONFIGURATION = {
fragmentTag: 'fragment',
selfClosingTags: ['meta'],
placeholderIdPrefix: 'c_',
contentIdPrefix: 'p_',
hideAttribute: 'p',
headTag: 'milla-head',
minifyJs: true,
minifyCss: true,
minifyHtml: true
};
| constructor() {
for (let prop in DEFAULT_CONFIGURATION) {
this[prop] = DEFAULT_CONFIGURATION[prop];
}
}
set(userConfigurations) {
for (let prop in userConfigurations) {
if (this.hasOwnProperty(prop)) {
this[prop] = userConfigurations[prop];
}
}
}
}
module.exports = new Configuration(); | class Configuration { |
replace_ElecNaming.py | #Daniel Sand
import pandas as pd
import numpy as np
fileName='/Tscores.csv'
newFileName='/Tscores_v3.csv'
df=pd.read_csv(fileName, sep=',')
#6 differnt electordes
oldFormat=['0-1','0-2','0-3','2-Jan','3-Jan','3-Feb']
newFormat=['0_1','0_2','0_3','2_1','3_1','3_2']
for iCont in range(0, len(oldFormat)):
currElec_old = oldFormat[iCont]
currElec_new = newFormat[iCont] | df.loc[df.Elec==currElec_old,'Elec']=currElec_new
df.to_csv(path_or_buf=newFileName) | |
ICloseable.ts | export interface ICloseable { | } | close(): this; |
CloseButton.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { black } from '../styles';
var closeButtonStyle = {
color: black,
lineHeight: '1rem',
fontSize: '1.5rem',
padding: '1rem',
cursor: 'pointer',
position: 'absolute',
right: 0, | var close = _ref.close;
return React.createElement(
'span',
{
title: 'Click or press Escape to dismiss.',
onClick: close,
style: closeButtonStyle
},
'\xD7'
);
}
export default CloseButton; | top: 0
};
function CloseButton(_ref) { |
parsing_types.rs | #[derive(Debug, PartialEq)]
pub struct RawHashlineParseData {
pub(super) indent_depth: usize,
pub(super) name: String,
pub(super) opts: String,
pub(super) args: String,
pub(super) comment: String,
}
#[derive(Debug, PartialEq)]
pub struct RawItemlineParseData {
pub(super) indent_depth: usize,
pub(super) item: String,
}
#[derive(Debug, PartialEq)]
pub enum Hashline {
OpenEnv(Environment),
PlainLine(String),
}
#[derive(Debug, PartialEq)]
pub struct Environment {
indent_depth: usize,
name: String,
opts: String,
comment: String,
is_list_like: bool,
}
#[inline]
fn is_a_list_environment(input: &str) -> bool |
impl From<RawHashlineParseData> for Hashline {
fn from(raw_hashline: RawHashlineParseData) -> Self {
if raw_hashline.args.trim().is_empty() {
// If no args are given, it's an environment
let is_list_like = is_a_list_environment(raw_hashline.name.as_ref());
Hashline::OpenEnv(Environment {
indent_depth: raw_hashline.indent_depth,
name: raw_hashline.name,
opts: raw_hashline.opts,
comment: raw_hashline.comment,
is_list_like,
})
} else {
// If there are some args, it's a single-line command
Hashline::PlainLine(format!(
r"{dummy:ind$}\{name}{opts}{{{args}}}{comment_sep}{comment}",
dummy = "",
ind = raw_hashline.indent_depth,
name = raw_hashline.name,
opts = raw_hashline.opts,
args = raw_hashline.args,
comment_sep = if raw_hashline.comment.is_empty() {
""
} else {
" "
},
comment = raw_hashline.comment.trim(),
))
}
}
}
impl From<RawItemlineParseData> for Hashline {
fn from(raw_itemline: RawItemlineParseData) -> Self {
Hashline::PlainLine(format!(
r"{dummy:ind$}\item{item_sep}{content}",
dummy = "",
ind = raw_itemline.indent_depth,
content = raw_itemline.item,
item_sep = if raw_itemline.item.is_empty() {
""
} else {
" "
},
))
}
}
impl Environment {
#[cfg(test)]
pub fn new(
indent_depth: usize,
name: String,
opts: String,
comment: String,
is_list_like: bool,
) -> Self {
Self {
indent_depth,
name,
opts,
comment,
is_list_like,
}
}
pub fn latex_begin(&self) -> String {
format!(
r"{dummy:ind$}\begin{{{name}}}{opts}{comment_sep}{comment}",
name = self.name,
opts = self.opts,
comment = self.comment,
dummy = "",
ind = self.indent_depth,
comment_sep = if self.comment.is_empty() { "" } else { " " },
)
}
pub fn latex_end(&self) -> String {
format!(
r"{dummy:ind$}\end{{{name}}}",
name = self.name,
dummy = "",
ind = self.indent_depth,
)
}
pub fn indent_depth(&self) -> usize {
self.indent_depth
}
pub fn is_list_like(&self) -> bool {
self.is_list_like
}
}
// LCOV_EXCL_START
#[cfg(test)]
mod tests {
#[test]
fn list_environment_recognition() {
use super::is_a_list_environment;
assert_eq!(is_a_list_environment("itemize"), true);
assert_eq!(is_a_list_environment("enumerate*"), true);
assert_eq!(is_a_list_environment(" description *"), true);
assert_eq!(is_a_list_environment(" descriptionitemize"), true);
assert_eq!(is_a_list_environment("item"), false);
assert_eq!(is_a_list_environment(" itemiz"), false);
assert_eq!(is_a_list_environment(" foobar"), false);
}
#[cfg(test)]
mod raw_hashline_parser_data_into_hashline {
use super::super::{Hashline, RawHashlineParseData};
#[test]
fn plain_lines() {
assert_eq!(
Hashline::from(RawHashlineParseData {
indent_depth: 0,
name: "foo".to_string(),
opts: "".to_string(),
args: "bar".to_string(),
comment: "".to_string()
}),
Hashline::PlainLine("\\foo{bar}".to_string())
);
assert_eq!(
Hashline::from(RawHashlineParseData {
indent_depth: 2,
name: "foo".to_string(),
opts: "".to_string(),
args: "bar".to_string(),
comment: "qux".to_string()
}),
Hashline::PlainLine(" \\foo{bar} qux".to_string())
);
assert_eq!(
Hashline::from(RawHashlineParseData {
indent_depth: 4,
name: "foo".to_string(),
opts: "bar".to_string(),
args: "qux".to_string(),
comment: "".to_string()
}),
Hashline::PlainLine(" \\foobar{qux}".to_string())
);
}
#[test]
fn environments() {
use super::super::Environment;
assert_eq!(
Hashline::from(RawHashlineParseData {
indent_depth: 0,
name: "foo".to_string(),
opts: "bar".to_string(),
args: "".to_string(),
comment: "".to_string()
}),
Hashline::OpenEnv(Environment {
indent_depth: 0,
name: "foo".to_string(),
opts: "bar".to_string(),
comment: "".to_string(),
is_list_like: false,
})
);
assert_eq!(
Hashline::from(RawHashlineParseData {
indent_depth: 2,
name: "foo".to_string(),
opts: "".to_string(),
args: "".to_string(),
comment: "bar".to_string()
}),
Hashline::OpenEnv(Environment {
indent_depth: 2,
name: "foo".to_string(),
opts: "".to_string(),
comment: "bar".to_string(),
is_list_like: false,
})
);
assert_eq!(
Hashline::from(RawHashlineParseData {
indent_depth: 4,
name: "foo".to_string(),
opts: "bar".to_string(),
args: "".to_string(),
comment: "qux".to_string()
}),
Hashline::OpenEnv(Environment {
indent_depth: 4,
name: "foo".to_string(),
opts: "bar".to_string(),
comment: "qux".to_string(),
is_list_like: false,
})
);
assert_eq!(
Hashline::from(RawHashlineParseData {
indent_depth: 0,
name: "itemize".to_string(),
opts: "bar".to_string(),
args: "".to_string(),
comment: "qux".to_string()
}),
Hashline::OpenEnv(Environment {
indent_depth: 0,
name: "itemize".to_string(),
opts: "bar".to_string(),
comment: "qux".to_string(),
is_list_like: true,
})
);
}
}
#[test]
fn raw_itemline_parser_data_into_hashline() {
use super::{Hashline, RawItemlineParseData};
assert_eq!(
Hashline::from(RawItemlineParseData {
indent_depth: 0,
item: "".to_string()
}),
Hashline::PlainLine(r"\item".to_string())
);
assert_eq!(
Hashline::from(RawItemlineParseData {
indent_depth: 0,
item: "".to_string()
}),
Hashline::PlainLine(r"\item".to_string())
);
assert_eq!(
Hashline::from(RawItemlineParseData {
indent_depth: 2,
item: "".to_string()
}),
Hashline::PlainLine(r" \item".to_string())
);
assert_eq!(
Hashline::from(RawItemlineParseData {
indent_depth: 0,
item: "foo".to_string()
}),
Hashline::PlainLine(r"\item foo".to_string())
);
assert_eq!(
Hashline::from(RawItemlineParseData {
indent_depth: 3,
item: "bar".to_string()
}),
Hashline::PlainLine(r" \item bar".to_string())
);
assert_eq!(
Hashline::from(RawItemlineParseData {
indent_depth: 0,
item: "**".to_string()
}),
Hashline::PlainLine(r"\item **".to_string())
);
}
#[test]
fn environment_methods() {
use super::Environment;
let env_1 = Environment {
indent_depth: 0,
name: "foo".to_string(),
opts: "bar".to_string(),
comment: "% baz".to_string(),
is_list_like: true,
};
assert_eq!(env_1.latex_begin(), "\\begin{foo}bar % baz");
assert_eq!(env_1.latex_end(), "\\end{foo}");
assert_eq!(env_1.is_list_like(), true);
assert_eq!(env_1.indent_depth(), 0);
let env_2 = Environment {
indent_depth: 2,
name: "abc".to_string(),
opts: "def".to_string(),
comment: "".to_string(),
is_list_like: false,
};
assert_eq!(env_2.latex_begin(), " \\begin{abc}def");
assert_eq!(env_2.latex_end(), " \\end{abc}");
assert_eq!(env_2.is_list_like(), false);
assert_eq!(env_2.indent_depth(), 2);
}
}
// LCOV_EXCL_STOP
| {
fn parser(input: &str) -> nom::IResult<&str, &str> {
use nom::branch::alt;
use nom::bytes::complete::tag;
alt((tag("itemize"), tag("enumerate"), tag("description")))(input)
}
parser(input.trim_start()).is_ok()
} |
body.js | d3.select("body").append("div").html("hi"); |
||
0001_initial.py | # Generated by Django 2.2.5 on 2019-10-07 08:27
from django.conf import settings |
class Migration(migrations.Migration):
initial = True
dependencies = [
('species', '0002_auto_20190908_0902'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Record',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
('updated_at', models.DateTimeField(default=django.utils.timezone.now)),
('species', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='species.Species')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
] | from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
|
tasks.py | from __future__ import absolute_import, unicode_literals
from django.conf import settings
from .models import Schedule
from celery.task.schedules import crontab
from celery import shared_task
from celery import task
import logging
import time, datetime
import requests
logger = logging.getLogger('portia_dashboard')
@task
def | ():
schedules = Schedule.objects.all()
for schedule in schedules:
nowTimestamp = int(time.time() * 1000)
if (nowTimestamp - schedule.date_update > schedule.interval * 1000) and (schedule.times > 0 or schedule.times < 0 ) :
if schedule.start_time > 0 and schedule.start_time > nowTimestamp:
continue
schedule_data = {
'project': schedule.project,
'spider': schedule.spider
}
request = requests.post(settings.SCHEDULE_URL, data=schedule_data)
if request.status_code == 200:
schedule.date_update = nowTimestamp
schedule.times = schedule.times -1 if ( schedule.times > 0 ) else schedule.times
schedule.save()
| schedule_monitor |
deploymentConfigs.go | /*
Copyright 2019 The Fossul 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 k8s
import (
"context"
"fmt"
"time"
apps "github.com/openshift/api/apps/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/util/retry"
)
func GetDeploymentConfig(namespace, deploymentConfigName, accessWithinCluster string) (*apps.DeploymentConfig, error) {
var deploymentConfig *apps.DeploymentConfig
client, err := getDeploymentConfigClient(accessWithinCluster)
if err != nil {
return deploymentConfig, err
}
deploymentConfig, err = client.DeploymentConfigs(namespace).Get(context.Background(), deploymentConfigName, metav1.GetOptions{})
if err != nil {
return deploymentConfig, err
}
return deploymentConfig, nil
}
func GetDeploymentConfigScaleInteger(namespace, deploymentConfigName, accessWithinCluster string) (int32, error) {
deploymentConfig, err := GetDeploymentConfig(namespace, deploymentConfigName, accessWithinCluster)
if err != nil {
return 0, err
}
return deploymentConfig.Spec.Replicas, nil
}
func ScaleDownDeploymentConfig(namespace, deploymentConfigName, accessWithinCluster string, size int32, t int) error {
client, err := getDeploymentConfigClient(accessWithinCluster)
if err != nil {
return err
}
deploymentConfig, err := GetDeploymentConfig(namespace, deploymentConfigName, accessWithinCluster)
if err != nil {
return err
}
deploymentConfig.Spec.Replicas = size
_, err = client.DeploymentConfigs(namespace).Update(context.Background(), deploymentConfig, metav1.UpdateOptions{})
if err != nil {
return err
}
var poll = 5 * time.Second
timeout := time.Duration(t) * time.Second
start := time.Now()
fmt.Printf("[DEBUG] Waiting up to %v for deployment to be scaled to %d\n", timeout, size)
return wait.PollImmediate(poll, timeout, func() (bool, error) {
deploymentConfig, err := GetDeploymentConfig(namespace, deploymentConfigName, accessWithinCluster)
if err != nil {
return false, nil
}
readyReplicas := deploymentConfig.Status.ReadyReplicas
numberReplicas := deploymentConfig.Status.Replicas
fmt.Printf("[DEBUG] Waiting for replicas to be scaled down [%d of %d] (%d seconds elapsed)\n", readyReplicas, numberReplicas, int(time.Since(start).Seconds()))
if readyReplicas == 0 {
return true, nil
}
return false, nil
})
}
func ScaleUpDeploymentConfig(namespace, deploymentConfigName, accessWithinCluster string, size int32, t int) error {
client, err := getDeploymentConfigClient(accessWithinCluster)
if err != nil {
return err
}
deploymentConfig, err := GetDeploymentConfig(namespace, deploymentConfigName, accessWithinCluster)
if err != nil {
return err
}
deploymentConfig.Spec.Replicas = size
_, err = client.DeploymentConfigs(namespace).Update(context.Background(), deploymentConfig, metav1.UpdateOptions{})
if err != nil {
return err
}
var poll = 5 * time.Second
timeout := time.Duration(t) * time.Second
start := time.Now()
fmt.Printf("[DEBUG] Waiting up to %v for deployment to be scaled to %d\n", timeout, size)
return wait.PollImmediate(poll, timeout, func() (bool, error) {
deploymentConfig, err := GetDeploymentConfig(namespace, deploymentConfigName, accessWithinCluster)
if err != nil {
return false, nil
}
readyReplicas := deploymentConfig.Status.ReadyReplicas
fmt.Printf("[DEBUG] Waiting for replicas to be scaled up [%d of %d] (%d seconds elapsed)\n", readyReplicas, size, int(time.Since(start).Seconds()))
if readyReplicas == size {
return true, nil
}
return false, nil
})
}
func UpdateDeploymentConfigVolume(pvcName, restorePvcName, namespace, deploymentConfigName, accessWithinCluster string) error {
client, err := getDeploymentConfigClient(accessWithinCluster)
if err != nil {
return err
}
deploymentConfig, err := GetDeploymentConfig(namespace, deploymentConfigName, accessWithinCluster)
if err != nil {
return err
}
//volumes := deploymentConfig.Spec.Template.Spec.Volumes
//for _, volume := range volumes {
// fmt.Println("[DEBUG] Updating pv [" + volume.Name + "] with new pvc [" + pvcName + "]")
// volume.PersistentVolumeClaim = GeneratePersistentVolumeClaimVolumeName(pvcName)
// fmt.Println("here 123 " + pvcName + " " + volume.PersistentVolumeClaim.ClaimName + " " + deploymentConfig.Spec.Template.Spec.Volumes[0].PersistentVolumeClaim.ClaimName)
//}
retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {
// Retrieve the latest version of Deployment before attempting update
// RetryOnConflict uses exponential backoff to avoid exhausting the apiserver
for _, volume := range deploymentConfig.Spec.Template.Spec.Volumes {
if volume.Name == pvcName {
volume.PersistentVolumeClaim.ClaimName = restorePvcName
}
}
_, updateErr := client.DeploymentConfigs(namespace).Update(context.Background(), deploymentConfig, metav1.UpdateOptions{})
return updateErr
})
if retryErr != nil |
//deploymentConfig.Spec.Template.Spec.Volumes[0].PersistentVolumeClaim = GeneratePersistentVolumeClaimVolumeName(pvcName)
// Should switch to patch at some point, below is example
//dcLabelPatchPayload, err := json.Marshal(apps.DeploymentConfig{
// ObjectMeta: metav1.ObjectMeta{
// Label: map[string]string{"spec": "patched"},
// },
//})
//testDcPatched, err := client.DeploymentConfigs(namespace).Patch(context.Background(), deploymentConfigName, types.StrategicMergePatchType, []byte(rcLabelPatchPayload), metav1.PatchOptions{})
//_, err = client.DeploymentConfigs(namespace).Update(context.Background(), deploymentConfig, metav1.UpdateOptions{})
//if err != nil {
// return err
//}
return nil
}
| {
return err
} |
compctrl.rs | #[doc = "Register `COMPCTRL[%s]` reader"]
pub struct R(crate::R<COMPCTRL_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<COMPCTRL_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<COMPCTRL_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<COMPCTRL_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `COMPCTRL[%s]` writer"]
pub struct W(crate::W<COMPCTRL_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<COMPCTRL_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<COMPCTRL_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<COMPCTRL_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `ENABLE` reader - Enable"]
pub struct ENABLE_R(crate::FieldReader<bool, bool>);
impl ENABLE_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
ENABLE_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for ENABLE_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `ENABLE` writer - Enable"]
pub struct ENABLE_W<'a> {
w: &'a mut W,
}
impl<'a> ENABLE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | ((value as u32 & 0x01) << 1);
self.w
}
}
#[doc = "Field `SINGLE` reader - Single-Shot Mode"]
pub struct SINGLE_R(crate::FieldReader<bool, bool>);
impl SINGLE_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
SINGLE_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for SINGLE_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `SINGLE` writer - Single-Shot Mode"]
pub struct SINGLE_W<'a> {
w: &'a mut W,
}
impl<'a> SINGLE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | ((value as u32 & 0x01) << 2);
self.w
}
}
#[doc = "Interrupt Selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum INTSEL_A {
#[doc = "0: Interrupt on comparator output toggle"]
TOGGLE = 0,
#[doc = "1: Interrupt on comparator output rising"]
RISING = 1,
#[doc = "2: Interrupt on comparator output falling"]
FALLING = 2,
#[doc = "3: Interrupt on end of comparison (single-shot mode only)"]
EOC = 3,
}
impl From<INTSEL_A> for u8 {
#[inline(always)]
fn from(variant: INTSEL_A) -> Self {
variant as _
}
}
#[doc = "Field `INTSEL` reader - Interrupt Selection"]
pub struct INTSEL_R(crate::FieldReader<u8, INTSEL_A>);
impl INTSEL_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
INTSEL_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> INTSEL_A {
match self.bits {
0 => INTSEL_A::TOGGLE,
1 => INTSEL_A::RISING,
2 => INTSEL_A::FALLING,
3 => INTSEL_A::EOC,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `TOGGLE`"]
#[inline(always)]
pub fn is_toggle(&self) -> bool {
**self == INTSEL_A::TOGGLE
}
#[doc = "Checks if the value of the field is `RISING`"]
#[inline(always)]
pub fn is_rising(&self) -> bool {
**self == INTSEL_A::RISING
}
#[doc = "Checks if the value of the field is `FALLING`"]
#[inline(always)]
pub fn is_falling(&self) -> bool {
**self == INTSEL_A::FALLING
}
#[doc = "Checks if the value of the field is `EOC`"]
#[inline(always)]
pub fn is_eoc(&self) -> bool {
**self == INTSEL_A::EOC
}
}
impl core::ops::Deref for INTSEL_R {
type Target = crate::FieldReader<u8, INTSEL_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `INTSEL` writer - Interrupt Selection"]
pub struct INTSEL_W<'a> {
w: &'a mut W,
}
impl<'a> INTSEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: INTSEL_A) -> &'a mut W {
self.bits(variant.into())
}
#[doc = "Interrupt on comparator output toggle"]
#[inline(always)]
pub fn toggle(self) -> &'a mut W {
self.variant(INTSEL_A::TOGGLE)
}
#[doc = "Interrupt on comparator output rising"]
#[inline(always)]
pub fn rising(self) -> &'a mut W {
self.variant(INTSEL_A::RISING)
}
#[doc = "Interrupt on comparator output falling"]
#[inline(always)]
pub fn falling(self) -> &'a mut W {
self.variant(INTSEL_A::FALLING)
}
#[doc = "Interrupt on end of comparison (single-shot mode only)"]
#[inline(always)]
pub fn eoc(self) -> &'a mut W {
self.variant(INTSEL_A::EOC)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 3)) | ((value as u32 & 0x03) << 3);
self.w
}
}
#[doc = "Field `RUNSTDBY` reader - Run in Standby"]
pub struct RUNSTDBY_R(crate::FieldReader<bool, bool>);
impl RUNSTDBY_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
RUNSTDBY_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for RUNSTDBY_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `RUNSTDBY` writer - Run in Standby"]
pub struct RUNSTDBY_W<'a> {
w: &'a mut W,
}
impl<'a> RUNSTDBY_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | ((value as u32 & 0x01) << 6);
self.w
}
}
#[doc = "Negative Input Mux Selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum MUXNEG_A {
#[doc = "0: I/O pin 0"]
PIN0 = 0,
#[doc = "1: I/O pin 1"]
PIN1 = 1,
#[doc = "2: I/O pin 2"]
PIN2 = 2,
#[doc = "3: I/O pin 3"]
PIN3 = 3,
#[doc = "4: Ground"]
GND = 4,
#[doc = "5: VDD scaler"]
VSCALE = 5,
#[doc = "6: Internal bandgap voltage"]
BANDGAP = 6,
#[doc = "7: DAC output"]
DAC = 7,
}
impl From<MUXNEG_A> for u8 {
#[inline(always)]
fn from(variant: MUXNEG_A) -> Self {
variant as _
}
}
#[doc = "Field `MUXNEG` reader - Negative Input Mux Selection"]
pub struct MUXNEG_R(crate::FieldReader<u8, MUXNEG_A>);
impl MUXNEG_R { | pub(crate) fn new(bits: u8) -> Self {
MUXNEG_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MUXNEG_A {
match self.bits {
0 => MUXNEG_A::PIN0,
1 => MUXNEG_A::PIN1,
2 => MUXNEG_A::PIN2,
3 => MUXNEG_A::PIN3,
4 => MUXNEG_A::GND,
5 => MUXNEG_A::VSCALE,
6 => MUXNEG_A::BANDGAP,
7 => MUXNEG_A::DAC,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `PIN0`"]
#[inline(always)]
pub fn is_pin0(&self) -> bool {
**self == MUXNEG_A::PIN0
}
#[doc = "Checks if the value of the field is `PIN1`"]
#[inline(always)]
pub fn is_pin1(&self) -> bool {
**self == MUXNEG_A::PIN1
}
#[doc = "Checks if the value of the field is `PIN2`"]
#[inline(always)]
pub fn is_pin2(&self) -> bool {
**self == MUXNEG_A::PIN2
}
#[doc = "Checks if the value of the field is `PIN3`"]
#[inline(always)]
pub fn is_pin3(&self) -> bool {
**self == MUXNEG_A::PIN3
}
#[doc = "Checks if the value of the field is `GND`"]
#[inline(always)]
pub fn is_gnd(&self) -> bool {
**self == MUXNEG_A::GND
}
#[doc = "Checks if the value of the field is `VSCALE`"]
#[inline(always)]
pub fn is_vscale(&self) -> bool {
**self == MUXNEG_A::VSCALE
}
#[doc = "Checks if the value of the field is `BANDGAP`"]
#[inline(always)]
pub fn is_bandgap(&self) -> bool {
**self == MUXNEG_A::BANDGAP
}
#[doc = "Checks if the value of the field is `DAC`"]
#[inline(always)]
pub fn is_dac(&self) -> bool {
**self == MUXNEG_A::DAC
}
}
impl core::ops::Deref for MUXNEG_R {
type Target = crate::FieldReader<u8, MUXNEG_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `MUXNEG` writer - Negative Input Mux Selection"]
pub struct MUXNEG_W<'a> {
w: &'a mut W,
}
impl<'a> MUXNEG_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MUXNEG_A) -> &'a mut W {
self.bits(variant.into())
}
#[doc = "I/O pin 0"]
#[inline(always)]
pub fn pin0(self) -> &'a mut W {
self.variant(MUXNEG_A::PIN0)
}
#[doc = "I/O pin 1"]
#[inline(always)]
pub fn pin1(self) -> &'a mut W {
self.variant(MUXNEG_A::PIN1)
}
#[doc = "I/O pin 2"]
#[inline(always)]
pub fn pin2(self) -> &'a mut W {
self.variant(MUXNEG_A::PIN2)
}
#[doc = "I/O pin 3"]
#[inline(always)]
pub fn pin3(self) -> &'a mut W {
self.variant(MUXNEG_A::PIN3)
}
#[doc = "Ground"]
#[inline(always)]
pub fn gnd(self) -> &'a mut W {
self.variant(MUXNEG_A::GND)
}
#[doc = "VDD scaler"]
#[inline(always)]
pub fn vscale(self) -> &'a mut W {
self.variant(MUXNEG_A::VSCALE)
}
#[doc = "Internal bandgap voltage"]
#[inline(always)]
pub fn bandgap(self) -> &'a mut W {
self.variant(MUXNEG_A::BANDGAP)
}
#[doc = "DAC output"]
#[inline(always)]
pub fn dac(self) -> &'a mut W {
self.variant(MUXNEG_A::DAC)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 8)) | ((value as u32 & 0x07) << 8);
self.w
}
}
#[doc = "Positive Input Mux Selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum MUXPOS_A {
#[doc = "0: I/O pin 0"]
PIN0 = 0,
#[doc = "1: I/O pin 1"]
PIN1 = 1,
#[doc = "2: I/O pin 2"]
PIN2 = 2,
#[doc = "3: I/O pin 3"]
PIN3 = 3,
#[doc = "4: VDD Scaler"]
VSCALE = 4,
}
impl From<MUXPOS_A> for u8 {
#[inline(always)]
fn from(variant: MUXPOS_A) -> Self {
variant as _
}
}
#[doc = "Field `MUXPOS` reader - Positive Input Mux Selection"]
pub struct MUXPOS_R(crate::FieldReader<u8, MUXPOS_A>);
impl MUXPOS_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
MUXPOS_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<MUXPOS_A> {
match self.bits {
0 => Some(MUXPOS_A::PIN0),
1 => Some(MUXPOS_A::PIN1),
2 => Some(MUXPOS_A::PIN2),
3 => Some(MUXPOS_A::PIN3),
4 => Some(MUXPOS_A::VSCALE),
_ => None,
}
}
#[doc = "Checks if the value of the field is `PIN0`"]
#[inline(always)]
pub fn is_pin0(&self) -> bool {
**self == MUXPOS_A::PIN0
}
#[doc = "Checks if the value of the field is `PIN1`"]
#[inline(always)]
pub fn is_pin1(&self) -> bool {
**self == MUXPOS_A::PIN1
}
#[doc = "Checks if the value of the field is `PIN2`"]
#[inline(always)]
pub fn is_pin2(&self) -> bool {
**self == MUXPOS_A::PIN2
}
#[doc = "Checks if the value of the field is `PIN3`"]
#[inline(always)]
pub fn is_pin3(&self) -> bool {
**self == MUXPOS_A::PIN3
}
#[doc = "Checks if the value of the field is `VSCALE`"]
#[inline(always)]
pub fn is_vscale(&self) -> bool {
**self == MUXPOS_A::VSCALE
}
}
impl core::ops::Deref for MUXPOS_R {
type Target = crate::FieldReader<u8, MUXPOS_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `MUXPOS` writer - Positive Input Mux Selection"]
pub struct MUXPOS_W<'a> {
w: &'a mut W,
}
impl<'a> MUXPOS_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MUXPOS_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "I/O pin 0"]
#[inline(always)]
pub fn pin0(self) -> &'a mut W {
self.variant(MUXPOS_A::PIN0)
}
#[doc = "I/O pin 1"]
#[inline(always)]
pub fn pin1(self) -> &'a mut W {
self.variant(MUXPOS_A::PIN1)
}
#[doc = "I/O pin 2"]
#[inline(always)]
pub fn pin2(self) -> &'a mut W {
self.variant(MUXPOS_A::PIN2)
}
#[doc = "I/O pin 3"]
#[inline(always)]
pub fn pin3(self) -> &'a mut W {
self.variant(MUXPOS_A::PIN3)
}
#[doc = "VDD Scaler"]
#[inline(always)]
pub fn vscale(self) -> &'a mut W {
self.variant(MUXPOS_A::VSCALE)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 12)) | ((value as u32 & 0x07) << 12);
self.w
}
}
#[doc = "Field `SWAP` reader - Swap Inputs and Invert"]
pub struct SWAP_R(crate::FieldReader<bool, bool>);
impl SWAP_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
SWAP_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for SWAP_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `SWAP` writer - Swap Inputs and Invert"]
pub struct SWAP_W<'a> {
w: &'a mut W,
}
impl<'a> SWAP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | ((value as u32 & 0x01) << 15);
self.w
}
}
#[doc = "Speed Selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum SPEED_A {
#[doc = "0: Low speed"]
LOW = 0,
#[doc = "3: High speed"]
HIGH = 3,
}
impl From<SPEED_A> for u8 {
#[inline(always)]
fn from(variant: SPEED_A) -> Self {
variant as _
}
}
#[doc = "Field `SPEED` reader - Speed Selection"]
pub struct SPEED_R(crate::FieldReader<u8, SPEED_A>);
impl SPEED_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
SPEED_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<SPEED_A> {
match self.bits {
0 => Some(SPEED_A::LOW),
3 => Some(SPEED_A::HIGH),
_ => None,
}
}
#[doc = "Checks if the value of the field is `LOW`"]
#[inline(always)]
pub fn is_low(&self) -> bool {
**self == SPEED_A::LOW
}
#[doc = "Checks if the value of the field is `HIGH`"]
#[inline(always)]
pub fn is_high(&self) -> bool {
**self == SPEED_A::HIGH
}
}
impl core::ops::Deref for SPEED_R {
type Target = crate::FieldReader<u8, SPEED_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `SPEED` writer - Speed Selection"]
pub struct SPEED_W<'a> {
w: &'a mut W,
}
impl<'a> SPEED_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SPEED_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Low speed"]
#[inline(always)]
pub fn low(self) -> &'a mut W {
self.variant(SPEED_A::LOW)
}
#[doc = "High speed"]
#[inline(always)]
pub fn high(self) -> &'a mut W {
self.variant(SPEED_A::HIGH)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 16)) | ((value as u32 & 0x03) << 16);
self.w
}
}
#[doc = "Field `HYSTEN` reader - Hysteresis Enable"]
pub struct HYSTEN_R(crate::FieldReader<bool, bool>);
impl HYSTEN_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
HYSTEN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for HYSTEN_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `HYSTEN` writer - Hysteresis Enable"]
pub struct HYSTEN_W<'a> {
w: &'a mut W,
}
impl<'a> HYSTEN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 19)) | ((value as u32 & 0x01) << 19);
self.w
}
}
#[doc = "Filter Length\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum FLEN_A {
#[doc = "0: No filtering"]
OFF = 0,
#[doc = "1: 3-bit majority function (2 of 3)"]
MAJ3 = 1,
#[doc = "2: 5-bit majority function (3 of 5)"]
MAJ5 = 2,
}
impl From<FLEN_A> for u8 {
#[inline(always)]
fn from(variant: FLEN_A) -> Self {
variant as _
}
}
#[doc = "Field `FLEN` reader - Filter Length"]
pub struct FLEN_R(crate::FieldReader<u8, FLEN_A>);
impl FLEN_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
FLEN_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<FLEN_A> {
match self.bits {
0 => Some(FLEN_A::OFF),
1 => Some(FLEN_A::MAJ3),
2 => Some(FLEN_A::MAJ5),
_ => None,
}
}
#[doc = "Checks if the value of the field is `OFF`"]
#[inline(always)]
pub fn is_off(&self) -> bool {
**self == FLEN_A::OFF
}
#[doc = "Checks if the value of the field is `MAJ3`"]
#[inline(always)]
pub fn is_maj3(&self) -> bool {
**self == FLEN_A::MAJ3
}
#[doc = "Checks if the value of the field is `MAJ5`"]
#[inline(always)]
pub fn is_maj5(&self) -> bool {
**self == FLEN_A::MAJ5
}
}
impl core::ops::Deref for FLEN_R {
type Target = crate::FieldReader<u8, FLEN_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `FLEN` writer - Filter Length"]
pub struct FLEN_W<'a> {
w: &'a mut W,
}
impl<'a> FLEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: FLEN_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "No filtering"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(FLEN_A::OFF)
}
#[doc = "3-bit majority function (2 of 3)"]
#[inline(always)]
pub fn maj3(self) -> &'a mut W {
self.variant(FLEN_A::MAJ3)
}
#[doc = "5-bit majority function (3 of 5)"]
#[inline(always)]
pub fn maj5(self) -> &'a mut W {
self.variant(FLEN_A::MAJ5)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 24)) | ((value as u32 & 0x07) << 24);
self.w
}
}
#[doc = "Output\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum OUT_A {
#[doc = "0: The output of COMPn is not routed to the COMPn I/O port"]
OFF = 0,
#[doc = "1: The asynchronous output of COMPn is routed to the COMPn I/O port"]
ASYNC = 1,
#[doc = "2: The synchronous output (including filtering) of COMPn is routed to the COMPn I/O port"]
SYNC = 2,
}
impl From<OUT_A> for u8 {
#[inline(always)]
fn from(variant: OUT_A) -> Self {
variant as _
}
}
#[doc = "Field `OUT` reader - Output"]
pub struct OUT_R(crate::FieldReader<u8, OUT_A>);
impl OUT_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
OUT_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<OUT_A> {
match self.bits {
0 => Some(OUT_A::OFF),
1 => Some(OUT_A::ASYNC),
2 => Some(OUT_A::SYNC),
_ => None,
}
}
#[doc = "Checks if the value of the field is `OFF`"]
#[inline(always)]
pub fn is_off(&self) -> bool {
**self == OUT_A::OFF
}
#[doc = "Checks if the value of the field is `ASYNC`"]
#[inline(always)]
pub fn is_async(&self) -> bool {
**self == OUT_A::ASYNC
}
#[doc = "Checks if the value of the field is `SYNC`"]
#[inline(always)]
pub fn is_sync(&self) -> bool {
**self == OUT_A::SYNC
}
}
impl core::ops::Deref for OUT_R {
type Target = crate::FieldReader<u8, OUT_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `OUT` writer - Output"]
pub struct OUT_W<'a> {
w: &'a mut W,
}
impl<'a> OUT_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: OUT_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "The output of COMPn is not routed to the COMPn I/O port"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(OUT_A::OFF)
}
#[doc = "The asynchronous output of COMPn is routed to the COMPn I/O port"]
#[inline(always)]
pub fn async_(self) -> &'a mut W {
self.variant(OUT_A::ASYNC)
}
#[doc = "The synchronous output (including filtering) of COMPn is routed to the COMPn I/O port"]
#[inline(always)]
pub fn sync(self) -> &'a mut W {
self.variant(OUT_A::SYNC)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 28)) | ((value as u32 & 0x03) << 28);
self.w
}
}
impl R {
#[doc = "Bit 1 - Enable"]
#[inline(always)]
pub fn enable(&self) -> ENABLE_R {
ENABLE_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Single-Shot Mode"]
#[inline(always)]
pub fn single(&self) -> SINGLE_R {
SINGLE_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bits 3:4 - Interrupt Selection"]
#[inline(always)]
pub fn intsel(&self) -> INTSEL_R {
INTSEL_R::new(((self.bits >> 3) & 0x03) as u8)
}
#[doc = "Bit 6 - Run in Standby"]
#[inline(always)]
pub fn runstdby(&self) -> RUNSTDBY_R {
RUNSTDBY_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bits 8:10 - Negative Input Mux Selection"]
#[inline(always)]
pub fn muxneg(&self) -> MUXNEG_R {
MUXNEG_R::new(((self.bits >> 8) & 0x07) as u8)
}
#[doc = "Bits 12:14 - Positive Input Mux Selection"]
#[inline(always)]
pub fn muxpos(&self) -> MUXPOS_R {
MUXPOS_R::new(((self.bits >> 12) & 0x07) as u8)
}
#[doc = "Bit 15 - Swap Inputs and Invert"]
#[inline(always)]
pub fn swap(&self) -> SWAP_R {
SWAP_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bits 16:17 - Speed Selection"]
#[inline(always)]
pub fn speed(&self) -> SPEED_R {
SPEED_R::new(((self.bits >> 16) & 0x03) as u8)
}
#[doc = "Bit 19 - Hysteresis Enable"]
#[inline(always)]
pub fn hysten(&self) -> HYSTEN_R {
HYSTEN_R::new(((self.bits >> 19) & 0x01) != 0)
}
#[doc = "Bits 24:26 - Filter Length"]
#[inline(always)]
pub fn flen(&self) -> FLEN_R {
FLEN_R::new(((self.bits >> 24) & 0x07) as u8)
}
#[doc = "Bits 28:29 - Output"]
#[inline(always)]
pub fn out(&self) -> OUT_R {
OUT_R::new(((self.bits >> 28) & 0x03) as u8)
}
}
impl W {
#[doc = "Bit 1 - Enable"]
#[inline(always)]
pub fn enable(&mut self) -> ENABLE_W {
ENABLE_W { w: self }
}
#[doc = "Bit 2 - Single-Shot Mode"]
#[inline(always)]
pub fn single(&mut self) -> SINGLE_W {
SINGLE_W { w: self }
}
#[doc = "Bits 3:4 - Interrupt Selection"]
#[inline(always)]
pub fn intsel(&mut self) -> INTSEL_W {
INTSEL_W { w: self }
}
#[doc = "Bit 6 - Run in Standby"]
#[inline(always)]
pub fn runstdby(&mut self) -> RUNSTDBY_W {
RUNSTDBY_W { w: self }
}
#[doc = "Bits 8:10 - Negative Input Mux Selection"]
#[inline(always)]
pub fn muxneg(&mut self) -> MUXNEG_W {
MUXNEG_W { w: self }
}
#[doc = "Bits 12:14 - Positive Input Mux Selection"]
#[inline(always)]
pub fn muxpos(&mut self) -> MUXPOS_W {
MUXPOS_W { w: self }
}
#[doc = "Bit 15 - Swap Inputs and Invert"]
#[inline(always)]
pub fn swap(&mut self) -> SWAP_W {
SWAP_W { w: self }
}
#[doc = "Bits 16:17 - Speed Selection"]
#[inline(always)]
pub fn speed(&mut self) -> SPEED_W {
SPEED_W { w: self }
}
#[doc = "Bit 19 - Hysteresis Enable"]
#[inline(always)]
pub fn hysten(&mut self) -> HYSTEN_W {
HYSTEN_W { w: self }
}
#[doc = "Bits 24:26 - Filter Length"]
#[inline(always)]
pub fn flen(&mut self) -> FLEN_W {
FLEN_W { w: self }
}
#[doc = "Bits 28:29 - Output"]
#[inline(always)]
pub fn out(&mut self) -> OUT_W {
OUT_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Comparator Control n\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [compctrl](index.html) module"]
pub struct COMPCTRL_SPEC;
impl crate::RegisterSpec for COMPCTRL_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [compctrl::R](R) reader structure"]
impl crate::Readable for COMPCTRL_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [compctrl::W](W) writer structure"]
impl crate::Writable for COMPCTRL_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets COMPCTRL[%s]
to value 0"]
impl crate::Resettable for COMPCTRL_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
} | #[inline(always)] |
runner_test.go | package oobmigration
import (
"context"
"errors"
"sync"
"testing"
"time"
"github.com/derision-test/glock"
"github.com/google/go-cmp/cmp"
"github.com/sourcegraph/sourcegraph/internal/observation"
)
func TestRunner(t *testing.T) {
store := NewMockStoreIface()
ticker := glock.NewMockTicker(time.Second)
refreshTicker := glock.NewMockTicker(time.Second * 30)
store.ListFunc.SetDefaultReturn([]Migration{
{ID: 1, Progress: 0.5},
}, nil)
runner := newRunner(store, refreshTicker, &observation.TestContext)
migrator := NewMockMigrator()
migrator.ProgressFunc.SetDefaultReturn(0.5, nil)
if err := runner.Register(1, migrator, MigratorOptions{ticker: ticker}); err != nil {
t.Fatalf("unexpected error registering migrator: %s", err)
}
go runner.Start()
tickN(ticker, 3)
runner.Stop()
if callCount := len(migrator.UpFunc.History()); callCount != 3 {
t.Errorf("unexpected number of calls to Up. want=%d have=%d", 3, callCount)
}
if callCount := len(migrator.DownFunc.History()); callCount != 0 {
t.Errorf("unexpected number of calls to Down. want=%d have=%d", 0, callCount)
}
}
func TestRunnerError(t *testing.T) {
store := NewMockStoreIface()
ticker := glock.NewMockTicker(time.Second)
refreshTicker := glock.NewMockTicker(time.Second * 30)
store.ListFunc.SetDefaultReturn([]Migration{
{ID: 1, Progress: 0.5},
}, nil)
runner := newRunner(store, refreshTicker, &observation.TestContext)
migrator := NewMockMigrator()
migrator.ProgressFunc.SetDefaultReturn(0.5, nil)
migrator.UpFunc.SetDefaultReturn(errors.New("uh-oh"))
if err := runner.Register(1, migrator, MigratorOptions{ticker: ticker}); err != nil {
t.Fatalf("unexpected error registering migrator: %s", err)
}
go runner.Start()
tickN(ticker, 1)
runner.Stop()
if calls := store.AddErrorFunc.history; len(calls) != 1 {
t.Fatalf("unexpected number of calls to AddError. want=%d have=%d", 1, len(calls))
} else {
if calls[0].Arg1 != 1 {
t.Errorf("unexpected migrationId. want=%d have=%d", 1, calls[0].Arg1)
}
if calls[0].Arg2 != "uh-oh" {
t.Errorf("unexpected error message. want=%s have=%s", "uh-oh", calls[0].Arg2)
}
}
}
func TestRunnerRemovesCompleted(t *testing.T) {
store := NewMockStoreIface()
ticker1 := glock.NewMockTicker(time.Second)
ticker2 := glock.NewMockTicker(time.Second)
ticker3 := glock.NewMockTicker(time.Second)
refreshTicker := glock.NewMockTicker(time.Second * 30)
store.ListFunc.SetDefaultReturn([]Migration{
{ID: 1, Progress: 0.5},
{ID: 2, Progress: 0.1, ApplyReverse: true},
{ID: 3, Progress: 0.9},
}, nil)
runner := newRunner(store, refreshTicker, &observation.TestContext)
// Makes no progress
migrator1 := NewMockMigrator()
migrator1.ProgressFunc.SetDefaultReturn(0.5, nil)
// Goes to 0
migrator2 := NewMockMigrator()
migrator2.ProgressFunc.PushReturn(0.05, nil)
migrator2.ProgressFunc.SetDefaultReturn(0, nil)
// Goes to 1
migrator3 := NewMockMigrator()
migrator3.ProgressFunc.PushReturn(0.95, nil)
migrator3.ProgressFunc.SetDefaultReturn(1, nil)
if err := runner.Register(1, migrator1, MigratorOptions{ticker: ticker1}); err != nil {
t.Fatalf("unexpected error registering migrator: %s", err)
}
if err := runner.Register(2, migrator2, MigratorOptions{ticker: ticker2}); err != nil {
t.Fatalf("unexpected error registering migrator: %s", err)
}
if err := runner.Register(3, migrator3, MigratorOptions{ticker: ticker3}); err != nil {
t.Fatalf("unexpected error registering migrator: %s", err)
}
go runner.Start()
tickN(ticker1, 5)
tickN(ticker2, 5)
tickN(ticker3, 5)
runner.Stop()
// not finished
if callCount := len(migrator1.UpFunc.History()); callCount != 5 {
t.Errorf("unexpected number of calls to Up. want=%d have=%d", 5, callCount)
}
// finished after 2 updates
if callCount := len(migrator2.DownFunc.History()); callCount != 1 {
t.Errorf("unexpected number of calls to Down. want=%d have=%d", 1, callCount)
}
// finished after 2 updates
if callCount := len(migrator3.UpFunc.History()); callCount != 1 {
t.Errorf("unexpected number of calls to Up. want=%d have=%d", 1, callCount)
}
}
func TestRunMigrator(t *testing.T) {
store := NewMockStoreIface()
ticker := glock.NewMockTicker(time.Second)
migrator := NewMockMigrator()
migrator.ProgressFunc.SetDefaultReturn(0.5, nil)
runMigratorWrapped(store, migrator, ticker, func(migrations chan<- Migration) {
migrations <- Migration{ID: 1, Progress: 0.5}
tickN(ticker, 3)
})
if callCount := len(migrator.UpFunc.History()); callCount != 3 {
t.Errorf("unexpected number of calls to Up. want=%d have=%d", 3, callCount)
}
if callCount := len(migrator.DownFunc.History()); callCount != 0 {
t.Errorf("unexpected number of calls to Down. want=%d have=%d", 0, callCount)
}
}
func TestRunMigratorMigrationErrors(t *testing.T) {
store := NewMockStoreIface()
ticker := glock.NewMockTicker(time.Second)
migrator := NewMockMigrator()
migrator.ProgressFunc.SetDefaultReturn(0.5, nil)
migrator.UpFunc.SetDefaultReturn(errors.New("uh-oh"))
runMigratorWrapped(store, migrator, ticker, func(migrations chan<- Migration) {
migrations <- Migration{ID: 1, Progress: 0.5}
tickN(ticker, 1)
})
if calls := store.AddErrorFunc.history; len(calls) != 1 {
t.Fatalf("unexpected number of calls to AddError. want=%d have=%d", 1, len(calls))
} else {
if calls[0].Arg1 != 1 {
t.Errorf("unexpected migrationId. want=%d have=%d", 1, calls[0].Arg1)
}
if calls[0].Arg2 != "uh-oh" {
t.Errorf("unexpected error message. want=%s have=%s", "uh-oh", calls[0].Arg2)
}
}
}
func TestRunMigratorMigrationFinishesUp(t *testing.T) {
store := NewMockStoreIface()
ticker := glock.NewMockTicker(time.Second)
migrator := NewMockMigrator()
migrator.ProgressFunc.PushReturn(0.8, nil) // check
migrator.ProgressFunc.PushReturn(0.9, nil) // after up
migrator.ProgressFunc.SetDefaultReturn(1.0, nil) // after up
runMigratorWrapped(store, migrator, ticker, func(migrations chan<- Migration) {
migrations <- Migration{ID: 1, Progress: 0.8}
tickN(ticker, 5)
})
if callCount := len(migrator.UpFunc.History()); callCount != 2 {
t.Errorf("unexpected number of calls to Up. want=%d have=%d", 2, callCount)
}
if callCount := len(migrator.DownFunc.History()); callCount != 0 {
t.Errorf("unexpected number of calls to Down. want=%d have=%d", 0, callCount)
}
}
func TestRunMigratorMigrationFinishesDown(t *testing.T) {
store := NewMockStoreIface()
ticker := glock.NewMockTicker(time.Second)
migrator := NewMockMigrator()
migrator.ProgressFunc.PushReturn(0.2, nil) // check
migrator.ProgressFunc.PushReturn(0.1, nil) // after down
migrator.ProgressFunc.SetDefaultReturn(0.0, nil) // after down
runMigratorWrapped(store, migrator, ticker, func(migrations chan<- Migration) {
migrations <- Migration{ID: 1, Progress: 0.2, ApplyReverse: true}
tickN(ticker, 5)
})
if callCount := len(migrator.UpFunc.History()); callCount != 0 {
t.Errorf("unexpected number of calls to Up. want=%d have=%d", 0, callCount)
}
if callCount := len(migrator.DownFunc.History()); callCount != 2 {
t.Errorf("unexpected number of calls to Down. want=%d have=%d", 2, callCount)
}
}
func TestRunMigratorMigrationChangesDirection(t *testing.T) {
store := NewMockStoreIface()
ticker := glock.NewMockTicker(time.Second)
migrator := NewMockMigrator()
migrator.ProgressFunc.PushReturn(0.2, nil) // check
migrator.ProgressFunc.PushReturn(0.1, nil) // after down
migrator.ProgressFunc.PushReturn(0.0, nil) // after down
migrator.ProgressFunc.PushReturn(0.0, nil) // re-check
migrator.ProgressFunc.PushReturn(0.1, nil) // after up
migrator.ProgressFunc.PushReturn(0.2, nil) // after up
runMigratorWrapped(store, migrator, ticker, func(migrations chan<- Migration) {
migrations <- Migration{ID: 1, Progress: 0.2, ApplyReverse: true}
tickN(ticker, 5)
migrations <- Migration{ID: 1, Progress: 0.0, ApplyReverse: false}
tickN(ticker, 5)
})
if callCount := len(migrator.UpFunc.History()); callCount != 5 {
t.Errorf("unexpected number of calls to Up. want=%d have=%d", 5, callCount)
}
if callCount := len(migrator.DownFunc.History()); callCount != 2 {
t.Errorf("unexpected number of calls to Down. want=%d have=%d", 2, callCount)
}
}
func | (t *testing.T) {
store := NewMockStoreIface()
ticker := glock.NewMockTicker(time.Second)
progressValues := []float64{
0.20, // inital check
0.25, 0.30, 0.35, 0.40, 0.45, // after up (x5)
0.45, // re-check
0.50, 0.55, 0.60, 0.65, 0.70, // after up (x5)
}
migrator := NewMockMigrator()
for _, val := range progressValues {
migrator.ProgressFunc.PushReturn(val, nil)
}
runMigratorWrapped(store, migrator, ticker, func(migrations chan<- Migration) {
migrations <- Migration{ID: 1, Progress: 0.2, ApplyReverse: false}
tickN(ticker, 5)
migrations <- Migration{ID: 1, Progress: 1.0, ApplyReverse: false}
tickN(ticker, 5)
})
if callCount := len(migrator.UpFunc.History()); callCount != 10 {
t.Errorf("unexpected number of calls to Up. want=%d have=%d", 10, callCount)
}
if callCount := len(migrator.DownFunc.History()); callCount != 0 {
t.Errorf("unexpected number of calls to Down. want=%d have=%d", 0, callCount)
}
}
// runMigratorWrapped creates a migrations channel, then passes it to both the runMigrator
// function and the given interact function, which execute concurrently. This channel can
// control the behavior of the migration controller from within the interact function.
//
// This method blocks until both functions return. The return of the interact function
// cancels a context controlling the runMigrator main loop.
func runMigratorWrapped(store storeIface, migrator Migrator, ticker glock.Ticker, interact func(migrations chan<- Migration)) {
ctx, cancel := context.WithCancel(context.Background())
migrations := make(chan Migration)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
runMigrator(
ctx,
store,
migrator,
migrations,
migratorOptions{ticker: ticker},
newOperations(&observation.TestContext),
)
}()
interact(migrations)
cancel()
wg.Wait()
}
// tickN advances the given ticker by one second n times with a guaranteed reader.
func tickN(ticker *glock.MockTicker, n int) {
for i := 0; i < n; i++ {
ticker.BlockingAdvance(time.Second)
}
}
func TestRunnerValidate(t *testing.T) {
store := NewMockStoreIface()
store.ListFunc.SetDefaultReturn([]Migration{
{ID: 1, Introduced: NewVersion(3, 10), Progress: 1, Deprecated: newVersionPtr(3, 11)},
{ID: 1, Introduced: NewVersion(3, 11), Progress: 1, Deprecated: newVersionPtr(3, 13)},
{ID: 1, Introduced: NewVersion(3, 11), Progress: 1, Deprecated: newVersionPtr(3, 12)},
{ID: 1, Introduced: NewVersion(3, 12), Progress: 0},
{ID: 1, Introduced: NewVersion(3, 13), Progress: 0},
}, nil)
runner := newRunner(store, nil, &observation.TestContext)
statusErr := runner.Validate(context.Background(), NewVersion(3, 12), NewVersion(0, 0))
if statusErr != nil {
t.Errorf("unexpected status error: %s ", statusErr)
}
}
func TestRunnerValidateUnfinishedUp(t *testing.T) {
store := NewMockStoreIface()
store.ListFunc.SetDefaultReturn([]Migration{
{ID: 1, Introduced: NewVersion(3, 11), Progress: 0.65, Deprecated: newVersionPtr(3, 12)},
}, nil)
runner := newRunner(store, nil, &observation.TestContext)
statusErr := runner.Validate(context.Background(), NewVersion(3, 12), NewVersion(0, 0))
if diff := cmp.Diff(wrapMigrationErrors(newMigrationStatusError(1, 1, 0.65)).Error(), statusErr.Error()); diff != "" {
t.Errorf("unexpected status error (-want +got):\n%s", diff)
}
}
func TestRunnerValidateUnfinishedDown(t *testing.T) {
store := NewMockStoreIface()
store.ListFunc.SetDefaultReturn([]Migration{
{ID: 1, Introduced: NewVersion(3, 13), Progress: 0.15, Deprecated: newVersionPtr(3, 15), ApplyReverse: true},
}, nil)
runner := newRunner(store, nil, &observation.TestContext)
statusErr := runner.Validate(context.Background(), NewVersion(3, 12), NewVersion(0, 0))
if diff := cmp.Diff(wrapMigrationErrors(newMigrationStatusError(1, 0, 0.15)).Error(), statusErr.Error()); diff != "" {
t.Errorf("unexpected status error (-want +got):\n%s", diff)
}
}
| TestRunMigratorMigrationDesyncedFromData |
lib-reducer.ts | import {Permissions} from './lib-state';
export function | (state = [], action): Permissions {
return state
}
| libReducer |
pca.py | #!/usr/bin/env python
""" a small class for Principal Component Analysis
Usage:
p = PCA( A, fraction=0.90 )
In:
A: an array of e.g. 1000 observations x 20 variables, 1000 rows x 20 columns
fraction: use principal components that account for e.g.
90 % of the total variance
Out:
p.U, p.d, p.Vt: from numpy.linalg.svd, A = U . d . Vt
p.dinv: 1/d or 0, see NR
p.eigen: the eigenvalues of A*A, in decreasing order (p.d**2).
eigen[j] / eigen.sum() is variable j's fraction of the total variance;
look at the first few eigen[] to see how many PCs get to 90 %, 95 % ...
p.npc: number of principal components,
e.g. 2 if the top 2 eigenvalues are >= `fraction` of the total.
It's ok to change this; methods use the current value.
Methods:
The methods of class PCA transform vectors or arrays of e.g.
20 variables, 2 principal components and 1000 observations,
using partial matrices U' d' Vt', parts of the full U d Vt:
A ~ U' . d' . Vt' where e.g.
U' is 1000 x 2
d' is diag([ d0, d1 ]), the 2 largest singular values
Vt' is 2 x 20. Dropping the primes,
d . Vt 2 principal vars = p.vars_pc( 20 vars )
U 1000 obs = p.pc_obs( 2 principal vars )
U . d . Vt 1000 obs, p.obs( 20 vars ) = pc_obs( vars_pc( vars ))
fast approximate A . vars, using the `npc` principal components
Ut 2 pcs = p.obs_pc( 1000 obs )
V . dinv 20 vars = p.pc_vars( 2 principal vars )
V . dinv . Ut 20 vars, p.vars( 1000 obs ) = pc_vars( obs_pc( obs )),
fast approximate Ainverse . obs: vars that give ~ those obs.
Notes:
PCA does not center or scale A; you usually want to first
A -= A.mean(A, axis=0)
A /= A.std(A, axis=0)
with the little class Center or the like, below.
See also:
http://en.wikipedia.org/wiki/Principal_component_analysis
http://en.wikipedia.org/wiki/Singular_value_decomposition
Press et al., Numerical Recipes (2 or 3 ed), SVD
PCA micro-tutorial
iris-pca .py .png
"""
from __future__ import division
import numpy as np
dot = np.dot
# import bz.numpyutil as nu
# dot = nu.pdot
__version__ = "2010-04-14 apr"
__author_email__ = "denis-bz-py at t-online dot de"
#...............................................................................
class PCA:
def __init__( self, A, fraction=0.90 ):
assert 0 <= fraction <= 1
# A = U . diag(d) . Vt, O( m n^2 ), lapack_lite --
self.U, self.d, self.Vt = np.linalg.svd( A, full_matrices=False )
assert np.all( self.d[:-1] >= self.d[1:] ) # sorted
self.eigen = self.d**2
self.sumvariance = np.cumsum(self.eigen)
self.sumvariance /= self.sumvariance[-1]
self.npc = np.searchsorted( self.sumvariance, fraction ) + 1
self.dinv = np.array([ 1/d if d > self.d[0] * 1e-6 else 0
for d in self.d ])
def pc( self ):
""" e.g. 1000 x 2 U[:, :npc] * d[:npc], to plot etc. """
n = self.npc
return self.U[:, :n] * self.d[:n]
# These 1-line methods may not be worth the bother;
# then use U d Vt directly --
def vars_pc( self, x ):
n = self.npc
return self.d[:n] * dot( self.Vt[:n], x.T ).T # 20 vars -> 2 principal
def pc_vars( self, p ):
n = self.npc
return dot( self.Vt[:n].T, (self.dinv[:n] * p).T ) .T # 2 PC -> 20 vars
def pc_obs( self, p ):
n = self.npc
return dot( self.U[:, :n], p.T ) # 2 principal -> 1000 obs
def obs_pc( self, obs ):
n = self.npc
return dot( self.U[:, :n].T, obs ) .T # 1000 obs -> 2 principal
def obs( self, x ):
return self.pc_obs( self.vars_pc(x) ) # 20 vars -> 2 principal -> 1000 obs
def vars( self, obs ):
return self.pc_vars( self.obs_pc(obs) ) # 1000 obs -> 2 principal -> 20 vars
class | :
""" A -= A.mean() /= A.std(), inplace -- use A.copy() if need be
uncenter(x) == original A . x
"""
# mttiw
def __init__( self, A, axis=0, scale=True, verbose=1 ):
self.mean = A.mean(axis=axis)
if verbose:
print "Center -= A.mean:", self.mean
A -= self.mean
if scale:
std = A.std(axis=axis)
self.std = np.where( std, std, 1. )
if verbose:
print "Center /= A.std:", self.std
A /= self.std
else:
self.std = np.ones( A.shape[-1] )
self.A = A
def uncenter( self, x ):
return np.dot( self.A, x * self.std ) + np.dot( x, self.mean )
#...............................................................................
if __name__ == "__main__":
import sys
csv = "iris4.csv" # wikipedia Iris_flower_data_set
# 5.1,3.5,1.4,0.2 # ,Iris-setosa ...
N = 1000
K = 20
fraction = .90
seed = 1
exec "\n".join( sys.argv[1:] ) # N= ...
np.random.seed(seed)
np.set_printoptions(1, threshold=100, suppress=True ) # .1f
try:
A = np.genfromtxt( csv, delimiter="," )
N, K = A.shape
except IOError:
A = np.random.normal( size=(N, K) ) # gen correlated ?
print "csv: %s N: %d K: %d fraction: %.2g" % (csv, N, K, fraction)
Center(A)
print "A:", A
print "PCA ..." ,
p = PCA( A, fraction=fraction )
print "npc:", p.npc
print "% variance:", p.sumvariance * 100
print "Vt[0], weights that give PC 0:", p.Vt[0]
print "A . Vt[0]:", dot( A, p.Vt[0] )
print "pc:", p.pc()
print "\nobs <-> pc <-> x: with fraction=1, diffs should be ~ 0"
x = np.ones(K)
# x = np.ones(( 3, K ))
print "x:", x
pc = p.vars_pc(x) # d' Vt' x
print "vars_pc(x):", pc
print "back to ~ x:", p.pc_vars(pc)
Ax = dot( A, x.T )
pcx = p.obs(x) # U' d' Vt' x
print "Ax:", Ax
print "A'x:", pcx
print "max |Ax - A'x|: %.2g" % np.linalg.norm( Ax - pcx, np.inf )
b = Ax # ~ back to original x, Ainv A x
back = p.vars(b)
print "~ back again:", back
print "max |back - x|: %.2g" % np.linalg.norm( back - x, np.inf )
# end pca.py | Center |
options.go | package stomp
import (
"context"
"time"
"github.com/ship-os/ship-micro/v2/broker"
)
// SubscribeHeaders sets headers for subscriptions
func SubscribeHeaders(h map[string]string) broker.SubscribeOption {
return setSubscribeOption(subscribeHeaderKey{}, h)
}
type subscribeContextKey struct{}
// SubscribeContext set the context for broker.SubscribeOption
func SubscribeContext(ctx context.Context) broker.SubscribeOption {
return setSubscribeOption(subscribeContextKey{}, ctx)
}
type ackSuccessKey struct{}
// AckOnSuccess will automatically acknowledge messages when no error is returned
func AckOnSuccess() broker.SubscribeOption {
return setSubscribeOption(ackSuccessKey{}, true)
}
// Durable sets a durable subscription
func Durable() broker.SubscribeOption {
return setSubscribeOption(durableQueueKey{}, true)
}
// Receipt requests a receipt for the delivery should be received
func Receipt(ct time.Duration) broker.PublishOption {
return setPublishOption(receiptKey{}, true)
}
// SuppressContentLength requests that send does not include a content length | return setPublishOption(suppressContentLengthKey{}, true)
}
// ConnectTimeout sets the connection timeout duration
func ConnectTimeout(ct time.Duration) broker.Option {
return setBrokerOption(connectTimeoutKey{}, ct)
}
// Auth sets the authentication information
func Auth(username string, password string) broker.Option {
return setBrokerOption(authKey{}, &authRecord{
username: username,
password: password,
})
}
// ConnectHeaders adds headers for the connection
func ConnectHeaders(h map[string]string) broker.Option {
return setBrokerOption(connectHeaderKey{}, h)
}
// VirtualHost adds host header to define the vhost
func VirtualHost(h string) broker.Option {
return setBrokerOption(vHostKey{}, h)
} | func SuppressContentLength(ct time.Duration) broker.PublishOption { |
simonsays.py | """Simon Says
Exercises
1. Speed up tile flash rate.
2. Add more tiles.
"""
from random import choice
from time import sleep
from turtle import *
from rohans2dtlkit import floor, square, vector
pattern = []
guesses = []
tiles = {
vector(0, 0): ('red', 'dark red'),
vector(0, -200): ('blue', 'dark blue'),
vector(-200, 0): ('green', 'dark green'),
vector(-200, -200): ('yellow', 'khaki'),
}
def grid():
"Draw grid of tiles."
square(0, 0, 200, 'dark red')
square(0, -200, 200, 'dark blue')
square(-200, 0, 200, 'dark green')
square(-200, -200, 200, 'khaki')
update()
def flash(tile):
"Flash tile in grid."
glow, dark = tiles[tile]
square(tile.x, tile.y, 200, glow)
update()
sleep(0.5)
square(tile.x, tile.y, 200, dark)
update()
sleep(0.5)
def | ():
"Grow pattern and flash tiles."
tile = choice(list(tiles))
pattern.append(tile)
for tile in pattern:
flash(tile)
print('Pattern length:', len(pattern))
guesses.clear()
def tap(x, y):
"Respond to screen tap."
onscreenclick(None)
x = floor(x, 200)
y = floor(y, 200)
tile = vector(x, y)
index = len(guesses)
if tile != pattern[index]:
exit()
guesses.append(tile)
flash(tile)
if len(guesses) == len(pattern):
grow()
onscreenclick(tap)
def start(x, y):
"Start game."
grow()
onscreenclick(tap)
setup(420, 420, 370, 0)
hideturtle()
tracer(False)
grid()
onscreenclick(start)
done()
| grow |
plan_json_provider.go | package terraform
import (
"io/ioutil"
"github.com/infracost/infracost/internal/config"
"github.com/infracost/infracost/internal/schema"
"github.com/pkg/errors"
)
type PlanJSONProvider struct {
Path string
env *config.Environment
}
func NewPlanJSONProvider(cfg *config.Config, projectCfg *config.Project) schema.Provider {
return &PlanJSONProvider{
Path: projectCfg.Path,
env: cfg.Environment,
}
}
func (p *PlanJSONProvider) Type() string {
return "terraform_plan_json"
}
func (p *PlanJSONProvider) DisplayType() string {
return "Terraform plan JSON file"
}
func (p *PlanJSONProvider) AddMetadata(metadata *schema.ProjectMetadata) {
// no op
}
func (p *PlanJSONProvider) LoadResources(project *schema.Project, usage map[string]*schema.UsageData) error {
j, err := ioutil.ReadFile(p.Path)
if err != nil |
parser := NewParser(p.env)
pastResources, resources, err := parser.parseJSON(j, usage)
if err != nil {
return errors.Wrap(err, "Error parsing Terraform plan JSON file")
}
project.PastResources = pastResources
project.Resources = resources
return nil
}
| {
return errors.Wrap(err, "Error reading Terraform plan JSON file")
} |
solution1.py | # Python3
def diffOne(a, b):
count = 0
for i in range(len(a)):
if a[i] != b[i]:
count += 1
if count == 2:
return False
return bool(count)
def func(inputArray, curr):
if len(inputArray) == 1:
return diffOne(inputArray[0], curr)
for i in range(len(inputArray)):
if diffOne(inputArray[i], curr):
inputArray[i], inputArray[-1] = inputArray[-1], inputArray[i]
if func(inputArray[:-1], inputArray[-1]):
return True
inputArray[i], inputArray[-1] = inputArray[-1], inputArray[i]
return False
def stringsRearrangement(inputArray):
for i in range(len(inputArray)):
inputArray[i], inputArray[-1] = inputArray[-1], inputArray[i]
if func(inputArray[:-1], inputArray[-1]):
|
inputArray[i], inputArray[-1] = inputArray[-1], inputArray[i]
return False
| return True |
dataset.py | import glob
import os
import warnings
from datetime import datetime
from copy import deepcopy
import numpy as np
import pyedflib
import scipy.io as sio
from config import cfg
from thirdparty.cerebus import NsxFile, NevFile
from thirdparty.nex import Reader as NexReader
from .utils import find_nearest_time
def _load_neuracle(data_dir):
"""
neuracle file loader
:param data_dir: root data dir for the experiment
:return:
data: ndarray, (channels, timesteps)
ch_name: list, name of channels
timestamp: list, index of trigger
"""
f = {
'data': os.path.join(data_dir, 'data.bdf'),
'evt': os.path.join(data_dir, 'evt.bdf')
}
# read data
f_data = pyedflib.EdfReader(f['data'])
ch_names = f_data.getSignalLabels()
data = np.array([f_data.readSignal(i) for i in range(f_data.signals_in_file)])
# sample frequiencies
sfreq = f_data.getSampleFrequencies()
assert np.unique(sfreq).size == 1
if cfg.amp_info.samplerate != sfreq[0]:
warnings.warn('Samplerate in config file does not equal to data file record')
cfg.amp_info.samplerate = int(sfreq[0])
# read event
f_evt = pyedflib.EdfReader(f['evt'])
event, _, _ = f_evt.readAnnotations()
event = list(map(lambda x: int(x * cfg.amp_info.samplerate), event))
return data, ch_names, event
def _load_usbamp(data_dir):
"""
USBAmp file loader
:param data_dir: root dir
:return:
data: ndarray, (channels, timesteps)
ch_name: list, name of channels
timestamp: list, index of trigger
"""
# edf USBAmp
files = glob.glob(os.path.join(data_dir, '*.edf'))
assert len(files) == 1
f = pyedflib.EdfReader(files[0])
ch_names = f.getSignalLabels()
# filter channel
# find trigger channel
triggers = []
sig = []
for i, chan in enumerate(ch_names):
if 'trigger' in chan:
triggers.append(i)
else:
sig.append(i)
sigbuf = np.array([f.readSignal(i) for i in range(len(ch_names))])
ch_names = [ch_names[i] for i in sig]
trigger = -1
for ch_ind in triggers:
if not np.allclose(np.diff(sigbuf[ch_ind]), 0):
trigger = ch_ind
break
diff = np.diff(sigbuf[trigger])
timestamp = np.nonzero(np.logical_and(diff <= 1, diff >= 0.2))[0].tolist()
data = sigbuf[sig]
return data, ch_names, timestamp
def _load_nex(data_dir):
|
def _load_cerebus(data_dir):
# search data_dir
nsx_files = glob.glob(os.path.join(data_dir, '*.ns*'))
nev_files = glob.glob(os.path.join(data_dir, '*.nev'))
assert len(nsx_files) == len(nev_files) == 1
# loading
f_data = NsxFile(nsx_files[0])
f_evt = NevFile(nev_files[0])
data = f_data.getdata()
evt = f_evt.getdata()
f_data.close()
f_evt.close()
# some basic information
samplerate = data['samp_per_s']
if cfg.amp_info.samplerate != samplerate:
warnings.warn('Samplerate in config file does not equal to data file record')
cfg.amp_info.samplerate = samplerate
timestampresolution = f_evt.basic_header['TimeStampResolution']
ch_names = []
for info in f_data.extended_headers:
ch_names.append(info['ElectrodeLabel'])
event = evt['dig_events']['TimeStamps'][0]
event = list(map(lambda x: int(x / timestampresolution * cfg.amp_info.samplerate), event))
return data['data'], ch_names, event
class Dataset:
"""
for loading data and event order.
"""
data_format = {
'nex': _load_nex,
'ns3': _load_cerebus,
'nev': _load_cerebus,
'edf': _load_usbamp,
'bdf': _load_neuracle
}
def __init__(self, subject, date=None, loaddata=True):
self.subject = subject
self._subj_path = os.path.dirname(__file__) + '/../data/' + subject
if date is None:
self._date = find_nearest_time(self._subj_path)
else:
if isinstance(date, datetime):
# convert datetime to str
self._date = date.strftime("%Y-%m-%d-%H-%M-%S")
else:
self._date = date
print(self._date)
self.root_dir = os.path.join(self._subj_path, self._date)
# self.montage = OrderedSet(cfg.subj_info.montage)
self.montage = deepcopy(cfg.subj_info.montage)
# load stim order
self.events = self.load_event()
if loaddata:
self.load_all()
else:
self.data, self.ch_names, self.timestamp, self.montage_indices, self.events_backup = [None] * 5
def load_all(self):
# load data and timestamps
dataarray, ch_names, timestamp = self._load_data()
timestamp = Dataset.ts_check(timestamp)
self.data = dataarray
# list to set
self.ch_names = ch_names
self.timestamp = timestamp
self.montage_indices = self.get_channel_indices(self.montage, self.ch_names)
self.events_backup = self.events.copy()
if cfg.exp_config.bidir:
assert 2 * len(timestamp) == self.events.size, print('Dual-directional: ', len(timestamp), self.events.size)
self.events = self.events[:, ::2]
else:
assert len(timestamp) == self.events.size, print('Unidirectional: ', len(timestamp), self.events.size)
def _load_data(self):
"""
Read data according to file format
:return:
dataext: str, data file name
"""
walk_path = self.root_dir
loader = None
for f in os.listdir(walk_path):
_ext = f.split('.')[-1]
try:
loader = Dataset.data_format[_ext]
break
except KeyError:
pass
if loader is None:
raise FileNotFoundError('No matching data format found')
return loader(walk_path)
def load_event(self):
walk_path = self.root_dir
file = glob.glob(os.path.join(walk_path, self.subject) + '*')
assert len(file) == 1
file = file[0]
if file.endswith('.mat'):
raw = sio.loadmat(file)
order = raw['stim_order']
order -= 1
return order.reshape((-1, 12))
else:
with open(file) as f:
stim_order = [[int(x) for x in line.split()] for line in f if len(line) > 1]
return np.array(stim_order)
@staticmethod
def get_channel_indices(target_channels, channels_in_data):
"""
Get corresponding index number for channels in target channels
:param target_channels: list, target channel names
:param channels_in_data: list, all channel names in data source.
:return:
"""
indices = []
# build a dictionary for indexing
channel_book = {name: i for i, name in enumerate(channels_in_data)}
for ch in target_channels:
try:
indices.append(channel_book[ch])
except ValueError as err:
print(err)
return indices
@staticmethod
def ts_check(ts):
# check time stamp intervals.
# In our experience, sometimes an accidental wrong trigger may appear at the beginning during recording.
fs = cfg.amp_info.samplerate
while len(ts) % 12 and (not (fs * 0.1 <= ts[1] - ts[0] <= fs * 0.3)):
del ts[0]
return ts
| """
nex file loader
:param data_dir:
:return:
data: ndarray, shape (ch, timesteps)
ch_names: list, name of each channel
timestamps: list, stimulation onset
"""
files = glob.glob(os.path.join(data_dir, '*.nex'))
assert len(files) == 1
reader = NexReader(useNumpy=True)
data = reader.ReadNexFile(files[0])
var = data['Variables']
ch_names = []
trigger_ch = None
con_data = []
samplerate = cfg.amp_info.samplerate
for i, ch in enumerate(var):
if 'CH' in ch['Header']['Name']:
ch_names.append(ch['Header']['Name'])
con_data.append(ch['ContinuousValues'])
samplerate = ch['Header']['SamplingRate']
if 'digin' == ch['Header']['Name']:
trigger_ch = i
if samplerate != cfg.amp_info.samplerate:
warnings.warn('Samplerate in config file does not equal to data file record, recorded value is %d' % samplerate)
assert trigger_ch is not None
timestamp = np.round(data['Variables'][trigger_ch]['Timestamps'] * samplerate).astype(np.int32).tolist()
con_data = np.array(con_data)
return con_data, ch_names, timestamp |
Task.py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005-2010 (ita)
"""
Tasks represent atomic operations such as processes.
"""
import os, shutil, re, tempfile, time, pprint
from waflib import Context, Utils, Logs, Errors
from binascii import hexlify
# task states
NOT_RUN = 0
"""The task was not executed yet"""
MISSING = 1
"""The task has been executed but the files have not been created"""
CRASHED = 2
"""The task execution returned a non-zero exit status"""
EXCEPTION = 3
"""An exception occured in the task execution"""
SKIPPED = 8
"""The task did not have to be executed"""
SUCCESS = 9
"""The task was successfully executed"""
ASK_LATER = -1
"""The task is not ready to be executed"""
SKIP_ME = -2
"""The task does not need to be executed"""
RUN_ME = -3
"""The task must be executed"""
COMPILE_TEMPLATE_SHELL = '''
def f(tsk):
env = tsk.env
gen = tsk.generator
bld = gen.bld
wd = getattr(tsk, 'cwd', None)
p = env.get_flat
tsk.last_cmd = cmd = \'\'\' %s \'\'\' % s
return tsk.exec_command(cmd, cwd=wd, env=env.env or None)
'''
COMPILE_TEMPLATE_NOSHELL = '''
def f(tsk):
env = tsk.env
gen = tsk.generator
bld = gen.bld
wd = getattr(tsk, 'cwd', None)
def to_list(xx):
if isinstance(xx, str): return [xx]
return xx
tsk.last_cmd = lst = []
%s
lst = [x for x in lst if x]
return tsk.exec_command(lst, cwd=wd, env=env.env or None)
'''
def cache_outputs(cls):
"""
Task class decorator applied to all task classes by default unless they define the attribute 'nocache'::
from waflib import Task
class foo(Task.Task):
nocache = True
If bld.cache_global is defined and if the task instances produces output nodes,
the files will be copied into a folder in the cache directory
The files may also be retrieved from that folder, if it exists
"""
m1 = cls.run
def run(self):
bld = self.generator.bld
if bld.cache_global and not bld.nocache:
if self.can_retrieve_cache():
return 0
return m1(self)
cls.run = run
m2 = cls.post_run
def post_run(self):
bld = self.generator.bld
ret = m2(self)
if bld.cache_global and not bld.nocache:
self.put_files_cache()
return ret
cls.post_run = post_run
return cls
classes = {}
"class tasks created by user scripts or Waf tools are kept in this dict name -> class object"
class store_task_type(type):
"""
Metaclass: store the task classes into :py:const:`waflib.Task.classes`, or to the dict pointed
by the class attribute 'register'.
The attribute 'run_str' will be processed to compute a method 'run' on the task class
The decorator :py:func:`waflib.Task.cache_outputs` is also applied to the class
"""
def __init__(cls, name, bases, dict):
super(store_task_type, cls).__init__(name, bases, dict)
name = cls.__name__
if name.endswith('_task'):
name = name.replace('_task', '')
if name != 'evil' and name != 'TaskBase':
global classes
if getattr(cls, 'run_str', None):
# if a string is provided, convert it to a method
(f, dvars) = compile_fun(cls.run_str, cls.shell)
cls.hcode = cls.run_str
cls.run_str = None
cls.run = f
cls.vars = list(set(cls.vars + dvars))
cls.vars.sort()
elif getattr(cls, 'run', None) and not 'hcode' in cls.__dict__:
# getattr(cls, 'hcode') would look in the upper classes
cls.hcode = Utils.h_fun(cls.run)
if not getattr(cls, 'nocache', None):
cls = cache_outputs(cls)
# be creative
getattr(cls, 'register', classes)[name] = cls
evil = store_task_type('evil', (object,), {})
"Base class provided to avoid writing a metaclass, so the code can run in python 2.6 and 3.x unmodified"
class TaskBase(evil):
"""
Base class for all Waf tasks, which should be seen as an interface.
For illustration purposes, instances of this class will execute the attribute
'fun' in :py:meth:`waflib.Task.TaskBase.run`. When in doubt, create
subclasses of :py:class:`waflib.Task.Task` instead.
Subclasses should override these methods:
#. __str__: string to display to the user
#. runnable_status: ask the task if it should be run, skipped, or if we have to ask later
#. run: let threads execute the task
#. post_run: let threads update the data regarding the task (cache)
"""
color = 'GREEN'
"""Color for the console display, see :py:const:`waflib.Logs.colors_lst`"""
ext_in = []
"""File extensions that objects of this task class might use"""
ext_out = []
"""File extensions that objects of this task class might create"""
before = []
"""List of task class names to execute before instances of this class"""
after = []
"""List of task class names to execute after instances of this class"""
hcode = ''
"""String representing an additional hash for the class representation"""
def __init__(self, *k, **kw):
"""
The base task class requires a task generator, which will be itself if missing
"""
self.hasrun = NOT_RUN
try:
self.generator = kw['generator']
except KeyError:
self.generator = self
def __repr__(self):
"for debugging purposes"
return '\n\t{task %r: %s %s}' % (self.__class__.__name__, id(self), str(getattr(self, 'fun', '')))
def __str__(self):
"string to display to the user"
if hasattr(self, 'fun'):
return 'executing: %s\n' % self.fun.__name__
return self.__class__.__name__ + '\n'
def __hash__(self):
"Very fast hashing scheme but not persistent (replace/implement in subclasses and see :py:meth:`waflib.Task.Task.uid`)"
return id(self)
def exec_command(self, cmd, **kw):
"""
Wrapper for :py:meth:`waflib.Context.Context.exec_command` which sets a current working directory to ``build.variant_dir``
:return: the return code
:rtype: int
"""
bld = self.generator.bld
try:
if not kw.get('cwd', None):
kw['cwd'] = bld.cwd
except AttributeError:
bld.cwd = kw['cwd'] = bld.variant_dir
return bld.exec_command(cmd, **kw)
def runnable_status(self):
"""
State of the task
:return: a task state in :py:const:`waflib.Task.RUN_ME`, :py:const:`waflib.Task.SKIP_ME` or :py:const:`waflib.Task.ASK_LATER`.
:rtype: int
"""
return RUN_ME
def process(self):
"""
Assume that the task has had a new attribute ``master`` which is an instance of :py:class:`waflib.Runner.Parallel`.
Execute the task and then put it back in the queue :py:attr:`waflib.Runner.Parallel.out` (may be replaced by subclassing).
"""
m = self.master
if m.stop:
m.out.put(self)
return
# remove the task signature immediately before it is executed
# in case of failure the task will be executed again
try:
del self.generator.bld.task_sigs[self.uid()]
except KeyError:
pass
try:
self.generator.bld.returned_tasks.append(self)
self.log_display(self.generator.bld)
ret = self.run()
except Exception:
self.err_msg = Utils.ex_stack()
self.hasrun = EXCEPTION
# TODO cleanup
m.error_handler(self)
m.out.put(self)
return
if ret:
self.err_code = ret
self.hasrun = CRASHED
else:
try:
self.post_run()
except Errors.WafError:
pass
except Exception:
self.err_msg = Utils.ex_stack()
self.hasrun = EXCEPTION
else:
self.hasrun = SUCCESS
if self.hasrun != SUCCESS:
m.error_handler(self)
m.out.put(self)
def run(self):
"""
Called by threads to execute the tasks. The default is empty and meant to be overridden in subclasses.
It is a bad idea to create nodes in this method (so, no node.ant_glob)
:rtype: int
"""
if hasattr(self, 'fun'):
return self.fun(self)
return 0
def post_run(self):
"Update the cache files (executed by threads). Override in subclasses."
pass
def log_display(self, bld):
"Write the execution status on the context logger"
bld.to_log(self.display())
def display(self):
"""
Return an execution status for the console, the progress bar, or the IDE output.
:rtype: string
"""
col1 = Logs.colors(self.color)
col2 = Logs.colors.NORMAL
master = self.master
def cur():
# the current task position, computed as late as possible
tmp = -1
if hasattr(master, 'ready'):
tmp -= master.ready.qsize()
return master.processed + tmp
if self.generator.bld.progress_bar == 1:
return self.generator.bld.progress_line(cur(), master.total, col1, col2)
if self.generator.bld.progress_bar == 2:
ela = str(self.generator.bld.timer)
try:
ins = ','.join([n.name for n in self.inputs])
except AttributeError:
ins = ''
try:
outs = ','.join([n.name for n in self.outputs])
except AttributeError:
outs = ''
return '|Total %s|Current %s|Inputs %s|Outputs %s|Time %s|\n' % (master.total, cur(), ins, outs, ela)
s = str(self)
if not s:
return None
total = master.total
n = len(str(total))
fs = '[%%%dd/%%%dd] %%s%%s%%s' % (n, n)
return fs % (cur(), total, col1, s, col2)
def attr(self, att, default=None):
"""
Retrieve an attribute from the instance or from the class.
:param att: variable name
:type att: string
:param default: default value
"""
ret = getattr(self, att, self)
if ret is self: return getattr(self.__class__, att, default)
return ret
def hash_constraints(self):
"""
Identify a task type for all the constraints relevant for the scheduler: precedence, file production
:return: a hash value
:rtype: string
"""
cls = self.__class__
tup = (str(cls.before), str(cls.after), str(cls.ext_in), str(cls.ext_out), cls.__name__, cls.hcode)
h = hash(tup)
return h
def format_error(self):
"""
Error message to display to the user when a build fails
:rtype: string
"""
msg = getattr(self, 'last_cmd', '')
# Format msg to be better read-able
output = ''
for i in msg:
if not isinstance(i, str):
output += str(i) + ' '
else:
output += i + ' '
msg = output[:len(output)-1]
name = self.__class__.__name__.replace('_task', '') + ' (' + self.env['PLATFORM'] + '|' + self.env['CONFIGURATION'] + ')'
if getattr(self, "err_msg", None):
return self.err_msg
elif not self.hasrun:
return 'task in %r was not executed for some reason: %r' % (name, self)
elif self.hasrun == CRASHED:
try:
return ' -> task in %r failed (exit status %r): %r\n%r' % (name, self.err_code, self, msg)
except AttributeError:
return ' -> task in %r failed: %r\n%r' % (name, self, msg)
elif self.hasrun == MISSING:
return ' -> missing files in %r: %r\n%r' % (name, self, msg)
else:
return 'invalid status for task in %r: %r' % (name, self.hasrun)
def colon(self, var1, var2):
"""
private function for the moment
used for scriptlet expressions such as ${FOO_ST:FOO}, for example, if
env.FOO_ST = ['-a', '-b']
env.FOO = ['1', '2']
then the result will be ['-a', '-b', '1', '-a', '-b', '2']
"""
tmp = self.env[var1]
if isinstance(var2, str):
it = self.env[var2]
else:
it = var2
if isinstance(tmp, str):
return [tmp % x for x in it]
else:
if Logs.verbose and not tmp and it:
Logs.warn('Missing env variable %r for task %r (generator %r)' % (var1, self, self.generator))
lst = []
for y in it:
lst.extend(tmp)
lst.append(y)
return lst
class Task(TaskBase):
"""
This class deals with the filesystem (:py:class:`waflib.Node.Node`). The method :py:class:`waflib.Task.Task.runnable_status`
uses a hash value (from :py:class:`waflib.Task.Task.signature`) which is persistent from build to build. When the value changes,
the task has to be executed. The method :py:class:`waflib.Task.Task.post_run` will assign the task signature to the output
nodes (if present).
"""
vars = []
"""Variables to depend on (class attribute used for :py:meth:`waflib.Task.Task.sig_vars`)"""
shell = False
"""Execute the command with the shell (class attribute)"""
def __init__(self, *k, **kw):
TaskBase.__init__(self, *k, **kw)
self.env = kw['env']
"""ConfigSet object (make sure to provide one)"""
self.inputs = []
"""List of input nodes, which represent the files used by the task instance"""
self.outputs = []
"""List of output nodes, which represent the files created by the task instance"""
self.dep_nodes = []
"""List of additional nodes to depend on"""
self.run_after = set([])
"""Set of tasks that must be executed before this one"""
self.sig_debug_output = ''
"""String output detailing a signature mismatch"""
self.sig_implicit_debug_log = ''
"""String output to aggregate implicit deps for logging purposes"""
# Additionally, you may define the following
#self.dep_vars = 'PREFIX DATADIR'
def __str__(self):
"string to display to the user"
env = self.env
src_str = ' '.join([a.nice_path() for a in self.inputs])
tgt_str = ' '.join([a.nice_path() for a in self.outputs])
if self.outputs and self.inputs: sep = ' -> '
else: sep = ''
name = self.__class__.__name__.replace('_task', '') + ' (' + env['PLATFORM'] + '|' + env['CONFIGURATION'] + ')'
return '%s: %s%s%s\n' % (name, src_str, sep, tgt_str)
def __repr__(self):
"for debugging purposes"
try:
ins = ",".join([x.name for x in self.inputs])
outs = ",".join([x.name for x in self.outputs])
except AttributeError:
ins = ",".join([str(x) for x in self.inputs])
outs = ",".join([str(x) for x in self.outputs])
return "".join(['\n\t{task %r: ' % id(self), self.__class__.__name__, " ", ins, " -> ", outs, '}'])
def uid(self):
"""
Return an identifier used to determine if tasks are up-to-date. Since the
identifier will be stored between executions, it must be:
- unique: no two tasks return the same value (for a given build context)
- the same for a given task instance
By default, the node paths, the class name, and the function are used
as inputs to compute a hash.
The pointer to the object (python built-in 'id') will change between build executions,
and must be avoided in such hashes.
:return: hash value
:rtype: string
"""
try:
return self.uid_
except AttributeError:
# this is not a real hot zone, but we want to avoid surprises here
m = Utils.md5()
up = m.update
up(self.__class__.__name__.encode())
deplist = [k.abspath().encode() for k in self.inputs + self.outputs]
dep_bld_sigs_str = "".join(deplist)
up(dep_bld_sigs_str)
self.uid_ = m.digest()
return self.uid_
def set_inputs(self, inp):
"""
Append the nodes to the *inputs*
:param inp: input nodes
:type inp: node or list of nodes
"""
if isinstance(inp, list): self.inputs += inp
else: self.inputs.append(inp)
def | (self, out):
"""
Append the nodes to the *outputs*
:param out: output nodes
:type out: node or list of nodes
"""
if isinstance(out, list): self.outputs += out
else: self.outputs.append(out)
def set_run_after(self, task):
"""
Run this task only after *task*. Affect :py:meth:`waflib.Task.runnable_status`
You probably want to use tsk.run_after.add(task) directly
:param task: task
:type task: :py:class:`waflib.Task.Task`
"""
assert isinstance(task, TaskBase)
self.run_after.add(task)
def signature(self):
"""
Task signatures are stored between build executions, they are use to track the changes
made to the input nodes (not to the outputs!). The signature hashes data from various sources:
* explicit dependencies: files listed in the inputs (list of node objects) :py:meth:`waflib.Task.Task.sig_explicit_deps`
* implicit dependencies: list of nodes returned by scanner methods (when present) :py:meth:`waflib.Task.Task.sig_implicit_deps`
* hashed data: variables/values read from task.__class__.vars/task.env :py:meth:`waflib.Task.Task.sig_vars`
If the signature is expected to give a different result, clear the cache kept in ``self.cache_sig``::
from waflib import Task
class cls(Task.Task):
def signature(self):
sig = super(Task.Task, self).signature()
delattr(self, 'cache_sig')
return super(Task.Task, self).signature()
"""
try: return self.cache_sig
except AttributeError: pass
self.m = Utils.md5()
self.m.update(self.hcode.encode())
# explicit deps
exp_deps = self.sig_explicit_deps()
self.m.update(exp_deps)
# env vars
self.sig_vars()
# implicit deps / scanner results
if self.scan:
imp_deps = self.sig_implicit_deps()
self.m.update(imp_deps)
ret = self.cache_sig = self.m.digest()
return ret
def runnable_status(self):
"""
Override :py:meth:`waflib.Task.TaskBase.runnable_status` to determine if the task is ready
to be run (:py:attr:`waflib.Task.Task.run_after`)
"""
for t in self.run_after:
if not t.hasrun:
return ASK_LATER
bld = self.generator.bld
self.sig_debug_output = ""
# first compute the signature
try:
new_sig = self.signature()
except Errors.TaskNotReady:
return ASK_LATER
# compare the signature to a signature computed previously
key = self.uid()
try:
prev_sig = bld.task_sigs[key]
except KeyError:
Logs.debug("task: task %r must run as it was never run before or the task code changed" % self)
return RUN_ME
if new_sig != prev_sig:
if Logs.sig_delta:
sig_debug_path = os.path.join('TaskSigDeltaOutput','{}_{}_{}.log'.format(self.__class__.__name__, self.inputs[0].name.replace(".", ""), time.time()))
sig_debug_node = self.generator.bld.bldnode.find_or_declare(sig_debug_path)
sig_debug_node.write(self.sig_debug_output)
return RUN_ME
# compare the signatures of the outputs
for node in self.outputs:
try:
if node.sig != new_sig:
return RUN_ME
except AttributeError:
Logs.debug("task: task %r must run as the output nodes do not exist" % self)
return RUN_ME
return SKIP_ME
def post_run(self):
"""
Called after successful execution to update the cache data :py:class:`waflib.Node.Node` sigs
and :py:attr:`waflib.Build.BuildContext.task_sigs`.
The node signature is obtained from the task signature, but the output nodes may also get the signature
of their contents. See the class decorator :py:func:`waflib.Task.update_outputs` if you need this behaviour.
"""
bld = self.generator.bld
sig = self.signature()
for node in self.outputs:
# check if the node exists ..
try:
os.stat(node.abspath())
except OSError:
self.hasrun = MISSING
self.err_msg = '-> missing file: %r' % node.abspath()
raise Errors.WafError(self.err_msg)
# important, store the signature for the next run
node.sig = node.cache_sig = sig
bld.task_sigs[self.uid()] = self.cache_sig
def sig_explicit_deps(self):
"""
Used by :py:meth:`waflib.Task.Task.signature`, hash :py:attr:`waflib.Task.Task.inputs`
and :py:attr:`waflib.Task.Task.dep_nodes` signatures.
:rtype: hash value
"""
bld = self.generator.bld
bld_sigs = []
exp_output = ''
# the inputs
for x in self.inputs + self.dep_nodes:
try:
bld_sig = x.get_bld_sig()
if Logs.sig_delta:
exp_output += '{} {} {}\n'.format(x.name, x.abspath(), hexlify(bld_sig))
bld_sigs.append(bld_sig)
except (AttributeError, TypeError, IOError):
Logs.warn('Missing signature for node %r (required by %r)' % (x, self))
continue # skip adding the signature to the calculation, but continue adding other dependencies
# manual dependencies, they can slow down the builds
if bld.deps_man:
additional_deps = bld.deps_man
for x in self.inputs + self.outputs:
try:
d = additional_deps[id(x)]
except KeyError:
continue
for v in d:
v_name = v.name
if isinstance(v, bld.root.__class__):
try:
v = v.get_bld_sig()
except AttributeError:
raise Errors.WafError('Missing node signature for %r (required by %r)' % (v, self))
elif hasattr(v, '__call__'):
v = v() # dependency is a function, call it
if Logs.sig_delta:
exp_output += '{} {}\n'.format(v_name, hexlify(v))
bld_sigs.append(v)
dep_bld_sigs_str = "".join(bld_sigs)
m = Utils.md5()
m.update(dep_bld_sigs_str)
explicit_sig = m.digest()
if Logs.sig_delta:
key = self.uid()
prev_sig = bld.task_sigs.get((key, 'exp'), [])
if prev_sig and prev_sig != explicit_sig:
self.capture_signature_log('\nExplicit(Old):\n')
self.capture_signature_log(bld.last_build['exp_deps'].get(key,''))
self.capture_signature_log('\nExplicit(New):\n')
self.capture_signature_log(exp_output)
bld.last_build['exp_deps'][key] = exp_output
bld.task_sigs[(key, 'exp')] = explicit_sig
return explicit_sig
def sig_vars(self):
"""
Used by :py:meth:`waflib.Task.Task.signature`, hash :py:attr:`waflib.Task.Task.env` variables/values
:rtype: hash value
"""
bld = self.generator.bld
env = self.env
upd = self.m.update
key = self.uid()
# dependencies on the environment vars
act_sig = bld.hash_env_vars(env, self.__class__.vars)
upd(act_sig)
if Logs.sig_delta:
prev_act_sig = bld.task_sigs.get((key, 'env'), [])
prev_dep_sig = bld.task_sigs.get((key, 'dep_vars'), [])
bld.task_sigs[(key, 'env')] = act_sig
# additional variable dependencies, if provided
dep_vars = getattr(self, 'dep_vars', None)
dep_sig = ''
if dep_vars:
dep_sig = bld.hash_env_vars(env, dep_vars)
upd(dep_sig)
if Logs.sig_delta:
bld.task_sigs[(key, 'dep_vars')] = dep_sig
if prev_dep_sig and prev_dep_sig != dep_sig:
self.capture_signature_log('\nDep Vars:\n'+pprint.pformat(dep_vars))
if Logs.sig_delta:
if (prev_act_sig and prev_act_sig != act_sig) or (prev_dep_sig and prev_dep_sig != dep_sig):
self.capture_signature_log('\nEnv(Current):\n'+pprint.pformat(bld.debug_get_env_vars(env, self.__class__.vars)))
prev_env = bld.last_build['env'].get(key, {})
self.capture_signature_log('\nEnv(Last):\n'+pprint.pformat(prev_env))
bld.last_build['env'][key] = bld.debug_get_env_vars(env, self.__class__.vars)
return self.m.digest()
scan = None
"""
This method, when provided, returns a tuple containing:
* a list of nodes corresponding to real files
* a list of names for files not found in path_lst
For example::
from waflib.Task import Task
class mytask(Task):
def scan(self, node):
return ((), ())
The first and second lists are stored in :py:attr:`waflib.Build.BuildContext.node_deps` and
:py:attr:`waflib.Build.BuildContext.raw_deps` respectively.
"""
def sig_implicit_deps(self):
"""
Used by :py:meth:`waflib.Task.Task.signature` hashes node signatures obtained by scanning for dependencies (:py:meth:`waflib.Task.Task.scan`).
:rtype: hash value
"""
bld = self.generator.bld
# get the task signatures from previous runs
key = self.uid()
prev = bld.task_sigs.get((key, 'imp'), [])
# for issue #379
if prev:
try:
# if a dep is deleted, it will be missing. Don't warn, the signature will be different
sid = self.compute_sig_implicit_deps(False)
if prev == sid:
return prev
except Exception:
# when a file was renamed (IOError usually), remove the stale nodes (headers in folders without source files)
# this will break the order calculation for headers created during the build in the source directory (should be uncommon)
# the behaviour will differ when top != out
deps = bld.node_deps.get(self.uid(), [])
for x in deps:
if x.is_child_of(bld.srcnode):
try:
os.stat(x.abspath())
except OSError:
try:
del x.parent.children[x.name]
except KeyError:
pass
# the previous signature and the current signature don't match, delete the implicit deps, and cause a rescan below
del bld.task_sigs[(key, 'imp')]
# no previous run or the signature of the dependencies has changed, rescan the dependencies
(nodes, names) = self.scan()
if Logs.verbose:
Logs.debug('deps: scanner for %s returned %s %s' % (str(self), str(nodes), str(names)))
# store the dependencies in the cache
bld.node_deps[key] = nodes
bld.raw_deps[key] = names
# recompute the signature and return it
old_sig_debug_log = self.sig_implicit_debug_log
bld.task_sigs[(key, 'imp')] = sig = self.compute_sig_implicit_deps(False)
# Make the equality check since it's possible we didn't have a prior imp key but had prior nodes
# and said nodes didn't change
if Logs.sig_delta and old_sig_debug_log != self.sig_implicit_debug_log:
self.capture_signature_log('\nImplicit(Old):\n')
self.capture_signature_log(old_sig_debug_log)
self.capture_signature_log('\nImplicit(New):\n')
self.capture_signature_log(self.sig_implicit_debug_log)
return sig
def compute_sig_implicit_deps(self, warn_on_missing=True):
"""
Used by :py:meth:`waflib.Task.Task.sig_implicit_deps` for computing the actual hash of the
:py:class:`waflib.Node.Node` returned by the scanner.
:return: hash value
:rtype: string
"""
bld = self.generator.bld
self.are_implicit_nodes_ready()
self.sig_implicit_debug_log = ''
# scanner returns a node that does not have a signature
# just *ignore* the error and let them figure out from the compiler output
# waf -k behaviour
deps = bld.node_deps.get(self.uid(), [])
bld_sigs = []
for k in deps:
try:
bld_sig = k.get_bld_sig()
if Logs.sig_delta:
self.sig_implicit_debug_log += ('{} {}\n'.format(k.name, hexlify(bld_sig)))
except:
if warn_on_missing:
Logs.warn('Missing signature for node %r (dependency will not be tracked)' % k)
continue # skip adding the signature to the calculation, but continue adding other dependencies
bld_sigs.append(bld_sig)
dep_bld_sigs_str = "".join(bld_sigs)
m = Utils.md5()
m.update(dep_bld_sigs_str)
return m.digest()
def are_implicit_nodes_ready(self):
"""
For each node returned by the scanner, see if there is a task behind it, and force the build order
The performance impact on null builds is nearly invisible (1.66s->1.86s), but this is due to
agressive caching (1.86s->28s)
"""
bld = self.generator.bld
try:
cache = bld.dct_implicit_nodes
except AttributeError:
bld.dct_implicit_nodes = cache = {}
try:
dct = cache[bld.cur]
except KeyError:
dct = cache[bld.cur] = {}
for tsk in bld.cur_tasks:
for x in tsk.outputs:
dct[x] = tsk
# find any dependency that is not part of the run_after set already
deps = bld.node_deps.get(self.uid(), [])
deps_missing_from_runafter = [dct[i] for i in deps if i in dct and dct[i] not in self.run_after]
# verify that all tasks have not already run
for tsk in deps_missing_from_runafter:
if not tsk.hasrun:
#print "task is not ready..."
raise Errors.TaskNotReady('not ready')
# update the run_after tasks
self.run_after.update(deps_missing_from_runafter)
def capture_signature_log(self, output):
"""
Logging function to aggregate info on what caused the task signature to change between runs
"""
if hasattr(self, 'sig_debug_output'):
self.sig_debug_output += output
def can_retrieve_cache(self):
"""
Used by :py:meth:`waflib.Task.cache_outputs`
Retrieve build nodes from the cache
update the file timestamps to help cleaning the least used entries from the cache
additionally, set an attribute 'cached' to avoid re-creating the same cache files
Suppose there are files in `cache/dir1/file1` and `cache/dir2/file2`:
#. read the timestamp of dir1
#. try to copy the files
#. look at the timestamp again, if it has changed, the data may have been corrupt (cache update by another process)
#. should an exception occur, ignore the data
"""
if not getattr(self, 'outputs', None):
return None
sig = self.signature()
ssig = Utils.to_hex(self.uid()) + Utils.to_hex(sig)
# first try to access the cache folder for the task
dname = os.path.join(self.generator.bld.cache_global, ssig)
try:
t1 = os.stat(dname).st_mtime
except OSError:
return None
for node in self.outputs:
orig = os.path.join(dname, node.name)
try:
shutil.copy2(orig, node.abspath())
# mark the cache file as used recently (modified)
os.utime(orig, None)
except (OSError, IOError):
Logs.debug('task: failed retrieving file')
return None
# is it the same folder?
try:
t2 = os.stat(dname).st_mtime
except OSError:
return None
if t1 != t2:
return None
for node in self.outputs:
node.sig = sig
if self.generator.bld.progress_bar < 1:
self.generator.bld.to_log('restoring from cache %r\n' % node.abspath())
self.cached = True
return True
def put_files_cache(self):
"""
Used by :py:func:`waflib.Task.cache_outputs` to store the build files in the cache
"""
# file caching, if possible
# try to avoid data corruption as much as possible
if getattr(self, 'cached', None):
return None
if not getattr(self, 'outputs', None):
return None
sig = self.signature()
ssig = Utils.to_hex(self.uid()) + Utils.to_hex(sig)
dname = os.path.join(self.generator.bld.cache_global, ssig)
tmpdir = tempfile.mkdtemp(prefix=self.generator.bld.cache_global + os.sep + 'waf')
try:
shutil.rmtree(dname)
except Exception:
pass
try:
for node in self.outputs:
dest = os.path.join(tmpdir, node.name)
shutil.copy2(node.abspath(), dest)
except (OSError, IOError):
try:
shutil.rmtree(tmpdir)
except Exception:
pass
else:
try:
os.rename(tmpdir, dname)
except OSError:
try:
shutil.rmtree(tmpdir)
except Exception:
pass
else:
try:
os.chmod(dname, Utils.O755)
except Exception:
pass
def is_before(t1, t2):
"""
Return a non-zero value if task t1 is to be executed before task t2::
t1.ext_out = '.h'
t2.ext_in = '.h'
t2.after = ['t1']
t1.before = ['t2']
waflib.Task.is_before(t1, t2) # True
:param t1: task
:type t1: :py:class:`waflib.Task.TaskBase`
:param t2: task
:type t2: :py:class:`waflib.Task.TaskBase`
"""
to_list = Utils.to_list
for k in to_list(t2.ext_in):
if k in to_list(t1.ext_out):
return 1
if t1.__class__.__name__ in to_list(t2.after):
return 1
if t2.__class__.__name__ in to_list(t1.before):
return 1
return 0
def set_file_constraints(tasks):
"""
Adds tasks to the task 'run_after' attribute based on the task inputs and outputs
:param tasks: tasks
:type tasks: list of :py:class:`waflib.Task.TaskBase`
"""
ins = Utils.defaultdict(set)
outs = Utils.defaultdict(set)
for x in tasks:
for a in getattr(x, 'inputs', []) + getattr(x, 'dep_nodes', []):
ins[id(a)].add(x)
for a in getattr(x, 'outputs', []):
outs[id(a)].add(x)
links = set(ins.keys()).intersection(outs.keys())
for k in links:
for a in ins[k]:
a.run_after.update(outs[k])
def set_precedence_constraints(tasks):
"""
Add tasks to the task 'run_after' attribute based on the after/before/ext_out/ext_in attributes
:param tasks: tasks
:type tasks: list of :py:class:`waflib.Task.TaskBase`
"""
cstr_groups = Utils.defaultdict(list)
for x in tasks:
h = x.hash_constraints()
cstr_groups[h].append(x)
keys = list(cstr_groups.keys())
maxi = len(keys)
# this list should be short
for i in range(maxi):
t1 = cstr_groups[keys[i]][0]
for j in range(i + 1, maxi):
t2 = cstr_groups[keys[j]][0]
# add the constraints based on the comparisons
if is_before(t1, t2):
a = i
b = j
elif is_before(t2, t1):
a = j
b = i
else:
continue
aval = set(cstr_groups[keys[a]])
for x in cstr_groups[keys[b]]:
x.run_after.update(aval)
def funex(c):
"""
Compile a function by 'exec'
:param c: function to compile
:type c: string
:return: the function 'f' declared in the input string
:rtype: function
"""
dc = {}
exec(c, dc)
return dc['f']
reg_act = re.compile(r"(?P<backslash>\\)|(?P<dollar>\$\$)|(?P<subst>\$\{(?P<var>\w+)(?P<code>.*?)\})", re.M)
def compile_fun_shell(line):
"""
Create a compiled function to execute a process with the shell
WARNING: this method may disappear anytime, so use compile_fun instead
"""
extr = []
def repl(match):
g = match.group
if g('dollar'): return "$"
elif g('backslash'): return '\\\\'
elif g('subst'): extr.append((g('var'), g('code'))); return "%s"
return None
line = reg_act.sub(repl, line) or line
parm = []
dvars = []
app = parm.append
for (var, meth) in extr:
if var == 'SRC':
if meth: app('tsk.inputs%s' % meth)
else: app('" ".join([a.path_from(bld.bldnode) for a in tsk.inputs])')
elif var == 'ABS_SRC':
if meth: app('tsk.inputs%s' % meth)
else: app('" ".join([\'"{}"\'.format(a.abspath()) for a in tsk.inputs])')
elif var == 'TGT':
if meth: app('tsk.outputs%s' % meth)
else: app('" ".join([a.path_from(bld.bldnode) for a in tsk.outputs])')
elif meth:
if meth.startswith(':'):
m = meth[1:]
if m == 'SRC':
m = '[a.path_from(bld.bldnode) for a in tsk.inputs]'
if m == 'ABS_SRC':
m = '[a.abspath() for a in tsk.inputs]'
elif m == 'TGT':
m = '[a.path_from(bld.bldnode) for a in tsk.outputs]'
elif m[:3] not in ('tsk', 'gen', 'bld'):
dvars.extend([var, meth[1:]])
m = '%r' % m
app('" ".join(tsk.colon(%r, %s))' % (var, m))
else:
app('%s%s' % (var, meth))
else:
if not var in dvars: dvars.append(var)
app("p('%s')" % var)
if parm: parm = "%% (%s) " % (',\n\t\t'.join(parm))
else: parm = ''
c = COMPILE_TEMPLATE_SHELL % (line, parm)
Logs.debug('action: %s' % c.strip().splitlines())
return (funex(c), dvars)
def compile_fun_noshell(line):
"""
Create a compiled function to execute a process without the shell
WARNING: this method may disappear anytime, so use compile_fun instead
"""
extr = []
def repl(match):
g = match.group
if g('dollar'): return "$"
elif g('subst'): extr.append((g('var'), g('code'))); return "<<|@|>>"
return None
line2 = reg_act.sub(repl, line)
params = line2.split('<<|@|>>')
assert(extr)
buf = []
dvars = []
app = buf.append
for x in range(len(extr)):
params[x] = params[x].strip()
if params[x]:
app("lst.extend(%r)" % params[x].split())
(var, meth) = extr[x]
if var == 'SRC':
if meth: app('lst.append(tsk.inputs%s)' % meth)
else: app("lst.extend([a.abspath() for a in tsk.inputs])")
elif var == 'TGT':
if meth: app('lst.append(tsk.outputs%s)' % meth)
else: app("lst.extend([a.abspath() for a in tsk.outputs])")
elif meth:
if meth.startswith(':'):
m = meth[1:]
if m == 'SRC':
m = '[a.abspath() for a in tsk.inputs]'
elif m == 'TGT':
m = '[a.abspath() for a in tsk.outputs]'
elif m[:3] not in ('tsk', 'gen', 'bld'):
dvars.extend([var, m])
m = '%r' % m
app('lst.extend(tsk.colon(%r, %s))' % (var, m))
else:
app('lst.extend(gen.to_list(%s%s))' % (var, meth))
else:
app('lst.extend(to_list(env[%r]))' % var)
if not var in dvars: dvars.append(var)
if extr:
if params[-1]:
app("lst.extend(%r)" % params[-1].split())
fun = COMPILE_TEMPLATE_NOSHELL % "\n\t".join(buf)
Logs.debug('action: %s' % fun.strip().splitlines())
return (funex(fun), dvars)
def compile_fun(line, shell=False):
"""
Parse a string expression such as "${CC} ${SRC} -o ${TGT}" and return a pair containing:
* the function created (compiled) for use as :py:meth:`waflib.Task.TaskBase.run`
* the list of variables that imply a dependency from self.env
for example::
from waflib.Task import compile_fun
compile_fun('cxx', '${CXX} -o ${TGT[0]} ${SRC} -I ${SRC[0].parent.bldpath()}')
def build(bld):
bld(source='wscript', rule='echo "foo\\${SRC[0].name}\\bar"')
The env variables (CXX, ..) on the task must not hold dicts (order)
The reserved keywords *TGT* and *SRC* represent the task input and output nodes
"""
if line.find('<') > 0 or line.find('>') > 0 or line.find('&&') > 0:
shell = True
if shell:
return compile_fun_shell(line)
else:
return compile_fun_noshell(line)
def task_factory(name, func=None, vars=None, color='GREEN', ext_in=[], ext_out=[], before=[], after=[], shell=False, scan=None):
"""
Deprecated. Return a new task subclass with the function ``run`` compiled from the line given.
Provided for compatibility with waf 1.4-1.5, when we did not have the metaclass to register new classes (will be removed in Waf 1.8)
:param func: method run
:type func: string or function
:param vars: list of variables to hash
:type vars: list of string
:param color: color to use
:type color: string
:param shell: when *func* is a string, enable/disable the use of the shell
:type shell: bool
:param scan: method scan
:type scan: function
:rtype: :py:class:`waflib.Task.Task`
"""
params = {
'vars': vars or [], # function arguments are static, and this one may be modified by the class
'color': color,
'name': name,
'ext_in': Utils.to_list(ext_in),
'ext_out': Utils.to_list(ext_out),
'before': Utils.to_list(before),
'after': Utils.to_list(after),
'shell': shell,
'scan': scan,
}
if isinstance(func, str):
params['run_str'] = func
else:
params['run'] = func
cls = type(Task)(name, (Task,), params)
global classes
classes[name] = cls
return cls
def always_run(cls):
"""
Task class decorator
Set all task instances of this class to be executed whenever a build is started
The task signature is calculated, but the result of the comparation between
task signatures is bypassed
"""
old = cls.runnable_status
def always(self):
ret = old(self)
if ret == SKIP_ME:
ret = RUN_ME
return ret
cls.runnable_status = always
return cls
def update_outputs(cls):
"""
Task class decorator
If you want to create files in the source directory. For example, to keep *foo.txt* in the source
directory, create it first and declare::
def build(bld):
bld(rule='cp ${SRC} ${TGT}', source='wscript', target='foo.txt', update_outputs=True)
"""
old_post_run = cls.post_run
def post_run(self):
old_post_run(self)
for node in self.outputs:
node.sig = node.cache_sig = Utils.h_file(node.abspath())
self.generator.bld.task_sigs[node.abspath()] = self.uid() # issue #1017
cls.post_run = post_run
old_runnable_status = cls.runnable_status
def runnable_status(self):
status = old_runnable_status(self)
if status != RUN_ME:
return status
try:
# by default, we check that the output nodes have the signature of the task
# perform a second check, returning 'SKIP_ME' as we are expecting that
# the signatures do not match
bld = self.generator.bld
prev_sig = bld.task_sigs[self.uid()]
if prev_sig == self.signature():
for x in self.outputs:
if not x.sig or bld.task_sigs[x.abspath()] != self.uid():
return RUN_ME
return SKIP_ME
except KeyError:
pass
except IndexError:
pass
except AttributeError:
pass
return RUN_ME
cls.runnable_status = runnable_status
return cls
| set_outputs |
rounding_tests.rs | use minimal_lexical::extended_float::ExtendedFloat;
use minimal_lexical::rounding;
#[test]
fn round_test() | {
let mut fp = ExtendedFloat {
mant: 9223372036854776832,
exp: -10,
};
rounding::round::<f64, _>(&mut fp, |f, s| {
f.mant >>= s;
f.exp += s;
});
assert_eq!(fp.mant, 0);
assert_eq!(fp.exp, 1);
let mut fp = ExtendedFloat {
mant: 9223372036854776832,
exp: -10,
};
rounding::round::<f64, _>(&mut fp, |f, s| {
f.mant >>= s;
f.exp += s;
// Round-up.
f.mant += 1;
});
assert_eq!(fp.mant, 1);
assert_eq!(fp.exp, 1);
// Round-down
let mut fp = ExtendedFloat {
mant: 9223372036854776832,
exp: -10,
};
rounding::round::<f64, _>(&mut fp, |f, s| {
rounding::round_nearest_tie_even(f, s, |is_odd, is_halfway, is_above| {
is_above || (is_odd && is_halfway)
});
});
assert_eq!(fp.mant, 0);
assert_eq!(fp.exp, 1);
// Round up
let mut fp = ExtendedFloat {
mant: 9223372036854778880,
exp: -10,
};
rounding::round::<f64, _>(&mut fp, |f, s| {
rounding::round_nearest_tie_even(f, s, |is_odd, is_halfway, is_above| {
is_above || (is_odd && is_halfway)
});
});
assert_eq!(fp.mant, 2);
assert_eq!(fp.exp, 1);
// Round down
let mut fp = ExtendedFloat {
mant: 9223372036854778880,
exp: -10,
};
rounding::round::<f64, _>(&mut fp, rounding::round_down);
assert_eq!(fp.mant, 1);
assert_eq!(fp.exp, 1);
} |
|
AppConstant.constant.js | * =========================================================================
* Copyright 2018 T-Mobile, US
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* See the readme.txt file for additional language around disclaimer of warranties.
* =========================================================================
*/
'use strict';
( function( app ) {
app.constant( 'AppConstant', {
// TO-BE-UPDATED : Link to be updated once the functionality is decided
'FORGOT_PASSWORD_LINK' : '',
'PERISCOPE_LINK' : '',
'PERISCOPE_GET_ROLES_LINK' : '',
'PERISCOPE_GET_ROLES_KEY' : '',
'PERISCOPE_GET_USERS_LINK' : '',
'PERISCOPE_GET_USERS_KEY' : '',
'PERISCOPE_KEY' : '',
'X-API-KEY' : ''
} );
} )( angular.module( 'pacman.constants.AppConstant', [] ) ); | /* |
|
dnspolicy_dnsglobal_binding.go | /*
* Copyright (c) 2021 Citrix Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dns
/**
* Binding class showing the dnsglobal that can be bound to dnspolicy.
*/
type Dnspolicydnsglobalbinding struct {
/**
* Location where policy is bound
*/
Boundto string `json:"boundto,omitempty"`
/**
* Specifies the priority of the policy.
*/
Priority int `json:"priority,omitempty"`
/**
* Indicates whether policy is bound or not.
*/
Activepolicy int `json:"activepolicy,omitempty"`
/**
* Expression specifying the priority of the next policy which will get evaluated if the current policy rule evaluates to TRUE.
*/
Gotopriorityexpression string `json:"gotopriorityexpression,omitempty"`
/**
* Type of policy label invocation.
*/
Labeltype string `json:"labeltype,omitempty"`
/**
* Name of the label to invoke if the current policy rule evaluates to TRUE.
*/
Labelname string `json:"labelname,omitempty"`
/**
* Name of the DNS policy.
*/
Name string `json:"name,omitempty"`
| } | |
fn_test.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 graph
import (
"context"
"reflect"
"testing"
"github.com/apache/beam/sdks/go/pkg/beam/core/typex"
)
func TestNewDoFn(t *testing.T) {
t.Run("valid", func(t *testing.T) {
tests := []struct {
dfn interface{}
opt func(*config)
}{
{dfn: func(string) int { return 0 }, opt: NumMainInputs(MainSingle)},
{dfn: func(string, int) int { return 0 }, opt: NumMainInputs(MainKv)},
{dfn: func(context.Context, typex.Window, typex.EventTime, reflect.Type, string, int, func(*int) bool, func() func(*int) bool, func(int)) (typex.EventTime, int, error) {
return 0, 0, nil
}, opt: NumMainInputs(MainKv)},
{dfn: &GoodDoFn{}, opt: NumMainInputs(MainSingle)},
{dfn: &GoodDoFnOmittedMethods{}, opt: NumMainInputs(MainSingle)},
{dfn: &GoodDoFnEmits{}, opt: NumMainInputs(MainSingle)},
{dfn: &GoodDoFnSideInputs{}, opt: NumMainInputs(MainSingle)},
{dfn: &GoodDoFnKv{}, opt: NumMainInputs(MainKv)},
{dfn: &GoodDoFnKvSideInputs{}, opt: NumMainInputs(MainKv)},
{dfn: &GoodDoFnAllExtras{}, opt: NumMainInputs(MainKv)},
{dfn: &GoodDoFnUnexportedExtraMethod{}, opt: NumMainInputs(MainSingle)},
{dfn: &GoodDoFnCoGbk1{}, opt: NumMainInputs(MainKv)},
{dfn: &GoodDoFnCoGbk2{}, opt: CoGBKMainInput(3)},
{dfn: &GoodDoFnCoGbk7{}, opt: CoGBKMainInput(8)},
{dfn: &GoodDoFnCoGbk1wSide{}, opt: NumMainInputs(MainKv)},
}
for _, test := range tests {
t.Run(reflect.TypeOf(test.dfn).String(), func(t *testing.T) {
// Valid DoFns should pass validation with and without KV info.
if _, err := NewDoFn(test.dfn); err != nil {
t.Fatalf("NewDoFn failed: %v", err)
}
if _, err := NewDoFn(test.dfn, test.opt); err != nil {
cfg := defaultConfig()
test.opt(cfg)
t.Fatalf("NewDoFn(%#v) failed: %v", cfg, err)
}
})
}
})
t.Run("invalid", func(t *testing.T) {
tests := []struct {
dfn interface{}
}{
// Validate main inputs.
{dfn: func() int { return 0 }}, // No inputs.
{dfn: func(func(*int) bool, int) int { // Side input before main input.
return 0
}},
{dfn: &BadDoFnHasRTracker{}},
// Validate emit parameters.
{dfn: &BadDoFnNoEmitsStartBundle{}},
{dfn: &BadDoFnMissingEmitsStartBundle{}},
{dfn: &BadDoFnMismatchedEmitsStartBundle{}},
{dfn: &BadDoFnNoEmitsFinishBundle{}},
// Validate side inputs.
{dfn: &BadDoFnMissingSideInputsStartBundle{}},
{dfn: &BadDoFnMismatchedSideInputsStartBundle{}},
// Validate setup/teardown.
{dfn: &BadDoFnParamsInSetup{}},
{dfn: &BadDoFnParamsInTeardown{}},
// Validate return values.
{dfn: &BadDoFnReturnValuesInStartBundle{}},
{dfn: &BadDoFnReturnValuesInFinishBundle{}},
{dfn: &BadDoFnReturnValuesInSetup{}},
{dfn: &BadDoFnReturnValuesInTeardown{}},
}
for _, test := range tests {
t.Run(reflect.TypeOf(test.dfn).String(), func(t *testing.T) {
if cfn, err := NewDoFn(test.dfn); err != nil {
t.Logf("NewDoFn failed as expected:\n%v", err)
} else {
t.Errorf("NewDoFn(%v) = %v, want failure", cfn.Name(), cfn)
}
// If validation fails with unknown main inputs, then it should
// always fail for any known number of main inputs, so test them
// all. Error messages won't necessarily match.
if cfn, err := NewDoFn(test.dfn, NumMainInputs(MainSingle)); err != nil {
t.Logf("NewDoFn failed as expected:\n%v", err)
} else {
t.Errorf("NewDoFn(%v, NumMainInputs(MainSingle)) = %v, want failure", cfn.Name(), cfn)
}
if cfn, err := NewDoFn(test.dfn, NumMainInputs(MainKv)); err != nil {
t.Logf("NewDoFn failed as expected:\n%v", err)
} else {
t.Errorf("NewDoFn(%v, NumMainInputs(MainKv)) = %v, want failure", cfn.Name(), cfn)
}
})
}
})
// Tests ambiguous situations that pass DoFn validation when number of main
// inputs is unknown, but fails when it's specified.
t.Run("invalidWithKnownKvs", func(t *testing.T) {
tests := []struct {
dfn interface{}
main mainInputs
}{
{dfn: func(int) int { return 0 }, main: MainKv}, // Not enough inputs.
{dfn: func(int, func(int)) int { // Emit before all main inputs.
return 0
}, main: MainKv},
{dfn: &BadDoFnAmbiguousMainInput{}, main: MainKv},
{dfn: &BadDoFnAmbiguousSideInput{}, main: MainSingle},
// These are ambiguous with CoGBKs, but should fail with known MainInputs.
{dfn: &BadDoFnNoSideInputsStartBundle{}, main: MainSingle},
{dfn: &BadDoFnNoSideInputsStartBundle{}, main: MainKv},
{dfn: &BadDoFnNoSideInputsFinishBundle{}, main: MainSingle},
{dfn: &BadDoFnNoSideInputsFinishBundle{}, main: MainKv},
}
for _, test := range tests {
t.Run(reflect.TypeOf(test.dfn).String(), func(t *testing.T) {
// These tests should be ambiguous enough to pass NewDoFn. If
// validation improves and they start failing, move the test
// cases to "invalid".
if _, err := NewDoFn(test.dfn); err != nil {
t.Fatalf("NewDoFn failed: %v", err)
}
if cfn, err := NewDoFn(test.dfn, NumMainInputs(test.main)); err != nil {
t.Logf("NewDoFn failed as expected:\n%v", err)
} else {
t.Errorf("NewDoFn(%v, NumMainInputs(%v)) = %v, want failure", cfn.Name(), test.main, cfn)
}
})
}
})
}
func TestNewDoFnSdf(t *testing.T) {
t.Run("valid", func(t *testing.T) {
tests := []struct {
dfn interface{}
main mainInputs
}{
{dfn: &GoodSdf{}, main: MainSingle},
{dfn: &GoodSdfKv{}, main: MainKv},
}
for _, test := range tests {
t.Run(reflect.TypeOf(test.dfn).String(), func(t *testing.T) {
// Valid DoFns should pass validation with and without KV info.
if _, err := NewDoFn(test.dfn); err != nil {
t.Fatalf("NewDoFn with SDF failed: %v", err)
}
if _, err := NewDoFn(test.dfn, NumMainInputs(test.main)); err != nil {
t.Fatalf("NewDoFn(NumMainInputs(%v)) with SDF failed: %v", test.main, err)
}
})
}
})
t.Run("invalid", func(t *testing.T) {
tests := []struct {
dfn interface{}
}{
// Validate missing SDF methods cause errors.
{dfn: &BadSdfMissingMethods{}},
// Validate param numbers.
{dfn: &BadSdfParamsCreateRest{}},
{dfn: &BadSdfParamsSplitRest{}},
{dfn: &BadSdfParamsRestSize{}},
{dfn: &BadSdfParamsCreateTracker{}},
// Validate return numbers.
{dfn: &BadSdfReturnsCreateRest{}},
{dfn: &BadSdfReturnsSplitRest{}},
{dfn: &BadSdfReturnsRestSize{}},
{dfn: &BadSdfReturnsCreateTracker{}},
// Validate element types consistent with ProcessElement.
{dfn: &BadSdfElementTCreateRest{}},
{dfn: &BadSdfElementTSplitRest{}},
{dfn: &BadSdfElementTRestSize{}},
// Validate restriction type consistent with CreateRestriction.
{dfn: &BadSdfRestTSplitRestParam{}},
{dfn: &BadSdfRestTSplitRestReturn{}},
{dfn: &BadSdfRestTRestSize{}},
{dfn: &BadSdfRestTCreateTracker{}},
// Validate other types
{dfn: &BadSdfRestSizeReturn{}},
{dfn: &BadSdfCreateTrackerReturn{}},
{dfn: &BadSdfMismatchedRTracker{}},
{dfn: &BadSdfMissingRTracker{}},
}
for _, test := range tests {
t.Run(reflect.TypeOf(test.dfn).String(), func(t *testing.T) {
if cfn, err := NewDoFn(test.dfn); err != nil {
t.Logf("NewDoFn with SDF failed as expected:\n%v", err)
} else {
t.Errorf("NewDoFn(%v) = %v, want failure", cfn.Name(), cfn)
}
// If validation fails with unknown main inputs, then it should
// always fail for any known number of main inputs, so test them
// all. Error messages won't necessarily match.
if cfn, err := NewDoFn(test.dfn, NumMainInputs(MainSingle)); err != nil {
t.Logf("NewDoFn(NumMainInputs(MainSingle)) with SDF failed as expected:\n%v", err)
} else {
t.Errorf("NewDoFn(%v, NumMainInputs(MainSingle)) = %v, want failure", cfn.Name(), cfn)
}
if cfn, err := NewDoFn(test.dfn, NumMainInputs(MainKv)); err != nil {
t.Logf("NewDoFn(NumMainInputs(MainKv)) with SDF failed as expected:\n%v", err)
} else {
t.Errorf("NewDoFn(%v, NumMainInputs(MainKv)) = %v, want failure", cfn.Name(), cfn)
}
})
}
})
}
func | (t *testing.T) {
t.Run("valid", func(t *testing.T) {
tests := []struct {
cfn interface{}
}{
{cfn: func(int, int) int { return 0 }},
{cfn: func(string, string) string { return "" }},
{cfn: func(MyAccum, MyAccum) MyAccum { return MyAccum{} }},
{cfn: func(MyAccum, MyAccum) (MyAccum, error) { return MyAccum{}, nil }},
{cfn: func(context.Context, MyAccum, MyAccum) MyAccum { return MyAccum{} }},
{cfn: func(context.Context, MyAccum, MyAccum) (MyAccum, error) { return MyAccum{}, nil }},
{cfn: &GoodCombineFn{}},
{cfn: &GoodWErrorCombineFn{}},
{cfn: &GoodWContextCombineFn{}},
{cfn: &GoodCombineFnUnexportedExtraMethod{}},
}
for _, test := range tests {
t.Run(reflect.TypeOf(test.cfn).String(), func(t *testing.T) {
if _, err := NewCombineFn(test.cfn); err != nil {
t.Fatalf("NewCombineFn failed: %v", err)
}
})
}
})
t.Run("invalid", func(t *testing.T) {
tests := []struct {
cfn interface{}
}{
// Validate MergeAccumulator errors
{cfn: func() int { return 0 }},
{cfn: func(int, int) {}},
{cfn: func(int, int) string { return "" }},
{cfn: func(string, string) int { return 0 }},
{cfn: func(int, string) int { return 0 }},
{cfn: func(string, int) int { return 0 }},
{cfn: func(string, int) (int, error) { return 0, nil }},
{cfn: &BadCombineFnNoMergeAccumulators{}},
{cfn: &BadCombineFnNonBinaryMergeAccumulators{}},
// Validate accumulator type mismatches
{cfn: &BadCombineFnMisMatchedCreateAccumulator{}},
{cfn: &BadCombineFnMisMatchedAddInputIn{}},
{cfn: &BadCombineFnMisMatchedAddInputOut{}},
{cfn: &BadCombineFnMisMatchedAddInputBoth{}},
{cfn: &BadCombineFnMisMatchedExtractOutput{}},
// Validate signatures
{cfn: &BadCombineFnInvalidCreateAccumulator1{}},
{cfn: &BadCombineFnInvalidCreateAccumulator2{}},
{cfn: &BadCombineFnInvalidCreateAccumulator3{}},
{cfn: &BadCombineFnInvalidCreateAccumulator4{}},
{cfn: &BadCombineFnInvalidAddInput1{}},
{cfn: &BadCombineFnInvalidAddInput2{}},
{cfn: &BadCombineFnInvalidAddInput3{}},
{cfn: &BadCombineFnInvalidAddInput4{}},
{cfn: &BadCombineFnInvalidExtractOutput1{}},
{cfn: &BadCombineFnInvalidExtractOutput2{}},
{cfn: &BadCombineFnInvalidExtractOutput3{}},
{cfn: &BadCombineFnExtraExportedMethod{}},
}
for _, test := range tests {
t.Run(reflect.TypeOf(test.cfn).String(), func(t *testing.T) {
if cfn, err := NewCombineFn(test.cfn); err != nil {
// Note to Developer: To work on improving the error messages, use t.Errorf instead!
t.Logf("NewCombineFn failed as expected:\n%v", err)
} else {
t.Errorf("AsCombineFn(%v) = %v, want failure", cfn.Name(), cfn)
}
})
}
})
}
// Do not copy. The following types are for testing signatures only.
// They are not working examples.
// Keep all test functions Above this point.
// Examples of correct DoFn signatures
type GoodDoFn struct{}
func (fn *GoodDoFn) ProcessElement(int) int {
return 0
}
func (fn *GoodDoFn) StartBundle() {
}
func (fn *GoodDoFn) FinishBundle() {
}
func (fn *GoodDoFn) Setup() {
}
func (fn *GoodDoFn) Teardown() {
}
type GoodDoFnOmittedMethods struct{}
func (fn *GoodDoFnOmittedMethods) ProcessElement(int) int {
return 0
}
type GoodDoFnEmits struct{}
func (fn *GoodDoFnEmits) ProcessElement(int, func(int), func(string)) int {
return 0
}
func (fn *GoodDoFnEmits) StartBundle(func(int), func(string)) {
}
func (fn *GoodDoFnEmits) FinishBundle(func(int), func(string)) {
}
type GoodDoFnSideInputs struct{}
func (fn *GoodDoFnSideInputs) ProcessElement(int, func(*int) bool, string, func() func(*int) bool) int {
return 0
}
func (fn *GoodDoFnSideInputs) StartBundle(func(*int) bool, string, func() func(*int) bool) {
}
func (fn *GoodDoFnSideInputs) FinishBundle(func(*int) bool, string, func() func(*int) bool) {
}
type GoodDoFnKv struct{}
func (fn *GoodDoFnKv) ProcessElement(int, int) int {
return 0
}
func (fn *GoodDoFnKv) StartBundle() {
}
func (fn *GoodDoFnKv) FinishBundle() {
}
type GoodDoFnKvSideInputs struct{}
func (fn *GoodDoFnKvSideInputs) ProcessElement(int, int, string, func(*int) bool, func() func(*int) bool) int {
return 0
}
func (fn *GoodDoFnKvSideInputs) StartBundle(string, func(*int) bool, func() func(*int) bool) {
}
func (fn *GoodDoFnKvSideInputs) FinishBundle(string, func(*int) bool, func() func(*int) bool) {
}
type GoodDoFnCoGbk1 struct{}
func (fn *GoodDoFnCoGbk1) ProcessElement(int, func(*string) bool) int {
return 0
}
func (fn *GoodDoFnCoGbk1) StartBundle() {
}
func (fn *GoodDoFnCoGbk1) FinishBundle() {
}
type GoodDoFnCoGbk2 struct{}
func (fn *GoodDoFnCoGbk2) ProcessElement(int, func(*int) bool, func(*string) bool) int {
return 0
}
func (fn *GoodDoFnCoGbk2) StartBundle() {
}
func (fn *GoodDoFnCoGbk2) FinishBundle() {
}
type GoodDoFnCoGbk7 struct{}
func (fn *GoodDoFnCoGbk7) ProcessElement(k int, v1, v2, v3, v4, v5, v6, v7 func(*int) bool) int {
return 0
}
func (fn *GoodDoFnCoGbk7) StartBundle() {
}
func (fn *GoodDoFnCoGbk7) FinishBundle() {
}
type GoodDoFnCoGbk1wSide struct{}
func (fn *GoodDoFnCoGbk1wSide) ProcessElement(int, func(*string) bool, func(*int) bool) int {
return 0
}
func (fn *GoodDoFnCoGbk1wSide) StartBundle(func(*int) bool) {
}
func (fn *GoodDoFnCoGbk1wSide) FinishBundle(func(*int) bool) {
}
type GoodDoFnAllExtras struct{}
func (fn *GoodDoFnAllExtras) ProcessElement(context.Context, typex.Window, typex.EventTime, reflect.Type, string, int, func(*int) bool, func() func(*int) bool, func(int)) (typex.EventTime, int, error) {
return 0, 0, nil
}
func (fn *GoodDoFnAllExtras) StartBundle(context.Context, func(*int) bool, func() func(*int) bool, func(int)) {
}
func (fn *GoodDoFnAllExtras) FinishBundle(context.Context, func(*int) bool, func() func(*int) bool, func(int)) {
}
func (fn *GoodDoFnAllExtras) Setup(context.Context) error {
return nil
}
func (fn *GoodDoFnAllExtras) Teardown(context.Context) error {
return nil
}
type GoodDoFnUnexportedExtraMethod struct{}
func (fn *GoodDoFnUnexportedExtraMethod) ProcessElement(int) int {
return 0
}
func (fn *GoodDoFnUnexportedExtraMethod) StartBundle() {
}
func (fn *GoodDoFnUnexportedExtraMethod) FinishBundle() {
}
func (fn *GoodDoFnUnexportedExtraMethod) Setup() {
}
func (fn *GoodDoFnUnexportedExtraMethod) Teardown() {
}
func (fn *GoodDoFnUnexportedExtraMethod) unexportedFunction() {
}
// Examples of incorrect DoFn signatures.
// Embedding good DoFns avoids repetitive ProcessElement signatures when desired.
type BadDoFnHasRTracker struct {
*GoodDoFn
}
func (fn *BadDoFnHasRTracker) ProcessElement(*RTrackerT, int) int {
return 0
}
// Examples of emit parameter mismatches.
type BadDoFnNoEmitsStartBundle struct {
*GoodDoFnEmits
}
func (fn *BadDoFnNoEmitsStartBundle) StartBundle() {
}
type BadDoFnMissingEmitsStartBundle struct {
*GoodDoFnEmits
}
func (fn *BadDoFnMissingEmitsStartBundle) StartBundle(func(int)) {
}
type BadDoFnMismatchedEmitsStartBundle struct {
*GoodDoFnEmits
}
func (fn *BadDoFnMismatchedEmitsStartBundle) StartBundle(func(int), func(int)) {
}
type BadDoFnNoEmitsFinishBundle struct {
*GoodDoFnEmits
}
func (fn *BadDoFnNoEmitsFinishBundle) FinishBundle() {
}
// Examples of side input mismatches.
type BadDoFnNoSideInputsStartBundle struct {
*GoodDoFnSideInputs
}
func (fn *BadDoFnNoSideInputsStartBundle) StartBundle() {
}
type BadDoFnMissingSideInputsStartBundle struct {
*GoodDoFnSideInputs
}
func (fn *BadDoFnMissingSideInputsStartBundle) StartBundle(func(*int) bool) {
}
type BadDoFnMismatchedSideInputsStartBundle struct {
*GoodDoFnSideInputs
}
func (fn *BadDoFnMismatchedSideInputsStartBundle) StartBundle(func(*int) bool, int, func() func(*int)) {
}
type BadDoFnNoSideInputsFinishBundle struct {
*GoodDoFnSideInputs
}
func (fn *BadDoFnNoSideInputsFinishBundle) FinishBundle() {
}
// Examples of incorrect Setup/Teardown methods.
type BadDoFnParamsInSetup struct {
*GoodDoFn
}
func (*BadDoFnParamsInSetup) Setup(int) {
}
type BadDoFnParamsInTeardown struct {
*GoodDoFn
}
func (*BadDoFnParamsInTeardown) Teardown(int) {
}
type BadDoFnReturnValuesInStartBundle struct {
*GoodDoFn
}
func (*BadDoFnReturnValuesInStartBundle) StartBundle() int {
return 0
}
type BadDoFnReturnValuesInFinishBundle struct {
*GoodDoFn
}
func (*BadDoFnReturnValuesInFinishBundle) FinishBundle() int {
return 0
}
type BadDoFnReturnValuesInSetup struct {
*GoodDoFn
}
func (*BadDoFnReturnValuesInSetup) Setup() int {
return 0
}
type BadDoFnReturnValuesInTeardown struct {
*GoodDoFn
}
func (*BadDoFnReturnValuesInTeardown) Teardown() int {
return 0
}
type BadDoFnAmbiguousMainInput struct {
*GoodDoFn
}
// Ambiguous param #2 (string) is a main input but used as side input.
func (fn *BadDoFnAmbiguousMainInput) ProcessElement(int, string, bool) int {
return 0
}
func (fn *BadDoFnAmbiguousMainInput) StartBundle(string, bool) {
}
func (fn *BadDoFnAmbiguousMainInput) FinishBundle(string, bool) {
}
type BadDoFnAmbiguousSideInput struct {
*GoodDoFn
}
// Ambiguous param #2 (string) is a side input but used as main input.
func (fn *BadDoFnAmbiguousSideInput) ProcessElement(int, string, bool) int {
return 0
}
func (fn *BadDoFnAmbiguousSideInput) StartBundle(bool) {
}
func (fn *BadDoFnAmbiguousSideInput) FinishBundle(bool) {
}
// Examples of correct SplittableDoFn signatures
type RestT struct{}
type RTrackerT struct{}
func (rt *RTrackerT) TryClaim(interface{}) bool {
return true
}
func (rt *RTrackerT) GetError() error {
return nil
}
func (rt *RTrackerT) TrySplit(fraction float64) (interface{}, interface{}, error) {
return nil, nil, nil
}
func (rt *RTrackerT) GetProgress() (float64, float64) {
return 0, 0
}
func (rt *RTrackerT) IsDone() bool {
return true
}
type GoodSdf struct {
*GoodDoFn
}
func (fn *GoodSdf) CreateInitialRestriction(int) RestT {
return RestT{}
}
func (fn *GoodSdf) SplitRestriction(int, RestT) []RestT {
return []RestT{}
}
func (fn *GoodSdf) RestrictionSize(int, RestT) float64 {
return 0
}
func (fn *GoodSdf) CreateTracker(RestT) *RTrackerT {
return &RTrackerT{}
}
func (fn *GoodSdf) ProcessElement(*RTrackerT, int) int {
return 0
}
type GoodSdfKv struct {
*GoodDoFnKv
}
func (fn *GoodSdfKv) CreateInitialRestriction(int, int) RestT {
return RestT{}
}
func (fn *GoodSdfKv) SplitRestriction(int, int, RestT) []RestT {
return []RestT{}
}
func (fn *GoodSdfKv) RestrictionSize(int, int, RestT) float64 {
return 0
}
func (fn *GoodSdfKv) CreateTracker(RestT) *RTrackerT {
return &RTrackerT{}
}
func (fn *GoodSdfKv) ProcessElement(*RTrackerT, int, int) int {
return 0
}
// Examples of incorrect SDF signatures.
// Examples with missing methods.
type BadSdfMissingMethods struct {
*GoodDoFn
}
func (fn *BadSdfMissingMethods) CreateInitialRestriction(int) RestT {
return RestT{}
}
// Examples with incorrect numbers of parameters.
type BadSdfParamsCreateRest struct {
*GoodSdf
}
func (fn *BadSdfParamsCreateRest) CreateInitialRestriction(int, int) RestT {
return RestT{}
}
type BadSdfParamsSplitRest struct {
*GoodSdf
}
func (fn *BadSdfParamsSplitRest) SplitRestriction(int, int, RestT) []RestT {
return []RestT{}
}
type BadSdfParamsRestSize struct {
*GoodSdf
}
func (fn *BadSdfParamsRestSize) RestrictionSize(int, int, RestT) float64 {
return 0
}
type BadSdfParamsCreateTracker struct {
*GoodSdf
}
func (fn *BadSdfParamsCreateTracker) CreateTracker(int, RestT) *RTrackerT {
return &RTrackerT{}
}
// Examples with invalid numbers of return values.
type BadSdfReturnsCreateRest struct {
*GoodSdf
}
func (fn *BadSdfReturnsCreateRest) CreateInitialRestriction(int) (RestT, int) {
return RestT{}, 0
}
type BadSdfReturnsSplitRest struct {
*GoodSdf
}
func (fn *BadSdfReturnsSplitRest) SplitRestriction(int, RestT) ([]RestT, int) {
return []RestT{}, 0
}
type BadSdfReturnsRestSize struct {
*GoodSdf
}
func (fn *BadSdfReturnsRestSize) RestrictionSize(int, RestT) (float64, int) {
return 0, 0
}
type BadSdfReturnsCreateTracker struct {
*GoodSdf
}
func (fn *BadSdfReturnsCreateTracker) CreateTracker(RestT) (*RTrackerT, int) {
return &RTrackerT{}, 0
}
// Examples with element types inconsistent with ProcessElement.
type BadSdfElementTCreateRest struct {
*GoodSdf
}
func (fn *BadSdfElementTCreateRest) CreateInitialRestriction(float32) RestT {
return RestT{}
}
type BadSdfElementTSplitRest struct {
*GoodSdf
}
func (fn *BadSdfElementTSplitRest) SplitRestriction(float32, RestT) []RestT {
return []RestT{}
}
type BadSdfElementTRestSize struct {
*GoodSdf
}
func (fn *BadSdfElementTRestSize) RestrictionSize(float32, RestT) float64 {
return 0
}
// Examples with restriction type inconsistent CreateRestriction.
type BadRestT struct{}
type BadSdfRestTSplitRestParam struct {
*GoodSdf
}
func (fn *BadSdfRestTSplitRestParam) SplitRestriction(int, BadRestT) []RestT {
return []RestT{}
}
type BadSdfRestTSplitRestReturn struct {
*GoodSdf
}
func (fn *BadSdfRestTSplitRestReturn) SplitRestriction(int, RestT) []BadRestT {
return []BadRestT{}
}
type BadSdfRestTRestSize struct {
*GoodSdf
}
func (fn *BadSdfRestTRestSize) RestrictionSize(int, BadRestT) float64 {
return 0
}
type BadSdfRestTCreateTracker struct {
*GoodSdf
}
func (fn *BadSdfRestTCreateTracker) CreateTracker(BadRestT) *RTrackerT {
return &RTrackerT{}
}
// Examples of other type validation that needs to be done.
type BadSdfRestSizeReturn struct {
*GoodSdf
}
func (fn *BadSdfRestSizeReturn) BadSdfRestSizeReturn(int, RestT) int {
return 0
}
type BadRTrackerT struct{} // Fails to implement RTracker interface.
type BadSdfCreateTrackerReturn struct {
*GoodSdf
}
func (fn *BadSdfCreateTrackerReturn) CreateTracker(RestT) *BadRTrackerT {
return &BadRTrackerT{}
}
type BadSdfMissingRTracker struct {
*GoodSdf
}
func (fn *BadSdfMissingRTracker) ProcessElement(int) int {
return 0
}
type OtherRTrackerT struct {
*RTrackerT
}
type BadSdfMismatchedRTracker struct {
*GoodSdf
}
func (fn *BadSdfMismatchedRTracker) ProcessElement(*OtherRTrackerT, int) int {
return 0
}
// Examples of correct CombineFn signatures
type MyAccum struct{}
type GoodCombineFn struct{}
func (fn *GoodCombineFn) MergeAccumulators(MyAccum, MyAccum) MyAccum {
return MyAccum{}
}
func (fn *GoodCombineFn) CreateAccumulator() MyAccum {
return MyAccum{}
}
func (fn *GoodCombineFn) AddInput(MyAccum, int) MyAccum {
return MyAccum{}
}
func (fn *GoodCombineFn) ExtractOutput(MyAccum) int64 {
return 0
}
type GoodWErrorCombineFn struct{}
func (fn *GoodWErrorCombineFn) MergeAccumulators(int, int) (int, error) {
return 0, nil
}
type GoodWContextCombineFn struct{}
func (fn *GoodWContextCombineFn) MergeAccumulators(context.Context, MyAccum, MyAccum) MyAccum {
return MyAccum{}
}
func (fn *GoodWContextCombineFn) CreateAccumulator(context.Context) MyAccum {
return MyAccum{}
}
func (fn *GoodWContextCombineFn) AddInput(context.Context, MyAccum, int) MyAccum {
return MyAccum{}
}
func (fn *GoodWContextCombineFn) ExtractOutput(context.Context, MyAccum) int64 {
return 0
}
type GoodCombineFnUnexportedExtraMethod struct {
*GoodCombineFn
}
func (fn *GoodCombineFnUnexportedExtraMethod) unexportedExtraMethod(context.Context, string) string {
return ""
}
// Examples of incorrect CombineFn signatures.
// Embedding *GoodCombineFn avoids repetitive MergeAccumulators signatures when desired.
// The immediately following examples are relating to accumulator mismatches.
type BadCombineFnNoMergeAccumulators struct{}
func (fn *BadCombineFnNoMergeAccumulators) CreateAccumulator() string { return "" }
type BadCombineFnNonBinaryMergeAccumulators struct {
*GoodCombineFn
}
func (fn *BadCombineFnNonBinaryMergeAccumulators) MergeAccumulators(int, string) int {
return 0
}
type BadCombineFnMisMatchedCreateAccumulator struct {
*GoodCombineFn
}
func (fn *BadCombineFnMisMatchedCreateAccumulator) CreateAccumulator() string {
return ""
}
type BadCombineFnMisMatchedAddInputIn struct {
*GoodCombineFn
}
func (fn *BadCombineFnMisMatchedAddInputIn) AddInput(string, int) MyAccum {
return MyAccum{}
}
type BadCombineFnMisMatchedAddInputOut struct {
*GoodCombineFn
}
func (fn *BadCombineFnMisMatchedAddInputOut) AddInput(MyAccum, int) string {
return ""
}
type BadCombineFnMisMatchedAddInputBoth struct {
*GoodCombineFn
}
func (fn *BadCombineFnMisMatchedAddInputBoth) AddInput(string, int) string {
return ""
}
type BadCombineFnMisMatchedExtractOutput struct {
*GoodCombineFn
}
func (fn *BadCombineFnMisMatchedExtractOutput) ExtractOutput(string) int {
return 0
}
// Examples of incorrect CreateAccumulator signatures
type BadCombineFnInvalidCreateAccumulator1 struct {
*GoodCombineFn
}
func (fn *BadCombineFnInvalidCreateAccumulator1) CreateAccumulator(context.Context, string) int {
return 0
}
type BadCombineFnInvalidCreateAccumulator2 struct {
*GoodCombineFn
}
func (fn *BadCombineFnInvalidCreateAccumulator2) CreateAccumulator(string) int {
return 0
}
type BadCombineFnInvalidCreateAccumulator3 struct {
*GoodCombineFn
}
func (fn *BadCombineFnInvalidCreateAccumulator3) CreateAccumulator() (MyAccum, string) {
return MyAccum{}, ""
}
type BadCombineFnInvalidCreateAccumulator4 struct {
*GoodCombineFn
}
func (fn *BadCombineFnInvalidCreateAccumulator4) CreateAccumulator() (string, MyAccum) {
return "", MyAccum{}
}
// Examples of incorrect AddInput signatures
type BadCombineFnInvalidAddInput1 struct {
*GoodCombineFn
}
func (fn *BadCombineFnInvalidAddInput1) AddInput(context.Context, string) int {
return 0
}
type BadCombineFnInvalidAddInput2 struct {
*GoodCombineFn
}
func (fn *BadCombineFnInvalidAddInput2) AddInput(string) int {
return 0
}
type BadCombineFnInvalidAddInput3 struct {
*GoodCombineFn
}
func (fn *BadCombineFnInvalidAddInput3) AddInput(context.Context, string, string, string) int {
return 0
}
type BadCombineFnInvalidAddInput4 struct {
*GoodCombineFn
}
func (fn *BadCombineFnInvalidAddInput4) AddInput(MyAccum, string) (int, int, int) {
return 0, 0, 0
}
// Examples of incorrect ExtractOutput signatures
type BadCombineFnInvalidExtractOutput1 struct {
*GoodCombineFn
}
func (fn *BadCombineFnInvalidExtractOutput1) ExtractOutput(MyAccum, string) (int, int, int) {
return 0, 0, 0
}
type BadCombineFnInvalidExtractOutput2 struct {
*GoodCombineFn
}
func (fn *BadCombineFnInvalidExtractOutput2) ExtractOutput() (int, int, int) {
return 0, 0, 0
}
type BadCombineFnInvalidExtractOutput3 struct {
*GoodCombineFn
}
func (fn *BadCombineFnInvalidExtractOutput3) ExtractOutput(context.Context, MyAccum, int) int {
return 0
}
// Other CombineFn Errors
type BadCombineFnExtraExportedMethod struct {
*GoodCombineFn
}
func (fn *BadCombineFnExtraExportedMethod) ExtraMethod(string) int {
return 0
}
| TestNewCombineFn |
losses.py | import torch
import torch.nn as nn
import time
import sys
softmax = nn.Softmax(dim=1).cuda()
def distributed_sinkhorn(Q, nmb_iters):
with torch.no_grad():
sum_Q = torch.sum(Q)
# dist.all_reduce(sum_Q)
Q /= sum_Q
u = torch.zeros(Q.shape[0]).cuda(non_blocking=True)
r = torch.ones(Q.shape[0]).cuda(non_blocking=True) / Q.shape[0]
c = torch.ones(Q.shape[1]).cuda(non_blocking=True) / ( Q.shape[1])
curr_sum = torch.sum(Q, dim=1)
# dist.all_reduce(curr_sum)
for it in range(nmb_iters):
u = curr_sum
Q *= (r / u).unsqueeze(1)
Q *= (c / torch.sum(Q, dim=0)).unsqueeze(0)
curr_sum = torch.sum(Q, dim=1)
# dist.all_reduce(curr_sum)
return (Q / torch.sum(Q, dim=0, keepdim=True)).t().float()
def | (out_queue, epsilon=0.05):
return distributed_sinkhorn(torch.exp(out_queue / epsilon).t(), 3)
def byol_loss_fn(x, y):
#x = F.normalize(x, dim=-1, p=2)
#y = F.normalize(y, dim=-1, p=2)
return 2 - 2 * (x * y).sum(dim=-1)
def ByolLoss(features_one, features_two):
online_pred_one = nn.functional.normalize(features_one['online_pred'], dim=1, p=2)
online_pred_two = nn.functional.normalize(features_two['online_pred'], dim=1, p=2)
target_proj_one = nn.functional.normalize(features_one['target_proj'], dim=1, p=2)
target_proj_two = nn.functional.normalize(features_two['target_proj'], dim=1, p=2)
byol_loss = byol_loss_fn(online_pred_one, target_proj_two).mean() + byol_loss_fn(online_pred_two, target_proj_one).mean()
sys.stdout.flush()
return byol_loss
def softSubLosses(outOne, outTwo,qOne, qTwo, param=0.1):
pOne = softmax(outOne/param)
pTwo = softmax(outTwo/param)
subloss_1 = - torch.mean(torch.sum(qTwo * torch.log(pOne), dim=1))
subloss_2 = - torch.mean(torch.sum(qOne * torch.log(pTwo), dim=1))
return subloss_1, subloss_2
def SoftLoss(outcodes_one, outcodes_two, alpha=1, temperature=0.1, overclustering=False):
if alpha > 0:
if overclustering:
out_one, out_two = outcodes_one['cTz_overcluster'], outcodes_two['cTz_overcluster']
else:
out_one, out_two = outcodes_one['cTz'], outcodes_two['cTz']
#ATTENTION: I have deleted clone operations. Please think about it. My decision can be wrong!!!!
with torch.no_grad():
q_one = getQ(out_one)
q_two = getQ(out_two)
subloss_1, subloss_2 = softSubLosses(out_one, out_two, q_one, q_two, temperature)
sys.stdout.flush()
return (subloss_1 + subloss_2)/2.0, q_one, q_two
else:
return torch.tensor(0), None, None
def ConsensusLossForAGivenProjection(out_rand_one, out_rand_two, q_one, q_two, param=0.1):
p_rand_one = softmax(out_rand_one/ param)
p_rand_two = softmax(out_rand_two/ param)
rand_loss_1 = -torch.mean(torch.sum(q_two * torch.log(p_rand_one), dim=1))
rand_loss_2 = -torch.mean(torch.sum(q_one * torch.log(p_rand_two), dim=1))
return (-torch.mean(torch.sum(q_two * torch.log(p_rand_one), dim=1)) - torch.mean(torch.sum(q_one * torch.log(p_rand_two), dim=1)))/2
def ConsensusLoss(gamma, outcodes_one, outcodes_two, rand_outs_one, rand_outs_two, q_one, q_two, overclustering=False, temperature=0.1):
loss = torch.tensor(0).cuda()
if q_one is None or q_two is None:
# check this when gamma>0 but alpha=0
if overclustering:
out_one, out_two = outcodes_one['cTz_overcluster'], outcodes_two['cTz_overcluster']
else:
out_one, out_two = outcodes_one['cTz'], outcodes_two['cTz']
q_one = getQ(out_one)
q_two = getQ(out_two)
if gamma > 0:
for randind in range(len(rand_outs_one)):
if overclustering:
temp = ConsensusLossForAGivenProjection(rand_outs_one[randind]['cTz_overcluster'], rand_outs_two[randind]['cTz_overcluster'], q_one, q_two, temperature)
loss = loss + temp
else:
temp= ConsensusLossForAGivenProjection(rand_outs_one[randind]['cTz'], rand_outs_two[randind]['cTz'], q_one, q_two, temperature)
loss = loss + temp
sys.stdout.flush()
return loss/len(rand_outs_one)
| getQ |
engine2d.js | /**
* Engine2D game engine.
*
* @author jackdalton
*/
/**
* Engine2D namespace
*
* @namespace
*/
var Engine2D = {
TYPE: {
RECT: 1,
CIRCLE: 2
},
/**
* Engine2D game scene constructor.
*
* @constructor
* @this {GameScene}
*/
GameScene: function() {
var self = this;
self.objects = {};
/**
* Checks whether a game object ID is valid or not.
*
* @private
* @param {string} objectId - ID to validate.
* @returns {boolean} - Whether the generated object ID is valid or not.
*/
var isValidID = function(objectId) {
var pass;
for (var i in self.objects) {
if (self.objects[i].id == objectId) pass = true;
}
if (!!pass)
return true;
else
return false;
};
/**
* Adds game object to scene.
*
* @param {Object} gameObject - Valid Engine2D game object to add to scene.
* @memberof Engine2D.GameScene
*/
self.addObject = function(gameObject) {
var pass;
for (var i in Engine2D.TYPE) {
if (gameObject.type == Engine2D.TYPE[i]) pass = true;
}
if (!!pass)
self.objects[gameObject.id] = gameObject;
else
throw new TypeError("\"" + gameObject.type + "\" is not a valid Engine2D game object type.");
};
/**
* Disables a game object.
*
* @param {string} objectId - ID of desired object in the scene to disable.
* @memberof Engine2D.GameScene
*/
self.disableObject = function(objectId) {
if (isValidID(objectId))
self.objects[objectId].alive = false;
else
throw new ReferenceError("Object \"" + objectId + "\" either doesn't exist, or hasn't been added to the scene.");
};
/**
* Enables a game object.
*
* @param {string} objectId - ID of desired object in the scene to enable.
* @memberof Engine2D.GameScene
*/
self.enableObject = function(objectId) {
if (isValidID(objectId))
self.objects[objectId].alive = true;
else
throw new ReferenceError("Object \"" + objectId + "\" either doesn't exist, or hasn't been added to the scene.");
};
/**
* Permanently destroys a game object.
*
* @param {string} objectId - ID of desired object in the scene to destroy.
* @memberof Engine2D.GameScene
*/
self.destroyObject = function(objectId) {
if (isValidID(objectId))
delete self.objects[objectId];
else
throw new ReferenceError("Object \"" + objectId + "\" either doesn't exist, or hasn't been added to the scene.");
};
},
/**
* Engine2D rectangle constructor.
*
* @constructor
* @this {Rect}
* @param {Object} options - An object specifying various aspects of a rectangle.
*/
Rect: function(options) {
var self = this;
options = options || {};
self.id = options.id || Engine2D.randomID();
self.type = Engine2D.TYPE.RECT;
self.alive = options.alive || true;
self.size = {}, self.position = {};
self.size.width = options.width || 0;
self.size.height = options.height || 0; | self.position.x = options.x || 0;
self.position.y = options.y || 0;
},
/**
* Engine2D circle constructor.
*
* @constructor
* @this {Circle}
* @param {Object} options - An object specifying various aspects of a circle.
*/
Circle: function(options) {
var self = this;
options = options || {};
self.id = options.id || Engine2D.randomID();
self.type = Engine2D.TYPE.CIRCLE;
self.alive = options.alive || true;
self.size = {}, self.position = {};
self.size.radius = options.radius || 0;
self.position.x = options.x || 0;
self.position.y = options.y || 0;
},
/**
* Used to generate random object IDs for Engine2D game objects.
*
* @returns {string} - Randomly generated object ID.
*/
randomID: function() {
var opts = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", out = "";
var i = 0;
while (i < 5) {
i++;
out += opts[Math.floor(Math.random() * opts.length)];
}
return out;
}
};
if (typeof module !== "undefined") {
module.exports = Engine2D;
} else {
window.Engine2D = Engine2D;
} | |
bruteSearch.py | import numpy as np
from itertools import product
from markovGames.gameDefs.mdpDefs import Policy
def getAllDetPol(numStates, numActions):
detProbs = [np.array([1 if j == i else 0 for j in range(numActions)]) for i in range(numActions)]
return product(detProbs, repeat=numStates)
def getPolList(states, acSet):
# list of possible deterministic policies
numStates = len(states)
numActions = len(acSet)
detPol = getAllDetPol(numStates, numActions)
return [Policy(states, pol, acSet) for pol in detPol]
def prodPolList(states, listActions):
# get policies for each action Set
polList = [getPolList(states, ac) for ac in listActions]
return polList
def getPayoff(utilMap, listAcSet):
# utilMap: maps list of agent policies to real numbers,
# allPolicyList: list of agent i (list of possible policies)
def | (index):
jointAc = [listAcSet[j][ind] for j, ind in enumerate(index)]
val = utilMap(jointAc)
return val
numPL = [len(pL) for pL in listAcSet]
payoff = np.zeros(numPL)
for ind in product(*[range(nI) for nI in numPL]):
payoff[ind] = utilInd(ind)
return payoff
def getArgOpt(tensor):
return np.unravel_index(np.argmax(tensor), tensor.shape)
def bruteFindNash(payoffList):
TOLERANCE = 1e-7
cpnes = list(np.argwhere(payoffList[0] > np.amax(payoffList[0], 0) - TOLERANCE))
cpnes = [tuple(cpne) for cpne in cpnes]
N = len(payoffList)
for i in range(1, N):
pMat = payoffList[i]
for cpne in cpnes[:]:
ind = cpne[:i] + (slice(None),) + cpne[i + 1:]
if pMat[cpne] < np.max(pMat[ind]) - TOLERANCE:
cpnes.pop(cpnes.index(cpne))
return cpnes
def getEfficiency(cpnes, welfareMat):
# welfareMat - matrix form of welfare
pneWelf = [welfareMat[cpne] for cpne in cpnes]
opt = np.max(welfareMat)
priceRatios = [float(pne) / opt for pne in pneWelf]
return priceRatios
def getPoA(cpnes, welfareMat):
return min(getEfficiency(cpnes, welfareMat))
| utilInd |
cifar_tools.py | import cPickle
import numpy as np
def | (file):
fo = open(file, 'rb')
dict = cPickle.load(fo)
fo.close()
return dict
def clean(data):
imgs = data.reshape(data.shape[0], 3, 32, 32)
grayscale_imgs = imgs.mean(1)
cropped_imgs = grayscale_imgs[:, 4:28, 4:28]
img_data = cropped_imgs.reshape(data.shape[0], -1)
img_size = np.shape(img_data)[1]
means = np.mean(img_data, axis=1)
meansT = means.reshape(len(means), 1)
stds = np.std(img_data, axis=1)
stdsT = stds.reshape(len(stds), 1)
adj_stds = np.maximum(stdsT, 1.0 / np.sqrt(img_size))
normalized = (img_data - meansT) / adj_stds
return normalized
def read_data(directory):
names = unpickle('{}/batches.meta'.format(directory))['label_names']
print('names', names)
data, labels = [], []
for i in range(1, 6):
filename = '{}/data_batch_{}'.format(directory, i)
batch_data = unpickle(filename)
if len(data) > 0:
data = np.vstack((data, batch_data['data']))
labels = np.hstack((labels, batch_data['labels']))
else:
data = batch_data['data']
labels = batch_data['labels']
print(np.shape(data), np.shape(labels))
data = clean(data)
data = data.astype(np.float32)
return names, data, labels
| unpickle |
build-url.ts | import {Pipe, PipeTransform} from '@angular/core';
import {environment} from '@app/env';
/**
* Generated class for the BuildUrlPipe pipe.
*
* See https://angular.io/api/core/Pipe for more info on Angular Pipes.
*/ | name: 'buildUrl',
})
export class BuildUrlPipe implements PipeTransform {
/**
* Takes a value and makes it lowercase.
*/
transform(value: string, ...args) {
if(value){
return value.startsWith('http') ? value : `${environment.baseFilesUrl}/${value}`
}
return value;
}
} | @Pipe({ |
test_metering_agent.py | # Copyright (C) 2013 eNovance SAS <[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.
import mock
from oslo_config import cfg
from oslo_utils import fixture as utils_fixture
from oslo_utils import timeutils
from oslo_utils import uuidutils
from neutron.conf.services import metering_agent as metering_agent_config
from neutron.services.metering.agents import metering_agent
from neutron.tests import base
from neutron.tests import fake_notifier
_uuid = uuidutils.generate_uuid
TENANT_ID = _uuid()
LABEL_ID = _uuid()
ROUTERS = [{'status': 'ACTIVE',
'name': 'router1',
'gw_port_id': None,
'admin_state_up': True,
'tenant_id': TENANT_ID,
'_metering_labels': [{'rules': [],
'id': LABEL_ID}],
'id': _uuid()}]
ROUTERS_WITH_RULE = [{'status': 'ACTIVE',
'name': 'router1',
'gw_port_id': None,
'admin_state_up': True,
'tenant_id': TENANT_ID,
'_metering_labels': [{'rule': {},
'id': LABEL_ID}],
'id': _uuid()}]
class TestMeteringOperations(base.BaseTestCase):
def setUp(self):
super(TestMeteringOperations, self).setUp()
metering_agent_config.register_metering_agent_opts()
self.noop_driver = ('neutron.services.metering.drivers.noop.'
'noop_driver.NoopMeteringDriver')
cfg.CONF.set_override('driver', 'noop')
cfg.CONF.set_override('measure_interval', 0)
cfg.CONF.set_override('report_interval', 0)
self.setup_notification_driver()
metering_rpc = ('neutron.services.metering.agents.metering_agent.'
'MeteringPluginRpc._get_sync_data_metering')
self.metering_rpc_patch = mock.patch(metering_rpc, return_value=[])
self.metering_rpc_patch.start()
self.driver_patch = mock.patch(self.noop_driver, spec=True)
self.driver_patch.start()
loopingcall_patch = mock.patch(
'oslo_service.loopingcall.FixedIntervalLoopingCall')
loopingcall_patch.start()
self.agent = metering_agent.MeteringAgent('my agent', cfg.CONF)
self.driver = self.agent.metering_driver
def test_add_metering_label(self):
self.agent.add_metering_label(None, ROUTERS)
self.assertEqual(1, self.driver.add_metering_label.call_count)
def test_remove_metering_label(self):
self.agent.remove_metering_label(None, ROUTERS)
self.assertEqual(1, self.driver.remove_metering_label.call_count)
def test_update_metering_label_rule(self):
self.agent.update_metering_label_rules(None, ROUTERS)
self.assertEqual(1, self.driver.update_metering_label_rules.call_count)
def test_add_metering_label_rule(self):
self.agent.add_metering_label_rule(None, ROUTERS_WITH_RULE)
self.assertEqual(1, self.driver.add_metering_label_rule.call_count)
def test_remove_metering_label_rule(self):
self.agent.remove_metering_label_rule(None, ROUTERS_WITH_RULE)
self.assertEqual(1, self.driver.remove_metering_label_rule.call_count)
def test_routers_updated(self):
self.agent.routers_updated(None, ROUTERS)
self.assertEqual(1, self.driver.update_routers.call_count)
def test_get_traffic_counters(self):
self.agent._get_traffic_counters(None, ROUTERS)
self.assertEqual(1, self.driver.get_traffic_counters.call_count)
def test_sync_router_namespaces(self):
self.agent._sync_router_namespaces(None, ROUTERS)
self.assertEqual(1, self.driver.sync_router_namespaces.call_count)
def test_notification_report(self):
self.agent.routers_updated(None, ROUTERS)
self.driver.get_traffic_counters.return_value = {LABEL_ID:
{'pkts': 88,
'bytes': 444}}
self.agent._metering_loop()
self.assertNotEqual(len(fake_notifier.NOTIFICATIONS), 0)
for n in fake_notifier.NOTIFICATIONS:
if n['event_type'] == 'l3.meter':
break
self.assertEqual('l3.meter', n['event_type'])
payload = n['payload']
self.assertEqual(TENANT_ID, payload['tenant_id'])
self.assertEqual(LABEL_ID, payload['label_id'])
self.assertEqual(88, payload['pkts'])
self.assertEqual(444, payload['bytes'])
def test_notification_report_interval(self):
measure_interval = 30
report_interval = 600
now = timeutils.utcnow()
time_fixture = self.useFixture(utils_fixture.TimeFixture(now))
self.agent.routers_updated(None, ROUTERS)
self.driver.get_traffic_counters.return_value = {LABEL_ID:
{'pkts': 889,
'bytes': 4440}}
cfg.CONF.set_override('measure_interval', measure_interval)
cfg.CONF.set_override('report_interval', report_interval)
for i in range(report_interval):
self.agent._metering_loop()
count = 0
if len(fake_notifier.NOTIFICATIONS) > 1:
for n in fake_notifier.NOTIFICATIONS:
if n['event_type'] == 'l3.meter':
# skip the first notification because the time is 0
count += 1
if count > 1:
break
time_fixture.advance_time_seconds(measure_interval)
self.assertEqual('l3.meter', n['event_type'])
payload = n['payload']
self.assertEqual(TENANT_ID, payload['tenant_id'])
self.assertEqual(LABEL_ID, payload['label_id'])
self.assertLess((payload['time'] - report_interval),
measure_interval, payload)
interval = (payload['last_update'] - payload['first_update']) \
- report_interval
self.assertLess(interval, measure_interval, payload)
def test_router_deleted(self):
label_id = _uuid()
self.driver.get_traffic_counters = mock.MagicMock()
self.driver.get_traffic_counters.return_value = {label_id:
{'pkts': 44,
'bytes': 222}}
self.agent._add_metering_info = mock.MagicMock()
self.agent.routers_updated(None, ROUTERS)
self.agent.router_deleted(None, ROUTERS[0]['id'])
self.assertEqual(1, self.agent._add_metering_info.call_count)
self.assertEqual(1, self.driver.remove_router.call_count)
self.agent._add_metering_info.assert_called_with(label_id, 44, 222)
@mock.patch('time.time')
def _test_purge_metering_info(self, current_timestamp, is_empty,
mock_time):
mock_time.return_value = current_timestamp
self.agent.metering_infos = {'fake': {'last_update': 1}}
self.config(report_interval=1)
self.agent._purge_metering_info()
self.assertEqual(0 if is_empty else 1, len(self.agent.metering_infos))
self.assertEqual(1, mock_time.call_count)
def test_purge_metering_info(self):
# 1 < 2 - 1 -> False
self._test_purge_metering_info(2, False)
def test_purge_metering_info_delete(self):
# 1 < 3 - 1 -> False
self._test_purge_metering_info(3, True)
@mock.patch('time.time')
def _test_add_metering_info(self, expected_info, current_timestamp,
mock_time):
mock_time.return_value = current_timestamp
actual_info = self.agent._add_metering_info('fake_label_id', 1, 1)
self.assertEqual(1, len(self.agent.metering_infos))
self.assertEqual(expected_info, actual_info)
self.assertEqual(expected_info,
self.agent.metering_infos['fake_label_id'])
self.assertEqual(1, mock_time.call_count)
def test_add_metering_info_create(self):
expected_info = {'bytes': 1, 'pkts': 1, 'time': 0, 'first_update': 1,
'last_update': 1}
self._test_add_metering_info(expected_info, 1)
def test_add_metering_info_update(self):
expected_info = {'bytes': 1, 'pkts': 1, 'time': 0, 'first_update': 1,
'last_update': 1}
self.agent.metering_infos = {'fake_label_id': expected_info}
expected_info.update({'bytes': 2, 'pkts': 2, 'time': 1,
'last_update': 2})
self._test_add_metering_info(expected_info, 2)
def test_metering_agent_host_value(self):
expected_host = 'my agent'
self.assertEqual(expected_host, self.agent.host)
class TestMeteringDriver(base.BaseTestCase):
| def setUp(self):
super(TestMeteringDriver, self).setUp()
metering_agent_config.register_metering_agent_opts()
cfg.CONF.set_override('driver', 'noop')
self.agent = metering_agent.MeteringAgent('my agent', cfg.CONF)
self.driver = mock.Mock()
self.agent.metering_driver = self.driver
def test_add_metering_label_with_bad_driver_impl(self):
del self.driver.add_metering_label
with mock.patch.object(metering_agent, 'LOG') as log:
self.agent.add_metering_label(None, ROUTERS)
log.exception.assert_called_with(mock.ANY,
{'driver': 'noop',
'func': 'add_metering_label'})
def test_add_metering_label_runtime_error(self):
self.driver.add_metering_label.side_effect = RuntimeError
with mock.patch.object(metering_agent, 'LOG') as log:
self.agent.add_metering_label(None, ROUTERS)
log.exception.assert_called_with(mock.ANY,
{'driver': 'noop',
'func':
'add_metering_label'})
def test_init_chain(self):
with mock.patch('oslo_service.'
'periodic_task.PeriodicTasks.__init__') as init:
metering_agent.MeteringAgent('my agent', cfg.CONF)
init.assert_called_once_with(cfg.CONF) |
|
276ef161b610_.py | """empty message
Revision ID: 276ef161b610
Revises:
Create Date: 2017-10-24 19:30:22.200973
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '276ef161b610'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=128), nullable=True),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def | ():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('user')
# ### end Alembic commands ###
| downgrade |
0002_auto_20161121_1848.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-21 23:48
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| dependencies = [
('property_api', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='ckanresource',
name='ckan_instance',
),
migrations.AddField(
model_name='ckanresource',
name='slug',
field=models.CharField(default='', max_length=200),
preserve_default=False,
),
migrations.DeleteModel(
name='CKANInstance',
),
] |
|
undirect_test.go | // Copyright ©2015 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package graph_test
import (
"math"
"testing"
"github.com/ArkaGPL/gonum/graph"
"github.com/ArkaGPL/gonum/graph/iterator"
"github.com/ArkaGPL/gonum/graph/simple"
"github.com/ArkaGPL/gonum/mat"
)
type weightedDirectedBuilder interface {
graph.WeightedBuilder
graph.WeightedDirected
}
var weightedDirectedGraphs = []struct {
skipUnweighted bool
g func() weightedDirectedBuilder
edges []simple.WeightedEdge
absent float64
merge func(x, y float64, xe, ye graph.Edge) float64
want mat.Matrix
}{
{
g: func() weightedDirectedBuilder { return simple.NewWeightedDirectedGraph(0, 0) },
edges: []simple.WeightedEdge{
{F: simple.Node(0), T: simple.Node(1), W: 2},
{F: simple.Node(1), T: simple.Node(0), W: 1},
{F: simple.Node(1), T: simple.Node(2), W: 1},
},
want: mat.NewSymDense(3, []float64{
0, (1. + 2.) / 2., 0,
(1. + 2.) / 2., 0, 1. / 2.,
0, 1. / 2., 0,
}),
},
{
g: func() weightedDirectedBuilder { return simple.NewWeightedDirectedGraph(0, 0) },
edges: []simple.WeightedEdge{
{F: simple.Node(0), T: simple.Node(1), W: 2},
{F: simple.Node(1), T: simple.Node(0), W: 1},
{F: simple.Node(1), T: simple.Node(2), W: 1},
},
absent: 1,
merge: func(x, y float64, _, _ graph.Edge) float64 { return math.Sqrt(x * y) },
want: mat.NewSymDense(3, []float64{
0, math.Sqrt(1 * 2), 0,
math.Sqrt(1 * 2), 0, math.Sqrt(1 * 1),
0, math.Sqrt(1 * 1), 0,
}),
},
{
skipUnweighted: true, // The min merge function cannot be used in the unweighted case.
g: func() weightedDirectedBuilder { return simple.NewWeightedDirectedGraph(0, 0) },
edges: []simple.WeightedEdge{
{F: simple.Node(0), T: simple.Node(1), W: 2},
{F: simple.Node(1), T: simple.Node(0), W: 1},
{F: simple.Node(1), T: simple.Node(2), W: 1},
},
merge: func(x, y float64, _, _ graph.Edge) float64 { return math.Min(x, y) },
want: mat.NewSymDense(3, []float64{
0, math.Min(1, 2), 0,
math.Min(1, 2), 0, math.Min(1, 0),
0, math.Min(1, 0), 0,
}),
},
{
g: func() weightedDirectedBuilder { return simple.NewWeightedDirectedGraph(0, 0) },
edges: []simple.WeightedEdge{
{F: simple.Node(0), T: simple.Node(1), W: 2},
{F: simple.Node(1), T: simple.Node(0), W: 1},
{F: simple.Node(1), T: simple.Node(2), W: 1},
},
merge: func(x, y float64, xe, ye graph.Edge) float64 {
if xe == nil {
return y
}
if ye == nil {
return x
}
return math.Min(x, y)
},
want: mat.NewSymDense(3, []float64{
0, math.Min(1, 2), 0,
math.Min(1, 2), 0, 1,
0, 1, 0,
}),
},
{
g: func() weightedDirectedBuilder { return simple.NewWeightedDirectedGraph(0, 0) },
edges: []simple.WeightedEdge{
{F: simple.Node(0), T: simple.Node(1), W: 2},
{F: simple.Node(1), T: simple.Node(0), W: 1},
{F: simple.Node(1), T: simple.Node(2), W: 1},
},
merge: func(x, y float64, _, _ graph.Edge) float64 { return math.Max(x, y) },
want: mat.NewSymDense(3, []float64{
0, math.Max(1, 2), 0,
math.Max(1, 2), 0, math.Max(1, 0),
0, math.Max(1, 0), 0,
}),
},
}
func TestUndirect(t *testing.T) {
for i, test := range weightedDirectedGraphs {
if test.skipUnweighted {
continue
}
g := test.g()
for _, e := range test.edges {
g.SetWeightedEdge(e)
}
src := graph.Undirect{G: g}
nodes := graph.NodesOf(src.Nodes())
dst := simple.NewUndirectedMatrixFrom(nodes, 0, 0, 0)
for _, u := range nodes {
for _, v := range graph.NodesOf(src.From(u.ID())) {
dst.SetEdge(src.Edge(u.ID(), v.ID()))
}
}
want := unit{test.want}
if !mat.Equal(dst.Matrix(), want) {
t.Errorf("unexpected result for case %d:\ngot:\n%.4v\nwant:\n%.4v", i,
mat.Formatted(dst.Matrix()),
mat.Formatted(want),
)
}
}
}
func TestUndirectWeighted(t *testing.T) { |
type unit struct {
mat.Matrix
}
func (m unit) At(i, j int) float64 {
v := m.Matrix.At(i, j)
if v == 0 {
return 0
}
return 1
}
var nodeIteratorPairTests = []struct {
a, b graph.Nodes
len int
}{
{a: graph.Empty, b: graph.Empty, len: 0},
{a: iterator.NewOrderedNodes(nil), b: iterator.NewOrderedNodes(nil), len: 0},
{a: iterator.NewOrderedNodes([]graph.Node{simple.Node(0)}), b: graph.Empty, len: 1},
{a: graph.Empty, b: iterator.NewOrderedNodes([]graph.Node{simple.Node(0)}), len: 1},
{a: iterator.NewOrderedNodes([]graph.Node{simple.Node(0)}), b: iterator.NewOrderedNodes([]graph.Node{simple.Node(0)}), len: 1},
{a: iterator.NewOrderedNodes([]graph.Node{simple.Node(0)}), b: iterator.NewOrderedNodes([]graph.Node{simple.Node(1)}), len: 2},
{a: iterator.NewOrderedNodes([]graph.Node{simple.Node(0), simple.Node(1)}), b: iterator.NewOrderedNodes([]graph.Node{simple.Node(1)}), len: 2},
{a: iterator.NewOrderedNodes([]graph.Node{simple.Node(1)}), b: iterator.NewOrderedNodes([]graph.Node{simple.Node(0), simple.Node(1)}), len: 2},
}
func TestNodeIteratorPair(t *testing.T) {
for _, test := range nodeIteratorPairTests {
it := graph.NewNodeIteratorPair(test.a, test.b)
for i := 0; i < 2; i++ {
n := it.Len()
if n != test.len {
t.Errorf("unexpected length of iterator construction/reset: got:%d want:%d", n, test.len)
}
for it.Next() {
n--
}
if n != 0 {
t.Errorf("unexpected remaining nodes after iterator completion: got:%d want:0", n)
}
it.Reset()
}
}
}
|
for i, test := range weightedDirectedGraphs {
g := test.g()
for _, e := range test.edges {
g.SetWeightedEdge(e)
}
src := graph.UndirectWeighted{G: g, Absent: test.absent, Merge: test.merge}
nodes := graph.NodesOf(src.Nodes())
dst := simple.NewUndirectedMatrixFrom(nodes, 0, 0, 0)
for _, u := range nodes {
for _, v := range graph.NodesOf(src.From(u.ID())) {
dst.SetWeightedEdge(src.WeightedEdge(u.ID(), v.ID()))
}
}
if !mat.Equal(dst.Matrix(), test.want) {
t.Errorf("unexpected result for case %d:\ngot:\n%.4v\nwant:\n%.4v", i,
mat.Formatted(dst.Matrix()),
mat.Formatted(test.want),
)
}
}
}
|
version.go | package command
import (
"bytes"
"fmt"
)
// VersionCommand is a Command implementation prints the version.
type VersionCommand struct {
Meta
Revision string
Version string
VersionPrerelease string
CheckFunc VersionCheckFunc
}
// VersionCheckFunc is the callback called by the Version command to
// check if there is a new version of Terraform.
type VersionCheckFunc func() (VersionCheckInfo, error)
// VersionCheckInfo is the return value for the VersionCheckFunc callback
// and tells the Version command information about the latest version
// of Terraform.
type VersionCheckInfo struct {
Outdated bool
Latest string
Alerts []string
}
func (c *VersionCommand) Help() string {
return ""
}
func (c *VersionCommand) Run(args []string) int {
var versionString bytes.Buffer
args, err := c.Meta.process(args, false)
if err != nil {
return 1
}
fmt.Fprintf(&versionString, "Terraform v%s", c.Version)
if c.VersionPrerelease != "" {
fmt.Fprintf(&versionString, "-%s", c.VersionPrerelease)
if c.Revision != "" {
fmt.Fprintf(&versionString, " (%s)", c.Revision)
}
}
c.Ui.Output(versionString.String())
// If we have a version check function, then let's check for
// the latest version as well.
if c.CheckFunc != nil |
return 0
}
func (c *VersionCommand) Synopsis() string {
return "Prints the Terraform version"
}
| {
// Separate the prior output with a newline
c.Ui.Output("")
// Check the latest version
info, err := c.CheckFunc()
if err != nil {
c.Ui.Error(fmt.Sprintf(
"Error checking latest version: %s", err))
}
if info.Outdated {
c.Ui.Output(fmt.Sprintf(
"Your version of Terraform is out of date! The latest version\n"+
"is %s. You can update by downloading from www.terraform.io",
info.Latest))
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.