file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
managerresourcegroup.go
/* Copyright AppsCode Inc. and Contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by client-gen. DO NOT EDIT. package v1alpha1 import ( "context" "time" v1alpha1 "kubeform.dev/provider-alicloud-api/apis/resource/v1alpha1" scheme "kubeform.dev/provider-alicloud-api/client/clientset/versioned/scheme" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" rest "k8s.io/client-go/rest" ) // ManagerResourceGroupsGetter has a method to return a ManagerResourceGroupInterface. // A group's client should implement this interface. type ManagerResourceGroupsGetter interface { ManagerResourceGroups(namespace string) ManagerResourceGroupInterface } // ManagerResourceGroupInterface has methods to work with ManagerResourceGroup resources. type ManagerResourceGroupInterface interface { Create(ctx context.Context, managerResourceGroup *v1alpha1.ManagerResourceGroup, opts v1.CreateOptions) (*v1alpha1.ManagerResourceGroup, error) Update(ctx context.Context, managerResourceGroup *v1alpha1.ManagerResourceGroup, opts v1.UpdateOptions) (*v1alpha1.ManagerResourceGroup, error) UpdateStatus(ctx context.Context, managerResourceGroup *v1alpha1.ManagerResourceGroup, opts v1.UpdateOptions) (*v1alpha1.ManagerResourceGroup, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.ManagerResourceGroup, error) List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.ManagerResourceGroupList, error) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ManagerResourceGroup, err error) ManagerResourceGroupExpansion } // managerResourceGroups implements ManagerResourceGroupInterface type managerResourceGroups struct { client rest.Interface ns string } // newManagerResourceGroups returns a ManagerResourceGroups func newManagerResourceGroups(c *ResourceV1alpha1Client, namespace string) *managerResourceGroups
// Get takes name of the managerResourceGroup, and returns the corresponding managerResourceGroup object, and an error if there is any. func (c *managerResourceGroups) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.ManagerResourceGroup, err error) { result = &v1alpha1.ManagerResourceGroup{} err = c.client.Get(). Namespace(c.ns). Resource("managerresourcegroups"). Name(name). VersionedParams(&options, scheme.ParameterCodec). Do(ctx). Into(result) return } // List takes label and field selectors, and returns the list of ManagerResourceGroups that match those selectors. func (c *managerResourceGroups) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ManagerResourceGroupList, err error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } result = &v1alpha1.ManagerResourceGroupList{} err = c.client.Get(). Namespace(c.ns). Resource("managerresourcegroups"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Do(ctx). Into(result) return } // Watch returns a watch.Interface that watches the requested managerResourceGroups. func (c *managerResourceGroups) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } opts.Watch = true return c.client.Get(). Namespace(c.ns). Resource("managerresourcegroups"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Watch(ctx) } // Create takes the representation of a managerResourceGroup and creates it. Returns the server's representation of the managerResourceGroup, and an error, if there is any. func (c *managerResourceGroups) Create(ctx context.Context, managerResourceGroup *v1alpha1.ManagerResourceGroup, opts v1.CreateOptions) (result *v1alpha1.ManagerResourceGroup, err error) { result = &v1alpha1.ManagerResourceGroup{} err = c.client.Post(). Namespace(c.ns). Resource("managerresourcegroups"). VersionedParams(&opts, scheme.ParameterCodec). Body(managerResourceGroup). Do(ctx). Into(result) return } // Update takes the representation of a managerResourceGroup and updates it. Returns the server's representation of the managerResourceGroup, and an error, if there is any. func (c *managerResourceGroups) Update(ctx context.Context, managerResourceGroup *v1alpha1.ManagerResourceGroup, opts v1.UpdateOptions) (result *v1alpha1.ManagerResourceGroup, err error) { result = &v1alpha1.ManagerResourceGroup{} err = c.client.Put(). Namespace(c.ns). Resource("managerresourcegroups"). Name(managerResourceGroup.Name). VersionedParams(&opts, scheme.ParameterCodec). Body(managerResourceGroup). Do(ctx). Into(result) return } // UpdateStatus was generated because the type contains a Status member. // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). func (c *managerResourceGroups) UpdateStatus(ctx context.Context, managerResourceGroup *v1alpha1.ManagerResourceGroup, opts v1.UpdateOptions) (result *v1alpha1.ManagerResourceGroup, err error) { result = &v1alpha1.ManagerResourceGroup{} err = c.client.Put(). Namespace(c.ns). Resource("managerresourcegroups"). Name(managerResourceGroup.Name). SubResource("status"). VersionedParams(&opts, scheme.ParameterCodec). Body(managerResourceGroup). Do(ctx). Into(result) return } // Delete takes name of the managerResourceGroup and deletes it. Returns an error if one occurs. func (c *managerResourceGroups) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { return c.client.Delete(). Namespace(c.ns). Resource("managerresourcegroups"). Name(name). Body(&opts). Do(ctx). Error() } // DeleteCollection deletes a collection of objects. func (c *managerResourceGroups) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { var timeout time.Duration if listOpts.TimeoutSeconds != nil { timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second } return c.client.Delete(). Namespace(c.ns). Resource("managerresourcegroups"). VersionedParams(&listOpts, scheme.ParameterCodec). Timeout(timeout). Body(&opts). Do(ctx). Error() } // Patch applies the patch and returns the patched managerResourceGroup. func (c *managerResourceGroups) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ManagerResourceGroup, err error) { result = &v1alpha1.ManagerResourceGroup{} err = c.client.Patch(pt). Namespace(c.ns). Resource("managerresourcegroups"). Name(name). SubResource(subresources...). VersionedParams(&opts, scheme.ParameterCodec). Body(data). Do(ctx). Into(result) return }
{ return &managerResourceGroups{ client: c.RESTClient(), ns: namespace, } }
main.go
package main import ( "bufio" "compress/gzip" "errors" "fmt" "io" "os" "path" "path/filepath" "strconv" "strings" "time" "github.com/h2non/filetype" "github.com/rcowham/gitp4transfer/journal" libfastimport "github.com/rcowham/go-libgitfastimport" "github.com/perforce/p4prometheus/version" "github.com/sirupsen/logrus" "gopkg.in/alecthomas/kingpin.v2" ) func Humanize(b int) string { const unit = 1000 if b < unit { return fmt.Sprintf("%d B", b) } div, exp := int(unit), 0 for n := b / unit; n >= unit; n /= unit { div *= unit exp++ } return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "kMGTPE"[exp]) } type GitParserOptions struct { gitImportFile string extractFiles bool archiveRoot string createJournal bool importDepot string importPath string // After depot } type GitAction int const ( modify GitAction = iota delete copy rename ) // Performs simple hash func getBlobIDPath(rootDir string, blobID int) (dir string, name string) { n := fmt.Sprintf("%08d", blobID) d := path.Join(rootDir, n[0:2], n[2:5], n[5:8]) n = path.Join(d, n) return d, n } func writeBlob(rootDir string, blobID int, data *string) { dir, name := getBlobIDPath(rootDir, blobID) err := os.MkdirAll(dir, 0777) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create %s: %v", dir, err) } f, err := os.Create(name) if err != nil { panic(err) } defer f.Close() fmt.Fprint(f, *data) if err != nil { panic(err) } } // GitFile - A git file record - modify/delete/copy/move type GitFile struct { name string // Git filename (target for rename/copy) size int depotFile string // Full depot path rev int // Depot rev srcName string // Name of git source file for rename/copy srcDepotFile string // " srcRev int // " srcLbrRev int // " archiveFile string action GitAction p4action journal.FileAction targ string // For use with copy/move fileType journal.FileType compressed bool blob *libfastimport.CmdBlob } // GitCommit - A git commit type GitCommit struct { commit *libfastimport.CmdCommit commitSize int // Size of all files in this commit - useful for memory sizing files []GitFile } func (gc *GitCommit) writeCommit(j *journal.Journal) { j.WriteChange(gc.commit.Mark, gc.commit.Msg, int(gc.commit.Author.Time.Unix())) } type CommitMap map[int]*GitCommit type FileMap map[int]*GitFile type RevChange struct { // Struct to remember revs and changes per depotFile rev int chgNo int } // GitP4Transfer - Transfer via git fast-export file type GitP4Transfer struct { exportFile string logger *logrus.Logger gitChan chan GitCommit opts GitParserOptions depotFileRevs map[string]*RevChange // Map depotFile to latest rev/chg depotFileTypes map[string]journal.FileType // Map depotFile#rev to filetype (for renames/branching) testInput string // For testing only } func NewGitP4Transfer(logger *logrus.Logger) *GitP4Transfer { return &GitP4Transfer{logger: logger, depotFileRevs: make(map[string]*RevChange), depotFileTypes: make(map[string]journal.FileType)} } func (gf *GitFile) getDepotPath(opts GitParserOptions, name string) string { if len(opts.importPath) == 0 { return fmt.Sprintf("//%s/%s", opts.importDepot, name) } else { return fmt.Sprintf("//%s/%s/%s", opts.importDepot, opts.importPath, name) } } func (gf *GitFile) setDepotPaths(opts GitParserOptions) { gf.depotFile = gf.getDepotPath(opts, gf.name) if gf.srcName != "" { gf.srcDepotFile = gf.getDepotPath(opts, gf.srcName) } } // Sets compression option and binary/text func (gf *GitFile) updateFileDetails() { switch gf.action { case delete: gf.p4action = journal.Delete return case rename: gf.p4action = journal.Rename return case modify: gf.p4action = journal.Edit } // Compression defaults to false l := len(gf.blob.Data) if l > 261 { l = 261 } head := []byte(gf.blob.Data[:l]) if filetype.IsImage(head) || filetype.IsVideo(head) || filetype.IsArchive(head) || filetype.IsAudio(head) { gf.fileType = journal.UBinary return } if filetype.IsDocument(head) { gf.fileType = journal.Binary kind, _ := filetype.Match(head) switch kind.Extension { case "docx", "pptx", "xlsx": return // no compression } gf.compressed = true return } gf.fileType = journal.CText gf.compressed = true } func getOID(dataref string) (int, error) { if !strings.HasPrefix(dataref, ":") { return 0, errors.New("Invalid dataref") } return strconv.Atoi(dataref[1:]) } // WriteFile will write a data file using standard path: <depotRoot>/<path>,d/1.<changeNo>[.gz] func (gf *GitFile) WriteFile(depotRoot string, changeNo int) error { if gf.action == delete || gf.action == rename { return nil } rootDir := fmt.Sprintf("%s/%s,d", depotRoot, gf.depotFile[2:]) err := os.MkdirAll(rootDir, 0755) if err != nil { panic(err) } if gf.compressed { gf.compressed = true fname := fmt.Sprintf("%s/1.%d.gz", rootDir, changeNo) f, err := os.Create(fname) if err != nil { panic(err) } defer f.Close() zw := gzip.NewWriter(f) defer zw.Close() _, err = zw.Write([]byte(gf.blob.Data)) if err != nil { panic(err) } } else { fname := fmt.Sprintf("%s/1.%d", rootDir, changeNo) f, err := os.Create(fname) if err != nil { panic(err) } defer f.Close() fmt.Fprint(f, gf.blob.Data) if err != nil { panic(err) } } return nil } // WriteFile will write a data file using standard path: <depotRoot>/<path>,d/1.<changeNo>[.gz] func (gf *GitFile) WriteJournal(j *journal.Journal, c *GitCommit) { dt := int(c.commit.Author.Time.Unix()) chgNo := c.commit.Mark if gf.action == modify || gf.action == delete { j.WriteRev(gf.depotFile, gf.rev, gf.p4action, gf.fileType, chgNo, gf.depotFile, chgNo, dt) } else if gf.action == rename { j.WriteRev(gf.srcDepotFile, gf.srcRev, journal.Delete, gf.fileType, chgNo, gf.depotFile, chgNo, dt) j.WriteRev(gf.depotFile, gf.srcRev-1, journal.Add, gf.fileType, chgNo, gf.srcDepotFile, gf.srcLbrRev, dt) j.WriteInteg(gf.depotFile, gf.srcDepotFile, 0, gf.srcRev, 0, gf.rev, journal.BranchFrom, c.commit.Mark) } } // RunGetCommits - for small files - returns list of all commits and files. func (g *GitP4Transfer) RunGetCommits(options GitParserOptions) (CommitMap, FileMap) { var buf io.Reader if g.testInput != "" { buf = strings.NewReader(g.testInput) } else { file, err := os.Open(options.gitImportFile) if err != nil { fmt.Printf("ERROR: Failed to open file '%s': %v\n", options.gitImportFile, err) os.Exit(1) } defer file.Close() buf = bufio.NewReader(file) } g.opts = options commits := make(map[int]*GitCommit, 0) files := make(map[int]*GitFile, 0) var currCommit *GitCommit f := libfastimport.NewFrontend(buf, nil, nil) for { cmd, err := f.ReadCmd() if err != nil { if err != io.EOF { fmt.Printf("ERROR: Failed to read cmd: %v\n", err) } break } switch cmd.(type) { case libfastimport.CmdBlob: blob := cmd.(libfastimport.CmdBlob) g.logger.Debugf("Blob: Mark:%d OriginalOID:%s Size:%s\n", blob.Mark, blob.OriginalOID, Humanize(len(blob.Data))) files[blob.Mark] = &GitFile{blob: &blob} case libfastimport.CmdReset: reset := cmd.(libfastimport.CmdReset) g.logger.Debugf("Reset: - %+v\n", reset) case libfastimport.CmdCommit: commit := cmd.(libfastimport.CmdCommit) g.logger.Debugf("Commit: %+v\n", commit) currCommit = &GitCommit{commit: &commit, files: make([]GitFile, 0)} commits[commit.Mark] = currCommit case libfastimport.CmdCommitEnd: commit := cmd.(libfastimport.CmdCommitEnd) g.logger.Debugf("CommitEnd: %+v\n", commit) case libfastimport.FileModify: f := cmd.(libfastimport.FileModify) g.logger.Debugf("FileModify: %+v\n", f) oid, err := getOID(f.DataRef) if err != nil { g.logger.Errorf("Failed to get oid: %+v", f) } gf, ok := files[oid] if ok { gf.name = f.Path.String() gf.updateFileDetails() currCommit.files = append(currCommit.files, *gf) } case libfastimport.FileDelete: f := cmd.(libfastimport.FileDelete) g.logger.Debugf("FileModify: Path:%s\n", f.Path) case libfastimport.FileCopy: f := cmd.(libfastimport.FileCopy) g.logger.Debugf("FileCopy: Src:%s Dst:%s\n", f.Src, f.Dst) case libfastimport.FileRename: f := cmd.(libfastimport.FileRename) g.logger.Debugf("FileRename: Src:%s Dst:%s\n", f.Src, f.Dst) case libfastimport.CmdTag: t := cmd.(libfastimport.CmdTag) g.logger.Debugf("CmdTag: %+v\n", t) default: g.logger.Debugf("Not handled\n") g.logger.Debugf("Found cmd %+v\n", cmd) g.logger.Debugf("Cmd type %T\n", cmd) } } return commits, files } // DumpGit - incrementally parse the git file, collecting stats and optionally saving archives as we go // Useful for parsing very large git fast-export files without loading too much into memory! func (g *GitP4Transfer) DumpGit(options GitParserOptions, saveFiles bool) { var buf io.Reader if g.testInput != "" { buf = strings.NewReader(g.testInput) } else { file, err := os.Open(options.gitImportFile) if err != nil { fmt.Printf("ERROR: Failed to open file '%s': %v\n", options.gitImportFile, err) os.Exit(1) } defer file.Close() buf = bufio.NewReader(file) } g.opts = options commits := make(map[int]*GitCommit, 0) files := make(map[int]*GitFile, 0) extSizes := make(map[string]int) var currCommit *GitCommit var commitSize = 0 f := libfastimport.NewFrontend(buf, nil, nil) for { cmd, err := f.ReadCmd() if err != nil { if err != io.EOF { fmt.Printf("ERROR: Failed to read cmd: %v", err) } break } switch cmd.(type) { case libfastimport.CmdBlob: blob := cmd.(libfastimport.CmdBlob) g.logger.Infof("Blob: Mark:%d OriginalOID:%s Size:%s", blob.Mark, blob.OriginalOID, Humanize(len(blob.Data))) size := len(blob.Data) commitSize += size // We write the blobs as we go to avoid using up too much memory if saveFiles { writeBlob(g.opts.archiveRoot, blob.Mark, &blob.Data) } blob.Data = "" files[blob.Mark] = &GitFile{blob: &blob, size: size} case libfastimport.CmdReset: reset := cmd.(libfastimport.CmdReset) g.logger.Infof("Reset: - %+v", reset) case libfastimport.CmdCommit: commit := cmd.(libfastimport.CmdCommit) g.logger.Infof("Commit: %+v", commit) currCommit = &GitCommit{commit: &commit, commitSize: commitSize, files: make([]GitFile, 0)} commitSize = 0 commits[commit.Mark] = currCommit case libfastimport.CmdCommitEnd: commit := cmd.(libfastimport.CmdCommitEnd) g.logger.Infof("CommitEnd: %+v", commit) for _, f := range currCommit.files { extSizes[filepath.Ext(f.name)] += f.size } case libfastimport.FileModify: f := cmd.(libfastimport.FileModify) g.logger.Infof("FileModify: %+v", f) oid, err := getOID(f.DataRef) if err != nil { g.logger.Errorf("Failed to get oid: %+v", f) } gf, ok := files[oid] if ok { gf.name = f.Path.String() _, archName := getBlobIDPath(g.opts.archiveRoot, gf.blob.Mark) gf.archiveFile = archName g.logger.Infof("Path:%s Size:%s Archive:%s", gf.name, Humanize(gf.size), gf.archiveFile) currCommit.files = append(currCommit.files, *gf) } case libfastimport.FileDelete: f := cmd.(libfastimport.FileDelete) g.logger.Infof("FileDelete: Path:%s", f.Path) case libfastimport.FileCopy: f := cmd.(libfastimport.FileCopy) g.logger.Infof("FileCopy: Src:%s Dst:%s", f.Src, f.Dst) case libfastimport.FileRename: f := cmd.(libfastimport.FileRename) g.logger.Infof("FileRename: Src:%s Dst:%s", f.Src, f.Dst) case libfastimport.CmdTag: t := cmd.(libfastimport.CmdTag) g.logger.Infof("CmdTag: %+v", t) default: g.logger.Errorf("Not handled - found cmd %+v", cmd) g.logger.Infof("Cmd type %T", cmd) } } for ext, size := range extSizes { g.logger.Infof("Ext %s: %s", ext, Humanize(size)) } } // Maintain a list of latest revision counters indexed by depotFile func (g *GitP4Transfer) updateDepotRevs(gf *GitFile, chgNo int, isRename bool) { if _, ok := g.depotFileRevs[gf.depotFile]; !ok { g.depotFileRevs[gf.depotFile] = &RevChange{0, chgNo} } g.depotFileRevs[gf.depotFile].rev += 1 gf.rev = g.depotFileRevs[gf.depotFile].rev if gf.rev == 1 && gf.action == modify { gf.p4action = journal.Add } if gf.srcName == "" { g.updateDepotFileTypes(gf) } else { gf.p4action = journal.Add if _, ok := g.depotFileRevs[gf.srcDepotFile]; !ok { panic(fmt.Sprintf("Expected to find %s", gf.srcDepotFile)) } if isRename { // Rename means old file is being deleted g.depotFileRevs[gf.srcDepotFile].rev += 1 gf.srcRev = g.depotFileRevs[gf.srcDepotFile].rev gf.srcLbrRev = g.depotFileRevs[gf.srcDepotFile].chgNo gf.fileType = g.getDepotFileTypes(gf.srcDepotFile, gf.srcRev-1) } else { // Copy gf.srcRev = g.depotFileRevs[gf.srcDepotFile].rev gf.fileType = g.getDepotFileTypes(gf.srcDepotFile, gf.srcRev) gf.srcLbrRev = g.depotFileRevs[gf.srcDepotFile].chgNo } } } // Maintain a list of latest revision counters indexed by depotFile/rev func (g *GitP4Transfer) updateDepotFileTypes(gf *GitFile) { k := fmt.Sprintf("%s#%d", gf.depotFile, gf.rev) g.depotFileTypes[k] = gf.fileType } // Retrieve required filetype func (g *GitP4Transfer) getDepotFileTypes(depotFile string, rev int) journal.FileType { k := fmt.Sprintf("%s#%d", depotFile, rev) if _, ok := g.depotFileTypes[k]; !ok { return 0 } return g.depotFileTypes[k] } // GitParse - returns channel which contains commits with associated files. func (g *GitP4Transfer) GitParse(options GitParserOptions) chan GitCommit { var buf io.Reader if g.testInput != "" { buf = strings.NewReader(g.testInput) } else { file, err := os.Open(options.gitImportFile) if err != nil { fmt.Printf("ERROR: Failed to open file '%s': %v\n", options.gitImportFile, err) os.Exit(1) } defer file.Close() buf = bufio.NewReader(file) } g.opts = options g.gitChan = make(chan GitCommit, 100) blobFiles := make(map[int]*GitFile, 0) // Index by blob ID (mark) var currCommit *GitCommit f := libfastimport.NewFrontend(buf, nil, nil) go func() { defer close(g.gitChan) for { cmd, err := f.ReadCmd() if err != nil { if err != io.EOF { g.logger.Errorf("ERROR: Failed to read cmd: %v\n", err) } break } switch cmd.(type) { case libfastimport.CmdBlob: blob := cmd.(libfastimport.CmdBlob) g.logger.Debugf("Blob: Mark:%d OriginalOID:%s Size:%s\n", blob.Mark, blob.OriginalOID, Humanize(len(blob.Data))) blobFiles[blob.Mark] = &GitFile{blob: &blob, action: modify} blobFiles[blob.Mark].setDepotPaths(g.opts) g.updateDepotRevs(blobFiles[blob.Mark], 0, false) case libfastimport.CmdReset: reset := cmd.(libfastimport.CmdReset) g.logger.Debugf("Reset: - %+v\n", reset) case libfastimport.CmdCommit: if currCommit != nil { g.gitChan <- *currCommit } commit := cmd.(libfastimport.CmdCommit) g.logger.Debugf("Commit: %+v\n", commit) currCommit = &GitCommit{commit: &commit, files: make([]GitFile, 0)} case libfastimport.CmdCommitEnd: commit := cmd.(libfastimport.CmdCommitEnd) g.logger.Debugf("CommitEnd: %+v\n", commit) case libfastimport.FileModify: f := cmd.(libfastimport.FileModify) g.logger.Debugf("FileModify: %+v\n", f) oid, err := getOID(f.DataRef) if err != nil { g.logger.Errorf("Failed to get oid: %+v", f) } gf, ok := blobFiles[oid] if ok { gf.name = f.Path.String() gf.setDepotPaths(g.opts) gf.updateFileDetails() g.updateDepotRevs(gf, currCommit.commit.Mark, false) currCommit.files = append(currCommit.files, *gf) } case libfastimport.FileDelete: f := cmd.(libfastimport.FileDelete) g.logger.Debugf("FileDelete: Path:%s\n", f.Path) gf := &GitFile{name: f.Path.String(), action: delete} gf.setDepotPaths(g.opts) gf.updateFileDetails() g.updateDepotRevs(gf, currCommit.commit.Mark, false) currCommit.files = append(currCommit.files, *gf) case libfastimport.FileCopy: f := cmd.(libfastimport.FileCopy) g.logger.Debugf("FileCopy: Src:%s Dst:%s\n", f.Src, f.Dst) gf := &GitFile{name: f.Src.String(), targ: f.Dst.String(), action: copy} gf.setDepotPaths(g.opts) gf.updateFileDetails() g.updateDepotRevs(gf, currCommit.commit.Mark, false) currCommit.files = append(currCommit.files, *gf) case libfastimport.FileRename: f := cmd.(libfastimport.FileRename) g.logger.Debugf("FileRename: Src:%s Dst:%s\n", f.Src, f.Dst) gf := &GitFile{name: f.Dst.String(), srcName: f.Src.String(), action: rename} gf.setDepotPaths(g.opts) gf.updateFileDetails() g.updateDepotRevs(gf, currCommit.commit.Mark, true) currCommit.files = append(currCommit.files, *gf) case libfastimport.CmdTag: t := cmd.(libfastimport.CmdTag) g.logger.Debugf("CmdTag: %+v\n", t) default: g.logger.Errorf("Not handled: Found cmd %+v\n", cmd) g.logger.Errorf("Cmd type %T\n", cmd) } } if currCommit != nil { g.gitChan <- *currCommit } }() return g.gitChan } func
() { // Tracing code // ft, err := os.Create("trace.out") // if err != nil { // panic(err) // } // defer ft.Close() // err = trace.Start(ft) // if err != nil { // panic(err) // } // defer trace.Stop() // End of trace code // var err error var ( gitimport = kingpin.Arg( "gitimport", "Git fast-export file to process.", ).String() dump = kingpin.Flag( "dump", "Dump git file, saving the contained archive contents.", ).Bool() archive = kingpin.Flag( "archive.root", "Archive root dir under which to store extracted archives if --dump set.", ).String() debug = kingpin.Flag( "debug", "Enable debugging level.", ).Int() ) kingpin.UsageTemplate(kingpin.CompactUsageTemplate).Version(version.Print("gitp4transfer")).Author("Robert Cowham") kingpin.CommandLine.Help = "Parses one or more git fast-export files to create a Perforce Helix Core import\n" kingpin.HelpFlag.Short('h') kingpin.Parse() logger := logrus.New() logger.Level = logrus.InfoLevel if *debug > 0 { logger.Level = logrus.DebugLevel } startTime := time.Now() logger.Infof("%v", version.Print("gitp4transfer")) logger.Infof("Starting %s, gitimport: %v", startTime, *gitimport) g := NewGitP4Transfer(logger) opts := GitParserOptions{ gitImportFile: *gitimport, archiveRoot: *archive, } if *dump { g.DumpGit(opts, true) } else { commits, files := g.RunGetCommits(opts) for _, v := range commits { g.logger.Infof("Found commit: id %d, files: %d", v.commit.Mark, len(v.files)) } for _, v := range files { g.logger.Infof("Found file: %s, %d", v.name, v.blob.Mark) } } }
main
policies.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 utils import ( "github.com/streamnative/pulsarctl/pkg/pulsar/common" ) const ( FirstBoundary string = "0x00000000" LastBoundary string = "0xffffffff" ) type Policies struct { Bundles *BundlesData `json:"bundles"` Persistence *PersistencePolicies `json:"persistence"` RetentionPolicies *RetentionPolicies `json:"retention_policies"` SchemaValidationEnforced bool `json:"schema_validation_enforced"` DeduplicationEnabled *bool `json:"deduplicationEnabled"` Deleted bool `json:"deleted"` EncryptionRequired bool `json:"encryption_required"` MessageTTLInSeconds *int `json:"message_ttl_in_seconds"` MaxProducersPerTopic *int `json:"max_producers_per_topic"` MaxConsumersPerTopic *int `json:"max_consumers_per_topic"` MaxConsumersPerSubscription *int `json:"max_consumers_per_subscription"` CompactionThreshold *int64 `json:"compaction_threshold"` OffloadThreshold int64 `json:"offload_threshold"` OffloadDeletionLagMs *int64 `json:"offload_deletion_lag_ms"` AntiAffinityGroup string `json:"antiAffinityGroup"` ReplicationClusters []string `json:"replication_clusters"` LatencyStatsSampleRate map[string]int `json:"latency_stats_sample_rate"` BacklogQuotaMap map[BacklogQuotaType]BacklogQuota `json:"backlog_quota_map"` TopicDispatchRate map[string]DispatchRate `json:"topicDispatchRate"` SubscriptionDispatchRate map[string]DispatchRate `json:"subscriptionDispatchRate"` ReplicatorDispatchRate map[string]DispatchRate `json:"replicatorDispatchRate"` PublishMaxMessageRate map[string]PublishRate `json:"publishMaxMessageRate"` ClusterSubscribeRate map[string]SubscribeRate `json:"clusterSubscribeRate"` TopicAutoCreationConfig *TopicAutoCreationConfig `json:"autoTopicCreationOverride"` SchemaCompatibilityStrategy SchemaCompatibilityStrategy `json:"schema_auto_update_compatibility_strategy"` AuthPolicies common.AuthPolicies `json:"auth_policies"` SubscriptionAuthMode SubscriptionAuthMode `json:"subscription_auth_mode"` } func
() *Policies { return &Policies{ AuthPolicies: *common.NewAuthPolicies(), ReplicationClusters: make([]string, 0, 10), BacklogQuotaMap: make(map[BacklogQuotaType]BacklogQuota), TopicDispatchRate: make(map[string]DispatchRate), SubscriptionDispatchRate: make(map[string]DispatchRate), ReplicatorDispatchRate: make(map[string]DispatchRate), PublishMaxMessageRate: make(map[string]PublishRate), ClusterSubscribeRate: make(map[string]SubscribeRate), LatencyStatsSampleRate: make(map[string]int), MessageTTLInSeconds: nil, Deleted: false, EncryptionRequired: false, SubscriptionAuthMode: None, MaxProducersPerTopic: nil, MaxConsumersPerSubscription: nil, MaxConsumersPerTopic: nil, CompactionThreshold: nil, OffloadThreshold: -1, SchemaCompatibilityStrategy: Full, SchemaValidationEnforced: false, } }
NewDefaultPolicies
nested_includes.py
exec(open("Modified_data/next_level.py").read())
solc.d.ts
import { ethers } from "ethers"; export interface ContractCode {
name: string; compiler: string; bytecode: string; runtime: string; } export declare type CompilerOptions = { filename?: string; basedir?: string; optimize?: boolean; throwWarnings?: boolean; }; export declare function customRequire(path: string): (name: string) => any; export declare function wrapSolc(_solc: any): (source: string, options?: CompilerOptions) => Array<ContractCode>; export declare const compile: (source: string, options?: CompilerOptions) => ContractCode[]; //# sourceMappingURL=solc.d.ts.map
interface: ethers.utils.Interface;
conversion.rs
// Copyright 2014-2018 The GeoRust Developers // // 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 types::*; use Geometry; use Wkt; use std::convert::{TryFrom, TryInto}; use geo_types::CoordFloat; use thiserror::Error; #[derive(Error, Debug)] pub enum Error { #[error("The WKT Point was empty, but geo_type::Points cannot be empty")] PointConversionError, #[error("Mismatched geometry (expected {expected:?}, found {found:?})")] MismatchedGeometry { expected: &'static str, found: &'static str, }, #[error("Wrong number of Geometries: {0}")] WrongNumberOfGeometries(usize), #[error("External error: {0}")] External(Box<dyn std::error::Error>), } impl<T> TryFrom<Wkt<T>> for geo_types::Geometry<T> where T: CoordFloat, { type Error = Error; fn try_from(mut wkt: Wkt<T>) -> Result<Self, Self::Error> { if wkt.items.len() == 1 { Self::try_from(wkt.items.pop().unwrap()) } else { Geometry::GeometryCollection(GeometryCollection(wkt.items)).try_into() } } } #[macro_use] macro_rules! try_from_wkt_impl { ($($type: ident),+) => { $( /// Convert a Wkt enum into a specific geo-type impl<T: CoordFloat> TryFrom<Wkt<T>> for geo_types::$type<T> { type Error = Error; fn try_from(mut wkt: Wkt<T>) -> Result<Self, Self::Error> { match wkt.items.len() { 1 => { let item = wkt.items.pop().unwrap(); let geometry = geo_types::Geometry::try_from(item)?; Self::try_from(geometry).map_err(|e| { match e { geo_types::Error::MismatchedGeometry { expected, found } => { Error::MismatchedGeometry { expected, found } } // currently only one error type in geo-types error enum, but that seems likely to change #[allow(unreachable_patterns)] other => Error::External(Box::new(other)), } }) } other => Err(Error::WrongNumberOfGeometries(other)), } } } )+ } } try_from_wkt_impl!( Point, Line, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, Rect, Triangle ); impl<T> From<Coord<T>> for geo_types::Coordinate<T> where T: CoordFloat, { fn from(coord: Coord<T>) -> geo_types::Coordinate<T> { Self { x: coord.x, y: coord.y, } } } impl<T> TryFrom<Point<T>> for geo_types::Point<T> where T: CoordFloat, { type Error = Error; fn try_from(point: Point<T>) -> Result<Self, Self::Error> { match point.0 { Some(coord) => Ok(Self::new(coord.x, coord.y)), None => Err(Error::PointConversionError), } } } #[deprecated(since = "0.9", note = "use `geometry.try_into()` instead")] pub fn try_into_geometry<T>(geometry: &Geometry<T>) -> Result<geo_types::Geometry<T>, Error> where T: CoordFloat, { geometry.clone().try_into() } impl<'a, T> From<&'a LineString<T>> for geo_types::Geometry<T> where T: CoordFloat, { fn from(line_string: &'a LineString<T>) -> Self { Self::LineString(line_string.clone().into()) } } impl<T> From<LineString<T>> for geo_types::LineString<T> where T: CoordFloat, { fn from(line_string: LineString<T>) -> Self { let coords = line_string .0 .into_iter() .map(geo_types::Coordinate::from) .collect(); geo_types::LineString(coords) } } impl<'a, T> From<&'a MultiLineString<T>> for geo_types::Geometry<T> where T: CoordFloat, { fn from(multi_line_string: &'a MultiLineString<T>) -> geo_types::Geometry<T> { Self::MultiLineString(multi_line_string.clone().into()) } } impl<T> From<MultiLineString<T>> for geo_types::MultiLineString<T> where T: CoordFloat, { fn from(multi_line_string: MultiLineString<T>) -> geo_types::MultiLineString<T> { let geo_line_strings: Vec<geo_types::LineString<T>> = multi_line_string .0 .into_iter() .map(geo_types::LineString::from) .collect(); geo_types::MultiLineString(geo_line_strings) } } impl<'a, T> From<&'a Polygon<T>> for geo_types::Geometry<T> where T: CoordFloat, { fn from(polygon: &'a Polygon<T>) -> geo_types::Geometry<T> { Self::Polygon(polygon.clone().into()) } } impl<T> From<Polygon<T>> for geo_types::Polygon<T> where T: CoordFloat, { fn from(polygon: Polygon<T>) -> Self { let mut iter = polygon.0.into_iter().map(geo_types::LineString::from); match iter.next() { Some(interior) => geo_types::Polygon::new(interior, iter.collect()), None => geo_types::Polygon::new(geo_types::LineString(vec![]), vec![]), } } } impl<'a, T> TryFrom<&'a MultiPoint<T>> for geo_types::Geometry<T> where T: CoordFloat, { type Error = Error; fn try_from(multi_point: &'a MultiPoint<T>) -> Result<Self, Self::Error> { Ok(Self::MultiPoint(multi_point.clone().try_into()?)) } } impl<T> TryFrom<MultiPoint<T>> for geo_types::MultiPoint<T> where T: CoordFloat, { type Error = Error; fn try_from(multi_point: MultiPoint<T>) -> Result<Self, Self::Error> { let points: Vec<geo_types::Point<T>> = multi_point .0 .into_iter() .map(geo_types::Point::try_from) .collect::<Result<Vec<_>, _>>()?; Ok(geo_types::MultiPoint(points)) } } impl<'a, T> From<&'a MultiPolygon<T>> for geo_types::Geometry<T> where T: CoordFloat, { fn from(multi_polygon: &'a MultiPolygon<T>) -> Self { Self::MultiPolygon(multi_polygon.clone().into()) } } impl<T> From<MultiPolygon<T>> for geo_types::MultiPolygon<T> where T: CoordFloat, { fn from(multi_polygon: MultiPolygon<T>) -> Self { let geo_polygons: Vec<geo_types::Polygon<T>> = multi_polygon .0 .into_iter() .map(geo_types::Polygon::from) .collect(); geo_types::MultiPolygon(geo_polygons) } } #[deprecated(since = "0.9", note = "use `geometry_collection.try_into()` instead")] pub fn try_into_geometry_collection<T>( geometry_collection: &GeometryCollection<T>, ) -> Result<geo_types::Geometry<T>, Error> where T: CoordFloat, { Ok(geo_types::Geometry::GeometryCollection( geometry_collection.clone().try_into()?, )) } impl<T> TryFrom<GeometryCollection<T>> for geo_types::GeometryCollection<T> where T: CoordFloat, { type Error = Error; fn try_from(geometry_collection: GeometryCollection<T>) -> Result<Self, Self::Error> { let geo_geometeries = geometry_collection .0 .into_iter() .map(Geometry::try_into) .collect::<Result<_, _>>()?; Ok(geo_types::GeometryCollection(geo_geometeries)) } } impl<T> TryFrom<Geometry<T>> for geo_types::Geometry<T> where T: CoordFloat, { type Error = Error; fn try_from(geometry: Geometry<T>) -> Result<Self, Self::Error> { Ok(match geometry { Geometry::Point(g) => { // Special case as `geo::Point` can't be empty if g.0.is_some() { geo_types::Point::try_from(g)?.into() } else { geo_types::MultiPoint(vec![]).into() } } Geometry::LineString(g) => geo_types::Geometry::LineString(g.into()), Geometry::Polygon(g) => geo_types::Geometry::Polygon(g.into()), Geometry::MultiLineString(g) => geo_types::Geometry::MultiLineString(g.into()), Geometry::MultiPoint(g) => geo_types::Geometry::MultiPoint(g.try_into()?), Geometry::MultiPolygon(g) => geo_types::Geometry::MultiPolygon(g.into()), Geometry::GeometryCollection(g) => { geo_types::Geometry::GeometryCollection(g.try_into()?) } }) } } #[cfg(test)] mod tests { use super::*; #[test] fn convert_single_item_wkt() { let w_point = Point(Some(Coord { x: 1.0, y: 2.0, z: None, m: None, })) .as_item(); let mut wkt = Wkt::new(); wkt.add_item(w_point);
assert_eq!(converted, geo_types::Geometry::Point(g_point)); } #[test] fn convert_collection_wkt() { let w_point_1 = Point(Some(Coord { x: 1.0, y: 2.0, z: None, m: None, })) .as_item(); let w_point_2 = Point(Some(Coord { x: 3.0, y: 4.0, z: None, m: None, })) .as_item(); let mut wkt = Wkt::new(); wkt.add_item(w_point_1); wkt.add_item(w_point_2); let converted = geo_types::Geometry::try_from(wkt).unwrap(); let geo_collection: geo_types::GeometryCollection<f64> = geo_types::GeometryCollection(vec![ geo_types::Point::new(1.0, 2.0).into(), geo_types::Point::new(3.0, 4.0).into(), ]); assert_eq!( converted, geo_types::Geometry::GeometryCollection(geo_collection) ); } #[test] fn convert_empty_point() { let point = Point(None); let res: Result<geo_types::Point<f64>, Error> = point.try_into(); assert!(res.is_err()); } #[test] fn convert_point() { let point = Point(Some(Coord { x: 10., y: 20., z: None, m: None, })) .as_item(); let g_point: geo_types::Point<f64> = (10., 20.).into(); assert_eq!( geo_types::Geometry::Point(g_point), point.try_into().unwrap() ); } #[test] fn convert_empty_linestring() { let w_linestring = LineString(vec![]).as_item(); let g_linestring: geo_types::LineString<f64> = geo_types::LineString(vec![]); assert_eq!( geo_types::Geometry::LineString(g_linestring), w_linestring.try_into().unwrap() ); } #[test] fn convert_linestring() { let w_linestring = LineString(vec![ Coord { x: 10., y: 20., z: None, m: None, }, Coord { x: 30., y: 40., z: None, m: None, }, ]) .as_item(); let g_linestring: geo_types::LineString<f64> = vec![(10., 20.), (30., 40.)].into(); assert_eq!( geo_types::Geometry::LineString(g_linestring), w_linestring.try_into().unwrap() ); } #[test] fn convert_empty_polygon() { let w_polygon = Polygon(vec![]).as_item(); let g_polygon: geo_types::Polygon<f64> = geo_types::Polygon::new(geo_types::LineString(vec![]), vec![]); assert_eq!( geo_types::Geometry::Polygon(g_polygon), w_polygon.try_into().unwrap() ); } #[test] fn convert_polygon() { let w_polygon = Polygon(vec![ LineString(vec![ Coord { x: 0., y: 0., z: None, m: None, }, Coord { x: 20., y: 40., z: None, m: None, }, Coord { x: 40., y: 0., z: None, m: None, }, Coord { x: 0., y: 0., z: None, m: None, }, ]), LineString(vec![ Coord { x: 5., y: 5., z: None, m: None, }, Coord { x: 20., y: 30., z: None, m: None, }, Coord { x: 30., y: 5., z: None, m: None, }, Coord { x: 5., y: 5., z: None, m: None, }, ]), ]) .as_item(); let g_polygon: geo_types::Polygon<f64> = geo_types::Polygon::new( vec![(0., 0.), (20., 40.), (40., 0.), (0., 0.)].into(), vec![vec![(5., 5.), (20., 30.), (30., 5.), (5., 5.)].into()], ); assert_eq!( geo_types::Geometry::Polygon(g_polygon), w_polygon.try_into().unwrap() ); } #[test] fn convert_empty_multilinestring() { let w_multilinestring = MultiLineString(vec![]).as_item(); let g_multilinestring: geo_types::MultiLineString<f64> = geo_types::MultiLineString(vec![]); assert_eq!( geo_types::Geometry::MultiLineString(g_multilinestring), w_multilinestring.try_into().unwrap() ); } #[test] fn convert_multilinestring() { let w_multilinestring = MultiLineString(vec![ LineString(vec![ Coord { x: 10., y: 20., z: None, m: None, }, Coord { x: 30., y: 40., z: None, m: None, }, ]), LineString(vec![ Coord { x: 50., y: 60., z: None, m: None, }, Coord { x: 70., y: 80., z: None, m: None, }, ]), ]) .as_item(); let g_multilinestring: geo_types::MultiLineString<f64> = geo_types::MultiLineString(vec![ vec![(10., 20.), (30., 40.)].into(), vec![(50., 60.), (70., 80.)].into(), ]); assert_eq!( geo_types::Geometry::MultiLineString(g_multilinestring), w_multilinestring.try_into().unwrap() ); } #[test] fn convert_empty_multipoint() { let w_multipoint = MultiPoint(vec![]).as_item(); let g_multipoint: geo_types::MultiPoint<f64> = geo_types::MultiPoint(vec![]); assert_eq!( geo_types::Geometry::MultiPoint(g_multipoint), w_multipoint.try_into().unwrap() ); } #[test] fn convert_multipoint() { let w_multipoint = MultiPoint(vec![ Point(Some(Coord { x: 10., y: 20., z: None, m: None, })), Point(Some(Coord { x: 30., y: 40., z: None, m: None, })), ]) .as_item(); let g_multipoint: geo_types::MultiPoint<f64> = vec![(10., 20.), (30., 40.)].into(); assert_eq!( geo_types::Geometry::MultiPoint(g_multipoint), w_multipoint.try_into().unwrap() ); } #[test] fn convert_empty_multipolygon() { let w_multipolygon = MultiPolygon(vec![]).as_item(); let g_multipolygon: geo_types::MultiPolygon<f64> = geo_types::MultiPolygon(vec![]); assert_eq!( geo_types::Geometry::MultiPolygon(g_multipolygon), w_multipolygon.try_into().unwrap() ); } #[test] fn convert_multipolygon() { let w_multipolygon = MultiPolygon(vec![ Polygon(vec![ LineString(vec![ Coord { x: 0., y: 0., z: None, m: None, }, Coord { x: 20., y: 40., z: None, m: None, }, Coord { x: 40., y: 0., z: None, m: None, }, Coord { x: 0., y: 0., z: None, m: None, }, ]), LineString(vec![ Coord { x: 5., y: 5., z: None, m: None, }, Coord { x: 20., y: 30., z: None, m: None, }, Coord { x: 30., y: 5., z: None, m: None, }, Coord { x: 5., y: 5., z: None, m: None, }, ]), ]), Polygon(vec![LineString(vec![ Coord { x: 40., y: 40., z: None, m: None, }, Coord { x: 20., y: 45., z: None, m: None, }, Coord { x: 45., y: 30., z: None, m: None, }, Coord { x: 40., y: 40., z: None, m: None, }, ])]), ]) .as_item(); let g_multipolygon: geo_types::MultiPolygon<f64> = geo_types::MultiPolygon(vec![ geo_types::Polygon::new( vec![(0., 0.), (20., 40.), (40., 0.), (0., 0.)].into(), vec![vec![(5., 5.), (20., 30.), (30., 5.), (5., 5.)].into()], ), geo_types::Polygon::new( vec![(40., 40.), (20., 45.), (45., 30.), (40., 40.)].into(), vec![], ), ]); assert_eq!( geo_types::Geometry::MultiPolygon(g_multipolygon), w_multipolygon.try_into().unwrap() ); } #[test] fn convert_empty_geometrycollection() { let w_geometrycollection = GeometryCollection(vec![]).as_item(); let g_geometrycollection: geo_types::GeometryCollection<f64> = geo_types::GeometryCollection(vec![]); assert_eq!( geo_types::Geometry::GeometryCollection(g_geometrycollection), w_geometrycollection.try_into().unwrap() ); } #[test] fn convert_geometrycollection() { let w_point = Point(Some(Coord { x: 10., y: 20., z: None, m: None, })) .as_item(); let w_linestring = LineString(vec![ Coord { x: 10., y: 20., z: None, m: None, }, Coord { x: 30., y: 40., z: None, m: None, }, ]) .as_item(); let w_polygon = Polygon(vec![LineString(vec![ Coord { x: 0., y: 0., z: None, m: None, }, Coord { x: 20., y: 40., z: None, m: None, }, Coord { x: 40., y: 0., z: None, m: None, }, Coord { x: 0., y: 0., z: None, m: None, }, ])]) .as_item(); let w_multilinestring = MultiLineString(vec![ LineString(vec![ Coord { x: 10., y: 20., z: None, m: None, }, Coord { x: 30., y: 40., z: None, m: None, }, ]), LineString(vec![ Coord { x: 50., y: 60., z: None, m: None, }, Coord { x: 70., y: 80., z: None, m: None, }, ]), ]) .as_item(); let w_multipoint = MultiPoint(vec![ Point(Some(Coord { x: 10., y: 20., z: None, m: None, })), Point(Some(Coord { x: 30., y: 40., z: None, m: None, })), ]) .as_item(); let w_multipolygon = MultiPolygon(vec![ Polygon(vec![LineString(vec![ Coord { x: 0., y: 0., z: None, m: None, }, Coord { x: 20., y: 40., z: None, m: None, }, Coord { x: 40., y: 0., z: None, m: None, }, Coord { x: 0., y: 0., z: None, m: None, }, ])]), Polygon(vec![LineString(vec![ Coord { x: 40., y: 40., z: None, m: None, }, Coord { x: 20., y: 45., z: None, m: None, }, Coord { x: 45., y: 30., z: None, m: None, }, Coord { x: 40., y: 40., z: None, m: None, }, ])]), ]) .as_item(); let w_geometrycollection = GeometryCollection(vec![ w_point, w_multipoint, w_linestring, w_multilinestring, w_polygon, w_multipolygon, ]) .as_item(); let g_point: geo_types::Point<f64> = (10., 20.).into(); let g_linestring: geo_types::LineString<f64> = vec![(10., 20.), (30., 40.)].into(); let g_polygon: geo_types::Polygon<f64> = geo_types::Polygon::new( vec![(0., 0.), (20., 40.), (40., 0.), (0., 0.)].into(), vec![], ); let g_multilinestring: geo_types::MultiLineString<f64> = geo_types::MultiLineString(vec![ vec![(10., 20.), (30., 40.)].into(), vec![(50., 60.), (70., 80.)].into(), ]); let g_multipoint: geo_types::MultiPoint<f64> = vec![(10., 20.), (30., 40.)].into(); let g_multipolygon: geo_types::MultiPolygon<f64> = geo_types::MultiPolygon(vec![ geo_types::Polygon::new( vec![(0., 0.), (20., 40.), (40., 0.), (0., 0.)].into(), vec![], ), geo_types::Polygon::new( vec![(40., 40.), (20., 45.), (45., 30.), (40., 40.)].into(), vec![], ), ]); let g_geometrycollection: geo_types::GeometryCollection<f64> = geo_types::GeometryCollection(vec![ geo_types::Geometry::Point(g_point), geo_types::Geometry::MultiPoint(g_multipoint), geo_types::Geometry::LineString(g_linestring), geo_types::Geometry::MultiLineString(g_multilinestring), geo_types::Geometry::Polygon(g_polygon), geo_types::Geometry::MultiPolygon(g_multipolygon), ]); assert_eq!( geo_types::Geometry::GeometryCollection(g_geometrycollection), w_geometrycollection.try_into().unwrap() ); } }
let converted = geo_types::Geometry::try_from(wkt).unwrap(); let g_point: geo_types::Point<f64> = geo_types::Point::new(1.0, 2.0);
batch_storer.go
package order import ( "fmt" "github.com/btcsuite/btcd/btcec/v2" "github.com/btcsuite/btcd/wire" "github.com/lightninglabs/pool/account" "github.com/lightninglabs/pool/auctioneerrpc" ) // batchStorer is a type that implements BatchStorer and can persist a batch to // the local trader database. type batchStorer struct { orderStore Store getAccount func(*btcec.PublicKey) (*account.Account, error) } // StorePendingBatch makes sure all changes executed by a batch are correctly // and atomically staged to the database. It is assumed that the batch has // previously been fully validated and that all diffs contained are consistent! // Once the batch has been finalized/confirmed on-chain, then the stage // modifications will be applied atomically as a result of MarkBatchComplete. // // NOTE: This method is part of the BatchStorer interface. func (s *batchStorer) StorePendingBatch(batch *Batch) error { // Prepare the order modifications first. orders := make([]Nonce, len(batch.MatchedOrders)) orderModifiers := make([][]Modifier, len(orders)) orderIndex := 0 for nonce, theirOrders := range batch.MatchedOrders { // Get our order first to find out the number of unfulfilled // units. ourOrder, err := s.orderStore.GetOrder(nonce) if err != nil { return fmt.Errorf("error getting order: %v", err) } orders[orderIndex] = nonce // Find out if the order has unfulfilled units left or not. unitsUnfulfilled := ourOrder.Details().UnitsUnfulfilled for _, theirOrder := range theirOrders { unitsUnfulfilled -= theirOrder.UnitsFilled } switch { // The order has been fully filled and can be archived. case unitsUnfulfilled == 0: orderModifiers[orderIndex] = []Modifier{ StateModifier(StateExecuted), UnitsFulfilledModifier(0), } // The order has not been fully filled, but it cannot be matched // again due to its remaining unfulfilled units being below its // allowed minimum, so we'll archive it. case unitsUnfulfilled < ourOrder.Details().MinUnitsMatch: orderModifiers[orderIndex] = []Modifier{ StateModifier(StateExecuted), UnitsFulfilledModifier(unitsUnfulfilled), } // Some units were not yet filled. default: orderModifiers[orderIndex] = []Modifier{ StateModifier(StatePartiallyFilled), UnitsFulfilledModifier(unitsUnfulfilled), } } orderIndex++ } // Next create our account modifiers. accounts := make([]*account.Account, len(batch.AccountDiffs)) accountModifiers := make([][]account.Modifier, len(accounts)) for idx, diff := range batch.AccountDiffs { // Get the current state of the account first so we can create // a proper diff. acct, err := s.getAccount(diff.AccountKey) if err != nil { return fmt.Errorf("error getting account: %v", err) } accounts[idx] = acct var modifiers []account.Modifier // Determine the new state of the account and set the on-chain // attributes accordingly. switch diff.EndingState { // The account output has been recreated and needs to wait to be // confirmed again. case auctioneerrpc.AccountDiff_OUTPUT_RECREATED: modifiers = append( modifiers, account.StateModifier(account.StatePendingBatch), account.OutPointModifier(wire.OutPoint{ Index: uint32(diff.OutpointIndex), Hash: batch.BatchTX.TxHash(),
}), account.IncrementBatchKey(), ) // The account expiry needs to be updated only when the // client supports it. if batch.Version.SupportsAccountExtension() && diff.NewExpiry != 0 { modifiers = append( modifiers, account.ExpiryModifier(diff.NewExpiry), ) } // The account was fully spent on-chain. We need to wait for the // batch (spend) TX to be confirmed still. case auctioneerrpc.AccountDiff_OUTPUT_FULLY_SPENT, auctioneerrpc.AccountDiff_OUTPUT_DUST_ADDED_TO_FEES, auctioneerrpc.AccountDiff_OUTPUT_DUST_EXTENDED_OFFCHAIN: modifiers = append( modifiers, account.StateModifier(account.StatePendingClosed), ) default: return fmt.Errorf("invalid ending account state %d", diff.EndingState) } // Finally update the account value, height hint, and its latest // transaction. modifiers = append( modifiers, account.ValueModifier(diff.EndingBalance), ) modifiers = append( modifiers, account.HeightHintModifier(batch.HeightHint), ) modifiers = append( modifiers, account.LatestTxModifier(batch.BatchTX), ) accountModifiers[idx] = modifiers } // Everything is ready to be persisted now. return s.orderStore.StorePendingBatch( batch, orders, orderModifiers, accounts, accountModifiers, ) } // MarkBatchComplete marks a pending batch as complete, allowing a trader to // participate in a new batch. func (s *batchStorer) MarkBatchComplete() error { return s.orderStore.MarkBatchComplete() } // A compile-time constraint to ensure batchStorer implements BatchStorer. var _ BatchStorer = (*batchStorer)(nil)
0003_sparecustomer_spareorder_sparesold.py
# Generated by Django 2.1.5 on 2019-03-31 18:24 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('stock', '0002_spare_store'), ] operations = [ migrations.CreateModel( name='SpareCustomer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('email', models.CharField(max_length=100)), ('phone_number', models.CharField(max_length=10)), ('address', models.TextField()), ], ), migrations.CreateModel( name='SpareOrder', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('order_id', models.CharField(max_length=20)), ('order_type', models.CharField(choices=[('IN_SOURCE', 'IN_SOURCE'), ('OUT_SOURCE', 'OUT_SOURCE')], max_length=20)), ('total', models.DecimalField(decimal_places=2, max_digits=10)), ('order_date', models.DateTimeField(auto_now=True)), ('customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='stock.SpareCustomer')), ('sold_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
('store', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='accounts.Store')), ], ), migrations.CreateModel( name='SpareSold', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('spare_count', models.IntegerField()), ('spare_name', models.CharField(max_length=100)), ('spare_price', models.DecimalField(decimal_places=2, max_digits=10)), ('spare_price_type', models.CharField(choices=[('MRP', 'MRP'), ('MECHANIC', 'MECHANIC'), ('WHOLESALER', 'WHOLESALER'), ('CUSTOMER', 'CUSTOMER')], max_length=20)), ('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='stock.SpareOrder')), ('spare', models.ForeignKey(on_delete=models.SET('deleted'), to='stock.Spare')), ], ), ]
raplot.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """"WRITEME""" import matplotlib.pyplot as plt import numpy as np import pygimli as pg from pygimli.viewer.mpl import createColorBar # , updateColorBar from .ratools import shotReceiverDistances def drawTravelTimeData(ax, data, t=None):
def plotFirstPicks(ax, data, tt=None, plotva=False, marker='x-'): """Naming convention. drawFOO(ax, ... )""" pg.deprecated("use drawFirstPicks") return drawFirstPicks(ax=ax, data=data, tt=tt, plotva=plotva, marker=marker) def drawFirstPicks(ax, data, tt=None, plotva=False, marker='x-'): """plot first arrivals as lines""" px = pg.x(data) gx = np.array([px[int(g)] for g in data("g")]) sx = np.array([px[int(s)] for s in data("s")]) if tt is None: tt = np.array(data("t")) if plotva: tt = np.absolute(gx - sx) / tt uns = np.unique(sx) cols = plt.cm.tab10(np.arange(10)) for i, si in enumerate(uns): ti = tt[sx == si] gi = gx[sx == si] ii = gi.argsort() ax.plot(gi[ii], ti[ii], marker, color=cols[i % 10]) ax.plot(si, 0., 's', color=cols[i % 10], markersize=8) ax.grid(True) if plotva: ax.set_ylabel("Apparent velocity (m/s)") else: ax.set_ylabel("Traveltime (s)") ax.set_xlabel("x (m)") ax.invert_yaxis() def _getOffset(data, full=False): """Return vector of offsets (in m) between shot and receiver.""" pg.deprecated('use shotReceiverDistances') # 190429 ?? return shotReceiverDistances(data, full) def showVA(data, usePos=True, ax=None, **kwargs): """Show apparent velocity as image plot Parameters ---------- data : pg.DataContainer() Datacontainer with 's' and 'g' Sensorindieces and 't' traveltimes. """ ax, _ = pg.show(ax=ax) gci = drawVA(ax, data=data, usePos=usePos, **kwargs) cBar = createColorBar(gci, **kwargs) return gci, cBar def drawVA(ax, data, vals=None, usePos=True, pseudosection=False, **kwargs): """Draw apparent velocities as matrix into ax Parameters ---------- ax : mpl.Axes data : pg.DataContainer() Datacontainer with 's' and 'g' Sensorindieces and 't' traveltimes. usePos: bool [True] Use sensor positions for axes tick labels pseudosection : bool [False] Show in pseudosection style. vals : iterable Traveltimes, if None data need to contain 't' values. """ if isinstance(vals, str): vals = data(vals) if vals is None: vals = data('t') px = pg.x(data) gx = np.asarray([px[g] for g in data.id("g")]) sx = np.asarray([px[s] for s in data.id("s")]) offset = shotReceiverDistances(data, full=True) if min(vals) < 1e-10: print(vals) pg.error('zero traveltimes found.') va = offset / vals if pseudosection: midpoint = (gx + sx) / 2 gci = pg.viewer.mpl.dataview.drawVecMatrix(ax, midpoint, offset, va, queeze=True, label=pg.unit('as')) else: gci = pg.viewer.mpl.dataview.drawVecMatrix(ax, gx, sx, va, squeeze=True, label=pg.unit('as')) # A = np.ones((data.sensorCount(), data.sensorCount())) * np.nan # for i in range(data.size()): # A[int(data('s')[i]), int(data('g')[i])] = va[i] # gci = ax.imshow(A, interpolation='nearest') # ax.grid(True) if usePos: xt = np.arange(0, data.sensorCount(), 50) ax.set_xticks(xt) ax.set_xticklabels([str(int(px[xti])) for xti in xt]) ax.set_yticks(xt) ax.set_yticklabels([str(int(px[xti])) for xti in xt]) return gci def plotLines(ax, line_filename, step=1): xz = np.loadtxt(line_filename) n_points = xz.shape[0] if step == 2: for i in range(0, n_points, step): x = xz[i:i + step, 0] z = xz[i:i + step, 1] ax.plot(x, z, 'k-') if step == 1: ax.plot(xz[:, 0], xz[:, 1], 'k-')
""" Draw first arrival traveltime data into mpl ax a. data of type \ref DataContainer must contain sensorIdx 's' and 'g' and thus being numbered internally [0..n) """ x = pg.x(data.sensorPositions()) # z = pg.z(data.sensorPositions()) shots = pg.unique(pg.sort(data('s'))) geoph = pg.unique(pg.sort(data('g'))) startOffsetIDX = 0 if min(min(shots), min(geoph)) == 1: startOffsetIDX = 1 tShow = data('t') if t is not None: tShow = t ax.set_xlim([min(x), max(x)]) ax.set_ylim([max(tShow), -0.002]) ax.figure.show() for shot in shots: gIdx = pg.find(data('s') == shot) sensorIdx = [int(i__ - startOffsetIDX) for i__ in data('g')[gIdx]] ax.plot(x[sensorIdx], tShow[gIdx], 'x-') yPixel = ax.transData.inverted().transform_point((1, 1))[1] - \ ax.transData.inverted().transform_point((0, 0))[1] xPixel = ax.transData.inverted().transform_point((1, 1))[0] - \ ax.transData.inverted().transform_point((0, 0))[0] # draw shot points ax.plot(x[[int(i__ - startOffsetIDX) for i__ in shots]], np.zeros(len(shots)) + 8. * yPixel, 'gv', markersize=8) # draw geophone points ax.plot(x[[int(i__ - startOffsetIDX) for i__ in geoph]], np.zeros(len(geoph)) + 3. * yPixel, 'r^', markersize=8) ax.grid() ax.set_ylim([max(tShow), +16. * yPixel]) ax.set_xlim([min(x) - 5. * xPixel, max(x) + 5. * xPixel]) ax.set_xlabel('x-Coordinate [m]') ax.set_ylabel('Traveltime [ms]')
test_mail_list_model.py
import json from authors.apps.authentication.tests.base import BaseTestMethods from authors.apps.authentication.models import User from rest_framework.reverse import reverse from rest_framework import status class NotificationTests(BaseTestMethods): def test_create_mail_list(self): user = self.register_and_loginUser() token = user.data['token'] auth = f'Bearer {token}' url = reverse('mail-list-status') response = self.client.get(url, HTTP_AUTHORIZATION=auth) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertIsInstance(response.data, dict) self.assertEqual( response.data['user']['email'], '[email protected]') def test_create_update_notification_status(self): user = self.register_and_loginUser() token = user.data['token'] auth = f'Bearer {token}' url = reverse('mail-list-status') data = {'recieve_email_notifications': 'false'} response = self.client.put(url, data=data, HTTP_AUTHORIZATION=auth) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['recieve_email_notifications'], False) def test_fetch_all_user_notifications(self): user_1 = self.register_and_loginUser() user_1_token = user_1.data['token'] user_2 = self.register_and_login_user2() user_2_token = user_2.data['token'] this_user_2 = User.objects.get(email=user_2.data['email']) response = self.client.post( '/api/v1/users/{}/profile/follow'.format(this_user_2.username), HTTP_AUTHORIZATION=f'Bearer {user_1_token}') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual( json.loads(response.content)[ 'profile']['following'], True ) # fetch notification object url = reverse('all-notifications') notifications = self.client.get( url, format='json', HTTP_AUTHORIZATION=f'Bearer {user_2_token}') self.assertEqual(notifications.status_code, status.HTTP_200_OK) self.assertEqual( notifications.data['count'], 1) def test_cant_fetch_notifications_for_different_user(self): # register and login user user_1 = self.register_and_loginUser() user_1_token = user_1.data['token'] user_2 = self.register_and_login_user2() this_user_2 = User.objects.get(email=user_2.data['email']) # follow a registered user response = self.client.post( '/api/v1/users/{}/profile/follow'.format(this_user_2.username), HTTP_AUTHORIZATION=f'Bearer {user_1_token}') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual( json.loads(response.content)[ 'profile']['following'], True ) # fetch user notification objects url = reverse('all-notifications') notifications = self.client.get( url, format='json', HTTP_AUTHORIZATION=f'Bearer {user_1_token}') self.assertEqual( notifications.data['message'], 'You currently dont have any notifications') def test_fetch_all_user_unread_notifications(self): # register and login user user_1 = self.register_and_loginUser() user_1_token = user_1.data['token'] user_2 = self.register_and_login_user2() user_2_token = user_2.data['token'] this_user_2 = User.objects.get(email=user_2.data['email']) # follow a registered user response = self.client.post( '/api/v1/users/{}/profile/follow'.format(this_user_2.username), HTTP_AUTHORIZATION=f'Bearer {user_1_token}') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual( json.loads(response.content)[ 'profile']['following'], True ) # fetch notification object url = reverse('unread-notifications') notifications = self.client.get( url, format='json', HTTP_AUTHORIZATION=f'Bearer {user_2_token}') self.assertEqual(notifications.status_code, status.HTTP_200_OK) self.assertEqual( notifications.data['count'], 1) def test_failed_fetch_all_user_unread_notifications(self): # register and login user self.register_and_loginUser() user_2 = self.register_and_login_user2() user_2_token = user_2.data['token'] # fetch notification object url = reverse('unread-notifications') notifications = self.client.get( url, format='json', HTTP_AUTHORIZATION=f'Bearer {user_2_token}') self.assertEqual( notifications.data['message'], 'You currently dont have any unread notifications') def
(self): # register and login user user_1 = self.register_and_loginUser() user_1_token = user_1.data['token'] user_2 = self.register_and_login_user2() user_2_token = user_2.data['token'] this_user_2 = User.objects.get(email=user_2.data['email']) # follow a registered user response = self.client.post( '/api/v1/users/{}/profile/follow'.format(this_user_2.username), HTTP_AUTHORIZATION=f'Bearer {user_1_token}') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual( json.loads(response.content)[ 'profile']['following'], True ) # mark notifications as read url = reverse('mark-all-as-read') self.client.get( url, format='json', HTTP_AUTHORIZATION=f'Bearer {user_2_token}') # fetch notification object url = reverse('read-notifications') notifications = self.client.get( url, format='json', HTTP_AUTHORIZATION=f'Bearer {user_2_token}') self.assertEqual( notifications.data['count'], 1) def test_failed_fetch_all_user_read_notifications(self): # register and login user user_1 = self.register_and_loginUser() user_1_token = user_1.data['token'] user_2 = self.register_and_login_user2() user_2_token = user_2.data['token'] this_user_2 = User.objects.get(email=user_2.data['email']) # follow a registered user response = self.client.post( '/api/v1/users/{}/profile/follow'.format(this_user_2.username), HTTP_AUTHORIZATION=f'Bearer {user_1_token}') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual( json.loads(response.content)[ 'profile']['following'], True ) # fetch notification object url = reverse('read-notifications') notifications = self.client.get( url, format='json', HTTP_AUTHORIZATION=f'Bearer {user_2_token}') self.assertEqual( notifications.data['message'], 'You currently dont have any read notifications') def test_mark_all_notofications_as_read(self): # register and login user user_1 = self.register_and_loginUser() user_1_token = user_1.data['token'] user_2 = self.register_and_login_user2() user_2_token = user_2.data['token'] this_user_2 = User.objects.get(email=user_2.data['email']) # follow a registered user response = self.client.post( '/api/v1/users/{}/profile/follow'.format(this_user_2.username), HTTP_AUTHORIZATION=f'Bearer {user_1_token}') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual( json.loads(response.content)[ 'profile']['following'], True ) # mark notifications as read url = reverse('mark-all-as-read') notifications = self.client.get( url, format='json', HTTP_AUTHORIZATION=f'Bearer {user_2_token}') self.assertEqual( notifications.data['message'], 'All notifications marked as read')
test_fetch_all_user_read_notofications
mercury_test.go
// +build !travis package mercury import ( "flag" "testing" "github.com/jguyomard/slackbot-links/src/config" ) var ( testURL = "https://ilonet.fr/welcome-to-hugo/" testExpectedTitle = "Welcome to Hugo!" testExpectedDatePublished = "2016-06-11T00:00:00.000Z" testExpectedImageURL = "" testExpectedTotalPages = 1 testExpectedWordCount = 92 testExpectedDirection = "ltr" ) func
() { configFilePtr := flag.String("config-file", "/etc/slackbot-links/config.yaml", "conf file path") flag.Parse() config.SetFilePath(*configFilePtr) } func TestParse(t *testing.T) { infos, err := ParseURL(testURL) if err != nil { t.Fatal(err) } if infos.Title != testExpectedTitle { t.Fatal("mercury.Parse(): incorrect Title") } if infos.DatePublished != testExpectedDatePublished { t.Fatal("mercury.Parse(): incorrect DatePublished") } if infos.ImageURL != testExpectedImageURL { t.Fatal("mercury.Parse(): incorrect ImageURL") } if infos.TotalPages != testExpectedTotalPages { t.Fatal("mercury.Parse(): incorrect title") } if infos.Direction != testExpectedDirection { t.Fatal("mercury.Parse(): incorrect title") } if infos.WordCount != testExpectedWordCount { t.Fatal("mercury.Parse(): incorrect title") } }
init
system.go
package sdk import "github.com/convox/rack/structs" func (c *Client) SystemGet() (*structs.System, error) { var s structs.System if err := c.Get("/system", RequestOptions{}, &s); err != nil
return &s, nil }
{ return nil, err }
__init__.py
# Copyright 2012 OpenStack Foundation # # 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
# License for the specific language governing permissions and limitations # under the License. from keystone.contrib.stats.core import * # noqa
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
GameLauncher.py
# Replace "Keeper" with game file name. Ex: if your game file is called MyGame.Py, Write MyGame instead of Keeper from \ Keeper \ import * from OpenGL.GLUT import * # Setup Variables screenwidth = 800 screenheight = 800 gameTitle = b"BEKA Engine" def Timer(v):
def main(): glutInit() # Initialize Glut Features glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA) # Initialize Window Options glutInitWindowSize(screenwidth, screenheight) glutCreateWindow(gameTitle) glutPassiveMotionFunc(PassiveMotionFunc) # Mouse Functions Enable glutMotionFunc(MotionFunc) # Mouse Functions Enable glutMouseFunc(MouseMotion) # Mouse Functions Enable glutKeyboardFunc(keyboard) # Keyboard Functions Enable glutSpecialFunc(arrow_key) # Keyboard Functions Enable glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # Blend glEnable(GL_BLEND) init() # First fn in Keeper.py which imports sprites and instantiate objects glutTimerFunc(time_interval, Timer, 1) # Loop Along glutDisplayFunc(Update) glutMainLoop() main()
Update() glutTimerFunc(time_interval, Timer, 1)
ExtractCameraPose.py
import numpy as np import sys sys.dont_write_bytecode = True def ExtractCameraPose(E, K):
U, S, V_T = np.linalg.svd(E) W = np.array([[0, -1, 0], [1, 0, 0], [0, 0, 1]]) # print("E svd U", U) # print("E svd S", S) # print("E svd U[:, 2]", U[:, 2]) R = [] C = [] R.append(np.dot(U, np.dot(W, V_T))) R.append(np.dot(U, np.dot(W, V_T))) R.append(np.dot(U, np.dot(W.T, V_T))) R.append(np.dot(U, np.dot(W.T, V_T))) C.append(U[:, 2]) C.append(-U[:, 2]) C.append(U[:, 2]) C.append(-U[:, 2]) for i in range(4): if (np.linalg.det(R[i]) < 0): R[i] = -R[i] C[i] = -C[i] return R, C
k_sinf.rs
/* origin: FreeBSD /usr/src/lib/msun/src/k_sinf.c */ /* * Conversion to float by Ian Lance Taylor, Cygnus Support, [email protected]. * Optimized by Bruce D. Evans. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ /* |sin(x)/x - s(x)| < 2**-37.5 (~[-4.89e-12, 4.824e-12]). */ const S1: f64 = -0.166666666416265235595; /* -0x15555554cbac77.0p-55 */ const S2: f64 = 0.0083333293858894631756; /* 0x111110896efbb2.0p-59 */ const S3: f64 = -0.000198393348360966317347; /* -0x1a00f9e2cae774.0p-65 */ const S4: f64 = 0.0000027183114939898219064; /* 0x16cd878c3b46a7.0p-71 */ #[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub(crate) const fn
(x: f64) -> f32 { let z = x * x; let w = z * z; let r = S3 + z * S4; let s = z * x; ((x + s * (S1 + z * S2)) + s * w * r) as f32 }
k_sinf
stackinstall_test.go
/* Copyright 2019 The Crossplane 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 install import ( "context" "testing" "time" "github.com/google/go-cmp/cmp" "github.com/pkg/errors" corev1 "k8s.io/api/core/v1" kerrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" runtimev1alpha1 "github.com/crossplaneio/crossplane-runtime/apis/core/v1alpha1" "github.com/crossplaneio/crossplane-runtime/pkg/test" stacksapi "github.com/crossplaneio/crossplane/apis/stacks" "github.com/crossplaneio/crossplane/apis/stacks/v1alpha1" "github.com/crossplaneio/crossplane/pkg/stacks" ) const ( namespace = "cool-namespace" uidString = "definitely-a-uuid" uid = types.UID(uidString) resourceName = "cool-stackinstall" stackPackageImage = "cool/stack-package:rad" ) var ( ctx = context.Background() errBoom = errors.New("boom") ) func init() { _ = stacksapi.AddToScheme(scheme.Scheme) } // Test that our Reconciler implementation satisfies the Reconciler interface. var _ reconcile.Reconciler = &Reconciler{} // Resource modifiers type resourceModifier func(v1alpha1.StackInstaller) func withFinalizers(finalizers ...string) resourceModifier { return func(r v1alpha1.StackInstaller) { r.SetFinalizers(finalizers) } } func withConditions(c ...runtimev1alpha1.Condition) resourceModifier { return func(r v1alpha1.StackInstaller) { r.SetConditions(c...) } } func withDeletionTimestamp(t time.Time) resourceModifier { return func(r v1alpha1.StackInstaller) { r.SetDeletionTimestamp(&metav1.Time{Time: t}) } } func withInstallJob(jobRef *corev1.ObjectReference) resourceModifier { return func(r v1alpha1.StackInstaller) { r.SetInstallJob(jobRef) } } func withStackRecord(stackRecord *corev1.ObjectReference) resourceModifier { return func(r v1alpha1.StackInstaller) { r.SetStackRecord(stackRecord) } } func resource(rm ...resourceModifier) *v1alpha1.StackInstall { r := &v1alpha1.StackInstall{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, Name: resourceName, UID: uid, Finalizers: []string{}, }, Spec: v1alpha1.StackInstallSpec{}, } for _, m := range rm { m(r) } return r } func
(rm ...resourceModifier) *v1alpha1.ClusterStackInstall { r := &v1alpha1.ClusterStackInstall{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, Name: resourceName, UID: uid, Finalizers: []string{}, }, Spec: v1alpha1.StackInstallSpec{}, } for _, m := range rm { m(r) } return r } // mock implementations type mockFactory struct { MockNewHandler func(context.Context, v1alpha1.StackInstaller, client.Client, kubernetes.Interface, *stacks.ExecutorInfo) handler } func (f *mockFactory) newHandler(ctx context.Context, i v1alpha1.StackInstaller, kube client.Client, kubeclient kubernetes.Interface, ei *stacks.ExecutorInfo) handler { return f.MockNewHandler(ctx, i, kube, kubeclient, ei) } type mockHandler struct { MockSync func(context.Context) (reconcile.Result, error) MockCreate func(context.Context) (reconcile.Result, error) MockUpdate func(context.Context) (reconcile.Result, error) MockDelete func(context.Context) (reconcile.Result, error) } func (m *mockHandler) sync(ctx context.Context) (reconcile.Result, error) { return m.MockSync(ctx) } func (m *mockHandler) create(ctx context.Context) (reconcile.Result, error) { return m.MockCreate(ctx) } func (m *mockHandler) update(ctx context.Context) (reconcile.Result, error) { return m.MockUpdate(ctx) } func (m *mockHandler) delete(ctx context.Context) (reconcile.Result, error) { return m.MockDelete(ctx) } type mockExecutorInfoDiscoverer struct { MockDiscoverExecutorInfo func(ctx context.Context) (*stacks.ExecutorInfo, error) } func (m *mockExecutorInfoDiscoverer) Discover(ctx context.Context) (*stacks.ExecutorInfo, error) { return m.MockDiscoverExecutorInfo(ctx) } func TestReconcile(t *testing.T) { type want struct { result reconcile.Result err error } tests := []struct { name string req reconcile.Request rec *Reconciler want want }{ { name: "SuccessfulSyncStackInstall", req: reconcile.Request{NamespacedName: types.NamespacedName{Name: resourceName, Namespace: namespace}}, rec: &Reconciler{ kube: &test.MockClient{ MockGet: func(ctx context.Context, key client.ObjectKey, obj runtime.Object) error { *obj.(*v1alpha1.StackInstall) = *(resource()) return nil }, }, stackinator: func() v1alpha1.StackInstaller { return &v1alpha1.StackInstall{} }, executorInfoDiscoverer: &mockExecutorInfoDiscoverer{ MockDiscoverExecutorInfo: func(ctx context.Context) (*stacks.ExecutorInfo, error) { return &stacks.ExecutorInfo{Image: stackPackageImage}, nil }, }, factory: &mockFactory{ MockNewHandler: func(context.Context, v1alpha1.StackInstaller, client.Client, kubernetes.Interface, *stacks.ExecutorInfo) handler { return &mockHandler{ MockSync: func(context.Context) (reconcile.Result, error) { return reconcile.Result{}, nil }, } }, }, }, want: want{result: reconcile.Result{}, err: nil}, }, { name: "SuccessfulSyncClusterStackInstall", req: reconcile.Request{NamespacedName: types.NamespacedName{Name: resourceName, Namespace: namespace}}, rec: &Reconciler{ kube: &test.MockClient{ MockGet: func(ctx context.Context, key client.ObjectKey, obj runtime.Object) error { *obj.(*v1alpha1.ClusterStackInstall) = *(clusterInstallResource()) return nil }, }, stackinator: func() v1alpha1.StackInstaller { return &v1alpha1.ClusterStackInstall{} }, executorInfoDiscoverer: &mockExecutorInfoDiscoverer{ MockDiscoverExecutorInfo: func(ctx context.Context) (*stacks.ExecutorInfo, error) { return &stacks.ExecutorInfo{Image: stackPackageImage}, nil }, }, factory: &mockFactory{ MockNewHandler: func(context.Context, v1alpha1.StackInstaller, client.Client, kubernetes.Interface, *stacks.ExecutorInfo) handler { return &mockHandler{ MockSync: func(context.Context) (reconcile.Result, error) { return reconcile.Result{}, nil }, } }, }, }, want: want{result: reconcile.Result{}, err: nil}, }, { name: "SuccessfulDelete", req: reconcile.Request{NamespacedName: types.NamespacedName{Name: resourceName, Namespace: namespace}}, rec: &Reconciler{ kube: &test.MockClient{ MockGet: func(ctx context.Context, key client.ObjectKey, obj runtime.Object) error { *obj.(*v1alpha1.StackInstall) = *(resource(withDeletionTimestamp(time.Now()))) return nil }, }, stackinator: func() v1alpha1.StackInstaller { return &v1alpha1.StackInstall{} }, executorInfoDiscoverer: &mockExecutorInfoDiscoverer{ MockDiscoverExecutorInfo: func(ctx context.Context) (*stacks.ExecutorInfo, error) { return &stacks.ExecutorInfo{Image: stackPackageImage}, nil }, }, factory: &mockFactory{ MockNewHandler: func(context.Context, v1alpha1.StackInstaller, client.Client, kubernetes.Interface, *stacks.ExecutorInfo) handler { return &mockHandler{ MockDelete: func(context.Context) (reconcile.Result, error) { return reconcile.Result{}, nil }, } }, }, }, want: want{result: reconcile.Result{}, err: nil}, }, { name: "DiscoverExecutorInfoFailed", req: reconcile.Request{NamespacedName: types.NamespacedName{Name: resourceName, Namespace: namespace}}, rec: &Reconciler{ kube: &test.MockClient{ MockGet: func(ctx context.Context, key client.ObjectKey, obj runtime.Object) error { *obj.(*v1alpha1.StackInstall) = *(resource()) return nil }, MockStatusUpdate: func(ctx context.Context, obj runtime.Object, _ ...client.UpdateOption) error { return nil }, }, stackinator: func() v1alpha1.StackInstaller { return &v1alpha1.StackInstall{} }, executorInfoDiscoverer: &mockExecutorInfoDiscoverer{ MockDiscoverExecutorInfo: func(ctx context.Context) (*stacks.ExecutorInfo, error) { return nil, errors.New("test-discover-executorInfo-error") }, }, factory: nil, }, want: want{result: resultRequeue, err: nil}, }, { name: "ResourceNotFound", req: reconcile.Request{NamespacedName: types.NamespacedName{Name: resourceName, Namespace: namespace}}, rec: &Reconciler{ kube: &test.MockClient{ MockGet: func(ctx context.Context, key client.ObjectKey, obj runtime.Object) error { return kerrors.NewNotFound(schema.GroupResource{Group: v1alpha1.Group}, key.Name) }, }, stackinator: func() v1alpha1.StackInstaller { return &v1alpha1.StackInstall{} }, executorInfoDiscoverer: nil, factory: nil, }, want: want{result: reconcile.Result{}, err: nil}, }, { name: "ResourceGetError", req: reconcile.Request{NamespacedName: types.NamespacedName{Name: resourceName, Namespace: namespace}}, rec: &Reconciler{ kube: &test.MockClient{ MockGet: func(ctx context.Context, key client.ObjectKey, obj runtime.Object) error { return errors.New("test-get-error") }, }, stackinator: func() v1alpha1.StackInstaller { return &v1alpha1.StackInstall{} }, executorInfoDiscoverer: nil, factory: nil, }, want: want{result: reconcile.Result{}, err: errors.New("test-get-error")}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotResult, gotErr := tt.rec.Reconcile(tt.req) if diff := cmp.Diff(tt.want.err, gotErr, test.EquateErrors()); diff != "" { t.Errorf("Reconcile() -want error, +got error:\n%s", diff) } if diff := cmp.Diff(tt.want.result, gotResult); diff != "" { t.Errorf("Reconcile() -want, +got:\n%v", diff) } }) } } // TestStackInstallDelete tests the delete function of the stack install handler func TestStackInstallDelete(t *testing.T) { tn := time.Now() type want struct { result reconcile.Result err error si *v1alpha1.StackInstall } tests := []struct { name string handler *stackInstallHandler want want }{ { name: "FailList", handler: &stackInstallHandler{ // stack install starts with a finalizer and a deletion timestamp ext: resource(withFinalizers(installFinalizer), withDeletionTimestamp(tn)), kube: &test.MockClient{ MockList: func(ctx context.Context, list runtime.Object, opts ...client.ListOption) error { return errBoom }, MockDeleteAllOf: func(ctx context.Context, obj runtime.Object, opts ...client.DeleteAllOfOption) error { return nil }, MockUpdate: func(ctx context.Context, obj runtime.Object, opts ...client.UpdateOption) error { return nil }, MockStatusUpdate: func(ctx context.Context, obj runtime.Object, _ ...client.UpdateOption) error { return nil }, }, }, want: want{ result: resultRequeue, err: nil, si: resource( withFinalizers(installFinalizer), withDeletionTimestamp(tn), withConditions(runtimev1alpha1.ReconcileError(errBoom))), }, }, { name: "FailDeleteAllOf", handler: &stackInstallHandler{ // stack install starts with a finalizer and a deletion timestamp ext: resource(withFinalizers(installFinalizer), withDeletionTimestamp(tn)), kube: &test.MockClient{ MockList: func(ctx context.Context, list runtime.Object, opts ...client.ListOption) error { // set the list's items to a fake list of CRDs to delete list.(*v1alpha1.StackList).Items = []v1alpha1.Stack{} return nil }, MockDeleteAllOf: func(ctx context.Context, obj runtime.Object, opts ...client.DeleteAllOfOption) error { return errBoom }, MockUpdate: func(ctx context.Context, obj runtime.Object, opts ...client.UpdateOption) error { return nil }, MockStatusUpdate: func(ctx context.Context, obj runtime.Object, _ ...client.UpdateOption) error { return nil }, }, }, want: want{ result: resultRequeue, err: nil, si: resource( withFinalizers(installFinalizer), withDeletionTimestamp(tn), withConditions(runtimev1alpha1.ReconcileError(errBoom))), }, }, { name: "FailUpdate", handler: &stackInstallHandler{ // stack install starts with a finalizer and a deletion timestamp ext: resource(withFinalizers(installFinalizer), withDeletionTimestamp(tn)), kube: &test.MockClient{ MockList: func(ctx context.Context, list runtime.Object, opts ...client.ListOption) error { // set the list's items to a fake list of CRDs to delete list.(*v1alpha1.StackList).Items = []v1alpha1.Stack{} return nil }, MockDeleteAllOf: func(ctx context.Context, obj runtime.Object, opts ...client.DeleteAllOfOption) error { return nil }, MockDelete: func(ctx context.Context, obj runtime.Object, opts ...client.DeleteOption) error { return nil }, MockUpdate: func(ctx context.Context, obj runtime.Object, opts ...client.UpdateOption) error { return errBoom }, MockStatusUpdate: func(ctx context.Context, obj runtime.Object, _ ...client.UpdateOption) error { return nil }, }, }, want: want{ result: resultRequeue, err: nil, si: resource( // the finalizer will have been removed from our test object at least in memory // (even though the update call to the API server failed) withDeletionTimestamp(tn), withConditions(runtimev1alpha1.ReconcileError(errBoom))), }, }, { name: "RetryWhenStackExists", handler: &stackInstallHandler{ // stack install starts with a finalizer and a deletion timestamp ext: resource(withFinalizers(installFinalizer), withDeletionTimestamp(tn)), kube: &test.MockClient{ MockList: func(ctx context.Context, list runtime.Object, opts ...client.ListOption) error { // set the list's items to a fake list of CRDs to delete list.(*v1alpha1.StackList).Items = []v1alpha1.Stack{ {}, } return nil }, MockDeleteAllOf: func(ctx context.Context, obj runtime.Object, opts ...client.DeleteAllOfOption) error { return nil }, MockDelete: func(ctx context.Context, obj runtime.Object, opts ...client.DeleteOption) error { return nil }, MockUpdate: func(ctx context.Context, obj runtime.Object, opts ...client.UpdateOption) error { return errBoom }, MockStatusUpdate: func(ctx context.Context, obj runtime.Object, _ ...client.UpdateOption) error { return nil }, }, }, want: want{ result: resultRequeue, err: nil, si: resource( // the finalizer will have been removed from our test object at least in memory // (even though the update call to the API server failed) withDeletionTimestamp(tn), withFinalizers("finalizer.stackinstall.crossplane.io"), withConditions(runtimev1alpha1.ReconcileError(errors.New("Stack resources have not been deleted")))), }, }, { name: "SuccessfulDelete", handler: &stackInstallHandler{ // stack install starts with a finalizer and a deletion timestamp ext: resource(withFinalizers(installFinalizer), withDeletionTimestamp(tn)), kube: &test.MockClient{ MockList: func(ctx context.Context, list runtime.Object, opts ...client.ListOption) error { // set the list's items to a fake list of CRDs to delete list.(*v1alpha1.StackList).Items = []v1alpha1.Stack{} return nil }, MockDeleteAllOf: func(ctx context.Context, obj runtime.Object, opts ...client.DeleteAllOfOption) error { return nil }, MockDelete: func(ctx context.Context, obj runtime.Object, opts ...client.DeleteOption) error { return nil }, MockUpdate: func(ctx context.Context, obj runtime.Object, opts ...client.UpdateOption) error { return nil }, }, }, want: want{ result: reconcile.Result{}, err: nil, si: resource(withDeletionTimestamp(tn)), // finalizers get removed by delete function }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotResult, gotErr := tt.handler.delete(ctx) if diff := cmp.Diff(tt.want.err, gotErr, test.EquateErrors()); diff != "" { t.Errorf("delete() -want error, +got error:\n%s", diff) } if diff := cmp.Diff(tt.want.result, gotResult); diff != "" { t.Errorf("delete() -want result, +got result:\n%v", diff) } if diff := cmp.Diff(tt.want.si, tt.handler.ext, test.EquateConditions()); diff != "" { t.Errorf("delete() -want stackInstall, +got stackInstall:\n%v", diff) } }) } } func TestHandlerFactory(t *testing.T) { tests := []struct { name string factory factory want handler }{ { name: "SimpleCreate", factory: &handlerFactory{}, want: &stackInstallHandler{ kube: nil, jobCompleter: &stackInstallJobCompleter{client: nil, podLogReader: &K8sReader{Client: nil}}, executorInfo: &stacks.ExecutorInfo{Image: stackPackageImage}, ext: resource(), }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := tt.factory.newHandler(ctx, resource(), nil, nil, &stacks.ExecutorInfo{Image: stackPackageImage}) diff := cmp.Diff(tt.want, got, cmp.AllowUnexported( stackInstallHandler{}, stackInstallJobCompleter{}, K8sReader{}, )) if diff != "" { t.Errorf("newHandler() -want, +got:\n%v", diff) } }) } }
clusterInstallResource
util.rs
// Copyright Materialize, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License in the LICENSE file at the // root of this repository, or online 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 std::mem::{self, MaybeUninit}; pub fn unwrap_err<T, E>(res: Result<T, E>) -> E { match res { Ok(_) => panic!("Result was unexpectedly Ok"), Err(e) => e, } } /// Copies the elements from `src` to `this`, returning a mutable reference to /// the now initialized contents of `this`. /// /// This is a forward port of an unstable API. /// See: https://github.com/rust-lang/rust/issues/79995 pub fn copy_to_uninit_slice<'a, T>(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T] where T: Copy,
{ // SAFETY: &[T] and &[MaybeUninit<T>] have the same layout. let uninit_src: &[MaybeUninit<T>] = unsafe { mem::transmute(src) }; this.copy_from_slice(uninit_src); // SAFETY: Valid elements have just been copied into `this` so it is // initialized. unsafe { &mut *(this as *mut [MaybeUninit<T>] as *mut [T]) } }
zz_generated.test_data.go
/** * Copyright 2021 Rafael Fernández López <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.
**/ package constants // Code auto-generated. DO NOT EDIT. const ( // RawTestData represents the supported versions for this release RawTestData = `"containerdVersions": - "cniPluginsVersion": "0.8.6" "criToolsVersion": "1.18.0" "version": "1.3.4" "kubernetesVersions": "1.15.12": "containerdVersion": "1.3.4" "pauseVersion": "3.1" "1.16.15": "containerdVersion": "1.3.4" "pauseVersion": "3.1" "1.17.17": "containerdVersion": "1.3.4" "pauseVersion": "3.1" "1.18.18": "containerdVersion": "1.3.4" "pauseVersion": "3.1" "1.19.10": "containerdVersion": "1.3.4" "pauseVersion": "3.1" "1.20.6": "containerdVersion": "1.3.4" "pauseVersion": "3.1" "1.21.0": "containerdVersion": "1.3.4" "pauseVersion": "3.1" ` )
macosxauth.py
# -*- coding: utf-8 -*- """Authentication of Mac OS X users Currently uses shell commands to do lookup, should probably be rewritten to use PAM and/or PyObjC. """ import re import logging import pexpect from repoze.what.adapters import BaseSourceAdapter, SourceError __all__ = ['MacOSXAuthenticator', 'MacOSXMetadataProvider', 'MacOSXGroupAdapter'] # Get a logger. log = logging.getLogger(__name__.split(".")[0]) # allow something resembling unix userids, and common email addresses valid_userid = re.compile(r'^[a-zA-Z][a-zA-Z0-9@.\-_]{1,63}$') def get_output(argv): # Spawn a shell command and return all output, or None if there is an # error. if len(argv) == 1: cmd = pexpect.spawn(argv[0]) else: cmd = pexpect.spawn(argv[0], argv[1:]) # Read output. output = cmd.read() # Close the program. cmd.close() # Force close if it doesn't shutdown nicely. if cmd.isalive(): cmd.close(force=True) # If the command exited abnormally we abort. if cmd.signalstatus: log.debug("%s died with signal %d" % (argv[0], cmd.signalstatus)) return None # An exit status different from 0 means the command failed. if cmd.exitstatus != 0: log.debug("%s failed with exit status %d" % (argv[0], cmd.exitstatus)) return None # Return output. return output class MacOSXAuthenticator(object): """Authenticate Mac OS X users with dscl /Search -authonly.""" def authenticate(self, environ, identity): # Read userid and password. try: userid = identity["login"] password = identity["password"] except KeyError: return None # Make sure the userid doesn't contain funny characters. if not valid_userid.match(userid): log.info("MacOSXAuthenticator failed with invalid userid") return None # Verify userid and password with dscl. dscl_cmd = pexpect.spawn("/usr/bin/dscl", ["/Search", "-authonly", userid]) # Wait for the password prompt. dscl_cmd.waitnoecho() # Send the password. dscl_cmd.sendline(password) # Flush output. dscl_cmd.read() # Close the program. dscl_cmd.close() # Force close if it doesn't shutdown nicely. if dscl_cmd.isalive(): dscl_cmd.close(force=True) # If dscl exited abnormally authorization failed. if dscl_cmd.signalstatus: log.info("MacOSXAuthenticator failed for %s as dscl exited with status %s" % (userid, str(dscl_cmd.signalstatus))) return None # An exit status different from 0 means authorization failed. if dscl_cmd.exitstatus != 0: log.info("MacOSXAuthenticator failed for %s" % (userid)) return None # Success, return userid. log.info("MacOSXAuthenticator successfully authenticated %s" % userid)
class MacOSXMetadataProvider(object): """Provide metadata for Mac OS X users.""" metadata = {} def add_metadata(self, environ, identity): # Read userid. userid = identity.get("repoze.who.userid") # Make sure the userid doesn't contain funny characters. if not valid_userid.match(userid): return if userid in self.metadata: log.debug("Returning cached metadata for %s: %s" % (userid, repr(self.metadata[userid]))) identity.update(self.metadata[userid]) return self.metadata[userid] = {} log.debug("spawning dscl for %s" % userid) # Read display_name with dscl. dscl_cmd = pexpect.spawn("/usr/bin/dscl", ["/Search", "-read", "/Users/%s" % userid, "RealName"]) # Read output. realname_output = dscl_cmd.read().decode("utf-8") # Close the program. dscl_cmd.close() # Force close if it doesn't shutdown nicely. if dscl_cmd.isalive(): dscl_cmd.close(force=True) # If dscl exited abnormally we abort. if dscl_cmd.signalstatus: log.debug("dscl died for %s" % userid) return # An exit status different from 0 means the record couldn't re read. if dscl_cmd.exitstatus != 0: log.debug("RealName lookup with dscl failed for %s" % userid) return # If output doesn't match what we expect we abort. if not realname_output.startswith("RealName:"): log.debug("RealName lookup for %s returned unexpected result" % userid) return realname = realname_output.replace("RealName:", "").strip() log.debug("dscl returned RealName for %s: %s" % (userid, repr(realname))) self.metadata[userid]["display_name"] = realname identity.update({"display_name": realname}) class MacOSXGroupAdapter(BaseSourceAdapter): def __init__(self): self.groups = None super(MacOSXGroupAdapter, self).__init__(writable=False) def _get_all_sections(self): log.debug("spawning dscl to list all groups") dscl_output = get_output(["/usr/bin/dscl", "/Search", "-list", "/Groups"]) if dscl_output is None: raise SourceError("Couldn't list groups with dscl") self.groups = dict([(group, None) for group in dscl_output.strip().split()]) log.debug("dscl found %d groups" % len(self.groups)) return self.groups def _get_section_items(self, section): log.debug("spawning dscl to get members of %s" % section) dscl_output = get_output(["/usr/bin/dscl", "/Search", "-read", "/Groups/%s" % section, "GroupMembership"]) if dscl_output is None: raise SourceError("Couldn't read members of group %s with dscl" % section) if not dscl_output.startswith("GroupMembership:"): raise SourceError("Unexpected output when reading group members of %s with dscl" % section) return set(dscl_output.replace("GroupMembership:", "").strip().split()) def _find_sections(self, credentials): log.debug("finding sections for credentials %s" % repr(credentials)) userid = credentials['repoze.what.userid'] log.debug("spawning id to read groups for %s" % userid) # Read group membership with id -Gn <username> group_output = get_output(["/usr/bin/id", "-Gn", userid]) if group_output is None: return set() #raise SourceError("Couldn't read group membership for %s with id" % userid) groups = group_output.strip().split() log.debug("id returned groups for %s: %s" % (userid, repr(groups))) return set(groups) def _item_is_included(self, section, item): return item in self._get_section_items(section) def _section_exists(self, section): if self.groups is not None: return self.groups.has_key(section) else: self._get_all_sections() return self.groups.has_key(section) if __name__ == '__main__': import sys g = MacOSXGroupAdapter() print repr(g._section_exists("admin")) print repr(g._get_section_items("admin")) sys.exit(0) import getpass a = MacOSXAuthenticator() md = MacOSXMetadataProvider() username = raw_input("Username: ") password = getpass.getpass() userid = a.authenticate({}, {"login": username, "password": password}) if userid is None: sys.stderr.write("Authentication failed\n") sys.exit(1) identity = {"repoze.who.userid": userid} md.add_metadata({}, identity) print "Metadata for %s:" % userid, repr(identity) sys.exit(0) print "Authenticating chuck with norris" print "Result:", repr(a.authenticate({}, {"login": u"chuck", "password": u"norris"})) print "Authenticating chuck with hejsan" print "Result:", repr(a.authenticate({}, {"login": u"chuck", "password": u"hejsan"})) print "Authenticating authtest with hejsan99" print "Result:", repr(a.authenticate({}, {"login": u"authtest", "password": u"hejsan99"})) print "Getting metadata for chuck" identity = {"repoze.who.userid": "chuck"} md.add_metadata({}, identity) print "Result:", repr(identity) print "Getting metadata for authtest" identity = {"repoze.who.userid": "authtest"} md.add_metadata({}, identity) print "Result:", repr(identity)
return userid
analyticsApplication.go
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package kinesis import ( "context" "reflect" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" ) // Provides a Kinesis Analytics Application resource. Kinesis Analytics is a managed service that // allows processing and analyzing streaming data using standard SQL. // // For more details, see the [Amazon Kinesis Analytics Documentation](https://docs.aws.amazon.com/kinesisanalytics/latest/dev/what-is.html). // // > **Note:** To manage Amazon Kinesis Data Analytics for Apache Flink applications, use the `kinesisanalyticsv2.Application` resource. // // ## Example Usage // ### Kinesis Stream Input // // ```go // package main // // import ( // "fmt" // // "github.com/pulumi/pulumi-aws/sdk/v5/go/aws/kinesis" // "github.com/pulumi/pulumi/sdk/v3/go/pulumi" // ) // // func main() { // pulumi.Run(func(ctx *pulumi.Context) error { // testStream, err := kinesis.NewStream(ctx, "testStream", &kinesis.StreamArgs{ // ShardCount: pulumi.Int(1), // }) // if err != nil { // return err // } // _, err = kinesis.NewAnalyticsApplication(ctx, "testApplication", &kinesis.AnalyticsApplicationArgs{ // Inputs: &kinesis.AnalyticsApplicationInputsArgs{ // NamePrefix: pulumi.String("test_prefix"), // KinesisStream: &kinesis.AnalyticsApplicationInputsKinesisStreamArgs{ // ResourceArn: testStream.Arn, // RoleArn: pulumi.Any(aws_iam_role.Test.Arn), // }, // Parallelism: &kinesis.AnalyticsApplicationInputsParallelismArgs{ // Count: pulumi.Int(1), // }, // Schema: &kinesis.AnalyticsApplicationInputsSchemaArgs{ // RecordColumns: kinesis.AnalyticsApplicationInputsSchemaRecordColumnArray{ // &kinesis.AnalyticsApplicationInputsSchemaRecordColumnArgs{ // Mapping: pulumi.String(fmt.Sprintf("%v%v", "$", ".test")), // Name: pulumi.String("test"), // SqlType: pulumi.String("VARCHAR(8)"), // }, // }, // RecordEncoding: pulumi.String("UTF-8"), // RecordFormat: &kinesis.AnalyticsApplicationInputsSchemaRecordFormatArgs{ // MappingParameters: &kinesis.AnalyticsApplicationInputsSchemaRecordFormatMappingParametersArgs{ // Json: &kinesis.AnalyticsApplicationInputsSchemaRecordFormatMappingParametersJsonArgs{ // RecordRowPath: pulumi.String("$"), // }, // }, // }, // }, // }, // }) // if err != nil { // return err // } // return nil // }) // } // ``` // ### Starting An Application // // ```go // package main // // import ( // "github.com/pulumi/pulumi-aws/sdk/v5/go/aws/cloudwatch" // "github.com/pulumi/pulumi-aws/sdk/v5/go/aws/kinesis" // "github.com/pulumi/pulumi/sdk/v3/go/pulumi" // ) // // func main() { // pulumi.Run(func(ctx *pulumi.Context) error { // exampleLogGroup, err := cloudwatch.NewLogGroup(ctx, "exampleLogGroup", nil) // if err != nil { // return err // } // exampleLogStream, err := cloudwatch.NewLogStream(ctx, "exampleLogStream", &cloudwatch.LogStreamArgs{ // LogGroupName: exampleLogGroup.Name, // }) // if err != nil { // return err // } // exampleStream, err := kinesis.NewStream(ctx, "exampleStream", &kinesis.StreamArgs{ // ShardCount: pulumi.Int(1), // }) // if err != nil { // return err // } // exampleFirehoseDeliveryStream, err := kinesis.NewFirehoseDeliveryStream(ctx, "exampleFirehoseDeliveryStream", &kinesis.FirehoseDeliveryStreamArgs{ // Destination: pulumi.String("extended_s3"), // ExtendedS3Configuration: &kinesis.FirehoseDeliveryStreamExtendedS3ConfigurationArgs{ // BucketArn: pulumi.Any(aws_s3_bucket.Example.Arn), // RoleArn: pulumi.Any(aws_iam_role.Example.Arn), // }, // }) // if err != nil { // return err // } // _, err = kinesis.NewAnalyticsApplication(ctx, "test", &kinesis.AnalyticsApplicationArgs{ // CloudwatchLoggingOptions: &kinesis.AnalyticsApplicationCloudwatchLoggingOptionsArgs{ // LogStreamArn: exampleLogStream.Arn, // RoleArn: pulumi.Any(aws_iam_role.Example.Arn), // }, // Inputs: &kinesis.AnalyticsApplicationInputsArgs{ // NamePrefix: pulumi.String("example_prefix"), // Schema: &kinesis.AnalyticsApplicationInputsSchemaArgs{ // RecordColumns: kinesis.AnalyticsApplicationInputsSchemaRecordColumnArray{ // &kinesis.AnalyticsApplicationInputsSchemaRecordColumnArgs{ // Name: pulumi.String("COLUMN_1"), // SqlType: pulumi.String("INTEGER"), // }, // }, // RecordFormat: &kinesis.AnalyticsApplicationInputsSchemaRecordFormatArgs{ // MappingParameters: &kinesis.AnalyticsApplicationInputsSchemaRecordFormatMappingParametersArgs{ // Csv: &kinesis.AnalyticsApplicationInputsSchemaRecordFormatMappingParametersCsvArgs{ // RecordColumnDelimiter: pulumi.String(","), // RecordRowDelimiter: pulumi.String("|"), // }, // }, // }, // }, // KinesisStream: &kinesis.AnalyticsApplicationInputsKinesisStreamArgs{ // ResourceArn: exampleStream.Arn, // RoleArn: pulumi.Any(aws_iam_role.Example.Arn), // }, // StartingPositionConfigurations: kinesis.AnalyticsApplicationInputsStartingPositionConfigurationArray{ // &kinesis.AnalyticsApplicationInputsStartingPositionConfigurationArgs{ // StartingPosition: pulumi.String("NOW"), // }, // }, // }, // Outputs: kinesis.AnalyticsApplicationOutputArray{ // kinesis.AnalyticsApplicationOutputArgs{ // Name: pulumi.String("OUTPUT_1"), // Schema: &kinesis.AnalyticsApplicationOutputSchemaArgs{ // RecordFormatType: pulumi.String("CSV"), // }, // KinesisFirehose: &kinesis.AnalyticsApplicationOutputKinesisFirehoseArgs{ // ResourceArn: exampleFirehoseDeliveryStream.Arn, // RoleArn: pulumi.Any(aws_iam_role.Example.Arn), // }, // }, // }, // StartApplication: pulumi.Bool(true), // }) // if err != nil { // return err // } // return nil // }) // } // ``` // // ## Import // // Kinesis Analytics Application can be imported by using ARN, e.g., // // ```sh // $ pulumi import aws:kinesis/analyticsApplication:AnalyticsApplication example arn:aws:kinesisanalytics:us-west-2:1234567890:application/example // ``` type AnalyticsApplication struct { pulumi.CustomResourceState // The ARN of the Kinesis Analytics Appliation. Arn pulumi.StringOutput `pulumi:"arn"` // The CloudWatch log stream options to monitor application errors. // See CloudWatch Logging Options below for more details. CloudwatchLoggingOptions AnalyticsApplicationCloudwatchLoggingOptionsPtrOutput `pulumi:"cloudwatchLoggingOptions"` // SQL Code to transform input data, and generate output. Code pulumi.StringPtrOutput `pulumi:"code"` // The Timestamp when the application version was created. CreateTimestamp pulumi.StringOutput `pulumi:"createTimestamp"` // Description of the application. Description pulumi.StringPtrOutput `pulumi:"description"` // Input configuration of the application. See Inputs below for more details. Inputs AnalyticsApplicationInputsPtrOutput `pulumi:"inputs"` // The Timestamp when the application was last updated. LastUpdateTimestamp pulumi.StringOutput `pulumi:"lastUpdateTimestamp"` // Name of the Kinesis Analytics Application. Name pulumi.StringOutput `pulumi:"name"` // Output destination configuration of the application. See Outputs below for more details. Outputs AnalyticsApplicationOutputTypeArrayOutput `pulumi:"outputs"` // An S3 Reference Data Source for the application. // See Reference Data Sources below for more details. ReferenceDataSources AnalyticsApplicationReferenceDataSourcesPtrOutput `pulumi:"referenceDataSources"` // Whether to start or stop the Kinesis Analytics Application. To start an application, an input with a defined `startingPosition` must be configured. // To modify an application's starting position, first stop the application by setting `startApplication = false`, then update `startingPosition` and set `startApplication = true`. StartApplication pulumi.BoolPtrOutput `pulumi:"startApplication"` // The Status of the application. Status pulumi.StringOutput `pulumi:"status"` // Key-value map of tags for the Kinesis Analytics Application. If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. Tags pulumi.StringMapOutput `pulumi:"tags"` // A map of tags assigned to the resource, including those inherited from the provider `defaultTags` configuration block. TagsAll pulumi.StringMapOutput `pulumi:"tagsAll"` // The Version of the application. Version pulumi.IntOutput `pulumi:"version"` } // NewAnalyticsApplication registers a new resource with the given unique name, arguments, and options. func NewAnalyticsApplication(ctx *pulumi.Context, name string, args *AnalyticsApplicationArgs, opts ...pulumi.ResourceOption) (*AnalyticsApplication, error) { if args == nil { args = &AnalyticsApplicationArgs{} } var resource AnalyticsApplication err := ctx.RegisterResource("aws:kinesis/analyticsApplication:AnalyticsApplication", name, args, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // GetAnalyticsApplication gets an existing AnalyticsApplication resource's state with the given name, ID, and optional // state properties that are used to uniquely qualify the lookup (nil if not required). func GetAnalyticsApplication(ctx *pulumi.Context, name string, id pulumi.IDInput, state *AnalyticsApplicationState, opts ...pulumi.ResourceOption) (*AnalyticsApplication, error) { var resource AnalyticsApplication err := ctx.ReadResource("aws:kinesis/analyticsApplication:AnalyticsApplication", name, id, state, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // Input properties used for looking up and filtering AnalyticsApplication resources. type analyticsApplicationState struct { // The ARN of the Kinesis Analytics Appliation. Arn *string `pulumi:"arn"` // The CloudWatch log stream options to monitor application errors. // See CloudWatch Logging Options below for more details. CloudwatchLoggingOptions *AnalyticsApplicationCloudwatchLoggingOptions `pulumi:"cloudwatchLoggingOptions"` // SQL Code to transform input data, and generate output. Code *string `pulumi:"code"` // The Timestamp when the application version was created. CreateTimestamp *string `pulumi:"createTimestamp"` // Description of the application. Description *string `pulumi:"description"` // Input configuration of the application. See Inputs below for more details. Inputs *AnalyticsApplicationInputs `pulumi:"inputs"` // The Timestamp when the application was last updated. LastUpdateTimestamp *string `pulumi:"lastUpdateTimestamp"` // Name of the Kinesis Analytics Application. Name *string `pulumi:"name"` // Output destination configuration of the application. See Outputs below for more details. Outputs []AnalyticsApplicationOutputType `pulumi:"outputs"` // An S3 Reference Data Source for the application. // See Reference Data Sources below for more details. ReferenceDataSources *AnalyticsApplicationReferenceDataSources `pulumi:"referenceDataSources"` // Whether to start or stop the Kinesis Analytics Application. To start an application, an input with a defined `startingPosition` must be configured. // To modify an application's starting position, first stop the application by setting `startApplication = false`, then update `startingPosition` and set `startApplication = true`. StartApplication *bool `pulumi:"startApplication"` // The Status of the application. Status *string `pulumi:"status"` // Key-value map of tags for the Kinesis Analytics Application. If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. Tags map[string]string `pulumi:"tags"` // A map of tags assigned to the resource, including those inherited from the provider `defaultTags` configuration block. TagsAll map[string]string `pulumi:"tagsAll"` // The Version of the application. Version *int `pulumi:"version"` } type AnalyticsApplicationState struct { // The ARN of the Kinesis Analytics Appliation. Arn pulumi.StringPtrInput // The CloudWatch log stream options to monitor application errors. // See CloudWatch Logging Options below for more details. CloudwatchLoggingOptions AnalyticsApplicationCloudwatchLoggingOptionsPtrInput // SQL Code to transform input data, and generate output. Code pulumi.StringPtrInput // The Timestamp when the application version was created. CreateTimestamp pulumi.StringPtrInput // Description of the application. Description pulumi.StringPtrInput // Input configuration of the application. See Inputs below for more details. Inputs AnalyticsApplicationInputsPtrInput // The Timestamp when the application was last updated. LastUpdateTimestamp pulumi.StringPtrInput // Name of the Kinesis Analytics Application. Name pulumi.StringPtrInput // Output destination configuration of the application. See Outputs below for more details. Outputs AnalyticsApplicationOutputTypeArrayInput // An S3 Reference Data Source for the application. // See Reference Data Sources below for more details. ReferenceDataSources AnalyticsApplicationReferenceDataSourcesPtrInput // Whether to start or stop the Kinesis Analytics Application. To start an application, an input with a defined `startingPosition` must be configured. // To modify an application's starting position, first stop the application by setting `startApplication = false`, then update `startingPosition` and set `startApplication = true`. StartApplication pulumi.BoolPtrInput // The Status of the application. Status pulumi.StringPtrInput // Key-value map of tags for the Kinesis Analytics Application. If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. Tags pulumi.StringMapInput // A map of tags assigned to the resource, including those inherited from the provider `defaultTags` configuration block. TagsAll pulumi.StringMapInput // The Version of the application. Version pulumi.IntPtrInput } func (AnalyticsApplicationState) ElementType() reflect.Type { return reflect.TypeOf((*analyticsApplicationState)(nil)).Elem() } type analyticsApplicationArgs struct { // The CloudWatch log stream options to monitor application errors. // See CloudWatch Logging Options below for more details. CloudwatchLoggingOptions *AnalyticsApplicationCloudwatchLoggingOptions `pulumi:"cloudwatchLoggingOptions"` // SQL Code to transform input data, and generate output. Code *string `pulumi:"code"` // Description of the application. Description *string `pulumi:"description"` // Input configuration of the application. See Inputs below for more details. Inputs *AnalyticsApplicationInputs `pulumi:"inputs"` // Name of the Kinesis Analytics Application. Name *string `pulumi:"name"` // Output destination configuration of the application. See Outputs below for more details. Outputs []AnalyticsApplicationOutputType `pulumi:"outputs"` // An S3 Reference Data Source for the application. // See Reference Data Sources below for more details. ReferenceDataSources *AnalyticsApplicationReferenceDataSources `pulumi:"referenceDataSources"` // Whether to start or stop the Kinesis Analytics Application. To start an application, an input with a defined `startingPosition` must be configured.
StartApplication *bool `pulumi:"startApplication"` // Key-value map of tags for the Kinesis Analytics Application. If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. Tags map[string]string `pulumi:"tags"` } // The set of arguments for constructing a AnalyticsApplication resource. type AnalyticsApplicationArgs struct { // The CloudWatch log stream options to monitor application errors. // See CloudWatch Logging Options below for more details. CloudwatchLoggingOptions AnalyticsApplicationCloudwatchLoggingOptionsPtrInput // SQL Code to transform input data, and generate output. Code pulumi.StringPtrInput // Description of the application. Description pulumi.StringPtrInput // Input configuration of the application. See Inputs below for more details. Inputs AnalyticsApplicationInputsPtrInput // Name of the Kinesis Analytics Application. Name pulumi.StringPtrInput // Output destination configuration of the application. See Outputs below for more details. Outputs AnalyticsApplicationOutputTypeArrayInput // An S3 Reference Data Source for the application. // See Reference Data Sources below for more details. ReferenceDataSources AnalyticsApplicationReferenceDataSourcesPtrInput // Whether to start or stop the Kinesis Analytics Application. To start an application, an input with a defined `startingPosition` must be configured. // To modify an application's starting position, first stop the application by setting `startApplication = false`, then update `startingPosition` and set `startApplication = true`. StartApplication pulumi.BoolPtrInput // Key-value map of tags for the Kinesis Analytics Application. If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. Tags pulumi.StringMapInput } func (AnalyticsApplicationArgs) ElementType() reflect.Type { return reflect.TypeOf((*analyticsApplicationArgs)(nil)).Elem() } type AnalyticsApplicationInput interface { pulumi.Input ToAnalyticsApplicationOutput() AnalyticsApplicationOutput ToAnalyticsApplicationOutputWithContext(ctx context.Context) AnalyticsApplicationOutput } func (*AnalyticsApplication) ElementType() reflect.Type { return reflect.TypeOf((**AnalyticsApplication)(nil)).Elem() } func (i *AnalyticsApplication) ToAnalyticsApplicationOutput() AnalyticsApplicationOutput { return i.ToAnalyticsApplicationOutputWithContext(context.Background()) } func (i *AnalyticsApplication) ToAnalyticsApplicationOutputWithContext(ctx context.Context) AnalyticsApplicationOutput { return pulumi.ToOutputWithContext(ctx, i).(AnalyticsApplicationOutput) } // AnalyticsApplicationArrayInput is an input type that accepts AnalyticsApplicationArray and AnalyticsApplicationArrayOutput values. // You can construct a concrete instance of `AnalyticsApplicationArrayInput` via: // // AnalyticsApplicationArray{ AnalyticsApplicationArgs{...} } type AnalyticsApplicationArrayInput interface { pulumi.Input ToAnalyticsApplicationArrayOutput() AnalyticsApplicationArrayOutput ToAnalyticsApplicationArrayOutputWithContext(context.Context) AnalyticsApplicationArrayOutput } type AnalyticsApplicationArray []AnalyticsApplicationInput func (AnalyticsApplicationArray) ElementType() reflect.Type { return reflect.TypeOf((*[]*AnalyticsApplication)(nil)).Elem() } func (i AnalyticsApplicationArray) ToAnalyticsApplicationArrayOutput() AnalyticsApplicationArrayOutput { return i.ToAnalyticsApplicationArrayOutputWithContext(context.Background()) } func (i AnalyticsApplicationArray) ToAnalyticsApplicationArrayOutputWithContext(ctx context.Context) AnalyticsApplicationArrayOutput { return pulumi.ToOutputWithContext(ctx, i).(AnalyticsApplicationArrayOutput) } // AnalyticsApplicationMapInput is an input type that accepts AnalyticsApplicationMap and AnalyticsApplicationMapOutput values. // You can construct a concrete instance of `AnalyticsApplicationMapInput` via: // // AnalyticsApplicationMap{ "key": AnalyticsApplicationArgs{...} } type AnalyticsApplicationMapInput interface { pulumi.Input ToAnalyticsApplicationMapOutput() AnalyticsApplicationMapOutput ToAnalyticsApplicationMapOutputWithContext(context.Context) AnalyticsApplicationMapOutput } type AnalyticsApplicationMap map[string]AnalyticsApplicationInput func (AnalyticsApplicationMap) ElementType() reflect.Type { return reflect.TypeOf((*map[string]*AnalyticsApplication)(nil)).Elem() } func (i AnalyticsApplicationMap) ToAnalyticsApplicationMapOutput() AnalyticsApplicationMapOutput { return i.ToAnalyticsApplicationMapOutputWithContext(context.Background()) } func (i AnalyticsApplicationMap) ToAnalyticsApplicationMapOutputWithContext(ctx context.Context) AnalyticsApplicationMapOutput { return pulumi.ToOutputWithContext(ctx, i).(AnalyticsApplicationMapOutput) } type AnalyticsApplicationOutput struct{ *pulumi.OutputState } func (AnalyticsApplicationOutput) ElementType() reflect.Type { return reflect.TypeOf((**AnalyticsApplication)(nil)).Elem() } func (o AnalyticsApplicationOutput) ToAnalyticsApplicationOutput() AnalyticsApplicationOutput { return o } func (o AnalyticsApplicationOutput) ToAnalyticsApplicationOutputWithContext(ctx context.Context) AnalyticsApplicationOutput { return o } type AnalyticsApplicationArrayOutput struct{ *pulumi.OutputState } func (AnalyticsApplicationArrayOutput) ElementType() reflect.Type { return reflect.TypeOf((*[]*AnalyticsApplication)(nil)).Elem() } func (o AnalyticsApplicationArrayOutput) ToAnalyticsApplicationArrayOutput() AnalyticsApplicationArrayOutput { return o } func (o AnalyticsApplicationArrayOutput) ToAnalyticsApplicationArrayOutputWithContext(ctx context.Context) AnalyticsApplicationArrayOutput { return o } func (o AnalyticsApplicationArrayOutput) Index(i pulumi.IntInput) AnalyticsApplicationOutput { return pulumi.All(o, i).ApplyT(func(vs []interface{}) *AnalyticsApplication { return vs[0].([]*AnalyticsApplication)[vs[1].(int)] }).(AnalyticsApplicationOutput) } type AnalyticsApplicationMapOutput struct{ *pulumi.OutputState } func (AnalyticsApplicationMapOutput) ElementType() reflect.Type { return reflect.TypeOf((*map[string]*AnalyticsApplication)(nil)).Elem() } func (o AnalyticsApplicationMapOutput) ToAnalyticsApplicationMapOutput() AnalyticsApplicationMapOutput { return o } func (o AnalyticsApplicationMapOutput) ToAnalyticsApplicationMapOutputWithContext(ctx context.Context) AnalyticsApplicationMapOutput { return o } func (o AnalyticsApplicationMapOutput) MapIndex(k pulumi.StringInput) AnalyticsApplicationOutput { return pulumi.All(o, k).ApplyT(func(vs []interface{}) *AnalyticsApplication { return vs[0].(map[string]*AnalyticsApplication)[vs[1].(string)] }).(AnalyticsApplicationOutput) } func init() { pulumi.RegisterInputType(reflect.TypeOf((*AnalyticsApplicationInput)(nil)).Elem(), &AnalyticsApplication{}) pulumi.RegisterInputType(reflect.TypeOf((*AnalyticsApplicationArrayInput)(nil)).Elem(), AnalyticsApplicationArray{}) pulumi.RegisterInputType(reflect.TypeOf((*AnalyticsApplicationMapInput)(nil)).Elem(), AnalyticsApplicationMap{}) pulumi.RegisterOutputType(AnalyticsApplicationOutput{}) pulumi.RegisterOutputType(AnalyticsApplicationArrayOutput{}) pulumi.RegisterOutputType(AnalyticsApplicationMapOutput{}) }
// To modify an application's starting position, first stop the application by setting `startApplication = false`, then update `startingPosition` and set `startApplication = true`.
VolumeExtractChannel.py
# Name: VolumeExtractChannel import inviwopy as ivw import numpy as np class VolumeExtractChannel(ivw.Processor): def __init__(self, id, name): ivw.Processor.__init__(self, id, name) self.inport = ivw.data.VolumeInport("inport") self.addInport(self.inport, owner=False) self.outport = ivw.data.VolumeOutport("outport") self.addOutport(self.outport, owner=False) self.channel = ivw.properties.IntProperty("channel", "channel", 0, 0, 4, 1) self.addProperty(self.channel, owner=False) @staticmethod def processorInfo(): return ivw.ProcessorInfo( classIdentifier = "org.inviwo.VolumeExtractChannel", displayName = "Volume Extract Channel", category = "Volume Operation", codeState = ivw.CodeState.Stable, tags = ivw.Tags.PY ) def getProcessorInfo(self):
def process(self): volume = self.inport.getData() if len(volume.data.shape) <= 3: self.outport.setData(volume) return channels = volume.data.shape[3] volumeSlice = volume.data[:,:,:, np.clip(self.channel.value, 0, channels-1)] newVolume = ivw.data.Volume(volumeSlice) newVolume.dataMap = volume.dataMap newVolume.modelMatrix = volume.modelMatrix newVolume.worldMatrix = volume.worldMatrix newVolume.copyMetaDataFrom(volume) newVolume.swizzlemask = volume.swizzlemask newVolume.interpolation = volume.interpolation newVolume.wrapping = volume.wrapping self.outport.setData(newVolume)
return VolumeExtractChannel.processorInfo()
smaz.go
package smaz import ( "fmt" ) const codelen = 241 var codebook = [codelen]string{ "\002s,\266", "\003had\232\002leW", "\003on \216", "", "\001yS", "\002ma\255\002li\227", "\003or \260", "", "\002ll\230\003s t\277", "\004fromg\002mel", "", "\003its\332", "\001z\333", "\003ingF", "\001>\336", "\001 \000\003 (\002nc\344", "\002nd=\003 on\312", "\002ne\213\003hat\276\003re q", "", "\002ngT\003herz\004have\306\003s o\225", "", "\003ionk\003s a\254\002ly\352", "\003hisL\003 inN\003 be\252", "", "\003 fo\325\003 of \003 ha\311", "", "\002of\005", "\003 co\241\002no\267\003 ma\370", "", "", "\003 cl\356\003enta\003 an7", "\002ns\300\001\"e", "\003n t\217\002ntP\003s, \205", "\002pe\320\003 we\351\002om\223", "\002on\037", "", "\002y G", "\003 wa\271", "\003 re\321\002or*", "", "\002=\"\251\002ot\337", "\003forD\002ou[", "\003 toR", "\003 th\r", "\003 it\366", "\003but\261\002ra\202\003 wi\363\002</\361", "\003 wh\237", "\002 4", "\003nd ?", "\002re!", "", "\003ng c", "", "\003ly \307\003ass\323\001a\004\002rir", "", "", "", "\002se_", "\003of \"", "\003div\364\002ros\003ere\240", "", "\002ta\310\001bZ\002si\324", "", "\003and\a\002rs\335", "\002rt\362", "\002teE", "\003ati\316", "\002so\263", "\002th\021", "\002tiJ\001c\034\003allp", "\003ate\345", "\002ss\246", "\002stM", "", "\002><\346", "\002to\024", "\003arew", "\001d\030", "\002tr\303", "", "\001\n1\003 a \222", "\003f tv\002veo", "\002un\340", "", "\003e o\242", "\002a \243\002wa\326\001e\002", "\002ur\226\003e a\274", "\002us\244\003\n\r\n\247", "\002ut\304\003e c\373", "\002we\221", "", "", "\002wh\302", "\001f,", "", "", "", "\003d t\206", "", "", "\003th \343", "\001g;", "", "", "\001\r9\003e s\265", "\003e t\234", "", "\003to Y", "\003e\r\n\236", "\002d \036\001h\022", "", "\001,Q", "\002 a\031", "\002 b^", "\002\r\n\025\002 cI", "\002 d\245", "\002 e\253", "\002 fh\001i\b\002e \v", "", "\002 hU\001-\314", "\002 i8", "", "", "\002 l\315", "\002 m{", "\002f :\002 n\354", "\002 o\035", "\002 p}\001.n\003\r\n\r\250", "", "\002 r\275", "\002 s>", "\002 t\016", "", "\002g \235\005which+\003whi\367", "\002 w5", "\001/\305", "\003as \214", "\003at \207", "", "\003who\331", "", "\001l\026\002h \212", "", "\002, $", "", "\004withV", "", "", "", "\001m-", "", "", "\002ac\357", "\002ad\350", "\003TheH", "", "", "\004this\233\001n\t", "", "\002. y", "", "\002alX\003e, \365", "\003tio\215\002be\\", "\002an\032\003ver\347", "", "\004that0\003tha\313\001o\006", "\003was2", "\002arO", "\002as.", "\002at'\003the\001\004they\200\005there\322\005theird", "\002ce\210", "\004were]", "", "\002ch\231\002l \264\001p<", "", "", "\003one\256", "", "\003he \023\002dej", "\003ter\270", "\002cou", "", "\002by\177\002di\201\002eax", "", "\002ec\327", "\002edB", "\002ee\353", "", "", "\001r\f\002n )", "", "", "", "\002el\262", "", "\003in i\002en3", "", "\002o `\001s\n", "", "\002er\033", "\003is t\002es6", "", "\002ge\371", "\004.com\375", "\002fo\334\003our\330", "\003ch \301\001t\003", "\002hab", "", "\003men\374", "", "\002he\020", "", "", "\001u&", "\002hif", "", "\003not\204\002ic\203", "\003ed @\002id\355", "", "", "\002ho\273", "\002r K\001vm", "", "", "", "\003t t\257\002il\360", "\002im\342", "\003en \317\002in\017", "\002io\220", "\002s \027\001wA", "", "\003er |", "\003es ~\002is%", "\002it/", "", "\002iv\272", "", "\002t #\ahttp://C\001x\372", "\002la\211", "\001<\341", "\003, a\224", } var reverse = [...]string{ " ", "the", "e", "t", "a", "of", "o", "and", "i", "n", "s", "e ", "r", " th", " t", "in", "he", "th", "h", "he ", "to", "\r\n", "l", "s ", "d", " a", "an", "er", "c", " o", "d ", "on", " of", "re", "of ", "t ", ", ", "is", "u", "at", " ", "n ", "or", "which", "f", "m", "as", "it", "that", "\n", "was", "en", " ", " w", "es", " an", " i", "\r", "f ", "g", "p", "nd", " s", "nd ", "ed ", "w", "ed", "http://", "for", "te", "ing", "y ", "The", " c", "ti", "r ", "his", "st", " in", "ar", "nt", ",", " to", "y", "ng", " h", "with", "le", "al", "to ", "b", "ou", "be", "were", " b", "se", "o ", "ent", "ha", "ng ", "their", "\"", "hi", "from", " f", "in ", "de", "ion", "me", "v", ".", "ve", "all", "re ", "ri", "ro", "is ", "co", "f t", "are", "ea", ". ", "her", " m", "er ", " p", "es ", "by", "they", "di", "ra", "ic", "not", "s, ", "d t", "at ", "ce", "la", "h ", "ne", "as ", "tio", "on ", "n t", "io", "we", " a ", "om", ", a", "s o", "ur", "li", "ll", "ch", "had", "this", "e t", "g ", "e\r\n", " wh", "ere", " co", "e o", "a ", "us", " d", "ss", "\n\r\n", "\r\n\r", "=\"", " be", " e", "s a", "ma", "one", "t t", "or ", "but", "el", "so", "l ", "e s", "s,", "no", "ter", " wa", "iv", "ho", "e a", " r", "hat", "s t", "ns", "ch ", "wh", "tr", "ut", "/", "have", "ly ", "ta", " ha", " on", "tha", "-", " l", "ati", "en ", "pe", " re", "there", "ass", "si", " fo", "wa", "ec", "our", "who", "its", "z", "fo", "rs", ">", "ot", "un", "<", "im", "th ", "nc", "ate", "><", "ver", "ad", " we", "ly", "ee", " n", "id", " cl", "ac", "il", "</", "rt", " wi", "div", "e, ", " it", "whi", " ma", "ge", "x", "e c", "men", ".com", } func flushVerbatim(v, out []byte) ([]byte, []byte) { if len(v) > 1 { out = append(out, 0xff, byte(len(v)-1)) } else { out = append(out, 0xfe) } return v[:0], append(out, v...) } func Compress(in []byte) ([]byte, error) { var h1, h2, h3 uint32 var out, v []byte // verbatim for i := 0; i < len(in); { h1 = uint32(in[i]) << 3 h2 = h1 if i+1 < len(in) { h2 += uint32(in[i+1]) } if i+2 < len(in) { h3 = h2 ^ uint32(in[i+2]) } j := 7 if j > len(in)-i { j = len(in) - i } // Try to lookup substrings into the hash table, starting from the // longer to the shorter substrings var found bool var cbi int Loop: for ; j > 0; j-- { switch j { case 1: cbi = int(h1 % codelen) case 2: cbi = int(h2 % codelen) default: cbi = int(h3 % codelen) } slot, sl := codebook[cbi], 0 Next: for k := 0; k < len(slot); k += 2 + sl { sl = int(slot[k]) if sl == j { for l := 0; l < j; l++ { if i+l >= len(in) || slot[k+1+l] != in[i+l] { continue Next } } // Match found in the hash table, // prepare a verbatim bytes flush if needed if len(v) > 0 { v, out = flushVerbatim(v, out) } // Emit the byte out = append(out, slot[k+j+1]) found = true i += j break Loop } } } if !found { // Match not found - add the byte to the verbatim buffer v = append(v, in[i]) i++ } // Perform a verbatim flush if needed if len(v) == 256 || len(v) > 0 && i == len(in) { v, out = flushVerbatim(v, out) } } if len(v) > 0 { _, out = flushVerbatim(v, out) } return out, nil } func Decompress(in []byte) ([]byte, error) { var out []byte for i := 0; i < len(in); i++ { switch c := in[i]; c { case 254: // Verbatim byte if i++; i >= len(in) { return nil, fmt.Errorf("invalid") } out = append(out, in[i]) case 255: // Verbatim string if i++; i >= len(in) { return nil, fmt.Errorf("invalid") } l := int(in[i]) + 1 if i++; i+l > len(in)
out = append(out, in[i:i+l]...) i += l - 1 default: // Codebook entry e := reverse[c] out = append(out, e...) } } return out, nil }
{ return nil, fmt.Errorf("invalid") }
commands.rs
use failure; use regex::Regex; use std::cmp; use std::fs::{self, File}; use std::io::{self, Write}; use Red; #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum Address { CurrentLine, LastLine, Numbered(usize), Offset(isize), } #[derive(Debug, PartialEq, Eq)] pub enum Mode { Command, Input, } #[derive(Debug, PartialEq, Eq)] pub enum Action { Quit, Continue, Unknown, } #[derive(Debug, PartialEq, Eq)] pub enum Command { Noop, Quit { force: bool, }, Help, Jump { address: Address, }, Print { start: Option<Address>, end: Option<Address>, }, Numbered { start: Option<Address>, end: Option<Address>, }, Delete { start: Option<Address>, end: Option<Address>, }, Write { start: Option<Address>, end: Option<Address>, file: Option<String>, }, Insert { before: Option<Address>, }, Append { after: Option<Address>, }, Edit { file: Option<String>, }, Change { start: Option<Address>, end: Option<Address>, }, Read { after: Option<Address>, file: Option<String>, }, Move { start: Option<Address>, end: Option<Address>, dest: Address, }, Substitute { start: Option<Address>, end: Option<Address>, arg: Option<String>, }, } impl Command { pub fn execute(self, ed: &mut Red) -> Result<Action, failure::Error> { debug!("Command::execute: {:?}", self); use Command::*; match self { Noop => Self::noop(ed), Help => Self::help(ed), Quit { force } => Self::quit(ed, force), Jump { address } => Self::jump(ed, address), Print { start, end } => Self::print(ed, start, end), Numbered { start, end } => Self::numbered(ed, start, end), Delete { start, end } => Self::delete(ed, start, end), Write { start, end, file } => Self::write(ed, start, end, file), Insert { before } => Self::insert(ed, before), Append { after } => Self::append(ed, after), Edit { file } => Self::edit(ed, file), Change { start, end } => Self::change(ed, start, end), Read { after, file } => Self::read(ed, after, file), Move { start, end, dest } => Self::move_lines(ed, start, end, dest), Substitute { start, end, arg } => Self::substitute(ed, start, end, arg), } } fn noop(ed: &mut Red) -> Result<Action, failure::Error> { if ed.current_line < ed.lines() {
Ok(Action::Unknown) } } fn help(ed: &mut Red) -> Result<Action, failure::Error> { if let Some(error) = ed.last_error.as_ref() { println!("{}", error); } Ok(Action::Continue) } fn quit(ed: &mut Red, force: bool) -> Result<Action, failure::Error> { if !force && ed.dirty { ed.dirty = false; Err(format_err!("Warning: buffer modified")) } else { Ok(Action::Quit) } } fn jump(ed: &mut Red, addr: Address) -> Result<Action, failure::Error> { use self::Address::*; match addr { CurrentLine => { /* Don't jump at all */ } LastLine => { let new_line = ed.lines(); ed.set_line(new_line)? } Numbered(n) => ed.set_line(n)?, Offset(n) => { let new_line = ed.current_line as isize + n; if new_line < 1 { return Err(format_err!("Invalid address")); } ed.set_line(new_line as usize)?; } } // After a jump, print the current line Self::print(ed, None, None) } fn print( ed: &mut Red, start: Option<Address>, end: Option<Address>, ) -> Result<Action, failure::Error> { let stdout = io::stdout(); let handle = stdout.lock(); Self::write_range(handle, ed, start, end, false) } fn numbered( ed: &mut Red, start: Option<Address>, end: Option<Address>, ) -> Result<Action, failure::Error> { let stdout = io::stdout(); let handle = stdout.lock(); Self::write_range(handle, ed, start, end, true) } fn delete( ed: &mut Red, start: Option<Address>, end: Option<Address>, ) -> Result<Action, failure::Error> { if ed.data.is_empty() { return Err(format_err!("Invalid address")); } match (start, end) { (None, None) => { let line = ed.current_line; ed.data.remove(line - 1); ed.dirty = true; ed.current_line = cmp::min(line, ed.data.len()); } (Some(start), None) => { let line = Self::get_actual_line(&ed, start)?; ed.data.remove(line - 1); ed.dirty = true; ed.current_line = cmp::min(line, ed.data.len()); } (None, Some(end)) => { let end = Self::get_actual_line(&ed, end)?; for _ in 1..=end { ed.data.remove(0); } ed.dirty = true; ed.current_line = cmp::min(end, ed.data.len()); } (Some(start), Some(end)) => { let start = Self::get_actual_line(&ed, start)?; let end = Self::get_actual_line(&ed, end)?; for _ in start..=end { ed.data.remove(start - 1); } ed.dirty = true; ed.current_line = cmp::min(start, ed.data.len()); } } Ok(Action::Continue) } fn write( ed: &mut Red, mut start: Option<Address>, mut end: Option<Address>, file: Option<String>, ) -> Result<Action, failure::Error> { let file = file.or_else(|| ed.path.clone()); match file { None => Ok(Action::Unknown), Some(path) => { // By default, write the whole buffer if start.is_none() && end.is_none() { start = Some(Address::Numbered(1)); end = Some(Address::LastLine); } debug!("Writing to file {:?} ({:?}..{:?})", path, start, end); let file = File::create(&path)?; Self::write_range(file, ed, start, end, false)?; let size = fs::metadata(&path)?.len(); println!("{}", size); ed.path = Some(path); ed.dirty = false; Ok(Action::Continue) } } } fn insert(ed: &mut Red, before: Option<Address>) -> Result<Action, failure::Error> { let mut addr = before .map(|addr| Self::get_actual_line(&ed, addr)) .unwrap_or_else(|| Ok(ed.current_line))?; // Insert after the previous line if addr > 0 { addr -= 1; } ed.current_line = addr; ed.mode = Mode::Input; Ok(Action::Continue) } fn append(ed: &mut Red, after: Option<Address>) -> Result<Action, failure::Error> { let addr = after .map(|addr| Self::get_actual_line(&ed, addr)) .unwrap_or_else(|| Ok(ed.current_line))?; ed.current_line = addr; ed.mode = Mode::Input; Ok(Action::Continue) } fn edit(ed: &mut Red, file: Option<String>) -> Result<Action, failure::Error> { let file = file.or_else(|| ed.path.clone()); let file = match file { None => return Err(format_err!("No current filename")), Some(file) => file, }; ed.load_file(file)?; Ok(Action::Continue) } fn change( ed: &mut Red, start: Option<Address>, end: Option<Address>, ) -> Result<Action, failure::Error> { Self::delete(ed, start, end)?; let mut addr = ed.current_line; if addr > 0 { addr -= 1; } ed.current_line = addr; ed.mode = Mode::Input; ed.dirty = true; Ok(Action::Continue) } fn read( ed: &mut Red, after: Option<Address>, file: Option<String>, ) -> Result<Action, failure::Error> { let file = file.or_else(|| ed.path.clone()); let file = match file { None => return Err(format_err!("No current filename")), Some(file) => file, }; let data = ed.load_data(&file)?; let mut addr = after .map(|addr| Self::get_actual_line(&ed, addr)) .unwrap_or_else(|| Ok(ed.current_line))?; let mut written = 0; for line in data { written += line.len() + 1; if ed.data.is_empty() { ed.data.push(line); } else { ed.data.insert(addr, line); } addr += 1; } ed.dirty = true; ed.current_line = addr; println!("{}", written); Ok(Action::Continue) } fn move_lines( ed: &mut Red, start: Option<Address>, end: Option<Address>, dest: Address, ) -> Result<Action, failure::Error> { if ed.data.is_empty() { return Ok(Action::Continue); } let mut dest = Self::get_actual_line(&ed, dest)?; debug!("Moving after line {}", dest); match (start, end) { (None, None) => { let line_no = ed.current_line; debug!("Moving line {} to {}", line_no, dest); if line_no == dest { return Err(format_err!("Invalid destination")); } let line = ed.data.remove(line_no - 1); if dest > line_no { dest -= 1; } debug!("After adjustment: Moving line {} to {}", line_no, dest); ed.data.insert(dest, line); ed.set_line(dest)?; } (Some(start), None) => { let line_no = Self::get_actual_line(&ed, start)?; debug!("Moving line {} to {}", line_no, dest); if line_no == dest { return Err(format_err!("Invalid destination")); } let line = ed.data.remove(line_no - 1); if dest > line_no { dest -= 1; } debug!("After adjustment: Moving line {} to {}", line_no, dest); ed.data.insert(dest, line); let dest = cmp::max(dest, 1); ed.set_line(dest)?; } (None, Some(end)) => { let mut lines = vec![]; let end = Self::get_actual_line(&ed, end)?; debug!("Moving lines 1..{} to {}", end, dest); if dest <= end { return Err(format_err!("Invalid destination")); } for _ in 1..=end { lines.push(ed.data.remove(0)); } dest -= lines.len(); debug!("New destination after adjustment: {}", dest); for line in lines { ed.data.insert(dest, line); dest += 1; } ed.set_line(dest)?; } (Some(start), Some(end)) => { let mut lines = vec![]; let start = Self::get_actual_line(&ed, start)?; let end = Self::get_actual_line(&ed, end)?; debug!("Moving lines {}..{} to {}", start, end, dest); if dest >= start && dest <= end { return Err(format_err!("Invalid destination")); } for _ in start..=end { lines.push(ed.data.remove(start - 1)); } if end < dest { dest -= lines.len(); } debug!("New destination after adjustment: {}", dest); for line in lines { ed.data.insert(dest, line); dest += 1; } ed.set_line(dest)?; } } ed.dirty = true; Ok(Action::Continue) } fn substitute( ed: &mut Red, start: Option<Address>, end: Option<Address>, arg: Option<String>, ) -> Result<Action, failure::Error> { let arg = match arg { None => return Err(format_err!("No previous substitution")), Some(arg) => arg, }; if &arg[0..=0] != "/" { return Err(format_err!("Missing pattern delimiter")); } let arg = &arg[1..]; let regex_end = match arg.find(|c| c == '/') { None => return Err(format_err!("Missing pattern delimiter")), Some(idx) => idx, }; let re = &arg[..regex_end]; debug!("Regex: {:?}", re); let mut replacement = &arg[regex_end + 1..]; let flags = match replacement.find(|c| c == '/') { None => "", Some(idx) => { let flags = &replacement[idx + 1..]; replacement = &replacement[0..idx]; flags } }; debug!("Replacement: {:?}", replacement); debug!("Flags: {:?}", flags); let re = Regex::new(re).map_err(|_| format_err!("No match"))?; let all = flags.chars().any(|c| c == 'g'); let mut start = start .map(|addr| Self::get_actual_line(&ed, addr)) .unwrap_or_else(|| Ok(ed.current_line))?; let end = end .map(|addr| Self::get_actual_line(&ed, addr)) .unwrap_or_else(|| Ok(ed.current_line))?; if start == 0 { return Err(format_err!("Invalid address")); } start -= 1; debug!("Replacement in range: {}..{}", start, end); let mut modified = None; for (line, idx) in ed.data[start..end].iter_mut().zip(start..end) { let new = if all { let s = re.replace_all(line, replacement); if &*s == line { continue; } s.into_owned() } else { let s = re.replace(line, replacement); if &*s == line { continue; } s.into_owned() }; line.replace_range(.., &new); modified = Some(idx + 1); } if let Some(idx) = modified { ed.dirty = true; ed.set_line(idx)?; Self::print(ed, None, None) } else { Err(format_err!("No match")) } } fn write_range<W: Write>( mut output: W, ed: &mut Red, start: Option<Address>, end: Option<Address>, show_number: bool, ) -> Result<Action, failure::Error> { if ed.data.is_empty() { return Err(format_err!("Invalid address")); } match (start, end) { (None, None) => { if show_number { write!(output, "{}\t", ed.current_line)?; } writeln!(output, "{}", ed.get_line(ed.current_line).unwrap())?; } (Some(start), None) => { ed.current_line = Self::get_actual_line(&ed, start)?; if show_number { write!(output, "{}\t", ed.current_line)?; } writeln!(output, "{}", ed.get_line(ed.current_line).unwrap())?; } (None, Some(end)) => { let end = Self::get_actual_line(&ed, end)?; for line in 1..=end { if show_number { write!(output, "{}\t", line)?; } writeln!(output, "{}", ed.get_line(line).unwrap())?; } ed.current_line = end; } (Some(start), Some(end)) => { let start = Self::get_actual_line(&ed, start)?; let end = Self::get_actual_line(&ed, end)?; for line in start..=end { if show_number { write!(output, "{}\t", line)?; } writeln!(output, "{}", ed.get_line(line).unwrap())?; } ed.current_line = end; } } Ok(Action::Continue) } fn get_actual_line(ed: &Red, addr: Address) -> Result<usize, failure::Error> { use self::Address::*; match addr { CurrentLine => Ok(ed.current_line), LastLine => Ok(ed.lines()), Numbered(n) => { if n > ed.lines() { return Err(format_err!("Invalid address")); } Ok(n) } Offset(n) => { let line = ed.current_line as isize + n; if line < 1 { return Err(format_err!("Invalid address")); } let line = line as usize; if line > ed.lines() { return Err(format_err!("Invalid address")); } Ok(line) } } } }
ed.current_line += 1; Self::print(ed, None, None) } else {
SSLIM_BPR.py
from course_lib.Base.Recommender_utils import check_matrix from course_lib.Base.BaseSimilarityMatrixRecommender import BaseItemSimilarityMatrixRecommender from course_lib.Base.Recommender_utils import similarityMatrixTopK from course_lib.Base.Incremental_Training_Early_Stopping import Incremental_Training_Early_Stopping from course_lib.CythonCompiler.run_compile_subprocess import run_compile_subprocess import sys import scipy.sparse as sps from course_lib.SLIM_BPR.Cython.SLIM_BPR_Cython import estimate_required_MB, get_RAM_status class SSLIM_BPR(BaseItemSimilarityMatrixRecommender, Incremental_Training_Early_Stopping): RECOMMENDER_NAME = "SSLIM_BPR_Recommender" def __init__(self, URM_train, ICM_train, verbose=True, free_mem_threshold=0.5, recompile_cython=False): super(SSLIM_BPR, self).__init__(URM_train, verbose=verbose) assert 0.0 <= free_mem_threshold <= 1.0, \ "SSLIM_BPR_Recommender: free_mem_threshold must be between 0.0 and 1.0, provided was '{}'".format( free_mem_threshold) self.n_users, self.n_items = self.URM_train.shape self.ICM_train = ICM_train self.free_mem_threshold = free_mem_threshold if recompile_cython: print("Compiling in Cython") self.runCompilationScript() print("Compilation Complete") def fit(self, epochs=300, positive_threshold_BPR=None, train_with_sparse_weights=None, symmetric=True, random_seed=None,
**earlystopping_kwargs): # Import compiled module from course_lib.SLIM_BPR.Cython.SLIM_BPR_Cython_Epoch import SLIM_BPR_Cython_Epoch self.symmetric = symmetric self.train_with_sparse_weights = train_with_sparse_weights if self.train_with_sparse_weights is None: # auto select required_m = estimate_required_MB(self.n_items, self.symmetric) total_m, _, available_m = get_RAM_status() if total_m is not None: string = "Automatic selection of fastest train mode. Available RAM is {:.2f} MB ({:.2f}%) of {:.2f} MB, required is {:.2f} MB. ".format( available_m, available_m / total_m * 100, total_m, required_m) else: string = "Automatic selection of fastest train mode. Unable to get current RAM status, you may be using a non-Linux operating system. " if total_m is None or required_m / available_m < self.free_mem_threshold: self._print(string + "Using dense matrix.") self.train_with_sparse_weights = False else: self._print(string + "Using sparse matrix.") self.train_with_sparse_weights = True # Select only positive interactions URM_train_positive = self.URM_train.copy() URM_train_positive = sps.vstack([alpha*URM_train_positive, (1-alpha)*self.ICM_train.T.copy()]) self.positive_threshold_BPR = positive_threshold_BPR self.sgd_mode = sgd_mode self.epochs = epochs if self.positive_threshold_BPR is not None: URM_train_positive.data = URM_train_positive.data >= self.positive_threshold_BPR URM_train_positive.eliminate_zeros() assert URM_train_positive.nnz > 0, \ "SSLIM_BPR_Cython: URM_train_positive is empty, positive threshold is too high" self.cythonEpoch = SLIM_BPR_Cython_Epoch(URM_train_positive, train_with_sparse_weights=self.train_with_sparse_weights, final_model_sparse_weights=True, topK=topK, learning_rate=learning_rate, li_reg=lambda_i, lj_reg=lambda_j, batch_size=1, symmetric=self.symmetric, sgd_mode=sgd_mode, verbose=self.verbose, random_seed=random_seed, gamma=gamma, beta_1=beta_1, beta_2=beta_2) if (topK != False and topK < 1): raise ValueError( "TopK not valid. Acceptable values are either False or a positive integer value. Provided value was '{}'".format( topK)) self.topK = topK self.batch_size = batch_size self.lambda_i = lambda_i self.lambda_j = lambda_j self.learning_rate = learning_rate self.S_incremental = self.cythonEpoch.get_S() self.S_best = self.S_incremental.copy() self._train_with_early_stopping(epochs, algorithm_name=self.RECOMMENDER_NAME, **earlystopping_kwargs) self.get_S_incremental_and_set_W() self.cythonEpoch._dealloc() sys.stdout.flush() def _prepare_model_for_validation(self): self.get_S_incremental_and_set_W() def _update_best_model(self): self.S_best = self.S_incremental.copy() def _run_epoch(self, num_epoch): self.cythonEpoch.epochIteration_Cython() def get_S_incremental_and_set_W(self): self.S_incremental = self.cythonEpoch.get_S() if self.train_with_sparse_weights: self.W_sparse = self.S_incremental self.W_sparse = check_matrix(self.W_sparse, format='csr') else: self.W_sparse = similarityMatrixTopK(self.S_incremental, k=self.topK) self.W_sparse = check_matrix(self.W_sparse, format='csr') def runCompilationScript(self): # Run compile script setting the working directory to ensure the compiled file are contained in the # appropriate subfolder and not the project root file_subfolder = "/SLIM_BPR/Cython" file_to_compile_list = ['SLIM_BPR_Cython_Epoch.pyx'] run_compile_subprocess(file_subfolder, file_to_compile_list) print("{}: Compiled module {} in subfolder: {}".format(self.RECOMMENDER_NAME, file_to_compile_list, file_subfolder)) # Command to run compilation script # python compile_script.py SLIM_BPR_Cython_Epoch.pyx build_ext --inplace # Command to generate html report # cython -a SLIM_BPR_Cython_Epoch.pyx
batch_size=1000, lambda_i=0.0, lambda_j=0.0, learning_rate=1e-4, topK=200, alpha=0.5, sgd_mode='adagrad', gamma=0.995, beta_1=0.9, beta_2=0.999,
handshake_client.go
// Copyright 2009 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 tls import ( "bytes" "crypto" "crypto/ecdsa" "crypto/rsa" "crypto/subtle" "crypto/x509" "errors" "fmt" "io" "net" "strconv" "strings" ) type clientHandshakeState struct { c *Conn serverHello *serverHelloMsg hello *clientHelloMsg suite *cipherSuite finishedHash finishedHash masterSecret []byte session *ClientSessionState } func (c *Conn) clientHandshake() error { if c.config == nil { c.config = defaultConfig() } if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify { return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config") } nextProtosLength := 0 for _, proto := range c.config.NextProtos { if l := len(proto); l == 0 || l > 255 { return errors.New("tls: invalid NextProtos value") } else { nextProtosLength += 1 + l } } if nextProtosLength > 0xffff { return errors.New("tls: NextProtos values too large") } hello := &clientHelloMsg{ vers: c.config.maxVersion(), compressionMethods: []uint8{compressionNone}, random: make([]byte, 32), ocspStapling: true, scts: true, serverName: hostnameInSNI(c.config.ServerName), supportedCurves: c.config.curvePreferences(), supportedPoints: []uint8{pointFormatUncompressed}, nextProtoNeg: len(c.config.NextProtos) > 0, secureRenegotiation: true, alpnProtocols: c.config.NextProtos, } possibleCipherSuites := c.config.cipherSuites() hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites)) NextCipherSuite: for _, suiteId := range possibleCipherSuites { for _, suite := range cipherSuites { if suite.id != suiteId { continue } // Don't advertise TLS 1.2-only cipher suites unless // we're attempting TLS 1.2. if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 { continue } hello.cipherSuites = append(hello.cipherSuites, suiteId) continue NextCipherSuite } } _, err := io.ReadFull(c.config.rand(), hello.random) if err != nil { c.sendAlert(alertInternalError) return errors.New("tls: short read from Rand: " + err.Error()) } if hello.vers >= VersionTLS12 { hello.signatureAndHashes = supportedSignatureAlgorithms } var session *ClientSessionState var cacheKey string sessionCache := c.config.ClientSessionCache if c.config.SessionTicketsDisabled { sessionCache = nil } if sessionCache != nil { hello.ticketSupported = true // Try to resume a previously negotiated TLS session, if // available. cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config) candidateSession, ok := sessionCache.Get(cacheKey) if ok { // Check that the ciphersuite/version used for the // previous session are still valid. cipherSuiteOk := false for _, id := range hello.cipherSuites { if id == candidateSession.cipherSuite { cipherSuiteOk = true break } } versOk := candidateSession.vers >= c.config.minVersion() && candidateSession.vers <= c.config.maxVersion() if versOk && cipherSuiteOk { session = candidateSession } } } if session != nil { hello.sessionTicket = session.sessionTicket // A random session ID is used to detect when the // server accepted the ticket and is resuming a session // (see RFC 5077). hello.sessionId = make([]byte, 16) if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil { c.sendAlert(alertInternalError) return errors.New("tls: short read from Rand: " + err.Error()) } } if _, err := c.writeRecord(recordTypeHandshake, hello.marshal()); err != nil { return err } msg, err := c.readHandshake() if err != nil { return err } serverHello, ok := msg.(*serverHelloMsg) if !ok { c.sendAlert(alertUnexpectedMessage) return unexpectedMessageError(serverHello, msg) } vers, ok := c.config.mutualVersion(serverHello.vers) if !ok || vers < VersionTLS10 { // TLS 1.0 is the minimum version supported as a client. c.sendAlert(alertProtocolVersion) return fmt.Errorf("tls: server selected unsupported protocol version %x", serverHello.vers) } c.vers = vers c.haveVers = true suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite) if suite == nil { c.sendAlert(alertHandshakeFailure) return errors.New("tls: server chose an unconfigured cipher suite") } hs := &clientHandshakeState{ c: c, serverHello: serverHello, hello: hello, suite: suite, finishedHash: newFinishedHash(c.vers, suite), session: session, } isResume, err := hs.processServerHello() if err != nil { return err } // No signatures of the handshake are needed in a resumption. // Otherwise, in a full handshake, if we don't have any certificates // configured then we will never send a CertificateVerify message and // thus no signatures are needed in that case either. if isResume || len(c.config.Certificates) == 0 { hs.finishedHash.discardHandshakeBuffer() } hs.finishedHash.Write(hs.hello.marshal()) hs.finishedHash.Write(hs.serverHello.marshal()) if isResume { if err := hs.establishKeys(); err != nil { return err } if err := hs.readSessionTicket(); err != nil { return err } if err := hs.readFinished(c.firstFinished[:]); err != nil { return err } if err := hs.sendFinished(nil); err != nil { return err } } else { if err := hs.doFullHandshake(); err != nil { return err } if err := hs.establishKeys(); err != nil { return err } if err := hs.sendFinished(c.firstFinished[:]); err != nil { return err } if err := hs.readSessionTicket(); err != nil { return err } if err := hs.readFinished(nil); err != nil { return err } } if sessionCache != nil && hs.session != nil && session != hs.session { sessionCache.Put(cacheKey, hs.session) } c.didResume = isResume c.handshakeComplete = true c.cipherSuite = suite.id return nil } func (hs *clientHandshakeState) doFullHandshake() error { c := hs.c msg, err := c.readHandshake() if err != nil { return err } certMsg, ok := msg.(*certificateMsg) if !ok || len(certMsg.certificates) == 0 { c.sendAlert(alertUnexpectedMessage) return unexpectedMessageError(certMsg, msg) } hs.finishedHash.Write(certMsg.marshal()) certs := make([]*x509.Certificate, len(certMsg.certificates)) for i, asn1Data := range certMsg.certificates { cert, err := x509.ParseCertificate(asn1Data) if err != nil { c.sendAlert(alertBadCertificate) return errors.New("tls: failed to parse certificate from server: " + err.Error()) } certs[i] = cert } if !c.config.InsecureSkipVerify { opts := x509.VerifyOptions{ Roots: c.config.RootCAs, CurrentTime: c.config.time(), DNSName: c.config.ServerName, Intermediates: x509.NewCertPool(), } for i, cert := range certs { if i == 0 { continue } opts.Intermediates.AddCert(cert) } c.verifiedChains, err = certs[0].Verify(opts) if err != nil { c.sendAlert(alertBadCertificate) return err } } switch certs[0].PublicKey.(type) { case *rsa.PublicKey, *ecdsa.PublicKey: break default: c.sendAlert(alertUnsupportedCertificate) return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey) } c.peerCertificates = certs if hs.serverHello.ocspStapling { msg, err = c.readHandshake() if err != nil { return err } cs, ok := msg.(*certificateStatusMsg) if !ok { c.sendAlert(alertUnexpectedMessage) return unexpectedMessageError(cs, msg) } hs.finishedHash.Write(cs.marshal()) if cs.statusType == statusTypeOCSP { c.ocspResponse = cs.response } } msg, err = c.readHandshake() if err != nil { return err } keyAgreement := hs.suite.ka(c.vers) skx, ok := msg.(*serverKeyExchangeMsg) if ok { hs.finishedHash.Write(skx.marshal()) err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, certs[0], skx) if err != nil { c.sendAlert(alertUnexpectedMessage) return err } msg, err = c.readHandshake() if err != nil { return err } } var chainToSend *Certificate var certRequested bool certReq, ok := msg.(*certificateRequestMsg) if ok { certRequested = true // RFC 4346 on the certificateAuthorities field: // A list of the distinguished names of acceptable certificate // authorities. These distinguished names may specify a desired // distinguished name for a root CA or for a subordinate CA; // thus, this message can be used to describe both known roots // and a desired authorization space. If the // certificate_authorities list is empty then the client MAY // send any certificate of the appropriate // ClientCertificateType, unless there is some external // arrangement to the contrary. hs.finishedHash.Write(certReq.marshal()) var rsaAvail, ecdsaAvail bool for _, certType := range certReq.certificateTypes { switch certType { case certTypeRSASign: rsaAvail = true case certTypeECDSASign: ecdsaAvail = true } } // We need to search our list of client certs for one // where SignatureAlgorithm is acceptable to the server and the // Issuer is in certReq.certificateAuthorities findCert: for i, chain := range c.config.Certificates { if !rsaAvail && !ecdsaAvail { continue } for j, cert := range chain.Certificate { x509Cert := chain.Leaf // parse the certificate if this isn't the leaf // node, or if chain.Leaf was nil if j != 0 || x509Cert == nil { if x509Cert, err = x509.ParseCertificate(cert); err != nil { c.sendAlert(alertInternalError) return errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error()) } } switch { case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA: case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA: default: continue findCert } if len(certReq.certificateAuthorities) == 0 { // they gave us an empty list, so just take the // first cert from c.config.Certificates chainToSend = &chain break findCert } for _, ca := range certReq.certificateAuthorities { if bytes.Equal(x509Cert.RawIssuer, ca) { chainToSend = &chain break findCert } } } } msg, err = c.readHandshake() if err != nil { return err } } shd, ok := msg.(*serverHelloDoneMsg) if !ok { c.sendAlert(alertUnexpectedMessage) return unexpectedMessageError(shd, msg) } hs.finishedHash.Write(shd.marshal()) // If the server requested a certificate then we have to send a // Certificate message, even if it's empty because we don't have a // certificate to send. if certRequested { certMsg = new(certificateMsg) if chainToSend != nil { certMsg.certificates = chainToSend.Certificate } hs.finishedHash.Write(certMsg.marshal()) if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil { return err } } preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, certs[0]) if err != nil { c.sendAlert(alertInternalError) return err } if ckx != nil { hs.finishedHash.Write(ckx.marshal()) if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil { return err } } if chainToSend != nil { certVerify := &certificateVerifyMsg{ hasSignatureAndHash: c.vers >= VersionTLS12, } key, ok := chainToSend.PrivateKey.(crypto.Signer) if !ok { c.sendAlert(alertInternalError) return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey) } var signatureType uint8 switch key.Public().(type) { case *ecdsa.PublicKey: signatureType = signatureECDSA case *rsa.PublicKey: signatureType = signatureRSA default: c.sendAlert(alertInternalError) return fmt.Errorf("tls: failed to sign handshake with client certificate: unknown client certificate key type: %T", key) } certVerify.signatureAndHash, err = hs.finishedHash.selectClientCertSignatureAlgorithm(certReq.signatureAndHashes, signatureType) if err != nil { c.sendAlert(alertInternalError) return err } digest, hashFunc, err := hs.finishedHash.hashForClientCertificate(certVerify.signatureAndHash, hs.masterSecret) if err != nil { c.sendAlert(alertInternalError) return err } certVerify.signature, err = key.Sign(c.config.rand(), digest, hashFunc) if err != nil { c.sendAlert(alertInternalError) return err } hs.finishedHash.Write(certVerify.marshal()) if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil { return err } } hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random) hs.finishedHash.discardHandshakeBuffer() return nil } func (hs *clientHandshakeState) establishKeys() error { c := hs.c clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen) var clientCipher, serverCipher interface{} var clientHash, serverHash macFunction if hs.suite.cipher != nil { clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */) clientHash = hs.suite.mac(c.vers, clientMAC) serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */) serverHash = hs.suite.mac(c.vers, serverMAC) } else { clientCipher = hs.suite.aead(clientKey, clientIV) serverCipher = hs.suite.aead(serverKey, serverIV) } c.in.prepareCipherSpec(c.vers, serverCipher, serverHash) c.out.prepareCipherSpec(c.vers, clientCipher, clientHash) return nil } func (hs *clientHandshakeState) serverResumedSession() bool { // If the server responded with the same sessionId then it means the // sessionTicket is being used to resume a TLS session. return hs.session != nil && hs.hello.sessionId != nil && bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId) } func (hs *clientHandshakeState) processServerHello() (bool, error) { c := hs.c if hs.serverHello.compressionMethod != compressionNone { c.sendAlert(alertUnexpectedMessage) return false, errors.New("tls: server selected unsupported compression format") } clientDidNPN := hs.hello.nextProtoNeg clientDidALPN := len(hs.hello.alpnProtocols) > 0 serverHasNPN := hs.serverHello.nextProtoNeg serverHasALPN := len(hs.serverHello.alpnProtocol) > 0 if !clientDidNPN && serverHasNPN { c.sendAlert(alertHandshakeFailure) return false, errors.New("server advertised unrequested NPN extension") } if !clientDidALPN && serverHasALPN { c.sendAlert(alertHandshakeFailure) return false, errors.New("server advertised unrequested ALPN extension") } if serverHasNPN && serverHasALPN { c.sendAlert(alertHandshakeFailure) return false, errors.New("server advertised both NPN and ALPN extensions") } if serverHasALPN { c.clientProtocol = hs.serverHello.alpnProtocol c.clientProtocolFallback = false } c.scts = hs.serverHello.scts if !hs.serverResumedSession() { return false, nil } // Restore masterSecret and peerCerts from previous state hs.masterSecret = hs.session.masterSecret c.peerCertificates = hs.session.serverCertificates c.verifiedChains = hs.session.verifiedChains return true, nil } func (hs *clientHandshakeState) readFinished(out []byte) error { c := hs.c c.readRecord(recordTypeChangeCipherSpec) if err := c.in.error(); err != nil { return err } msg, err := c.readHandshake() if err != nil { return err } serverFinished, ok := msg.(*finishedMsg) if !ok { c.sendAlert(alertUnexpectedMessage) return unexpectedMessageError(serverFinished, msg) } verify := hs.finishedHash.serverSum(hs.masterSecret) if len(verify) != len(serverFinished.verifyData) || subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 { c.sendAlert(alertHandshakeFailure) return errors.New("tls: server's Finished message was incorrect") } hs.finishedHash.Write(serverFinished.marshal()) copy(out, verify) return nil } func (hs *clientHandshakeState) readSessionTicket() error { if !hs.serverHello.ticketSupported { return nil } c := hs.c msg, err := c.readHandshake() if err != nil { return err } sessionTicketMsg, ok := msg.(*newSessionTicketMsg) if !ok { c.sendAlert(alertUnexpectedMessage) return unexpectedMessageError(sessionTicketMsg, msg) } hs.finishedHash.Write(sessionTicketMsg.marshal()) hs.session = &ClientSessionState{ sessionTicket: sessionTicketMsg.ticket, vers: c.vers, cipherSuite: hs.suite.id, masterSecret: hs.masterSecret, serverCertificates: c.peerCertificates, verifiedChains: c.verifiedChains, } return nil } func (hs *clientHandshakeState) sendFinished(out []byte) error { c := hs.c if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil { return err } if hs.serverHello.nextProtoNeg { nextProto := new(nextProtoMsg) proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos) nextProto.proto = proto c.clientProtocol = proto c.clientProtocolFallback = fallback hs.finishedHash.Write(nextProto.marshal()) if _, err := c.writeRecord(recordTypeHandshake, nextProto.marshal()); err != nil { return err } } finished := new(finishedMsg) finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret) hs.finishedHash.Write(finished.marshal()) if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil { return err } copy(out, finished.verifyData) return nil } // clientSessionCacheKey returns a key used to cache sessionTickets that could // be used to resume previously negotiated TLS sessions with a server. func clientSessionCacheKey(serverAddr net.Addr, config *Config) string
// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol // given list of possible protocols and a list of the preference order. The // first list must not be empty. It returns the resulting protocol and flag // indicating if the fallback case was reached. func mutualProtocol(protos, preferenceProtos []string) (string, bool) { for _, s := range preferenceProtos { for _, c := range protos { if s == c { return s, false } } } return protos[0], true } // hostnameInSNI converts name into an approriate hostname for SNI. // Literal IP addresses and absolute FQDNs are not permitted as SNI values. // See https://tools.ietf.org/html/rfc6066#section-3. func hostnameInSNI(name string) string { host := name if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' { host = host[1 : len(host)-1] } if i := strings.LastIndex(host, "%"); i > 0 { host = host[:i] } if net.ParseIP(host) != nil { return "" } if len(name) > 0 && name[len(name)-1] == '.' { name = name[:len(name)-1] } return name }
{ if len(config.ServerName) > 0 { return config.ServerName } return serverAddr.String() }
CreateSecurityMonitoringRule.go
// Create a detection rule returns "OK" response package main import ( "context" "encoding/json" "fmt" "os" datadog "github.com/DataDog/datadog-api-client-go/api/v2/datadog" ) func main() { body := datadog.SecurityMonitoringRuleCreatePayload{ Name: "Example-Create_a_detection_rule_returns_OK_response", Queries: []datadog.SecurityMonitoringRuleQueryCreate{ { Query: "@test:true", Aggregation: datadog.SECURITYMONITORINGRULEQUERYAGGREGATION_COUNT.Ptr(), GroupByFields: &[]string{}, DistinctFields: &[]string{}, Metric: datadog.PtrString(""), }, }, Filters: &[]datadog.SecurityMonitoringFilter{}, Cases: []datadog.SecurityMonitoringRuleCaseCreate{ { Name: datadog.PtrString(""), Status: datadog.SECURITYMONITORINGRULESEVERITY_INFO, Condition: datadog.PtrString("a > 0"), Notifications: &[]string{}, }, }, Options: datadog.SecurityMonitoringRuleOptions{ EvaluationWindow: datadog.SECURITYMONITORINGRULEEVALUATIONWINDOW_FIFTEEN_MINUTES.Ptr(), KeepAlive: datadog.SECURITYMONITORINGRULEKEEPALIVE_ONE_HOUR.Ptr(), MaxSignalDuration: datadog.SECURITYMONITORINGRULEMAXSIGNALDURATION_ONE_DAY.Ptr(), }, Message: "Test rule", Tags: &[]string{}, IsEnabled: true, } ctx := datadog.NewDefaultContext(context.Background()) configuration := datadog.NewConfiguration() apiClient := datadog.NewAPIClient(configuration) resp, r, err := apiClient.SecurityMonitoringApi.CreateSecurityMonitoringRule(ctx, body) if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `SecurityMonitoringApi.CreateSecurityMonitoringRule`: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) } responseContent, _ := json.MarshalIndent(resp, "", " ") fmt.Fprintf(os.Stdout, "Response from `SecurityMonitoringApi.CreateSecurityMonitoringRule`:\n%s\n", responseContent)
}
replica_set_test.go
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package replicaset import ( "errors" "fmt" "math/rand" "net/http/httptest" "net/url" "reflect" "strings" "sync" "testing" "time" apps "k8s.io/api/apps/v1" "k8s.io/api/core/v1" apiequality "k8s.io/apimachinery/pkg/api/equality" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/uuid" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/informers" clientset "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/fake" restclient "k8s.io/client-go/rest" core "k8s.io/client-go/testing" "k8s.io/client-go/tools/cache" utiltesting "k8s.io/client-go/util/testing" "k8s.io/client-go/util/workqueue" "k8s.io/kubernetes/pkg/controller" . "k8s.io/kubernetes/pkg/controller/testutil" "k8s.io/kubernetes/pkg/securitycontext" ) func testNewReplicaSetControllerFromClient(client clientset.Interface, stopCh chan struct{}, burstReplicas int) (*ReplicaSetController, informers.SharedInformerFactory) { informers := informers.NewSharedInformerFactory(client, controller.NoResyncPeriodFunc()) ret := NewReplicaSetController( informers.Apps().V1().ReplicaSets(), informers.Core().V1().Pods(), client, burstReplicas, ) ret.podListerSynced = alwaysReady ret.rsListerSynced = alwaysReady return ret, informers } func skipListerFunc(verb string, url url.URL) bool { if verb != "GET" { return false } if strings.HasSuffix(url.Path, "/pods") || strings.Contains(url.Path, "/replicasets") { return true } return false } var alwaysReady = func() bool { return true } func newReplicaSet(replicas int, selectorMap map[string]string) *apps.ReplicaSet { rs := &apps.ReplicaSet{ TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "ReplicaSet"}, ObjectMeta: metav1.ObjectMeta{ UID: uuid.NewUUID(), Name: "foobar", Namespace: metav1.NamespaceDefault, ResourceVersion: "18", }, Spec: apps.ReplicaSetSpec{ Replicas: func() *int32 { i := int32(replicas); return &i }(), Selector: &metav1.LabelSelector{MatchLabels: selectorMap}, Template: v1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{ "name": "foo", "type": "production", }, }, Spec: v1.PodSpec{ Containers: []v1.Container{ { Image: "foo/bar", TerminationMessagePath: v1.TerminationMessagePathDefault, ImagePullPolicy: v1.PullIfNotPresent, SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults(), }, }, RestartPolicy: v1.RestartPolicyAlways, DNSPolicy: v1.DNSDefault, NodeSelector: map[string]string{ "baz": "blah", }, }, }, }, } return rs } // create a pod with the given phase for the given rs (same selectors and namespace) func
(name string, rs *apps.ReplicaSet, status v1.PodPhase, lastTransitionTime *metav1.Time, properlyOwned bool) *v1.Pod { var conditions []v1.PodCondition if status == v1.PodRunning { condition := v1.PodCondition{Type: v1.PodReady, Status: v1.ConditionTrue} if lastTransitionTime != nil { condition.LastTransitionTime = *lastTransitionTime } conditions = append(conditions, condition) } var controllerReference metav1.OwnerReference if properlyOwned { var trueVar = true controllerReference = metav1.OwnerReference{UID: rs.UID, APIVersion: "v1beta1", Kind: "ReplicaSet", Name: rs.Name, Controller: &trueVar} } return &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: rs.Namespace, Labels: rs.Spec.Selector.MatchLabels, OwnerReferences: []metav1.OwnerReference{controllerReference}, }, Status: v1.PodStatus{Phase: status, Conditions: conditions}, } } // create count pods with the given phase for the given ReplicaSet (same selectors and namespace), and add them to the store. func newPodList(store cache.Store, count int, status v1.PodPhase, labelMap map[string]string, rs *apps.ReplicaSet, name string) *v1.PodList { pods := []v1.Pod{} var trueVar = true controllerReference := metav1.OwnerReference{UID: rs.UID, APIVersion: "v1beta1", Kind: "ReplicaSet", Name: rs.Name, Controller: &trueVar} for i := 0; i < count; i++ { pod := newPod(fmt.Sprintf("%s%d", name, i), rs, status, nil, false) pod.ObjectMeta.Labels = labelMap pod.OwnerReferences = []metav1.OwnerReference{controllerReference} if store != nil { store.Add(pod) } pods = append(pods, *pod) } return &v1.PodList{ Items: pods, } } // processSync initiates a sync via processNextWorkItem() to test behavior that // depends on both functions (such as re-queueing on sync error). func processSync(rsc *ReplicaSetController, key string) error { // Save old syncHandler and replace with one that captures the error. oldSyncHandler := rsc.syncHandler defer func() { rsc.syncHandler = oldSyncHandler }() var syncErr error rsc.syncHandler = func(key string) error { syncErr = oldSyncHandler(key) return syncErr } rsc.queue.Add(key) rsc.processNextWorkItem() return syncErr } func validateSyncReplicaSet(t *testing.T, fakePodControl *controller.FakePodControl, expectedCreates, expectedDeletes, expectedPatches int) { if e, a := expectedCreates, len(fakePodControl.Templates); e != a { t.Errorf("Unexpected number of creates. Expected %d, saw %d\n", e, a) } if e, a := expectedDeletes, len(fakePodControl.DeletePodName); e != a { t.Errorf("Unexpected number of deletes. Expected %d, saw %d\n", e, a) } if e, a := expectedPatches, len(fakePodControl.Patches); e != a { t.Errorf("Unexpected number of patches. Expected %d, saw %d\n", e, a) } } func TestSyncReplicaSetDoesNothing(t *testing.T) { client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: "", Version: "v1"}}}) fakePodControl := controller.FakePodControl{} stopCh := make(chan struct{}) defer close(stopCh) manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas) // 2 running pods, a controller with 2 replicas, sync is a no-op labelMap := map[string]string{"foo": "bar"} rsSpec := newReplicaSet(2, labelMap) informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rsSpec) newPodList(informers.Core().V1().Pods().Informer().GetIndexer(), 2, v1.PodRunning, labelMap, rsSpec, "pod") manager.podControl = &fakePodControl manager.syncReplicaSet(GetKey(rsSpec, t)) validateSyncReplicaSet(t, &fakePodControl, 0, 0, 0) } func TestDeleteFinalStateUnknown(t *testing.T) { client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: "", Version: "v1"}}}) fakePodControl := controller.FakePodControl{} stopCh := make(chan struct{}) defer close(stopCh) manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas) manager.podControl = &fakePodControl received := make(chan string) manager.syncHandler = func(key string) error { received <- key return nil } // The DeletedFinalStateUnknown object should cause the ReplicaSet manager to insert // the controller matching the selectors of the deleted pod into the work queue. labelMap := map[string]string{"foo": "bar"} rsSpec := newReplicaSet(1, labelMap) informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rsSpec) pods := newPodList(nil, 1, v1.PodRunning, labelMap, rsSpec, "pod") manager.deletePod(cache.DeletedFinalStateUnknown{Key: "foo", Obj: &pods.Items[0]}) go manager.worker() expected := GetKey(rsSpec, t) select { case key := <-received: if key != expected { t.Errorf("Unexpected sync all for ReplicaSet %v, expected %v", key, expected) } case <-time.After(wait.ForeverTestTimeout): t.Errorf("Processing DeleteFinalStateUnknown took longer than expected") } } // Tell the rs to create 100 replicas, but simulate a limit (like a quota limit) // of 10, and verify that the rs doesn't make 100 create calls per sync pass func TestSyncReplicaSetCreateFailures(t *testing.T) { fakePodControl := controller.FakePodControl{} fakePodControl.CreateLimit = 10 labelMap := map[string]string{"foo": "bar"} rs := newReplicaSet(fakePodControl.CreateLimit*10, labelMap) client := fake.NewSimpleClientset(rs) stopCh := make(chan struct{}) defer close(stopCh) manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas) informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rs) manager.podControl = &fakePodControl manager.syncReplicaSet(GetKey(rs, t)) validateSyncReplicaSet(t, &fakePodControl, fakePodControl.CreateLimit, 0, 0) expectedLimit := 0 for pass := uint8(0); expectedLimit <= fakePodControl.CreateLimit; pass++ { expectedLimit += controller.SlowStartInitialBatchSize << pass } if fakePodControl.CreateCallCount > expectedLimit { t.Errorf("Unexpected number of create calls. Expected <= %d, saw %d\n", fakePodControl.CreateLimit*2, fakePodControl.CreateCallCount) } } func TestSyncReplicaSetDormancy(t *testing.T) { // Setup a test server so we can lie about the current state of pods fakeHandler := utiltesting.FakeHandler{ StatusCode: 200, ResponseBody: "{}", SkipRequestFn: skipListerFunc, T: t, } testServer := httptest.NewServer(&fakeHandler) defer testServer.Close() client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: "", Version: "v1"}}}) fakePodControl := controller.FakePodControl{} stopCh := make(chan struct{}) defer close(stopCh) manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas) manager.podControl = &fakePodControl labelMap := map[string]string{"foo": "bar"} rsSpec := newReplicaSet(2, labelMap) informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rsSpec) newPodList(informers.Core().V1().Pods().Informer().GetIndexer(), 1, v1.PodRunning, labelMap, rsSpec, "pod") // Creates a replica and sets expectations rsSpec.Status.Replicas = 1 rsSpec.Status.ReadyReplicas = 1 rsSpec.Status.AvailableReplicas = 1 manager.syncReplicaSet(GetKey(rsSpec, t)) validateSyncReplicaSet(t, &fakePodControl, 1, 0, 0) // Expectations prevents replicas but not an update on status rsSpec.Status.Replicas = 0 rsSpec.Status.ReadyReplicas = 0 rsSpec.Status.AvailableReplicas = 0 fakePodControl.Clear() manager.syncReplicaSet(GetKey(rsSpec, t)) validateSyncReplicaSet(t, &fakePodControl, 0, 0, 0) // Get the key for the controller rsKey, err := controller.KeyFunc(rsSpec) if err != nil { t.Errorf("Couldn't get key for object %#v: %v", rsSpec, err) } // Lowering expectations should lead to a sync that creates a replica, however the // fakePodControl error will prevent this, leaving expectations at 0, 0 manager.expectations.CreationObserved(rsKey) rsSpec.Status.Replicas = 1 rsSpec.Status.ReadyReplicas = 1 rsSpec.Status.AvailableReplicas = 1 fakePodControl.Clear() fakePodControl.Err = fmt.Errorf("Fake Error") manager.syncReplicaSet(GetKey(rsSpec, t)) validateSyncReplicaSet(t, &fakePodControl, 1, 0, 0) // This replica should not need a Lowering of expectations, since the previous create failed fakePodControl.Clear() fakePodControl.Err = nil manager.syncReplicaSet(GetKey(rsSpec, t)) validateSyncReplicaSet(t, &fakePodControl, 1, 0, 0) // 2 PUT for the ReplicaSet status during dormancy window. // Note that the pod creates go through pod control so they're not recorded. fakeHandler.ValidateRequestCount(t, 2) } func TestPodControllerLookup(t *testing.T) { stopCh := make(chan struct{}) defer close(stopCh) manager, informers := testNewReplicaSetControllerFromClient(clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: "", Version: "v1"}}}), stopCh, BurstReplicas) testCases := []struct { inRSs []*apps.ReplicaSet pod *v1.Pod outRSName string }{ // pods without labels don't match any ReplicaSets { inRSs: []*apps.ReplicaSet{ {ObjectMeta: metav1.ObjectMeta{Name: "basic"}}}, pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo1", Namespace: metav1.NamespaceAll}}, outRSName: "", }, // Matching labels, not namespace { inRSs: []*apps.ReplicaSet{ { ObjectMeta: metav1.ObjectMeta{Name: "foo"}, Spec: apps.ReplicaSetSpec{ Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}}, }, }, }, pod: &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: "foo2", Namespace: "ns", Labels: map[string]string{"foo": "bar"}}}, outRSName: "", }, // Matching ns and labels returns the key to the ReplicaSet, not the ReplicaSet name { inRSs: []*apps.ReplicaSet{ { ObjectMeta: metav1.ObjectMeta{Name: "bar", Namespace: "ns"}, Spec: apps.ReplicaSetSpec{ Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}}, }, }, }, pod: &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: "foo3", Namespace: "ns", Labels: map[string]string{"foo": "bar"}}}, outRSName: "bar", }, } for _, c := range testCases { for _, r := range c.inRSs { informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(r) } if rss := manager.getPodReplicaSets(c.pod); rss != nil { if len(rss) != 1 { t.Errorf("len(rss) = %v, want %v", len(rss), 1) continue } rs := rss[0] if c.outRSName != rs.Name { t.Errorf("Got replica set %+v expected %+v", rs.Name, c.outRSName) } } else if c.outRSName != "" { t.Errorf("Expected a replica set %v pod %v, found none", c.outRSName, c.pod.Name) } } } func TestWatchControllers(t *testing.T) { fakeWatch := watch.NewFake() client := fake.NewSimpleClientset() client.PrependWatchReactor("replicasets", core.DefaultWatchReactor(fakeWatch, nil)) stopCh := make(chan struct{}) defer close(stopCh) informers := informers.NewSharedInformerFactory(client, controller.NoResyncPeriodFunc()) manager := NewReplicaSetController( informers.Apps().V1().ReplicaSets(), informers.Core().V1().Pods(), client, BurstReplicas, ) informers.Start(stopCh) var testRSSpec apps.ReplicaSet received := make(chan string) // The update sent through the fakeWatcher should make its way into the workqueue, // and eventually into the syncHandler. The handler validates the received controller // and closes the received channel to indicate that the test can finish. manager.syncHandler = func(key string) error { obj, exists, err := informers.Apps().V1().ReplicaSets().Informer().GetIndexer().GetByKey(key) if !exists || err != nil { t.Errorf("Expected to find replica set under key %v", key) } rsSpec := *obj.(*apps.ReplicaSet) if !apiequality.Semantic.DeepDerivative(rsSpec, testRSSpec) { t.Errorf("Expected %#v, but got %#v", testRSSpec, rsSpec) } close(received) return nil } // Start only the ReplicaSet watcher and the workqueue, send a watch event, // and make sure it hits the sync method. go wait.Until(manager.worker, 10*time.Millisecond, stopCh) testRSSpec.Name = "foo" fakeWatch.Add(&testRSSpec) select { case <-received: case <-time.After(wait.ForeverTestTimeout): t.Errorf("unexpected timeout from result channel") } } func TestWatchPods(t *testing.T) { client := fake.NewSimpleClientset() fakeWatch := watch.NewFake() client.PrependWatchReactor("pods", core.DefaultWatchReactor(fakeWatch, nil)) stopCh := make(chan struct{}) defer close(stopCh) manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas) // Put one ReplicaSet into the shared informer labelMap := map[string]string{"foo": "bar"} testRSSpec := newReplicaSet(1, labelMap) informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(testRSSpec) received := make(chan string) // The pod update sent through the fakeWatcher should figure out the managing ReplicaSet and // send it into the syncHandler. manager.syncHandler = func(key string) error { namespace, name, err := cache.SplitMetaNamespaceKey(key) if err != nil { t.Errorf("Error splitting key: %v", err) } rsSpec, err := manager.rsLister.ReplicaSets(namespace).Get(name) if err != nil { t.Errorf("Expected to find replica set under key %v: %v", key, err) } if !apiequality.Semantic.DeepDerivative(rsSpec, testRSSpec) { t.Errorf("\nExpected %#v,\nbut got %#v", testRSSpec, rsSpec) } close(received) return nil } // Start only the pod watcher and the workqueue, send a watch event, // and make sure it hits the sync method for the right ReplicaSet. go informers.Core().V1().Pods().Informer().Run(stopCh) go manager.Run(1, stopCh) pods := newPodList(nil, 1, v1.PodRunning, labelMap, testRSSpec, "pod") testPod := pods.Items[0] testPod.Status.Phase = v1.PodFailed fakeWatch.Add(&testPod) select { case <-received: case <-time.After(wait.ForeverTestTimeout): t.Errorf("unexpected timeout from result channel") } } func TestUpdatePods(t *testing.T) { stopCh := make(chan struct{}) defer close(stopCh) manager, informers := testNewReplicaSetControllerFromClient(fake.NewSimpleClientset(), stopCh, BurstReplicas) received := make(chan string) manager.syncHandler = func(key string) error { namespace, name, err := cache.SplitMetaNamespaceKey(key) if err != nil { t.Errorf("Error splitting key: %v", err) } rsSpec, err := manager.rsLister.ReplicaSets(namespace).Get(name) if err != nil { t.Errorf("Expected to find replica set under key %v: %v", key, err) } received <- rsSpec.Name return nil } go wait.Until(manager.worker, 10*time.Millisecond, stopCh) // Put 2 ReplicaSets and one pod into the informers labelMap1 := map[string]string{"foo": "bar"} testRSSpec1 := newReplicaSet(1, labelMap1) informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(testRSSpec1) testRSSpec2 := *testRSSpec1 labelMap2 := map[string]string{"bar": "foo"} testRSSpec2.Spec.Selector = &metav1.LabelSelector{MatchLabels: labelMap2} testRSSpec2.Name = "barfoo" informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(&testRSSpec2) isController := true controllerRef1 := metav1.OwnerReference{UID: testRSSpec1.UID, APIVersion: "v1", Kind: "ReplicaSet", Name: testRSSpec1.Name, Controller: &isController} controllerRef2 := metav1.OwnerReference{UID: testRSSpec2.UID, APIVersion: "v1", Kind: "ReplicaSet", Name: testRSSpec2.Name, Controller: &isController} // case 1: Pod with a ControllerRef pod1 := newPodList(informers.Core().V1().Pods().Informer().GetIndexer(), 1, v1.PodRunning, labelMap1, testRSSpec1, "pod").Items[0] pod1.OwnerReferences = []metav1.OwnerReference{controllerRef1} pod1.ResourceVersion = "1" pod2 := pod1 pod2.Labels = labelMap2 pod2.ResourceVersion = "2" manager.updatePod(&pod1, &pod2) expected := sets.NewString(testRSSpec1.Name) for _, name := range expected.List() { t.Logf("Expecting update for %+v", name) select { case got := <-received: if !expected.Has(got) { t.Errorf("Expected keys %#v got %v", expected, got) } case <-time.After(wait.ForeverTestTimeout): t.Errorf("Expected update notifications for replica sets") } } // case 2: Remove ControllerRef (orphan). Expect to sync label-matching RS. pod1 = newPodList(informers.Core().V1().Pods().Informer().GetIndexer(), 1, v1.PodRunning, labelMap1, testRSSpec1, "pod").Items[0] pod1.ResourceVersion = "1" pod1.Labels = labelMap2 pod1.OwnerReferences = []metav1.OwnerReference{controllerRef2} pod2 = pod1 pod2.OwnerReferences = nil pod2.ResourceVersion = "2" manager.updatePod(&pod1, &pod2) expected = sets.NewString(testRSSpec2.Name) for _, name := range expected.List() { t.Logf("Expecting update for %+v", name) select { case got := <-received: if !expected.Has(got) { t.Errorf("Expected keys %#v got %v", expected, got) } case <-time.After(wait.ForeverTestTimeout): t.Errorf("Expected update notifications for replica sets") } } // case 2: Remove ControllerRef (orphan). Expect to sync both former owner and // any label-matching RS. pod1 = newPodList(informers.Core().V1().Pods().Informer().GetIndexer(), 1, v1.PodRunning, labelMap1, testRSSpec1, "pod").Items[0] pod1.ResourceVersion = "1" pod1.Labels = labelMap2 pod1.OwnerReferences = []metav1.OwnerReference{controllerRef1} pod2 = pod1 pod2.OwnerReferences = nil pod2.ResourceVersion = "2" manager.updatePod(&pod1, &pod2) expected = sets.NewString(testRSSpec1.Name, testRSSpec2.Name) for _, name := range expected.List() { t.Logf("Expecting update for %+v", name) select { case got := <-received: if !expected.Has(got) { t.Errorf("Expected keys %#v got %v", expected, got) } case <-time.After(wait.ForeverTestTimeout): t.Errorf("Expected update notifications for replica sets") } } // case 4: Keep ControllerRef, change labels. Expect to sync owning RS. pod1 = newPodList(informers.Core().V1().Pods().Informer().GetIndexer(), 1, v1.PodRunning, labelMap1, testRSSpec1, "pod").Items[0] pod1.ResourceVersion = "1" pod1.Labels = labelMap1 pod1.OwnerReferences = []metav1.OwnerReference{controllerRef2} pod2 = pod1 pod2.Labels = labelMap2 pod2.ResourceVersion = "2" manager.updatePod(&pod1, &pod2) expected = sets.NewString(testRSSpec2.Name) for _, name := range expected.List() { t.Logf("Expecting update for %+v", name) select { case got := <-received: if !expected.Has(got) { t.Errorf("Expected keys %#v got %v", expected, got) } case <-time.After(wait.ForeverTestTimeout): t.Errorf("Expected update notifications for replica sets") } } } func TestControllerUpdateRequeue(t *testing.T) { // This server should force a requeue of the controller because it fails to update status.Replicas. labelMap := map[string]string{"foo": "bar"} rs := newReplicaSet(1, labelMap) client := fake.NewSimpleClientset(rs) client.PrependReactor("update", "replicasets", func(action core.Action) (bool, runtime.Object, error) { if action.GetSubresource() != "status" { return false, nil, nil } return true, nil, errors.New("failed to update status") }) stopCh := make(chan struct{}) defer close(stopCh) manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas) informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rs) rs.Status = apps.ReplicaSetStatus{Replicas: 2} newPodList(informers.Core().V1().Pods().Informer().GetIndexer(), 1, v1.PodRunning, labelMap, rs, "pod") fakePodControl := controller.FakePodControl{} manager.podControl = &fakePodControl // Enqueue once. Then process it. Disable rate-limiting for this. manager.queue = workqueue.NewRateLimitingQueue(workqueue.NewMaxOfRateLimiter()) manager.enqueueReplicaSet(rs) manager.processNextWorkItem() // It should have been requeued. if got, want := manager.queue.Len(), 1; got != want { t.Errorf("queue.Len() = %v, want %v", got, want) } } func TestControllerUpdateStatusWithFailure(t *testing.T) { rs := newReplicaSet(1, map[string]string{"foo": "bar"}) fakeClient := &fake.Clientset{} fakeClient.AddReactor("get", "replicasets", func(action core.Action) (bool, runtime.Object, error) { return true, rs, nil }) fakeClient.AddReactor("*", "*", func(action core.Action) (bool, runtime.Object, error) { return true, &apps.ReplicaSet{}, fmt.Errorf("Fake error") }) fakeRSClient := fakeClient.Apps().ReplicaSets("default") numReplicas := int32(10) newStatus := apps.ReplicaSetStatus{Replicas: numReplicas} updateReplicaSetStatus(fakeRSClient, rs, newStatus) updates, gets := 0, 0 for _, a := range fakeClient.Actions() { if a.GetResource().Resource != "replicasets" { t.Errorf("Unexpected action %+v", a) continue } switch action := a.(type) { case core.GetAction: gets++ // Make sure the get is for the right ReplicaSet even though the update failed. if action.GetName() != rs.Name { t.Errorf("Expected get for ReplicaSet %v, got %+v instead", rs.Name, action.GetName()) } case core.UpdateAction: updates++ // Confirm that the update has the right status.Replicas even though the Get // returned a ReplicaSet with replicas=1. if c, ok := action.GetObject().(*apps.ReplicaSet); !ok { t.Errorf("Expected a ReplicaSet as the argument to update, got %T", c) } else if c.Status.Replicas != numReplicas { t.Errorf("Expected update for ReplicaSet to contain replicas %v, got %v instead", numReplicas, c.Status.Replicas) } default: t.Errorf("Unexpected action %+v", a) break } } if gets != 1 || updates != 2 { t.Errorf("Expected 1 get and 2 updates, got %d gets %d updates", gets, updates) } } // TODO: This test is too hairy for a unittest. It should be moved to an E2E suite. func doTestControllerBurstReplicas(t *testing.T, burstReplicas, numReplicas int) { labelMap := map[string]string{"foo": "bar"} rsSpec := newReplicaSet(numReplicas, labelMap) client := fake.NewSimpleClientset(rsSpec) fakePodControl := controller.FakePodControl{} stopCh := make(chan struct{}) defer close(stopCh) manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, burstReplicas) manager.podControl = &fakePodControl informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rsSpec) expectedPods := int32(0) pods := newPodList(nil, numReplicas, v1.PodPending, labelMap, rsSpec, "pod") rsKey, err := controller.KeyFunc(rsSpec) if err != nil { t.Errorf("Couldn't get key for object %#v: %v", rsSpec, err) } // Size up the controller, then size it down, and confirm the expected create/delete pattern for _, replicas := range []int32{int32(numReplicas), 0} { *(rsSpec.Spec.Replicas) = replicas informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rsSpec) for i := 0; i < numReplicas; i += burstReplicas { manager.syncReplicaSet(GetKey(rsSpec, t)) // The store accrues active pods. It's also used by the ReplicaSet to determine how many // replicas to create. activePods := int32(len(informers.Core().V1().Pods().Informer().GetIndexer().List())) if replicas != 0 { // This is the number of pods currently "in flight". They were created by the // ReplicaSet controller above, which then puts the ReplicaSet to sleep till // all of them have been observed. expectedPods = replicas - activePods if expectedPods > int32(burstReplicas) { expectedPods = int32(burstReplicas) } // This validates the ReplicaSet manager sync actually created pods validateSyncReplicaSet(t, &fakePodControl, int(expectedPods), 0, 0) // This simulates the watch events for all but 1 of the expected pods. // None of these should wake the controller because it has expectations==BurstReplicas. for i := int32(0); i < expectedPods-1; i++ { informers.Core().V1().Pods().Informer().GetIndexer().Add(&pods.Items[i]) manager.addPod(&pods.Items[i]) } podExp, exists, err := manager.expectations.GetExpectations(rsKey) if !exists || err != nil { t.Fatalf("Did not find expectations for rs.") } if add, _ := podExp.GetExpectations(); add != 1 { t.Fatalf("Expectations are wrong %v", podExp) } } else { expectedPods = (replicas - activePods) * -1 if expectedPods > int32(burstReplicas) { expectedPods = int32(burstReplicas) } validateSyncReplicaSet(t, &fakePodControl, 0, int(expectedPods), 0) // To accurately simulate a watch we must delete the exact pods // the rs is waiting for. expectedDels := manager.expectations.GetUIDs(GetKey(rsSpec, t)) podsToDelete := []*v1.Pod{} isController := true for _, key := range expectedDels.List() { nsName := strings.Split(key, "/") podsToDelete = append(podsToDelete, &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: nsName[1], Namespace: nsName[0], Labels: rsSpec.Spec.Selector.MatchLabels, OwnerReferences: []metav1.OwnerReference{ {UID: rsSpec.UID, APIVersion: "v1", Kind: "ReplicaSet", Name: rsSpec.Name, Controller: &isController}, }, }, }) } // Don't delete all pods because we confirm that the last pod // has exactly one expectation at the end, to verify that we // don't double delete. for i := range podsToDelete[1:] { informers.Core().V1().Pods().Informer().GetIndexer().Delete(podsToDelete[i]) manager.deletePod(podsToDelete[i]) } podExp, exists, err := manager.expectations.GetExpectations(rsKey) if !exists || err != nil { t.Fatalf("Did not find expectations for ReplicaSet.") } if _, del := podExp.GetExpectations(); del != 1 { t.Fatalf("Expectations are wrong %v", podExp) } } // Check that the ReplicaSet didn't take any action for all the above pods fakePodControl.Clear() manager.syncReplicaSet(GetKey(rsSpec, t)) validateSyncReplicaSet(t, &fakePodControl, 0, 0, 0) // Create/Delete the last pod // The last add pod will decrease the expectation of the ReplicaSet to 0, // which will cause it to create/delete the remaining replicas up to burstReplicas. if replicas != 0 { informers.Core().V1().Pods().Informer().GetIndexer().Add(&pods.Items[expectedPods-1]) manager.addPod(&pods.Items[expectedPods-1]) } else { expectedDel := manager.expectations.GetUIDs(GetKey(rsSpec, t)) if expectedDel.Len() != 1 { t.Fatalf("Waiting on unexpected number of deletes.") } nsName := strings.Split(expectedDel.List()[0], "/") isController := true lastPod := &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: nsName[1], Namespace: nsName[0], Labels: rsSpec.Spec.Selector.MatchLabels, OwnerReferences: []metav1.OwnerReference{ {UID: rsSpec.UID, APIVersion: "v1", Kind: "ReplicaSet", Name: rsSpec.Name, Controller: &isController}, }, }, } informers.Core().V1().Pods().Informer().GetIndexer().Delete(lastPod) manager.deletePod(lastPod) } pods.Items = pods.Items[expectedPods:] } // Confirm that we've created the right number of replicas activePods := int32(len(informers.Core().V1().Pods().Informer().GetIndexer().List())) if activePods != *(rsSpec.Spec.Replicas) { t.Fatalf("Unexpected number of active pods, expected %d, got %d", *(rsSpec.Spec.Replicas), activePods) } // Replenish the pod list, since we cut it down sizing up pods = newPodList(nil, int(replicas), v1.PodRunning, labelMap, rsSpec, "pod") } } func TestControllerBurstReplicas(t *testing.T) { doTestControllerBurstReplicas(t, 5, 30) doTestControllerBurstReplicas(t, 5, 12) doTestControllerBurstReplicas(t, 3, 2) } type FakeRSExpectations struct { *controller.ControllerExpectations satisfied bool expSatisfied func() } func (fe FakeRSExpectations) SatisfiedExpectations(controllerKey string) bool { fe.expSatisfied() return fe.satisfied } // TestRSSyncExpectations tests that a pod cannot sneak in between counting active pods // and checking expectations. func TestRSSyncExpectations(t *testing.T) { client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: "", Version: "v1"}}}) fakePodControl := controller.FakePodControl{} stopCh := make(chan struct{}) defer close(stopCh) manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, 2) manager.podControl = &fakePodControl labelMap := map[string]string{"foo": "bar"} rsSpec := newReplicaSet(2, labelMap) informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rsSpec) pods := newPodList(nil, 2, v1.PodPending, labelMap, rsSpec, "pod") informers.Core().V1().Pods().Informer().GetIndexer().Add(&pods.Items[0]) postExpectationsPod := pods.Items[1] manager.expectations = controller.NewUIDTrackingControllerExpectations(FakeRSExpectations{ controller.NewControllerExpectations(), true, func() { // If we check active pods before checking expectataions, the // ReplicaSet will create a new replica because it doesn't see // this pod, but has fulfilled its expectations. informers.Core().V1().Pods().Informer().GetIndexer().Add(&postExpectationsPod) }, }) manager.syncReplicaSet(GetKey(rsSpec, t)) validateSyncReplicaSet(t, &fakePodControl, 0, 0, 0) } func TestDeleteControllerAndExpectations(t *testing.T) { rs := newReplicaSet(1, map[string]string{"foo": "bar"}) client := fake.NewSimpleClientset(rs) stopCh := make(chan struct{}) defer close(stopCh) manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, 10) informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rs) fakePodControl := controller.FakePodControl{} manager.podControl = &fakePodControl // This should set expectations for the ReplicaSet manager.syncReplicaSet(GetKey(rs, t)) validateSyncReplicaSet(t, &fakePodControl, 1, 0, 0) fakePodControl.Clear() // Get the ReplicaSet key rsKey, err := controller.KeyFunc(rs) if err != nil { t.Errorf("Couldn't get key for object %#v: %v", rs, err) } // This is to simulate a concurrent addPod, that has a handle on the expectations // as the controller deletes it. podExp, exists, err := manager.expectations.GetExpectations(rsKey) if !exists || err != nil { t.Errorf("No expectations found for ReplicaSet") } informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Delete(rs) manager.syncReplicaSet(GetKey(rs, t)) if _, exists, err = manager.expectations.GetExpectations(rsKey); exists { t.Errorf("Found expectaions, expected none since the ReplicaSet has been deleted.") } // This should have no effect, since we've deleted the ReplicaSet. podExp.Add(-1, 0) informers.Core().V1().Pods().Informer().GetIndexer().Replace(make([]interface{}, 0), "0") manager.syncReplicaSet(GetKey(rs, t)) validateSyncReplicaSet(t, &fakePodControl, 0, 0, 0) } // shuffle returns a new shuffled list of container controllers. func shuffle(controllers []*apps.ReplicaSet) []*apps.ReplicaSet { numControllers := len(controllers) randIndexes := rand.Perm(numControllers) shuffled := make([]*apps.ReplicaSet, numControllers) for i := 0; i < numControllers; i++ { shuffled[i] = controllers[randIndexes[i]] } return shuffled } func TestOverlappingRSs(t *testing.T) { client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: "", Version: "v1"}}}) labelMap := map[string]string{"foo": "bar"} stopCh := make(chan struct{}) defer close(stopCh) manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, 10) // Create 10 ReplicaSets, shuffled them randomly and insert them into the // ReplicaSet controller's store. // All use the same CreationTimestamp since ControllerRef should be able // to handle that. timestamp := metav1.Date(2014, time.December, 0, 0, 0, 0, 0, time.Local) var controllers []*apps.ReplicaSet for j := 1; j < 10; j++ { rsSpec := newReplicaSet(1, labelMap) rsSpec.CreationTimestamp = timestamp rsSpec.Name = fmt.Sprintf("rs%d", j) controllers = append(controllers, rsSpec) } shuffledControllers := shuffle(controllers) for j := range shuffledControllers { informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(shuffledControllers[j]) } // Add a pod with a ControllerRef and make sure only the corresponding // ReplicaSet is synced. Pick a RS in the middle since the old code used to // sort by name if all timestamps were equal. rs := controllers[3] pods := newPodList(nil, 1, v1.PodPending, labelMap, rs, "pod") pod := &pods.Items[0] isController := true pod.OwnerReferences = []metav1.OwnerReference{ {UID: rs.UID, APIVersion: "v1", Kind: "ReplicaSet", Name: rs.Name, Controller: &isController}, } rsKey := GetKey(rs, t) manager.addPod(pod) queueRS, _ := manager.queue.Get() if queueRS != rsKey { t.Fatalf("Expected to find key %v in queue, found %v", rsKey, queueRS) } } func TestDeletionTimestamp(t *testing.T) { c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: "", Version: "v1"}}}) labelMap := map[string]string{"foo": "bar"} stopCh := make(chan struct{}) defer close(stopCh) manager, informers := testNewReplicaSetControllerFromClient(c, stopCh, 10) rs := newReplicaSet(1, labelMap) informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rs) rsKey, err := controller.KeyFunc(rs) if err != nil { t.Errorf("Couldn't get key for object %#v: %v", rs, err) } pod := newPodList(nil, 1, v1.PodPending, labelMap, rs, "pod").Items[0] pod.DeletionTimestamp = &metav1.Time{Time: time.Now()} pod.ResourceVersion = "1" manager.expectations.ExpectDeletions(rsKey, []string{controller.PodKey(&pod)}) // A pod added with a deletion timestamp should decrement deletions, not creations. manager.addPod(&pod) queueRS, _ := manager.queue.Get() if queueRS != rsKey { t.Fatalf("Expected to find key %v in queue, found %v", rsKey, queueRS) } manager.queue.Done(rsKey) podExp, exists, err := manager.expectations.GetExpectations(rsKey) if !exists || err != nil || !podExp.Fulfilled() { t.Fatalf("Wrong expectations %#v", podExp) } // An update from no deletion timestamp to having one should be treated // as a deletion. oldPod := newPodList(nil, 1, v1.PodPending, labelMap, rs, "pod").Items[0] oldPod.ResourceVersion = "2" manager.expectations.ExpectDeletions(rsKey, []string{controller.PodKey(&pod)}) manager.updatePod(&oldPod, &pod) queueRS, _ = manager.queue.Get() if queueRS != rsKey { t.Fatalf("Expected to find key %v in queue, found %v", rsKey, queueRS) } manager.queue.Done(rsKey) podExp, exists, err = manager.expectations.GetExpectations(rsKey) if !exists || err != nil || !podExp.Fulfilled() { t.Fatalf("Wrong expectations %#v", podExp) } // An update to the pod (including an update to the deletion timestamp) // should not be counted as a second delete. isController := true secondPod := &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Namespace: pod.Namespace, Name: "secondPod", Labels: pod.Labels, OwnerReferences: []metav1.OwnerReference{ {UID: rs.UID, APIVersion: "v1", Kind: "ReplicaSet", Name: rs.Name, Controller: &isController}, }, }, } manager.expectations.ExpectDeletions(rsKey, []string{controller.PodKey(secondPod)}) oldPod.DeletionTimestamp = &metav1.Time{Time: time.Now()} oldPod.ResourceVersion = "2" manager.updatePod(&oldPod, &pod) podExp, exists, err = manager.expectations.GetExpectations(rsKey) if !exists || err != nil || podExp.Fulfilled() { t.Fatalf("Wrong expectations %#v", podExp) } // A pod with a non-nil deletion timestamp should also be ignored by the // delete handler, because it's already been counted in the update. manager.deletePod(&pod) podExp, exists, err = manager.expectations.GetExpectations(rsKey) if !exists || err != nil || podExp.Fulfilled() { t.Fatalf("Wrong expectations %#v", podExp) } // Deleting the second pod should clear expectations. manager.deletePod(secondPod) queueRS, _ = manager.queue.Get() if queueRS != rsKey { t.Fatalf("Expected to find key %v in queue, found %v", rsKey, queueRS) } manager.queue.Done(rsKey) podExp, exists, err = manager.expectations.GetExpectations(rsKey) if !exists || err != nil || !podExp.Fulfilled() { t.Fatalf("Wrong expectations %#v", podExp) } } // setupManagerWithGCEnabled creates a RS manager with a fakePodControl func setupManagerWithGCEnabled(stopCh chan struct{}, objs ...runtime.Object) (manager *ReplicaSetController, fakePodControl *controller.FakePodControl, informers informers.SharedInformerFactory) { c := fake.NewSimpleClientset(objs...) fakePodControl = &controller.FakePodControl{} manager, informers = testNewReplicaSetControllerFromClient(c, stopCh, BurstReplicas) manager.podControl = fakePodControl return manager, fakePodControl, informers } func TestDoNotPatchPodWithOtherControlRef(t *testing.T) { labelMap := map[string]string{"foo": "bar"} rs := newReplicaSet(2, labelMap) stopCh := make(chan struct{}) defer close(stopCh) manager, fakePodControl, informers := setupManagerWithGCEnabled(stopCh, rs) informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rs) var trueVar = true otherControllerReference := metav1.OwnerReference{UID: uuid.NewUUID(), APIVersion: "v1beta1", Kind: "ReplicaSet", Name: "AnotherRS", Controller: &trueVar} // add to podLister a matching Pod controlled by another controller. Expect no patch. pod := newPod("pod", rs, v1.PodRunning, nil, true) pod.OwnerReferences = []metav1.OwnerReference{otherControllerReference} informers.Core().V1().Pods().Informer().GetIndexer().Add(pod) err := manager.syncReplicaSet(GetKey(rs, t)) if err != nil { t.Fatal(err) } // because the matching pod already has a controller, so 2 pods should be created. validateSyncReplicaSet(t, fakePodControl, 2, 0, 0) } func TestPatchPodFails(t *testing.T) { labelMap := map[string]string{"foo": "bar"} rs := newReplicaSet(2, labelMap) stopCh := make(chan struct{}) defer close(stopCh) manager, fakePodControl, informers := setupManagerWithGCEnabled(stopCh, rs) informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rs) // add to podLister two matching pods. Expect two patches to take control // them. informers.Core().V1().Pods().Informer().GetIndexer().Add(newPod("pod1", rs, v1.PodRunning, nil, false)) informers.Core().V1().Pods().Informer().GetIndexer().Add(newPod("pod2", rs, v1.PodRunning, nil, false)) // let both patches fail. The rs controller will assume it fails to take // control of the pods and requeue to try again. fakePodControl.Err = fmt.Errorf("Fake Error") rsKey := GetKey(rs, t) err := processSync(manager, rsKey) if err == nil || !strings.Contains(err.Error(), "Fake Error") { t.Errorf("expected Fake Error, got %+v", err) } // 2 patches to take control of pod1 and pod2 (both fail). validateSyncReplicaSet(t, fakePodControl, 0, 0, 2) // RS should requeue itself. queueRS, _ := manager.queue.Get() if queueRS != rsKey { t.Fatalf("Expected to find key %v in queue, found %v", rsKey, queueRS) } } // RS controller shouldn't adopt or create more pods if the rc is about to be // deleted. func TestDoNotAdoptOrCreateIfBeingDeleted(t *testing.T) { labelMap := map[string]string{"foo": "bar"} rs := newReplicaSet(2, labelMap) now := metav1.Now() rs.DeletionTimestamp = &now stopCh := make(chan struct{}) defer close(stopCh) manager, fakePodControl, informers := setupManagerWithGCEnabled(stopCh, rs) informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rs) pod1 := newPod("pod1", rs, v1.PodRunning, nil, false) informers.Core().V1().Pods().Informer().GetIndexer().Add(pod1) // no patch, no create err := manager.syncReplicaSet(GetKey(rs, t)) if err != nil { t.Fatal(err) } validateSyncReplicaSet(t, fakePodControl, 0, 0, 0) } func TestDoNotAdoptOrCreateIfBeingDeletedRace(t *testing.T) { labelMap := map[string]string{"foo": "bar"} // Bare client says it IS deleted. rs := newReplicaSet(2, labelMap) now := metav1.Now() rs.DeletionTimestamp = &now stopCh := make(chan struct{}) defer close(stopCh) manager, fakePodControl, informers := setupManagerWithGCEnabled(stopCh, rs) // Lister (cache) says it's NOT deleted. rs2 := *rs rs2.DeletionTimestamp = nil informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(&rs2) // Recheck occurs if a matching orphan is present. pod1 := newPod("pod1", rs, v1.PodRunning, nil, false) informers.Core().V1().Pods().Informer().GetIndexer().Add(pod1) // sync should abort. err := manager.syncReplicaSet(GetKey(rs, t)) if err == nil { t.Error("syncReplicaSet() err = nil, expected non-nil") } // no patch, no create. validateSyncReplicaSet(t, fakePodControl, 0, 0, 0) } var ( imagePullBackOff apps.ReplicaSetConditionType = "ImagePullBackOff" condImagePullBackOff = func() apps.ReplicaSetCondition { return apps.ReplicaSetCondition{ Type: imagePullBackOff, Status: v1.ConditionTrue, Reason: "NonExistentImage", } } condReplicaFailure = func() apps.ReplicaSetCondition { return apps.ReplicaSetCondition{ Type: apps.ReplicaSetReplicaFailure, Status: v1.ConditionTrue, Reason: "OtherFailure", } } condReplicaFailure2 = func() apps.ReplicaSetCondition { return apps.ReplicaSetCondition{ Type: apps.ReplicaSetReplicaFailure, Status: v1.ConditionTrue, Reason: "AnotherFailure", } } status = func() *apps.ReplicaSetStatus { return &apps.ReplicaSetStatus{ Conditions: []apps.ReplicaSetCondition{condReplicaFailure()}, } } ) func TestGetCondition(t *testing.T) { exampleStatus := status() tests := []struct { name string status apps.ReplicaSetStatus condType apps.ReplicaSetConditionType condStatus v1.ConditionStatus condReason string expected bool }{ { name: "condition exists", status: *exampleStatus, condType: apps.ReplicaSetReplicaFailure, expected: true, }, { name: "condition does not exist", status: *exampleStatus, condType: imagePullBackOff, expected: false, }, } for _, test := range tests { cond := GetCondition(test.status, test.condType) exists := cond != nil if exists != test.expected { t.Errorf("%s: expected condition to exist: %t, got: %t", test.name, test.expected, exists) } } } func TestSetCondition(t *testing.T) { tests := []struct { name string status *apps.ReplicaSetStatus cond apps.ReplicaSetCondition expectedStatus *apps.ReplicaSetStatus }{ { name: "set for the first time", status: &apps.ReplicaSetStatus{}, cond: condReplicaFailure(), expectedStatus: &apps.ReplicaSetStatus{Conditions: []apps.ReplicaSetCondition{condReplicaFailure()}}, }, { name: "simple set", status: &apps.ReplicaSetStatus{Conditions: []apps.ReplicaSetCondition{condImagePullBackOff()}}, cond: condReplicaFailure(), expectedStatus: &apps.ReplicaSetStatus{Conditions: []apps.ReplicaSetCondition{condImagePullBackOff(), condReplicaFailure()}}, }, { name: "overwrite", status: &apps.ReplicaSetStatus{Conditions: []apps.ReplicaSetCondition{condReplicaFailure()}}, cond: condReplicaFailure2(), expectedStatus: &apps.ReplicaSetStatus{Conditions: []apps.ReplicaSetCondition{condReplicaFailure2()}}, }, } for _, test := range tests { SetCondition(test.status, test.cond) if !reflect.DeepEqual(test.status, test.expectedStatus) { t.Errorf("%s: expected status: %v, got: %v", test.name, test.expectedStatus, test.status) } } } func TestRemoveCondition(t *testing.T) { tests := []struct { name string status *apps.ReplicaSetStatus condType apps.ReplicaSetConditionType expectedStatus *apps.ReplicaSetStatus }{ { name: "remove from empty status", status: &apps.ReplicaSetStatus{}, condType: apps.ReplicaSetReplicaFailure, expectedStatus: &apps.ReplicaSetStatus{}, }, { name: "simple remove", status: &apps.ReplicaSetStatus{Conditions: []apps.ReplicaSetCondition{condReplicaFailure()}}, condType: apps.ReplicaSetReplicaFailure, expectedStatus: &apps.ReplicaSetStatus{}, }, { name: "doesn't remove anything", status: status(), condType: imagePullBackOff, expectedStatus: status(), }, } for _, test := range tests { RemoveCondition(test.status, test.condType) if !reflect.DeepEqual(test.status, test.expectedStatus) { t.Errorf("%s: expected status: %v, got: %v", test.name, test.expectedStatus, test.status) } } } func TestSlowStartBatch(t *testing.T) { fakeErr := fmt.Errorf("fake error") callCnt := 0 callLimit := 0 var lock sync.Mutex fn := func() error { lock.Lock() defer lock.Unlock() callCnt++ if callCnt > callLimit { return fakeErr } return nil } tests := []struct { name string count int callLimit int fn func() error expectedSuccesses int expectedErr error expectedCallCnt int }{ { name: "callLimit = 0 (all fail)", count: 10, callLimit: 0, fn: fn, expectedSuccesses: 0, expectedErr: fakeErr, expectedCallCnt: 1, // 1(first batch): function will be called at least once }, { name: "callLimit = count (all succeed)", count: 10, callLimit: 10, fn: fn, expectedSuccesses: 10, expectedErr: nil, expectedCallCnt: 10, // 1(first batch) + 2(2nd batch) + 4(3rd batch) + 3(4th batch) = 10 }, { name: "callLimit < count (some succeed)", count: 10, callLimit: 5, fn: fn, expectedSuccesses: 5, expectedErr: fakeErr, expectedCallCnt: 7, // 1(first batch) + 2(2nd batch) + 4(3rd batch) = 7 }, } for _, test := range tests { callCnt = 0 callLimit = test.callLimit successes, err := slowStartBatch(test.count, 1, test.fn) if successes != test.expectedSuccesses { t.Errorf("%s: unexpected processed batch size, expected %d, got %d", test.name, test.expectedSuccesses, successes) } if err != test.expectedErr { t.Errorf("%s: unexpected processed batch size, expected %v, got %v", test.name, test.expectedErr, err) } // verify that slowStartBatch stops trying more calls after a batch fails if callCnt != test.expectedCallCnt { t.Errorf("%s: slowStartBatch() still tries calls after a batch fails, expected %d calls, got %d", test.name, test.expectedCallCnt, callCnt) } } } func TestGetPodsToDelete(t *testing.T) { labelMap := map[string]string{"name": "foo"} rs := newReplicaSet(1, labelMap) // an unscheduled, pending pod unscheduledPendingPod := newPod("unscheduled-pending-pod", rs, v1.PodPending, nil, true) // a scheduled, pending pod scheduledPendingPod := newPod("scheduled-pending-pod", rs, v1.PodPending, nil, true) scheduledPendingPod.Spec.NodeName = "fake-node" // a scheduled, running, not-ready pod scheduledRunningNotReadyPod := newPod("scheduled-running-not-ready-pod", rs, v1.PodRunning, nil, true) scheduledRunningNotReadyPod.Spec.NodeName = "fake-node" scheduledRunningNotReadyPod.Status.Conditions = []v1.PodCondition{ { Type: v1.PodReady, Status: v1.ConditionFalse, }, } // a scheduled, running, ready pod scheduledRunningReadyPod := newPod("scheduled-running-ready-pod", rs, v1.PodRunning, nil, true) scheduledRunningReadyPod.Spec.NodeName = "fake-node" scheduledRunningReadyPod.Status.Conditions = []v1.PodCondition{ { Type: v1.PodReady, Status: v1.ConditionTrue, }, } tests := []struct { name string pods []*v1.Pod diff int expectedPodsToDelete []*v1.Pod }{ // Order used when selecting pods for deletion: // an unscheduled, pending pod // a scheduled, pending pod // a scheduled, running, not-ready pod // a scheduled, running, ready pod // Note that a pending pod cannot be ready { "len(pods) = 0 (i.e., diff = 0 too)", []*v1.Pod{}, 0, []*v1.Pod{}, }, { "diff = len(pods)", []*v1.Pod{ scheduledRunningNotReadyPod, scheduledRunningReadyPod, }, 2, []*v1.Pod{scheduledRunningNotReadyPod, scheduledRunningReadyPod}, }, { "diff < len(pods)", []*v1.Pod{ scheduledRunningReadyPod, scheduledRunningNotReadyPod, }, 1, []*v1.Pod{scheduledRunningNotReadyPod}, }, { "various pod phases and conditions, diff = len(pods)", []*v1.Pod{ scheduledRunningReadyPod, scheduledRunningNotReadyPod, scheduledPendingPod, unscheduledPendingPod, }, 4, []*v1.Pod{ scheduledRunningReadyPod, scheduledRunningNotReadyPod, scheduledPendingPod, unscheduledPendingPod, }, }, { "scheduled vs unscheduled, diff < len(pods)", []*v1.Pod{ scheduledPendingPod, unscheduledPendingPod, }, 1, []*v1.Pod{ unscheduledPendingPod, }, }, { "ready vs not-ready, diff < len(pods)", []*v1.Pod{ scheduledRunningReadyPod, scheduledRunningNotReadyPod, scheduledRunningNotReadyPod, }, 2, []*v1.Pod{ scheduledRunningNotReadyPod, scheduledRunningNotReadyPod, }, }, { "pending vs running, diff < len(pods)", []*v1.Pod{ scheduledPendingPod, scheduledRunningNotReadyPod, }, 1, []*v1.Pod{ scheduledPendingPod, }, }, { "various pod phases and conditions, diff < len(pods)", []*v1.Pod{ scheduledRunningReadyPod, scheduledRunningNotReadyPod, scheduledPendingPod, unscheduledPendingPod, }, 3, []*v1.Pod{ unscheduledPendingPod, scheduledPendingPod, scheduledRunningNotReadyPod, }, }, } for _, test := range tests { podsToDelete := getPodsToDelete(test.pods, test.diff) if len(podsToDelete) != len(test.expectedPodsToDelete) { t.Errorf("%s: unexpected pods to delete, expected %v, got %v", test.name, test.expectedPodsToDelete, podsToDelete) } if !reflect.DeepEqual(podsToDelete, test.expectedPodsToDelete) { t.Errorf("%s: unexpected pods to delete, expected %v, got %v", test.name, test.expectedPodsToDelete, podsToDelete) } } } func TestGetPodKeys(t *testing.T) { labelMap := map[string]string{"name": "foo"} rs := newReplicaSet(1, labelMap) pod1 := newPod("pod1", rs, v1.PodRunning, nil, true) pod2 := newPod("pod2", rs, v1.PodRunning, nil, true) tests := []struct { name string pods []*v1.Pod expectedPodKeys []string }{ { "len(pods) = 0 (i.e., pods = nil)", []*v1.Pod{}, []string{}, }, { "len(pods) > 0", []*v1.Pod{ pod1, pod2, }, []string{"default/pod1", "default/pod2"}, }, } for _, test := range tests { podKeys := getPodKeys(test.pods) if len(podKeys) != len(test.expectedPodKeys) { t.Errorf("%s: unexpected keys for pods to delete, expected %v, got %v", test.name, test.expectedPodKeys, podKeys) } for i := 0; i < len(podKeys); i++ { if podKeys[i] != test.expectedPodKeys[i] { t.Errorf("%s: unexpected keys for pods to delete, expected %v, got %v", test.name, test.expectedPodKeys, podKeys) } } } }
newPod
GlobalStyle.ts
import { createGlobalStyle } from 'styled-components' import olympic from 'src/assets/fonts/olympic-branding.ttf' import cocogoose from 'src/assets/fonts/cocogoose.otf' const GlobalStyle = createGlobalStyle` @font-face { font-family: "olympic"; src: url(${olympic}); url(${olympic}) format("ttf") } @font-face { font-family: "cocogoose"; src: url(${cocogoose}); url(${cocogoose}) format("ttf") } @import url('https://fonts.googleapis.com/css?family=Varela+Round&display=swap'); dl,h1,h2,h3,h4,h5,h6,ol,p,pre,ul{margin-top:0}address,dl,ol,p,pre,ul{margin-bottom:1rem}body,caption{text-align:left}button,hr,input{overflow:visible}pre,textarea{overflow:auto}div{display:flex}article,aside,dialog,figcaption,figure,footer,header,hgroup,legend,main,nav,section{display:block}dd,h1,h2,h3,h4,h5,h6,label,legend{margin-bottom:0}address,legend{line-height:inherit}progress,sub,sup{vertical-align:baseline}label,output{display:inline-block}*,::after,::before{box-sizing:border-box}html{font-family:sans-serif;line-height:1.15;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;-ms-overflow-style:scrollbar;-webkit-tap-highlight-color:transparent}@-ms-viewport{width:device-width}body{margin:0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif,'Apple Color Emoji','Segoe UI Emoji','Segoe UI Symbol';font-size:1rem;font-weight:400;line-height:1.5;color:#212529;background-color:#fff}[tabindex='-1']:focus{outline:0!important}hr{box-sizing:content-box;height:0}abbr[data-original-title],abbr[title]{-webkit-text-decoration:none dotted;text-decoration:none dotted;cursor:help;border-bottom:0}address{font-style:normal}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-left:0}blockquote,figure{margin:0 0 1rem}dfn{font-style:italic}b,strong{font-weight:bolder}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0}sub{bottom:-.25em}sup{top:-.5em}a{color:#222;text-decoration:none;background-color:transparent;-webkit-text-decoration-skip:objects}a:hover{text-decoration:none}a:not([href]):not([tabindex]),a:not([href]):not([tabindex]):focus,a:not([href]):not([tabindex]):hover{text-decoration:none}a:not([href]):not([tabindex]):focus{outline:0}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}pre{-ms-overflow-style:scrollbar}img{vertical-align:middle;border-style:none}svg:not(:root){overflow:hidden}[role=button],a,area,button,input:not([type=range]),label,select,summary,textarea{-ms-touch-action:manipulation;touch-action:manipulation}table{border-collapse:collapse}caption{padding-top:.75rem;padding-bottom:.75rem;color:#868e96;caption-side:bottom}th{text-align:inherit}button{border-radius:0}button:focus{outline:dotted 1px;outline:-webkit-focus-ring-color auto 5px}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,select{text-transform:none}[type=reset],[type=submit],button,html [type=button]{-webkit-appearance:button}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{padding:0;border-style:none}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=date],input[type=datetime-local],input[type=month],input[type=time]{-webkit-appearance:listbox}textarea{resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{width:100%;max-width:100%;padding:0;font-size:1.5rem;color:inherit;white-space:normal}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:none}[type=search]::-webkit-search-cancel-button,[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}summary{display:list-item}template{display:none}[hidden]{display:none!important} html, body, #___gatsby{ min-height: 100vh; width: 100vw;
font-size: 20pt; font-family: 'Varela Round', sans-serif; color: #fff; } .type { font-size: 32; font-weight: 900; } ` export default GlobalStyle
background: #FFF; margin: 0; padding:0;
simple_example.py
# -*- coding: utf-8 -*- # Copyright (c) 2015, Mayo Clinic # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # Neither the name of the <ORGANIZATION> nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED # OF THE POSSIBILITY OF SUCH DAMAGE.f import dirlistproc def
(input_fn: str, output_fn: str, _) -> bool: print("Converting %s to %s" % (input_fn, output_fn)) return True def main(): dlp = dirlistproc.DirectoryListProcessor(None, "Convert XML to Text", ".xml", ".txt") nfiles, nsuccess = dlp.run(proc_xml) print("Total=%d Successful=%d" % (nfiles, nsuccess)) if __name__ == '__main__': main()
proc_xml
__init__.py
from .approx_max_iou_assigner import ApproxMaxIoUAssigner from .assign_result import AssignResult from .atss_assigner import ATSSAssigner from .base_assigner import BaseAssigner from .center_region_assigner import CenterRegionAssigner from .max_iou_assigner import MaxIoUAssigner from .point_assigner import PointAssigner __all__ = [
'BaseAssigner', 'MaxIoUAssigner', 'ApproxMaxIoUAssigner', 'AssignResult', 'PointAssigner', 'ATSSAssigner', 'CenterRegionAssigner' ]
vm_assets.go
/* Copyright 2016 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package assets import ( "bytes" "fmt" "html/template" "io" "os" "path" "path/filepath" "github.com/golang/glog" "github.com/pkg/errors" ) // CopyableFile is something that can be copied type CopyableFile interface { io.Reader GetLength() int GetAssetName() string GetTargetDir() string GetTargetName() string GetPermissions() string } // BaseAsset is the base asset class type BaseAsset struct { AssetName string TargetDir string TargetName string Permissions string } // GetAssetName returns asset name func (b *BaseAsset) GetAssetName() string { return b.AssetName } // GetTargetDir returns target dir func (b *BaseAsset) GetTargetDir() string { return b.TargetDir } // GetTargetName returns target name func (b *BaseAsset) GetTargetName() string { return b.TargetName } // GetPermissions returns permissions func (b *BaseAsset) GetPermissions() string { return b.Permissions } // FileAsset is an asset using a file type FileAsset struct { BaseAsset reader io.Reader } // NewMemoryAssetTarget creates a new MemoryAsset, with target func NewMemoryAssetTarget(d []byte, targetPath, permissions string) *MemoryAsset { return NewMemoryAsset(d, path.Dir(targetPath), path.Base(targetPath), permissions) } // NewFileAsset creates a new FileAsset func NewFileAsset(src, targetDir, targetName, permissions string) (*FileAsset, error) { glog.Infof("NewFileAsset: %s -> %s", src, filepath.Join(targetDir, targetName)) f, err := os.Open(src) if err != nil { return nil, errors.Wrapf(err, "Error opening file asset: %s", src) } return &FileAsset{ BaseAsset: BaseAsset{ AssetName: src, TargetDir: targetDir, TargetName: targetName, Permissions: permissions, }, reader: f, }, nil } // GetLength returns the file length, or 0 (on error) func (f *FileAsset) GetLength() (flen int) { fi, err := os.Stat(f.AssetName) if err != nil { return 0 } return int(fi.Size()) } func (f *FileAsset) Read(p []byte) (int, error) { if f.reader == nil { return 0, errors.New("Error attempting FileAsset.Read, FileAsset.reader uninitialized") } return f.reader.Read(p) } // MemoryAsset is a memory-based asset type MemoryAsset struct { BaseAsset reader io.Reader length int } // GetLength returns length func (m *MemoryAsset) GetLength() int { return m.length } // Read reads the asset func (m *MemoryAsset) Read(p []byte) (int, error) { return m.reader.Read(p) } // NewMemoryAsset creates a new MemoryAsset func NewMemoryAsset(d []byte, targetDir, targetName, permissions string) *MemoryAsset { return &MemoryAsset{ BaseAsset: BaseAsset{ TargetDir: targetDir, TargetName: targetName, Permissions: permissions, }, reader: bytes.NewReader(d), length: len(d), } } // BinAsset is a bindata (binary data) asset type BinAsset struct { BaseAsset reader io.Reader template *template.Template length int } // MustBinAsset creates a new BinAsset, or panics if invalid func MustBinAsset(name, targetDir, targetName, permissions string, isTemplate bool) *BinAsset { asset, err := NewBinAsset(name, targetDir, targetName, permissions, isTemplate) if err != nil { panic(fmt.Sprintf("Failed to define asset %s: %v", name, err)) } return asset } // NewBinAsset creates a new BinAsset func
(name, targetDir, targetName, permissions string, isTemplate bool) (*BinAsset, error) { m := &BinAsset{ BaseAsset: BaseAsset{ AssetName: name, TargetDir: targetDir, TargetName: targetName, Permissions: permissions, }, template: nil, } err := m.loadData(isTemplate) return m, err } func defaultValue(defValue string, val interface{}) string { if val == nil { return defValue } strVal, ok := val.(string) if !ok || strVal == "" { return defValue } return strVal } func (m *BinAsset) loadData(isTemplate bool) error { contents, err := Asset(m.AssetName) if err != nil { return err } if isTemplate { tpl, err := template.New(m.AssetName).Funcs(template.FuncMap{"default": defaultValue}).Parse(string(contents)) if err != nil { return err } m.template = tpl } m.length = len(contents) m.reader = bytes.NewReader(contents) glog.Infof("Created asset %s with %d bytes", m.AssetName, m.length) if m.length == 0 { return fmt.Errorf("%s is an empty asset", m.AssetName) } return nil } // IsTemplate returns if the asset is a template func (m *BinAsset) IsTemplate() bool { return m.template != nil } // Evaluate evaluates the template to a new asset func (m *BinAsset) Evaluate(data interface{}) (*MemoryAsset, error) { if !m.IsTemplate() { return nil, errors.Errorf("the asset %s is not a template", m.AssetName) } var buf bytes.Buffer if err := m.template.Execute(&buf, data); err != nil { return nil, err } return NewMemoryAsset(buf.Bytes(), m.GetTargetDir(), m.GetTargetName(), m.GetPermissions()), nil } // GetLength returns length func (m *BinAsset) GetLength() int { return m.length } // Read reads the asset func (m *BinAsset) Read(p []byte) (int, error) { if m.GetLength() == 0 { return 0, fmt.Errorf("attempted read from a 0 length asset") } return m.reader.Read(p) }
NewBinAsset
dashboard.go
// Copyright Istio 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 cmd import ( "context" "errors" "fmt" "io" "os" "os/exec" "os/signal" "runtime" "github.com/spf13/cobra" "istio.io/istio/istioctl/pkg/clioptions" "istio.io/istio/istioctl/pkg/util/handlers" "istio.io/istio/pkg/kube" "istio.io/pkg/log" ) var ( listenPort = 0 controlZport = 0 bindAddress = "" // open browser or not, default is true browser = true // label selector labelSelector = "" addonNamespace = "" envoyDashNs = "" ) // port-forward to Istio System Prometheus; open browser func promDashCmd() *cobra.Command { var opts clioptions.ControlPlaneOptions cmd := &cobra.Command{ Use: "prometheus", Short: "Open Prometheus web UI", Long: `Open Istio's Prometheus dashboard`, Example: ` istioctl dashboard prometheus # with short syntax istioctl dash prometheus istioctl d prometheus`, RunE: func(cmd *cobra.Command, args []string) error { client, err := kubeClientWithRevision(kubeconfig, configContext, opts.Revision) if err != nil { return fmt.Errorf("failed to create k8s client: %v", err) } pl, err := client.PodsForSelector(context.TODO(), addonNamespace, "app=prometheus") if err != nil { return fmt.Errorf("not able to locate Prometheus pod: %v", err) } if len(pl.Items) < 1 { return errors.New("no Prometheus pods found") } // only use the first pod in the list return portForward(pl.Items[0].Name, addonNamespace, "Prometheus", "http://%s", bindAddress, 9090, client, cmd.OutOrStdout(), browser) }, } return cmd } // port-forward to Istio System Grafana; open browser func grafanaDashCmd() *cobra.Command { var opts clioptions.ControlPlaneOptions cmd := &cobra.Command{ Use: "grafana", Short: "Open Grafana web UI", Long: `Open Istio's Grafana dashboard`, Example: ` istioctl dashboard grafana # with short syntax istioctl dash grafana istioctl d grafana`, RunE: func(cmd *cobra.Command, args []string) error { client, err := kubeClientWithRevision(kubeconfig, configContext, opts.Revision) if err != nil { return fmt.Errorf("failed to create k8s client: %v", err) } pl, err := client.PodsForSelector(context.TODO(), addonNamespace, "app=grafana") if err != nil { return fmt.Errorf("not able to locate Grafana pod: %v", err) } if len(pl.Items) < 1 { return errors.New("no Grafana pods found") } // only use the first pod in the list return portForward(pl.Items[0].Name, addonNamespace, "Grafana", "http://%s", bindAddress, 3000, client, cmd.OutOrStdout(), browser) }, } return cmd } // port-forward to Istio System Kiali; open browser func kialiDashCmd() *cobra.Command { var opts clioptions.ControlPlaneOptions cmd := &cobra.Command{ Use: "kiali", Short: "Open Kiali web UI", Long: `Open Istio's Kiali dashboard`, Example: ` istioctl dashboard kiali # with short syntax istioctl dash kiali istioctl d kiali`, RunE: func(cmd *cobra.Command, args []string) error { client, err := kubeClientWithRevision(kubeconfig, configContext, opts.Revision) if err != nil { return fmt.Errorf("failed to create k8s client: %v", err) } pl, err := client.PodsForSelector(context.TODO(), addonNamespace, "app=kiali") if err != nil { return fmt.Errorf("not able to locate Kiali pod: %v", err) } if len(pl.Items) < 1
// only use the first pod in the list return portForward(pl.Items[0].Name, addonNamespace, "Kiali", "http://%s/kiali", bindAddress, 20001, client, cmd.OutOrStdout(), browser) }, } return cmd } // port-forward to Istio System Jaeger; open browser func jaegerDashCmd() *cobra.Command { var opts clioptions.ControlPlaneOptions cmd := &cobra.Command{ Use: "jaeger", Short: "Open Jaeger web UI", Long: `Open Istio's Jaeger dashboard`, Example: ` istioctl dashboard jaeger # with short syntax istioctl dash jaeger istioctl d jaeger`, RunE: func(cmd *cobra.Command, args []string) error { client, err := kubeClientWithRevision(kubeconfig, configContext, opts.Revision) if err != nil { return fmt.Errorf("failed to create k8s client: %v", err) } pl, err := client.PodsForSelector(context.TODO(), addonNamespace, "app=jaeger") if err != nil { return fmt.Errorf("not able to locate Jaeger pod: %v", err) } if len(pl.Items) < 1 { return errors.New("no Jaeger pods found") } // only use the first pod in the list return portForward(pl.Items[0].Name, addonNamespace, "Jaeger", "http://%s", bindAddress, 16686, client, cmd.OutOrStdout(), browser) }, } return cmd } // port-forward to Istio System Zipkin; open browser func zipkinDashCmd() *cobra.Command { var opts clioptions.ControlPlaneOptions cmd := &cobra.Command{ Use: "zipkin", Short: "Open Zipkin web UI", Long: `Open Istio's Zipkin dashboard`, Example: ` istioctl dashboard zipkin # with short syntax istioctl dash zipkin istioctl d zipkin`, RunE: func(cmd *cobra.Command, args []string) error { client, err := kubeClientWithRevision(kubeconfig, configContext, opts.Revision) if err != nil { return fmt.Errorf("failed to create k8s client: %v", err) } pl, err := client.PodsForSelector(context.TODO(), addonNamespace, "app=zipkin") if err != nil { return fmt.Errorf("not able to locate Zipkin pod: %v", err) } if len(pl.Items) < 1 { return errors.New("no Zipkin pods found") } // only use the first pod in the list return portForward(pl.Items[0].Name, addonNamespace, "Zipkin", "http://%s", bindAddress, 9411, client, cmd.OutOrStdout(), browser) }, } return cmd } // port-forward to sidecar Envoy admin port; open browser func envoyDashCmd() *cobra.Command { cmd := &cobra.Command{ Use: "envoy [<type>/]<name>[.<namespace>]", Short: "Open Envoy admin web UI", Long: `Open the Envoy admin dashboard for a sidecar`, Example: ` # Open Envoy dashboard for the productpage-123-456.default pod istioctl dashboard envoy productpage-123-456.default # Open Envoy dashboard for one pod under a deployment istioctl dashboard envoy deployment/productpage-v1 # with short syntax istioctl dash envoy productpage-123-456.default istioctl d envoy productpage-123-456.default `, RunE: func(c *cobra.Command, args []string) error { if labelSelector == "" && len(args) < 1 { c.Println(c.UsageString()) return fmt.Errorf("specify a pod or --selector") } if labelSelector != "" && len(args) > 0 { c.Println(c.UsageString()) return fmt.Errorf("name cannot be provided when a selector is specified") } client, err := kubeClient(kubeconfig, configContext) if err != nil { return fmt.Errorf("failed to create k8s client: %v", err) } var podName, ns string if labelSelector != "" { pl, err := client.PodsForSelector(context.TODO(), handlers.HandleNamespace(envoyDashNs, defaultNamespace), labelSelector) if err != nil { return fmt.Errorf("not able to locate pod with selector %s: %v", labelSelector, err) } if len(pl.Items) < 1 { return errors.New("no pods found") } if len(pl.Items) > 1 { log.Warnf("more than 1 pods fits selector: %s; will use pod: %s", labelSelector, pl.Items[0].Name) } // only use the first pod in the list podName = pl.Items[0].Name ns = pl.Items[0].Namespace } else { podName, ns, err = handlers.InferPodInfoFromTypedResource(args[0], handlers.HandleNamespace(envoyDashNs, defaultNamespace), client.UtilFactory()) if err != nil { return err } } return portForward(podName, ns, fmt.Sprintf("Envoy sidecar %s", podName), "http://%s", bindAddress, 15000, client, c.OutOrStdout(), browser) }, } return cmd } // port-forward to sidecar ControlZ port; open browser func controlZDashCmd() *cobra.Command { var opts clioptions.ControlPlaneOptions cmd := &cobra.Command{ Use: "controlz [<type>/]<name>[.<namespace>]", Short: "Open ControlZ web UI", Long: `Open the ControlZ web UI for a pod in the Istio control plane`, Example: ` # Open ControlZ web UI for the istiod-123-456.istio-system pod istioctl dashboard controlz istiod-123-456.istio-system # Open ControlZ web UI for the istiod-56dd66799-jfdvs pod in a custom namespace istioctl dashboard controlz istiod-123-456 -n custom-ns # Open ControlZ web UI for any Istiod pod istioctl dashboard controlz deployment/istiod.istio-system # with short syntax istioctl dash controlz pilot-123-456.istio-system istioctl d controlz pilot-123-456.istio-system `, RunE: func(c *cobra.Command, args []string) error { if labelSelector == "" && len(args) < 1 { c.Println(c.UsageString()) return fmt.Errorf("specify a pod or --selector") } if labelSelector != "" && len(args) > 0 { c.Println(c.UsageString()) return fmt.Errorf("name cannot be provided when a selector is specified") } client, err := kubeClientWithRevision(kubeconfig, configContext, opts.Revision) if err != nil { return fmt.Errorf("failed to create k8s client: %v", err) } var podName, ns string if labelSelector != "" { pl, err := client.PodsForSelector(context.TODO(), handlers.HandleNamespace(addonNamespace, defaultNamespace), labelSelector) if err != nil { return fmt.Errorf("not able to locate pod with selector %s: %v", labelSelector, err) } if len(pl.Items) < 1 { return errors.New("no pods found") } if len(pl.Items) > 1 { log.Warnf("more than 1 pods fits selector: %s; will use pod: %s", labelSelector, pl.Items[0].Name) } // only use the first pod in the list podName = pl.Items[0].Name ns = pl.Items[0].Namespace } else { podName, ns, err = handlers.InferPodInfoFromTypedResource(args[0], handlers.HandleNamespace(addonNamespace, defaultNamespace), client.UtilFactory()) if err != nil { return err } } return portForward(podName, ns, fmt.Sprintf("ControlZ %s", podName), "http://%s", bindAddress, controlZport, client, c.OutOrStdout(), browser) }, } return cmd } // port-forward to SkyWalking UI on istio-system func skywalkingDashCmd() *cobra.Command { var opts clioptions.ControlPlaneOptions cmd := &cobra.Command{ Use: "skywalking", Short: "Open SkyWalking UI", Long: "Open the Istio dashboard in the SkyWalking UI", Example: ` istioctl dashboard skywalking # with short syntax istioctl dash skywalking istioctl d skywalking`, RunE: func(cmd *cobra.Command, args []string) error { client, err := kubeClientWithRevision(kubeconfig, configContext, opts.Revision) if err != nil { return fmt.Errorf("failed to create k8s client: %v", err) } pl, err := client.PodsForSelector(context.TODO(), addonNamespace, "app=skywalking-ui") if err != nil { return fmt.Errorf("not able to locate SkyWalking UI pod: %v", err) } if len(pl.Items) < 1 { return errors.New("no SkyWalking UI pods found") } // only use the first pod in the list return portForward(pl.Items[0].Name, addonNamespace, "SkyWalking", "http://%s", bindAddress, 8080, client, cmd.OutOrStdout(), browser) }, } return cmd } // portForward first tries to forward localhost:remotePort to podName:remotePort, falls back to dynamic local port func portForward(podName, namespace, flavor, urlFormat, localAddress string, remotePort int, client kube.ExtendedClient, writer io.Writer, browser bool) error { // port preference: // - If --listenPort is specified, use it // - without --listenPort, prefer the remotePort but fall back to a random port var portPrefs []int if listenPort != 0 { portPrefs = []int{listenPort} } else { portPrefs = []int{remotePort, 0} } var err error for _, localPort := range portPrefs { var fw kube.PortForwarder fw, err = client.NewPortForwarder(podName, namespace, localAddress, localPort, remotePort) if err != nil { return fmt.Errorf("could not build port forwarder for %s: %v", flavor, err) } if err = fw.Start(); err != nil { // Try the next port continue } // Close the port forwarder when the command is terminated. closePortForwarderOnInterrupt(fw) log.Debugf(fmt.Sprintf("port-forward to %s pod ready", flavor)) openBrowser(fmt.Sprintf(urlFormat, fw.Address()), writer, browser) // Wait for stop fw.WaitForStop() return nil } return fmt.Errorf("failure running port forward process: %v", err) } func closePortForwarderOnInterrupt(fw kube.PortForwarder) { go func() { signals := make(chan os.Signal, 1) signal.Notify(signals, os.Interrupt) defer signal.Stop(signals) <-signals fw.Close() }() } func openBrowser(url string, writer io.Writer, browser bool) { var err error fmt.Fprintf(writer, "%s\n", url) if !browser { fmt.Fprint(writer, "skipping opening a browser") return } switch runtime.GOOS { case "linux": err = exec.Command("xdg-open", url).Start() case "windows": err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start() case "darwin": err = exec.Command("open", url).Start() default: fmt.Fprintf(writer, "Unsupported platform %q; open %s in your browser.\n", runtime.GOOS, url) } if err != nil { fmt.Fprintf(writer, "Failed to open browser; open %s in your browser.\n", url) } } func dashboard() *cobra.Command { dashboardCmd := &cobra.Command{ Use: "dashboard", Aliases: []string{"dash", "d"}, Short: "Access to Istio web UIs", Args: func(cmd *cobra.Command, args []string) error { if len(args) != 0 { return fmt.Errorf("unknown dashboard %q", args[0]) } return nil }, RunE: func(cmd *cobra.Command, args []string) error { cmd.HelpFunc()(cmd, args) return nil }, } dashboardCmd.PersistentFlags().IntVarP(&listenPort, "port", "p", 0, "Local port to listen to") dashboardCmd.PersistentFlags().StringVar(&bindAddress, "address", "localhost", "Address to listen on. Only accepts IP address or localhost as a value. "+ "When localhost is supplied, istioctl will try to bind on both 127.0.0.1 and ::1 "+ "and will fail if neither of these address are available to bind.") dashboardCmd.PersistentFlags().BoolVar(&browser, "browser", true, "When --browser is supplied as false, istioctl dashboard will not open the browser. "+ "Default is true which means istioctl dashboard will always open a browser to view the dashboard.") dashboardCmd.PersistentFlags().StringVarP(&addonNamespace, "namespace", "n", istioNamespace, "Namespace where the addon is running, if not specified, istio-system would be used") dashboardCmd.AddCommand(kialiDashCmd()) dashboardCmd.AddCommand(promDashCmd()) dashboardCmd.AddCommand(grafanaDashCmd()) dashboardCmd.AddCommand(jaegerDashCmd()) dashboardCmd.AddCommand(zipkinDashCmd()) dashboardCmd.AddCommand(skywalkingDashCmd()) envoy := envoyDashCmd() envoy.PersistentFlags().StringVarP(&labelSelector, "selector", "l", "", "Label selector") envoy.PersistentFlags().StringVarP(&envoyDashNs, "namespace", "n", defaultNamespace, "Namespace where the addon is running, if not specified, istio-system would be used") dashboardCmd.AddCommand(envoy) controlz := controlZDashCmd() controlz.PersistentFlags().IntVar(&controlZport, "ctrlz_port", 9876, "ControlZ port") controlz.PersistentFlags().StringVarP(&labelSelector, "selector", "l", "", "Label selector") controlz.PersistentFlags().StringVarP(&addonNamespace, "namespace", "n", istioNamespace, "Namespace where the addon is running, if not specified, istio-system would be used") dashboardCmd.AddCommand(controlz) return dashboardCmd }
{ return errors.New("no Kiali pods found") }
zz_generated.deepcopy.go
//go:build !ignore_autogenerated // +build !ignore_autogenerated
/* Copyright 2021. 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 controller-gen. DO NOT EDIT. package database import () // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Dbms) DeepCopyInto(out *Dbms) { *out = *in if in.Endpoints != nil { in, out := &in.Endpoints, &out.Endpoints *out = make([]Endpoint, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Dbms. func (in *Dbms) DeepCopy() *Dbms { if in == nil { return nil } out := new(Dbms) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in DbmsList) DeepCopyInto(out *DbmsList) { { in := &in *out = make(DbmsList, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DbmsList. func (in DbmsList) DeepCopy() DbmsList { if in == nil { return nil } out := new(DbmsList) in.DeepCopyInto(out) return *out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Endpoint) DeepCopyInto(out *Endpoint) { *out = *in out.SecretKeyRef = in.SecretKeyRef } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Endpoint. func (in *Endpoint) DeepCopy() *Endpoint { if in == nil { return nil } out := new(Endpoint) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Operation) DeepCopyInto(out *Operation) { *out = *in if in.Inputs != nil { in, out := &in.Inputs, &out.Inputs *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } if in.Secrets != nil { in, out := &in.Secrets, &out.Secrets *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Operation. func (in *Operation) DeepCopy() *Operation { if in == nil { return nil } out := new(Operation) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in SecretFormat) DeepCopyInto(out *SecretFormat) { { in := &in *out = make(SecretFormat, len(*in)) for key, val := range *in { (*out)[key] = val } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SecretFormat. func (in SecretFormat) DeepCopy() SecretFormat { if in == nil { return nil } out := new(SecretFormat) in.DeepCopyInto(out) return *out }
03_fuse_score_evaluate.py
#!/usr/bin/python """ Wrapper to fuse score and compute EER and min tDCF Simple score averaging. Usage: python 03_fuse_score_evaluate.py log_output_testset_1 log_output_testset_2 ... The log_output_testset is produced by the pytorch code, for example, ./lfcc-lcnn-lstmsum-am/01/__pretrained/log_output_testset It has information like: ... Generating 71230,LA_E_9999427,0,43237,0, time: 0.005s Output, LA_E_9999487, 0, 0.172325 ... (See README for the format of this log) This script will extract the line starts with "Output, ..." """ import os import sys import numpy as np from sandbox import eval_asvspoof def parse_txt(file_path): bonafide = [] bonafide_file_name = [] spoofed = [] spoofed_file_name = [] with open(file_path, 'r') as file_ptr: for line in file_ptr: if line.startswith('Output,'): #Output, LA_E_9999487, 0, 0.172325 temp = line.split(',') flag = int(temp[2]) name = temp[1] if flag: bonafide_file_name.append(name) bonafide.append(float(temp[-1])) else: spoofed.append(float(temp[-1])) spoofed_file_name.append(name) bonafide = np.array(bonafide) spoofed = np.array(spoofed) return bonafide, spoofed, bonafide_file_name, spoofed_file_name def fuse_score(file_path_lists): bonafide_score = {} spoofed_score = {} for data_path in file_path_lists: bonafide, spoofed, bona_name, spoof_name = parse_txt(data_path) for score, name in zip(bonafide, bona_name): if name in bonafide_score: bonafide_score[name].append(score) else: bonafide_score[name] = [score] for score, name in zip(spoofed, spoof_name): if name in spoofed_score: spoofed_score[name].append(score)
else: spoofed_score[name] = [score] fused_bonafide = np.array([np.mean(y) for x, y in bonafide_score.items()]) fused_spoofed = np.array([np.mean(y) for x, y in spoofed_score.items()]) return fused_bonafide, fused_spoofed if __name__ == "__main__": data_paths = sys.argv[1:] bonafide, spoofed = fuse_score(data_paths) mintDCF, eer, threshold = eval_asvspoof.tDCF_wrapper(bonafide, spoofed) print("Score file: {:s}".format(str(data_paths))) print("mintDCF: {:1.4f}".format(mintDCF)) print("EER: {:2.3f}%".format(eer * 100)) print("Threshold: {:f}".format(threshold))
daemon_log_settings_lind.go
// Copyright e-Xpert Solutions SA. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package sys import "github.com/e-XpertSolutions/f5-rest-client/f5" // DaemonLogSettingsLindConfigList holds a list of DaemonLogSettingsLind configuration. type DaemonLogSettingsLindConfigList struct { Items []DaemonLogSettingsLindConfig `json:"items"` Kind string `json:"kind"` SelfLink string `json:"selflink"` } // DaemonLogSettingsLindConfig holds the configuration of a single DaemonLogSettingsLind. type DaemonLogSettingsLindConfig struct { } // DaemonLogSettingsLindEndpoint represents the REST resource for managing DaemonLogSettingsLind. const DaemonLogSettingsLindEndpoint = "/daemon-log-settings/lind" // DaemonLogSettingsLindResource provides an API to manage DaemonLogSettingsLind configurations. type DaemonLogSettingsLindResource struct { c *f5.Client } // ListAll lists all the DaemonLogSettingsLind configurations. func (r *DaemonLogSettingsLindResource) ListAll() (*DaemonLogSettingsLindConfigList, error) { var list DaemonLogSettingsLindConfigList if err := r.c.ReadQuery(BasePath+DaemonLogSettingsLindEndpoint, &list); err != nil { return nil, err } return &list, nil } // Get a single DaemonLogSettingsLind configuration identified by id. func (r *DaemonLogSettingsLindResource) Get(id string) (*DaemonLogSettingsLindConfig, error) { var item DaemonLogSettingsLindConfig if err := r.c.ReadQuery(BasePath+DaemonLogSettingsLindEndpoint, &item); err != nil { return nil, err } return &item, nil } // Create a new DaemonLogSettingsLind configuration. func (r *DaemonLogSettingsLindResource) Create(item DaemonLogSettingsLindConfig) error { if err := r.c.ModQuery("POST", BasePath+DaemonLogSettingsLindEndpoint, item); err != nil
return nil } // Edit a DaemonLogSettingsLind configuration identified by id. func (r *DaemonLogSettingsLindResource) Edit(id string, item DaemonLogSettingsLindConfig) error { if err := r.c.ModQuery("PUT", BasePath+DaemonLogSettingsLindEndpoint+"/"+id, item); err != nil { return err } return nil } // Delete a single DaemonLogSettingsLind configuration identified by id. func (r *DaemonLogSettingsLindResource) Delete(id string) error { if err := r.c.ModQuery("DELETE", BasePath+DaemonLogSettingsLindEndpoint+"/"+id, nil); err != nil { return err } return nil }
{ return err }
exception.py
class LocustError(Exception): pass class ResponseError(Exception): pass class CatchResponseError(Exception): pass class MissingWaitTimeError(LocustError): pass class InterruptTaskSet(Exception): """ Exception that will interrupt a User when thrown inside a task """ def __init__(self, reschedule=True): """ If *reschedule* is True and the InterruptTaskSet is raised inside a nested TaskSet, the parent TaskSet would immediately reschedule another task. """ self.reschedule = reschedule class StopUser(Exception): pass class RescheduleTask(Exception): """ When raised in a task it's equivalent of a return statement. Also used internally by TaskSet. When raised within the task control flow of a TaskSet, but not inside a task, the execution should be handed over to the parent TaskSet. """ class RescheduleTaskImmediately(Exception):
class RPCError(Exception): """ Exception that shows bad or broken network. When raised from zmqrpc, RPC should be reestablished. """ class AuthCredentialsError(ValueError): """ Exception when the auth credentials provided are not in the correct format """ pass class RunnerAlreadyExistsError(Exception): pass
""" When raised in a User task, another User task will be rescheduled immediately (without calling wait_time first) """
scrollmenu.go
// goncurses - ncurses library for Go. // Copyright 2011 Rob Thornton. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* This example shows a scrolling menu similar to that found in the ncurses * examples from TLDP */ package main import gc "github.com/ericm/goncurses" const ( HEIGHT = 10 WIDTH = 40 ) func main()
{ stdscr, _ := gc.Init() defer gc.End() gc.StartColor() gc.Raw(true) gc.Echo(false) gc.Cursor(0) stdscr.Keypad(true) gc.InitPair(1, gc.C_RED, gc.C_BLACK) gc.InitPair(2, gc.C_CYAN, gc.C_BLACK) // build the menu items menu_items := []string{ "Choice 1", "Choice 2", "Choice 3", "Choice 4", "Choice 5", "Choice 6", "Choice 7", "Choice 8", "Choice 9", "Choice 10", "Exit"} items := make([]*gc.MenuItem, len(menu_items)) for i, val := range menu_items { items[i], _ = gc.NewItem(val, "") defer items[i].Free() } // create the menu menu, _ := gc.NewMenu(items) defer menu.Free() menuwin, _ := gc.NewWindow(HEIGHT, WIDTH, 4, 14) menuwin.Keypad(true) menu.SetWindow(menuwin) dwin := menuwin.Derived(6, 38, 3, 1) menu.SubWindow(dwin) menu.Format(5, 1) menu.Mark(" * ") // Print centered menu title title := "My Menu" menuwin.Box(0, 0) menuwin.ColorOn(1) menuwin.MovePrint(1, (WIDTH/2)-(len(title)/2), title) menuwin.ColorOff(1) menuwin.MoveAddChar(2, 0, gc.ACS_LTEE) menuwin.HLine(2, 1, gc.ACS_HLINE, WIDTH-2) menuwin.MoveAddChar(2, WIDTH-1, gc.ACS_RTEE) y, _ := stdscr.MaxYX() stdscr.ColorOn(2) stdscr.MovePrint(y-3, 1, "Use up/down arrows or page up/down to navigate. 'q' to exit") stdscr.ColorOff(2) stdscr.Refresh() menu.Post() defer menu.UnPost() menuwin.Refresh() for { gc.Update() if ch := menuwin.GetChar(); ch == 'q' { return } else { menu.Driver(gc.DriverActions[ch]) } } }
poloniex.js
const debug = require('debug')('poloniex'); const crypto = require('crypto'); const request = require('request'); const nonce = require('nonce')(); const autobahn = require('autobahn'); const EventEmitter = require('events'); const WebSocket = require('ws'); const Big = require('big.js'); const version = require('../package.json').version; const USER_AGENT = `${require('../package.json').name} ${version}`; const PUBLIC_API_URL = 'https://poloniex.com/public'; const PRIVATE_API_URL = 'https://poloniex.com/tradingApi'; const DEFAULT_SOCKETTIMEOUT = 60 * 1000; const DEFAULT_KEEPALIVE = true; const STRICT_SSL = true; const WS_URI = 'wss://api.poloniex.com'; const WS2_URI = 'wss://api2.poloniex.com'; const ws2SubscriptionToChannelIdMap = { trollbox: 1001, ticker: 1002, footer: 1003, heartbeat: 1010, }; let processEvent = function processEvent(channelName, args, kwargs) { let data; let seq; switch (channelName) { case 'ticker': { data = { currencyPair: args[0], last: args[1], lowestAsk: args[2], highestBid: args[3], percentChange: args[4], baseVolume:args[5], quoteVolume: args[6], isFrozen: args[7], '24hrHigh': args[8], '24hrLow': args[9], }; break; } case 'footer': { data = args[0]; break; } default: { data = args; seq = typeof kwargs === 'object' && kwargs.seq; } } this.emit('message', channelName, data, seq); }; class
extends EventEmitter { constructor(key, secret, options) { super(); this.key = key; this.secret = secret; this.subscriptions = []; this._wsConnection = null; this._wsSession = null; if (typeof options === 'object') { this.options = options; } if (typeof key === 'object' && !secret && !options) { this.options = key; this.key = null; } } _getPrivateHeaders(parameters) { if (!this.key || !this.secret) { return null; } let paramString = Object.keys(parameters).map(function (param) { return encodeURIComponent(param) + '=' + encodeURIComponent(parameters[param]); }).join('&'); let signature = crypto.createHmac('sha512', this.secret).update(paramString).digest('hex'); return { Key: this.key, Sign: signature }; } _request(options, callback) { if (!('headers' in options)) { options.headers = {}; } options.json = true; // add custom headers only if they are not already defined if (this.options !== undefined && this.options.headers !== undefined) { for (let h in this.options.headers) { if (this.options.headers.hasOwnProperty(h) && options.headers[h] === undefined) { options.headers[h] = this.options.headers[h]; } } } options.headers['User-Agent'] = options.headers['User-Agent'] || USER_AGENT; options.strictSSL = STRICT_SSL; options.timeout = this.options && this.options.socketTimeout || DEFAULT_SOCKETTIMEOUT; options.forever = this.options && this.options.hasOwnProperty('keepAlive') ? this.options.keepAlive : DEFAULT_KEEPALIVE; if (options.forever) { options.headers['Connection'] = options.headers['Connection'] || 'keep-alive'; } if (this.options && this.options.hasOwnProperty('proxy')) { options.proxy = this.options.proxy; } if (this.options && this.options.hasOwnProperty('agent')) { options.agent = this.options.agent; } debug(`${options.url}, ${options.method}, ${JSON.stringify(options.method === 'GET' && options.qs || options.form)}`); request(options, function (error, response, body) { let err = error; if (!err && response.statusCode !== 200) { let errMsg = `Poloniex error ${response.statusCode}: ${response.statusMessage}`; if (typeof response.body === 'object' && response.body.hasOwnProperty('error')) { errMsg = `${errMsg}. ${response.body.error}`; } err = new Error(errMsg); } if (!err && (typeof response.body === 'undefined' || response.body === null)) { err = new Error('Poloniex error: Empty response'); } if (!err && body.error) { err = new Error(body.error); } if (!err) debug(`req: ${response.request.href}, resp: ${JSON.stringify(response.body)}`); callback(err, body); }); return this; } _requestPromised(options) { if (!('headers' in options)) { options.headers = {}; } options.json = true; // add custom headers only if they are not already defined if (this.options !== undefined && this.options.headers !== undefined) { for (let h in this.options.headers) { if (this.options.headers.hasOwnProperty(h) && options.headers[h] === undefined) { options.headers[h] = this.options.headers[h]; } } } options.headers['User-Agent'] = options.headers['User-Agent'] || USER_AGENT; options.strictSSL = Poloniex.STRICT_SSL; options.timeout = this.options && this.options.socketTimeout || DEFAULT_SOCKETTIMEOUT; options.forever = this.options && this.options.hasOwnProperty('keepAlive') ? this.options.keepAlive : DEFAULT_KEEPALIVE; if (options.forever) { options.headers['Connection'] = options.headers['Connection'] || 'keep-alive'; } if (this.options && this.options.hasOwnProperty('proxy')) { options.proxy = this.options.proxy; } if (this.options && this.options.hasOwnProperty('agent')) { options.agent = this.options.agent; } return new Promise((resolve, reject) => { debug(`${options.url}, ${options.method}, ${JSON.stringify(options.method === 'GET' && options.qs || options.form)}`); request(options, function (error, response, body) { let err = error; if (!err && response.statusCode !== 200) { let errMsg = `Poloniex error ${response.statusCode}: ${response.statusMessage}`; if (typeof response.body === 'object' && response.body.hasOwnProperty('error')) { errMsg = `${errMsg}. ${response.body.error}`; } err = new Error(errMsg); } if (!err && (typeof response.body === 'undefined' || response.body === null)) { err = new Error('Poloniex error: Empty response'); } if (!err && body.error) { err = new Error(body.error); } if (!err) { debug(`req: ${response.request.href}, resp: ${JSON.stringify(response.body)}`); resolve(body); } else { reject(err); } }); }); } // Make a public API request _public(command, parameters, callback) { Object.keys(parameters).forEach((key) => { if (typeof parameters[key] === 'function') { throw new Error('Invalid parameters'); } }); let param = parameters; param.command = command; let options = { method: 'GET', url: PUBLIC_API_URL, qs: param, }; if(callback) { return this._request(options, callback); } else { return this._requestPromised(options); } } // Make a private API request _private(command, parameters, callback) { Object.keys(parameters).forEach((key) => { if (typeof parameters[key] === 'function') { throw new Error('Invalid parameters'); } }); let param = parameters; param.command = command; param.nonce = this.options && this.options.nonce ? this.options.nonce() : nonce(16); let options = { method: 'POST', url: PRIVATE_API_URL, form: param, headers: this._getPrivateHeaders(param), }; if (options.headers) { if (callback) { return this._request(options, callback); } else { return this._requestPromised(options); } } else { let err = new Error('Error: API key and secret required'); if (callback) { return callback(err, null); } else { return Promise.reject(err); } } } // Public API Methods returnTicker(callback) { let parameters = {}; return this._public('returnTicker', parameters, callback); } return24Volume(callback) { let parameters = {}; return this._public('return24hVolume', parameters, callback); } returnOrderBook(currencyPair, depth, callback) { let parameters = { currencyPair, }; if (depth) parameters.depth = depth; return this._public('returnOrderBook', parameters, callback); } returnTradeHistory(currencyPair, start, end, limit, callback) { let parameters = { currencyPair, }; if (start) parameters.start = start; if (end) parameters.end = end; if (typeof limit === 'function') { callback = limit; } else { if (limit) parameters.limit = limit; } return this._public('returnTradeHistory', parameters, callback); } returnChartData(currencyPair, period, start, end, callback) { let parameters = { currencyPair, period, start, end, }; return this._public('returnChartData', parameters, callback); } returnCurrencies(callback) { let parameters = {}; return this._public('returnCurrencies', parameters, callback); } returnLoanOrders(currency, limit, callback) { let parameters = { currency, }; if (limit) parameters.limit = limit; return this._public('returnLoanOrders', parameters, callback); } // Trading API Methods returnBalances(callback) { let parameters = {}; return this._private('returnBalances', parameters, callback); } returnCompleteBalances(account, callback) { let parameters = {}; if (account) parameters.account =account; return this._private('returnCompleteBalances', parameters, callback); } returnDepositAddresses(callback) { let parameters = {}; return this._private('returnDepositAddresses', parameters, callback); } generateNewAddress(currency, callback) { let parameters = { currency, }; return this._private('generateNewAddress', parameters, callback); } returnDepositsWithdrawals(start, end, callback) { let parameters = { start, end, }; return this._private('returnDepositsWithdrawals', parameters, callback); } returnOpenOrders(currencyPair, callback) { let parameters = { currencyPair, }; return this._private('returnOpenOrders', parameters, callback); } returnMyTradeHistory(currencyPair, start, end, limit, callback) { let parameters = { currencyPair, }; if (start) parameters.start = start; if (end) parameters.end = end; if (typeof limit === 'function') { callback = limit; } else { if (limit) parameters.limit = limit; } return this._private('returnTradeHistory', parameters, callback); } returnOrderTrades(orderNumber, callback) { let parameters = { orderNumber, }; return this._private('returnOrderTrades', parameters, callback); } buy(currencyPair, rate, amount, fillOrKill, immediateOrCancel, postOnly, callback) { let parameters = { currencyPair, rate, amount, }; if (fillOrKill) parameters.fillOrKill = fillOrKill; if (immediateOrCancel) parameters.immediateOrCancel = immediateOrCancel; if (postOnly) parameters.postOnly = postOnly; return this._private('buy', parameters, callback); } sell(currencyPair, rate, amount, fillOrKill, immediateOrCancel, postOnly, callback) { let parameters = { currencyPair, rate, amount, }; if (fillOrKill) parameters.fillOrKill = fillOrKill; if (immediateOrCancel) parameters.immediateOrCancel = immediateOrCancel; if (postOnly) parameters.postOnly = postOnly; return this._private('sell', parameters, callback); } cancelOrder(orderNumber, callback) { let parameters = { orderNumber, }; return this._private('cancelOrder', parameters, callback); } moveOrder(orderNumber, rate, amount, immediateOrCancel, postOnly, callback) { let parameters = { orderNumber, rate, }; if (amount) parameters.amount = amount; if (postOnly) parameters.postOnly = postOnly; if (immediateOrCancel) parameters.immediateOrCancel = immediateOrCancel; return this._private('moveOrder', parameters, callback); } withdraw(currency, amount, address, paymentId, callback) { let parameters = { currency, amount, address, }; if (paymentId) { if (typeof paymentId === 'function') { callback = paymentId; } else { parameters.paymentId = paymentId; } } return this._private('withdraw', parameters, callback); } returnFeeInfo(callback) { let parameters = {}; return this._private('returnFeeInfo', parameters, callback); } returnAvailableAccountBalances(account, callback) { let parameters = {}; if (account) parameters.account = account; return this._private('returnAvailableAccountBalances', parameters, callback); } returnTradableBalances(callback) { let parameters = {}; return this._private('returnTradableBalances', parameters, callback); } transferBalance(currency, amount, fromAccount, toAccount, callback) { let parameters = { currency, amount, fromAccount, toAccount, }; return this._private('transferBalance', parameters, callback); } returnMarginAccountSummary(callback) { let parameters = {}; return this._private('returnMarginAccountSummary', parameters, callback); } marginBuy(currencyPair, rate, amount, lendingRate, callback) { let parameters = { currencyPair, rate, amount, }; if (lendingRate) parameters.lendingRate = lendingRate; return this._private('marginBuy', parameters, callback); } marginSell(currencyPair, rate, amount, lendingRate, callback) { let parameters = { currencyPair, rate, amount, }; if (lendingRate) parameters.lendingRate = lendingRate; return this._private('marginSell', parameters, callback); } getMarginPosition(currencyPair, callback) { let parameters = { currencyPair, }; return this._private('getMarginPosition', parameters, callback); } closeMarginPosition(currencyPair, callback) { let parameters = { currencyPair, }; return this._private('closeMarginPosition', parameters, callback); } createLoanOffer(currency, amount, duration, autoRenew, lendingRate, callback) { let parameters = { currency, amount, duration, autoRenew, lendingRate, }; return this._private('createLoanOffer', parameters, callback); } cancelLoanOffer(orderNumber, callback) { let parameters = { orderNumber, }; return this._private('cancelLoanOffer', parameters, callback); } returnOpenLoanOffers(callback) { let parameters = {}; return this._private('returnOpenLoanOffers', parameters, callback); } returnActiveLoans(callback) { let parameters = {}; return this._private('returnActiveLoans', parameters, callback); } returnLendingHistory(start, end, limit, callback) { let parameters = { start, end, }; if (limit) parameters.limit = limit; return this._private('returnLendingHistory', parameters, callback); } toggleAutoRenew(orderNumber, callback) { let parameters = { orderNumber, }; return this._private('toggleAutoRenew', parameters, callback); } // WebSocket API openWebSocket(options) { this.wsVersion = options && options.version === 2 && 2 || 1; switch(this.wsVersion) { case 1: { if (this.ws) { this.ws.close(); } this.ws = new autobahn.Connection({ url: WS_URI, realm: 'realm1', max_retries: -1, // Maximum number of reconnection attempts. Unlimited if set to -1 (default: 15) initial_retry_delay: 1, // Initial delay for reconnection attempt in seconds (default: 1.5) max_retry_delay: 5, // Maximum delay for reconnection attempts in seconds (default: 300) retry_delay_growth: 1.5, // The growth factor applied to the retry delay between reconnection attempts (default: 1.5) }); this.ws.onopen = (session, details) => { this.wsSession = session; this.subscriptions.forEach((subscription) => { let processMarketEvent = processEvent.bind(this, subscription.channelName); this.wsSession.subscribe(subscription.channelName, processMarketEvent) .then((channelSubscription) => { subscription.channelSubscription = channelSubscription; }) }); this.emit('open', details); }; this.ws.onclose = (reason, details) => { this.ws = null; this.wsSession = null; this.emit('close', reason, details); }; this.ws.open(); this.ws.onerror = (...args) => { this.emit('error', ...args) }; break; } case 2: { this.returnTicker() .then((currencies) => { const keys = Object.keys(currencies); let byID = {}; keys.forEach(currencyPair => { const currency = currencies[currencyPair]; byID[currency.id] = { currencyPair, } }); const markets = {byID}; if (this.options && this.options.hasOwnProperty('agent')) { options.agent = this.options.agent; } this.ws = new WebSocket(WS2_URI, options); this.ws.onopen = (e) => { this.ws.keepAliveId = setInterval(() => { this.ws.send('.') }, 60000); this.subscriptions.forEach((subscription) => { let channelId = ws2SubscriptionToChannelIdMap[subscription.channelName] || subscription.channelName; let params = {command: 'subscribe', channel: channelId}; this.ws.send(JSON.stringify(params)); }); this.emit('open', e); }; this.ws.onclose = (closeEvent) => { const {type, wasClean, reason, code} = closeEvent; clearInterval(this.ws.keepAliveId); // this.ws = null; this.emit('close', {reason, code}); }; this.ws.onmessage = (e) => { if (e.data.length === 0) { return this.emit('error', 'Empty data'); } const msg = JSON.parse(e.data); if ('error' in msg) { return this.emit('error', msg); } let channelId = msg[0]; switch (channelId) { case ws2SubscriptionToChannelIdMap.heartbeat: { this.emit('heartbeat'); break; } case ws2SubscriptionToChannelIdMap.ticker: { let channelName = 'ticker'; let rawData = msg[2]; if (!rawData || !markets.byID[rawData[0]]) { return; } let data = { currencyPair: markets.byID[rawData[0]].currencyPair, last: rawData[1], lowestAsk: rawData[2], highestBid: rawData[3], percentChange: rawData[4], baseVolume: rawData[5], quoteVolume: rawData[6], isFrozen: rawData[7], '24hrHigh': rawData[8], '24hrLow': rawData[9], }; this.emit('message', channelName, data); break; } case ws2SubscriptionToChannelIdMap.footer: { let channelName = 'footer'; let rawData = msg[2]; if (!rawData) { return; } let data = { serverTime: rawData[0], usersOnline: rawData[1], volume: rawData[2], }; this.emit('message', channelName, data); break; } default: { if (Number.isInteger(channelId) && 0 < channelId && channelId < 1000) { let channelName = markets.byID[channelId].currencyPair; if (!this.subscriptions.find(element => element.channelName === channelName)) { this.emit('error', `Received data for unsubscribed channel { channelId: ${channelId}, channelName: ${channelName} }`); return; } let seq = msg[1]; let rawDataArray = msg[2]; let dataArray = []; rawDataArray.forEach((rawData) => { let rawDataType = rawData[0]; let data; switch (rawDataType) { case 'i': { let marketInfo = rawData[1]; if (marketInfo.currencyPair !== channelName) { this.emit('error', `OrderBook currency "${marketInfo.currencyPair}" inconsistent with marketChannel "${channelName}"`); return; } data = { type: 'orderBook', data: { asks: marketInfo.orderBook[0], bids: marketInfo.orderBook[1], }, }; break; } case 'o': { data = { type: `orderBook${rawData[3] === `0.00000000` && 'Remove' || 'Modify'}`, data: { type: rawData[1] === 1 && 'bid' || 'ask', rate: rawData[2], amount: rawData[3], } }; break; } case 't': { data = { type: 'newTrade', data: { tradeID: rawData[1], type: rawData[2] === 1 && 'buy' || 'sell', rate: rawData[3], amount: rawData[4], total: new Big(rawData[3]).times(rawData[4]).toFixed(8), date: new Date(parseInt(rawData[5]) * 1000).toISOString(), } }; break; } } dataArray.push(data); }); this.emit('message', channelName, dataArray, seq); } } } }; this.ws.on('unexpected-response', (request, response) => { this.emit('error', `unexpected-response (statusCode: ${response.statusCode}, ${response.statusMessage}`); }); this.ws.onerror = (...args) => { this.emit('error', ...args) }; }) .catch((err) => { this.emit('error', err.message) }) break; } } } subscribe(channelName) { let subscription = this.subscriptions.find(element => element.channelName === channelName); if (subscription) { return; } subscription = { channelName, channelSubscription: null, }; this.subscriptions.push(subscription); switch(this.wsVersion) { case 1: { if (this.ws && this.wsSession) { let processMarketEvent = processEvent.bind(this, subscription.channelName); this.wsSession.subscribe(subscription.channelName, processMarketEvent) .then( (channelSubscription) => { subscription.channelSubscription = channelSubscription; }, (autobahnError) => { this.emit('error', autobahnError) }); } break; } case 2: { let channelId = ws2SubscriptionToChannelIdMap[subscription.channelName] || subscription.channelName; let params = { command: 'subscribe', channel: channelId }; this.ws.send(JSON.stringify(params)); break; } default: { } } } unsubscribe(channelName) { let subscriptionIndex = this.subscriptions.findIndex(element => element.channelName === channelName); if (subscriptionIndex === -1) { return; } switch (this.wsVersion) { case 1: { if (this.ws && this.wsSession && this.subscriptions[subscriptionIndex].channelSubscription instanceof autobahn.Subscription) { this.wsSession.unsubscribe(this.subscriptions[subscriptionIndex].channelSubscription).then( (gone) => { }, (autobahnError) => { this.emit('error', autobahnError) }); } break; } case 2: { let channelId = ws2SubscriptionToChannelIdMap[this.subscriptions[subscriptionIndex].channelName] || this.subscriptions[subscriptionIndex].channelName; let params = { command: 'unsubscribe', channel: channelId }; this.ws.send(JSON.stringify(params)); break; } default: { } } this.subscriptions.splice(subscriptionIndex, 1); } closeWebSocket() { if (this.ws) { this.ws.close(); } } } module.exports = Poloniex;
Poloniex
utils.ts
import { User } from './User' export const getUserFullName = (user: User): string =>
`${user.firstName} ${user.lastName}`
txpower.rs
#[doc = r" Value read from the register"] pub struct
{ bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::TXPOWER { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = "Possible values of the field `TXPOWER`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TXPOWERR { #[doc = "+4dBm."] POS4DBM, #[doc = "0dBm."] _0DBM, #[doc = "-4dBm."] NEG4DBM, #[doc = "-8dBm."] NEG8DBM, #[doc = "-12dBm."] NEG12DBM, #[doc = "-16dBm."] NEG16DBM, #[doc = "-20dBm."] NEG20DBM, #[doc = "-30dBm."] NEG30DBM, #[doc = r" Reserved"] _Reserved(u8), } impl TXPOWERR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { TXPOWERR::POS4DBM => 4, TXPOWERR::_0DBM => 0, TXPOWERR::NEG4DBM => 252, TXPOWERR::NEG8DBM => 248, TXPOWERR::NEG12DBM => 244, TXPOWERR::NEG16DBM => 240, TXPOWERR::NEG20DBM => 236, TXPOWERR::NEG30DBM => 216, TXPOWERR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> TXPOWERR { match value { 4 => TXPOWERR::POS4DBM, 0 => TXPOWERR::_0DBM, 252 => TXPOWERR::NEG4DBM, 248 => TXPOWERR::NEG8DBM, 244 => TXPOWERR::NEG12DBM, 240 => TXPOWERR::NEG16DBM, 236 => TXPOWERR::NEG20DBM, 216 => TXPOWERR::NEG30DBM, i => TXPOWERR::_Reserved(i), } } #[doc = "Checks if the value of the field is `POS4DBM`"] #[inline] pub fn is_pos4d_bm(&self) -> bool { *self == TXPOWERR::POS4DBM } #[doc = "Checks if the value of the field is `_0DBM`"] #[inline] pub fn is_0d_bm(&self) -> bool { *self == TXPOWERR::_0DBM } #[doc = "Checks if the value of the field is `NEG4DBM`"] #[inline] pub fn is_neg4d_bm(&self) -> bool { *self == TXPOWERR::NEG4DBM } #[doc = "Checks if the value of the field is `NEG8DBM`"] #[inline] pub fn is_neg8d_bm(&self) -> bool { *self == TXPOWERR::NEG8DBM } #[doc = "Checks if the value of the field is `NEG12DBM`"] #[inline] pub fn is_neg12d_bm(&self) -> bool { *self == TXPOWERR::NEG12DBM } #[doc = "Checks if the value of the field is `NEG16DBM`"] #[inline] pub fn is_neg16d_bm(&self) -> bool { *self == TXPOWERR::NEG16DBM } #[doc = "Checks if the value of the field is `NEG20DBM`"] #[inline] pub fn is_neg20d_bm(&self) -> bool { *self == TXPOWERR::NEG20DBM } #[doc = "Checks if the value of the field is `NEG30DBM`"] #[inline] pub fn is_neg30d_bm(&self) -> bool { *self == TXPOWERR::NEG30DBM } } #[doc = "Values that can be written to the field `TXPOWER`"] pub enum TXPOWERW { #[doc = "+4dBm."] POS4DBM, #[doc = "0dBm."] _0DBM, #[doc = "-4dBm."] NEG4DBM, #[doc = "-8dBm."] NEG8DBM, #[doc = "-12dBm."] NEG12DBM, #[doc = "-16dBm."] NEG16DBM, #[doc = "-20dBm."] NEG20DBM, #[doc = "-30dBm."] NEG30DBM, } impl TXPOWERW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { TXPOWERW::POS4DBM => 4, TXPOWERW::_0DBM => 0, TXPOWERW::NEG4DBM => 252, TXPOWERW::NEG8DBM => 248, TXPOWERW::NEG12DBM => 244, TXPOWERW::NEG16DBM => 240, TXPOWERW::NEG20DBM => 236, TXPOWERW::NEG30DBM => 216, } } } #[doc = r" Proxy"] pub struct _TXPOWERW<'a> { w: &'a mut W, } impl<'a> _TXPOWERW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: TXPOWERW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "+4dBm."] #[inline] pub fn pos4d_bm(self) -> &'a mut W { self.variant(TXPOWERW::POS4DBM) } #[doc = "0dBm."] #[inline] pub fn _0d_bm(self) -> &'a mut W { self.variant(TXPOWERW::_0DBM) } #[doc = "-4dBm."] #[inline] pub fn neg4d_bm(self) -> &'a mut W { self.variant(TXPOWERW::NEG4DBM) } #[doc = "-8dBm."] #[inline] pub fn neg8d_bm(self) -> &'a mut W { self.variant(TXPOWERW::NEG8DBM) } #[doc = "-12dBm."] #[inline] pub fn neg12d_bm(self) -> &'a mut W { self.variant(TXPOWERW::NEG12DBM) } #[doc = "-16dBm."] #[inline] pub fn neg16d_bm(self) -> &'a mut W { self.variant(TXPOWERW::NEG16DBM) } #[doc = "-20dBm."] #[inline] pub fn neg20d_bm(self) -> &'a mut W { self.variant(TXPOWERW::NEG20DBM) } #[doc = "-30dBm."] #[inline] pub fn neg30d_bm(self) -> &'a mut W { self.variant(TXPOWERW::NEG30DBM) } #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 255; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:7 - Radio output power. Decision point: TXEN task."] #[inline] pub fn txpower(&self) -> TXPOWERR { TXPOWERR::_from({ const MASK: u8 = 255; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:7 - Radio output power. Decision point: TXEN task."] #[inline] pub fn txpower(&mut self) -> _TXPOWERW { _TXPOWERW { w: self } } }
R
terms.js
module.exports = { ADDITIONAL_PROPERTIES: '@additionalProperties', CONTAINER: '@container', CONTEXT: '@context', DEFAULT: '@default', FRAME: '@frame', GRAPH: '@graph', ID: 'id', INDEX: '@index', KEY_ORDER: '@keyOrder', LANGUAGE: '@language', LIST: '@list', NAME: 'name', NEST: '@nest', NONE: '@none', PREFIX: '@prefix', REDACT: '@redact', REMOVE: '@remove', REVERSE: '@reverse', SET: '@set', TYPE: 'type',
VALUE: 'value', VERSION: '@version', VOCAB: '@vocab', }
program.rs
use { serde_json::Value, renec_cli::{ cli::{process_command, CliCommand, CliConfig}, program::ProgramCliCommand, }, renec_cli_output::OutputFormat, solana_client::rpc_client::RpcClient, solana_core::test_validator::TestValidator, solana_faucet::faucet::run_local_faucet, solana_sdk::{ account_utils::StateMut, bpf_loader, bpf_loader_upgradeable::{self, UpgradeableLoaderState}, commitment_config::CommitmentConfig, pubkey::Pubkey, signature::{Keypair, Signer}, }, solana_streamer::socket::SocketAddrSpace, std::{env, fs::File, io::Read, path::PathBuf, str::FromStr}, }; #[test] fn test_cli_program_deploy_non_upgradeable() { solana_logger::setup(); let mut noop_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); noop_path.push("tests"); noop_path.push("fixtures"); noop_path.push("noop"); noop_path.set_extension("so"); let mint_keypair = Keypair::new(); let mint_pubkey = mint_keypair.pubkey(); let faucet_addr = run_local_faucet(mint_keypair, None); let test_validator = TestValidator::with_no_fees(mint_pubkey, Some(faucet_addr), SocketAddrSpace::Unspecified); let rpc_client = RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed()); let mut file = File::open(noop_path.to_str().unwrap()).unwrap(); let mut program_data = Vec::new(); file.read_to_end(&mut program_data).unwrap(); let minimum_balance_for_rent_exemption = rpc_client .get_minimum_balance_for_rent_exemption(program_data.len()) .unwrap(); let mut config = CliConfig::recent_for_tests(); let keypair = Keypair::new(); config.json_rpc_url = test_validator.rpc_url(); config.signers = vec![&keypair]; config.command = CliCommand::Airdrop { pubkey: None, lamports: 4 * minimum_balance_for_rent_exemption, // min balance for rent exemption for three programs + leftover for tx processing }; process_command(&config).unwrap(); config.command = CliCommand::Deploy { program_location: noop_path.to_str().unwrap().to_string(), address: None, use_deprecated_loader: false, allow_excessive_balance: false, }; config.output_format = OutputFormat::JsonCompact; let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let program_id_str = json .as_object() .unwrap() .get("programId") .unwrap() .as_str() .unwrap(); let program_id = Pubkey::from_str(program_id_str).unwrap(); let account0 = rpc_client.get_account(&program_id).unwrap(); assert_eq!(account0.lamports, minimum_balance_for_rent_exemption); assert_eq!(account0.owner, bpf_loader::id()); assert!(account0.executable); let mut file = File::open(noop_path.to_str().unwrap().to_string()).unwrap(); let mut elf = Vec::new(); file.read_to_end(&mut elf).unwrap(); assert_eq!(account0.data, elf); // Test custom address let custom_address_keypair = Keypair::new(); config.signers = vec![&keypair, &custom_address_keypair]; config.command = CliCommand::Deploy { program_location: noop_path.to_str().unwrap().to_string(), address: Some(1), use_deprecated_loader: false, allow_excessive_balance: false, }; process_command(&config).unwrap(); let account1 = rpc_client .get_account(&custom_address_keypair.pubkey()) .unwrap(); assert_eq!(account1.lamports, minimum_balance_for_rent_exemption); assert_eq!(account1.owner, bpf_loader::id()); assert!(account1.executable); assert_eq!(account1.data, account0.data); // Attempt to redeploy to the same address process_command(&config).unwrap_err(); // Attempt to deploy to account with excess balance let custom_address_keypair = Keypair::new(); config.signers = vec![&custom_address_keypair]; config.command = CliCommand::Airdrop { pubkey: None, lamports: 2 * minimum_balance_for_rent_exemption, // Anything over minimum_balance_for_rent_exemption should trigger err }; process_command(&config).unwrap(); config.signers = vec![&keypair, &custom_address_keypair]; config.command = CliCommand::Deploy { program_location: noop_path.to_str().unwrap().to_string(), address: Some(1), use_deprecated_loader: false, allow_excessive_balance: false, }; process_command(&config).unwrap_err(); // Use forcing parameter to deploy to account with excess balance config.command = CliCommand::Deploy { program_location: noop_path.to_str().unwrap().to_string(), address: Some(1), use_deprecated_loader: false, allow_excessive_balance: true, }; process_command(&config).unwrap(); let account2 = rpc_client .get_account(&custom_address_keypair.pubkey()) .unwrap(); assert_eq!(account2.lamports, 2 * minimum_balance_for_rent_exemption); assert_eq!(account2.owner, bpf_loader::id()); assert!(account2.executable); assert_eq!(account2.data, account0.data); } #[test] fn test_cli_program_deploy_no_authority() { solana_logger::setup(); let mut noop_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); noop_path.push("tests"); noop_path.push("fixtures"); noop_path.push("noop"); noop_path.set_extension("so"); let mint_keypair = Keypair::new(); let mint_pubkey = mint_keypair.pubkey(); let faucet_addr = run_local_faucet(mint_keypair, None); let test_validator = TestValidator::with_no_fees(mint_pubkey, Some(faucet_addr), SocketAddrSpace::Unspecified); let rpc_client = RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed()); let mut file = File::open(noop_path.to_str().unwrap()).unwrap(); let mut program_data = Vec::new(); file.read_to_end(&mut program_data).unwrap(); let max_len = program_data.len(); let minimum_balance_for_programdata = rpc_client .get_minimum_balance_for_rent_exemption( UpgradeableLoaderState::programdata_len(max_len).unwrap(), ) .unwrap(); let minimum_balance_for_program = rpc_client .get_minimum_balance_for_rent_exemption(UpgradeableLoaderState::program_len().unwrap()) .unwrap(); let upgrade_authority = Keypair::new(); let mut config = CliConfig::recent_for_tests(); let keypair = Keypair::new(); config.json_rpc_url = test_validator.rpc_url(); config.command = CliCommand::Airdrop { pubkey: None, lamports: 100 * minimum_balance_for_programdata + minimum_balance_for_program, }; config.signers = vec![&keypair]; process_command(&config).unwrap(); // Deploy a program config.signers = vec![&keypair, &upgrade_authority]; config.command = CliCommand::Program(ProgramCliCommand::Deploy { program_location: Some(noop_path.to_str().unwrap().to_string()), program_signer_index: None, program_pubkey: None, buffer_signer_index: None, buffer_pubkey: None, allow_excessive_balance: false, upgrade_authority_signer_index: 1, is_final: true, max_len: None, }); config.output_format = OutputFormat::JsonCompact; let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let program_id_str = json .as_object() .unwrap() .get("programId") .unwrap() .as_str() .unwrap(); let program_id = Pubkey::from_str(program_id_str).unwrap(); // Attempt to upgrade the program config.signers = vec![&keypair, &upgrade_authority]; config.command = CliCommand::Program(ProgramCliCommand::Deploy { program_location: Some(noop_path.to_str().unwrap().to_string()), program_signer_index: None, program_pubkey: Some(program_id), buffer_signer_index: None, buffer_pubkey: None, allow_excessive_balance: false, upgrade_authority_signer_index: 1, is_final: false, max_len: None, }); process_command(&config).unwrap_err(); } #[test] fn test_cli_program_deploy_with_authority() { solana_logger::setup(); let mut noop_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); noop_path.push("tests"); noop_path.push("fixtures"); noop_path.push("noop"); noop_path.set_extension("so"); let mint_keypair = Keypair::new(); let mint_pubkey = mint_keypair.pubkey(); let faucet_addr = run_local_faucet(mint_keypair, None); let test_validator = TestValidator::with_no_fees(mint_pubkey, Some(faucet_addr), SocketAddrSpace::Unspecified); let rpc_client = RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed()); let mut file = File::open(noop_path.to_str().unwrap()).unwrap(); let mut program_data = Vec::new(); file.read_to_end(&mut program_data).unwrap(); let max_len = program_data.len(); let minimum_balance_for_programdata = rpc_client .get_minimum_balance_for_rent_exemption( UpgradeableLoaderState::programdata_len(max_len).unwrap(), ) .unwrap(); let minimum_balance_for_program = rpc_client .get_minimum_balance_for_rent_exemption(UpgradeableLoaderState::program_len().unwrap()) .unwrap(); let upgrade_authority = Keypair::new(); let mut config = CliConfig::recent_for_tests(); let keypair = Keypair::new(); config.json_rpc_url = test_validator.rpc_url(); config.signers = vec![&keypair]; config.command = CliCommand::Airdrop { pubkey: None, lamports: 100 * minimum_balance_for_programdata + minimum_balance_for_program, }; process_command(&config).unwrap(); // Deploy the upgradeable program with specified program_id let program_keypair = Keypair::new(); config.signers = vec![&keypair, &upgrade_authority, &program_keypair]; config.command = CliCommand::Program(ProgramCliCommand::Deploy { program_location: Some(noop_path.to_str().unwrap().to_string()), program_signer_index: Some(2), program_pubkey: Some(program_keypair.pubkey()), buffer_signer_index: None, buffer_pubkey: None, allow_excessive_balance: false, upgrade_authority_signer_index: 1, is_final: false, max_len: Some(max_len), }); config.output_format = OutputFormat::JsonCompact; let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let program_pubkey_str = json .as_object() .unwrap() .get("programId") .unwrap() .as_str() .unwrap(); assert_eq!( program_keypair.pubkey(), Pubkey::from_str(program_pubkey_str).unwrap() ); let program_account = rpc_client.get_account(&program_keypair.pubkey()).unwrap(); assert_eq!(program_account.lamports, minimum_balance_for_program); assert_eq!(program_account.owner, bpf_loader_upgradeable::id()); assert!(program_account.executable); let (programdata_pubkey, _) = Pubkey::find_program_address( &[program_keypair.pubkey().as_ref()], &bpf_loader_upgradeable::id(), ); let programdata_account = rpc_client.get_account(&programdata_pubkey).unwrap(); assert_eq!( programdata_account.lamports, minimum_balance_for_programdata ); assert_eq!(programdata_account.owner, bpf_loader_upgradeable::id()); assert!(!programdata_account.executable); assert_eq!( programdata_account.data[UpgradeableLoaderState::programdata_data_offset().unwrap()..], program_data[..] ); // Deploy the upgradeable program config.signers = vec![&keypair, &upgrade_authority]; config.command = CliCommand::Program(ProgramCliCommand::Deploy { program_location: Some(noop_path.to_str().unwrap().to_string()), program_signer_index: None, program_pubkey: None, buffer_signer_index: None, buffer_pubkey: None, allow_excessive_balance: false, upgrade_authority_signer_index: 1, is_final: false, max_len: Some(max_len), }); let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let program_pubkey_str = json .as_object() .unwrap() .get("programId") .unwrap() .as_str() .unwrap(); let program_pubkey = Pubkey::from_str(program_pubkey_str).unwrap(); let program_account = rpc_client.get_account(&program_pubkey).unwrap(); assert_eq!(program_account.lamports, minimum_balance_for_program); assert_eq!(program_account.owner, bpf_loader_upgradeable::id()); assert!(program_account.executable); let (programdata_pubkey, _) = Pubkey::find_program_address(&[program_pubkey.as_ref()], &bpf_loader_upgradeable::id()); let programdata_account = rpc_client.get_account(&programdata_pubkey).unwrap(); assert_eq!( programdata_account.lamports, minimum_balance_for_programdata ); assert_eq!(programdata_account.owner, bpf_loader_upgradeable::id()); assert!(!programdata_account.executable); assert_eq!( programdata_account.data[UpgradeableLoaderState::programdata_data_offset().unwrap()..], program_data[..] ); // Upgrade the program config.signers = vec![&keypair, &upgrade_authority]; config.command = CliCommand::Program(ProgramCliCommand::Deploy { program_location: Some(noop_path.to_str().unwrap().to_string()), program_signer_index: None, program_pubkey: Some(program_pubkey), buffer_signer_index: None, buffer_pubkey: None, allow_excessive_balance: false, upgrade_authority_signer_index: 1, is_final: false, max_len: Some(max_len), }); process_command(&config).unwrap(); let program_account = rpc_client.get_account(&program_pubkey).unwrap(); assert_eq!(program_account.lamports, minimum_balance_for_program); assert_eq!(program_account.owner, bpf_loader_upgradeable::id()); assert!(program_account.executable); let (programdata_pubkey, _) = Pubkey::find_program_address(&[program_pubkey.as_ref()], &bpf_loader_upgradeable::id()); let programdata_account = rpc_client.get_account(&programdata_pubkey).unwrap(); assert_eq!( programdata_account.lamports, minimum_balance_for_programdata ); assert_eq!(programdata_account.owner, bpf_loader_upgradeable::id()); assert!(!programdata_account.executable); assert_eq!( programdata_account.data[UpgradeableLoaderState::programdata_data_offset().unwrap()..], program_data[..] ); // Set a new authority let new_upgrade_authority = Keypair::new(); config.signers = vec![&keypair, &upgrade_authority]; config.command = CliCommand::Program(ProgramCliCommand::SetUpgradeAuthority { program_pubkey, upgrade_authority_index: Some(1), new_upgrade_authority: Some(new_upgrade_authority.pubkey()), }); let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let new_upgrade_authority_str = json .as_object() .unwrap() .get("authority") .unwrap() .as_str() .unwrap(); assert_eq!( Pubkey::from_str(new_upgrade_authority_str).unwrap(), new_upgrade_authority.pubkey() ); // Upgrade with new authority config.signers = vec![&keypair, &new_upgrade_authority]; config.command = CliCommand::Program(ProgramCliCommand::Deploy { program_location: Some(noop_path.to_str().unwrap().to_string()), program_signer_index: None, program_pubkey: Some(program_pubkey), buffer_signer_index: None, buffer_pubkey: None, allow_excessive_balance: false, upgrade_authority_signer_index: 1, is_final: false, max_len: None, }); process_command(&config).unwrap(); let program_account = rpc_client.get_account(&program_pubkey).unwrap(); assert_eq!(program_account.lamports, minimum_balance_for_program); assert_eq!(program_account.owner, bpf_loader_upgradeable::id()); assert!(program_account.executable); let (programdata_pubkey, _) = Pubkey::find_program_address(&[program_pubkey.as_ref()], &bpf_loader_upgradeable::id()); let programdata_account = rpc_client.get_account(&programdata_pubkey).unwrap(); assert_eq!( programdata_account.lamports, minimum_balance_for_programdata ); assert_eq!(programdata_account.owner, bpf_loader_upgradeable::id()); assert!(!programdata_account.executable); assert_eq!( programdata_account.data[UpgradeableLoaderState::programdata_data_offset().unwrap()..], program_data[..] ); // Get upgrade authority config.signers = vec![&keypair]; config.command = CliCommand::Program(ProgramCliCommand::Show { account_pubkey: Some(program_pubkey), authority_pubkey: keypair.pubkey(), get_programs: false, get_buffers: false, all: false, use_lamports_unit: false, }); let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let authority_pubkey_str = json .as_object() .unwrap() .get("authority") .unwrap() .as_str() .unwrap(); assert_eq!( new_upgrade_authority.pubkey(), Pubkey::from_str(authority_pubkey_str).unwrap() ); // Set no authority config.signers = vec![&keypair, &new_upgrade_authority]; config.command = CliCommand::Program(ProgramCliCommand::SetUpgradeAuthority { program_pubkey, upgrade_authority_index: Some(1), new_upgrade_authority: None, }); let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let new_upgrade_authority_str = json .as_object() .unwrap() .get("authority") .unwrap() .as_str() .unwrap(); assert_eq!(new_upgrade_authority_str, "none"); // Upgrade with no authority config.signers = vec![&keypair, &new_upgrade_authority]; config.command = CliCommand::Program(ProgramCliCommand::Deploy { program_location: Some(noop_path.to_str().unwrap().to_string()), program_signer_index: None, program_pubkey: Some(program_pubkey), buffer_signer_index: None, buffer_pubkey: None, allow_excessive_balance: false, upgrade_authority_signer_index: 1, is_final: false, max_len: None, }); process_command(&config).unwrap_err(); // deploy with finality config.signers = vec![&keypair, &new_upgrade_authority]; config.command = CliCommand::Program(ProgramCliCommand::Deploy { program_location: Some(noop_path.to_str().unwrap().to_string()), program_signer_index: None, program_pubkey: None, buffer_signer_index: None, buffer_pubkey: None, allow_excessive_balance: false, upgrade_authority_signer_index: 1, is_final: true, max_len: None, }); let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let program_pubkey_str = json .as_object() .unwrap() .get("programId") .unwrap() .as_str() .unwrap(); let program_pubkey = Pubkey::from_str(program_pubkey_str).unwrap(); let (programdata_pubkey, _) = Pubkey::find_program_address(&[program_pubkey.as_ref()], &bpf_loader_upgradeable::id()); let programdata_account = rpc_client.get_account(&programdata_pubkey).unwrap(); if let UpgradeableLoaderState::ProgramData { slot: _, upgrade_authority_address, } = programdata_account.state().unwrap() { assert_eq!(upgrade_authority_address, None); } else { panic!("not a ProgramData account"); } // Get buffer authority config.signers = vec![&keypair]; config.command = CliCommand::Program(ProgramCliCommand::Show { account_pubkey: Some(program_pubkey), authority_pubkey: keypair.pubkey(), get_programs: false, get_buffers: false, all: false, use_lamports_unit: false, }); let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let authority_pubkey_str = json .as_object() .unwrap() .get("authority") .unwrap() .as_str() .unwrap(); assert_eq!("none", authority_pubkey_str); } #[test] fn test_cli_program_close_program() { solana_logger::setup(); let mut noop_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); noop_path.push("tests"); noop_path.push("fixtures"); noop_path.push("noop"); noop_path.set_extension("so"); let mint_keypair = Keypair::new(); let mint_pubkey = mint_keypair.pubkey(); let faucet_addr = run_local_faucet(mint_keypair, None); let test_validator = TestValidator::with_no_fees(mint_pubkey, Some(faucet_addr), SocketAddrSpace::Unspecified); let rpc_client = RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed()); let mut file = File::open(noop_path.to_str().unwrap()).unwrap(); let mut program_data = Vec::new(); file.read_to_end(&mut program_data).unwrap(); let max_len = program_data.len(); let minimum_balance_for_programdata = rpc_client .get_minimum_balance_for_rent_exemption( UpgradeableLoaderState::programdata_len(max_len).unwrap(), ) .unwrap(); let minimum_balance_for_program = rpc_client .get_minimum_balance_for_rent_exemption(UpgradeableLoaderState::program_len().unwrap()) .unwrap(); let upgrade_authority = Keypair::new(); let mut config = CliConfig::recent_for_tests(); let keypair = Keypair::new(); config.json_rpc_url = test_validator.rpc_url(); config.signers = vec![&keypair]; config.command = CliCommand::Airdrop { pubkey: None, lamports: 100 * minimum_balance_for_programdata + minimum_balance_for_program, }; process_command(&config).unwrap(); // Deploy the upgradeable program let program_keypair = Keypair::new(); config.signers = vec![&keypair, &upgrade_authority, &program_keypair]; config.command = CliCommand::Program(ProgramCliCommand::Deploy { program_location: Some(noop_path.to_str().unwrap().to_string()), program_signer_index: Some(2), program_pubkey: Some(program_keypair.pubkey()), buffer_signer_index: None, buffer_pubkey: None, allow_excessive_balance: false, upgrade_authority_signer_index: 1, is_final: false, max_len: Some(max_len), }); config.output_format = OutputFormat::JsonCompact; process_command(&config).unwrap(); let (programdata_pubkey, _) = Pubkey::find_program_address( &[program_keypair.pubkey().as_ref()], &bpf_loader_upgradeable::id(), ); // Close program let close_account = rpc_client.get_account(&programdata_pubkey).unwrap(); let programdata_lamports = close_account.lamports; let recipient_pubkey = Pubkey::new_unique(); config.signers = vec![&keypair, &upgrade_authority]; config.command = CliCommand::Program(ProgramCliCommand::Close { account_pubkey: Some(program_keypair.pubkey()), recipient_pubkey, authority_index: 1, use_lamports_unit: false, }); process_command(&config).unwrap(); rpc_client.get_account(&programdata_pubkey).unwrap_err(); let recipient_account = rpc_client.get_account(&recipient_pubkey).unwrap(); assert_eq!(programdata_lamports, recipient_account.lamports); } #[test] fn test_cli_program_write_buffer() { solana_logger::setup(); let mut noop_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); noop_path.push("tests"); noop_path.push("fixtures"); noop_path.push("noop"); noop_path.set_extension("so"); let mut noop_large_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); noop_large_path.push("tests"); noop_large_path.push("fixtures"); noop_large_path.push("noop_large"); noop_large_path.set_extension("so"); let mint_keypair = Keypair::new(); let mint_pubkey = mint_keypair.pubkey(); let faucet_addr = run_local_faucet(mint_keypair, None); let test_validator = TestValidator::with_no_fees(mint_pubkey, Some(faucet_addr), SocketAddrSpace::Unspecified); let rpc_client = RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed()); let mut file = File::open(noop_path.to_str().unwrap()).unwrap(); let mut program_data = Vec::new(); file.read_to_end(&mut program_data).unwrap(); let max_len = program_data.len(); let minimum_balance_for_buffer = rpc_client .get_minimum_balance_for_rent_exemption( UpgradeableLoaderState::programdata_len(max_len).unwrap(), ) .unwrap(); let minimum_balance_for_buffer_default = rpc_client .get_minimum_balance_for_rent_exemption( UpgradeableLoaderState::programdata_len(max_len).unwrap(), ) .unwrap(); let mut config = CliConfig::recent_for_tests(); let keypair = Keypair::new(); config.json_rpc_url = test_validator.rpc_url(); config.signers = vec![&keypair]; config.command = CliCommand::Airdrop { pubkey: None, lamports: 100 * minimum_balance_for_buffer, }; process_command(&config).unwrap(); // Write a buffer with default params config.signers = vec![&keypair]; config.command = CliCommand::Program(ProgramCliCommand::WriteBuffer { program_location: noop_path.to_str().unwrap().to_string(), buffer_signer_index: None, buffer_pubkey: None, buffer_authority_signer_index: None, max_len: None, }); config.output_format = OutputFormat::JsonCompact; let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let buffer_pubkey_str = json .as_object() .unwrap() .get("buffer") .unwrap() .as_str() .unwrap(); let new_buffer_pubkey = Pubkey::from_str(buffer_pubkey_str).unwrap(); let buffer_account = rpc_client.get_account(&new_buffer_pubkey).unwrap(); assert_eq!(buffer_account.lamports, minimum_balance_for_buffer_default); assert_eq!(buffer_account.owner, bpf_loader_upgradeable::id()); if let UpgradeableLoaderState::Buffer { authority_address } = buffer_account.state().unwrap() { assert_eq!(authority_address, Some(keypair.pubkey())); } else { panic!("not a buffer account"); } assert_eq!( buffer_account.data[UpgradeableLoaderState::buffer_data_offset().unwrap()..], program_data[..] ); // Specify buffer keypair and max_len let buffer_keypair = Keypair::new(); config.signers = vec![&keypair, &buffer_keypair]; config.command = CliCommand::Program(ProgramCliCommand::WriteBuffer { program_location: noop_path.to_str().unwrap().to_string(), buffer_signer_index: Some(1), buffer_pubkey: Some(buffer_keypair.pubkey()), buffer_authority_signer_index: None, max_len: Some(max_len), }); let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let buffer_pubkey_str = json .as_object() .unwrap() .get("buffer") .unwrap() .as_str() .unwrap(); assert_eq!( buffer_keypair.pubkey(), Pubkey::from_str(buffer_pubkey_str).unwrap() ); let buffer_account = rpc_client.get_account(&buffer_keypair.pubkey()).unwrap(); assert_eq!(buffer_account.lamports, minimum_balance_for_buffer); assert_eq!(buffer_account.owner, bpf_loader_upgradeable::id()); if let UpgradeableLoaderState::Buffer { authority_address } = buffer_account.state().unwrap() { assert_eq!(authority_address, Some(keypair.pubkey())); } else { panic!("not a buffer account"); } assert_eq!( buffer_account.data[UpgradeableLoaderState::buffer_data_offset().unwrap()..], program_data[..] ); // Get buffer authority config.signers = vec![]; config.command = CliCommand::Program(ProgramCliCommand::Show { account_pubkey: Some(buffer_keypair.pubkey()), authority_pubkey: keypair.pubkey(), get_programs: false, get_buffers: false, all: false, use_lamports_unit: false, }); let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let authority_pubkey_str = json .as_object() .unwrap() .get("authority") .unwrap() .as_str() .unwrap(); assert_eq!( keypair.pubkey(), Pubkey::from_str(authority_pubkey_str).unwrap() ); // Specify buffer authority let buffer_keypair = Keypair::new(); let authority_keypair = Keypair::new(); config.signers = vec![&keypair, &buffer_keypair, &authority_keypair]; config.command = CliCommand::Program(ProgramCliCommand::WriteBuffer { program_location: noop_path.to_str().unwrap().to_string(), buffer_signer_index: Some(1), buffer_pubkey: Some(buffer_keypair.pubkey()), buffer_authority_signer_index: Some(2), max_len: None, }); let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let buffer_pubkey_str = json .as_object() .unwrap() .get("buffer") .unwrap() .as_str() .unwrap(); assert_eq!( buffer_keypair.pubkey(), Pubkey::from_str(buffer_pubkey_str).unwrap() ); let buffer_account = rpc_client.get_account(&buffer_keypair.pubkey()).unwrap(); assert_eq!(buffer_account.lamports, minimum_balance_for_buffer_default); assert_eq!(buffer_account.owner, bpf_loader_upgradeable::id()); if let UpgradeableLoaderState::Buffer { authority_address } = buffer_account.state().unwrap() { assert_eq!(authority_address, Some(authority_keypair.pubkey())); } else { panic!("not a buffer account"); } assert_eq!( buffer_account.data[UpgradeableLoaderState::buffer_data_offset().unwrap()..], program_data[..] ); // Specify authority only let buffer_keypair = Keypair::new(); let authority_keypair = Keypair::new(); config.signers = vec![&keypair, &buffer_keypair, &authority_keypair]; config.command = CliCommand::Program(ProgramCliCommand::WriteBuffer { program_location: noop_path.to_str().unwrap().to_string(), buffer_signer_index: None, buffer_pubkey: None, buffer_authority_signer_index: Some(2), max_len: None, }); let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let buffer_pubkey_str = json .as_object() .unwrap() .get("buffer") .unwrap() .as_str() .unwrap(); let buffer_pubkey = Pubkey::from_str(buffer_pubkey_str).unwrap(); let buffer_account = rpc_client.get_account(&buffer_pubkey).unwrap(); assert_eq!(buffer_account.lamports, minimum_balance_for_buffer_default); assert_eq!(buffer_account.owner, bpf_loader_upgradeable::id()); if let UpgradeableLoaderState::Buffer { authority_address } = buffer_account.state().unwrap() { assert_eq!(authority_address, Some(authority_keypair.pubkey())); } else { panic!("not a buffer account"); } assert_eq!( buffer_account.data[UpgradeableLoaderState::buffer_data_offset().unwrap()..], program_data[..] ); // Get buffer authority config.signers = vec![]; config.command = CliCommand::Program(ProgramCliCommand::Show { account_pubkey: Some(buffer_pubkey), authority_pubkey: keypair.pubkey(), get_programs: false, get_buffers: false, all: false, use_lamports_unit: false, }); let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let authority_pubkey_str = json .as_object() .unwrap() .get("authority") .unwrap() .as_str() .unwrap(); assert_eq!( authority_keypair.pubkey(), Pubkey::from_str(authority_pubkey_str).unwrap() ); // Close buffer let close_account = rpc_client.get_account(&buffer_pubkey).unwrap(); assert_eq!(minimum_balance_for_buffer, close_account.lamports); let recipient_pubkey = Pubkey::new_unique(); config.signers = vec![&keypair, &authority_keypair]; config.command = CliCommand::Program(ProgramCliCommand::Close { account_pubkey: Some(buffer_pubkey), recipient_pubkey, authority_index: 1, use_lamports_unit: false, }); process_command(&config).unwrap(); rpc_client.get_account(&buffer_pubkey).unwrap_err(); let recipient_account = rpc_client.get_account(&recipient_pubkey).unwrap(); assert_eq!(minimum_balance_for_buffer, recipient_account.lamports); // Write a buffer with default params config.signers = vec![&keypair]; config.command = CliCommand::Program(ProgramCliCommand::WriteBuffer { program_location: noop_path.to_str().unwrap().to_string(), buffer_signer_index: None, buffer_pubkey: None, buffer_authority_signer_index: None, max_len: None, }); config.output_format = OutputFormat::JsonCompact; let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let buffer_pubkey_str = json .as_object() .unwrap() .get("buffer") .unwrap() .as_str() .unwrap(); let new_buffer_pubkey = Pubkey::from_str(buffer_pubkey_str).unwrap(); // Close buffers and deposit default keypair let pre_lamports = rpc_client.get_account(&keypair.pubkey()).unwrap().lamports; config.signers = vec![&keypair]; config.command = CliCommand::Program(ProgramCliCommand::Close { account_pubkey: Some(new_buffer_pubkey), recipient_pubkey: keypair.pubkey(), authority_index: 0, use_lamports_unit: false, }); process_command(&config).unwrap(); rpc_client.get_account(&new_buffer_pubkey).unwrap_err(); let recipient_account = rpc_client.get_account(&keypair.pubkey()).unwrap(); assert_eq!( pre_lamports + minimum_balance_for_buffer, recipient_account.lamports ); // write small buffer then attempt to deploy larger program let buffer_keypair = Keypair::new(); config.signers = vec![&keypair, &buffer_keypair]; config.command = CliCommand::Program(ProgramCliCommand::WriteBuffer { program_location: noop_path.to_str().unwrap().to_string(), buffer_signer_index: Some(1), buffer_pubkey: Some(buffer_keypair.pubkey()), buffer_authority_signer_index: None, max_len: None, //Some(max_len), }); process_command(&config).unwrap(); config.signers = vec![&keypair, &buffer_keypair]; config.command = CliCommand::Program(ProgramCliCommand::Deploy { program_location: Some(noop_large_path.to_str().unwrap().to_string()), program_signer_index: None, program_pubkey: None, buffer_signer_index: Some(1), buffer_pubkey: Some(buffer_keypair.pubkey()), allow_excessive_balance: false, upgrade_authority_signer_index: 1, is_final: true, max_len: None, }); config.output_format = OutputFormat::JsonCompact; let error = process_command(&config).unwrap_err(); assert_eq!( error.to_string(), "Buffer account passed is not large enough, may have been for a different deploy?" ); } #[test] fn test_cli_program_set_buffer_authority() { solana_logger::setup(); let mut noop_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); noop_path.push("tests"); noop_path.push("fixtures"); noop_path.push("noop"); noop_path.set_extension("so"); let mint_keypair = Keypair::new(); let mint_pubkey = mint_keypair.pubkey(); let faucet_addr = run_local_faucet(mint_keypair, None); let test_validator = TestValidator::with_no_fees(mint_pubkey, Some(faucet_addr), SocketAddrSpace::Unspecified); let rpc_client = RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed()); let mut file = File::open(noop_path.to_str().unwrap()).unwrap(); let mut program_data = Vec::new(); file.read_to_end(&mut program_data).unwrap(); let max_len = program_data.len(); let minimum_balance_for_buffer = rpc_client .get_minimum_balance_for_rent_exemption( UpgradeableLoaderState::programdata_len(max_len).unwrap(), ) .unwrap(); let mut config = CliConfig::recent_for_tests(); let keypair = Keypair::new(); config.json_rpc_url = test_validator.rpc_url(); config.signers = vec![&keypair]; config.command = CliCommand::Airdrop { pubkey: None, lamports: 100 * minimum_balance_for_buffer, }; process_command(&config).unwrap(); // Write a buffer let buffer_keypair = Keypair::new(); config.signers = vec![&keypair, &buffer_keypair]; config.command = CliCommand::Program(ProgramCliCommand::WriteBuffer { program_location: noop_path.to_str().unwrap().to_string(), buffer_signer_index: Some(1), buffer_pubkey: Some(buffer_keypair.pubkey()), buffer_authority_signer_index: None, max_len: None, }); process_command(&config).unwrap(); let buffer_account = rpc_client.get_account(&buffer_keypair.pubkey()).unwrap(); if let UpgradeableLoaderState::Buffer { authority_address } = buffer_account.state().unwrap() { assert_eq!(authority_address, Some(keypair.pubkey())); } else { panic!("not a buffer account"); } // Set new authority let new_buffer_authority = Keypair::new(); config.signers = vec![&keypair, &buffer_keypair]; config.command = CliCommand::Program(ProgramCliCommand::SetBufferAuthority { buffer_pubkey: buffer_keypair.pubkey(), buffer_authority_index: Some(0), new_buffer_authority: new_buffer_authority.pubkey(), }); config.output_format = OutputFormat::JsonCompact; let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let new_buffer_authority_str = json .as_object() .unwrap() .get("authority") .unwrap() .as_str() .unwrap(); assert_eq!( Pubkey::from_str(new_buffer_authority_str).unwrap(), new_buffer_authority.pubkey() ); let buffer_account = rpc_client.get_account(&buffer_keypair.pubkey()).unwrap(); if let UpgradeableLoaderState::Buffer { authority_address } = buffer_account.state().unwrap() { assert_eq!(authority_address, Some(new_buffer_authority.pubkey())); } else { panic!("not a buffer account"); } // Set authority to buffer config.signers = vec![&keypair, &new_buffer_authority]; config.command = CliCommand::Program(ProgramCliCommand::SetBufferAuthority { buffer_pubkey: buffer_keypair.pubkey(), buffer_authority_index: Some(1), new_buffer_authority: buffer_keypair.pubkey(), }); let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let buffer_authority_str = json .as_object() .unwrap() .get("authority") .unwrap() .as_str() .unwrap(); assert_eq!( Pubkey::from_str(buffer_authority_str).unwrap(), buffer_keypair.pubkey() ); let buffer_account = rpc_client.get_account(&buffer_keypair.pubkey()).unwrap(); if let UpgradeableLoaderState::Buffer { authority_address } = buffer_account.state().unwrap() { assert_eq!(authority_address, Some(buffer_keypair.pubkey())); } else { panic!("not a buffer account"); } } #[test] fn test_cli_program_mismatch_buffer_authority() { solana_logger::setup(); let mut noop_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); noop_path.push("tests"); noop_path.push("fixtures"); noop_path.push("noop"); noop_path.set_extension("so"); let mint_keypair = Keypair::new(); let mint_pubkey = mint_keypair.pubkey(); let faucet_addr = run_local_faucet(mint_keypair, None); let test_validator = TestValidator::with_no_fees(mint_pubkey, Some(faucet_addr), SocketAddrSpace::Unspecified); let rpc_client = RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed()); let mut file = File::open(noop_path.to_str().unwrap()).unwrap(); let mut program_data = Vec::new(); file.read_to_end(&mut program_data).unwrap(); let max_len = program_data.len(); let minimum_balance_for_buffer = rpc_client .get_minimum_balance_for_rent_exemption( UpgradeableLoaderState::programdata_len(max_len).unwrap(), ) .unwrap(); let mut config = CliConfig::recent_for_tests(); let keypair = Keypair::new(); config.json_rpc_url = test_validator.rpc_url(); config.signers = vec![&keypair]; config.command = CliCommand::Airdrop { pubkey: None, lamports: 100 * minimum_balance_for_buffer, }; process_command(&config).unwrap(); // Write a buffer let buffer_authority = Keypair::new(); let buffer_keypair = Keypair::new(); config.signers = vec![&keypair, &buffer_keypair, &buffer_authority]; config.command = CliCommand::Program(ProgramCliCommand::WriteBuffer { program_location: noop_path.to_str().unwrap().to_string(), buffer_signer_index: Some(1), buffer_pubkey: Some(buffer_keypair.pubkey()), buffer_authority_signer_index: Some(2), max_len: None, }); process_command(&config).unwrap(); let buffer_account = rpc_client.get_account(&buffer_keypair.pubkey()).unwrap(); if let UpgradeableLoaderState::Buffer { authority_address } = buffer_account.state().unwrap() { assert_eq!(authority_address, Some(buffer_authority.pubkey())); } else { panic!("not a buffer account"); } // Attempt to deploy with mismatched authority let upgrade_authority = Keypair::new(); config.signers = vec![&keypair, &upgrade_authority]; config.command = CliCommand::Program(ProgramCliCommand::Deploy { program_location: Some(noop_path.to_str().unwrap().to_string()), program_signer_index: None, program_pubkey: None, buffer_signer_index: None, buffer_pubkey: Some(buffer_keypair.pubkey()), allow_excessive_balance: false, upgrade_authority_signer_index: 1, is_final: true, max_len: None, }); process_command(&config).unwrap_err(); // Attempt to deploy matched authority config.signers = vec![&keypair, &buffer_authority]; config.command = CliCommand::Program(ProgramCliCommand::Deploy { program_location: Some(noop_path.to_str().unwrap().to_string()), program_signer_index: None, program_pubkey: None, buffer_signer_index: None, buffer_pubkey: Some(buffer_keypair.pubkey()), allow_excessive_balance: false, upgrade_authority_signer_index: 1, is_final: true, max_len: None, }); process_command(&config).unwrap(); } #[test] fn
() { solana_logger::setup(); let mut noop_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); noop_path.push("tests"); noop_path.push("fixtures"); noop_path.push("noop"); noop_path.set_extension("so"); let mint_keypair = Keypair::new(); let mint_pubkey = mint_keypair.pubkey(); let faucet_addr = run_local_faucet(mint_keypair, None); let test_validator = TestValidator::with_no_fees(mint_pubkey, Some(faucet_addr), SocketAddrSpace::Unspecified); let rpc_client = RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed()); let mut file = File::open(noop_path.to_str().unwrap()).unwrap(); let mut program_data = Vec::new(); file.read_to_end(&mut program_data).unwrap(); let max_len = program_data.len(); let minimum_balance_for_buffer = rpc_client .get_minimum_balance_for_rent_exemption( UpgradeableLoaderState::programdata_len(max_len).unwrap(), ) .unwrap(); let mut config = CliConfig::recent_for_tests(); let keypair = Keypair::new(); config.json_rpc_url = test_validator.rpc_url(); config.output_format = OutputFormat::Json; // Airdrop config.signers = vec![&keypair]; config.command = CliCommand::Airdrop { pubkey: None, lamports: 100 * minimum_balance_for_buffer, }; process_command(&config).unwrap(); // Write a buffer let buffer_keypair = Keypair::new(); let authority_keypair = Keypair::new(); config.signers = vec![&keypair, &buffer_keypair, &authority_keypair]; config.command = CliCommand::Program(ProgramCliCommand::WriteBuffer { program_location: noop_path.to_str().unwrap().to_string(), buffer_signer_index: Some(1), buffer_pubkey: Some(buffer_keypair.pubkey()), buffer_authority_signer_index: Some(2), max_len: None, }); process_command(&config).unwrap(); // Verify show config.signers = vec![&keypair]; config.command = CliCommand::Program(ProgramCliCommand::Show { account_pubkey: Some(buffer_keypair.pubkey()), authority_pubkey: keypair.pubkey(), get_programs: false, get_buffers: false, all: false, use_lamports_unit: false, }); let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let address_str = json .as_object() .unwrap() .get("address") .unwrap() .as_str() .unwrap(); assert_eq!( buffer_keypair.pubkey(), Pubkey::from_str(address_str).unwrap() ); let authority_str = json .as_object() .unwrap() .get("authority") .unwrap() .as_str() .unwrap(); assert_eq!( authority_keypair.pubkey(), Pubkey::from_str(authority_str).unwrap() ); let data_len = json .as_object() .unwrap() .get("dataLen") .unwrap() .as_u64() .unwrap(); assert_eq!(max_len, data_len as usize); // Deploy let program_keypair = Keypair::new(); config.signers = vec![&keypair, &authority_keypair, &program_keypair]; config.command = CliCommand::Program(ProgramCliCommand::Deploy { program_location: Some(noop_path.to_str().unwrap().to_string()), program_signer_index: Some(2), program_pubkey: Some(program_keypair.pubkey()), buffer_signer_index: None, buffer_pubkey: None, allow_excessive_balance: false, upgrade_authority_signer_index: 1, is_final: false, max_len: Some(max_len), }); config.output_format = OutputFormat::JsonCompact; let min_slot = rpc_client.get_slot().unwrap(); process_command(&config).unwrap(); let max_slot = rpc_client.get_slot().unwrap(); // Verify show config.signers = vec![&keypair]; config.command = CliCommand::Program(ProgramCliCommand::Show { account_pubkey: Some(program_keypair.pubkey()), authority_pubkey: keypair.pubkey(), get_programs: false, get_buffers: false, all: false, use_lamports_unit: false, }); let response = process_command(&config); let json: Value = serde_json::from_str(&response.unwrap()).unwrap(); let address_str = json .as_object() .unwrap() .get("programId") .unwrap() .as_str() .unwrap(); assert_eq!( program_keypair.pubkey(), Pubkey::from_str(address_str).unwrap() ); let programdata_address_str = json .as_object() .unwrap() .get("programdataAddress") .unwrap() .as_str() .unwrap(); let (programdata_pubkey, _) = Pubkey::find_program_address( &[program_keypair.pubkey().as_ref()], &bpf_loader_upgradeable::id(), ); assert_eq!( programdata_pubkey, Pubkey::from_str(programdata_address_str).unwrap() ); let authority_str = json .as_object() .unwrap() .get("authority") .unwrap() .as_str() .unwrap(); assert_eq!( authority_keypair.pubkey(), Pubkey::from_str(authority_str).unwrap() ); let deployed_slot = json .as_object() .unwrap() .get("lastDeploySlot") .unwrap() .as_u64() .unwrap(); assert!(deployed_slot >= min_slot); assert!(deployed_slot <= max_slot); let data_len = json .as_object() .unwrap() .get("dataLen") .unwrap() .as_u64() .unwrap(); assert_eq!(max_len, data_len as usize); } #[test] fn test_cli_program_dump() { solana_logger::setup(); let mut noop_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); noop_path.push("tests"); noop_path.push("fixtures"); noop_path.push("noop"); noop_path.set_extension("so"); let mint_keypair = Keypair::new(); let mint_pubkey = mint_keypair.pubkey(); let faucet_addr = run_local_faucet(mint_keypair, None); let test_validator = TestValidator::with_no_fees(mint_pubkey, Some(faucet_addr), SocketAddrSpace::Unspecified); let rpc_client = RpcClient::new_with_commitment(test_validator.rpc_url(), CommitmentConfig::processed()); let mut file = File::open(noop_path.to_str().unwrap()).unwrap(); let mut program_data = Vec::new(); file.read_to_end(&mut program_data).unwrap(); let max_len = program_data.len(); let minimum_balance_for_buffer = rpc_client .get_minimum_balance_for_rent_exemption( UpgradeableLoaderState::programdata_len(max_len).unwrap(), ) .unwrap(); let mut config = CliConfig::recent_for_tests(); let keypair = Keypair::new(); config.json_rpc_url = test_validator.rpc_url(); config.output_format = OutputFormat::Json; // Airdrop config.signers = vec![&keypair]; config.command = CliCommand::Airdrop { pubkey: None, lamports: 100 * minimum_balance_for_buffer, }; process_command(&config).unwrap(); // Write a buffer let buffer_keypair = Keypair::new(); let authority_keypair = Keypair::new(); config.signers = vec![&keypair, &buffer_keypair, &authority_keypair]; config.command = CliCommand::Program(ProgramCliCommand::WriteBuffer { program_location: noop_path.to_str().unwrap().to_string(), buffer_signer_index: Some(1), buffer_pubkey: Some(buffer_keypair.pubkey()), buffer_authority_signer_index: Some(2), max_len: None, }); process_command(&config).unwrap(); // Verify dump let mut out_file = { let current_exe = env::current_exe().unwrap(); PathBuf::from(current_exe.parent().unwrap().parent().unwrap()) }; out_file.set_file_name("out.txt"); config.signers = vec![&keypair]; config.command = CliCommand::Program(ProgramCliCommand::Dump { account_pubkey: Some(buffer_keypair.pubkey()), output_location: out_file.clone().into_os_string().into_string().unwrap(), }); process_command(&config).unwrap(); let mut file = File::open(out_file).unwrap(); let mut out_data = Vec::new(); file.read_to_end(&mut out_data).unwrap(); assert_eq!(program_data.len(), out_data.len()); for i in 0..program_data.len() { assert_eq!(program_data[i], out_data[i]); } }
test_cli_program_show
session.pb.gw.go
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. // source: server/session/session.proto /* Package session is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ package session import ( "context" "io" "net/http" "github.com/golang/protobuf/descriptor" "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) // Suppress "imported and not used" errors var _ codes.Code var _ io.Reader var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage var _ = metadata.Join func request_SessionService_GetUserInfo_0(ctx context.Context, marshaler runtime.Marshaler, client SessionServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq GetUserInfoRequest var metadata runtime.ServerMetadata msg, err := client.GetUserInfo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func
(ctx context.Context, marshaler runtime.Marshaler, server SessionServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq GetUserInfoRequest var metadata runtime.ServerMetadata msg, err := server.GetUserInfo(ctx, &protoReq) return msg, metadata, err } func request_SessionService_Create_0(ctx context.Context, marshaler runtime.Marshaler, client SessionServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SessionCreateRequest var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := client.Create(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_SessionService_Create_0(ctx context.Context, marshaler runtime.Marshaler, server SessionServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SessionCreateRequest var metadata runtime.ServerMetadata newReader, berr := utilities.IOReaderFactory(req.Body) if berr != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) } if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } msg, err := server.Create(ctx, &protoReq) return msg, metadata, err } func request_SessionService_Delete_0(ctx context.Context, marshaler runtime.Marshaler, client SessionServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SessionDeleteRequest var metadata runtime.ServerMetadata msg, err := client.Delete(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } func local_request_SessionService_Delete_0(ctx context.Context, marshaler runtime.Marshaler, server SessionServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq SessionDeleteRequest var metadata runtime.ServerMetadata msg, err := server.Delete(ctx, &protoReq) return msg, metadata, err } // RegisterSessionServiceHandlerServer registers the http handlers for service SessionService to "mux". // UnaryRPC :call SessionServiceServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterSessionServiceHandlerFromEndpoint instead. func RegisterSessionServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server SessionServiceServer) error { mux.Handle("GET", pattern_SessionService_GetUserInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_SessionService_GetUserInfo_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_SessionService_GetUserInfo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_SessionService_Create_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_SessionService_Create_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_SessionService_Create_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("DELETE", pattern_SessionService_Delete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := local_request_SessionService_Delete_0(rctx, inboundMarshaler, server, req, pathParams) md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_SessionService_Delete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } // RegisterSessionServiceHandlerFromEndpoint is same as RegisterSessionServiceHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterSessionServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { conn, err := grpc.Dial(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) } }() }() return RegisterSessionServiceHandler(ctx, mux, conn) } // RegisterSessionServiceHandler registers the http handlers for service SessionService to "mux". // The handlers forward requests to the grpc endpoint over "conn". func RegisterSessionServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterSessionServiceHandlerClient(ctx, mux, NewSessionServiceClient(conn)) } // RegisterSessionServiceHandlerClient registers the http handlers for service SessionService // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "SessionServiceClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "SessionServiceClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "SessionServiceClient" to call the correct interceptors. func RegisterSessionServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client SessionServiceClient) error { mux.Handle("GET", pattern_SessionService_GetUserInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_SessionService_GetUserInfo_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_SessionService_GetUserInfo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("POST", pattern_SessionService_Create_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_SessionService_Create_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_SessionService_Create_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) mux.Handle("DELETE", pattern_SessionService_Delete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } resp, md, err := request_SessionService_Delete_0(rctx, inboundMarshaler, client, req, pathParams) ctx = runtime.NewServerMetadataContext(ctx, md) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } forward_SessionService_Delete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) return nil } var ( pattern_SessionService_GetUserInfo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"api", "v1", "session", "userinfo"}, "", runtime.AssumeColonVerbOpt(true))) pattern_SessionService_Create_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"api", "v1", "session"}, "", runtime.AssumeColonVerbOpt(true))) pattern_SessionService_Delete_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"api", "v1", "session"}, "", runtime.AssumeColonVerbOpt(true))) ) var ( forward_SessionService_GetUserInfo_0 = runtime.ForwardResponseMessage forward_SessionService_Create_0 = runtime.ForwardResponseMessage forward_SessionService_Delete_0 = runtime.ForwardResponseMessage )
local_request_SessionService_GetUserInfo_0
tx.go
package cli import ( "github.com/spf13/cobra" "github.com/cosmos/osmosis-sdk/client" "github.com/cosmos/osmosis-sdk/client/flags" "github.com/cosmos/osmosis-sdk/client/tx" sdk "github.com/cosmos/osmosis-sdk/types" "github.com/cosmos/osmosis-sdk/x/slashing/types" ) // NewTxCmd returns a root CLI command handler for all x/slashing transaction commands. func NewTxCmd() *cobra.Command { slashingTxCmd := &cobra.Command{ Use: types.ModuleName, Short: "Slashing transaction subcommands", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, RunE: client.ValidateCmd, } slashingTxCmd.AddCommand(NewUnjailTxCmd()) return slashingTxCmd } func NewUnjailTxCmd() *cobra.Command
{ cmd := &cobra.Command{ Use: "unjail", Args: cobra.NoArgs, Short: "unjail validator previously jailed for downtime", Long: `unjail a jailed validator: $ <appd> tx slashing unjail --from mykey `, RunE: func(cmd *cobra.Command, args []string) error { clientCtx, err := client.GetClientTxContext(cmd) if err != nil { return err } valAddr := clientCtx.GetFromAddress() msg := types.NewMsgUnjail(sdk.ValAddress(valAddr)) if err := msg.ValidateBasic(); err != nil { return err } return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, } flags.AddTxFlagsToCmd(cmd) return cmd }
auth.component.ts
import {Component, OnInit} from '@angular/core'; import {Router} from '@angular/router'; import {Data} from 'src/app/core/shared-data/shared-data'; import {ConfirmationService, MessageService} from 'primeng/api'; import {UserService} from 'src/app/core/user/user.service'; import {AuthService} from "../../core/auth/service/auth.service"; import {EAuthTask} from "../../core/auth/service/auth-task"; import {utils} from "../../core/utils/utils"; import {TranslocoService} from "@ngneat/transloco"; import {finalize, first} from "rxjs"; @Component({ selector: 'sw-auth', templateUrl: './auth.component.html' }) export class AuthComponent implements OnInit { constructor(private readonly authService: AuthService, private readonly router: Router, private readonly messageService: MessageService, private readonly userService: UserService, private readonly translocoService: TranslocoService, private readonly confirmationService: ConfirmationService) { } ngOnInit(): void { const url = Data.GetAndRemove('authURL') as URL; if (url == null) { this.router.navigateByUrl('/home'); return; } const state = url.searchParams.get('state') as string; const code = url.searchParams.get('code') as string; const scope = url.searchParams.get('scope') as string; this.authService.authenticate(state, code, scope) .subscribe({ next: (response) => { if (response.Result.Task == EAuthTask.Register) { this.userService.setUserRegisterData(response.Result); this.router.navigateByUrl('/home/register'); } if (response.Result.Task == EAuthTask.Login) { this.userService.setUserData(response.Result); this.userService.redirecLoggedUser(); } if (response.Result.Task == EAuthTask.Activate) { utils.openModal(this.confirmationService, this.translocoService, 'home.auth.reactivateUserTitle', 'home.auth.reactivateUserMessage', () => this.sendEmailToReactivateAccount(response.Result.Token), () => this.router.navigateByUrl('/home')
); } }, error: (errorResponse) => { utils.toastError(errorResponse, this.messageService, this.translocoService) this.router.navigateByUrl('/home'); } }); } private sendEmailToReactivateAccount(userId: string): void { this.userService.reactivateAccountEmail(userId) .pipe(finalize(() => this.router.navigateByUrl('/home'))) .subscribe({ next: () => { utils.toastSuccess(this.messageService, this.translocoService, this.translocoService.translate('home.auth.reactivateEmailSend')); }, error: (errorResponse) => { utils.toastError(errorResponse, this.messageService, this.translocoService) } }); } }
transform.rs
use crate::config::OutputConfig; use crate::metrics::{RECONNECT_COUNTER, SENT_COUNTER, SENT_HISTO}; use anyhow::{anyhow, Result}; use crossbeam::select; use crossbeam_channel::Receiver; use std::io::prelude::*; use std::net::TcpStream; use std::time::Duration; use std::{net::SocketAddr, net::ToSocketAddrs}; use tracing::{error, info}; use vapi::vsl::LogRecord; fn send_to_stdout(rx: Receiver<LogRecord>) -> Result<()> { loop { select! { recv(rx) -> res => { let log = match res { Ok(l) => l, Err(e) => { error!("Error recv: {}", e); continue; }, }; SENT_COUNTER.inc(); let timer = SENT_HISTO.start_timer(); println!("-----------------------------------------"); println!("{}", serde_json::to_string_pretty(&log).unwrap()); timer.observe_duration(); } } } } fn loop_until_connected( addr: &SocketAddr, timeout: Duration, retry_interval: Duration, ) -> TcpStream { loop { match TcpStream::connect_timeout(addr, timeout) { Ok(s) => { info!("Connected to {}", addr); return s; } Err(e) => { error!("Failed to connect: {}", e); std::thread::sleep(retry_interval); } } } } fn send_to_tcp( rx: Receiver<LogRecord>, host: &str, port: u16, timeout: u64, retry_interval: u64, sender_threads: u64, ) -> Result<()> { let addr: SocketAddr = (host, port) .to_socket_addrs()? .next() .ok_or_else(|| anyhow!("Invalid addr: {}:{}", host, port))?; let timeout = Duration::from_secs(timeout); let retry_interval = Duration::from_secs(retry_interval); let _ = crossbeam::thread::scope(|s| { let mut handles = Vec::new(); for i in 0..sender_threads { let h = s.spawn(|_| -> ! { let mut stream = loop_until_connected(&addr, timeout, retry_interval); loop { select! { recv(rx) -> res => { let log = match res { Ok(l) => l, Err(e) => { error!("Error in recv: {}", e); continue; }, }; SENT_COUNTER.inc(); let mut json: String = match serde_json::to_string(&log) { Ok(j) => j, Err(e) => { error!("Couldn't transform struct: {}", e); continue; }, }; json.push('\n'); let timer = SENT_HISTO.start_timer(); let res = stream.write(json.as_bytes()); timer.observe_duration(); if let Err(e) = res { error!("Error writing to TCP socket: {}", e); stream = loop_until_connected(&addr, timeout, retry_interval); RECONNECT_COUNTER.inc(); } } } } }); info!("Started sender thread {}", i); handles.push(h); } for handle in handles { let _ = handle.join(); } }); Ok(()) } fn null_consumer(rx: Receiver<LogRecord>) -> Result<()>
pub fn consume_logs_forever(output: &OutputConfig, rx: Receiver<LogRecord>) { let res = match output { OutputConfig::Stdout => send_to_stdout(rx), OutputConfig::Tcp { host, port, connect_timeout_secs, retry_interval_secs, sender_threads, } => send_to_tcp( rx, host, *port, *connect_timeout_secs, *retry_interval_secs, *sender_threads, ), OutputConfig::Null => null_consumer(rx), }; if let Err(e) = res { error!("Output failure: {}", e); std::process::exit(1); } }
{ loop { select! { recv(rx) -> res => { match res { Ok(_) => { SENT_COUNTER.inc(); } Err(e) => { error!("Error in transform: {}", e)} } } } } }
odin.py
import json from fastapi import APIRouter, HTTPException from util.helm import Helm from models.deployRequest import DeployRequest from models.rollbackRequest import RollbackRequest from util.utilityHelpers import Utils from util.kubernetes import Kubernentes import etcd3 router = APIRouter() etcd = etcd3.client() @router.post("/odin/service/", tags=["odin"]) async def deploy_service(deploy_request: DeployRequest): try: Helm.odinHelmSetup() output = Utils.getJson(Helm.deployService(deploy_request.service_name, deploy_request.chart_name, deploy_request.values)) service_list = Utils.getJson(Helm.listAllServices()) etcd.put('service_list', json.dumps(service_list)) return { "status": "200", "metadata": output, "error": "" } except Exception as ex: raise HTTPException( status_code=500, detail="Service deployment failed: " + str(ex)) @router.delete("/odin/service/{service_name}", tags=["odin"]) async def delete_service(service_name):
@router.get("/odin/service/{service_name}/status", tags=["odin"]) async def get_status(service_name): try: status = Utils.getJson(Helm.getServiceStatus(service_name)) values = Utils.getJson(Helm.getServiceValues(service_name)) revisions = Utils.getJson(Helm.getServiceRevisions(service_name)) return { "status": "200", "metadata": status, "values": values, "revisions": revisions, "error": "" } except Exception as ex: raise HTTPException( status_code=500, detail="Failed to fetch Service Status: " + str(ex)) @router.get("/odin/service/{service_name}/revisions", tags=["odin"]) async def get_revisions(service_name): try: revisions = Utils.getJson(Helm.getServiceRevisions(service_name)) return { "status": "200", "revisions": revisions, "error": "" } except Exception as ex: raise HTTPException( status_code=500, detail="Failed to fetch Service Revisions: " + str(ex)) @router.post("/odin/service/rollback", tags=["odin"]) async def rollback_service(rollback_request: RollbackRequest): try: Helm.odinHelmSetup() Helm.rollbackService( rollback_request.service_name, rollback_request.revision) return { "status": "200", "metadata": "Rolled back successfully", "error": "" } except Exception as ex: raise HTTPException( status_code=500, detail="Service deployment failed: " + str(ex)) @router.get("/odin/services/", tags=["odin"]) async def get_all_services(): try: # service_list = Utils.getJsonValue(etcd, 'service_list') service_list = Utils.getJson(Helm.listAllServices()) return { "status": "200", "metadata": service_list, "error": "" } except Exception as ex: raise HTTPException( status_code=500, detail="Failed to fetch all services: " + str(ex)) @router.get("/odin/metrics/{pod_name}", tags=["odin"]) async def get_pod_metrics(pod_name): try: metrics_params = Kubernentes.getPodMetrics(podName=pod_name).split() return { "status": "200", "metadata": { "name": metrics_params[3], "cpu": metrics_params[4], "memory": metrics_params[5] } } except Exception as ex: raise HTTPException( status_code=500, details="Error getting metrics: " + str(ex) )
try: Helm.deleteService(service_name) service_list = Utils.getJson(Helm.listAllServices()) etcd.put('service_list', json.dumps(service_list)) return { "status": "200", "error": "" } except Exception as ex: raise HTTPException( status_code=500, detail="Service delete failed: " + str(ex))
palm_pretrain.py
from libai.config import LazyCall, get_config
graph = get_config("common/models/graph.py").graph train = get_config("common/train.py").train optim = get_config("common/optim.py").optim data = get_config("common/data/gpt_dataset.py") dataloader = data.dataloader tokenization = data.tokenization vocab_file = "./projects/PaLM/gpt_dataset/gpt2-vocab.json" merge_files = "./projects/PaLM/gpt_dataset/gpt2-merges.txt" data_prefix = "./projects/PaLM/gpt_dataset/loss_compara_content_sentence" tokenization.tokenizer.vocab_file = vocab_file tokenization.tokenizer.merges_file = merge_files dataloader.train.dataset[0].data_prefix = data_prefix dataloader.train.dataset[0].indexed_dataset.data_prefix = data_prefix train.train_micro_batch_size = 4 train.activation_checkpoint.enabled = True train.evaluation.evaluator = LazyCall(PPLEvaluator)() train.output_dir = "./output/palm_output"
from .models.palm_small import model from libai.evaluation import PPLEvaluator
ModalWrapper.tsx
import * as React from 'react'; import * as PropTypes from 'prop-types'; import ModalDialog from '../_shared/ModalDialog'; import { Omit } from '@material-ui/core'; import { WrapperProps } from './Wrapper'; import { DialogProps as MuiDialogProps } from '@material-ui/core/Dialog'; export interface ModalWrapperProps<T = {}> extends WrapperProps<T> { /** * "OK" label message * @default 'OK' */ okLabel?: React.ReactNode; /** * "CANCEL" label message * @default 'CANCEL' */ cancelLabel?: React.ReactNode; /** * "CLEAR" label message * @default 'CLEAR' */ clearLabel?: React.ReactNode; /** * "CLEAR" label message * @default 'CLEAR' */ todayLabel?: React.ReactNode; /** * If true today button will be displayed <b>Note*</b> that clear button has higher priority * @default false */ showTodayButton?: boolean; /** * Show clear action in picker dialog * @default false */ clearable?: boolean; /** * Props to be passed directly to material-ui Dialog * @type {Partial<MuiDialogProps>} */ DialogProps?: Partial<Omit<MuiDialogProps, 'classes'>>; } export const ModalWrapper: React.FC<ModalWrapperProps<any>> = ({ open, children, okLabel, cancelLabel, clearLabel, todayLabel, showTodayButton, clearable, DialogProps, showTabs, wider, InputComponent, DateInputProps, onClear, onAccept, onDismiss, onSetToday, ...other }) => { const handleKeyDown = React.useCallback( (event: KeyboardEvent) => { switch (event.key) { case 'Enter': onAccept(); break; default: return; // if key is not handled, stop execution } // if event was handled prevent other side effects event.preventDefault(); }, [onAccept] ); return ( <React.Fragment> <InputComponent {...other} {...DateInputProps} /> <ModalDialog wider={wider} showTabs={showTabs} open={open} onKeyDownInner={handleKeyDown} onClear={onClear} onAccept={onAccept}
todayLabel={todayLabel} okLabel={okLabel} cancelLabel={cancelLabel} clearable={clearable} showTodayButton={showTodayButton} children={children} {...DialogProps} /> </React.Fragment> ); }; ModalWrapper.propTypes = { okLabel: PropTypes.node, cancelLabel: PropTypes.node, clearLabel: PropTypes.node, clearable: PropTypes.bool, todayLabel: PropTypes.node, showTodayButton: PropTypes.bool, DialogProps: PropTypes.object, } as any; ModalWrapper.defaultProps = { okLabel: 'OK', cancelLabel: 'Cancel', clearLabel: 'Clear', todayLabel: 'Today', clearable: false, showTodayButton: false, }; export default ModalWrapper;
onDismiss={onDismiss} onSetToday={onSetToday} clearLabel={clearLabel}
styles.js
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["styles"],{ /***/ "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css": /*!************************************************************************!*\ !*** ./node_modules/@angular/material/prebuilt-themes/indigo-pink.css ***! \************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var content = __webpack_require__(/*! !../../../raw-loader!../../../postcss-loader/lib??embedded!./indigo-pink.css */ "./node_modules/raw-loader/index.js!./node_modules/postcss-loader/lib/index.js??embedded!./node_modules/@angular/material/prebuilt-themes/indigo-pink.css"); if(typeof content === 'string') content = [[module.i, content, '']]; var transform; var insertInto; var options = {"hmr":true} options.transform = transform options.insertInto = undefined; var update = __webpack_require__(/*! ../../../style-loader/lib/addStyles.js */ "./node_modules/style-loader/lib/addStyles.js")(content, options); if(content.locals) module.exports = content.locals; if(false) {} /***/ }), /***/ "./node_modules/raw-loader/index.js!./node_modules/postcss-loader/lib/index.js??embedded!./node_modules/@angular/material/prebuilt-themes/indigo-pink.css": /*!**********************************************************************************************************************************************!*\ !*** ./node_modules/raw-loader!./node_modules/postcss-loader/lib??embedded!./node_modules/@angular/material/prebuilt-themes/indigo-pink.css ***! \**********************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = ".mat-badge-content{font-weight:600;font-size:12px;font-family:Roboto,\"Helvetica Neue\",sans-serif}.mat-badge-small .mat-badge-content{font-size:6px}.mat-badge-large .mat-badge-content{font-size:24px}.mat-h1,.mat-headline,.mat-typography h1{font:400 24px/32px Roboto,\"Helvetica Neue\",sans-serif;margin:0 0 16px}.mat-h2,.mat-title,.mat-typography h2{font:500 20px/32px Roboto,\"Helvetica Neue\",sans-serif;margin:0 0 16px}.mat-h3,.mat-subheading-2,.mat-typography h3{font:400 16px/28px Roboto,\"Helvetica Neue\",sans-serif;margin:0 0 16px}.mat-h4,.mat-subheading-1,.mat-typography h4{font:400 15px/24px Roboto,\"Helvetica Neue\",sans-serif;margin:0 0 16px}.mat-h5,.mat-typography h5{font:400 11.62px/20px Roboto,\"Helvetica Neue\",sans-serif;margin:0 0 12px}.mat-h6,.mat-typography h6{font:400 9.38px/20px Roboto,\"Helvetica Neue\",sans-serif;margin:0 0 12px}.mat-body-2,.mat-body-strong{font:500 14px/24px Roboto,\"Helvetica Neue\",sans-serif}.mat-body,.mat-body-1,.mat-typography{font:400 14px/20px Roboto,\"Helvetica Neue\",sans-serif}.mat-body p,.mat-body-1 p,.mat-typography p{margin:0 0 12px}.mat-caption,.mat-small{font:400 12px/20px Roboto,\"Helvetica Neue\",sans-serif}.mat-display-4,.mat-typography .mat-display-4{font:300 112px/112px Roboto,\"Helvetica Neue\",sans-serif;margin:0 0 56px;letter-spacing:-.05em}.mat-display-3,.mat-typography .mat-display-3{font:400 56px/56px Roboto,\"Helvetica Neue\",sans-serif;margin:0 0 64px;letter-spacing:-.02em}.mat-display-2,.mat-typography .mat-display-2{font:400 45px/48px Roboto,\"Helvetica Neue\",sans-serif;margin:0 0 64px;letter-spacing:-.005em}.mat-display-1,.mat-typography .mat-display-1{font:400 34px/40px Roboto,\"Helvetica Neue\",sans-serif;margin:0 0 64px}.mat-bottom-sheet-container{font:400 14px/20px Roboto,\"Helvetica Neue\",sans-serif}.mat-button,.mat-fab,.mat-flat-button,.mat-icon-button,.mat-mini-fab,.mat-raised-button,.mat-stroked-button{font-family:Roboto,\"Helvetica Neue\",sans-serif;font-size:14px;font-weight:500}.mat-button-toggle{font-family:Roboto,\"Helvetica Neue\",sans-serif}.mat-card{font-family:Roboto,\"Helvetica Neue\",sans-serif}.mat-card-title{font-size:24px;font-weight:500}.mat-card-header .mat-card-title{font-size:20px}.mat-card-content,.mat-card-subtitle{font-size:14px}.mat-checkbox{font-family:Roboto,\"Helvetica Neue\",sans-serif}.mat-checkbox-layout .mat-checkbox-label{line-height:24px}.mat-chip{font-size:14px;font-weight:500}.mat-chip .mat-chip-remove.mat-icon,.mat-chip .mat-chip-trailing-icon.mat-icon{font-size:18px}.mat-table{font-family:Roboto,\"Helvetica Neue\",sans-serif}.mat-header-cell{font-size:12px;font-weight:500}.mat-cell,.mat-footer-cell{font-size:14px}.mat-calendar{font-family:Roboto,\"Helvetica Neue\",sans-serif}.mat-calendar-body{font-size:13px}.mat-calendar-body-label,.mat-calendar-period-button{font-size:14px;font-weight:500}.mat-calendar-table-header th{font-size:11px;font-weight:400}.mat-dialog-title{font:500 20px/32px Roboto,\"Helvetica Neue\",sans-serif}.mat-expansion-panel-header{font-family:Roboto,\"Helvetica Neue\",sans-serif;font-size:15px;font-weight:400}.mat-expansion-panel-content{font:400 14px/20px Roboto,\"Helvetica Neue\",sans-serif}.mat-form-field{font-size:inherit;font-weight:400;line-height:1.125;font-family:Roboto,\"Helvetica Neue\",sans-serif}.mat-form-field-wrapper{padding-bottom:1.34375em}.mat-form-field-prefix .mat-icon,.mat-form-field-suffix .mat-icon{font-size:150%;line-height:1.125}.mat-form-field-prefix .mat-icon-button,.mat-form-field-suffix .mat-icon-button{height:1.5em;width:1.5em}.mat-form-field-prefix .mat-icon-button .mat-icon,.mat-form-field-suffix .mat-icon-button .mat-icon{height:1.125em;line-height:1.125}.mat-form-field-infix{padding:.5em 0;border-top:.84375em solid transparent}.mat-form-field-can-float .mat-input-server:focus+.mat-form-field-label-wrapper .mat-form-field-label,.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-label{-webkit-transform:translateY(-1.34375em) scale(.75);transform:translateY(-1.34375em) scale(.75);width:133.33333%}.mat-form-field-can-float .mat-input-server[label]:not(:label-shown)+.mat-form-field-label-wrapper .mat-form-field-label{-webkit-transform:translateY(-1.34374em) scale(.75);transform:translateY(-1.34374em) scale(.75);width:133.33334%}.mat-form-field-label-wrapper{top:-.84375em;padding-top:.84375em}.mat-form-field-label{top:1.34375em}.mat-form-field-underline{bottom:1.34375em}.mat-form-field-subscript-wrapper{font-size:75%;margin-top:.66667em;top:calc(100% - 1.79167em)}.mat-form-field-appearance-legacy .mat-form-field-wrapper{padding-bottom:1.25em}.mat-form-field-appearance-legacy .mat-form-field-infix{padding:.4375em 0}.mat-form-field-appearance-legacy.mat-form-field-can-float .mat-input-server:focus+.mat-form-field-label-wrapper .mat-form-field-label,.mat-form-field-appearance-legacy.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-label{-webkit-transform:translateY(-1.28125em) scale(.75) perspective(100px) translateZ(.001px);transform:translateY(-1.28125em) scale(.75) perspective(100px) translateZ(.001px);-ms-transform:translateY(-1.28125em) scale(.75);width:133.33333%}.mat-form-field-appearance-legacy.mat-form-field-can-float .mat-form-field-autofill-control:-webkit-autofill+.mat-form-field-label-wrapper .mat-form-field-label{-webkit-transform:translateY(-1.28125em) scale(.75) perspective(100px) translateZ(.00101px);transform:translateY(-1.28125em) scale(.75) perspective(100px) translateZ(.00101px);-ms-transform:translateY(-1.28124em) scale(.75);width:133.33334%}.mat-form-field-appearance-legacy.mat-form-field-can-float .mat-input-server[label]:not(:label-shown)+.mat-form-field-label-wrapper .mat-form-field-label{-webkit-transform:translateY(-1.28125em) scale(.75) perspective(100px) translateZ(.00102px);transform:translateY(-1.28125em) scale(.75) perspective(100px) translateZ(.00102px);-ms-transform:translateY(-1.28123em) scale(.75);width:133.33335%}.mat-form-field-appearance-legacy .mat-form-field-label{top:1.28125em}.mat-form-field-appearance-legacy .mat-form-field-underline{bottom:1.25em}.mat-form-field-appearance-legacy .mat-form-field-subscript-wrapper{margin-top:.54167em;top:calc(100% - 1.66667em)}@media print{.mat-form-field-appearance-legacy.mat-form-field-can-float .mat-input-server:focus+.mat-form-field-label-wrapper .mat-form-field-label,.mat-form-field-appearance-legacy.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-label{-webkit-transform:translateY(-1.28122em) scale(.75);transform:translateY(-1.28122em) scale(.75)}.mat-form-field-appearance-legacy.mat-form-field-can-float .mat-form-field-autofill-control:-webkit-autofill+.mat-form-field-label-wrapper .mat-form-field-label{-webkit-transform:translateY(-1.28121em) scale(.75);transform:translateY(-1.28121em) scale(.75)}.mat-form-field-appearance-legacy.mat-form-field-can-float .mat-input-server[label]:not(:label-shown)+.mat-form-field-label-wrapper .mat-form-field-label{-webkit-transform:translateY(-1.2812em) scale(.75);transform:translateY(-1.2812em) scale(.75)}}.mat-form-field-appearance-fill .mat-form-field-infix{padding:.25em 0 .75em 0}.mat-form-field-appearance-fill .mat-form-field-label{top:1.09375em;margin-top:-.5em}.mat-form-field-appearance-fill.mat-form-field-can-float .mat-input-server:focus+.mat-form-field-label-wrapper .mat-form-field-label,.mat-form-field-appearance-fill.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-label{-webkit-transform:translateY(-.59375em) scale(.75);transform:translateY(-.59375em) scale(.75);width:133.33333%}.mat-form-field-appearance-fill.mat-form-field-can-float .mat-input-server[label]:not(:label-shown)+.mat-form-field-label-wrapper .mat-form-field-label{-webkit-transform:translateY(-.59374em) scale(.75);transform:translateY(-.59374em) scale(.75);width:133.33334%}.mat-form-field-appearance-outline .mat-form-field-infix{padding:1em 0 1em 0}.mat-form-field-appearance-outline .mat-form-field-label{top:1.84375em;margin-top:-.25em}.mat-form-field-appearance-outline.mat-form-field-can-float .mat-input-server:focus+.mat-form-field-label-wrapper .mat-form-field-label,.mat-form-field-appearance-outline.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-label{-webkit-transform:translateY(-1.59375em) scale(.75);transform:translateY(-1.59375em) scale(.75);width:133.33333%}.mat-form-field-appearance-outline.mat-form-field-can-float .mat-input-server[label]:not(:label-shown)+.mat-form-field-label-wrapper .mat-form-field-label{-webkit-transform:translateY(-1.59374em) scale(.75);transform:translateY(-1.59374em) scale(.75);width:133.33334%}.mat-grid-tile-footer,.mat-grid-tile-header{font-size:14px}.mat-grid-tile-footer .mat-line,.mat-grid-tile-header .mat-line{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;box-sizing:border-box}.mat-grid-tile-footer .mat-line:nth-child(n+2),.mat-grid-tile-header .mat-line:nth-child(n+2){font-size:12px}input.mat-input-element{margin-top:-.0625em}.mat-menu-item{font-family:Roboto,\"Helvetica Neue\",sans-serif;font-size:14px;font-weight:400}.mat-paginator,.mat-paginator-page-size .mat-select-trigger{font-family:Roboto,\"Helvetica Neue\",sans-serif;font-size:12px}.mat-radio-button{font-family:Roboto,\"Helvetica Neue\",sans-serif}.mat-select{font-family:Roboto,\"Helvetica Neue\",sans-serif}.mat-select-trigger{height:1.125em}.mat-slide-toggle-content{font-family:Roboto,\"Helvetica Neue\",sans-serif}.mat-slider-thumb-label-text{font-family:Roboto,\"Helvetica Neue\",sans-serif;font-size:12px;font-weight:500}.mat-stepper-horizontal,.mat-stepper-vertical{font-family:Roboto,\"Helvetica Neue\",sans-serif}.mat-step-label{font-size:14px;font-weight:400}.mat-step-sub-label-error{font-weight:400}.mat-step-label-error{font-size:14px}.mat-step-label-selected{font-size:14px;font-weight:500}.mat-tab-group{font-family:Roboto,\"Helvetica Neue\",sans-serif}.mat-tab-label,.mat-tab-link{font-family:Roboto,\"Helvetica Neue\",sans-serif;font-size:14px;font-weight:500}.mat-toolbar,.mat-toolbar h1,.mat-toolbar h2,.mat-toolbar h3,.mat-toolbar h4,.mat-toolbar h5,.mat-toolbar h6{font:500 20px/32px Roboto,\"Helvetica Neue\",sans-serif;margin:0}.mat-tooltip{font-family:Roboto,\"Helvetica Neue\",sans-serif;font-size:10px;padding-top:6px;padding-bottom:6px}.mat-tooltip-handset{font-size:14px;padding-top:8px;padding-bottom:8px}.mat-list-item{font-family:Roboto,\"Helvetica Neue\",sans-serif}.mat-list-option{font-family:Roboto,\"Helvetica Neue\",sans-serif}.mat-list-base .mat-list-item{font-size:16px}.mat-list-base .mat-list-item .mat-line{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;box-sizing:border-box}.mat-list-base .mat-list-item .mat-line:nth-child(n+2){font-size:14px}.mat-list-base .mat-list-option{font-size:16px}.mat-list-base .mat-list-option .mat-line{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;box-sizing:border-box}.mat-list-base .mat-list-option .mat-line:nth-child(n+2){font-size:14px}.mat-list-base .mat-subheader{font-family:Roboto,\"Helvetica Neue\",sans-serif;font-size:14px;font-weight:500}.mat-list-base[dense] .mat-list-item{font-size:12px}.mat-list-base[dense] .mat-list-item .mat-line{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;box-sizing:border-box}.mat-list-base[dense] .mat-list-item .mat-line:nth-child(n+2){font-size:12px}.mat-list-base[dense] .mat-list-option{font-size:12px}.mat-list-base[dense] .mat-list-option .mat-line{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;box-sizing:border-box}.mat-list-base[dense] .mat-list-option .mat-line:nth-child(n+2){font-size:12px}.mat-list-base[dense] .mat-subheader{font-family:Roboto,\"Helvetica Neue\",sans-serif;font-size:12px;font-weight:500}.mat-option{font-family:Roboto,\"Helvetica Neue\",sans-serif;font-size:16px}.mat-optgroup-label{font:500 14px/24px Roboto,\"Helvetica Neue\",sans-serif}.mat-simple-snackbar{font-family:Roboto,\"Helvetica Neue\",sans-serif;font-size:14px}.mat-simple-snackbar-action{line-height:1;font-family:inherit;font-size:inherit;font-weight:500}.mat-tree{font-family:Roboto,\"Helvetica Neue\",sans-serif}.mat-nested-tree-node,.mat-tree-node{font-weight:400;font-size:14px}.mat-ripple{overflow:hidden;position:relative}.mat-ripple.mat-ripple-unbounded{overflow:visible}.mat-ripple-element{position:absolute;border-radius:50%;pointer-events:none;transition:opacity,-webkit-transform 0s cubic-bezier(0,0,.2,1);transition:opacity,transform 0s cubic-bezier(0,0,.2,1);transition:opacity,transform 0s cubic-bezier(0,0,.2,1),-webkit-transform 0s cubic-bezier(0,0,.2,1);-webkit-transform:scale(0);transform:scale(0)}@media screen and (-ms-high-contrast:active){.mat-ripple-element{display:none}}.cdk-visually-hidden{border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;outline:0;-webkit-appearance:none;-moz-appearance:none}.cdk-global-overlay-wrapper,.cdk-overlay-container{pointer-events:none;top:0;left:0;height:100%;width:100%}.cdk-overlay-container{position:fixed;z-index:1000}.cdk-overlay-container:empty{display:none}.cdk-global-overlay-wrapper{display:flex;position:absolute;z-index:1000}.cdk-overlay-pane{position:absolute;pointer-events:auto;box-sizing:border-box;z-index:1000;display:flex;max-width:100%;max-height:100%}.cdk-overlay-backdrop{position:absolute;top:0;bottom:0;left:0;right:0;z-index:1000;pointer-events:auto;-webkit-tap-highlight-color:transparent;transition:opacity .4s cubic-bezier(.25,.8,.25,1);opacity:0}.cdk-overlay-backdrop.cdk-overlay-backdrop-showing{opacity:1}@media screen and (-ms-high-contrast:active){.cdk-overlay-backdrop.cdk-overlay-backdrop-showing{opacity:.6}}.cdk-overlay-dark-backdrop{background:rgba(0,0,0,.32)}.cdk-overlay-transparent-backdrop,.cdk-overlay-transparent-backdrop.cdk-overlay-backdrop-showing{opacity:0}.cdk-overlay-connected-position-bounding-box{position:absolute;z-index:1000;display:flex;flex-direction:column;min-width:1px;min-height:1px}.cdk-global-scrollblock{position:fixed;width:100%;overflow-y:scroll}@-webkit-keyframes cdk-text-field-autofill-start{/*!*/}@keyframes cdk-text-field-autofill-start{/*!*/}@-webkit-keyframes cdk-text-field-autofill-end{/*!*/}@keyframes cdk-text-field-autofill-end{/*!*/}.cdk-text-field-autofill-monitored:-webkit-autofill{-webkit-animation-name:cdk-text-field-autofill-start;animation-name:cdk-text-field-autofill-start}.cdk-text-field-autofill-monitored:not(:-webkit-autofill){-webkit-animation-name:cdk-text-field-autofill-end;animation-name:cdk-text-field-autofill-end}textarea.cdk-textarea-autosize{resize:none}textarea.cdk-textarea-autosize-measuring{height:auto!important;overflow:hidden!important;padding:2px 0!important;box-sizing:content-box!important}.mat-ripple-element{background-color:rgba(0,0,0,.1)}.mat-option{color:rgba(0,0,0,.87)}.mat-option:focus:not(.mat-option-disabled),.mat-option:hover:not(.mat-option-disabled){background:rgba(0,0,0,.04)}.mat-option.mat-selected:not(.mat-option-multiple):not(.mat-option-disabled){background:rgba(0,0,0,.04)}.mat-option.mat-active{background:rgba(0,0,0,.04);color:rgba(0,0,0,.87)}.mat-option.mat-option-disabled{color:rgba(0,0,0,.38)}.mat-primary .mat-option.mat-selected:not(.mat-option-disabled){color:#3f51b5}.mat-accent .mat-option.mat-selected:not(.mat-option-disabled){color:#ff4081}.mat-warn .mat-option.mat-selected:not(.mat-option-disabled){color:#f44336}.mat-optgroup-label{color:rgba(0,0,0,.54)}.mat-optgroup-disabled .mat-optgroup-label{color:rgba(0,0,0,.38)}.mat-pseudo-checkbox{color:rgba(0,0,0,.54)}.mat-pseudo-checkbox::after{color:#fafafa}.mat-accent .mat-pseudo-checkbox-checked,.mat-accent .mat-pseudo-checkbox-indeterminate,.mat-pseudo-checkbox-checked,.mat-pseudo-checkbox-indeterminate{background:#ff4081}.mat-primary .mat-pseudo-checkbox-checked,.mat-primary .mat-pseudo-checkbox-indeterminate{background:#3f51b5}.mat-warn .mat-pseudo-checkbox-checked,.mat-warn .mat-pseudo-checkbox-indeterminate{background:#f44336}.mat-pseudo-checkbox-checked.mat-pseudo-checkbox-disabled{background:#b0b0b0}.mat-elevation-z0{box-shadow:0 0 0 0 rgba(0,0,0,.2),0 0 0 0 rgba(0,0,0,.14),0 0 0 0 rgba(0,0,0,.12)}.mat-elevation-z1{box-shadow:0 2px 1px -1px rgba(0,0,0,.2),0 1px 1px 0 rgba(0,0,0,.14),0 1px 3px 0 rgba(0,0,0,.12)}.mat-elevation-z2{box-shadow:0 3px 1px -2px rgba(0,0,0,.2),0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12)}.mat-elevation-z3{box-shadow:0 3px 3px -2px rgba(0,0,0,.2),0 3px 4px 0 rgba(0,0,0,.14),0 1px 8px 0 rgba(0,0,0,.12)}.mat-elevation-z4{box-shadow:0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12)}.mat-elevation-z5{box-shadow:0 3px 5px -1px rgba(0,0,0,.2),0 5px 8px 0 rgba(0,0,0,.14),0 1px 14px 0 rgba(0,0,0,.12)}.mat-elevation-z6{box-shadow:0 3px 5px -1px rgba(0,0,0,.2),0 6px 10px 0 rgba(0,0,0,.14),0 1px 18px 0 rgba(0,0,0,.12)}.mat-elevation-z7{box-shadow:0 4px 5px -2px rgba(0,0,0,.2),0 7px 10px 1px rgba(0,0,0,.14),0 2px 16px 1px rgba(0,0,0,.12)}.mat-elevation-z8{box-shadow:0 5px 5px -3px rgba(0,0,0,.2),0 8px 10px 1px rgba(0,0,0,.14),0 3px 14px 2px rgba(0,0,0,.12)}.mat-elevation-z9{box-shadow:0 5px 6px -3px rgba(0,0,0,.2),0 9px 12px 1px rgba(0,0,0,.14),0 3px 16px 2px rgba(0,0,0,.12)}.mat-elevation-z10{box-shadow:0 6px 6px -3px rgba(0,0,0,.2),0 10px 14px 1px rgba(0,0,0,.14),0 4px 18px 3px rgba(0,0,0,.12)}.mat-elevation-z11{box-shadow:0 6px 7px -4px rgba(0,0,0,.2),0 11px 15px 1px rgba(0,0,0,.14),0 4px 20px 3px rgba(0,0,0,.12)}.mat-elevation-z12{box-shadow:0 7px 8px -4px rgba(0,0,0,.2),0 12px 17px 2px rgba(0,0,0,.14),0 5px 22px 4px rgba(0,0,0,.12)}.mat-elevation-z13{box-shadow:0 7px 8px -4px rgba(0,0,0,.2),0 13px 19px 2px rgba(0,0,0,.14),0 5px 24px 4px rgba(0,0,0,.12)}.mat-elevation-z14{box-shadow:0 7px 9px -4px rgba(0,0,0,.2),0 14px 21px 2px rgba(0,0,0,.14),0 5px 26px 4px rgba(0,0,0,.12)}.mat-elevation-z15{box-shadow:0 8px 9px -5px rgba(0,0,0,.2),0 15px 22px 2px rgba(0,0,0,.14),0 6px 28px 5px rgba(0,0,0,.12)}.mat-elevation-z16{box-shadow:0 8px 10px -5px rgba(0,0,0,.2),0 16px 24px 2px rgba(0,0,0,.14),0 6px 30px 5px rgba(0,0,0,.12)}.mat-elevation-z17{box-shadow:0 8px 11px -5px rgba(0,0,0,.2),0 17px 26px 2px rgba(0,0,0,.14),0 6px 32px 5px rgba(0,0,0,.12)}.mat-elevation-z18{box-shadow:0 9px 11px -5px rgba(0,0,0,.2),0 18px 28px 2px rgba(0,0,0,.14),0 7px 34px 6px rgba(0,0,0,.12)}.mat-elevation-z19{box-shadow:0 9px 12px -6px rgba(0,0,0,.2),0 19px 29px 2px rgba(0,0,0,.14),0 7px 36px 6px rgba(0,0,0,.12)}.mat-elevation-z20{box-shadow:0 10px 13px -6px rgba(0,0,0,.2),0 20px 31px 3px rgba(0,0,0,.14),0 8px 38px 7px rgba(0,0,0,.12)}.mat-elevation-z21{box-shadow:0 10px 13px -6px rgba(0,0,0,.2),0 21px 33px 3px rgba(0,0,0,.14),0 8px 40px 7px rgba(0,0,0,.12)}.mat-elevation-z22{box-shadow:0 10px 14px -6px rgba(0,0,0,.2),0 22px 35px 3px rgba(0,0,0,.14),0 8px 42px 7px rgba(0,0,0,.12)}.mat-elevation-z23{box-shadow:0 11px 14px -7px rgba(0,0,0,.2),0 23px 36px 3px rgba(0,0,0,.14),0 9px 44px 8px rgba(0,0,0,.12)}.mat-elevation-z24{box-shadow:0 11px 15px -7px rgba(0,0,0,.2),0 24px 38px 3px rgba(0,0,0,.14),0 9px 46px 8px rgba(0,0,0,.12)}.mat-app-background{background-color:#fafafa;color:rgba(0,0,0,.87)}.mat-theme-loaded-marker{display:none}.mat-autocomplete-panel{background:#fff;color:rgba(0,0,0,.87)}.mat-autocomplete-panel:not([class*=mat-elevation-z]){box-shadow:0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12)}.mat-autocomplete-panel .mat-option.mat-selected:not(.mat-active):not(:hover){background:#fff}.mat-autocomplete-panel .mat-option.mat-selected:not(.mat-active):not(:hover):not(.mat-option-disabled){color:rgba(0,0,0,.87)}.mat-badge-content{color:#fff;background:#3f51b5}.mat-badge-accent .mat-badge-content{background:#ff4081;color:#fff}.mat-badge-warn .mat-badge-content{color:#fff;background:#f44336}.mat-badge{position:relative}.mat-badge-hidden .mat-badge-content{display:none}.mat-badge-disabled .mat-badge-content{background:#b9b9b9;color:rgba(0,0,0,.38)}.mat-badge-content{position:absolute;text-align:center;display:inline-block;border-radius:50%;transition:-webkit-transform .2s ease-in-out;transition:transform .2s ease-in-out;transition:transform .2s ease-in-out, -webkit-transform .2s ease-in-out;-webkit-transform:scale(.6);transform:scale(.6);overflow:hidden;white-space:nowrap;text-overflow:ellipsis;pointer-events:none}.mat-badge-content.mat-badge-active{-webkit-transform:none;transform:none}.mat-badge-small .mat-badge-content{width:16px;height:16px;line-height:16px}@media screen and (-ms-high-contrast:active){.mat-badge-small .mat-badge-content{outline:solid 1px;border-radius:0}}.mat-badge-small.mat-badge-above .mat-badge-content{top:-8px}.mat-badge-small.mat-badge-below .mat-badge-content{bottom:-8px}.mat-badge-small.mat-badge-before .mat-badge-content{left:-16px}[dir=rtl] .mat-badge-small.mat-badge-before .mat-badge-content{left:auto;right:-16px}.mat-badge-small.mat-badge-after .mat-badge-content{right:-16px}[dir=rtl] .mat-badge-small.mat-badge-after .mat-badge-content{right:auto;left:-16px}.mat-badge-small.mat-badge-overlap.mat-badge-before .mat-badge-content{left:-8px}[dir=rtl] .mat-badge-small.mat-badge-overlap.mat-badge-before .mat-badge-content{left:auto;right:-8px}.mat-badge-small.mat-badge-overlap.mat-badge-after .mat-badge-content{right:-8px}[dir=rtl] .mat-badge-small.mat-badge-overlap.mat-badge-after .mat-badge-content{right:auto;left:-8px}.mat-badge-medium .mat-badge-content{width:22px;height:22px;line-height:22px}@media screen and (-ms-high-contrast:active){.mat-badge-medium .mat-badge-content{outline:solid 1px;border-radius:0}}.mat-badge-medium.mat-badge-above .mat-badge-content{top:-11px}.mat-badge-medium.mat-badge-below .mat-badge-content{bottom:-11px}.mat-badge-medium.mat-badge-before .mat-badge-content{left:-22px}[dir=rtl] .mat-badge-medium.mat-badge-before .mat-badge-content{left:auto;right:-22px}.mat-badge-medium.mat-badge-after .mat-badge-content{right:-22px}[dir=rtl] .mat-badge-medium.mat-badge-after .mat-badge-content{right:auto;left:-22px}.mat-badge-medium.mat-badge-overlap.mat-badge-before .mat-badge-content{left:-11px}[dir=rtl] .mat-badge-medium.mat-badge-overlap.mat-badge-before .mat-badge-content{left:auto;right:-11px}.mat-badge-medium.mat-badge-overlap.mat-badge-after .mat-badge-content{right:-11px}[dir=rtl] .mat-badge-medium.mat-badge-overlap.mat-badge-after .mat-badge-content{right:auto;left:-11px}.mat-badge-large .mat-badge-content{width:28px;height:28px;line-height:28px}@media screen and (-ms-high-contrast:active){.mat-badge-large .mat-badge-content{outline:solid 1px;border-radius:0}}.mat-badge-large.mat-badge-above .mat-badge-content{top:-14px}.mat-badge-large.mat-badge-below .mat-badge-content{bottom:-14px}.mat-badge-large.mat-badge-before .mat-badge-content{left:-28px}[dir=rtl] .mat-badge-large.mat-badge-before .mat-badge-content{left:auto;right:-28px}.mat-badge-large.mat-badge-after .mat-badge-content{right:-28px}[dir=rtl] .mat-badge-large.mat-badge-after .mat-badge-content{right:auto;left:-28px}.mat-badge-large.mat-badge-overlap.mat-badge-before .mat-badge-content{left:-14px}[dir=rtl] .mat-badge-large.mat-badge-overlap.mat-badge-before .mat-badge-content{left:auto;right:-14px}.mat-badge-large.mat-badge-overlap.mat-badge-after .mat-badge-content{right:-14px}[dir=rtl] .mat-badge-large.mat-badge-overlap.mat-badge-after .mat-badge-content{right:auto;left:-14px}.mat-bottom-sheet-container{box-shadow:0 8px 10px -5px rgba(0,0,0,.2),0 16px 24px 2px rgba(0,0,0,.14),0 6px 30px 5px rgba(0,0,0,.12);background:#fff;color:rgba(0,0,0,.87)}.mat-button,.mat-icon-button,.mat-stroked-button{color:inherit;background:0 0}.mat-button.mat-primary,.mat-icon-button.mat-primary,.mat-stroked-button.mat-primary{color:#3f51b5}.mat-button.mat-accent,.mat-icon-button.mat-accent,.mat-stroked-button.mat-accent{color:#ff4081}.mat-button.mat-warn,.mat-icon-button.mat-warn,.mat-stroked-button.mat-warn{color:#f44336}.mat-button.mat-accent[disabled],.mat-button.mat-primary[disabled],.mat-button.mat-warn[disabled],.mat-button[disabled][disabled],.mat-icon-button.mat-accent[disabled],.mat-icon-button.mat-primary[disabled],.mat-icon-button.mat-warn[disabled],.mat-icon-button[disabled][disabled],.mat-stroked-button.mat-accent[disabled],.mat-stroked-button.mat-primary[disabled],.mat-stroked-button.mat-warn[disabled],.mat-stroked-button[disabled][disabled]{color:rgba(0,0,0,.26)}.mat-button.mat-primary .mat-button-focus-overlay,.mat-icon-button.mat-primary .mat-button-focus-overlay,.mat-stroked-button.mat-primary .mat-button-focus-overlay{background-color:#3f51b5}.mat-button.mat-accent .mat-button-focus-overlay,.mat-icon-button.mat-accent .mat-button-focus-overlay,.mat-stroked-button.mat-accent .mat-button-focus-overlay{background-color:#ff4081}.mat-button.mat-warn .mat-button-focus-overlay,.mat-icon-button.mat-warn .mat-button-focus-overlay,.mat-stroked-button.mat-warn .mat-button-focus-overlay{background-color:#f44336}.mat-button[disabled] .mat-button-focus-overlay,.mat-icon-button[disabled] .mat-button-focus-overlay,.mat-stroked-button[disabled] .mat-button-focus-overlay{background-color:transparent}.mat-button .mat-ripple-element,.mat-icon-button .mat-ripple-element,.mat-stroked-button .mat-ripple-element{opacity:.1;background-color:currentColor}.mat-button-focus-overlay{background:#000}.mat-stroked-button:not([disabled]){border-color:rgba(0,0,0,.12)}.mat-fab,.mat-flat-button,.mat-mini-fab,.mat-raised-button{color:rgba(0,0,0,.87);background-color:#fff}.mat-fab.mat-primary,.mat-flat-button.mat-primary,.mat-mini-fab.mat-primary,.mat-raised-button.mat-primary{color:#fff}.mat-fab.mat-accent,.mat-flat-button.mat-accent,.mat-mini-fab.mat-accent,.mat-raised-button.mat-accent{color:#fff}.mat-fab.mat-warn,.mat-flat-button.mat-warn,.mat-mini-fab.mat-warn,.mat-raised-button.mat-warn{color:#fff}.mat-fab.mat-accent[disabled],.mat-fab.mat-primary[disabled],.mat-fab.mat-warn[disabled],.mat-fab[disabled][disabled],.mat-flat-button.mat-accent[disabled],.mat-flat-button.mat-primary[disabled],.mat-flat-button.mat-warn[disabled],.mat-flat-button[disabled][disabled],.mat-mini-fab.mat-accent[disabled],.mat-mini-fab.mat-primary[disabled],.mat-mini-fab.mat-warn[disabled],.mat-mini-fab[disabled][disabled],.mat-raised-button.mat-accent[disabled],.mat-raised-button.mat-primary[disabled],.mat-raised-button.mat-warn[disabled],.mat-raised-button[disabled][disabled]{color:rgba(0,0,0,.26)}.mat-fab.mat-primary,.mat-flat-button.mat-primary,.mat-mini-fab.mat-primary,.mat-raised-button.mat-primary{background-color:#3f51b5}.mat-fab.mat-accent,.mat-flat-button.mat-accent,.mat-mini-fab.mat-accent,.mat-raised-button.mat-accent{background-color:#ff4081}.mat-fab.mat-warn,.mat-flat-button.mat-warn,.mat-mini-fab.mat-warn,.mat-raised-button.mat-warn{background-color:#f44336}.mat-fab.mat-accent[disabled],.mat-fab.mat-primary[disabled],.mat-fab.mat-warn[disabled],.mat-fab[disabled][disabled],.mat-flat-button.mat-accent[disabled],.mat-flat-button.mat-primary[disabled],.mat-flat-button.mat-warn[disabled],.mat-flat-button[disabled][disabled],.mat-mini-fab.mat-accent[disabled],.mat-mini-fab.mat-primary[disabled],.mat-mini-fab.mat-warn[disabled],.mat-mini-fab[disabled][disabled],.mat-raised-button.mat-accent[disabled],.mat-raised-button.mat-primary[disabled],.mat-raised-button.mat-warn[disabled],.mat-raised-button[disabled][disabled]{background-color:rgba(0,0,0,.12)}.mat-fab.mat-primary .mat-ripple-element,.mat-flat-button.mat-primary .mat-ripple-element,.mat-mini-fab.mat-primary .mat-ripple-element,.mat-raised-button.mat-primary .mat-ripple-element{background-color:rgba(255,255,255,.1)}.mat-fab.mat-accent .mat-ripple-element,.mat-flat-button.mat-accent .mat-ripple-element,.mat-mini-fab.mat-accent .mat-ripple-element,.mat-raised-button.mat-accent .mat-ripple-element{background-color:rgba(255,255,255,.1)}.mat-fab.mat-warn .mat-ripple-element,.mat-flat-button.mat-warn .mat-ripple-element,.mat-mini-fab.mat-warn .mat-ripple-element,.mat-raised-button.mat-warn .mat-ripple-element{background-color:rgba(255,255,255,.1)}.mat-flat-button:not([class*=mat-elevation-z]),.mat-stroked-button:not([class*=mat-elevation-z]){box-shadow:0 0 0 0 rgba(0,0,0,.2),0 0 0 0 rgba(0,0,0,.14),0 0 0 0 rgba(0,0,0,.12)}.mat-raised-button:not([class*=mat-elevation-z]){box-shadow:0 3px 1px -2px rgba(0,0,0,.2),0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12)}.mat-raised-button:not([disabled]):active:not([class*=mat-elevation-z]){box-shadow:0 5px 5px -3px rgba(0,0,0,.2),0 8px 10px 1px rgba(0,0,0,.14),0 3px 14px 2px rgba(0,0,0,.12)}.mat-raised-button[disabled]:not([class*=mat-elevation-z]){box-shadow:0 0 0 0 rgba(0,0,0,.2),0 0 0 0 rgba(0,0,0,.14),0 0 0 0 rgba(0,0,0,.12)}.mat-fab:not([class*=mat-elevation-z]),.mat-mini-fab:not([class*=mat-elevation-z]){box-shadow:0 3px 5px -1px rgba(0,0,0,.2),0 6px 10px 0 rgba(0,0,0,.14),0 1px 18px 0 rgba(0,0,0,.12)}.mat-fab:not([disabled]):active:not([class*=mat-elevation-z]),.mat-mini-fab:not([disabled]):active:not([class*=mat-elevation-z]){box-shadow:0 7px 8px -4px rgba(0,0,0,.2),0 12px 17px 2px rgba(0,0,0,.14),0 5px 22px 4px rgba(0,0,0,.12)}.mat-fab[disabled]:not([class*=mat-elevation-z]),.mat-mini-fab[disabled]:not([class*=mat-elevation-z]){box-shadow:0 0 0 0 rgba(0,0,0,.2),0 0 0 0 rgba(0,0,0,.14),0 0 0 0 rgba(0,0,0,.12)}.mat-button-toggle-group,.mat-button-toggle-standalone{box-shadow:0 3px 1px -2px rgba(0,0,0,.2),0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12)}.mat-button-toggle-group-appearance-standard,.mat-button-toggle-standalone.mat-button-toggle-appearance-standard{box-shadow:none}.mat-button-toggle{color:rgba(0,0,0,.38)}.mat-button-toggle .mat-button-toggle-focus-overlay{background-color:rgba(0,0,0,.12)}.mat-button-toggle-appearance-standard{color:rgba(0,0,0,.87);background:#fff}.mat-button-toggle-appearance-standard .mat-button-toggle-focus-overlay{background-color:#000}.mat-button-toggle-group-appearance-standard .mat-button-toggle+.mat-button-toggle{border-left:solid 1px rgba(0,0,0,.12)}[dir=rtl] .mat-button-toggle-group-appearance-standard .mat-button-toggle+.mat-button-toggle{border-left:none;border-right:solid 1px rgba(0,0,0,.12)}.mat-button-toggle-group-appearance-standard.mat-button-toggle-vertical .mat-button-toggle+.mat-button-toggle{border-left:none;border-right:none;border-top:solid 1px rgba(0,0,0,.12)}.mat-button-toggle-checked{background-color:#e0e0e0;color:rgba(0,0,0,.54)}.mat-button-toggle-checked.mat-button-toggle-appearance-standard{color:rgba(0,0,0,.87)}.mat-button-toggle-disabled{color:rgba(0,0,0,.26);background-color:#eee}.mat-button-toggle-disabled.mat-button-toggle-appearance-standard{background:#fff}.mat-button-toggle-disabled.mat-button-toggle-checked{background-color:#bdbdbd}.mat-button-toggle-group-appearance-standard,.mat-button-toggle-standalone.mat-button-toggle-appearance-standard{border:solid 1px rgba(0,0,0,.12)}.mat-card{background:#fff;color:rgba(0,0,0,.87)}.mat-card:not([class*=mat-elevation-z]){box-shadow:0 2px 1px -1px rgba(0,0,0,.2),0 1px 1px 0 rgba(0,0,0,.14),0 1px 3px 0 rgba(0,0,0,.12)}.mat-card.mat-card-flat:not([class*=mat-elevation-z]){box-shadow:0 0 0 0 rgba(0,0,0,.2),0 0 0 0 rgba(0,0,0,.14),0 0 0 0 rgba(0,0,0,.12)}.mat-card-subtitle{color:rgba(0,0,0,.54)}.mat-checkbox-frame{border-color:rgba(0,0,0,.54)}.mat-checkbox-checkmark{fill:#fafafa}.mat-checkbox-checkmark-path{stroke:#fafafa!important}@media screen and (-ms-high-contrast:black-on-white){.mat-checkbox-checkmark-path{stroke:#000!important}}.mat-checkbox-mixedmark{background-color:#fafafa}.mat-checkbox-checked.mat-primary .mat-checkbox-background,.mat-checkbox-indeterminate.mat-primary .mat-checkbox-background{background-color:#3f51b5}.mat-checkbox-checked.mat-accent .mat-checkbox-background,.mat-checkbox-indeterminate.mat-accent .mat-checkbox-background{background-color:#ff4081}.mat-checkbox-checked.mat-warn .mat-checkbox-background,.mat-checkbox-indeterminate.mat-warn .mat-checkbox-background{background-color:#f44336}.mat-checkbox-disabled.mat-checkbox-checked:not(.mat-checkbox-indeterminate) .mat-checkbox-background{background-color:#b0b0b0}.mat-checkbox-disabled:not(.mat-checkbox-checked) .mat-checkbox-frame{border-color:#b0b0b0}.mat-checkbox-disabled .mat-checkbox-label{color:rgba(0,0,0,.54)}@media screen and (-ms-high-contrast:active){.mat-checkbox-disabled{opacity:.5}}@media screen and (-ms-high-contrast:active){.mat-checkbox-background{background:0 0}}.mat-checkbox:not(.mat-checkbox-disabled).mat-primary .mat-checkbox-ripple .mat-ripple-element{background-color:#3f51b5}.mat-checkbox:not(.mat-checkbox-disabled).mat-accent .mat-checkbox-ripple .mat-ripple-element{background-color:#ff4081}.mat-checkbox:not(.mat-checkbox-disabled).mat-warn .mat-checkbox-ripple .mat-ripple-element{background-color:#f44336}.mat-chip.mat-standard-chip{background-color:#e0e0e0;color:rgba(0,0,0,.87)}.mat-chip.mat-standard-chip .mat-chip-remove{color:rgba(0,0,0,.87);opacity:.4}.mat-chip.mat-standard-chip:not(.mat-chip-disabled):active{box-shadow:0 3px 3px -2px rgba(0,0,0,.2),0 3px 4px 0 rgba(0,0,0,.14),0 1px 8px 0 rgba(0,0,0,.12)}.mat-chip.mat-standard-chip:not(.mat-chip-disabled) .mat-chip-remove:hover{opacity:.54}.mat-chip.mat-standard-chip.mat-chip-disabled{opacity:.4}.mat-chip.mat-standard-chip::after{background:#000}.mat-chip.mat-standard-chip.mat-chip-selected.mat-primary{background-color:#3f51b5;color:#fff}.mat-chip.mat-standard-chip.mat-chip-selected.mat-primary .mat-chip-remove{color:#fff;opacity:.4}.mat-chip.mat-standard-chip.mat-chip-selected.mat-primary .mat-ripple-element{background:rgba(255,255,255,.1)}.mat-chip.mat-standard-chip.mat-chip-selected.mat-warn{background-color:#f44336;color:#fff}.mat-chip.mat-standard-chip.mat-chip-selected.mat-warn .mat-chip-remove{color:#fff;opacity:.4}.mat-chip.mat-standard-chip.mat-chip-selected.mat-warn .mat-ripple-element{background:rgba(255,255,255,.1)}.mat-chip.mat-standard-chip.mat-chip-selected.mat-accent{background-color:#ff4081;color:#fff}.mat-chip.mat-standard-chip.mat-chip-selected.mat-accent .mat-chip-remove{color:#fff;opacity:.4}.mat-chip.mat-standard-chip.mat-chip-selected.mat-accent .mat-ripple-element{background:rgba(255,255,255,.1)}.mat-table{background:#fff}.mat-table tbody,.mat-table tfoot,.mat-table thead,.mat-table-sticky,[mat-footer-row],[mat-header-row],[mat-row],mat-footer-row,mat-header-row,mat-row{background:inherit}mat-footer-row,mat-header-row,mat-row,td.mat-cell,td.mat-footer-cell,th.mat-header-cell{border-bottom-color:rgba(0,0,0,.12)}.mat-header-cell{color:rgba(0,0,0,.54)}.mat-cell,.mat-footer-cell{color:rgba(0,0,0,.87)}.mat-calendar-arrow{border-top-color:rgba(0,0,0,.54)}.mat-datepicker-content .mat-calendar-next-button,.mat-datepicker-content .mat-calendar-previous-button,.mat-datepicker-toggle{color:rgba(0,0,0,.54)}.mat-calendar-table-header{color:rgba(0,0,0,.38)}.mat-calendar-table-header-divider::after{background:rgba(0,0,0,.12)}.mat-calendar-body-label{color:rgba(0,0,0,.54)}.mat-calendar-body-cell-content{color:rgba(0,0,0,.87);border-color:transparent}.mat-calendar-body-disabled>.mat-calendar-body-cell-content:not(.mat-calendar-body-selected){color:rgba(0,0,0,.38)}.cdk-keyboard-focused .mat-calendar-body-active>.mat-calendar-body-cell-content:not(.mat-calendar-body-selected),.cdk-program-focused .mat-calendar-body-active>.mat-calendar-body-cell-content:not(.mat-calendar-body-selected),.mat-calendar-body-cell:not(.mat-calendar-body-disabled):hover>.mat-calendar-body-cell-content:not(.mat-calendar-body-selected){background-color:rgba(0,0,0,.04)}.mat-calendar-body-today:not(.mat-calendar-body-selected){border-color:rgba(0,0,0,.38)}.mat-calendar-body-disabled>.mat-calendar-body-today:not(.mat-calendar-body-selected){border-color:rgba(0,0,0,.18)}.mat-calendar-body-selected{background-color:#3f51b5;color:#fff}.mat-calendar-body-disabled>.mat-calendar-body-selected{background-color:rgba(63,81,181,.4)}.mat-calendar-body-today.mat-calendar-body-selected{box-shadow:inset 0 0 0 1px #fff}.mat-datepicker-content{box-shadow:0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12);background-color:#fff;color:rgba(0,0,0,.87)}.mat-datepicker-content.mat-accent .mat-calendar-body-selected{background-color:#ff4081;color:#fff}.mat-datepicker-content.mat-accent .mat-calendar-body-disabled>.mat-calendar-body-selected{background-color:rgba(255,64,129,.4)}.mat-datepicker-content.mat-accent .mat-calendar-body-today.mat-calendar-body-selected{box-shadow:inset 0 0 0 1px #fff}.mat-datepicker-content.mat-warn .mat-calendar-body-selected{background-color:#f44336;color:#fff}.mat-datepicker-content.mat-warn .mat-calendar-body-disabled>.mat-calendar-body-selected{background-color:rgba(244,67,54,.4)}.mat-datepicker-content.mat-warn .mat-calendar-body-today.mat-calendar-body-selected{box-shadow:inset 0 0 0 1px #fff}.mat-datepicker-content-touch{box-shadow:0 0 0 0 rgba(0,0,0,.2),0 0 0 0 rgba(0,0,0,.14),0 0 0 0 rgba(0,0,0,.12)}.mat-datepicker-toggle-active{color:#3f51b5}.mat-datepicker-toggle-active.mat-accent{color:#ff4081}.mat-datepicker-toggle-active.mat-warn{color:#f44336}.mat-dialog-container{box-shadow:0 11px 15px -7px rgba(0,0,0,.2),0 24px 38px 3px rgba(0,0,0,.14),0 9px 46px 8px rgba(0,0,0,.12);background:#fff;color:rgba(0,0,0,.87)}.mat-divider{border-top-color:rgba(0,0,0,.12)}.mat-divider-vertical{border-right-color:rgba(0,0,0,.12)}.mat-expansion-panel{background:#fff;color:rgba(0,0,0,.87)}.mat-expansion-panel:not([class*=mat-elevation-z]){box-shadow:0 3px 1px -2px rgba(0,0,0,.2),0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12)}.mat-action-row{border-top-color:rgba(0,0,0,.12)}.mat-expansion-panel:not(.mat-expanded) .mat-expansion-panel-header:not([aria-disabled=true]).cdk-keyboard-focused,.mat-expansion-panel:not(.mat-expanded) .mat-expansion-panel-header:not([aria-disabled=true]).cdk-program-focused,.mat-expansion-panel:not(.mat-expanded) .mat-expansion-panel-header:not([aria-disabled=true]):hover{background:rgba(0,0,0,.04)}@media (hover:none){.mat-expansion-panel:not(.mat-expanded):not([aria-disabled=true]) .mat-expansion-panel-header:hover{background:#fff}}.mat-expansion-panel-header-title{color:rgba(0,0,0,.87)}.mat-expansion-indicator::after,.mat-expansion-panel-header-description{color:rgba(0,0,0,.54)}.mat-expansion-panel-header[aria-disabled=true]{color:rgba(0,0,0,.26)}.mat-expansion-panel-header[aria-disabled=true] .mat-expansion-panel-header-description,.mat-expansion-panel-header[aria-disabled=true] .mat-expansion-panel-header-title{color:inherit}.mat-form-field-label{color:rgba(0,0,0,.6)}.mat-hint{color:rgba(0,0,0,.6)}.mat-form-field.mat-focused .mat-form-field-label{color:#3f51b5}.mat-form-field.mat-focused .mat-form-field-label.mat-accent{color:#ff4081}.mat-form-field.mat-focused .mat-form-field-label.mat-warn{color:#f44336}.mat-focused .mat-form-field-required-marker{color:#ff4081}.mat-form-field-ripple{background-color:rgba(0,0,0,.87)}.mat-form-field.mat-focused .mat-form-field-ripple{background-color:#3f51b5}.mat-form-field.mat-focused .mat-form-field-ripple.mat-accent{background-color:#ff4081}.mat-form-field.mat-focused .mat-form-field-ripple.mat-warn{background-color:#f44336}.mat-form-field.mat-form-field-invalid .mat-form-field-label{color:#f44336}.mat-form-field.mat-form-field-invalid .mat-form-field-label .mat-form-field-required-marker,.mat-form-field.mat-form-field-invalid .mat-form-field-label.mat-accent{color:#f44336}.mat-form-field.mat-form-field-invalid .mat-form-field-ripple,.mat-form-field.mat-form-field-invalid .mat-form-field-ripple.mat-accent{background-color:#f44336}.mat-error{color:#f44336}.mat-form-field-appearance-legacy .mat-form-field-label{color:rgba(0,0,0,.54)}.mat-form-field-appearance-legacy .mat-hint{color:rgba(0,0,0,.54)}.mat-form-field-appearance-legacy .mat-form-field-underline{background-color:rgba(0,0,0,.42)}.mat-form-field-appearance-legacy.mat-form-field-disabled .mat-form-field-underline{background-image:linear-gradient(to right,rgba(0,0,0,.42) 0,rgba(0,0,0,.42) 33%,transparent 0);background-size:4px 100%;background-repeat:repeat-x}.mat-form-field-appearance-standard .mat-form-field-underline{background-color:rgba(0,0,0,.42)}.mat-form-field-appearance-standard.mat-form-field-disabled .mat-form-field-underline{background-image:linear-gradient(to right,rgba(0,0,0,.42) 0,rgba(0,0,0,.42) 33%,transparent 0);background-size:4px 100%;background-repeat:repeat-x}.mat-form-field-appearance-fill .mat-form-field-flex{background-color:rgba(0,0,0,.04)}.mat-form-field-appearance-fill.mat-form-field-disabled .mat-form-field-flex{background-color:rgba(0,0,0,.02)}.mat-form-field-appearance-fill .mat-form-field-underline::before{background-color:rgba(0,0,0,.42)}.mat-form-field-appearance-fill.mat-form-field-disabled .mat-form-field-label{color:rgba(0,0,0,.38)}.mat-form-field-appearance-fill.mat-form-field-disabled .mat-form-field-underline::before{background-color:transparent}.mat-form-field-appearance-outline .mat-form-field-outline{color:rgba(0,0,0,.12)}.mat-form-field-appearance-outline .mat-form-field-outline-thick{color:rgba(0,0,0,.87)}.mat-form-field-appearance-outline.mat-focused .mat-form-field-outline-thick{color:#3f51b5}.mat-form-field-appearance-outline.mat-focused.mat-accent .mat-form-field-outline-thick{color:#ff4081}.mat-form-field-appearance-outline.mat-focused.mat-warn .mat-form-field-outline-thick{color:#f44336}.mat-form-field-appearance-outline.mat-form-field-invalid.mat-form-field-invalid .mat-form-field-outline-thick{color:#f44336}.mat-form-field-appearance-outline.mat-form-field-disabled .mat-form-field-label{color:rgba(0,0,0,.38)}.mat-form-field-appearance-outline.mat-form-field-disabled .mat-form-field-outline{color:rgba(0,0,0,.06)}.mat-icon.mat-primary{color:#3f51b5}.mat-icon.mat-accent{color:#ff4081}.mat-icon.mat-warn{color:#f44336}.mat-form-field-type-mat-native-select .mat-form-field-infix::after{color:rgba(0,0,0,.54)}.mat-form-field-type-mat-native-select.mat-form-field-disabled .mat-form-field-infix::after,.mat-input-element:disabled{color:rgba(0,0,0,.38)}.mat-input-element{caret-color:#3f51b5}.mat-input-element::-webkit-input-placeholder{color:rgba(0,0,0,.42)}.mat-input-element::-ms-input-placeholder{color:rgba(0,0,0,.42)}.mat-input-element::placeholder{color:rgba(0,0,0,.42)}.mat-input-element::-moz-placeholder{color:rgba(0,0,0,.42)}.mat-input-element::-webkit-input-placeholder{color:rgba(0,0,0,.42)}.mat-input-element:-ms-input-placeholder{color:rgba(0,0,0,.42)}.mat-accent .mat-input-element{caret-color:#ff4081}.mat-form-field-invalid .mat-input-element,.mat-warn .mat-input-element{caret-color:#f44336}.mat-form-field-type-mat-native-select.mat-form-field-invalid .mat-form-field-infix::after{color:#f44336}.mat-list-base .mat-list-item{color:rgba(0,0,0,.87)}.mat-list-base .mat-list-option{color:rgba(0,0,0,.87)}.mat-list-base .mat-subheader{color:rgba(0,0,0,.54)}.mat-list-item-disabled{background-color:#eee}.mat-list-option:focus,.mat-list-option:hover,.mat-nav-list .mat-list-item:focus,.mat-nav-list .mat-list-item:hover{background:rgba(0,0,0,.04)}.mat-menu-panel{background:#fff}.mat-menu-panel:not([class*=mat-elevation-z]){box-shadow:0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12)}.mat-menu-item{background:0 0;color:rgba(0,0,0,.87)}.mat-menu-item[disabled],.mat-menu-item[disabled]::after{color:rgba(0,0,0,.38)}.mat-menu-item .mat-icon:not([color]),.mat-menu-item-submenu-trigger::after{color:rgba(0,0,0,.54)}.mat-menu-item-highlighted:not([disabled]),.mat-menu-item.cdk-keyboard-focused:not([disabled]),.mat-menu-item.cdk-program-focused:not([disabled]),.mat-menu-item:hover:not([disabled]){background:rgba(0,0,0,.04)}.mat-paginator{background:#fff}.mat-paginator,.mat-paginator-page-size .mat-select-trigger{color:rgba(0,0,0,.54)}.mat-paginator-decrement,.mat-paginator-increment{border-top:2px solid rgba(0,0,0,.54);border-right:2px solid rgba(0,0,0,.54)}.mat-paginator-first,.mat-paginator-last{border-top:2px solid rgba(0,0,0,.54)}.mat-icon-button[disabled] .mat-paginator-decrement,.mat-icon-button[disabled] .mat-paginator-first,.mat-icon-button[disabled] .mat-paginator-increment,.mat-icon-button[disabled] .mat-paginator-last{border-color:rgba(0,0,0,.38)}.mat-progress-bar-background{fill:#c5cae9}.mat-progress-bar-buffer{background-color:#c5cae9}.mat-progress-bar-fill::after{background-color:#3f51b5}.mat-progress-bar.mat-accent .mat-progress-bar-background{fill:#ff80ab}.mat-progress-bar.mat-accent .mat-progress-bar-buffer{background-color:#ff80ab}.mat-progress-bar.mat-accent .mat-progress-bar-fill::after{background-color:#ff4081}.mat-progress-bar.mat-warn .mat-progress-bar-background{fill:#ffcdd2}.mat-progress-bar.mat-warn .mat-progress-bar-buffer{background-color:#ffcdd2}.mat-progress-bar.mat-warn .mat-progress-bar-fill::after{background-color:#f44336}.mat-progress-spinner circle,.mat-spinner circle{stroke:#3f51b5}.mat-progress-spinner.mat-accent circle,.mat-spinner.mat-accent circle{stroke:#ff4081}.mat-progress-spinner.mat-warn circle,.mat-spinner.mat-warn circle{stroke:#f44336}.mat-radio-outer-circle{border-color:rgba(0,0,0,.54)}.mat-radio-button.mat-primary.mat-radio-checked .mat-radio-outer-circle{border-color:#3f51b5}.mat-radio-button.mat-primary .mat-radio-inner-circle,.mat-radio-button.mat-primary .mat-radio-ripple .mat-ripple-element:not(.mat-radio-persistent-ripple),.mat-radio-button.mat-primary.mat-radio-checked .mat-radio-persistent-ripple,.mat-radio-button.mat-primary:active .mat-radio-persistent-ripple{background-color:#3f51b5}.mat-radio-button.mat-accent.mat-radio-checked .mat-radio-outer-circle{border-color:#ff4081}.mat-radio-button.mat-accent .mat-radio-inner-circle,.mat-radio-button.mat-accent .mat-radio-ripple .mat-ripple-element:not(.mat-radio-persistent-ripple),.mat-radio-button.mat-accent.mat-radio-checked .mat-radio-persistent-ripple,.mat-radio-button.mat-accent:active .mat-radio-persistent-ripple{background-color:#ff4081}.mat-radio-button.mat-warn.mat-radio-checked .mat-radio-outer-circle{border-color:#f44336}.mat-radio-button.mat-warn .mat-radio-inner-circle,.mat-radio-button.mat-warn .mat-radio-ripple .mat-ripple-element:not(.mat-radio-persistent-ripple),.mat-radio-button.mat-warn.mat-radio-checked .mat-radio-persistent-ripple,.mat-radio-button.mat-warn:active .mat-radio-persistent-ripple{background-color:#f44336}.mat-radio-button.mat-radio-disabled .mat-radio-outer-circle,.mat-radio-button.mat-radio-disabled.mat-radio-checked .mat-radio-outer-circle{border-color:rgba(0,0,0,.38)}.mat-radio-button.mat-radio-disabled .mat-radio-inner-circle,.mat-radio-button.mat-radio-disabled .mat-radio-ripple .mat-ripple-element{background-color:rgba(0,0,0,.38)}.mat-radio-button.mat-radio-disabled .mat-radio-label-content{color:rgba(0,0,0,.38)}.mat-radio-button .mat-ripple-element{background-color:#000}.mat-select-value{color:rgba(0,0,0,.87)}.mat-select-placeholder{color:rgba(0,0,0,.42)}.mat-select-disabled .mat-select-value{color:rgba(0,0,0,.38)}.mat-select-arrow{color:rgba(0,0,0,.54)}.mat-select-panel{background:#fff}.mat-select-panel:not([class*=mat-elevation-z]){box-shadow:0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12)}.mat-select-panel .mat-option.mat-selected:not(.mat-option-multiple){background:rgba(0,0,0,.12)}.mat-form-field.mat-focused.mat-primary .mat-select-arrow{color:#3f51b5}.mat-form-field.mat-focused.mat-accent .mat-select-arrow{color:#ff4081}.mat-form-field.mat-focused.mat-warn .mat-select-arrow{color:#f44336}.mat-form-field .mat-select.mat-select-invalid .mat-select-arrow{color:#f44336}.mat-form-field .mat-select.mat-select-disabled .mat-select-arrow{color:rgba(0,0,0,.38)}.mat-drawer-container{background-color:#fafafa;color:rgba(0,0,0,.87)}.mat-drawer{background-color:#fff;color:rgba(0,0,0,.87)}.mat-drawer.mat-drawer-push{background-color:#fff}.mat-drawer:not(.mat-drawer-side){box-shadow:0 8px 10px -5px rgba(0,0,0,.2),0 16px 24px 2px rgba(0,0,0,.14),0 6px 30px 5px rgba(0,0,0,.12)}.mat-drawer-side{border-right:solid 1px rgba(0,0,0,.12)}.mat-drawer-side.mat-drawer-end{border-left:solid 1px rgba(0,0,0,.12);border-right:none}[dir=rtl] .mat-drawer-side{border-left:solid 1px rgba(0,0,0,.12);border-right:none}[dir=rtl] .mat-drawer-side.mat-drawer-end{border-left:none;border-right:solid 1px rgba(0,0,0,.12)}.mat-drawer-backdrop.mat-drawer-shown{background-color:rgba(0,0,0,.6)}.mat-slide-toggle.mat-checked .mat-slide-toggle-thumb{background-color:#ff4081}.mat-slide-toggle.mat-checked .mat-slide-toggle-bar{background-color:rgba(255,64,129,.54)}.mat-slide-toggle.mat-checked .mat-ripple-element{background-color:#ff4081}.mat-slide-toggle.mat-primary.mat-checked .mat-slide-toggle-thumb{background-color:#3f51b5}.mat-slide-toggle.mat-primary.mat-checked .mat-slide-toggle-bar{background-color:rgba(63,81,181,.54)}.mat-slide-toggle.mat-primary.mat-checked .mat-ripple-element{background-color:#3f51b5}.mat-slide-toggle.mat-warn.mat-checked .mat-slide-toggle-thumb{background-color:#f44336}.mat-slide-toggle.mat-warn.mat-checked .mat-slide-toggle-bar{background-color:rgba(244,67,54,.54)}.mat-slide-toggle.mat-warn.mat-checked .mat-ripple-element{background-color:#f44336}.mat-slide-toggle:not(.mat-checked) .mat-ripple-element{background-color:#000}.mat-slide-toggle-thumb{box-shadow:0 2px 1px -1px rgba(0,0,0,.2),0 1px 1px 0 rgba(0,0,0,.14),0 1px 3px 0 rgba(0,0,0,.12);background-color:#fafafa}.mat-slide-toggle-bar{background-color:rgba(0,0,0,.38)}.mat-slider-track-background{background-color:rgba(0,0,0,.26)}.mat-primary .mat-slider-thumb,.mat-primary .mat-slider-thumb-label,.mat-primary .mat-slider-track-fill{background-color:#3f51b5}.mat-primary .mat-slider-thumb-label-text{color:#fff}.mat-accent .mat-slider-thumb,.mat-accent .mat-slider-thumb-label,.mat-accent .mat-slider-track-fill{background-color:#ff4081}.mat-accent .mat-slider-thumb-label-text{color:#fff}.mat-warn .mat-slider-thumb,.mat-warn .mat-slider-thumb-label,.mat-warn .mat-slider-track-fill{background-color:#f44336}.mat-warn .mat-slider-thumb-label-text{color:#fff}.mat-slider-focus-ring{background-color:rgba(255,64,129,.2)}.cdk-focused .mat-slider-track-background,.mat-slider:hover .mat-slider-track-background{background-color:rgba(0,0,0,.38)}.mat-slider-disabled .mat-slider-thumb,.mat-slider-disabled .mat-slider-track-background,.mat-slider-disabled .mat-slider-track-fill{background-color:rgba(0,0,0,.26)}.mat-slider-disabled:hover .mat-slider-track-background{background-color:rgba(0,0,0,.26)}.mat-slider-min-value .mat-slider-focus-ring{background-color:rgba(0,0,0,.12)}.mat-slider-min-value.mat-slider-thumb-label-showing .mat-slider-thumb,.mat-slider-min-value.mat-slider-thumb-label-showing .mat-slider-thumb-label{background-color:rgba(0,0,0,.87)}.mat-slider-min-value.mat-slider-thumb-label-showing.cdk-focused .mat-slider-thumb,.mat-slider-min-value.mat-slider-thumb-label-showing.cdk-focused .mat-slider-thumb-label{background-color:rgba(0,0,0,.26)}.mat-slider-min-value:not(.mat-slider-thumb-label-showing) .mat-slider-thumb{border-color:rgba(0,0,0,.26);background-color:transparent}.mat-slider-min-value:not(.mat-slider-thumb-label-showing).cdk-focused .mat-slider-thumb,.mat-slider-min-value:not(.mat-slider-thumb-label-showing):hover .mat-slider-thumb{border-color:rgba(0,0,0,.38)}.mat-slider-min-value:not(.mat-slider-thumb-label-showing).cdk-focused.mat-slider-disabled .mat-slider-thumb,.mat-slider-min-value:not(.mat-slider-thumb-label-showing):hover.mat-slider-disabled .mat-slider-thumb{border-color:rgba(0,0,0,.26)}.mat-slider-has-ticks .mat-slider-wrapper::after{border-color:rgba(0,0,0,.7)}.mat-slider-horizontal .mat-slider-ticks{background-image:repeating-linear-gradient(to right,rgba(0,0,0,.7),rgba(0,0,0,.7) 2px,transparent 0,transparent);background-image:-moz-repeating-linear-gradient(.0001deg,rgba(0,0,0,.7),rgba(0,0,0,.7) 2px,transparent 0,transparent)}.mat-slider-vertical .mat-slider-ticks{background-image:repeating-linear-gradient(to bottom,rgba(0,0,0,.7),rgba(0,0,0,.7) 2px,transparent 0,transparent)}.mat-step-header.cdk-keyboard-focused,.mat-step-header.cdk-program-focused,.mat-step-header:hover{background-color:rgba(0,0,0,.04)}@media (hover:none){.mat-step-header:hover{background:0 0}}.mat-step-header .mat-step-label,.mat-step-header .mat-step-optional{color:rgba(0,0,0,.54)}.mat-step-header .mat-step-icon{background-color:rgba(0,0,0,.54);color:#fff}.mat-step-header .mat-step-icon-selected,.mat-step-header .mat-step-icon-state-done,.mat-step-header .mat-step-icon-state-edit{background-color:#3f51b5;color:#fff}.mat-step-header .mat-step-icon-state-error{background-color:transparent;color:#f44336}.mat-step-header .mat-step-label.mat-step-label-active{color:rgba(0,0,0,.87)}.mat-step-header .mat-step-label.mat-step-label-error{color:#f44336}.mat-stepper-horizontal,.mat-stepper-vertical{background-color:#fff}.mat-stepper-vertical-line::before{border-left-color:rgba(0,0,0,.12)}.mat-horizontal-stepper-header::after,.mat-horizontal-stepper-header::before,.mat-stepper-horizontal-line{border-top-color:rgba(0,0,0,.12)}.mat-sort-header-arrow{color:#757575}.mat-tab-header,.mat-tab-nav-bar{border-bottom:1px solid rgba(0,0,0,.12)}.mat-tab-group-inverted-header .mat-tab-header,.mat-tab-group-inverted-header .mat-tab-nav-bar{border-top:1px solid rgba(0,0,0,.12);border-bottom:none}.mat-tab-label,.mat-tab-link{color:rgba(0,0,0,.87)}.mat-tab-label.mat-tab-disabled,.mat-tab-link.mat-tab-disabled{color:rgba(0,0,0,.38)}.mat-tab-header-pagination-chevron{border-color:rgba(0,0,0,.87)}.mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron{border-color:rgba(0,0,0,.38)}.mat-tab-group[class*=mat-background-] .mat-tab-header,.mat-tab-nav-bar[class*=mat-background-]{border-bottom:none;border-top:none}.mat-tab-group.mat-primary .mat-tab-label.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-group.mat-primary .mat-tab-label.cdk-program-focused:not(.mat-tab-disabled),.mat-tab-group.mat-primary .mat-tab-link.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-group.mat-primary .mat-tab-link.cdk-program-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-primary .mat-tab-label.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-primary .mat-tab-label.cdk-program-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-primary .mat-tab-link.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-primary .mat-tab-link.cdk-program-focused:not(.mat-tab-disabled){background-color:rgba(197,202,233,.3)}.mat-tab-group.mat-primary .mat-ink-bar,.mat-tab-nav-bar.mat-primary .mat-ink-bar{background-color:#3f51b5}.mat-tab-group.mat-primary.mat-background-primary .mat-ink-bar,.mat-tab-nav-bar.mat-primary.mat-background-primary .mat-ink-bar{background-color:#fff}.mat-tab-group.mat-accent .mat-tab-label.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-group.mat-accent .mat-tab-label.cdk-program-focused:not(.mat-tab-disabled),.mat-tab-group.mat-accent .mat-tab-link.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-group.mat-accent .mat-tab-link.cdk-program-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-accent .mat-tab-label.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-accent .mat-tab-label.cdk-program-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-accent .mat-tab-link.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-accent .mat-tab-link.cdk-program-focused:not(.mat-tab-disabled){background-color:rgba(255,128,171,.3)}.mat-tab-group.mat-accent .mat-ink-bar,.mat-tab-nav-bar.mat-accent .mat-ink-bar{background-color:#ff4081}.mat-tab-group.mat-accent.mat-background-accent .mat-ink-bar,.mat-tab-nav-bar.mat-accent.mat-background-accent .mat-ink-bar{background-color:#fff}.mat-tab-group.mat-warn .mat-tab-label.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-group.mat-warn .mat-tab-label.cdk-program-focused:not(.mat-tab-disabled),.mat-tab-group.mat-warn .mat-tab-link.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-group.mat-warn .mat-tab-link.cdk-program-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-warn .mat-tab-label.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-warn .mat-tab-label.cdk-program-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-warn .mat-tab-link.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-warn .mat-tab-link.cdk-program-focused:not(.mat-tab-disabled){background-color:rgba(255,205,210,.3)}.mat-tab-group.mat-warn .mat-ink-bar,.mat-tab-nav-bar.mat-warn .mat-ink-bar{background-color:#f44336}.mat-tab-group.mat-warn.mat-background-warn .mat-ink-bar,.mat-tab-nav-bar.mat-warn.mat-background-warn .mat-ink-bar{background-color:#fff}.mat-tab-group.mat-background-primary .mat-tab-label.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-group.mat-background-primary .mat-tab-label.cdk-program-focused:not(.mat-tab-disabled),.mat-tab-group.mat-background-primary .mat-tab-link.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-group.mat-background-primary .mat-tab-link.cdk-program-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-background-primary .mat-tab-label.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-background-primary .mat-tab-label.cdk-program-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-background-primary .mat-tab-link.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-background-primary .mat-tab-link.cdk-program-focused:not(.mat-tab-disabled){background-color:rgba(197,202,233,.3)}.mat-tab-group.mat-background-primary .mat-tab-header,.mat-tab-group.mat-background-primary .mat-tab-links,.mat-tab-nav-bar.mat-background-primary .mat-tab-header,.mat-tab-nav-bar.mat-background-primary .mat-tab-links{background-color:#3f51b5}.mat-tab-group.mat-background-primary .mat-tab-label,.mat-tab-group.mat-background-primary .mat-tab-link,.mat-tab-nav-bar.mat-background-primary .mat-tab-label,.mat-tab-nav-bar.mat-background-primary .mat-tab-link{color:#fff}.mat-tab-group.mat-background-primary .mat-tab-label.mat-tab-disabled,.mat-tab-group.mat-background-primary .mat-tab-link.mat-tab-disabled,.mat-tab-nav-bar.mat-background-primary .mat-tab-label.mat-tab-disabled,.mat-tab-nav-bar.mat-background-primary .mat-tab-link.mat-tab-disabled{color:rgba(255,255,255,.4)}.mat-tab-group.mat-background-primary .mat-tab-header-pagination-chevron,.mat-tab-nav-bar.mat-background-primary .mat-tab-header-pagination-chevron{border-color:#fff}.mat-tab-group.mat-background-primary .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron,.mat-tab-nav-bar.mat-background-primary .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron{border-color:rgba(255,255,255,.4)}.mat-tab-group.mat-background-primary .mat-ripple-element,.mat-tab-nav-bar.mat-background-primary .mat-ripple-element{background-color:rgba(255,255,255,.12)}.mat-tab-group.mat-background-accent .mat-tab-label.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-group.mat-background-accent .mat-tab-label.cdk-program-focused:not(.mat-tab-disabled),.mat-tab-group.mat-background-accent .mat-tab-link.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-group.mat-background-accent .mat-tab-link.cdk-program-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-background-accent .mat-tab-label.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-background-accent .mat-tab-label.cdk-program-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-background-accent .mat-tab-link.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-background-accent .mat-tab-link.cdk-program-focused:not(.mat-tab-disabled){background-color:rgba(255,128,171,.3)}.mat-tab-group.mat-background-accent .mat-tab-header,.mat-tab-group.mat-background-accent .mat-tab-links,.mat-tab-nav-bar.mat-background-accent .mat-tab-header,.mat-tab-nav-bar.mat-background-accent .mat-tab-links{background-color:#ff4081}.mat-tab-group.mat-background-accent .mat-tab-label,.mat-tab-group.mat-background-accent .mat-tab-link,.mat-tab-nav-bar.mat-background-accent .mat-tab-label,.mat-tab-nav-bar.mat-background-accent .mat-tab-link{color:#fff}.mat-tab-group.mat-background-accent .mat-tab-label.mat-tab-disabled,.mat-tab-group.mat-background-accent .mat-tab-link.mat-tab-disabled,.mat-tab-nav-bar.mat-background-accent .mat-tab-label.mat-tab-disabled,.mat-tab-nav-bar.mat-background-accent .mat-tab-link.mat-tab-disabled{color:rgba(255,255,255,.4)}.mat-tab-group.mat-background-accent .mat-tab-header-pagination-chevron,.mat-tab-nav-bar.mat-background-accent .mat-tab-header-pagination-chevron{border-color:#fff}.mat-tab-group.mat-background-accent .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron,.mat-tab-nav-bar.mat-background-accent .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron{border-color:rgba(255,255,255,.4)}.mat-tab-group.mat-background-accent .mat-ripple-element,.mat-tab-nav-bar.mat-background-accent .mat-ripple-element{background-color:rgba(255,255,255,.12)}.mat-tab-group.mat-background-warn .mat-tab-label.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-group.mat-background-warn .mat-tab-label.cdk-program-focused:not(.mat-tab-disabled),.mat-tab-group.mat-background-warn .mat-tab-link.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-group.mat-background-warn .mat-tab-link.cdk-program-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-background-warn .mat-tab-label.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-background-warn .mat-tab-label.cdk-program-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-background-warn .mat-tab-link.cdk-keyboard-focused:not(.mat-tab-disabled),.mat-tab-nav-bar.mat-background-warn .mat-tab-link.cdk-program-focused:not(.mat-tab-disabled){background-color:rgba(255,205,210,.3)}.mat-tab-group.mat-background-warn .mat-tab-header,.mat-tab-group.mat-background-warn .mat-tab-links,.mat-tab-nav-bar.mat-background-warn .mat-tab-header,.mat-tab-nav-bar.mat-background-warn .mat-tab-links{background-color:#f44336}.mat-tab-group.mat-background-warn .mat-tab-label,.mat-tab-group.mat-background-warn .mat-tab-link,.mat-tab-nav-bar.mat-background-warn .mat-tab-label,.mat-tab-nav-bar.mat-background-warn .mat-tab-link{color:#fff}.mat-tab-group.mat-background-warn .mat-tab-label.mat-tab-disabled,.mat-tab-group.mat-background-warn .mat-tab-link.mat-tab-disabled,.mat-tab-nav-bar.mat-background-warn .mat-tab-label.mat-tab-disabled,.mat-tab-nav-bar.mat-background-warn .mat-tab-link.mat-tab-disabled{color:rgba(255,255,255,.4)}.mat-tab-group.mat-background-warn .mat-tab-header-pagination-chevron,.mat-tab-nav-bar.mat-background-warn .mat-tab-header-pagination-chevron{border-color:#fff}.mat-tab-group.mat-background-warn .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron,.mat-tab-nav-bar.mat-background-warn .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron{border-color:rgba(255,255,255,.4)}.mat-tab-group.mat-background-warn .mat-ripple-element,.mat-tab-nav-bar.mat-background-warn .mat-ripple-element{background-color:rgba(255,255,255,.12)}.mat-toolbar{background:#f5f5f5;color:rgba(0,0,0,.87)}.mat-toolbar.mat-primary{background:#3f51b5;color:#fff}.mat-toolbar.mat-accent{background:#ff4081;color:#fff}.mat-toolbar.mat-warn{background:#f44336;color:#fff}.mat-toolbar .mat-focused .mat-form-field-ripple,.mat-toolbar .mat-form-field-ripple,.mat-toolbar .mat-form-field-underline{background-color:currentColor}.mat-toolbar .mat-focused .mat-form-field-label,.mat-toolbar .mat-form-field-label,.mat-toolbar .mat-form-field.mat-focused .mat-select-arrow,.mat-toolbar .mat-select-arrow,.mat-toolbar .mat-select-value{color:inherit}.mat-toolbar .mat-input-element{caret-color:currentColor}.mat-tooltip{background:rgba(97,97,97,.9)}.mat-tree{background:#fff}.mat-nested-tree-node,.mat-tree-node{color:rgba(0,0,0,.87)}.mat-snack-bar-container{color:rgba(255,255,255,.7);background:#323232;box-shadow:0 3px 5px -1px rgba(0,0,0,.2),0 6px 10px 0 rgba(0,0,0,.14),0 1px 18px 0 rgba(0,0,0,.12)}.mat-simple-snackbar-action{color:#ff4081}" /***/ }), /***/ "./node_modules/raw-loader/index.js!./node_modules/postcss-loader/lib/index.js??embedded!./src/styles.css": /*!**********************************************************************************************!*\ !*** ./node_modules/raw-loader!./node_modules/postcss-loader/lib??embedded!./src/styles.css ***! \**********************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = "/* You can add global styles to this file, and also import other style files */\n\nhtml,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video{margin:0;padding:0;border:0;font-size:100%;font:inherit;vertical-align:baseline}\n\nbutton,input[type='button'],input[type='submit'],input[type='reset'],input[type='file']{border-radius:0}\n\ninput[type='text']::-ms-clear{display:none}\n\narticle,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block}\n\nbody{line-height:1}\n\nsup{vertical-align:super}\n\nsub{vertical-align:sub}\n\nol,ul{list-style:none}\n\nblockquote,q{quotes:none}\n\nblockquote:before,blockquote:after,q:before,q:after{content:'';content:none}\n\ntable{border-collapse:collapse;border-spacing:0}\n\n*{box-sizing:border-box}\n\n@-webkit-keyframes skeleton{0%{width:0%;left:0;right:auto;opacity:0.3}20%{width:100%;left:0;right:auto;opacity:1}28%{width:100%;left:auto;right:0}51%{width:0%;left:auto;right:0}58%{width:0%;left:auto;right:0}82%{width:100%;left:auto;right:0}83%{width:100%;left:0;right:auto}96%{width:0%;left:0;right:auto}100%{width:0%;left:0;right:auto;opacity:0.3}}\n\n@keyframes skeleton{0%{width:0%;left:0;right:auto;opacity:0.3}20%{width:100%;left:0;right:auto;opacity:1}28%{width:100%;left:auto;right:0}51%{width:0%;left:auto;right:0}58%{width:0%;left:auto;right:0}82%{width:100%;left:auto;right:0}83%{width:100%;left:0;right:auto}96%{width:0%;left:0;right:auto}100%{width:0%;left:0;right:auto;opacity:0.3}}\n\n.bx--text-truncate--end{width:100%;display:inline-block;text-overflow:ellipsis;white-space:nowrap;overflow:hidden}\n\n.bx--text-truncate--front{width:100%;display:inline-block;direction:rtl;text-overflow:ellipsis;white-space:nowrap;overflow:hidden}\n\n@font-face{font-family:'ibm-plex-mono';font-style:normal;font-weight:300;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexMono-Light.woff\") format(\"woff\")}\n\n@font-face{font-family:'ibm-plex-mono';font-style:normal;font-weight:300;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexMono-Light-Pi.woff2\") format(\"woff2\");unicode-range:\"U+03C0, U+0E3F, U+2070, U+2074-2079, U+2080-2089, U+2113, U+2116, U+2126, U+212E, U+2150-2151, U+2153-215E, U+2190-2199, U+21A9-21AA, U+21B0-21B3, U+21B6-21B7, U+21BA-21BB, U+21C4, U+21C6, U+2202, U+2206, U+220F, U+2211, U+221A, U+221E, U+222B, U+2248, U+2260, U+2264-2265, U+25CA, U+2713, U+274C, U+2B0E-2B11, U+EBE1, U+EBE3-EBE4, U+EBE6-EBE7, U+ECE0, U+EFCC\"}\n\n@font-face{font-family:'ibm-plex-mono';font-style:normal;font-weight:300;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexMono-Light-Latin3.woff2\") format(\"woff2\");unicode-range:\"U+0102-0103, U+1EA0-1EF9, U+20AB\"}\n\n@font-face{font-family:'ibm-plex-mono';font-style:normal;font-weight:300;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexMono-Light-Latin2.woff2\") format(\"woff2\");unicode-range:\"U+0100-024F, U+0259, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF, U+FB01-FB02\"}\n\n@font-face{font-family:'ibm-plex-mono';font-style:normal;font-weight:300;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexMono-Light-Latin1.woff2\") format(\"woff2\");unicode-range:\"U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+20AC, U+2122, U+2212, U+FB01-FB02\"}\n\n@font-face{font-family:'ibm-plex-mono';font-style:normal;font-weight:400;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexMono-Regular.woff\") format(\"woff\")}\n\n@font-face{font-family:'ibm-plex-mono';font-style:normal;font-weight:400;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexMono-Regular-Pi.woff2\") format(\"woff2\");unicode-range:\"U+03C0, U+0E3F, U+2070, U+2074-2079, U+2080-2089, U+2113, U+2116, U+2126, U+212E, U+2150-2151, U+2153-215E, U+2190-2199, U+21A9-21AA, U+21B0-21B3, U+21B6-21B7, U+21BA-21BB, U+21C4, U+21C6, U+2202, U+2206, U+220F, U+2211, U+221A, U+221E, U+222B, U+2248, U+2260, U+2264-2265, U+25CA, U+2713, U+274C, U+2B0E-2B11, U+EBE1, U+EBE3-EBE4, U+EBE6-EBE7, U+ECE0, U+EFCC\"}\n\n@font-face{font-family:'ibm-plex-mono';font-style:normal;font-weight:400;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexMono-Regular-Latin3.woff2\") format(\"woff2\");unicode-range:\"U+0102-0103, U+1EA0-1EF9, U+20AB\"}\n\n@font-face{font-family:'ibm-plex-mono';font-style:normal;font-weight:400;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexMono-Regular-Latin2.woff2\") format(\"woff2\");unicode-range:\"U+0100-024F, U+0259, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF, U+FB01-FB02\"}\n\n@font-face{font-family:'ibm-plex-mono';font-style:normal;font-weight:400;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexMono-Regular-Latin1.woff2\") format(\"woff2\");unicode-range:\"U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+20AC, U+2122, U+2212, U+FB01-FB02\"}\n\n@font-face{font-family:'ibm-plex-mono';font-style:normal;font-weight:600;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexMono-SemiBold.woff\") format(\"woff\")}\n\n@font-face{font-family:'ibm-plex-mono';font-style:normal;font-weight:600;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexMono-SemiBold-Pi.woff2\") format(\"woff2\");unicode-range:\"U+03C0, U+0E3F, U+2070, U+2074-2079, U+2080-2089, U+2113, U+2116, U+2126, U+212E, U+2150-2151, U+2153-215E, U+2190-2199, U+21A9-21AA, U+21B0-21B3, U+21B6-21B7, U+21BA-21BB, U+21C4, U+21C6, U+2202, U+2206, U+220F, U+2211, U+221A, U+221E, U+222B, U+2248, U+2260, U+2264-2265, U+25CA, U+2713, U+274C, U+2B0E-2B11, U+EBE1, U+EBE3-EBE4, U+EBE6-EBE7, U+ECE0, U+EFCC\"}\n\n@font-face{font-family:'ibm-plex-mono';font-style:normal;font-weight:600;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexMono-SemiBold-Latin3.woff2\") format(\"woff2\");unicode-range:\"U+0102-0103, U+1EA0-1EF9, U+20AB\"}\n\n@font-face{font-family:'ibm-plex-mono';font-style:normal;font-weight:600;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexMono-SemiBold-Latin2.woff2\") format(\"woff2\");unicode-range:\"U+0100-024F, U+0259, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF, U+FB01-FB02\"}\n\n@font-face{font-family:'ibm-plex-mono';font-style:normal;font-weight:600;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexMono-SemiBold-Latin1.woff2\") format(\"woff2\");unicode-range:\"U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+20AC, U+2122, U+2212, U+FB01-FB02\"}\n\n@font-face{font-family:'ibm-plex-sans';font-style:normal;font-weight:300;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexSans-Light.woff\") format(\"woff\")}\n\n@font-face{font-family:'ibm-plex-sans';font-style:normal;font-weight:300;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexSans-Light-Pi.woff2\") format(\"woff2\");unicode-range:\"U+03C0, U+0E3F, U+2070, U+2074-2079, U+2080-2089, U+2113, U+2116, U+2126, U+212E, U+2150-2151, U+2153-215E, U+2190-2199, U+21A9-21AA, U+21B0-21B3, U+21B6-21B7, U+21BA-21BB, U+21C4, U+21C6, U+2202, U+2206, U+220F, U+2211, U+221A, U+221E, U+222B, U+2248, U+2260, U+2264-2265, U+25CA, U+2713, U+274C, U+2B0E-2B11, U+EBE1, U+EBE3-EBE4, U+EBE6-EBE7, U+ECE0, U+EFCC\"}\n\n@font-face{font-family:'ibm-plex-sans';font-style:normal;font-weight:300;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexSans-Light-Latin3.woff2\") format(\"woff2\");unicode-range:\"U+0102-0103, U+1EA0-1EF9, U+20AB\"}\n\n@font-face{font-family:'ibm-plex-sans';font-style:normal;font-weight:300;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexSans-Light-Latin2.woff2\") format(\"woff2\");unicode-range:\"U+0100-024F, U+0259, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF, U+FB01-FB02\"}\n\n@font-face{font-family:'ibm-plex-sans';font-style:normal;font-weight:300;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexSans-Light-Latin1.woff2\") format(\"woff2\");unicode-range:\"U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+20AC, U+2122, U+2212, U+FB01-FB02\"}\n\n@font-face{font-family:'ibm-plex-sans';font-style:normal;font-weight:400;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexSans-Regular.woff\") format(\"woff\")}\n\n@font-face{font-family:'ibm-plex-sans';font-style:normal;font-weight:400;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexSans-Regular-Pi.woff2\") format(\"woff2\");unicode-range:\"U+03C0, U+0E3F, U+2070, U+2074-2079, U+2080-2089, U+2113, U+2116, U+2126, U+212E, U+2150-2151, U+2153-215E, U+2190-2199, U+21A9-21AA, U+21B0-21B3, U+21B6-21B7, U+21BA-21BB, U+21C4, U+21C6, U+2202, U+2206, U+220F, U+2211, U+221A, U+221E, U+222B, U+2248, U+2260, U+2264-2265, U+25CA, U+2713, U+274C, U+2B0E-2B11, U+EBE1, U+EBE3-EBE4, U+EBE6-EBE7, U+ECE0, U+EFCC\"}\n\n@font-face{font-family:'ibm-plex-sans';font-style:normal;font-weight:400;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexSans-Regular-Latin3.woff2\") format(\"woff2\");unicode-range:\"U+0102-0103, U+1EA0-1EF9, U+20AB\"}\n\n@font-face{font-family:'ibm-plex-sans';font-style:normal;font-weight:400;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexSans-Regular-Latin2.woff2\") format(\"woff2\");unicode-range:\"U+0100-024F, U+0259, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF, U+FB01-FB02\"}\n\n@font-face{font-family:'ibm-plex-sans';font-style:normal;font-weight:400;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexSans-Regular-Latin1.woff2\") format(\"woff2\");unicode-range:\"U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+20AC, U+2122, U+2212, U+FB01-FB02\"}\n\n@font-face{font-family:'ibm-plex-sans';font-style:normal;font-weight:600;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexSans-SemiBold.woff\") format(\"woff\")}\n\n@font-face{font-family:'ibm-plex-sans';font-style:normal;font-weight:600;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexSans-SemiBold-Pi.woff2\") format(\"woff2\");unicode-range:\"U+03C0, U+0E3F, U+2070, U+2074-2079, U+2080-2089, U+2113, U+2116, U+2126, U+212E, U+2150-2151, U+2153-215E, U+2190-2199, U+21A9-21AA, U+21B0-21B3, U+21B6-21B7, U+21BA-21BB, U+21C4, U+21C6, U+2202, U+2206, U+220F, U+2211, U+221A, U+221E, U+222B, U+2248, U+2260, U+2264-2265, U+25CA, U+2713, U+274C, U+2B0E-2B11, U+EBE1, U+EBE3-EBE4, U+EBE6-EBE7, U+ECE0, U+EFCC\"}\n\n@font-face{font-family:'ibm-plex-sans';font-style:normal;font-weight:600;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexSans-SemiBold-Latin3.woff2\") format(\"woff2\");unicode-range:\"U+0102-0103, U+1EA0-1EF9, U+20AB\"}\n\n@font-face{font-family:'ibm-plex-sans';font-style:normal;font-weight:600;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexSans-SemiBold-Latin2.woff2\") format(\"woff2\");unicode-range:\"U+0100-024F, U+0259, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF, U+FB01-FB02\"}\n\n@font-face{font-family:'ibm-plex-sans';font-style:normal;font-weight:600;src:url(\"https://unpkg.com/carbon-components@latest/src/globals/fonts/IBMPlexSans-SemiBold-Latin1.woff2\") format(\"woff2\");unicode-range:\"U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+20AC, U+2122, U+2212, U+FB01-FB02\"}\n\n.bx--assistive-text,.bx--visually-hidden{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);border:0;visibility:visible;white-space:nowrap}\n\n.bx--body{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;color:#152935;background-color:#f4f7fb;line-height:1}\n\nbody{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;color:#152935;background-color:#f4f7fb;line-height:1}\n\n.bx--type-giga{font-size:4.75rem;line-height:1.25;font-weight:300}\n\n.bx--type-mega{font-size:3.375rem;line-height:1.25;font-weight:300}\n\n.bx--type-omega{font-size:0.75rem;line-height:1.25;font-weight:600}\n\n.bx--type-caption{font-size:0.75rem;line-height:1.5;font-weight:400}\n\n.bx--type-legal{font-size:0.6875rem;line-height:1.5;font-weight:400}\n\n.bx--type-caps{text-transform:uppercase}\n\nstrong,.bx--type-strong{font-weight:700}\n\np{font-size:1rem;line-height:1.5;font-weight:400}\n\nem{font-style:italic}\n\na{color:#3d70b2}\n\nh1,.bx--type-alpha{font-size:2.25rem;line-height:1.25;font-weight:300}\n\nh2,.bx--type-beta{font-size:1.75rem;line-height:1.25;font-weight:300}\n\nh3,.bx--type-gamma{font-size:1.25rem;line-height:1.25;font-weight:300}\n\nh4,.bx--type-delta{font-size:1.125rem;line-height:1.25;font-weight:600}\n\nh5,.bx--type-epsilon{font-size:1rem;line-height:1.25;font-weight:600}\n\nh6,.bx--type-zeta{font-size:0.875rem;line-height:1.25;font-weight:600}\n\n.bx--grid{margin-left:3%;margin-right:3%;padding-left:5px;padding-right:5px}\n\n@media (min-width: 576px){.bx--grid{margin-left:5%;margin-right:5%;padding-left:10px;padding-right:10px}}\n\n@media (min-width: 1600px){.bx--grid{margin:0 auto}}\n\n.bx--grid.max{max-width:1600px}\n\n.bx--row{display:flex;flex-wrap:wrap;margin:0 -5px}\n\n@media (min-width: 576px){.bx--row{margin:0 -10px}}\n\n[class*='bx--col']{position:relative;width:100%;padding:0 5px}\n\n@media (min-width: 576px){[class*='bx--col']{padding:0 10px}}\n\n.bx--col-xs-1{flex:0 0 8.33333%;max-width:8.33333%}\n\n.bx--offset-xs-1{margin-left:8.33333%}\n\n.bx--col-xs-2{flex:0 0 16.66667%;max-width:16.66667%}\n\n.bx--offset-xs-2{margin-left:16.66667%}\n\n.bx--col-xs-3{flex:0 0 25%;max-width:25%}\n\n.bx--offset-xs-3{margin-left:25%}\n\n.bx--col-xs-4{flex:0 0 33.33333%;max-width:33.33333%}\n\n.bx--offset-xs-4{margin-left:33.33333%}\n\n.bx--col-xs-5{flex:0 0 41.66667%;max-width:41.66667%}\n\n.bx--offset-xs-5{margin-left:41.66667%}\n\n.bx--col-xs-6{flex:0 0 50%;max-width:50%}\n\n.bx--offset-xs-6{margin-left:50%}\n\n.bx--col-xs-7{flex:0 0 58.33333%;max-width:58.33333%}\n\n.bx--offset-xs-7{margin-left:58.33333%}\n\n.bx--col-xs-8{flex:0 0 66.66667%;max-width:66.66667%}\n\n.bx--offset-xs-8{margin-left:66.66667%}\n\n.bx--col-xs-9{flex:0 0 75%;max-width:75%}\n\n.bx--offset-xs-9{margin-left:75%}\n\n.bx--col-xs-10{flex:0 0 83.33333%;max-width:83.33333%}\n\n.bx--offset-xs-10{margin-left:83.33333%}\n\n.bx--col-xs-11{flex:0 0 91.66667%;max-width:91.66667%}\n\n.bx--offset-xs-11{margin-left:91.66667%}\n\n.bx--col-xs-12{flex:0 0 100%;max-width:100%}\n\n.bx--offset-xs-12{margin-left:100%}\n\n@media (min-width: 576px){.bx--col-sm-auto{flex:0 0 auto;width:auto}.bx--col-sm-1{flex:0 0 8.33333%;max-width:8.33333%}.bx--offset-sm-1{margin-left:8.33333%}.bx--col-sm-2{flex:0 0 16.66667%;max-width:16.66667%}.bx--offset-sm-2{margin-left:16.66667%}.bx--col-sm-3{flex:0 0 25%;max-width:25%}.bx--offset-sm-3{margin-left:25%}.bx--col-sm-4{flex:0 0 33.33333%;max-width:33.33333%}.bx--offset-sm-4{margin-left:33.33333%}.bx--col-sm-5{flex:0 0 41.66667%;max-width:41.66667%}.bx--offset-sm-5{margin-left:41.66667%}.bx--col-sm-6{flex:0 0 50%;max-width:50%}.bx--offset-sm-6{margin-left:50%}.bx--col-sm-7{flex:0 0 58.33333%;max-width:58.33333%}.bx--offset-sm-7{margin-left:58.33333%}.bx--col-sm-8{flex:0 0 66.66667%;max-width:66.66667%}.bx--offset-sm-8{margin-left:66.66667%}.bx--col-sm-9{flex:0 0 75%;max-width:75%}.bx--offset-sm-9{margin-left:75%}.bx--col-sm-10{flex:0 0 83.33333%;max-width:83.33333%}.bx--offset-sm-10{margin-left:83.33333%}.bx--col-sm-11{flex:0 0 91.66667%;max-width:91.66667%}.bx--offset-sm-11{margin-left:91.66667%}.bx--col-sm-12{flex:0 0 100%;max-width:100%}.bx--offset-sm-12{margin-left:100%}}\n\n@media (min-width: 768px){.bx--col-md-auto{flex:0 0 auto;width:auto}.bx--col-md-1{flex:0 0 8.33333%;max-width:8.33333%}.bx--offset-md-1{margin-left:8.33333%}.bx--col-md-2{flex:0 0 16.66667%;max-width:16.66667%}.bx--offset-md-2{margin-left:16.66667%}.bx--col-md-3{flex:0 0 25%;max-width:25%}.bx--offset-md-3{margin-left:25%}.bx--col-md-4{flex:0 0 33.33333%;max-width:33.33333%}.bx--offset-md-4{margin-left:33.33333%}.bx--col-md-5{flex:0 0 41.66667%;max-width:41.66667%}.bx--offset-md-5{margin-left:41.66667%}.bx--col-md-6{flex:0 0 50%;max-width:50%}.bx--offset-md-6{margin-left:50%}.bx--col-md-7{flex:0 0 58.33333%;max-width:58.33333%}.bx--offset-md-7{margin-left:58.33333%}.bx--col-md-8{flex:0 0 66.66667%;max-width:66.66667%}.bx--offset-md-8{margin-left:66.66667%}.bx--col-md-9{flex:0 0 75%;max-width:75%}.bx--offset-md-9{margin-left:75%}.bx--col-md-10{flex:0 0 83.33333%;max-width:83.33333%}.bx--offset-md-10{margin-left:83.33333%}.bx--col-md-11{flex:0 0 91.66667%;max-width:91.66667%}.bx--offset-md-11{margin-left:91.66667%}.bx--col-md-12{flex:0 0 100%;max-width:100%}.bx--offset-md-12{margin-left:100%}}\n\n@media (min-width: 992px){.bx--col-lg-auto{flex:0 0 auto;width:auto}.bx--col-lg-1{flex:0 0 8.33333%;max-width:8.33333%}.bx--offset-lg-1{margin-left:8.33333%}.bx--col-lg-2{flex:0 0 16.66667%;max-width:16.66667%}.bx--offset-lg-2{margin-left:16.66667%}.bx--col-lg-3{flex:0 0 25%;max-width:25%}.bx--offset-lg-3{margin-left:25%}.bx--col-lg-4{flex:0 0 33.33333%;max-width:33.33333%}.bx--offset-lg-4{margin-left:33.33333%}.bx--col-lg-5{flex:0 0 41.66667%;max-width:41.66667%}.bx--offset-lg-5{margin-left:41.66667%}.bx--col-lg-6{flex:0 0 50%;max-width:50%}.bx--offset-lg-6{margin-left:50%}.bx--col-lg-7{flex:0 0 58.33333%;max-width:58.33333%}.bx--offset-lg-7{margin-left:58.33333%}.bx--col-lg-8{flex:0 0 66.66667%;max-width:66.66667%}.bx--offset-lg-8{margin-left:66.66667%}.bx--col-lg-9{flex:0 0 75%;max-width:75%}.bx--offset-lg-9{margin-left:75%}.bx--col-lg-10{flex:0 0 83.33333%;max-width:83.33333%}.bx--offset-lg-10{margin-left:83.33333%}.bx--col-lg-11{flex:0 0 91.66667%;max-width:91.66667%}.bx--offset-lg-11{margin-left:91.66667%}.bx--col-lg-12{flex:0 0 100%;max-width:100%}.bx--offset-lg-12{margin-left:100%}}\n\n@media (min-width: 1200px){.bx--col-xl-auto{flex:0 0 auto;width:auto}.bx--col-xl-1{flex:0 0 8.33333%;max-width:8.33333%}.bx--offset-xl-1{margin-left:8.33333%}.bx--col-xl-2{flex:0 0 16.66667%;max-width:16.66667%}.bx--offset-xl-2{margin-left:16.66667%}.bx--col-xl-3{flex:0 0 25%;max-width:25%}.bx--offset-xl-3{margin-left:25%}.bx--col-xl-4{flex:0 0 33.33333%;max-width:33.33333%}.bx--offset-xl-4{margin-left:33.33333%}.bx--col-xl-5{flex:0 0 41.66667%;max-width:41.66667%}.bx--offset-xl-5{margin-left:41.66667%}.bx--col-xl-6{flex:0 0 50%;max-width:50%}.bx--offset-xl-6{margin-left:50%}.bx--col-xl-7{flex:0 0 58.33333%;max-width:58.33333%}.bx--offset-xl-7{margin-left:58.33333%}.bx--col-xl-8{flex:0 0 66.66667%;max-width:66.66667%}.bx--offset-xl-8{margin-left:66.66667%}.bx--col-xl-9{flex:0 0 75%;max-width:75%}.bx--offset-xl-9{margin-left:75%}.bx--col-xl-10{flex:0 0 83.33333%;max-width:83.33333%}.bx--offset-xl-10{margin-left:83.33333%}.bx--col-xl-11{flex:0 0 91.66667%;max-width:91.66667%}.bx--offset-xl-11{margin-left:91.66667%}.bx--col-xl-12{flex:0 0 100%;max-width:100%}.bx--offset-xl-12{margin-left:100%}}\n\n@media (min-width: 1600px){.bx--col-xxl-auto{flex:0 0 auto;width:auto}.bx--col-xxl-1{flex:0 0 8.33333%;max-width:8.33333%}.bx--offset-xxl-1{margin-left:8.33333%}.bx--col-xxl-2{flex:0 0 16.66667%;max-width:16.66667%}.bx--offset-xxl-2{margin-left:16.66667%}.bx--col-xxl-3{flex:0 0 25%;max-width:25%}.bx--offset-xxl-3{margin-left:25%}.bx--col-xxl-4{flex:0 0 33.33333%;max-width:33.33333%}.bx--offset-xxl-4{margin-left:33.33333%}.bx--col-xxl-5{flex:0 0 41.66667%;max-width:41.66667%}.bx--offset-xxl-5{margin-left:41.66667%}.bx--col-xxl-6{flex:0 0 50%;max-width:50%}.bx--offset-xxl-6{margin-left:50%}.bx--col-xxl-7{flex:0 0 58.33333%;max-width:58.33333%}.bx--offset-xxl-7{margin-left:58.33333%}.bx--col-xxl-8{flex:0 0 66.66667%;max-width:66.66667%}.bx--offset-xxl-8{margin-left:66.66667%}.bx--col-xxl-9{flex:0 0 75%;max-width:75%}.bx--offset-xxl-9{margin-left:75%}.bx--col-xxl-10{flex:0 0 83.33333%;max-width:83.33333%}.bx--offset-xxl-10{margin-left:83.33333%}.bx--col-xxl-11{flex:0 0 91.66667%;max-width:91.66667%}.bx--offset-xxl-11{margin-left:91.66667%}.bx--col-xxl-12{flex:0 0 100%;max-width:100%}.bx--offset-xxl-12{margin-left:100%}}\n\n.bx--col-xs,.bx--col-sm,.bx--col-md,.bx--col-lg{flex-basis:0;flex:1;flex-grow:1;max-width:100%}\n\nbutton.bx--btn{display:inline-block}\n\nbutton.bx--btn::-moz-focus-inner{padding:0;border:0}\n\nbutton.bx--btn .bx--btn__icon{position:relative;vertical-align:middle;top:-1px}\n\n@media all and (-ms-high-contrast: none), (-ms-high-contrast: active){button.bx--btn .bx--btn__icon{top:0}}\n\n.bx--btn{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;letter-spacing:0;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;flex-shrink:0;font-size:.875rem;font-weight:600;height:2.5rem;padding:0 1rem;border-radius:0;text-align:center;text-decoration:none;transition-duration:250ms;transition-timing-function:ease-in;white-space:nowrap;line-height:16px}\n\n.bx--btn:disabled{cursor:not-allowed;opacity:0.5}\n\n.bx--btn .bx--btn__icon{width:1rem;height:1rem;margin-left:0.5rem;transition-duration:250ms;transition-timing-function:ease-in}\n\n.bx--btn--primary{background-color:#3d70b2;border-width:2px;border-style:solid;border-color:transparent;color:#fff}\n\n.bx--btn--primary:focus,.bx--btn--primary:hover{background-color:#30588c}\n\n.bx--btn--primary:focus{border:2px solid #f4f7fb;outline:2px solid #30588c}\n\n.bx--btn--primary:disabled:hover,.bx--btn--primary:disabled:focus{background-color:#3d70b2}\n\n.bx--btn--primary:active{background-color:#234066}\n\n.bx--btn--primary .bx--btn__icon{fill:#fff}\n\n.bx--btn--secondary{background-color:transparent;border-width:2px;border-style:solid;border-color:#3d70b2;color:#3d70b2}\n\n.bx--btn--secondary:focus,.bx--btn--secondary:hover{background-color:#3d70b2}\n\n.bx--btn--secondary:focus{border:2px solid #f4f7fb;outline:2px solid #3d70b2}\n\n.bx--btn--secondary:disabled:hover,.bx--btn--secondary:disabled:focus{background-color:transparent}\n\n.bx--btn--secondary:active{background-color:transparent}\n\n.bx--btn--secondary .bx--btn__icon{fill:#3d70b2}\n\n.bx--btn--secondary:hover,.bx--btn--secondary:focus{color:#fff}\n\n.bx--btn--secondary:active{color:#3d70b2}\n\n.bx--btn--secondary:hover>.bx--btn__icon,.bx--btn--secondary:focus>.bx--btn__icon{fill:#fff}\n\n.bx--btn--secondary:hover:disabled,.bx--btn--secondary:focus:disabled{color:#3d70b2}\n\n.bx--btn--tertiary{background-color:transparent;border-width:2px;border-style:solid;border-color:#5a6872;color:#5a6872}\n\n.bx--btn--tertiary:focus,.bx--btn--tertiary:hover{background-color:#5a6872}\n\n.bx--btn--tertiary:focus{border:2px solid #f4f7fb;outline:2px solid #5a6872}\n\n.bx--btn--tertiary:disabled:hover,.bx--btn--tertiary:disabled:focus{background-color:transparent}\n\n.bx--btn--tertiary:active{background-color:transparent}\n\n.bx--btn--tertiary .bx--btn__icon{fill:#5a6872}\n\n.bx--btn--tertiary:hover,.bx--btn--tertiary:focus{color:#fff}\n\n.bx--btn--tertiary:active{color:#5a6872}\n\n.bx--btn--tertiary:hover:disabled,.bx--btn--tertiary:focus:disabled{color:#5a6872}\n\n.bx--btn--tertiary:hover>.bx--btn__icon,.bx--btn--tertiary:focus>.bx--btn__icon{fill:#fff}\n\n.bx--btn--ghost{background-color:transparent;border-width:2px;border-style:solid;border-color:transparent;color:#3d70b2}\n\n.bx--btn--ghost:focus,.bx--btn--ghost:hover{background-color:#3d70b2}\n\n.bx--btn--ghost:focus{border:2px solid #f4f7fb;outline:2px solid #3d70b2}\n\n.bx--btn--ghost:disabled:hover,.bx--btn--ghost:disabled:focus{background-color:transparent}\n\n.bx--btn--ghost:active{background-color:transparent}\n\n.bx--btn--ghost .bx--btn__icon{fill:#3d70b2}\n\n.bx--btn--ghost:hover,.bx--btn--ghost:focus{color:#fff}\n\n.bx--btn--ghost:hover .bx--btn__icon,.bx--btn--ghost:focus .bx--btn__icon{fill:#fff}\n\n.bx--btn--ghost:active{color:#5a6872}\n\n.bx--btn--ghost .bx--btn__icon{margin-left:.5rem}\n\n.bx--btn--ghost:hover:disabled,.bx--btn--ghost:focus:disabled{color:#3d70b2}\n\n.bx--btn--ghost:hover:disabled .bx--btn__icon,.bx--btn--ghost:focus:disabled .bx--btn__icon{fill:#3d70b2}\n\n.bx--btn--danger{background-color:transparent;border-width:2px;border-style:solid;border-color:#e0182d;color:#e0182d}\n\n.bx--btn--danger:focus,.bx--btn--danger:hover{background-color:#e0182d}\n\n.bx--btn--danger:focus{border:2px solid #f4f7fb;outline:2px solid #e0182d}\n\n.bx--btn--danger:disabled:hover,.bx--btn--danger:disabled:focus{background-color:transparent}\n\n.bx--btn--danger:active{background-color:transparent}\n\n.bx--btn--danger .bx--btn__icon{fill:#e0182d}\n\n.bx--btn--danger:hover{color:#fff;border:2px solid transparent}\n\n.bx--btn--danger:focus{color:#fff}\n\n.bx--btn--danger:active{color:#e0182d}\n\n.bx--btn--danger:hover:disabled,.bx--btn--danger:focus:disabled{color:#e0182d;border:2px solid #e0182d}\n\n.bx--btn--danger:hover>.bx--btn__icon,.bx--btn--danger:focus>.bx--btn__icon{fill:#fff}\n\n.bx--btn--danger--primary{background-color:#e0182d;border-width:2px;border-style:solid;border-color:transparent;color:#fff}\n\n.bx--btn--danger--primary:focus,.bx--btn--danger--primary:hover{background-color:#b21324}\n\n.bx--btn--danger--primary:focus{border:2px solid #f4f7fb;outline:2px solid #b21324}\n\n.bx--btn--danger--primary:disabled:hover,.bx--btn--danger--primary:disabled:focus{background-color:#e0182d}\n\n.bx--btn--danger--primary:active{background-color:#840e1a}\n\n.bx--btn--danger--primary .bx--btn__icon{fill:#fff}\n\n.bx--btn--danger--primary:hover:disabled,.bx--btn--danger--primary:focus:disabled{color:#fff;border:2px solid #e0182d}\n\n.bx--btn--sm{letter-spacing:0;height:2rem;padding:0 .5rem}\n\n.bx--btn--secondary+.bx--btn--primary,.bx--btn--tertiary+.bx--btn--danger--primary{margin-left:1rem}\n\n.bx--btn.bx--skeleton{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:9.375rem}\n\n.bx--btn.bx--skeleton:hover,.bx--btn.bx--skeleton:focus,.bx--btn.bx--skeleton:active{border:none;outline:none;cursor:default}\n\n.bx--btn.bx--skeleton:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--btn--copy{position:relative;overflow:visible}\n\n.bx--btn--copy .bx--btn__icon{margin-left:.3125rem}\n\n.bx--btn--copy__feedback{position:absolute;display:none;top:1.2rem;left:50%}\n\n.bx--btn--copy__feedback:focus{border:2px solid red}\n\n.bx--btn--copy__feedback:before{box-shadow:0 4px 8px 0 rgba(0,0,0,0.1);font-size:0.75rem;top:1.1rem;padding:.25rem;color:#fff;content:attr(data-feedback);-webkit-transform:translateX(-50%);transform:translateX(-50%);white-space:nowrap;pointer-events:none;border-radius:4px;font-weight:400;z-index:2}\n\n.bx--btn--copy__feedback:after{top:0.85rem;width:0.6rem;height:0.6rem;left:-0.3rem;border-right:1px solid #272d33;border-bottom:1px solid #272d33;content:'';-webkit-transform:rotate(-135deg);transform:rotate(-135deg);z-index:1}\n\n.bx--btn--copy__feedback:before,.bx--btn--copy__feedback:after{position:absolute;display:block;background:#272d33}\n\n.bx--btn--copy__feedback--displayed{display:inline-flex}\n\n.bx--fieldset{margin-bottom:2rem}\n\n.bx--form-item{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;display:flex;flex-direction:column;flex:1;align-items:flex-start}\n\n.bx--form-item--light input,.bx--form-item--light input[type='number']{background:#fff !important}\n\n.bx--label{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;font-size:0.875rem;color:#152935;font-weight:600;display:inline-block;vertical-align:baseline;margin-bottom:.5rem}\n\n.bx--label .bx--tooltip__trigger{font-size:0.875rem}\n\n.bx--label--disabled{opacity:0.5}\n\n.bx--label.bx--skeleton{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:4.6875rem;height:.875rem}\n\n.bx--label.bx--skeleton:hover,.bx--label.bx--skeleton:focus,.bx--label.bx--skeleton:active{border:none;outline:none;cursor:default}\n\n.bx--label.bx--skeleton:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\ninput[data-invalid],textarea[data-invalid],select[data-invalid],.bx--list-box[data-invalid]{box-shadow:0 2px 0px 0px #e0182d}\n\ninput[data-invalid] ~ .bx--form-requirement,textarea[data-invalid] ~ .bx--form-requirement,select[data-invalid] ~ .bx--form-requirement,.bx--list-box[data-invalid] ~ .bx--form-requirement{max-height:12.5rem;display:block}\n\ninput:not(output):not([data-invalid]):-moz-ui-invalid{box-shadow:none}\n\n.bx--form-requirement{font-size:0.75rem;margin:.75rem 0 0;max-height:0;overflow:hidden;font-weight:600;line-height:1.5;display:none}\n\n.bx--form-requirement::before{content:'*';display:inline-block;color:#e0182d}\n\n.bx--form__helper-text{font-size:0.75rem;color:#5a6872;order:1;line-height:1.5;z-index:0;max-height:3rem;opacity:1;margin-bottom:.5rem}\n\n@-webkit-keyframes rotate{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}\n\n@keyframes rotate{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}\n\n@-webkit-keyframes rotate-end-p1{100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}\n\n@keyframes rotate-end-p1{100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}\n\n@-webkit-keyframes rotate-end-p2{100%{-webkit-transform:rotate(-360deg);transform:rotate(-360deg)}}\n\n@keyframes rotate-end-p2{100%{-webkit-transform:rotate(-360deg);transform:rotate(-360deg)}}\n\n@-webkit-keyframes init-stroke{0%{stroke-dashoffset:240}100%{stroke-dashoffset:40}}\n\n@keyframes init-stroke{0%{stroke-dashoffset:240}100%{stroke-dashoffset:40}}\n\n@-webkit-keyframes stroke-end{0%{stroke-dashoffset:40}100%{stroke-dashoffset:240}}\n\n@keyframes stroke-end{0%{stroke-dashoffset:40}100%{stroke-dashoffset:240}}\n\n.bx--loading{-webkit-animation-name:rotate;animation-name:rotate;-webkit-animation-duration:500ms;animation-duration:500ms;-webkit-animation-timing-function:linear;animation-timing-function:linear;-webkit-animation-fill-mode:forwards;animation-fill-mode:forwards;-webkit-animation-iteration-count:infinite;animation-iteration-count:infinite;width:10.5rem;height:10.5rem}\n\n.bx--loading svg circle{-webkit-animation-name:init-stroke;animation-name:init-stroke;-webkit-animation-duration:1000ms;animation-duration:1000ms;-webkit-animation-timing-function:cubic-bezier(0.5, 0, 0.1, 1);animation-timing-function:cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--loading__svg{fill:transparent;stroke:#6eedd8;stroke-width:7;stroke-linecap:butt;stroke-dasharray:240;stroke-dashoffset:40}\n\n.bx--loading--stop{-webkit-animation:rotate-end-p1 700ms cubic-bezier(0, 0, 0.25, 1) forwards,rotate-end-p2 700ms cubic-bezier(0, 0, 0.25, 1) 700ms forwards;animation:rotate-end-p1 700ms cubic-bezier(0, 0, 0.25, 1) forwards,rotate-end-p2 700ms cubic-bezier(0, 0, 0.25, 1) 700ms forwards}\n\n.bx--loading--stop svg circle{-webkit-animation-name:stroke-end;animation-name:stroke-end;-webkit-animation-duration:700ms;animation-duration:700ms;-webkit-animation-timing-function:cubic-bezier(0, 0, 0.25, 1);animation-timing-function:cubic-bezier(0, 0, 0.25, 1);-webkit-animation-delay:700ms;animation-delay:700ms;-webkit-animation-fill-mode:forwards;animation-fill-mode:forwards}\n\n.bx--loading--small{width:2rem;height:2rem}\n\n.bx--loading--small .bx--loading__svg{stroke:#5a6872}\n\n.bx--loading-overlay{position:fixed;top:0;left:0;height:100%;width:100%;background-color:rgba(255,255,255,0.6);display:flex;justify-content:center;align-items:center;transition:background-color 2000ms cubic-bezier(0.5, 0, 0.1, 1);z-index:8000}\n\n.bx--loading-overlay--stop{display:none}\n\n.bx--file{width:100%}\n\n.bx--file-input{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);border:0;visibility:visible;white-space:nowrap}\n\n.bx--file-btn{display:inline-flex;margin:0}\n\n.bx--label-description{font-size:0.875rem;line-height:1.5;color:#5a6872;margin-bottom:1.5rem}\n\n.bx--file-container{display:block;width:100%;margin-top:1.5rem}\n\n.bx--file__selected-file{display:block;overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap;width:300px;display:flex;align-items:center;justify-content:space-between;min-height:1.875rem;background-color:#fff;border:1px solid #dfe3e6;padding:0 1rem;margin-bottom:1rem}\n\n.bx--file__selected-file:last-child{margin-bottom:0}\n\n.bx--file-filename{font-size:0.75rem;display:block;overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap;width:100%;display:inline-flex;align-items:center;color:#152935;margin-right:1rem;height:1.875rem;direction:ltr;justify-content:flex-start}\n\n.bx--file__state-container{display:flex;align-items:center}\n\n.bx--file__state-container .bx--loading{width:1rem;height:1rem;margin-right:.5rem}\n\n.bx--file__state-container .bx--loading__svg{stroke:#5a6872}\n\n.bx--file__state-container .bx--file-close,.bx--file__state-container .bx--file-complete{width:1rem;height:1rem;fill:#152935;cursor:pointer}\n\n.bx--file__state-container .bx--file-close:focus,.bx--file__state-container .bx--file-complete:focus{outline:1px solid #3d70b2}\n\n.bx--file__state-container .bx--file-close{fill:#5a6872}\n\n.bx--file__state-container .bx--file-complete{fill:#5aa700}\n\n.bx--form-item.bx--checkbox-wrapper{margin-bottom:1rem}\n\n.bx--form-item.bx--checkbox-wrapper:first-of-type{margin-top:.5rem}\n\n.bx--form-item.bx--checkbox-wrapper:last-of-type{margin-bottom:0}\n\n.bx--checkbox{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);border:0;visibility:visible;white-space:nowrap}\n\n.bx--checkbox-label{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-size:0.875rem;display:flex;align-items:center;cursor:pointer;position:relative;padding-left:1.5rem;min-height:1rem}\n\n.bx--checkbox-label::before{box-sizing:border-box;content:'';position:absolute;left:0;top:calc(50% - 9px);height:1.125rem;width:1.125rem;border:2px solid #5a6872;background-color:#fff}\n\n.bx--checkbox-label::after{box-sizing:border-box;content:'';width:9px;height:5px;background:none;border-left:1px solid #fff;border-bottom:1px solid #fff;-webkit-transform:scale(0) rotate(-45deg);transform:scale(0) rotate(-45deg);position:absolute;left:.3125rem;top:50%;margin-top:-.1875rem}\n\n.bx--checkbox:checked+.bx--checkbox-label::before,.bx--checkbox:indeterminate+.bx--checkbox-label::before,.bx--checkbox-label[data-contained-checkbox-state='true']::before,.bx--checkbox-label[data-contained-checkbox-state='mixed']::before{background-color:#3d70b2;border-color:#3d70b2}\n\n.bx--checkbox:checked+.bx--checkbox-label::after,.bx--checkbox-label[data-contained-checkbox-state='true']::after{opacity:1;-webkit-transform:scale(1) rotate(-45deg);transform:scale(1) rotate(-45deg)}\n\n.bx--checkbox:not(:checked)+.bx--checkbox-label::after{opacity:0;-webkit-transform:scale(0) rotate(-45deg);transform:scale(0) rotate(-45deg)}\n\n.bx--checkbox:focus+.bx--checkbox-label::before,.bx--checkbox-label__focus::before{box-shadow:0 0 0 3px #7cc7ff;outline:1px solid transparent}\n\n.bx--checkbox:indeterminate+.bx--checkbox-label::after,.bx--checkbox-label[data-contained-checkbox-state='mixed']::after{-webkit-transform:scale(1) rotate(0deg);transform:scale(1) rotate(0deg);border-left:0 solid #fff;border-bottom:2px solid #fff;opacity:1;width:.625rem;margin-top:-.25rem;left:.25rem}\n\n.bx--checkbox:disabled+.bx--checkbox-label,.bx--checkbox:disabled ~ .bx--checkbox-label-text,.bx--checkbox-label[data-contained-checkbox-disabled='true']{opacity:0.5;cursor:not-allowed}\n\n.bx--checkbox-appearance{position:absolute;left:0;top:calc(50% - 9px);display:inline-block;height:1.125rem;width:1.125rem;margin-right:.5rem;background-color:#fff;border:2px solid #5a6872;min-width:1.125rem}\n\n.bx--checkbox:checked+.bx--checkbox-label .bx--checkbox-appearance{top:-.0625rem}\n\n.bx--checkbox:checked+.bx--checkbox-appearance,.bx--checkbox:checked+.bx--checkbox-label .bx--checkbox-appearance{display:flex;align-items:baseline;background-color:#3d70b2;border-color:#3d70b2}\n\n.bx--checkbox:focus+.bx--checkbox-label .bx--checkbox-appearance,.bx--checkbox:focus+.bx--checkbox-appearance{box-shadow:0 0 0 3px #7cc7ff;outline:1px solid transparent}\n\n.bx--checkbox:disabled+.bx--checkbox-appearance{opacity:0.5;cursor:not-allowed}\n\n.bx--checkbox-checkmark{display:none;fill:#fff;width:100%;height:100%}\n\n.bx--checkbox:checked+.bx--checkbox-appearance .bx--checkbox-checkmark,.bx--checkbox:checked+.bx--checkbox-label .bx--checkbox-appearance .bx--checkbox-checkmark{display:block}\n\n@-moz-document url-prefix(){.bx--checkbox:checked+.bx--checkbox-appearance .bx--checkbox-checkmark,.bx--checkbox:checked+.bx--checkbox-label .bx--checkbox-appearance .bx--checkbox-checkmark{stroke:#3d70b2}}\n\n.bx--checkbox-label.bx--skeleton{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:6.25rem;height:1.125rem}\n\n.bx--checkbox-label.bx--skeleton:hover,.bx--checkbox-label.bx--skeleton:focus,.bx--checkbox-label.bx--skeleton:active{border:none;outline:none;cursor:default}\n\n.bx--checkbox-label.bx--skeleton:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--checkbox-label.bx--skeleton:after,.bx--checkbox-label.bx--skeleton:before{border:none}\n\n.bx--list-box{position:relative;width:100%;height:2.5rem;max-height:2.5rem;background-color:#f4f7fb;border:none;box-shadow:0 1px 0 0 #5a6872;order:1;cursor:pointer;color:#152935}\n\n.bx--list-box[data-invalid],.bx--list-box[data-invalid] .bx--list-box__field:focus{box-shadow:0 2px 0 0 #e0182d}\n\n.bx--list-box[data-invalid] .bx--list-box__field:focus .bx--list-box__label{color:#e0182d}\n\n.bx--list-box ~ .bx--form-requirement{order:3;color:#e0182d;font-weight:400;margin-top:.25rem}\n\n.bx--list-box ~ .bx--form-requirement::before{display:none}\n\n.bx--list-box--light{background-color:#fff}\n\n.bx--list-box--disabled{opacity:0.5}\n\n.bx--list-box--disabled,.bx--list-box--disabled .bx--list-box__field,.bx--list-box--disabled .bx--list-box__menu-icon{cursor:not-allowed}\n\n.bx--list-box--disabled .bx--list-box__menu-item:hover,.bx--list-box--disabled .bx--list-box__menu-item--highlighted{background-color:transparent;text-decoration:none}\n\n.bx--list-box.bx--list-box--inline{background-color:inherit;width:auto;height:2rem;box-shadow:none}\n\n.bx--list-box--inline .bx--list-box__label{color:#3d70b2}\n\n.bx--list-box--inline .bx--list-box__field{padding:0 0 0 .625rem}\n\n.bx--list-box--inline .bx--list-box__menu-icon{position:static;padding:0 .5rem}\n\n.bx--list-box--inline>.bx--list-box__menu{top:2rem;width:18.75rem}\n\n.bx--list-box--inline>.bx--list-box__field[aria-expanded='true'] ~ .bx--list-box__menu{outline:1px solid #3d70b2;box-shadow:0 4px 8px 0 rgba(0,0,0,0.1)}\n\n.bx--list-box--inline>.bx--list-box__field[aria-expanded='true'],.bx--list-box.bx--list-box--inline>.bx--list-box__field:focus{outline:none;box-shadow:none}\n\n.bx--list-box__field{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;letter-spacing:0;display:inline-block;background:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:0;padding:0;cursor:pointer;width:100%;position:relative;display:inline-flex;align-items:center;height:100%;padding:0 1rem;cursor:pointer}\n\n.bx--list-box__field::-moz-focus-inner{border:0}\n\n.bx--list-box__field:focus,.bx--list-box__field[aria-expanded='true']{outline:none;box-shadow:0 2px 0 0 #3d70b2}\n\n.bx--list-box__field[disabled]{outline:none;opacity:0.5}\n\n.bx--list-box__label{font-size:0.875rem;color:#152935;font-weight:600;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}\n\n.bx--list-box__menu-icon{display:inline-block;position:absolute;top:0;right:0;bottom:0;height:100%;padding:0 1rem;transition:-webkit-transform 200ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 200ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 200ms cubic-bezier(0.5, 0, 0.1, 1), -webkit-transform 200ms cubic-bezier(0.5, 0, 0.1, 1);cursor:pointer}\n\n.bx--list-box__menu-icon>svg{fill:#3d70b2;height:100%}\n\n.bx--list-box__menu-icon--open{-webkit-transform:rotate(180deg);transform:rotate(180deg)}\n\n.bx--list-box__selection{display:inline-block;position:absolute;top:0;right:1.625rem;bottom:0;height:2.5rem;padding:0 1rem;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;transition:background-color 200ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--list-box__selection>svg{fill:#5a6872;height:100%}\n\n.bx--list-box__selection:focus{outline:1px solid #3d70b2}\n\n.bx--list-box__selection--multi{font-size:0.75rem;position:static;display:flex;align-items:center;justify-content:center;padding:0;background-color:#3d70b2;height:1.125rem;color:white;line-height:0;padding:.3125rem;margin-right:.625rem;border-radius:.8125rem}\n\n.bx--list-box__selection--multi>svg{fill:white;width:0.5rem;height:0.5rem;margin-left:.3125rem}\n\n.bx--list-box__selection--multi:focus,.bx--list-box__selection--multi:hover{background-color:#30588c;outline:none}\n\n.bx--list-box__menu{box-shadow:0px 3px 3px 0 rgba(0,0,0,0.1);position:absolute;left:0;right:0;top:2.5rem;width:100%;background-color:#fff;max-height:7.5rem;overflow-y:auto;z-index:7000}\n\n.bx--list-box__menu-item{font-size:0.875rem;display:flex;align-items:center;height:2.5rem;padding:0 1rem;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}\n\n.bx--list-box__menu-item:hover,.bx--list-box__menu-item--highlighted{background-color:rgba(85,150,230,0.1);outline:1px solid transparent;text-decoration:underline;color:#152935}\n\n.bx--list-box__menu-item .bx--checkbox-label{width:100%}\n\n.bx--list-box__menu-item .bx--checkbox-label-text{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}\n\n.bx--list-box__menu-item>.bx--form-item.bx--checkbox-wrapper{margin:0;width:100%}\n\n.bx--list-box input[role='combobox']{background-color:inherit;font-weight:600;outline-offset:0;min-width:0}\n\n.bx--list-box input[role='combobox']:-ms-input-placeholder{color:#cdd1d4;font-weight:400}\n\n.bx--list-box input[role='combobox']::-webkit-input-placeholder{color:#cdd1d4;font-weight:400}\n\n.bx--list-box input[role='combobox']::-ms-input-placeholder{color:#cdd1d4;font-weight:400}\n\n.bx--list-box input[role='combobox']::placeholder{color:#cdd1d4;font-weight:400}\n\n.bx--list-box--disabled input[role='combobox']{opacity:1}\n\n.bx--combo-box>.bx--list-box__field{padding:0}\n\n.bx--radio-button-group{display:flex;align-items:center;margin-top:.5rem}\n\n.bx--radio-button{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);border:0;visibility:visible;white-space:nowrap;visibility:unset}\n\n.bx--radio-button__label{font-size:0.875rem;font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;display:flex;align-items:center;cursor:pointer;margin-right:1rem}\n\n.bx--radio-button__appearance{background-color:#fff;border-radius:50%;border:2px solid #5a6872;flex-shrink:0;height:1.125rem;width:1.125rem;margin-right:.5rem}\n\n.bx--radio-button:checked+.bx--radio-button__label .bx--radio-button__appearance{display:flex;align-items:center;justify-content:center;border-color:#3d70b2}\n\n.bx--radio-button:checked+.bx--radio-button__label .bx--radio-button__appearance:before{content:'';display:inline-block;position:relative;width:0.5rem;height:0.5rem;border-radius:50%;background-color:#3d70b2}\n\n.bx--radio-button:disabled+.bx--radio-button__label{opacity:0.5;cursor:not-allowed}\n\n.bx--radio-button:focus+.bx--radio-button__label .bx--radio-button__appearance{box-shadow:0 0 0 3px #7cc7ff;outline:1px solid transparent}\n\n.bx--radio-button__label.bx--skeleton{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:6.25rem;height:1.125rem}\n\n.bx--radio-button__label.bx--skeleton:hover,.bx--radio-button__label.bx--skeleton:focus,.bx--radio-button__label.bx--skeleton:active{border:none;outline:none;cursor:default}\n\n.bx--radio-button__label.bx--skeleton:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--radio-button__label.bx--skeleton .bx--radio-button__appearance{display:none}\n\n.bx--toggle{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);border:0;visibility:visible;white-space:nowrap}\n\n.bx--toggle__label{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;position:relative;display:flex;align-items:center;transition:250ms cubic-bezier(0.5, 0, 0.1, 1);cursor:pointer;margin:1rem 0;color:#152935}\n\n.bx--toggle__appearance{position:relative;width:3rem}\n\n.bx--toggle__appearance:before{position:absolute;display:block;content:'';width:100%;height:.25rem;top:-2px;background-color:#8897a2;transition:250ms cubic-bezier(0.5, 0, 0.1, 1);cursor:pointer}\n\n.bx--toggle__appearance:after{box-sizing:border-box;position:absolute;display:block;border:2px solid #8897a2;cursor:pointer;top:-12px;width:1.5rem;height:1.5rem;background-color:#fff;border-radius:50%;content:'';transition:250ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--toggle--small+.bx--toggle__label{width:2rem}\n\n.bx--toggle--small+.bx--toggle__label .bx--toggle__appearance{width:2rem;height:1rem}\n\n.bx--toggle--small+.bx--toggle__label .bx--toggle__appearance:before{box-sizing:border-box;height:1rem;width:2rem;border-radius:0.9375rem;background-color:transparent;border:2px solid #8897a2;top:0}\n\n.bx--toggle--small+.bx--toggle__label .bx--toggle__appearance:after{width:.625rem;height:.625rem;background-color:#8897a2;border:none;top:3px;left:3px}\n\n.bx--toggle__check{fill:#8897a2;position:absolute;left:6px;top:6px;z-index:1;transition:250ms cubic-bezier(0.5, 0, 0.1, 1);-webkit-transform:scale(0.2);transform:scale(0.2)}\n\n.bx--toggle--small:checked+.bx--toggle__label .bx--toggle__check{fill:#3d70b2;-webkit-transform:scale(1) translateX(16px);transform:scale(1) translateX(16px)}\n\n.bx--toggle__text--left,.bx--toggle__text--right{font-size:0.875rem;position:relative;color:#152935}\n\n.bx--toggle__text--left{margin-right:.5rem}\n\n.bx--toggle__text--right{margin-left:.5rem}\n\n.bx--toggle:checked+.bx--toggle__label .bx--toggle__appearance:before{background-color:#3d70b2}\n\n.bx--toggle:checked+.bx--toggle__label .bx--toggle__appearance:after{-webkit-transform:translateX(24px);transform:translateX(24px);background-color:#3d70b2;box-shadow:none;border-color:#3d70b2}\n\n.bx--toggle--small:checked+.bx--toggle__label .bx--toggle__appearance:before{background-color:#3d70b2;border-color:#3d70b2}\n\n.bx--toggle--small:checked+.bx--toggle__label .bx--toggle__appearance:after{background-color:#fff;border-color:#fff;margin-left:0px;-webkit-transform:translateX(17px);transform:translateX(17px)}\n\n.bx--toggle:focus+.bx--toggle__label .bx--toggle__appearance:before{outline:1px solid transparent}\n\n.bx--toggle:focus+.bx--toggle__label .bx--toggle__appearance:after{box-shadow:0 0 0 3px #7cc7ff;outline:1px solid transparent}\n\n.bx--toggle--small:focus+.bx--toggle__label .bx--toggle__appearance:before{box-shadow:0 0 0 3px #7cc7ff;outline:1px solid transparent}\n\n.bx--toggle--small:focus+.bx--toggle__label .bx--toggle__appearance:after{outline:none;box-shadow:none}\n\n.bx--toggle:disabled+.bx--toggle__label{cursor:not-allowed;opacity:0.5}\n\n.bx--toggle:disabled+.bx--toggle__label .bx--toggle__appearance:before,.bx--toggle:disabled+.bx--toggle__label .bx--toggle__appearance:after{cursor:not-allowed;transition:250ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--toggle.bx--toggle--small+.bx--toggle__label>.bx--toggle__text--left,.bx--toggle.bx--toggle--small+.bx--toggle__label>.bx--toggle__text--right{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);border:0;visibility:visible;white-space:nowrap}\n\n.bx--toggle.bx--skeleton+.bx--toggle__label{cursor:default}\n\n.bx--toggle.bx--skeleton+.bx--toggle__label>.bx--toggle__appearance:before,.bx--toggle.bx--skeleton+.bx--toggle__label>.bx--toggle__appearance:after{background-color:#3d70b2;border-color:#3d70b2;cursor:default}\n\n.bx--toggle.bx--skeleton+.bx--toggle__label>.bx--toggle__text--left,.bx--toggle.bx--skeleton+.bx--toggle__label>.bx--toggle__text--right{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:1.25rem;height:.75rem}\n\n.bx--toggle.bx--skeleton+.bx--toggle__label>.bx--toggle__text--left:hover,.bx--toggle.bx--skeleton+.bx--toggle__label>.bx--toggle__text--left:focus,.bx--toggle.bx--skeleton+.bx--toggle__label>.bx--toggle__text--left:active,.bx--toggle.bx--skeleton+.bx--toggle__label>.bx--toggle__text--right:hover,.bx--toggle.bx--skeleton+.bx--toggle__label>.bx--toggle__text--right:focus,.bx--toggle.bx--skeleton+.bx--toggle__label>.bx--toggle__text--right:active{border:none;outline:none;cursor:default}\n\n.bx--toggle.bx--skeleton+.bx--toggle__label>.bx--toggle__text--left:before,.bx--toggle.bx--skeleton+.bx--toggle__label>.bx--toggle__text--right:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--toggle.bx--skeleton+.bx--toggle__label>.bx--toggle__appearance:before{background:transparent;border-color:#5a6872}\n\n.bx--toggle.bx--skeleton+.bx--toggle__label>.bx--toggle__appearance:after{background-color:#5a6872;border:none}\n\n.bx--search{display:flex;position:relative;width:100%}\n\n.bx--search .bx--label{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);border:0;visibility:visible;white-space:nowrap}\n\n.bx--search-input{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:none;background-color:#f4f7fb;color:#152935;font-weight:600;padding:0 2.5rem;text-overflow:ellipsis;width:100%;order:1}\n\n.bx--search-input:focus{outline:none}\n\n.bx--search-input:focus ~ .bx--search-magnifier{fill:#3d70b2}\n\n.bx--search-input:-ms-input-placeholder{color:#5a6872;font-weight:400}\n\n.bx--search-input::-webkit-input-placeholder{color:#5a6872;font-weight:400}\n\n.bx--search-input::-ms-input-placeholder{color:#5a6872;font-weight:400}\n\n.bx--search-input::placeholder{color:#5a6872;font-weight:400}\n\n.bx--search-input::-ms-clear{display:none}\n\n.bx--search--light .bx--search-input{background:#fff}\n\n.bx--search--sm .bx--search-input{font-size:0.875rem;height:2rem}\n\n.bx--search--lg .bx--search-input{font-size:0.875rem;height:2.5rem}\n\n.bx--search-magnifier,.bx--search-close{position:absolute;height:1rem;width:1rem;top:calc(50% - 0.5rem);z-index:1}\n\n.bx--search-magnifier{left:0.75rem;fill:#5a6872;z-index:2}\n\n.bx--search-close{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;letter-spacing:0;display:inline-block;background:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:0;padding:0;cursor:pointer;transition:opacity 250ms;fill:#5a6872;cursor:pointer;visibility:visible;opacity:1}\n\n.bx--search-close::-moz-focus-inner{border:0}\n\n.bx--search-close:focus{outline:1px solid #3d70b2;outline-offset:2px}\n\n.bx--search-close{right:0.75rem}\n\n.bx--search--lg .bx--search-close{right:.75rem}\n\n.bx--search-button{border:0;transition:250ms;height:2.5rem;width:2.5rem;min-width:2.5rem;margin-left:.25rem;background-color:#fff;position:relative;padding:0;outline:1px solid transparent;order:2}\n\n.bx--search-button svg{position:relative;top:-1px;box-sizing:border-box;vertical-align:middle;transition:250ms;fill:#30588c;height:1rem;width:1rem}\n\n.bx--search-button:hover,.bx--search-button:focus{cursor:pointer;background-color:#3d70b2;outline:1px solid transparent}\n\n.bx--search-button:hover svg,.bx--search-button:focus svg{fill:#fff}\n\n.bx--search-close--hidden{visibility:hidden;opacity:0}\n\n.bx--search-view--hidden{display:none}\n\n.bx--search--lg.bx--skeleton .bx--search-input,.bx--search--sm.bx--skeleton .bx--search-input{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:100%}\n\n.bx--search--lg.bx--skeleton .bx--search-input:hover,.bx--search--lg.bx--skeleton .bx--search-input:focus,.bx--search--lg.bx--skeleton .bx--search-input:active,.bx--search--sm.bx--skeleton .bx--search-input:hover,.bx--search--sm.bx--skeleton .bx--search-input:focus,.bx--search--sm.bx--skeleton .bx--search-input:active{border:none;outline:none;cursor:default}\n\n.bx--search--lg.bx--skeleton .bx--search-input:before,.bx--search--sm.bx--skeleton .bx--search-input:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--search--lg.bx--skeleton .bx--search-input:-ms-input-placeholder,.bx--search--sm.bx--skeleton .bx--search-input:-ms-input-placeholder{color:transparent}\n\n.bx--search--lg.bx--skeleton .bx--search-input::-webkit-input-placeholder,.bx--search--sm.bx--skeleton .bx--search-input::-webkit-input-placeholder{color:transparent}\n\n.bx--search--lg.bx--skeleton .bx--search-input::-ms-input-placeholder,.bx--search--sm.bx--skeleton .bx--search-input::-ms-input-placeholder{color:transparent}\n\n.bx--search--lg.bx--skeleton .bx--search-input::placeholder,.bx--search--sm.bx--skeleton .bx--search-input::placeholder{color:transparent}\n\n.bx--select{position:relative;display:flex;flex-direction:column}\n\n.bx--select-input{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;font-size:0.875rem;height:2.5rem;-webkit-appearance:none;-moz-appearance:none;appearance:none;display:block;width:100%;padding:0 2.5rem 0 1rem;color:#152935;background-color:#f4f7fb;border:none;box-shadow:0 1px 0 0 #5a6872;order:2;border-radius:0;cursor:pointer;border-bottom:1px solid transparent}\n\n.bx--select-input::-ms-expand{display:none}\n\n.bx--select-input ~ .bx--label{order:1}\n\n.bx--select-input:focus{outline:none;box-shadow:0 2px 0 0 #3d70b2}\n\n.bx--select-input[data-invalid],.bx--select-input[data-invalid]:focus{box-shadow:0 2px 0 0 #e0182d}\n\n.bx--select-input:focus ~ .bx--label{color:#3d70b2}\n\n.bx--select-input[data-invalid]:focus ~ .bx--label{color:#e0182d}\n\n.bx--select-input:disabled{opacity:0.5;cursor:not-allowed}\n\n.bx--select-input ~ .bx--form-requirement{order:3;color:#e0182d;font-weight:400;margin-top:.25rem}\n\n.bx--select-input ~ .bx--form-requirement::before{display:none}\n\n.bx--select--light .bx--select-input{background:#fff}\n\n.bx--select__arrow{fill:#3d70b2;position:absolute;right:1rem;bottom:1rem;width:.625rem;height:.3125rem;pointer-events:none}\n\n[data-invalid] ~ .bx--select__arrow{bottom:2.25rem}\n\n.bx--select-optgroup,.bx--select-option{color:#152935}\n\n.bx--select-option[disabled]{opacity:0.5;cursor:not-allowed}\n\n@-moz-document url-prefix(){.bx--select-option{background-color:#fff;color:#152935}.bx--select-optgroup{color:#152935}}\n\n.bx--select--inline{display:-ms-grid;display:grid;-ms-grid-columns:auto auto;grid-template-columns:auto auto}\n\n@media all and (-ms-high-contrast: none), (-ms-high-contrast: active){.bx--select--inline{display:flex;flex-direction:row;align-items:center}}\n\n.bx--select--inline .bx--label{white-space:nowrap;margin:0 .5rem 0 0;font-weight:400;-ms-grid-row-align:center;align-self:center}\n\n.bx--select--inline .bx--select-input{background-color:transparent;color:#3d70b2;font-weight:600;box-shadow:none}\n\n.bx--select--inline .bx--select-input:hover{background-color:#fff}\n\n.bx--select--inline .bx--select-input:focus{outline:1px solid #3d70b2}\n\n.bx--select--inline .bx--select-input ~ .bx--select__arrow{bottom:auto;top:1rem}\n\n.bx--select--inline .bx--select-input[data-invalid]{color:#152935;outline-offset:2px}\n\n.bx--select--inline .bx--select-input[data-invalid]:focus{outline:1px solid #e0182d;box-shadow:none}\n\n.bx--select--inline .bx--select-input:disabled ~ *{opacity:0.5;cursor:not-allowed}\n\n.bx--select--inline .bx--select-input ~ .bx--form-requirement{-ms-grid-column:2;grid-column-start:2}\n\n@media all and (-ms-high-contrast: none), (-ms-high-contrast: active){.bx--select--inline .bx--select-input ~ .bx--form-requirement{position:absolute;bottom:-1.5rem}}\n\n.bx--select.bx--skeleton{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:100%;height:2.5rem}\n\n.bx--select.bx--skeleton:hover,.bx--select.bx--skeleton:focus,.bx--select.bx--skeleton:active{border:none;outline:none;cursor:default}\n\n.bx--select.bx--skeleton:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--select.bx--skeleton .bx--select-input{display:none}\n\n.bx--text-input{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;font-size:0.875rem;display:block;width:100%;height:2.5rem;min-width:18.75rem;padding:0 1rem;color:#152935;background-color:#f4f7fb;border:none;box-shadow:0 1px 0 0 #5a6872;order:2;border-bottom:1px solid transparent}\n\n.bx--text-input ~ .bx--label{order:1}\n\n.bx--text-input:-ms-input-placeholder{color:#cdd1d4}\n\n.bx--text-input::-webkit-input-placeholder{color:#cdd1d4}\n\n.bx--text-input::-ms-input-placeholder{color:#cdd1d4}\n\n.bx--text-input::placeholder{color:#cdd1d4}\n\n.bx--text-input:focus{outline:none;box-shadow:0 2px 0 0 #3d70b2}\n\n.bx--text-input[data-invalid],.bx--text-input[data-invalid]:focus{box-shadow:0 2px 0 0 #e0182d}\n\n.bx--text-input:focus ~ .bx--label{color:#3d70b2}\n\n.bx--text-input[data-invalid]:focus+.bx--label{color:#e0182d}\n\n.bx--text-input:disabled{opacity:0.5;cursor:not-allowed}\n\n.bx--text-input:disabled:hover{border:none}\n\n.bx--text-input ~ .bx--form-requirement{order:3;color:#e0182d;font-weight:400;margin-top:.25rem}\n\n.bx--text-input ~ .bx--form-requirement::before{display:none}\n\n.bx--text-input-wrapper svg[hidden]{display:none}\n\n.bx--text-input[data-toggle-password-visibility]+.bx--text-input--password__visibility{top:-1.75rem;right:.75rem;display:flex;justify-content:center;align-self:flex-end;align-items:center;order:3;height:1rem;width:1rem;padding:0;margin-bottom:-1rem;border:0;background:none;cursor:pointer;outline:inherit}\n\n.bx--text-input[data-toggle-password-visibility]+.bx--text-input--password__visibility svg{fill:#3d70b2}\n\n.bx--text-input[data-toggle-password-visibility]+.bx--text-input--password__visibility svg:hover{fill:#30588c}\n\n.bx--text-input--light{background-color:#fff}\n\n.bx--text-input.bx--skeleton{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:100%}\n\n.bx--text-input.bx--skeleton:hover,.bx--text-input.bx--skeleton:focus,.bx--text-input.bx--skeleton:active{border:none;outline:none;cursor:default}\n\n.bx--text-input.bx--skeleton:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--text-input.bx--skeleton::-webkit-input-placeholder{color:transparent}\n\n.bx--text-area{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;font-size:0.875rem;width:100%;min-width:10rem;padding:1rem;color:#152935;background-color:#f4f7fb;border:none;box-shadow:0 1px 0 0 #5a6872;order:2;resize:vertical;border-bottom:1px solid transparent}\n\n.bx--text-area ~ .bx--label{order:1}\n\n.bx--text-area:focus{outline:none;box-shadow:0 2px 0 0 #3d70b2}\n\n.bx--text-area:-ms-input-placeholder{color:#cdd1d4}\n\n.bx--text-area::-webkit-input-placeholder{color:#cdd1d4}\n\n.bx--text-area::-ms-input-placeholder{color:#cdd1d4}\n\n.bx--text-area::placeholder{color:#cdd1d4}\n\n.bx--text-area:disabled{opacity:0.5;cursor:not-allowed}\n\n.bx--text-area:disabled:hover{border:1px solid transparent}\n\n.bx--text-area[data-invalid],.bx--text-area[data-invalid]:focus{box-shadow:0 2px 0 0 #e0182d}\n\n.bx--text-area:focus ~ .bx--label{color:#3d70b2}\n\n.bx--text-area[data-invalid]:focus+.bx--label{color:#e0182d}\n\n.bx--text-area ~ .bx--form-requirement{order:3;color:#e0182d;font-weight:400;margin-top:.25rem}\n\n.bx--text-area ~ .bx--form-requirement::before{display:none}\n\n.bx--text-area--light{background:#fff}\n\nbx--text-area.bx--skeleton{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);height:6.25rem}\n\nbx--text-area.bx--skeleton:hover,bx--text-area.bx--skeleton:focus,bx--text-area.bx--skeleton:active{border:none;outline:none;cursor:default}\n\nbx--text-area.bx--skeleton:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\nbx--text-area.bx--skeleton::-webkit-input-placeholder{color:transparent}\n\n.bx--number{display:flex;flex-direction:column;position:relative}\n\n.bx--number input[type='number']{font-size:0.875rem;font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;box-sizing:border-box;display:inline-flex;width:100%;min-width:9.375rem;padding-left:1rem;padding-right:2rem;font-weight:300;height:2.5rem;color:#152935;background-color:#f4f7fb;border:none;box-shadow:0 1px 0 0 #5a6872;order:2;border-radius:0;border-bottom:1px solid transparent}\n\n.bx--number input[type='number'] ~ .bx--label{order:1}\n\n.bx--number input[type='number']:focus{outline:none;box-shadow:0 2px 0 0 #3d70b2}\n\n.bx--number input[type='number']:focus ~ .bx--label{color:#3d70b2}\n\n.bx--number input[type='number']:disabled{opacity:0.5;cursor:not-allowed}\n\n.bx--number input[type='number']:disabled ~ .bx--number__controls{opacity:0.5;cursor:not-allowed;pointer-events:none}\n\n.bx--number input[type='number'] ~ .bx--form-requirement{order:3;color:#e0182d;font-weight:400;margin-top:.25rem;overflow:visible}\n\n.bx--number input[type='number'] ~ .bx--form-requirement::before{display:none}\n\n.bx--number input[type='number']{-webkit-appearance:textfield;-moz-appearance:textfield;appearance:textfield}\n\n.bx--number input[type='number']::-ms-clear{display:none}\n\n.bx--number input[type='number']::-webkit-inner-spin-button{-webkit-appearance:none;appearance:none}\n\n.bx--number__controls{position:absolute;display:block;left:auto;display:flex;flex-direction:column;justify-content:center;align-items:center;left:auto;right:0.5rem;top:2rem}\n\n.bx--number__control-btn{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;letter-spacing:0;display:inline-block;background:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:0;padding:0;cursor:pointer;width:100%;display:inline-flex;justify-content:center;align-items:center;position:relative;width:1.25rem;height:.625rem}\n\n.bx--number__control-btn::-moz-focus-inner{border:0}\n\n.bx--number__control-btn:focus{outline:1px solid #3d70b2}\n\n.bx--number__control-btn:hover{cursor:pointer}\n\n.bx--number__control-btn:hover svg{fill:#30588c}\n\n.bx--number__controls svg{fill:#3d70b2}\n\n.bx--number__controls svg:hover{cursor:pointer;fill:#30588c}\n\n.bx--number[data-invalid] .bx--form-requirement{display:inline-block;max-height:12.5rem}\n\n.bx--number[data-invalid] input[type='number'],.bx--number[data-invalid] input[type='number']:focus{outline:none;box-shadow:0 2px 0px 0px #e0182d}\n\n.bx--number[data-invalid] input[type='number']:focus ~ .bx--label{color:#e0182d}\n\n.bx--number--nolabel .bx--number__controls{top:0.625rem}\n\n.bx--number--helpertext .bx--number__controls{top:2.25rem}\n\n.bx--number--helpertext:not([data-invalid]) .bx--number__controls{top:auto;bottom:0.625rem}\n\n.bx--number--helpertext[data-invalid] .bx--number__controls{top:auto;bottom:2rem}\n\n.bx--number--light input[type='number']{background:#fff}\n\n.bx--number.bx--skeleton{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:100%;height:2.5rem}\n\n.bx--number.bx--skeleton:hover,.bx--number.bx--skeleton:focus,.bx--number.bx--skeleton:active{border:none;outline:none;cursor:default}\n\n.bx--number.bx--skeleton:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--number.bx--skeleton input[type='number']{display:none}\n\n.bx--link{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;font-size:0.875rem;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-weight:600;color:#3d70b2;text-decoration:underline;transition:250ms}\n\n.bx--link:visited{color:#3d70b2}\n\n.bx--link:active,.bx--link:hover,.bx--link:focus{color:#294c79}\n\n.bx--link:focus{outline:1px solid #3d70b2}\n\n.bx--link[aria-disabled='true']{opacity:0.5;pointer-events:none}\n\n.bx--list--nested,.bx--list--unordered,.bx--list--ordered{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;font-size:0.875rem;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;margin-left:2rem;line-height:1.5}\n\n.bx--list--unordered,.bx--list--ordered{padding:1rem}\n\n.bx--list__item{font-weight:600;padding-left:.25rem;color:#152935}\n\n.bx--list--unordered>.bx--list__item{list-style-type:disc}\n\n.bx--list--ordered>.bx--list__item{list-style-type:decimal}\n\n.bx--list--nested{margin-left:.5rem}\n\n.bx--list--nested>.bx--list__item{list-style-type:none;font-weight:400}\n\n.bx--list--nested>.bx--list__item:before{content:'-';padding-right:.25rem}\n\n.bx--overflow-menu{position:relative;width:1.25rem;height:2.375rem;cursor:pointer}\n\n.bx--overflow-menu:focus{outline:1px solid transparent;box-shadow:0 0 0 1px #3d70b2}\n\n.bx--overflow-menu__icon{width:100%;height:100%;padding:0.5rem;fill:#5a6872}\n\n.bx--overflow-menu__icon:hover,.bx--overflow-menu__icon:focus{fill:#3d70b2}\n\n.bx--overflow-menu-options{box-shadow:0 4px 8px 0 rgba(0,0,0,0.1);display:none;flex-direction:column;align-items:flex-start;position:absolute;z-index:10000;background-color:#fff;border:1px solid #dfe3e6;width:11.25rem;list-style:none;margin-top:.25rem;padding:.25rem 0 .5rem;left:-20px}\n\n.bx--overflow-menu-options--open{display:flex}\n\n.bx--overflow-menu-options:before{content:'';position:absolute;display:block;width:.5rem;height:.5rem;z-index:-1;-webkit-transform:rotate(45deg);transform:rotate(45deg);background-color:#fff;border-top:1px solid #dfe3e6;border-left:1px solid #dfe3e6;top:-5px;left:24px}\n\n.bx--overflow-menu-options[data-floating-menu-direction='top']:before{-webkit-transform:rotate(225deg);transform:rotate(225deg);top:auto;bottom:-5px}\n\n.bx--overflow-menu-options__option{display:flex;background-color:transparent;align-items:center;width:100%;padding:0}\n\n.bx--overflow-menu--divider{border-top:1px solid #dfe3e6}\n\n.bx--overflow-menu-options__btn{font-size:0.875rem;font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;font-weight:400;width:100%;height:100%;border:none;display:inline-block;background-color:transparent;text-align:left;padding:.5rem 1rem;cursor:pointer;color:#152935;max-width:11.25rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n\n.bx--overflow-menu-options__btn:focus{outline:1px solid transparent;text-decoration:underline;background-color:rgba(85,150,230,0.1);text-decoration:underline}\n\n.bx--overflow-menu-options__option--danger .bx--overflow-menu-options__btn:focus{outline:1px solid transparent;text-decoration:underline}\n\n.bx--overflow-menu-options__option:hover{background-color:rgba(85,150,230,0.1)}\n\n.bx--overflow-menu-options__option:hover .bx--overflow-menu-options__btn{text-decoration:none;background-color:rgba(85,150,230,0.1);text-decoration:none}\n\n.bx--overflow-menu-options__option--danger{border-top:1px solid #dfe3e6}\n\n.bx--overflow-menu-options__option--danger .bx--overflow-menu-options__btn:hover,.bx--overflow-menu-options__option--danger .bx--overflow-menu-options__btn:focus{color:#fff;background-color:#e0182d}\n\n.bx--overflow-menu-options__option--disabled:hover{background-color:#fff}\n\n.bx--overflow-menu-options__option--disabled .bx--overflow-menu-options__btn{color:#152935;cursor:not-allowed;opacity:0.5}\n\n.bx--overflow-menu-options__option--disabled:hover .bx--overflow-menu-options__btn{color:#152935;opacity:0.5;background-color:#fff}\n\n.bx--overflow-menu-options__option--disabled:hover .bx--overflow-menu-options__btn:active,.bx--overflow-menu-options__option--disabled:hover .bx--overflow-menu-options__btn:focus{background-color:#fff;pointer-events:none}\n\n.bx--overflow-menu--flip{left:-140px}\n\n.bx--overflow-menu--flip:before{left:145px}\n\n.bx--responsive-table-container{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;overflow-x:auto;overflow-y:hidden;width:99.9%}\n\n.bx--responsive-table{background-color:#fff;width:100%;min-width:500px;border-collapse:collapse;border-spacing:0;border:2px solid #dfe3e6}\n\n.bx--responsive-table td{font-size:0.875rem;padding:0 .375rem;vertical-align:middle;color:#152935}\n\n.bx--responsive-table td p{font-size:0.875rem}\n\n.bx--responsive-table th{font-size:0.75rem;padding:.5625rem .375rem;vertical-align:middle;font-weight:600;color:#152935}\n\n.bx--responsive-table th:focus{outline:1px solid transparent}\n\n.bx--responsive-table th:focus span{outline:1px solid #3d70b2}\n\n.bx--responsive-table--tall td,.bx--responsive-table--tall th{padding-top:.9375rem;padding-bottom:.9375rem}\n\n.bx--responsive-table--static-size{border-collapse:collapse;width:auto;border:2px solid #dfe3e6}\n\n.bx--responsive-table--static-size tr td:first-child,.bx--responsive-table--static-size tr th:first-child{padding-left:1.5rem}\n\n.bx--responsive-table--tall td,.bx--responsive-table--tall th{padding-top:.625rem;padding-bottom:.625rem}\n\n.bx--table-row{height:2rem;padding-left:1rem}\n\n.bx--table-head .bx--table-row{border-bottom:1px solid #3d70b2;height:2rem}\n\n.bx--table-header{font-size:0.75rem;font-weight:600;text-align:left;text-transform:uppercase;height:2.5rem}\n\n.bx--table-body>.bx--parent-row,.bx--table-body>.bx--parent-row{background-color:#fff}\n\n.bx--table-body>.bx--parent-row+.bx--expandable-row,.bx--table-body>.bx--parent-row+.bx--expandable-row{background-color:#fff}\n\n.bx--table-body>.bx--parent-row--even,.bx--table-body>.bx--parent-row--even{background-color:#f4f7fb}\n\n.bx--table-body>.bx--parent-row--even+.bx--expandable-row,.bx--table-body>.bx--parent-row--even+.bx--expandable-row{background-color:#f4f7fb}\n\n.bx--table-body .bx--table-row{border:1px solid transparent}\n\n.bx--table-body .bx--table-row:first-child:hover,.bx--table-body .bx--table-row:first-child:focus{border-left:2px solid #5596e6;outline:1px solid #5596e6}\n\n.bx--table-body .bx--table-row:not(:first-child):hover,.bx--table-body .bx--table-row:not(:first-child):focus{border-left:2px solid #5596e6;outline:1px solid #5596e6}\n\n.bx--expandable-row>td{border-left:4px solid #3d70b2;padding:2rem}\n\n.bx--expandable-row--hidden{visibility:hidden}\n\n.bx--table-expand{padding-left:.5rem;padding-right:.75rem;text-align:center;width:1.25rem;cursor:pointer}\n\n.bx--table-expand:focus{outline:1px solid transparent}\n\n.bx--table-expand:focus svg{outline:1px solid #3d70b2}\n\n.bx--table-expand__svg{fill:#5a6872;-webkit-transform:rotate(0deg);transform:rotate(0deg);transition:-webkit-transform 200ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 200ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 200ms cubic-bezier(0.5, 0, 0.1, 1), -webkit-transform 200ms cubic-bezier(0.5, 0, 0.1, 1);width:12px;height:12px;margin-left:.4375rem;margin-right:.125rem}\n\n@media all and (min--moz-device-pixel-ratio: 0) and (min-resolution: 3e1dpcm){.bx--table-expand__svg{margin-top:2px}}\n\n.bx--table-expand[data-previous-value='collapsed'] .bx--table-expand__svg{-webkit-transform:rotate(90deg);transform:rotate(90deg);transition:-webkit-transform 200ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 200ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 200ms cubic-bezier(0.5, 0, 0.1, 1), -webkit-transform 200ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n[data-event='sort']{cursor:pointer}\n\n.bx--table-sort__svg{fill:#5a6872;width:8px;height:8px;-webkit-transform:rotate(0deg);transform:rotate(0deg);transition:-webkit-transform 200ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 200ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 200ms cubic-bezier(0.5, 0, 0.1, 1), -webkit-transform 200ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--table-sort--ascending .bx--table-sort__svg{-webkit-transform:rotate(180deg);transform:rotate(180deg);transition:-webkit-transform 200ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 200ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 200ms cubic-bezier(0.5, 0, 0.1, 1), -webkit-transform 200ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--table-select{width:1.875rem;text-align:center;padding-left:0;padding-right:0}\n\n.bx--table-select .bx--checkbox-label{display:inline-flex;margin:0}\n\n@media all and (min--moz-device-pixel-ratio: 0) and (min-resolution: 3e1dpcm){.bx--table-select .bx--checkbox-label{margin-top:2px}}\n\n.bx--table-select .bx--checkbox-appearance{margin:0}\n\n.bx--table-overflow{width:2.5rem;text-align:center}\n\n.bx--table-overflow .bx--overflow-menu{padding:0}\n\n.bx--table-toolbar{display:flex;padding-top:.5rem;padding-bottom:.5rem;width:100%;position:relative}\n\n.bx--table-toolbar .bx--search-input{position:relative}\n\n.bx--table-toolbar .bx--search-input:focus{box-shadow:inset 0px 0px 0px 1px #3d70b2;outline:0}\n\n.bx--toolbar-content{display:flex;margin-left:auto}\n\n.bx--toolbar-action{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;letter-spacing:0;display:inline-block;background:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:0;padding:0;cursor:pointer;width:100%;cursor:pointer;padding-left:.75rem;padding-right:.75rem}\n\n.bx--toolbar-action::-moz-focus-inner{border:0}\n\n.bx--toolbar-action:hover>.bx--toolbar-action__icon{fill:#3d70b2}\n\n.bx--toolbar-action:focus{outline:1px solid #3d70b2}\n\n.bx--toolbar-action:focus>.bx--toolbar-action__icon{fill:#3d70b2}\n\n.bx--toolbar-action:active>.bx--toolbar-action__icon{fill:#3d70b2}\n\n.bx--toolbar-action:last-of-type{padding-right:0}\n\n.bx--toolbar-action ~ .bx--btn{margin-left:.75rem;margin-right:.75rem}\n\n.bx--toolbar-action__icon{height:1rem;width:auto;max-width:16px;fill:#5a6872;transition:250ms}\n\n.bx--batch-actions{display:flex;align-items:center;position:absolute;opacity:0;left:0;top:0;padding-left:1.5rem;padding-right:1.5rem;width:100%;height:100%;z-index:6000;background-color:transparent;transition:opacity 200ms cubic-bezier(0.5, 0, 0.1, 1),background-color 200ms cubic-bezier(0.5, 0, 0.1, 1);pointer-events:none;visibility:hidden}\n\n.bx--batch-actions:focus{outline:1px solid #3d70b2}\n\n.bx--batch-actions .bx--btn{color:#fff}\n\n.bx--batch-actions .bx--btn__icon{fill:#fff}\n\n.bx--batch-actions .bx--btn--ghost:hover,.bx--batch-actions .bx--btn--ghost:focus{background-color:#fff;color:#3d70b2}\n\n.bx--batch-actions .bx--btn--ghost:hover .bx--btn__icon,.bx--batch-actions .bx--btn--ghost:focus .bx--btn__icon{fill:#3d70b2}\n\n.bx--batch-actions .bx--btn--ghost:focus{border:2px solid #3d70b2;outline:2px solid #f4f7fb}\n\n.bx--batch-actions--active{visibility:visible;background-color:#3d70b2;pointer-events:all;transition:opacity 200ms cubic-bezier(0.5, 0, 0.1, 1),background-color 200ms cubic-bezier(0.5, 0, 0.1, 1);opacity:1}\n\n.bx--action-list{margin-left:-0.5rem}\n\n.bx--action-icons{margin-left:auto}\n\n.bx--action-icons svg{padding:0 .75rem;fill:#fff;height:1rem;width:auto}\n\n.bx--batch-summary{margin-left:auto;display:flex;align-items:center;color:#fff}\n\n.bx--batch-summary__para{font-size:0.875rem;margin-right:1.5rem}\n\n.bx--batch-summary__cancel{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;letter-spacing:0;display:inline-block;background:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:0;padding:0;cursor:pointer;font-size:0.875rem;color:#fff;border-bottom:1px solid transparent;font-weight:600;cursor:pointer;transition:border 250ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--batch-summary__cancel::-moz-focus-inner{border:0}\n\n.bx--batch-summary__cancel:hover,.bx--batch-summary__cancel:focus{border-bottom:1px solid #fff}\n\n.bx--batch-actions ~ .bx--toolbar-search-container,.bx--batch-actions ~ .bx--toolbar-content{opacity:1;transition:opacity 250ms}\n\n.bx--batch-actions--active ~ .bx--toolbar-search-container,.bx--batch-actions--active ~ .bx--toolbar-content{opacity:0}\n\n.bx--data-table-v2-container{width:100%;min-width:31.25rem;overflow-x:auto;padding-top:.125rem}\n\n.bx--data-table-v2{border-collapse:collapse;border-spacing:0;width:100%;border-bottom:1px solid #dfe3e6}\n\n.bx--data-table-v2 thead{font-size:0.875rem;background-color:#f4f7fb;font-weight:700;border-right:1px solid #dfe3e6}\n\n.bx--data-table-v2 tbody{font-size:0.875rem;background-color:#fff;border-right:1px solid #dfe3e6}\n\n.bx--data-table-v2 tr{height:3rem}\n\n.bx--data-table-v2 tr:hover td{background-color:rgba(85,150,230,0.1);border-top:1px solid #3d70b2;border-bottom:1px solid #3d70b2}\n\n.bx--data-table-v2 tr:hover td:first-of-type{border-left:1px solid #3d70b2}\n\n.bx--data-table-v2 tr:hover td:last-of-type{border-right:1px solid #3d70b2}\n\n.bx--data-table-v2 tr:hover .bx--overflow-menu{opacity:1}\n\n.bx--data-table-v2 th{border-top:1px solid #dfe3e6}\n\n.bx--data-table-v2 th,.bx--data-table-v2 td{font-size:0.875rem;border-top:1px solid #dfe3e6;padding-left:.75rem;vertical-align:middle;text-align:left;color:#152935}\n\n.bx--data-table-v2 th:first-of-type,.bx--data-table-v2 td:first-of-type{padding-left:1.5rem;border-left:1px solid #dfe3e6}\n\n.bx--data-table-v2 th:last-of-type,.bx--data-table-v2 td:last-of-type{padding-right:1.5rem}\n\n.bx--data-table-v2 .bx--checkbox-label{padding-left:1.75rem}\n\n.bx--data-table-v2 .bx--overflow-menu{opacity:0}\n\n.bx--data-table-v2 .bx--overflow-menu:focus{outline:0;opacity:1;box-shadow:none}\n\n.bx--data-table-v2 .bx--overflow-menu:focus .bx--overflow-menu__icon{box-shadow:inset 0px 0px 0px 1px #3d70b2}\n\n.bx--data-table-v2 .bx--overflow-menu__icon{-webkit-transform:rotate(90deg);transform:rotate(90deg)}\n\n.bx--data-table-v2-header{margin-bottom:.5rem;color:#152935}\n\n.bx--data-table-v2--zebra tbody tr:nth-child(even){background-color:#f4f7fb}\n\n.bx--data-table-v2--no-border{border-bottom-color:transparent}\n\n.bx--data-table-v2--no-border thead,.bx--data-table-v2--no-border tbody{border-right-color:transparent}\n\n.bx--data-table-v2--no-border th:first-of-type,.bx--data-table-v2--no-border td:first-of-type{border-left-color:transparent}\n\n.bx--data-table-v2--compact tbody tr{height:1.5rem}\n\n.bx--data-table-v2--short tbody tr{height:2rem}\n\n.bx--data-table-v2--tall tbody tr{height:4rem}\n\n.bx--data-table-v2--static{width:auto}\n\n.bx--data-table-v2--zebra tbody tr.bx--data-table-v2--selected,tbody tr.bx--data-table-v2--selected{background-color:rgba(85,150,230,0.1)}\n\ntr.bx--expandable-row-v2.bx--expandable-row--hidden-v2{display:none}\n\ntr.bx--expandable-row-v2>td:first-of-type{position:relative}\n\ntr.bx--expandable-row-v2>td:first-of-type:before{content:'';position:absolute;top:0;left:0;height:100%;width:2px;background-color:#3d70b2}\n\ntr.bx--expandable-row-v2+tr[data-child-row] td{border-top:0;padding-bottom:.5rem}\n\ntr.bx--expandable-row-v2:hover>td{background-color:rgba(85,150,230,0.1)}\n\ntr.bx--expandable-row-v2:hover>td:first-of-type{border-left:1px solid transparent}\n\ntr.bx--expandable-row-v2:hover>td:last-of-type{border-right:1px solid #3d70b2}\n\ntr.bx--expandable-row-v2:hover[data-parent-row]>td{border-bottom:0}\n\ntr.bx--expandable-row-v2:hover+tr[data-child-row]>td{background-color:rgba(85,150,230,0.1);border-bottom:1px solid #3d70b2;border-right:1px solid #3d70b2}\n\ntr.bx--expandable-row--hover-v2>td{background-color:rgba(85,150,230,0.1);border-top:1px solid #3d70b2}\n\ntr.bx--expandable-row--hover-v2>td:last-of-type{border-right:1px solid #3d70b2}\n\n.bx--table-expand-v2{width:2.5rem}\n\n.bx--table-expand-v2[data-previous-value='collapsed'] .bx--table-expand-v2__svg{-webkit-transform:rotate(90deg);transform:rotate(90deg);transition:-webkit-transform 200ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 200ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 200ms cubic-bezier(0.5, 0, 0.1, 1), -webkit-transform 200ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--table-expand-v2__button{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;letter-spacing:0;display:inline-block;background:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:0;padding:0;cursor:pointer}\n\n.bx--table-expand-v2__button::-moz-focus-inner{border:0}\n\n.bx--table-expand-v2__button:focus{outline:1px solid transparent}\n\n.bx--table-expand-v2__button:focus svg{box-shadow:inset 0px 0px 0px 1px #3d70b2}\n\n.bx--table-expand-v2__svg{fill:#5a6872;-webkit-transform:rotate(0deg);transform:rotate(0deg);transition:-webkit-transform 200ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 200ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 200ms cubic-bezier(0.5, 0, 0.1, 1), -webkit-transform 200ms cubic-bezier(0.5, 0, 0.1, 1);height:16px;width:auto;max-width:16px;padding:.125rem}\n\n.bx--table-sort-v2--ascending .bx--table-sort-v2__icon{-webkit-transform:rotate(180deg);transform:rotate(180deg);transition:-webkit-transform 200ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 200ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 200ms cubic-bezier(0.5, 0, 0.1, 1), -webkit-transform 200ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--table-sort-v2--active .bx--table-sort-v2__icon{opacity:1}\n\n.bx--data-table-v2 th:hover .bx--table-sort-v2__icon{opacity:1}\n\n.bx--table-sort-v2{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;letter-spacing:0;display:inline-block;background:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:0;padding:0;cursor:pointer;position:relative;font:inherit;cursor:pointer;display:flex;align-items:center;width:100%;color:#152935}\n\n.bx--table-sort-v2::-moz-focus-inner{border:0}\n\n.bx--table-sort-v2:focus{outline:0}\n\n.bx--table-sort-v2:focus svg{opacity:1;outline:1px solid #3d70b2;fill:#3d70b2;outline-offset:-0.5px}\n\n.bx--table-sort-v2__icon{position:relative;left:2px;transition:-webkit-transform 200ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 200ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 200ms cubic-bezier(0.5, 0, 0.1, 1), -webkit-transform 200ms cubic-bezier(0.5, 0, 0.1, 1);-webkit-transform:rotate(0);transform:rotate(0);opacity:0;fill:#5a6872;height:.5625rem;padding:.125rem;width:auto;min-width:14px}\n\n.bx--inline-edit-label{display:flex;justify-content:space-between;align-items:center}\n\n.bx--inline-edit-label:hover .bx--inline-edit-label__icon{opacity:1}\n\n.bx--inline-edit-label--inactive{display:none}\n\n.bx--inline-edit-label__action{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;letter-spacing:0;display:inline-block;background:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:0;padding:0;cursor:pointer}\n\n.bx--inline-edit-label__action::-moz-focus-inner{border:0}\n\n.bx--inline-edit-label__action:hover{cursor:pointer}\n\n.bx--inline-edit-label__action:focus{outline:1px solid #3d70b2;padding:.125rem}\n\n.bx--inline-edit-label__action:focus .bx--inline-edit-label__icon{width:auto;opacity:1}\n\n.bx--inline-edit-label__icon{fill:#5a6872;opacity:0}\n\n.bx--inline-edit-input{display:none}\n\n.bx--inline-edit-input--active{display:block;margin-left:-.75rem}\n\n.bx--inline-edit-input--active input{padding-left:.75rem}\n\n.bx--data-table-v2--short input{height:2rem}\n\n.bx--data-table-v2--short select{padding:0.45rem 2.75rem 0.45rem 1rem}\n\n.bx--data-table-v2--short .bx--select__arrow{top:0.875rem}\n\n.bx--data-table-v2.bx--skeleton th{border-bottom:1px solid #3d70b2}\n\n.bx--data-table-v2.bx--skeleton th:nth-child(3n+1){width:10%}\n\n.bx--data-table-v2.bx--skeleton th:nth-child(3n+2){width:30%}\n\n.bx--data-table-v2.bx--skeleton th:nth-child(3n+3){width:15%}\n\n.bx--data-table-v2.bx--skeleton th span,.bx--data-table-v2.bx--skeleton td span{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:75%;height:1rem;display:block}\n\n.bx--data-table-v2.bx--skeleton th span:hover,.bx--data-table-v2.bx--skeleton th span:focus,.bx--data-table-v2.bx--skeleton th span:active,.bx--data-table-v2.bx--skeleton td span:hover,.bx--data-table-v2.bx--skeleton td span:focus,.bx--data-table-v2.bx--skeleton td span:active{border:none;outline:none;cursor:default}\n\n.bx--data-table-v2.bx--skeleton th span:before,.bx--data-table-v2.bx--skeleton td span:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--data-table-v2.bx--skeleton tr:hover td{border-color:#dfe3e6;background:transparent}\n\n.bx--data-table-v2.bx--skeleton tr:hover td:first-of-type,.bx--data-table-v2.bx--skeleton tr:hover td:last-of-type{border-color:#dfe3e6}\n\n.bx--data-table-v2.bx--skeleton .bx--table-sort-v2{pointer-events:none}\n\n.bx--structured-list--selection .bx--structured-list-td,.bx--structured-list--selection .bx--structured-list-th{padding-left:1rem;padding-right:1rem}\n\n.bx--structured-list--selection .bx--structured-list-td:first-child,.bx--structured-list--selection .bx--structured-list-th:first-child{padding-left:1rem;padding-right:.5rem}\n\n.bx--structured-list--selection .bx--structured-list-td:last-child,.bx--structured-list--selection .bx--structured-list-th:last-child{padding-right:2rem}\n\n[data-structured-list] .bx--structured-list-td,[data-structured-list] .bx--structured-list-th{padding-left:1rem;padding-right:1rem}\n\n[data-structured-list] .bx--structured-list-td:first-child,[data-structured-list] .bx--structured-list-th:first-child{padding-left:1rem;padding-right:.5rem}\n\n[data-structured-list] .bx--structured-list-td:last-child,[data-structured-list] .bx--structured-list-th:last-child{padding-right:2rem}\n\n.bx--structured-list-input{display:none}\n\n.bx--structured-list{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;display:table;overflow-x:auto;overflow-y:hidden;width:100%;min-width:500px;border-collapse:collapse;border-spacing:0;margin-bottom:5rem;background-color:transparent}\n\n.bx--structured-list.bx--structured-list--border{border:1px solid #dfe3e6;background-color:#fff}\n\n.bx--structured-list.bx--structured-list--condensed .bx--structured-list-td,.bx--structured-list.bx--structured-list--condensed .bx--structured-list-th{padding:.5rem;padding-left:0}\n\n.bx--structured-list-row{display:table-row;border-bottom:1px solid #dfe3e6;transition:250ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--structured-list--selection .bx--structured-list-row:hover:not(.bx--structured-list-row--header-row){background-color:rgba(85,150,230,0.1);cursor:pointer}\n\n[data-structured-list] .bx--structured-list-row:hover:not(.bx--structured-list-row--header-row){background-color:rgba(85,150,230,0.1);cursor:pointer}\n\n.bx--structured-list-row.bx--structured-list-row--selected{background-color:rgba(85,150,230,0.1)}\n\n.bx--structured-list-row.bx--structured-list-row--header-row{border-bottom:2px solid #3d70b2;cursor:inherit}\n\n.bx--structured-list-row:focus:not(.bx--structured-list-row--header-row){outline:1px solid #3d70b2}\n\n.bx--structured-list-thead{display:table-header-group;vertical-align:middle}\n\n.bx--structured-list-th{padding-left:0;padding-right:2rem;padding-top:1rem;padding-bottom:1rem;font-size:0.75rem;display:table-cell;font-weight:600;height:2.5rem;text-align:left;text-transform:none;vertical-align:bottom}\n\n.bx--structured-list-th:last-child{padding-right:0}\n\n.bx--structured-list-tbody{display:table-row-group;vertical-align:middle}\n\n.bx--structured-list-td{font-size:0.875rem;line-height:1.5;padding-left:0;padding-right:2rem;padding-top:1rem;padding-bottom:1rem;position:relative;display:table-cell}\n\n.bx--structured-list-td:last-child{padding-right:2rem}\n\n.bx--structured-list-th,.bx--structured-list-td{color:#152935}\n\n.bx--structured-list-content--nowrap{white-space:nowrap}\n\n.bx--structured-list-svg{display:inline-block;fill:transparent;vertical-align:middle;transition:250ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--structured-list-row:hover .bx--structured-list-svg{fill:rgba(85,150,230,0.1)}\n\n.bx--structured-list-input:checked+.bx--structured-list-row .bx--structured-list-svg,.bx--structured-list-input:checked+.bx--structured-list-td .bx--structured-list-svg{fill:#5596e6}\n\n.bx--structured-list.bx--skeleton .bx--structured-list-th:first-child{width:8%}\n\n.bx--structured-list.bx--skeleton .bx--structured-list-th:nth-child(3n+2){width:30%}\n\n.bx--structured-list.bx--skeleton .bx--structured-list-th:nth-child(3n+3){width:15%}\n\n.bx--structured-list.bx--skeleton .bx--structured-list-th span{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:75%;height:1rem;display:block}\n\n.bx--structured-list.bx--skeleton .bx--structured-list-th span:hover,.bx--structured-list.bx--skeleton .bx--structured-list-th span:focus,.bx--structured-list.bx--skeleton .bx--structured-list-th span:active{border:none;outline:none;cursor:default}\n\n.bx--structured-list.bx--skeleton .bx--structured-list-th span:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--structured-list.bx--structured-list--border.bx--skeleton .bx--structured-list-th:first-child{width:5%}\n\n.bx--structured-list.bx--structured-list--border.bx--skeleton .bx--structured-list-th:first-child span{display:none}\n\n.bx--structured-list-content{font-size:0.875rem}\n\n.bx--snippet code{font-family:\"ibm-plex-mono\",\"Menlo\",\"DejaVu Sans Mono\",\"Bitstream Vera Sans Mono\",Courier,monospace}\n\n.bx--snippet--inline{position:relative;display:inline;padding:0;background:transparent;font-size:inherit;border:1px solid transparent;border-radius:4px;background-color:#f4f7fb;color:#152935;font-size:85%;cursor:pointer}\n\n.bx--snippet--inline:hover{background-color:#cfdced}\n\n.bx--snippet--inline:focus{outline:1px solid #3d70b2;outline:none;border:1px solid #3d70b2}\n\n.bx--snippet--inline code{padding:.0625rem .5rem}\n\n.bx--snippet--inline.bx--snippet--light{background-color:#fff}\n\n.bx--snippet--inline.bx--snippet--light:hover{background-color:rgba(85,150,230,0.1)}\n\n.bx--snippet--single{font-size:0.75rem;line-height:1.45;background:#fff;border:1px solid #dfe3e6;font-family:\"ibm-plex-mono\",\"Menlo\",\"DejaVu Sans Mono\",\"Bitstream Vera Sans Mono\",Courier,monospace;position:relative;max-width:37.5rem;width:100%;height:3.5rem;padding:0 2.5rem 0 1rem}\n\n.bx--snippet--single .bx--snippet-container{display:flex;align-items:center;height:130%;overflow-x:scroll;position:relative;padding-bottom:1rem}\n\n.bx--snippet--single pre{white-space:nowrap}\n\n.bx--snippet--multi{font-size:0.75rem;line-height:1.45;background:#fff;border:1px solid #dfe3e6;font-family:\"ibm-plex-mono\",\"Menlo\",\"DejaVu Sans Mono\",\"Bitstream Vera Sans Mono\",Courier,monospace;position:relative;max-width:37.5rem;width:100%;padding:1rem 3rem 2rem 1.5rem}\n\n.bx--snippet--multi .bx--snippet-container{overflow:hidden;position:relative;max-height:14.875rem;min-height:3.5rem;transition:all 250ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--snippet--expand.bx--snippet--multi .bx--snippet-container{max-height:93.75rem}\n\n.bx--snippet--multi .bx--snippet-container pre{white-space:pre-wrap}\n\n.bx--snippet__icon{fill:#3d70b2;height:1.5rem;width:1.125rem;transition:all 250ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--snippet__icon:hover{fill:#30588c}\n\n.bx--snippet-button{cursor:pointer;position:absolute;top:0.675rem;right:0.5rem;border:none;background-color:transparent;outline:none;padding:0;height:2rem;width:2rem;overflow:visible}\n\n.bx--snippet-button:focus{outline:1px solid #3d70b2}\n\n.bx--snippet .bx--btn--copy__feedback{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;z-index:8000;font-weight:400;left:inherit;top:0.75rem;right:1.25rem}\n\n.bx--snippet--code.bx--skeleton{height:6.125rem}\n\n.bx--snippet--terminal.bx--skeleton{height:3.5rem}\n\n.bx--snippet.bx--skeleton .bx--snippet-container{height:100%}\n\n.bx--snippet.bx--skeleton code{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:100%;height:1rem;display:block}\n\n.bx--snippet.bx--skeleton code:hover,.bx--snippet.bx--skeleton code:focus,.bx--snippet.bx--skeleton code:active{border:none;outline:none;cursor:default}\n\n.bx--snippet.bx--skeleton code:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--snippet-button .bx--btn--copy__feedback{top:1.5625rem;left:1rem;right:auto}\n\n.bx--snippet--inline .bx--btn--copy__feedback{right:auto;left:50%}\n\n.bx--snippet-btn--expand{position:absolute;right:0;bottom:0}\n\n.bx--snippet-btn--expand--hide .bx--snippet-btn--expand{display:none}\n\n.bx--snippet-btn--expand .bx--icon-chevron--down{fill:#3d70b2;margin-left:.25rem;-webkit-transform:rotate(0deg);transform:rotate(0deg);transition:250ms}\n\n.bx--snippet-btn--expand:hover .bx--icon-chevron--down,.bx--snippet-btn--expand:focus .bx--icon-chevron--down{fill:#fff}\n\n.bx--snippet--expand .bx--snippet-btn--expand .bx--icon-chevron--down{-webkit-transform:rotate(180deg);transform:rotate(180deg)}\n\nbx--snippet--multi.bx--skeleton{height:6.125rem}\n\n.bx--snippet--single.bx--skeleton{height:3.5rem}\n\n.bx--snippet.bx--skeleton .bx--snippet-container{height:100%}\n\n.bx--snippet.bx--skeleton span{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:100%;height:1rem;display:block;margin-top:0.5rem}\n\n.bx--snippet.bx--skeleton span:hover,.bx--snippet.bx--skeleton span:focus,.bx--snippet.bx--skeleton span:active{border:none;outline:none;cursor:default}\n\n.bx--snippet.bx--skeleton span:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--snippet.bx--skeleton span:first-child{margin:0}\n\n.bx--snippet.bx--skeleton span:nth-child(2){width:85%}\n\n.bx--snippet.bx--skeleton span:nth-child(3){width:95%}\n\n.bx--snippet--single.bx--skeleton .bx--snippet-container{padding-bottom:0}\n\n.bx--snippet--terminal{font-size:0.75rem;line-height:1.45;background:#fff;border:1px solid #dfe3e6;font-family:\"ibm-plex-mono\",\"Menlo\",\"DejaVu Sans Mono\",\"Bitstream Vera Sans Mono\",Courier,monospace;position:relative;max-width:37.5rem;width:100%;height:3.5rem;padding:0 2.5rem 0 1rem}\n\n.bx--snippet--terminal .bx--snippet-container{display:flex;align-items:center;height:130%;white-space:nowrap;overflow-x:scroll;position:relative;padding-bottom:1rem}\n\n.bx--snippet--code{font-size:0.75rem;line-height:1.45;background:#fff;border:1px solid #dfe3e6;font-family:\"ibm-plex-mono\",\"Menlo\",\"DejaVu Sans Mono\",\"Bitstream Vera Sans Mono\",Courier,monospace;position:relative;max-width:37.5rem;width:100%;padding:1rem 3rem 1rem 1.5rem}\n\n.bx--snippet--code .bx--snippet-container{overflow:hidden;position:relative;max-height:15.875rem;min-height:3.5rem;transition:all 250ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--snippet--expand.bx--snippet--code .bx--snippet-container{max-height:93.75rem}\n\n.bx--snippet--code .bx--snippet-container pre{white-space:pre-wrap}\n\n.bx--snippet--inline .bx--btn--copy__feedback{right:auto}\n\n.bx--snippet--code.bx--skeleton{height:6.125rem}\n\n.bx--snippet--terminal.bx--skeleton{height:3.5rem}\n\n.bx--snippet.bx--skeleton .bx--snippet-container{height:100%}\n\n.bx--snippet.bx--skeleton code{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:100%;height:1rem;display:block}\n\n.bx--snippet.bx--skeleton code:hover,.bx--snippet.bx--skeleton code:focus,.bx--snippet.bx--skeleton code:active{border:none;outline:none;cursor:default}\n\n.bx--snippet.bx--skeleton code:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--content-switcher{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;display:flex;height:2.5rem}\n\n.bx--content-switcher-btn{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-size:0.875rem;font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;background-color:transparent;display:flex;align-items:center;padding:0 2rem;margin:0;text-decoration:none;border:1px solid #3d70b2;color:#3d70b2}\n\n.bx--content-switcher-btn:focus{outline:1px solid transparent;background-color:#30588c;z-index:2;border-color:#30588c;text-decoration:underline;color:#fff}\n\n.bx--content-switcher-btn:hover{cursor:pointer}\n\n.bx--content-switcher-btn:hover,.bx--content-switcher-btn:active{background-color:#30588c;border-color:#30588c;color:#fff}\n\n.bx--content-switcher__icon{margin-right:.5rem;fill:currentColor}\n\n.bx--content-switcher__icon *{fill:currentColor}\n\n.bx--content-switcher-btn:not(:last-of-type){border-right:none}\n\n.bx--content-switcher-btn:not(:first-of-type){border-left:1px solid #3d70b2}\n\n.bx--content-switcher-btn:not(:first-of-type):hover{border-left-color:#30588c}\n\n.bx--content-switcher-btn:first-of-type{border-bottom-left-radius:8px;border-top-left-radius:8px}\n\n.bx--content-switcher-btn:first-of-type:hover{border-color:#30588c}\n\n.bx--content-switcher-btn:first-of-type:focus{z-index:0}\n\n.bx--content-switcher-btn:last-of-type{border-top-right-radius:8px;border-bottom-right-radius:8px}\n\n.bx--content-switcher-btn:last-of-type:hover{border-color:#30588c}\n\n.bx--content-switcher-btn:last-of-type:focus{z-index:0}\n\n.bx--content-switcher-btn.bx--content-switcher--selected{background-color:#3d70b2;color:#fff;font-weight:400;outline:1px solid transparent}\n\n.bx--content-switcher-btn.bx--content-switcher--selected:hover,.bx--content-switcher-btn.bx--content-switcher--selected:focus{border-color:#30588c;background-color:#30588c}\n\n.flatpickr-calendar{background:transparent;overflow:hidden;max-height:0;opacity:0;visibility:hidden;text-align:center;padding:0;-webkit-animation:none;animation:none;direction:ltr;border:0;font-size:14px;line-height:24px;border-radius:5px;position:absolute;width:315px;box-sizing:border-box;touch-action:manipulation;background:#fff;box-shadow:1px 0 0 #e6e6e6,-1px 0 0 #e6e6e6,0 1px 0 #e6e6e6,0 -1px 0 #e6e6e6,0 3px 13px rgba(0,0,0,0.08)}\n\n.flatpickr-calendar.open,.flatpickr-calendar.inline{opacity:1;visibility:visible;overflow:visible;max-height:640px}\n\n.flatpickr-calendar.open{display:inline-block;z-index:99999}\n\n.flatpickr-calendar.animate.open{-webkit-animation:fpFadeInDown 300ms cubic-bezier(0.23, 1, 0.32, 1);animation:fpFadeInDown 300ms cubic-bezier(0.23, 1, 0.32, 1)}\n\n.flatpickr-calendar.inline{display:block;position:relative;top:2px}\n\n.flatpickr-calendar.static{position:absolute;top:calc(100% + 2px)}\n\n.flatpickr-calendar.static.open{z-index:999;display:block}\n\n.flatpickr-calendar.hasWeeks{width:auto}\n\n.flatpickr-calendar .hasWeeks .dayContainer,.flatpickr-calendar .hasTime .dayContainer{border-bottom:0;border-bottom-right-radius:0;border-bottom-left-radius:0}\n\n.flatpickr-calendar .hasWeeks .dayContainer{border-left:0}\n\n.flatpickr-calendar.showTimeInput.hasTime .flatpickr-time{height:40px;border-top:1px solid #e6e6e6}\n\n.flatpickr-calendar.noCalendar.hasTime .flatpickr-time{height:auto}\n\n.flatpickr-calendar:before,.flatpickr-calendar:after{position:absolute;display:block;pointer-events:none;border:solid transparent;content:'';height:0;width:0;left:22px}\n\n.flatpickr-calendar.rightMost:before,.flatpickr-calendar.rightMost:after{left:auto;right:22px}\n\n.flatpickr-calendar:before{border-width:5px;margin:0 -5px}\n\n.flatpickr-calendar:after{border-width:4px;margin:0 -4px}\n\n.flatpickr-calendar.arrowTop:before,.flatpickr-calendar.arrowTop:after{bottom:100%}\n\n.flatpickr-calendar.arrowTop:before{border-bottom-color:#e6e6e6}\n\n.flatpickr-calendar.arrowTop:after{border-bottom-color:#fff}\n\n.flatpickr-calendar.arrowBottom:before,.flatpickr-calendar.arrowBottom:after{top:100%}\n\n.flatpickr-calendar.arrowBottom:before{border-top-color:#e6e6e6}\n\n.flatpickr-calendar.arrowBottom:after{border-top-color:#fff}\n\n.flatpickr-calendar:focus{outline:0}\n\n.flatpickr-wrapper{position:relative;display:inline-block}\n\n.flatpickr-month{background:transparent;color:rgba(0,0,0,0.9);fill:rgba(0,0,0,0.9);height:28px;line-height:1;text-align:center;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;overflow:hidden}\n\n.flatpickr-prev-month,.flatpickr-next-month{text-decoration:none;cursor:pointer;position:absolute;top:0px;line-height:16px;height:28px;padding:10px calc(3.57% - 1.5px);z-index:3}\n\n.flatpickr-prev-month i,.flatpickr-next-month i{position:relative}\n\n.flatpickr-prev-month.flatpickr-prev-month,.flatpickr-next-month.flatpickr-prev-month{left:0}\n\n.flatpickr-prev-month.flatpickr-next-month,.flatpickr-next-month.flatpickr-next-month{right:0}\n\n.flatpickr-prev-month:hover,.flatpickr-next-month:hover{color:#959ea9}\n\n.flatpickr-prev-month:hover svg,.flatpickr-next-month:hover svg{fill:#f64747}\n\n.flatpickr-prev-month svg,.flatpickr-next-month svg{width:14px}\n\n.flatpickr-prev-month svg path,.flatpickr-next-month svg path{transition:fill 0.1s;fill:inherit}\n\n.numInputWrapper{position:relative;height:auto}\n\n.numInputWrapper input,.numInputWrapper span{display:inline-block}\n\n.numInputWrapper input{width:100%}\n\n.numInputWrapper span{position:absolute;right:0;width:14px;padding:0 4px 0 2px;height:50%;line-height:50%;opacity:0;cursor:pointer;border:1px solid rgba(57,57,57,0.05);box-sizing:border-box}\n\n.numInputWrapper span:hover{background:rgba(0,0,0,0.1)}\n\n.numInputWrapper span:active{background:rgba(0,0,0,0.2)}\n\n.numInputWrapper span:after{display:block;content:'';position:absolute;top:33%}\n\n.numInputWrapper span.arrowUp{top:0;border-bottom:0}\n\n.numInputWrapper span.arrowUp:after{border-left:4px solid transparent;border-right:4px solid transparent;border-bottom:4px solid rgba(57,57,57,0.6)}\n\n.numInputWrapper span.arrowDown{top:50%}\n\n.numInputWrapper span.arrowDown:after{border-left:4px solid transparent;border-right:4px solid transparent;border-top:4px solid rgba(57,57,57,0.6)}\n\n.numInputWrapper span svg{width:inherit;height:auto}\n\n.numInputWrapper span svg path{fill:rgba(0,0,0,0.5)}\n\n.numInputWrapper:hover{background:rgba(0,0,0,0.05)}\n\n.numInputWrapper:hover span{opacity:1}\n\n.flatpickr-current-month{font-size:135%;line-height:inherit;font-weight:300;color:inherit;position:absolute;width:75%;left:12.5%;padding:6.16px 0 0 0;line-height:1;height:28px;display:inline-block;text-align:center;-webkit-transform:translate3d(0px, 0px, 0px);transform:translate3d(0px, 0px, 0px)}\n\n.flatpickr-current-month.slideLeft{-webkit-transform:translate3d(-100%, 0px, 0px);transform:translate3d(-100%, 0px, 0px);-webkit-animation:fpFadeOut 400ms ease,fpSlideLeft 400ms cubic-bezier(0.23, 1, 0.32, 1);animation:fpFadeOut 400ms ease,fpSlideLeft 400ms cubic-bezier(0.23, 1, 0.32, 1)}\n\n.flatpickr-current-month.slideLeftNew{-webkit-transform:translate3d(100%, 0px, 0px);transform:translate3d(100%, 0px, 0px);-webkit-animation:fpFadeIn 400ms ease,fpSlideLeftNew 400ms cubic-bezier(0.23, 1, 0.32, 1);animation:fpFadeIn 400ms ease,fpSlideLeftNew 400ms cubic-bezier(0.23, 1, 0.32, 1)}\n\n.flatpickr-current-month.slideRight{-webkit-transform:translate3d(100%, 0px, 0px);transform:translate3d(100%, 0px, 0px);-webkit-animation:fpFadeOut 400ms ease,fpSlideRight 400ms cubic-bezier(0.23, 1, 0.32, 1);animation:fpFadeOut 400ms ease,fpSlideRight 400ms cubic-bezier(0.23, 1, 0.32, 1)}\n\n.flatpickr-current-month.slideRightNew{-webkit-transform:translate3d(0, 0, 0px);transform:translate3d(0, 0, 0px);-webkit-animation:fpFadeIn 400ms ease,fpSlideRightNew 400ms cubic-bezier(0.23, 1, 0.32, 1);animation:fpFadeIn 400ms ease,fpSlideRightNew 400ms cubic-bezier(0.23, 1, 0.32, 1)}\n\n.flatpickr-current-month span.cur-month{font-family:inherit;font-weight:600;color:inherit;display:inline-block;margin-left:0.5ch;padding:0}\n\n.flatpickr-current-month span.cur-month:hover{background:rgba(0,0,0,0.05)}\n\n.flatpickr-current-month .numInputWrapper{width:6ch;width:7ch\\0;display:inline-block}\n\n.flatpickr-current-month .numInputWrapper span.arrowUp:after{border-bottom-color:rgba(0,0,0,0.9)}\n\n.flatpickr-current-month .numInputWrapper span.arrowDown:after{border-top-color:rgba(0,0,0,0.9)}\n\n.flatpickr-current-month input.cur-year{background:transparent;box-sizing:border-box;color:inherit;cursor:default;padding:0 0 0 0.5ch;margin:0;display:inline-block;font-size:inherit;font-family:inherit;font-weight:300;line-height:inherit;height:auto;border:0;border-radius:0;vertical-align:baseline}\n\n.flatpickr-current-month input.cur-year:focus{outline:0}\n\n.flatpickr-current-month input.cur-year[disabled],.flatpickr-current-month input.cur-year[disabled]:hover{font-size:100%;color:rgba(0,0,0,0.5);background:transparent;pointer-events:none}\n\n.flatpickr-weekdays{background:transparent;text-align:center;overflow:hidden;width:315px;display:flex;align-items:center;height:28px}\n\nspan.flatpickr-weekday{cursor:default;font-size:90%;background:transparent;color:rgba(0,0,0,0.54);line-height:1;margin:0;text-align:center;display:block;flex:1;font-weight:bolder}\n\n.dayContainer,.flatpickr-weeks{padding:1px 0 0 0}\n\n.flatpickr-days{position:relative;overflow:hidden;display:flex;width:315px}\n\n.flatpickr-days:focus{outline:0}\n\n.dayContainer{padding:0;outline:0;text-align:left;width:315px;min-width:315px;max-width:315px;box-sizing:border-box;display:inline-block;display:flex;flex-wrap:wrap;-ms-flex-wrap:wrap;justify-content:space-around;-webkit-transform:translate3d(0px, 0px, 0px);transform:translate3d(0px, 0px, 0px);opacity:1}\n\n.flatpickr-calendar.animate .dayContainer.slideLeft{-webkit-animation:fpFadeOut 400ms cubic-bezier(0.23, 1, 0.32, 1),fpSlideLeft 400ms cubic-bezier(0.23, 1, 0.32, 1);animation:fpFadeOut 400ms cubic-bezier(0.23, 1, 0.32, 1),fpSlideLeft 400ms cubic-bezier(0.23, 1, 0.32, 1)}\n\n.flatpickr-calendar.animate .dayContainer.slideLeft,.flatpickr-calendar.animate .dayContainer.slideLeftNew{-webkit-transform:translate3d(-100%, 0px, 0px);transform:translate3d(-100%, 0px, 0px)}\n\n.flatpickr-calendar.animate .dayContainer.slideLeftNew{-webkit-animation:fpFadeIn 400ms cubic-bezier(0.23, 1, 0.32, 1),fpSlideLeft 400ms cubic-bezier(0.23, 1, 0.32, 1);animation:fpFadeIn 400ms cubic-bezier(0.23, 1, 0.32, 1),fpSlideLeft 400ms cubic-bezier(0.23, 1, 0.32, 1)}\n\n.flatpickr-calendar.animate .dayContainer.slideRight{-webkit-animation:fpFadeOut 400ms cubic-bezier(0.23, 1, 0.32, 1),fpSlideRight 400ms cubic-bezier(0.23, 1, 0.32, 1);animation:fpFadeOut 400ms cubic-bezier(0.23, 1, 0.32, 1),fpSlideRight 400ms cubic-bezier(0.23, 1, 0.32, 1);-webkit-transform:translate3d(100%, 0px, 0px);transform:translate3d(100%, 0px, 0px)}\n\n.flatpickr-calendar.animate .dayContainer.slideRightNew{-webkit-animation:fpFadeIn 400ms cubic-bezier(0.23, 1, 0.32, 1),fpSlideRightNew 400ms cubic-bezier(0.23, 1, 0.32, 1);animation:fpFadeIn 400ms cubic-bezier(0.23, 1, 0.32, 1),fpSlideRightNew 400ms cubic-bezier(0.23, 1, 0.32, 1)}\n\n.flatpickr-day{background:none;border:1px solid transparent;border-radius:150px;box-sizing:border-box;color:#393939;cursor:pointer;font-weight:400;width:14.2857143%;flex-basis:14.2857143%;max-width:40px;height:40px;line-height:40px;margin:0;display:inline-block;position:relative;justify-content:center;text-align:center}\n\n.flatpickr-day.week.selected{border-radius:0;box-shadow:-5px 0 0 #569ff7, 5px 0 0 #569ff7}\n\n.flatpickr-weekwrapper{display:inline-block;float:left}\n\n.flatpickr-weekwrapper .flatpickr-weeks{padding:0 12px;box-shadow:1px 0 0 #e6e6e6}\n\n.flatpickr-weekwrapper .flatpickr-weekday{float:none;width:100%;line-height:28px}\n\n.flatpickr-weekwrapper span.flatpickr-day{display:block;width:100%;max-width:none}\n\n.flatpickr-innerContainer{display:block;display:flex;box-sizing:border-box;overflow:hidden}\n\n.flatpickr-rContainer{display:inline-block;padding:0;box-sizing:border-box}\n\n.flatpickr-time{text-align:center;outline:0;display:block;height:0;line-height:40px;max-height:40px;box-sizing:border-box;overflow:hidden;display:flex}\n\n.flatpickr-time:after{content:'';display:table;clear:both}\n\n.flatpickr-time .numInputWrapper{flex:1;width:40%;height:40px;float:left}\n\n.flatpickr-time .numInputWrapper span.arrowUp:after{border-bottom-color:#393939}\n\n.flatpickr-time .numInputWrapper span.arrowDown:after{border-top-color:#393939}\n\n.flatpickr-time.hasSeconds .numInputWrapper{width:26%}\n\n.flatpickr-time.time24hr .numInputWrapper{width:49%}\n\n.flatpickr-time input{background:transparent;box-shadow:none;border:0;border-radius:0;text-align:center;margin:0;padding:0;height:inherit;line-height:inherit;cursor:pointer;color:#393939;font-size:14px;position:relative;box-sizing:border-box}\n\n.flatpickr-time input.flatpickr-hour{font-weight:bold}\n\n.flatpickr-time input.flatpickr-minute,.flatpickr-time input.flatpickr-second{font-weight:400}\n\n.flatpickr-time input:focus{outline:0;border:0}\n\n.flatpickr-time .flatpickr-time-separator,.flatpickr-time .flatpickr-am-pm{height:inherit;display:inline-block;float:left;line-height:inherit;color:#393939;font-weight:bold;width:2%;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-ms-grid-row-align:center;align-self:center}\n\n.flatpickr-time .flatpickr-am-pm{outline:0;width:18%;cursor:pointer;text-align:center;font-weight:400}\n\n.flatpickr-time .flatpickr-am-pm:hover,.flatpickr-time .flatpickr-am-pm:focus{background:#f0f0f0}\n\n.flatpickr-input[readonly]{cursor:pointer}\n\n@-webkit-keyframes fpFadeInDown{from{opacity:0;-webkit-transform:translate3d(0, -20px, 0);transform:translate3d(0, -20px, 0)}to{opacity:1;-webkit-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0)}}\n\n@keyframes fpFadeInDown{from{opacity:0;-webkit-transform:translate3d(0, -20px, 0);transform:translate3d(0, -20px, 0)}to{opacity:1;-webkit-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0)}}\n\n@-webkit-keyframes fpSlideLeft{from{-webkit-transform:translate3d(0px, 0px, 0px);transform:translate3d(0px, 0px, 0px)}to{-webkit-transform:translate3d(-100%, 0px, 0px);transform:translate3d(-100%, 0px, 0px)}}\n\n@keyframes fpSlideLeft{from{-webkit-transform:translate3d(0px, 0px, 0px);transform:translate3d(0px, 0px, 0px)}to{-webkit-transform:translate3d(-100%, 0px, 0px);transform:translate3d(-100%, 0px, 0px)}}\n\n@-webkit-keyframes fpSlideLeftNew{from{-webkit-transform:translate3d(100%, 0px, 0px);transform:translate3d(100%, 0px, 0px)}to{-webkit-transform:translate3d(0px, 0px, 0px);transform:translate3d(0px, 0px, 0px)}}\n\n@keyframes fpSlideLeftNew{from{-webkit-transform:translate3d(100%, 0px, 0px);transform:translate3d(100%, 0px, 0px)}to{-webkit-transform:translate3d(0px, 0px, 0px);transform:translate3d(0px, 0px, 0px)}}\n\n@-webkit-keyframes fpSlideRight{from{-webkit-transform:translate3d(0, 0, 0px);transform:translate3d(0, 0, 0px)}to{-webkit-transform:translate3d(100%, 0px, 0px);transform:translate3d(100%, 0px, 0px)}}\n\n@keyframes fpSlideRight{from{-webkit-transform:translate3d(0, 0, 0px);transform:translate3d(0, 0, 0px)}to{-webkit-transform:translate3d(100%, 0px, 0px);transform:translate3d(100%, 0px, 0px)}}\n\n@-webkit-keyframes fpSlideRightNew{from{-webkit-transform:translate3d(-100%, 0, 0px);transform:translate3d(-100%, 0, 0px)}to{-webkit-transform:translate3d(0, 0, 0px);transform:translate3d(0, 0, 0px)}}\n\n@keyframes fpSlideRightNew{from{-webkit-transform:translate3d(-100%, 0, 0px);transform:translate3d(-100%, 0, 0px)}to{-webkit-transform:translate3d(0, 0, 0px);transform:translate3d(0, 0, 0px)}}\n\n@-webkit-keyframes fpFadeOut{from{opacity:1}to{opacity:0}}\n\n@keyframes fpFadeOut{from{opacity:1}to{opacity:0}}\n\n@-webkit-keyframes fpFadeIn{from{opacity:0}to{opacity:1}}\n\n@keyframes fpFadeIn{from{opacity:0}to{opacity:1}}\n\n.bx--date-picker{display:flex;align-items:flex-start}\n\n.bx--date-picker--light .bx--date-picker__input{background:#fff}\n\n.bx--date-picker ~ .bx--label{order:1}\n\n.bx--date-picker-container{position:relative;display:flex;flex-direction:column}\n\n.bx--date-picker.bx--date-picker--simple .bx--date-picker__input{width:7.125rem}\n\n.bx--date-picker.bx--date-picker--simple.bx--date-picker--short .bx--date-picker__input{width:5.7rem}\n\n.bx--date-picker.bx--date-picker--single .bx--date-picker__input{width:9rem}\n\n.bx--date-picker__input{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;font-size:0.875rem;display:block;position:relative;height:2.5rem;max-width:9rem;padding:0 1rem;background-color:#f4f7fb;border:none;box-shadow:0 1px 0 0 #5a6872;order:2;color:#152935;border-bottom:1px solid transparent}\n\n.bx--date-picker__input:focus,.bx--date-picker__input.bx--focused{outline:none;box-shadow:0 2px 0 0 #3d70b2}\n\n.bx--date-picker__input:focus ~ .bx--label{color:#3d70b2}\n\n.bx--date-picker__input[data-invalid],.bx--date-picker__input[data-invalid]:focus{box-shadow:0 2px 0 0 #e0182d}\n\n.bx--date-picker__input[data-invalid]:focus+.bx--label{color:#e0182d}\n\n.bx--date-picker__input ~ .bx--form-requirement{order:3;color:#e0182d;font-weight:400;margin-top:.25rem;overflow:visible}\n\n.bx--date-picker__input ~ .bx--form-requirement::before{display:none}\n\n.bx--date-picker__input:disabled{opacity:0.5;cursor:not-allowed}\n\n.bx--date-picker__input:disabled:hover{border:1px solid transparent}\n\n.bx--date-picker__input:-ms-input-placeholder{color:#5a6872}\n\n.bx--date-picker__input::-webkit-input-placeholder{color:#5a6872}\n\n.bx--date-picker__input::-ms-input-placeholder{color:#5a6872}\n\n.bx--date-picker__input::placeholder{color:#5a6872}\n\n.bx--date-picker__icon{position:absolute;top:2.25rem;left:1rem;fill:#3d70b2;cursor:pointer;z-index:1}\n\n.bx--date-picker__icon:hover{fill:#30588c}\n\n.bx--date-picker--nolabel .bx--date-picker__icon{top:.875rem}\n\n.bx--date-picker__icon ~ .bx--date-picker__input{padding-left:3rem}\n\n.bx--date-picker--range{display:flex;position:relative}\n\n.bx--date-picker--range>.bx--date-picker-container:first-child{margin-right:.5rem}\n\n.bx--date-picker--range .bx--date-picker__icon{right:-1.75rem;left:auto}\n\n.bx--date-picker--range .bx--date-picker__input{width:7.075rem}\n\n.bx--date-picker__calendar.flatpickr-calendar.open{box-shadow:0 12px 24px 0 rgba(0,0,0,0.1);background-color:#fff;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:1rem 1rem .25rem;width:17.8125rem !important;height:16.375rem;border-radius:0;border:none;overflow:hidden;margin-top:1px}\n\n.bx--date-picker__calendar.flatpickr-calendar.open:before,.bx--date-picker__calendar.flatpickr-calendar.open:after{display:none}\n\n.bx--date-picker__calendar.flatpickr-calendar.open:focus{outline:1px solid #3d70b2}\n\n.bx--date-picker__month,.flatpickr-month{width:100%;margin-bottom:.25rem}\n\n.bx--date-picker__month .flatpickr-prev-month,.bx--date-picker__month .flatpickr-next-month,.flatpickr-month .flatpickr-prev-month,.flatpickr-month .flatpickr-next-month{padding:0;line-height:1.25rem;fill:#152935}\n\n.bx--date-picker__month .flatpickr-prev-month:hover svg,.bx--date-picker__month .flatpickr-next-month:hover svg,.flatpickr-month .flatpickr-prev-month:hover svg,.flatpickr-month .flatpickr-next-month:hover svg{fill:#3d70b2}\n\n.bx--date-picker__month .flatpickr-current-month,.flatpickr-month .flatpickr-current-month{font-size:0.75rem;text-transform:uppercase;padding:0}\n\n.bx--date-picker__month .flatpickr-current-month svg,.flatpickr-month .flatpickr-current-month svg{fill:#152935}\n\n.bx--date-picker__month .flatpickr-current-month .cur-month,.flatpickr-month .flatpickr-current-month .cur-month{margin-right:0.25rem;color:#152935}\n\n.numInputWrapper,.flatpickr-current-month .numInputWrapper{min-width:2.375rem;width:2.375rem}\n\n.bx--date-picker__month .numInputWrapper .numInput,.flatpickr-month .numInputWrapper .numInput{font-weight:600;color:#152935;background-color:#f4f7fb;border:none;border-radius:0;min-width:2.375rem;width:2.375rem;padding:.25rem}\n\n.bx--date-picker__month .numInputWrapper .numInput:focus,.flatpickr-month .numInputWrapper .numInput:focus{outline:1px solid #3d70b2}\n\n.bx--date-picker__month .numInputWrapper span.arrowUp,.bx--date-picker__month .numInputWrapper span.arrowDown,.flatpickr-month .numInputWrapper span.arrowUp,.flatpickr-month .numInputWrapper span.arrowDown{left:2.6rem;border:none;width:.75rem}\n\n.bx--date-picker__month .numInputWrapper span.arrowUp:hover,.bx--date-picker__month .numInputWrapper span.arrowDown:hover,.flatpickr-month .numInputWrapper span.arrowUp:hover,.flatpickr-month .numInputWrapper span.arrowDown:hover{background:none}\n\n.bx--date-picker__month .numInputWrapper span.arrowUp:hover:after,.bx--date-picker__month .numInputWrapper span.arrowDown:hover:after,.flatpickr-month .numInputWrapper span.arrowUp:hover:after,.flatpickr-month .numInputWrapper span.arrowDown:hover:after{border-bottom-color:#5596e6;border-top-color:#5596e6}\n\n.bx--date-picker__month .numInputWrapper span.arrowUp:after,.bx--date-picker__month .numInputWrapper span.arrowDown:after,.flatpickr-month .numInputWrapper span.arrowUp:after,.flatpickr-month .numInputWrapper span.arrowDown:after{border-bottom-color:#3d70b2;border-top-color:#3d70b2}\n\n.bx--date-picker__month .numInputWrapper span.arrowUp,.flatpickr-month .numInputWrapper span.arrowUp{top:1px}\n\n.bx--date-picker__month .numInputWrapper span.arrowDown,.flatpickr-month .numInputWrapper span.arrowDown{top:9px}\n\nspan.bx--date-picker__weekday,span.flatpickr-weekday{font-size:0.75rem;font-weight:600;color:#152935}\n\n.bx--date-picker__day,.flatpickr-day{font-size:0.75rem;height:1.5625rem;width:1.8rem;line-height:1.5625rem;flex-basis:1.8rem;max-width:1.8rem;margin:.03125rem 0;display:flex;align-items:center;justify-content:center;color:#152935;border-radius:0;border:2px solid transparent}\n\n.bx--date-picker__day:hover,.flatpickr-day:hover{background:rgba(85,150,230,0.1)}\n\n.bx--date-picker__day:focus,.flatpickr-day:focus{outline:none;background:#dfe3e6}\n\n.bx--date-picker__days .nextMonthDay,.bx--date-picker__days .prevMonthDay{opacity:0.5;color:#5a6872}\n\n.bx--date-picker__day.today,.flatpickr-day.today{position:relative}\n\n.bx--date-picker__day.today::after,.flatpickr-day.today::after{content:'';position:absolute;display:block;top:90%;left:50%;-webkit-transform:translateX(-50%);transform:translateX(-50%);height:3px;width:3px;border-radius:50%;background:#3d70b2}\n\n.bx--date-picker__day.today.no-border,.flatpickr-day.today.no-border{border:none}\n\n.bx--date-picker__day.today.selected{border:2px solid #3d70b2}\n\n.bx--date-picker__day.today.selected::after{display:none}\n\n.bx--date-picker__day.disabled,.flatpickr-day.disabled{cursor:not-allowed;opacity:0.5;color:#5a6872}\n\n.bx--date-picker__day.disabled:hover,.flatpickr-day.disabled:hover{background:transparent}\n\n.bx--date-picker__day.inRange,.flatpickr-day.inRange{background:#f4f7fb;box-shadow:-6px 0 0 #f4f7fb,6px 0 0 #f4f7fb}\n\n.bx--date-picker__day.selected,.flatpickr-day.selected{border:2px solid #3d70b2;background:#fff}\n\n.bx--date-picker__day.startRange.selected,.flatpickr-day.startRange.selected{box-shadow:none;z-index:2}\n\n.bx--date-picker__day.endRange.inRange,.flatpickr-day.endRange.inRange{background:#fff;color:#152935;border:2px solid #3d70b2;z-index:3;box-shadow:none}\n\n.bx--date-picker__day.endRange.inRange.selected,.flatpickr-day.endRange.inRange.selected{box-shadow:none;border:2px solid #3d70b2;background:#fff}\n\n.bx--date-picker__day.startRange.inRange:not(.selected),.flatpickr-day.startRange.inRange:not(.selected){box-shadow:none;background:#fff;border:2px solid #3d70b2;z-index:3}\n\n.bx--date-picker__days,.dayContainer{width:14.0625rem;min-width:14.0625rem;max-width:14.0625rem;height:10.25rem}\n\n.flatpickr-innerContainer,.flatpickr-rContainer{width:14.0625rem;height:12.5rem}\n\n.bx--date-picker__weekdays,.flatpickr-weekdays,.flatpickr-weekdaycontainer{width:14.0625rem;margin-bottom:.25rem}\n\n.flatpickr-weekdaycontainer{display:flex}\n\n.flatpickr-months{display:flex;width:100%;position:relative}\n\n.flatpickr-prev-month,.flatpickr-next-month{padding-top:5px}\n\n.flatpickr-prev-month:hover svg,.flatpickr-next-month:hover svg{fill:#3d70b2}\n\n.flatpickr-next-month.disabled svg,.flatpickr-prev-month.disabled svg{fill:#5a6872;opacity:0.5;cursor:not-allowed}\n\n.flatpickr-next-month.disabled:hover svg,.flatpickr-prev-month.disabled:hover svg{fill:#5a6872}\n\n.bx--date-picker.bx--skeleton input,.bx--date-picker__input.bx--skeleton{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:100%}\n\n.bx--date-picker.bx--skeleton input:hover,.bx--date-picker.bx--skeleton input:focus,.bx--date-picker.bx--skeleton input:active,.bx--date-picker__input.bx--skeleton:hover,.bx--date-picker__input.bx--skeleton:focus,.bx--date-picker__input.bx--skeleton:active{border:none;outline:none;cursor:default}\n\n.bx--date-picker.bx--skeleton input:before,.bx--date-picker__input.bx--skeleton:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--date-picker.bx--skeleton input::-webkit-input-placeholder,.bx--date-picker__input.bx--skeleton::-webkit-input-placeholder{color:transparent}\n\n.bx--date-picker.bx--skeleton .bx--label{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:4.6875rem;height:.875rem}\n\n.bx--date-picker.bx--skeleton .bx--label:hover,.bx--date-picker.bx--skeleton .bx--label:focus,.bx--date-picker.bx--skeleton .bx--label:active{border:none;outline:none;cursor:default}\n\n.bx--date-picker.bx--skeleton .bx--label:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--dropdown{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;font-size:0.875rem;position:relative;list-style:none;display:block;background-color:#f4f7fb;border:none;box-shadow:0 1px 0 0 #5a6872;order:1;width:100%;height:2.5rem;cursor:pointer;color:#152935}\n\n.bx--dropdown:focus{outline:none;box-shadow:0 2px 0 0 #3d70b2}\n\n.bx--dropdown.bx--dropdown--open:focus{outline:1px solid transparent;box-shadow:none}\n\n.bx--dropdown .bx--dropdown--open .bx--dropdown-list{box-shadow:0 4px 8px 0 rgba(0,0,0,0.1)}\n\n.bx--dropdown--light{background-color:#fff}\n\n.bx--dropdown--up .bx--dropdown-list{bottom:2.5rem}\n\n.bx--dropdown__arrow{fill:#3d70b2;position:absolute;right:1rem;top:1.175rem;width:.625rem;height:.3125rem;pointer-events:none;transition:-webkit-transform 300ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 300ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 300ms cubic-bezier(0.5, 0, 0.1, 1), -webkit-transform 300ms cubic-bezier(0.5, 0, 0.1, 1);-webkit-transform-origin:50% 45%;transform-origin:50% 45%}\n\n.bx--dropdown[data-value=''] .bx--dropdown-text{color:#152935}\n\n.bx--dropdown-text{height:2.5rem;padding-top:.8125rem;padding-bottom:.8125rem;padding-left:1rem;padding-right:2.5rem;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;border:1px solid transparent}\n\n.bx--dropdown-list{box-shadow:0 4px 8px 0 rgba(0,0,0,0.1);font-size:0.875rem;background-color:#fff;display:flex;flex-direction:column;width:100%;list-style:none;position:absolute;z-index:7000;max-height:0;transition:max-height 300ms cubic-bezier(0, 0, 0.25, 1);overflow:hidden}\n\n.bx--dropdown-item{transition:opacity 300ms cubic-bezier(0, 0, 0.25, 1);opacity:0}\n\n.bx--dropdown-link{display:block;color:currentColor;text-decoration:none;font-weight:normal;padding:1rem 1.5rem 1rem 1rem;text-overflow:ellipsis;overflow:hidden}\n\n.bx--dropdown-link:hover,.bx--dropdown-link:focus{background-color:rgba(85,150,230,0.1);outline:1px solid transparent;text-decoration:underline;color:#152935}\n\n.bx--dropdown--selected{display:none}\n\n.bx--dropdown--open .bx--dropdown__arrow{-webkit-transform:rotate(-180deg);transform:rotate(-180deg)}\n\n.bx--dropdown--open .bx--dropdown-list{max-height:15rem}\n\n.bx--dropdown--open .bx--dropdown-list:hover{overflow:auto}\n\n.bx--dropdown--open .bx--dropdown-item{opacity:1}\n\n.bx--dropdown--disabled{opacity:0.5;cursor:not-allowed}\n\n.bx--dropdown--disabled:focus{outline:none}\n\n.bx--dropdown--auto-width{width:auto;max-width:25rem}\n\n.bx--dropdown--inline{background-color:transparent;box-shadow:none}\n\n.bx--dropdown--inline:focus{outline:none;box-shadow:none}\n\n.bx--dropdown--inline:focus .bx--dropdown-text{outline:1px solid #3d70b2}\n\n.bx--dropdown--inline[data-value=''] .bx--dropdown-text{color:#3d70b2}\n\n.bx--dropdown--inline .bx--dropdown-text{display:inline-block;padding-right:1.5rem;overflow:visible;color:#3d70b2}\n\n.bx--dropdown--inline .bx--dropdown-text:hover{background-color:#f4f7fb}\n\n.bx--dropdown--inline.bx--dropdown--open:focus{box-shadow:none}\n\n.bx--dropdown--inline.bx--dropdown--open:focus .bx--dropdown-list{box-shadow:0 4px 8px 0 rgba(0,0,0,0.1)}\n\n.bx--dropdown--inline.bx--dropdown--open:focus .bx--dropdown-text{outline:none}\n\n.bx--dropdown--inline .bx--dropdown__arrow{position:relative;top:-2px;left:8px;right:0;bottom:0}\n\n.bx--dropdown--inline .bx--dropdown-link{font-weight:normal}\n\n.bx--dropdown--inline .bx--dropdown-link:hover{background-color:#f4f7fb;color:#152935}\n\n.bx--dropdown-v2.bx--skeleton,.bx--dropdown.bx--skeleton{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1)}\n\n.bx--dropdown-v2.bx--skeleton:hover,.bx--dropdown-v2.bx--skeleton:focus,.bx--dropdown-v2.bx--skeleton:active,.bx--dropdown.bx--skeleton:hover,.bx--dropdown.bx--skeleton:focus,.bx--dropdown.bx--skeleton:active{border:none;outline:none;cursor:default}\n\n.bx--dropdown-v2.bx--skeleton:before,.bx--dropdown.bx--skeleton:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n@keyframes rotate{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}\n\n@keyframes rotate-end-p1{100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}\n\n@keyframes rotate-end-p2{100%{-webkit-transform:rotate(-360deg);transform:rotate(-360deg)}}\n\n@keyframes init-stroke{0%{stroke-dashoffset:240}100%{stroke-dashoffset:40}}\n\n@keyframes stroke-end{0%{stroke-dashoffset:40}100%{stroke-dashoffset:240}}\n\n.bx--modal{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;position:fixed;top:0;right:0;bottom:0;left:0;z-index:-1;display:flex;align-items:center;justify-content:center;content:'';opacity:0;background-color:rgba(223,227,230,0.5);transition:opacity 200ms, z-index 0s 200ms, visibility 0s 200ms;visibility:hidden}\n\n.bx--modal.is-visible{z-index:9000;opacity:1;transition:opacity 200ms;visibility:visible}\n\n.bx--modal--danger .bx--modal-container{border-top-color:#e0182d}\n\n.bx--modal-container{box-shadow:0 12px 24px 0 rgba(0,0,0,0.1);position:relative;display:flex;flex-direction:column;background-color:#fff;border-top:#3d70b2 4px solid;min-width:100%;max-height:100%;height:100%;padding:2rem 3% 0rem 3%}\n\n@media (min-width: 600px){.bx--modal-container{height:auto;min-width:500px;max-width:75%;max-height:90%;padding:2.5rem 3rem 0 3rem}}\n\n@media (min-width: 1024px){.bx--modal-container{max-width:50%;max-height:80%}}\n\n.bx--modal-header{margin-bottom:1.5rem}\n\n.bx--modal-header,.bx--modal-footer{flex-shrink:0}\n\n.bx--modal-header__label{font-size:0.75rem;letter-spacing:0;color:#152935;font-weight:600;text-transform:uppercase;margin-bottom:.5rem}\n\n.bx--modal-header__heading{font-size:1.75rem;font-weight:300;color:#5a6872}\n\n.bx--modal-content{overflow-y:auto;margin-bottom:3rem;color:#152935;font-weight:400}\n\n.bx--modal-footer{margin-top:auto;display:flex;justify-content:flex-end;background-color:#f4f7fb;margin-left:-1.5rem;margin-right:-1.5rem;padding:2rem 2rem}\n\n@media (min-width: 600px){.bx--modal-footer{margin-left:-3rem;margin-right:-3rem;padding:2rem 3rem}}\n\n.bx--modal-close{position:absolute;top:1rem;right:1rem;padding:0;overflow:hidden;cursor:pointer;background-color:transparent;border:none;padding:0.25rem 0.25rem 0.125rem}\n\n.bx--modal-close:focus{outline:1px solid #3d70b2}\n\n.bx--modal-close__icon{fill:#5a6872}\n\n.bx--multi-select.bx--combo-box>.bx--list-box__field{padding:0 1rem}\n\n.bx--multi-select.bx--combo-box input[role='combobox']{padding:0;outline:none}\n\n.bx--inline-notification{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-size:0.875rem;display:flex;justify-content:space-between;background-color:transparent;padding:.75rem 1rem;min-height:2.5rem;color:#5a6872;margin-top:1rem;margin-bottom:1rem}\n\n.bx--inline-notification--error{border:1px solid #e0182d;border-left:6px solid #e0182d}\n\n.bx--inline-notification--error .bx--inline-notification__icon{fill:#e0182d}\n\n.bx--inline-notification--success{border:1px solid #5aa700;border-left:6px solid #5aa700}\n\n.bx--inline-notification--success .bx--inline-notification__icon{fill:#5aa700}\n\n.bx--inline-notification--info{border:1px solid #5aaafa;border-left:6px solid #5aaafa}\n\n.bx--inline-notification--info .bx--inline-notification__icon{fill:#5aaafa}\n\n.bx--inline-notification--warning{border:1px solid #efc100;border-left:6px solid #efc100}\n\n.bx--inline-notification--warning .bx--inline-notification__icon{fill:#efc100}\n\n.bx--inline-notification__details{display:flex;align-items:center}\n\n.bx--inline-notification__icon{height:16px;width:16px;min-width:22px}\n\n.bx--inline-notification__text-wrapper{display:flex;flex-wrap:wrap;margin:0 1rem}\n\n@media (max-width: 640px){.bx--inline-notification__text-wrapper{flex-direction:column;width:100%}}\n\n.bx--inline-notification__title{font-size:0.875rem;font-weight:600;margin:0 .25rem 0 0;line-height:1.125}\n\n.bx--inline-notification__subtitle{font-size:0.875rem;line-height:1.125}\n\n.bx--inline-notification__close-button{background-color:transparent;border:none;cursor:pointer;padding:0;height:16px;width:12px;position:relative}\n\n.bx--inline-notification__close-button:focus{outline:1px solid #3d70b2}\n\n.bx--inline-notification__close-icon{height:10px;width:10px;fill:#5a6872;position:absolute;top:3px;right:1px}\n\n.bx--toast-notification{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;box-shadow:0 4px 8px 0 rgba(0,0,0,0.1);display:flex;justify-content:space-between;width:16.875rem;padding:1rem 1rem .5rem 1rem;background-color:#fff;color:#152935;margin-top:.5rem;margin-bottom:.5rem;margin-right:1rem}\n\n.bx--toast-notification:first-child{margin-top:1rem}\n\n.bx--toast-notification--error{border-left:6px solid #e0182d}\n\n.bx--toast-notification--success{border-left:6px solid #5aa700}\n\n.bx--toast-notification--info{border-left:6px solid #5aaafa}\n\n.bx--toast-notification--warning{border-left:6px solid #efc100}\n\n.bx--toast-notification__close-button{background-color:#fff;border:none;cursor:pointer;margin:0;width:12px;height:12px;position:relative}\n\n.bx--toast-notification__close-button:focus{outline:1px solid #3d70b2}\n\n.bx--toast-notification__close-icon,.bx--toast-notification__icon{height:10px;width:10px;fill:#5a6872;position:absolute;top:1px;right:1px}\n\n.bx--toast-notification__title{font-size:0.875rem;letter-spacing:0;font-weight:600;line-height:1;padding-bottom:.125rem}\n\n.bx--toast-notification__subtitle{font-size:0.75rem;color:#5a6872;margin-top:0;margin-bottom:1rem;line-height:1.2}\n\n.bx--toast-notification__caption{font-size:0.75rem;color:#5a6872;line-height:1}\n\n.bx--tooltip--icon{display:flex;align-items:center}\n\n.bx--tooltip__label{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;font-size:1rem;display:inline-flex;align-items:center;color:#152935;font-weight:normal;margin-bottom:.5rem}\n\n.bx--tooltip__label .bx--tooltip__trigger{margin-left:.5rem}\n\n.bx--tooltip__trigger{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;letter-spacing:0;display:inline-block;background:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:0;padding:0;cursor:pointer;display:inline-flex;align-items:center;cursor:pointer;font-size:1rem}\n\n.bx--tooltip__trigger::-moz-focus-inner{border:0}\n\n.bx--tooltip__trigger:focus{outline:1px solid #3d70b2;fill:#30588c}\n\n.bx--tooltip__trigger path,.bx--tooltip__trigger polygon,.bx--tooltip__trigger circle{fill:#3d70b2}\n\n.bx--tooltip__trigger:hover,.bx--tooltip__trigger:focus{color:#152935}\n\n.bx--tooltip__trigger:hover path,.bx--tooltip__trigger:hover polygon,.bx--tooltip__trigger:hover circle,.bx--tooltip__trigger:focus path,.bx--tooltip__trigger:focus polygon,.bx--tooltip__trigger:focus circle{fill:#30588c}\n\n.bx--tooltip__label--bold{font-weight:600}\n\n.bx--tooltip{box-shadow:0 4px 8px 0 rgba(0,0,0,0.1);position:absolute;display:none;max-width:15rem;background:#fff;margin-top:.25rem;padding:1rem;border:1px solid #dfe3e6;border-radius:.25rem;z-index:10000;word-wrap:break-word;color:#152935}\n\n.bx--tooltip p{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;font-size:0.875rem}\n\n.bx--tooltip div{display:flex;justify-content:space-between;align-items:flex-end;margin-top:1rem}\n\n.bx--tooltip .bx--tooltip__caret{position:absolute;background:#fff;left:0;top:-.3125rem;right:0;-webkit-transform:rotate(-135deg);transform:rotate(-135deg);width:0.6rem;height:0.6rem;border-right:1px solid #dfe3e6;border-bottom:1px solid #dfe3e6;margin:0 auto;content:''}\n\n.bx--tooltip[data-floating-menu-direction='left'] .bx--tooltip__caret{left:auto;top:50%;right:-.3125rem;-webkit-transform:rotate(-45deg) translate(50%, -50%);transform:rotate(-45deg) translate(50%, -50%)}\n\n.bx--tooltip[data-floating-menu-direction='top'] .bx--tooltip__caret{top:auto;bottom:-.375rem;-webkit-transform:rotate(45deg);transform:rotate(45deg)}\n\n.bx--tooltip[data-floating-menu-direction='right'] .bx--tooltip__caret{left:-.3125rem;top:50%;right:auto;-webkit-transform:rotate(135deg) translate(-50%, 50%);transform:rotate(135deg) translate(-50%, 50%)}\n\n.bx--tooltip--shown{display:block}\n\n.bx--tooltip--definition{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;font-size:1.125rem;position:relative}\n\n.bx--tooltip--definition .bx--tooltip__trigger{display:inline-flex;position:relative;border-bottom:2px dotted #8897a2}\n\n.bx--tooltip--definition .bx--tooltip__trigger:hover{border-bottom:2px dotted #30588c;cursor:pointer}\n\n.bx--tooltip--definition .bx--tooltip__trigger:hover+.bx--tooltip--definition__top,.bx--tooltip--definition .bx--tooltip__trigger:hover+.bx--tooltip--definition__bottom{display:block}\n\n.bx--tooltip--definition .bx--tooltip__trigger:focus{outline:1px solid #3d70b2}\n\n.bx--tooltip--definition .bx--tooltip__trigger:focus+.bx--tooltip--definition__top,.bx--tooltip--definition .bx--tooltip__trigger:focus+.bx--tooltip--definition__bottom{display:block}\n\n.bx--tooltip--definition__bottom,.bx--tooltip--definition__top{box-shadow:0 4px 8px 0 rgba(0,0,0,0.1);position:absolute;z-index:1;display:none;background:#272d33;max-width:11rem;margin-top:.75rem;padding:.5rem;border-radius:.25rem;pointer-events:none;cursor:pointer}\n\n.bx--tooltip--definition__bottom p,.bx--tooltip--definition__top p{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;font-size:0.75rem;color:#fff}\n\n.bx--tooltip--definition__bottom .bx--tooltip__caret,.bx--tooltip--definition__top .bx--tooltip__caret{position:absolute;right:0;left:0;width:0.6rem;height:0.6rem;background:#272d33;margin-left:1.5rem}\n\n.bx--tooltip--definition__bottom .bx--tooltip__caret{top:-0.2rem;-webkit-transform:rotate(-135deg);transform:rotate(-135deg)}\n\n.bx--tooltip--definition__top{-webkit-transform:translateY(-100%);transform:translateY(-100%);margin-top:-2rem}\n\n.bx--tooltip--definition__top .bx--tooltip__caret{bottom:-0.2rem;-webkit-transform:rotate(45deg);transform:rotate(45deg)}\n\n.bx--tooltip--icon__top,.bx--tooltip--icon__bottom{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;position:relative;display:inline-flex;align-items:center;cursor:pointer;overflow:visible}\n\n.bx--tooltip--icon__top path,.bx--tooltip--icon__bottom path{fill:#3d70b2}\n\n.bx--tooltip--icon__top:before,.bx--tooltip--icon__top:after,.bx--tooltip--icon__bottom:before,.bx--tooltip--icon__bottom:after{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;position:absolute;display:none;background-color:#272d33}\n\n.bx--tooltip--icon__top:before,.bx--tooltip--icon__bottom:before{right:0;left:0;width:0.6rem;height:0.6rem;margin:0 auto;content:'';margin-top:1px;margin-left:50%}\n\n.bx--tooltip--icon__top:after,.bx--tooltip--icon__bottom:after{font-size:0.75rem;box-shadow:0 4px 8px 0 rgba(0,0,0,0.1);max-width:11rem;margin-left:50%;padding:.25rem;border-radius:4px;color:#fff;font-weight:400;content:attr(aria-label);-webkit-transform:translateX(-50%);transform:translateX(-50%);white-space:nowrap;pointer-events:none;margin-left:50%}\n\n.bx--tooltip--icon__top:hover path,.bx--tooltip--icon__top:focus path,.bx--tooltip--icon__bottom:hover path,.bx--tooltip--icon__bottom:focus path{fill:#30588c}\n\n.bx--tooltip--icon__top:hover:before,.bx--tooltip--icon__top:hover:after,.bx--tooltip--icon__top:focus:before,.bx--tooltip--icon__top:focus:after,.bx--tooltip--icon__bottom:hover:before,.bx--tooltip--icon__bottom:hover:after,.bx--tooltip--icon__bottom:focus:before,.bx--tooltip--icon__bottom:focus:after{position:absolute;display:block}\n\n.bx--tooltip--icon__top:focus,.bx--tooltip--icon__bottom:focus{outline:1px solid transparent}\n\n.bx--tooltip--icon__top:focus svg,.bx--tooltip--icon__bottom:focus svg{outline:1px solid #3d70b2}\n\n.bx--tooltip--icon__top:before{top:0;-webkit-transform:translate(-50%, calc(-100% - 10px)) rotate(45deg);transform:translate(-50%, calc(-100% - 10px)) rotate(45deg)}\n\n.bx--tooltip--icon__top:after{top:0;-webkit-transform:translate(-50%, calc(-100% - 10px));transform:translate(-50%, calc(-100% - 10px))}\n\n.bx--tooltip--icon__bottom:before{bottom:0;-webkit-transform:translate(-50%, calc(100% + 10px)) rotate(135deg);transform:translate(-50%, calc(100% + 10px)) rotate(135deg)}\n\n.bx--tooltip--icon__bottom:after{bottom:0;-webkit-transform:translate(-50%, calc(100% + 10px));transform:translate(-50%, calc(100% + 10px))}\n\n.bx--tooltip--icon .bx--tooltip__trigger svg{margin-left:0}\n\n.bx--tabs{font-size:0.875rem;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;color:#152935;font-weight:600;height:auto;width:100%;position:relative}\n\n@media screen and (min-width: 768px){.bx--tabs{background:none;min-height:3.0625rem}}\n\n.bx--tabs-trigger{display:flex;align-items:center;justify-content:space-between;padding:0 1rem;height:2.5rem;cursor:pointer;background-color:#f4f7fb;box-shadow:0 1px 0 0 #5a6872}\n\n.bx--tabs-trigger svg{width:.625rem;height:.3125rem;fill:#3d70b2}\n\n.bx--tabs-trigger:focus{outline:none;box-shadow:0 2px 0 0 #3d70b2}\n\n@media screen and (min-width: 768px){.bx--tabs-trigger{display:none}}\n\n.bx--tabs--light.bx--tabs-trigger{background-color:#fff}\n\n.bx--tabs-trigger-text{text-decoration:none;font-weight:600;color:#152935}\n\n.bx--tabs-trigger-text:focus{outline:1px solid #3d70b2}\n\n.bx--tabs__nav{box-shadow:0 4px 8px 0 rgba(0,0,0,0.1);margin:0;padding:0;position:absolute;width:100%;list-style:none;display:flex;flex-direction:column;z-index:7000;background:#fff}\n\n@media screen and (min-width: 768px){.bx--tabs__nav{font-size:1rem;flex-direction:row;margin-right:1rem;margin-left:1rem;background:none;box-shadow:none;z-index:auto}}\n\n@media screen and (min-width: 1200px){.bx--tabs__nav{margin-left:0}}\n\n.bx--tabs__nav--hidden{display:none}\n\n@media screen and (min-width: 768px){.bx--tabs__nav--hidden{display:flex}}\n\n.bx--tabs__nav-item{font-size:0.875rem;background-color:#fff;padding:0;cursor:pointer}\n\n.bx--tabs__nav-item:hover,.bx--tabs__nav-item:focus{background-color:rgba(85,150,230,0.1)}\n\n@media screen and (min-width: 768px){.bx--tabs__nav-item:hover,.bx--tabs__nav-item:focus{outline:1px solid transparent;background:transparent}}\n\n@media screen and (min-width: 768px){.bx--tabs__nav-item{background:transparent;padding:.75rem 0 .75rem}.bx--tabs__nav-item+.bx--tabs__nav-item{margin-left:3rem}}\n\n.bx--tabs__nav-item--selected{border:none}\n\n@media screen and (min-width: 768px){.bx--tabs__nav-item--selected{border-bottom:2px solid #3d70b2}.bx--tabs__nav-item--selected .bx--tabs__nav-link{color:#3d70b2}.bx--tabs__nav-item--selected .bx--tabs__nav-link:focus{color:#3d70b2}}\n\n.bx--tabs__nav-item:hover .bx--tabs__nav-link{color:#152935}\n\n@media screen and (min-width: 768px){.bx--tabs__nav-item:hover .bx--tabs__nav-link{color:#3d70b2}}\n\n.bx--tabs__nav-link{display:inline-block;color:#152935;text-decoration:none;padding:1rem;width:100%;white-space:nowrap;text-overflow:ellipsis}\n\n.bx--tabs__nav-link:focus,.bx--tabs__nav-link:active{outline:1px solid transparent;background-color:#3d70b2;color:#fff}\n\n@media screen and (min-width: 768px){.bx--tabs__nav-link{padding:0 .125rem;width:auto}.bx--tabs__nav-link:hover{color:#3d70b2}.bx--tabs__nav-link:focus,.bx--tabs__nav-link:active{background-color:transparent;color:#152935;outline:1px solid transparent;box-shadow:0 0 0 1px #3d70b2}}\n\n.bx--tabs.bx--skeleton{pointer-events:none;cursor:default}\n\n.bx--tabs.bx--skeleton .bx--tabs__nav-link{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:4.6875rem;height:.75rem}\n\n.bx--tabs.bx--skeleton .bx--tabs__nav-link:hover,.bx--tabs.bx--skeleton .bx--tabs__nav-link:focus,.bx--tabs.bx--skeleton .bx--tabs__nav-link:active{border:none;outline:none;cursor:default}\n\n.bx--tabs.bx--skeleton .bx--tabs__nav-link:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--tabs.bx--skeleton .bx--tabs-trigger{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:6.25rem}\n\n.bx--tabs.bx--skeleton .bx--tabs-trigger:hover,.bx--tabs.bx--skeleton .bx--tabs-trigger:focus,.bx--tabs.bx--skeleton .bx--tabs-trigger:active{border:none;outline:none;cursor:default}\n\n.bx--tabs.bx--skeleton .bx--tabs-trigger:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--tabs.bx--skeleton .bx--tabs-trigger svg{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);border:0;visibility:visible;white-space:nowrap}\n\n.bx--tag{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;font-size:0.75rem;display:inline-flex;align-items:center;padding:0 .5rem;height:1.25rem;margin:.125rem;border-radius:.9375rem}\n\n.bx--tag:not(:first-child){margin-left:0}\n\n.bx--tag--ibm{background-color:#c0e6ff;color:#325c80}\n\n.bx--tag--beta{background-color:#dfe3e6;color:#394b54}\n\n.bx--tag--third-party{background-color:#a7fae6;color:#006d5d}\n\n.bx--tag--local,.bx--tag--dedicated,.bx--tag--custom{background-color:#eed2ff;color:#734098}\n\n.bx--tag--experimental{background-color:#ffd4a0;color:#a53725}\n\n.bx--tag--community{background-color:#c8f08f;color:#2d660a}\n\n.bx--tag--private{background-color:#fde876;color:#735f00}\n\n.bx--tag.bx--skeleton{background-color:#dfe3e6;color:#394b54;width:3.75rem}\n\n.bx--tag.bx--skeleton:after{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);content:'';height:.375rem;width:100%}\n\n.bx--tag.bx--skeleton:after:hover,.bx--tag.bx--skeleton:after:focus,.bx--tag.bx--skeleton:after:active{border:none;outline:none;cursor:default}\n\n.bx--tag.bx--skeleton:after:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--left-nav__trigger{width:3.75rem;height:3.125rem;position:relative;transition:250ms cubic-bezier(0.5, 0, 0.1, 1);cursor:pointer;z-index:9999}\n\n.bx--left-nav__trigger:focus{outline:0}\n\n.bx--left-nav__trigger:hover,.bx--left-nav__trigger:focus{background-color:#5aaafa}\n\n.bx--left-nav__trigger:hover span,.bx--left-nav__trigger:hover span:before,.bx--left-nav__trigger:hover span:after,.bx--left-nav__trigger:focus span,.bx--left-nav__trigger:focus span:before,.bx--left-nav__trigger:focus span:after{background:#fff}\n\n.bx--left-nav__trigger--btn{position:absolute;top:1.5rem;left:1.25rem;width:100%;transition:250ms cubic-bezier(0.5, 0, 0.1, 1);display:flex}\n\n.bx--left-nav__trigger--btn span,.bx--left-nav__trigger--btn span:before,.bx--left-nav__trigger--btn span:after{height:.125rem;width:1.25rem;cursor:pointer;position:absolute;display:block;content:'';transition:all 250ms ease}\n\n.bx--left-nav__trigger--btn span:before{top:-.375rem}\n\n.bx--left-nav__trigger--btn span:after{bottom:-.375rem}\n\n.bx--left-nav__trigger--active .bx--left-nav__trigger--btn{left:1.125rem}\n\n.bx--left-nav__trigger--active .bx--left-nav__trigger--btn span:before,.bx--left-nav__trigger--active .bx--left-nav__trigger--btn span:after{top:0;width:1.59125rem}\n\n.bx--left-nav__trigger--active .bx--left-nav__trigger--btn span:before{-webkit-transform:rotate(45deg);transform:rotate(45deg)}\n\n.bx--left-nav__trigger--active .bx--left-nav__trigger--btn span:after{-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}\n\n.bx--left-nav__trigger--apps span,.bx--left-nav__trigger--apps span:before,.bx--left-nav__trigger--apps span:after{background:#00b4a0}\n\n.bx--left-nav__trigger--apps:focus{outline:0}\n\n.bx--left-nav__trigger--apps:hover,.bx--left-nav__trigger--apps:focus{background-color:#008571}\n\n.bx--left-nav__trigger--apps:hover span,.bx--left-nav__trigger--apps:hover span:before,.bx--left-nav__trigger--apps:hover span:after,.bx--left-nav__trigger--apps:focus span,.bx--left-nav__trigger--apps:focus span:before,.bx--left-nav__trigger--apps:focus span:after{background:#fff}\n\n.bx--left-nav__trigger--apps.bx--left-nav__trigger--active span{background:transparent}\n\n.bx--left-nav__trigger--apps.bx--left-nav__trigger--active span:before,.bx--left-nav__trigger--apps.bx--left-nav__trigger--active span:after{background:#008571}\n\n.bx--left-nav__trigger--apps.bx--left-nav__trigger--active:hover,.bx--left-nav__trigger--apps.bx--left-nav__trigger--active:focus{background-color:#008571}\n\n.bx--left-nav__trigger--apps.bx--left-nav__trigger--active:hover span:before,.bx--left-nav__trigger--apps.bx--left-nav__trigger--active:hover span:after,.bx--left-nav__trigger--apps.bx--left-nav__trigger--active:focus span:before,.bx--left-nav__trigger--apps.bx--left-nav__trigger--active:focus span:after{background:#fff}\n\n.bx--left-nav__trigger--services span,.bx--left-nav__trigger--services span:before,.bx--left-nav__trigger--services span:after{background:#ba8ff7}\n\n.bx--left-nav__trigger--services:focus{outline:0}\n\n.bx--left-nav__trigger--services:hover,.bx--left-nav__trigger--services:focus{background-color:#734098}\n\n.bx--left-nav__trigger--services:hover span,.bx--left-nav__trigger--services:hover span:before,.bx--left-nav__trigger--services:hover span:after,.bx--left-nav__trigger--services:focus span,.bx--left-nav__trigger--services:focus span:before,.bx--left-nav__trigger--services:focus span:after{background:#fff}\n\n.bx--left-nav__trigger--services.bx--left-nav__trigger--active span{background:transparent}\n\n.bx--left-nav__trigger--services.bx--left-nav__trigger--active span:before,.bx--left-nav__trigger--services.bx--left-nav__trigger--active span:after{background:#734098}\n\n.bx--left-nav__trigger--services.bx--left-nav__trigger--active:hover,.bx--left-nav__trigger--services.bx--left-nav__trigger--active:focus{background-color:#734098}\n\n.bx--left-nav__trigger--services.bx--left-nav__trigger--active:hover span:before,.bx--left-nav__trigger--services.bx--left-nav__trigger--active:hover span:after,.bx--left-nav__trigger--services.bx--left-nav__trigger--active:focus span:before,.bx--left-nav__trigger--services.bx--left-nav__trigger--active:focus span:after{background:#fff}\n\n.bx--left-nav__trigger--infrastructure span,.bx--left-nav__trigger--infrastructure span:before,.bx--left-nav__trigger--infrastructure span:after{background:#5aaafa}\n\n.bx--left-nav__trigger--infrastructure:focus{outline:0}\n\n.bx--left-nav__trigger--infrastructure:hover,.bx--left-nav__trigger--infrastructure:focus{background-color:#3d70b2}\n\n.bx--left-nav__trigger--infrastructure:hover span,.bx--left-nav__trigger--infrastructure:hover span:before,.bx--left-nav__trigger--infrastructure:hover span:after,.bx--left-nav__trigger--infrastructure:focus span,.bx--left-nav__trigger--infrastructure:focus span:before,.bx--left-nav__trigger--infrastructure:focus span:after{background:#fff}\n\n.bx--left-nav__trigger--infrastructure.bx--left-nav__trigger--active span{background:transparent}\n\n.bx--left-nav__trigger--infrastructure.bx--left-nav__trigger--active span:before,.bx--left-nav__trigger--infrastructure.bx--left-nav__trigger--active span:after{background:#3d70b2}\n\n.bx--left-nav__trigger--infrastructure.bx--left-nav__trigger--active:hover,.bx--left-nav__trigger--infrastructure.bx--left-nav__trigger--active:focus{background-color:#3d70b2}\n\n.bx--left-nav__trigger--infrastructure.bx--left-nav__trigger--active:hover span:before,.bx--left-nav__trigger--infrastructure.bx--left-nav__trigger--active:hover span:after,.bx--left-nav__trigger--infrastructure.bx--left-nav__trigger--active:focus span:before,.bx--left-nav__trigger--infrastructure.bx--left-nav__trigger--active:focus span:after{background:#fff}\n\n.bx--global-header{box-shadow:0 6px 12px 0 rgba(0,0,0,0.1);font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;width:100%;position:fixed;top:2.25rem;left:0;display:flex;justify-content:space-between;height:3.125rem;line-height:1.5;background-color:#152935;z-index:9000}\n\n.bx--global-header__title{display:flex;align-items:center}\n\n.bx--global-header__title--logo{display:flex;align-items:center;padding:0 .5rem;text-decoration:none;color:#fff;position:relative}\n\n.bx--global-header__title--logo:hover .bx--logo__text,.bx--global-header__title--logo:focus .bx--logo__text{color:#7cc7ff}\n\n.bx--global-header__title--current-page{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;display:flex;align-items:center;font-weight:400;font-size:1.125rem;line-height:inherit;color:#5aaafa}\n\n.bx--unified-header--apps .bx--global-header__title--current-page{color:#00b4a0}\n\n.bx--unified-header--infrastructure .bx--global-header__title--current-page{color:#5aaafa}\n\n.bx--unified-header--services .bx--global-header__title--current-page{color:#ba8ff7}\n\n.bx--global-header .bx--logo__image{cursor:pointer;position:relative;margin-right:1.125rem}\n\n.bx--global-header .bx--logo__text{font-size:1.125rem;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-weight:400;cursor:pointer;text-decoration:none;color:#fff}\n\n.bx--global-header .bx--logo__text--bold{font-weight:600}\n\n.bx--global-header__left-container{display:flex;align-items:center}\n\n.bx--global-header__right-container{display:flex;align-items:center;padding-right:1%;background-color:#152935}\n\n.bx--global-header__menu{list-style:none;width:100%;display:flex;justify-content:flex-end}\n\n.bx--global-header__menu__item{width:100%;flex:0 1 100px}\n\n.bx--global-header__menu__item:focus{outline:0;background-color:#2d3f49;color:#5aaafa}\n\n.bx--global-header__menu__item:last-child .bx--dropdown-list{right:0}\n\n.bx--global-header__menu__item--link{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-size:0.875rem;font-weight:600;display:flex;justify-content:center;align-items:center;height:3.125rem;text-decoration:none;background-color:#152935;color:#fff;padding:0 1rem}\n\n.bx--global-header__menu__item--link:hover{color:#5aaafa}\n\n.bx--global-header__menu__item--link:focus{outline:0;background-color:#2d3f49;color:#5aaafa}\n\n.bx--global-header__menu__item .bx--dropdown{height:3.125rem;background-color:transparent}\n\n.bx--global-header__menu__item .bx--dropdown:focus{outline:0;background-color:#2d3f49}\n\n.bx--global-header__menu__item .bx--dropdown:focus .bx--dropdown__menu-text{color:#5aaafa}\n\n.bx--global-header__menu__item .bx--dropdown:focus .bx--dropdown__menu-text,.bx--global-header__menu__item .bx--dropdown:focus .bx--dropdown__list{outline:0}\n\n.bx--global-header__menu .bx--dropdown-text{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;display:flex;justify-content:center;padding-top:0;padding-right:1rem;padding-bottom:0;align-items:center;height:100%;z-index:1000;color:#fff}\n\n.bx--global-header__menu .bx--dropdown-text:hover{color:#5aaafa}\n\n.bx--global-header__menu .bx--dropdown-list{transition:250ms all cubic-bezier(0.5, 0, 0.1, 1);-webkit-transform:translateY(-150%);transform:translateY(-150%);opacity:0;visibility:hidden;display:flex;flex-direction:column;position:absolute;top:100%;width:auto;z-index:-1;padding-bottom:0.5rem}\n\n.bx--global-header__menu .bx--dropdown-item{min-width:200px;width:100%}\n\n.bx--global-header__menu .bx--dropdown-link{padding:0.5rem 0.75rem;color:#fff}\n\n.bx--global-header__menu .bx--dropdown-link:hover{color:#152935;background-color:#5aaafa}\n\n.bx--global-header__menu .bx--dropdown--open .bx--dropdown-text{background-color:#2d3f49;color:#5aaafa}\n\n.bx--global-header__menu .bx--dropdown--open .bx--dropdown-list{-webkit-transform:translateY(0);transform:translateY(0);opacity:1;visibility:visible;background-color:#2d3f49}\n\n.bx--top-nav{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;display:flex;justify-content:space-between;background-color:#0f212e;width:100%;height:2.25rem;padding:0 1rem;position:fixed;top:0;left:0;z-index:9500}\n\n.bx--top-nav__left-container,.bx--top-nav__right-container{list-style:none;display:flex;align-items:center;min-width:50%}\n\n.bx--top-nav__left-container .bx--dropdown,.bx--top-nav__right-container .bx--dropdown{font-size:0.75rem;list-style:none;background-color:#0f212e;color:#fff;height:100%;display:flex;align-items:center}\n\n.bx--top-nav__left-container .bx--dropdown__arrow,.bx--top-nav__right-container .bx--dropdown__arrow{fill:#fff;right:0.75rem;width:.75rem;height:1.5rem}\n\n.bx--top-nav__left-container .bx--dropdown-text,.bx--top-nav__right-container .bx--dropdown-text{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;max-width:12.5rem;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;font-weight:600}\n\n.bx--top-nav__left-container .bx--dropdown-list,.bx--top-nav__right-container .bx--dropdown-list{width:auto;position:absolute;top:100%;left:0;background-color:#2d3f49;transition:250ms all cubic-bezier(0.5, 0, 0.1, 1);display:flex;flex-direction:column;opacity:0;visibility:hidden;-webkit-transform:translateY(-50%);transform:translateY(-50%);z-index:-1}\n\n.bx--top-nav__left-container .bx--dropdown-item,.bx--top-nav__right-container .bx--dropdown-item{min-width:10.625rem;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}\n\n.bx--top-nav__left-container .bx--dropdown-item:hover,.bx--top-nav__right-container .bx--dropdown-item:hover{background-color:#5aaafa;color:#152935}\n\n.bx--top-nav__left-container .bx--dropdown-link,.bx--top-nav__right-container .bx--dropdown-link{color:#fff}\n\n.bx--top-nav__left-container .bx--dropdown--open,.bx--top-nav__right-container .bx--dropdown--open{background-color:#2d3f49}\n\n.bx--top-nav__left-container .bx--dropdown--open .bx--dropdown-text,.bx--top-nav__right-container .bx--dropdown--open .bx--dropdown-text{color:#5aaafa}\n\n.bx--top-nav__left-container .bx--dropdown--open .bx--dropdown__arrow,.bx--top-nav__right-container .bx--dropdown--open .bx--dropdown__arrow{fill:#5aaafa}\n\n.bx--top-nav__left-container .bx--dropdown--open .bx--dropdown-list,.bx--top-nav__right-container .bx--dropdown--open .bx--dropdown-list{-webkit-transform:translateY(0);transform:translateY(0);opacity:1;visibility:visible;background-color:#2d3f49}\n\n.bx--top-nav__left-container__link{font-size:0.6875rem;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;display:flex;justify-content:flex-start;background-color:#0f212e;align-items:flex-start;text-decoration:none;color:#fff;font-weight:600;margin-right:1rem}\n\n.bx--top-nav__left-container__link:hover,.bx--top-nav__left-container__link:focus{color:#5aaafa}\n\n.bx--top-nav__left-container__link:hover .bx--top-nav__left-container__link--icon,.bx--top-nav__left-container__link:focus .bx--top-nav__left-container__link--icon{fill:#5aaafa}\n\n.bx--top-nav__left-container__link--icon{width:0.675rem;height:0.7rem;fill:#fff;margin-right:0.3rem}\n\n.bx--top-nav__left-container__item:focus{outline:0}\n\n.bx--top-nav__left-container .bx--dropdown:focus,.bx--top-nav__left-container .bx--dropdown:hover{outline:0}\n\n.bx--top-nav__left-container .bx--dropdown:focus .bx--dropdown__arrow use,.bx--top-nav__left-container .bx--dropdown:hover .bx--dropdown__arrow use{fill:#5aaafa}\n\n.bx--top-nav__left-container .bx--dropdown:focus .bx--dropdown-text,.bx--top-nav__left-container .bx--dropdown:hover .bx--dropdown-text{background-color:#2d3f49;color:#5aaafa}\n\n.bx--top-nav__left-container .bx--dropdown-list{padding-bottom:0.5rem}\n\n.bx--top-nav__left-container .bx--dropdown__arrow{top:0.3rem;left:0.75rem;opacity:0;-webkit-transform:rotate(0);transform:rotate(0);-webkit-animation:250ms cubic-bezier(0.64, 0.57, 0.67, 1.53) 650ms 1 normal forwards fade;animation:250ms cubic-bezier(0.64, 0.57, 0.67, 1.53) 650ms 1 normal forwards fade}\n\n.bx--top-nav__left-container .bx--dropdown-text{-webkit-animation:250ms cubic-bezier(0.6, 0.22, 0.38, 2.03) 1 normal forwards pop-in;animation:250ms cubic-bezier(0.6, 0.22, 0.38, 2.03) 1 normal forwards pop-in;opacity:0;-webkit-transform:scale(0.5);transform:scale(0.5);padding:0.725rem 1rem 0.725rem 2rem}\n\n.bx--top-nav__left-container .bx--dropdown-link{padding:0.6rem 0.75rem}\n\n.bx--top-nav__left-container .bx--dropdown-link:hover,.bx--top-nav__left-container .bx--dropdown-link:focus{background-color:#5aaafa;color:#152935}\n\n.bx--top-nav__right-container{justify-content:flex-end}\n\n.bx--top-nav__right-container__item[data-trial] .bx--dropdown-text,.bx--top-nav__right-container__item[data-credit] .bx--dropdown-text{padding:0.75rem 2rem 0.75rem 1rem;color:#fff}\n\n.bx--top-nav__right-container__item[data-trial] .bx--dropdown-list,.bx--top-nav__right-container__item[data-credit] .bx--dropdown-list{left:initial;outline:0;right:0;min-width:20.3125rem;-webkit-transform:translateY(-10%);transform:translateY(-10%)}\n\n.bx--top-nav__right-container__item[data-trial] .bx--dropdown__arrow,.bx--top-nav__right-container__item[data-credit] .bx--dropdown__arrow{top:0.5rem}\n\n.bx--top-nav__right-container__item[data-trial] .bx--dropdown--open .bx--dropdown-list,.bx--top-nav__right-container__item[data-credit] .bx--dropdown--open .bx--dropdown-list{-webkit-transform:translateY(0);transform:translateY(0)}\n\n.bx--top-nav__right-container__item[data-trial] .bx--dropdown--open .bx--dropdown-text,.bx--top-nav__right-container__item[data-credit] .bx--dropdown--open .bx--dropdown-text{color:#5aaafa}\n\n.bx--top-nav__right-container__item[data-trial] .bx--dropdown:hover,.bx--top-nav__right-container__item[data-trial] .bx--dropdown:focus,.bx--top-nav__right-container__item[data-credit] .bx--dropdown:hover,.bx--top-nav__right-container__item[data-credit] .bx--dropdown:focus{outline:0;background-color:#2d3f49}\n\n.bx--top-nav__right-container__item[data-trial] .bx--dropdown:hover .bx--dropdown-text,.bx--top-nav__right-container__item[data-trial] .bx--dropdown:focus .bx--dropdown-text,.bx--top-nav__right-container__item[data-credit] .bx--dropdown:hover .bx--dropdown-text,.bx--top-nav__right-container__item[data-credit] .bx--dropdown:focus .bx--dropdown-text{color:#5aaafa}\n\n.bx--top-nav__right-container__item[data-trial] .bx--dropdown:hover .bx--dropdown__arrow use,.bx--top-nav__right-container__item[data-trial] .bx--dropdown:focus .bx--dropdown__arrow use,.bx--top-nav__right-container__item[data-credit] .bx--dropdown:hover .bx--dropdown__arrow use,.bx--top-nav__right-container__item[data-credit] .bx--dropdown:focus .bx--dropdown__arrow use{fill:#5aaafa}\n\n.bx--top-nav__right-container__item[data-trial] .bx--dropdown__trial-content,.bx--top-nav__right-container__item[data-trial] .bx--dropdown__credit-content,.bx--top-nav__right-container__item[data-credit] .bx--dropdown__trial-content,.bx--top-nav__right-container__item[data-credit] .bx--dropdown__credit-content{cursor:auto;display:flex;flex-direction:column;padding:1rem}\n\n.bx--top-nav__right-container__item[data-trial] .bx--dropdown__trial-content:focus,.bx--top-nav__right-container__item[data-trial] .bx--dropdown__trial-content:hover,.bx--top-nav__right-container__item[data-trial] .bx--dropdown__credit-content:focus,.bx--top-nav__right-container__item[data-trial] .bx--dropdown__credit-content:hover,.bx--top-nav__right-container__item[data-credit] .bx--dropdown__trial-content:focus,.bx--top-nav__right-container__item[data-credit] .bx--dropdown__trial-content:hover,.bx--top-nav__right-container__item[data-credit] .bx--dropdown__credit-content:focus,.bx--top-nav__right-container__item[data-credit] .bx--dropdown__credit-content:hover{outline:0;background-color:initial;color:#fff}\n\n.bx--top-nav__right-container__item[data-trial] .bx--dropdown__trial-content--desc,.bx--top-nav__right-container__item[data-trial] .bx--dropdown__credit-content--desc,.bx--top-nav__right-container__item[data-credit] .bx--dropdown__trial-content--desc,.bx--top-nav__right-container__item[data-credit] .bx--dropdown__credit-content--desc{margin-bottom:1rem}\n\n.bx--top-nav__right-container__item[data-trial] .bx--dropdown__trial-content .bx--link,.bx--top-nav__right-container__item[data-trial] .bx--dropdown__credit-content .bx--link,.bx--top-nav__right-container__item[data-credit] .bx--dropdown__trial-content .bx--link,.bx--top-nav__right-container__item[data-credit] .bx--dropdown__credit-content .bx--link{font-size:0.6875rem;color:#5aaafa;margin-top:1rem;text-align:center}\n\n.bx--top-nav__right-container__item[data-trial] .bx--dropdown__trial-content--desc,.bx--top-nav__right-container__item[data-credit] .bx--dropdown__trial-content--desc{font-size:0.75rem}\n\n.bx--top-nav__right-container__item[data-trial] .bx--dropdown__credit-content div .bx--dropdown__credit-content--heading,.bx--top-nav__right-container__item[data-credit] .bx--dropdown__credit-content div .bx--dropdown__credit-content--heading{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-size:0.75rem;font-weight:600}\n\n.bx--top-nav__right-container__item[data-trial] .bx--dropdown__credit-content div .bx--dropdown__credit-content--desc,.bx--top-nav__right-container__item[data-credit] .bx--dropdown__credit-content div .bx--dropdown__credit-content--desc{font-size:0.875rem}\n\n.bx--top-nav__right-container__item[data-trial] .bx--dropdown__credit-content div:last-child .bx--dropdown__credit-content--desc,.bx--top-nav__right-container__item[data-credit] .bx--dropdown__credit-content div:last-child .bx--dropdown__credit-content--desc{margin-bottom:0}\n\n.bx--top-nav__right-container__item:last-child .bx--dropdown:focus,.bx--top-nav__right-container__item:last-child .bx--dropdown:hover{background-color:#2d3f49;outline:0}\n\n.bx--top-nav__right-container__item:last-child .bx--dropdown__arrow{-webkit-transform-origin:50% 40%;transform-origin:50% 40%}\n\n.bx--top-nav__right-container__item:last-child .bx--dropdown__arrow use{fill:#5aaafa}\n\n.bx--top-nav__right-container__item:last-child .bx--dropdown-text--profile-image{height:2.25rem;width:2.25rem;min-height:2.25rem;min-width:2.25rem;display:flex;align-items:center;justify-content:center;margin:0rem 1rem}\n\n.bx--top-nav__right-container__item:last-child .bx--dropdown-text--profile-image .profile-image{display:flex;align-items:center;border-radius:50%;overflow:hidden}\n\n.bx--top-nav__right-container__item:last-child .bx--dropdown-text--profile-image .profile-image svg,.bx--top-nav__right-container__item:last-child .bx--dropdown-text--profile-image .profile-image img{fill:#fff;max-height:1.5rem;max-width:1.5rem}\n\n.bx--top-nav__right-container__item:last-child .bx--dropdown-list{right:0;left:inherit;padding:1rem;min-width:225px}\n\n.bx--top-nav__right-container__item:last-child .bx--dropdown-item{display:flex;justify-content:space-between}\n\n.bx--top-nav__right-container__item:last-child .bx--dropdown-item svg{min-height:3rem;min-width:3rem}\n\n.bx--top-nav__right-container__item:last-child .bx--dropdown-item:hover{background-color:inherit;color:inherit}\n\n.bx--top-nav__right-container__item[data-credit] .bx--dropdown-list{min-width:0;width:100%}\n\n.bx--dropdown__profile-dropdown--picture{max-width:3rem;max-height:3rem;border-radius:50%;width:100%;fill:#fff}\n\n.bx--dropdown__profile-dropdown--information{margin-left:1rem}\n\n.bx--dropdown__profile-dropdown--information p{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-size:0.875rem;font-weight:600}\n\n.bx--dropdown__profile-dropdown__container{display:flex;justify-content:flex-start;align-items:center}\n\n.bx--dropdown__profile-dropdown__container a{font-size:0.75rem;color:#5aaafa}\n\n.bx--dropdown__profile-dropdown__container a:hover{color:#7cc7ff}\n\n.bx--dropdown__profile-dropdown__container p{padding:0 0.5rem}\n\n@-webkit-keyframes pop-in{100%{opacity:1;-webkit-transform:scale(1);transform:scale(1)}}\n\n@keyframes pop-in{100%{opacity:1;-webkit-transform:scale(1);transform:scale(1)}}\n\n@-webkit-keyframes fade{100%{opacity:1}}\n\n@keyframes fade{100%{opacity:1}}\n\n.bx--top-nav__left-container--item:nth-child(1) .bx--dropdown-text{-webkit-animation-delay:200ms;animation-delay:200ms}\n\n.bx--top-nav__left-container--item:nth-child(2) .bx--dropdown-text{-webkit-animation-delay:300ms;animation-delay:300ms}\n\n.bx--top-nav__left-container--item:nth-child(3) .bx--dropdown-text{-webkit-animation-delay:400ms;animation-delay:400ms}\n\n.bx--global-header__left-nav{box-shadow:0 8px 16px 0 rgba(0,0,0,0.1);position:fixed;z-index:9000;width:15.625rem;top:2.25rem;left:0;height:100%;-webkit-transform:translate3d(-100%, 0, 0);transform:translate3d(-100%, 0, 0);transition:300ms cubic-bezier(0.5, 0, 0.1, 1);box-shadow:none;visibility:hidden}\n\n.bx--global-header__left-nav.bx--left-nav--active{-webkit-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0);box-shadow:0px 1px 15px 2px rgba(0,0,0,0.1);visibility:visible}\n\n.bx--left-nav{display:block;width:100%;height:100%;background-color:#fff;padding:0 0 4rem 0;overflow-y:auto;overflow-x:hidden}\n\n.bx--left-nav__close-row{height:3.125rem;width:100%;background-color:#fff}\n\n.bx--left-nav__header{align-items:center;height:3.125rem;cursor:pointer;position:relative;display:flex;background-color:#0f212e;justify-content:space-between;top:0;left:0;width:100%;padding:1.125rem 1.25rem}\n\n.bx--left-nav__header[data-left-nav-current-section='apps']{background-color:#008571}\n\n.bx--left-nav__header[data-left-nav-current-section='infrastructure']{background-color:#3d70b2}\n\n.bx--left-nav__header[data-left-nav-current-section='services']{background-color:#734098}\n\n.bx--left-nav__header--title{font-size:1rem;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;color:#fff;font-weight:600;margin-right:auto}\n\n.bx--left-nav__header--taxonomy-icon{width:1.5rem;height:1.5rem;fill:#fff;margin-right:1rem}\n\n.bx--left-nav__header--close-icon{width:.875rem;height:.875rem;display:block;fill:#fff}\n\n.bx--left-nav__sections{list-style:none;padding:0 0 1rem;width:100%;z-index:8000;position:relative;border-bottom:1px solid #8897a2;background-color:#fff}\n\n.bx--left-nav__section{display:flex;align-items:center;cursor:pointer;transition:250ms cubic-bezier(0.5, 0, 0.1, 1);background-color:#fff}\n\n.bx--left-nav__section:hover[data-left-nav-section='apps']{background-color:#008571}\n\n.bx--left-nav__section:hover[data-left-nav-section='services']{background-color:#734098}\n\n.bx--left-nav__section:hover[data-left-nav-section='infrastructure']{background-color:#4178be}\n\n.bx--left-nav__section:hover .bx--left-nav__section--link{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-weight:600;color:#fff}\n\n.bx--left-nav__section:hover .bx--left-nav__section--taxonomy-icon{fill:#fff}\n\n.bx--left-nav__section--active,.bx--left-nav__section--transition{justify-content:flex-start;align-items:center;cursor:pointer;position:relative;display:flex;background-color:#fff;top:0;left:0;width:100%;padding:0.8rem 0}\n\n.bx--left-nav__section--active[data-left-nav-section='apps'],[data-left-nav-section='apps'].bx--left-nav__section--transition{background-color:#008571}\n\n.bx--left-nav__section--active[data-left-nav-section='infrastructure'],[data-left-nav-section='infrastructure'].bx--left-nav__section--transition{background-color:#3d70b2}\n\n.bx--left-nav__section--active[data-left-nav-section='services'],[data-left-nav-section='services'].bx--left-nav__section--transition{background-color:#734098}\n\n.bx--left-nav__section--transition{position:absolute;z-index:9999;transition:all 0.3s cubic-bezier(0, 0, 0.25, 1)}\n\n.bx--left-nav__section--transition--50{-webkit-transform:translateY(100px);transform:translateY(100px)}\n\n.bx--left-nav__section--transition--100{-webkit-transform:translateY(150px);transform:translateY(150px)}\n\n.bx--left-nav__section--transition--0{-webkit-transform:translateY(50px);transform:translateY(50px)}\n\n.bx--left-nav__section--transition .bx--left-nav__section--taxonomy-icon{fill:#fff}\n\n.bx--left-nav__section--taxonomy-icon{width:1.5rem;height:1.5rem;fill:#152935;margin-right:1rem}\n\n.bx--left-nav__section--anchor{display:flex;width:100%;padding:0 1.25rem;align-items:center;text-decoration:none}\n\n.bx--left-nav__section--link{font-size:1rem;display:flex;align-items:center;color:#152935;height:3.125rem}\n\n.bx--left-nav__main-nav{list-style:none;display:flex;flex-direction:column;margin-bottom:5rem;margin-top:0;transition:all 250ms cubic-bezier(0, 0, 0.25, 1);padding-top:1rem;background-color:#fff}\n\n.bx--left-nav__main-nav--hidden{display:none}\n\n.bx--left-nav__main-nav--top{margin-top:-100vh}\n\n.bx--main-nav__parent-item{opacity:1;transition:opacity 200ms cubic-bezier(0.5, 0, 0.1, 1);cursor:pointer;width:100%;padding:0;margin-bottom:0.25rem;background-color:#fff}\n\n.bx--main-nav__parent-item--fade{opacity:0}\n\n.bx--main-nav__parent-item--hidden{display:none}\n\n.bx--main-nav__parent-item--expanded .bx--parent-item__link--down-icon svg{-webkit-transform:rotate(180deg);transform:rotate(180deg)}\n\n.bx--parent-item__link{font-size:0.875rem;font-weight:400;display:flex;align-items:center;justify-content:flex-start;text-decoration:none;padding:0.5rem 1.25rem;transition:background-color 250ms cubic-bezier(0.5, 0, 0.1, 1);color:#152935}\n\n.bx--parent-item__link .bx--parent-item__link--taxonomy-icon{width:1.5rem;height:1.5rem;transition:250ms cubic-bezier(0.5, 0, 0.1, 1);margin-right:1rem;fill:#152935}\n\n.bx--parent-item__link .bx--parent-item__link--down-icon{display:flex;margin-left:auto}\n\n.bx--parent-item__link .bx--parent-item__link--down-icon svg{width:.625rem;height:.625rem;transition:250ms cubic-bezier(0.5, 0, 0.1, 1);fill:#152935}\n\n.bx--left-nav__main-nav[data-left-nav-list='apps'] .bx--parent-item__link:hover{color:#008571}\n\n.bx--left-nav__main-nav[data-left-nav-list='apps'] .bx--parent-item__link:hover .bx--parent-item__link--taxonomy-icon,.bx--left-nav__main-nav[data-left-nav-list='apps'] .bx--parent-item__link:hover .bx--parent-item__link--down-icon svg{fill:#008571}\n\n.bx--left-nav__main-nav[data-left-nav-list='services'] .bx--parent-item__link:hover{color:#734098}\n\n.bx--left-nav__main-nav[data-left-nav-list='services'] .bx--parent-item__link:hover .bx--parent-item__link--taxonomy-icon,.bx--left-nav__main-nav[data-left-nav-list='services'] .bx--parent-item__link:hover .bx--parent-item__link--down-icon svg{fill:#734098}\n\n.bx--left-nav__main-nav[data-left-nav-list='infrastructure'] .bx--parent-item__link:hover{color:#3d70b2}\n\n.bx--left-nav__main-nav[data-left-nav-list='infrastructure'] .bx--parent-item__link:hover .bx--parent-item__link--taxonomy-icon,.bx--left-nav__main-nav[data-left-nav-list='infrastructure'] .bx--parent-item__link:hover .bx--parent-item__link--down-icon svg{fill:#3d70b2}\n\n.bx--main-nav__parent-item.bx--active-list-item .bx--parent-item__link{color:#fff}\n\n.bx--left-nav__main-nav[data-left-nav-list='apps'] .bx--main-nav__parent-item.bx--active-list-item .bx--parent-item__link{background-color:#008571}\n\n.bx--left-nav__main-nav[data-left-nav-list='apps'] .bx--main-nav__parent-item.bx--active-list-item .bx--parent-item__link:hover{color:#fff}\n\n.bx--left-nav__main-nav[data-left-nav-list='apps'] .bx--main-nav__parent-item.bx--active-list-item .bx--parent-item__link:hover .bx--parent-item__link--taxonomy-icon,.bx--left-nav__main-nav[data-left-nav-list='apps'] .bx--main-nav__parent-item.bx--active-list-item .bx--parent-item__link:hover .bx--parent-item__link--down-icon svg{fill:#fff}\n\n.bx--left-nav__main-nav[data-left-nav-list='services'] .bx--main-nav__parent-item.bx--active-list-item .bx--parent-item__link{background-color:#734098}\n\n.bx--left-nav__main-nav[data-left-nav-list='services'] .bx--main-nav__parent-item.bx--active-list-item .bx--parent-item__link:hover{color:#fff}\n\n.bx--left-nav__main-nav[data-left-nav-list='services'] .bx--main-nav__parent-item.bx--active-list-item .bx--parent-item__link:hover .bx--parent-item__link--taxonomy-icon,.bx--left-nav__main-nav[data-left-nav-list='services'] .bx--main-nav__parent-item.bx--active-list-item .bx--parent-item__link:hover .bx--parent-item__link--down-icon svg{fill:#fff}\n\n.bx--left-nav__main-nav[data-left-nav-list='infrastructure'] .bx--main-nav__parent-item.bx--active-list-item .bx--parent-item__link{background-color:#3d70b2}\n\n.bx--left-nav__main-nav[data-left-nav-list='infrastructure'] .bx--main-nav__parent-item.bx--active-list-item .bx--parent-item__link:hover{color:#fff}\n\n.bx--left-nav__main-nav[data-left-nav-list='infrastructure'] .bx--main-nav__parent-item.bx--active-list-item .bx--parent-item__link:hover .bx--parent-item__link--taxonomy-icon,.bx--left-nav__main-nav[data-left-nav-list='infrastructure'] .bx--main-nav__parent-item.bx--active-list-item .bx--parent-item__link:hover .bx--parent-item__link--down-icon svg{fill:#fff}\n\n.bx--main-nav__parent-item.bx--active-list-item .bx--parent-item__link--taxonomy-icon{fill:#fff}\n\n.bx--main-nav__parent-item.bx--active-list-item .bx--parent-item__link--down-icon svg{fill:#fff}\n\n.bx--main-nav__parent-item.bx--active-list-item:hover{color:#fff}\n\n.bx--main-nav__nested-list{display:flex;flex-direction:column;margin-top:0;list-style:none;max-height:0;transition:300ms cubic-bezier(0.5, 0, 0.1, 1);padding:0;opacity:0;overflow:hidden;margin-bottom:0}\n\n.bx--main-nav__parent-item--expanded .bx--main-nav__nested-list{max-height:20rem;transition:300ms cubic-bezier(0.5, 0, 0.1, 1);opacity:1;margin-top:0.5rem;overflow:visible}\n\n.bx--main-nav__parent-item--expanded .bx--main-nav__nested-list .bx--nested-list__item{opacity:1}\n\n.bx--nested-list__item{width:100%;position:static;margin-bottom:0.25rem;padding:0;transition:250ms;opacity:0}\n\n.bx--nested-list__item--link{font-size:0.875rem;color:#152935;padding:0.5rem 1.35rem 0.5rem 2rem;font-weight:400;display:flex;align-items:center;justify-content:space-between;text-decoration:none;position:relative;margin-right:auto}\n\n.bx--left-nav__main-nav[data-left-nav-list='apps'] .bx--nested-list__item--link:hover{color:#008571}\n\n.bx--left-nav__main-nav[data-left-nav-list='apps'] .bx--nested-list__item--link:hover .bx--left-nav-list__item-link--taxonomy-icon{fill:#008571}\n\n.bx--left-nav__main-nav[data-left-nav-list='services'] .bx--nested-list__item--link:hover{color:#734098}\n\n.bx--left-nav__main-nav[data-left-nav-list='services'] .bx--nested-list__item--link:hover .bx--left-nav-list__item-link--taxonomy-icon{fill:#734098}\n\n.bx--left-nav__main-nav[data-left-nav-list='infrastructure'] .bx--nested-list__item--link:hover{color:#3d70b2}\n\n.bx--left-nav__main-nav[data-left-nav-list='infrastructure'] .bx--nested-list__item--link:hover .bx--left-nav-list__item-link--taxonomy-icon{fill:#3d70b2}\n\n.bx--nested-list__item--icon svg{width:.625rem;height:.625rem;fill:#152935}\n\n.bx--left-nav__main-nav[data-left-nav-list='apps'] .bx--nested-list__item.bx--active-list-item .bx--nested-list__item--link{background-color:#008571}\n\n.bx--left-nav__main-nav[data-left-nav-list='apps'] .bx--nested-list__item.bx--active-list-item .bx--nested-list__item--link:hover{color:#fff}\n\n.bx--left-nav__main-nav[data-left-nav-list='apps'] .bx--nested-list__item.bx--active-list-item .bx--nested-list__item--link:hover .bx--parent-item__link--taxonomy-icon{fill:#fff}\n\n.bx--left-nav__main-nav[data-left-nav-list='services'] .bx--nested-list__item.bx--active-list-item .bx--nested-list__item--link{background-color:#734098}\n\n.bx--left-nav__main-nav[data-left-nav-list='services'] .bx--nested-list__item.bx--active-list-item .bx--nested-list__item--link:hover{color:#fff}\n\n.bx--left-nav__main-nav[data-left-nav-list='services'] .bx--nested-list__item.bx--active-list-item .bx--nested-list__item--link:hover .bx--parent-item__link--taxonomy-icon{fill:#fff}\n\n.bx--left-nav__main-nav[data-left-nav-list='infrastructure'] .bx--nested-list__item.bx--active-list-item .bx--nested-list__item--link{background-color:#3d70b2}\n\n.bx--left-nav__main-nav[data-left-nav-list='infrastructure'] .bx--nested-list__item.bx--active-list-item .bx--nested-list__item--link:hover{color:#fff}\n\n.bx--left-nav__main-nav[data-left-nav-list='infrastructure'] .bx--nested-list__item.bx--active-list-item .bx--nested-list__item--link:hover .bx--parent-item__link--taxonomy-icon{fill:#fff}\n\n.bx--nested-list__item.bx--active-list-item .bx--nested-list__item--icon svg{fill:#152935}\n\n.bx--nested-list__flyout-menu{box-shadow:0 4px 8px 0 rgba(0,0,0,0.1);display:none;min-width:auto;white-space:nowrap;outline:none;position:absolute;z-index:9999;color:#fff}\n\n.bx--nested-list__flyout-menu:before{content:'';display:block;position:absolute;width:120%;height:120%;top:-3rem;left:0;padding:2rem;z-index:-1}\n\n.bx--nested-list__flyout-menu--displayed{display:block;border-left:1px solid #8897a2}\n\n.bx--flyout-menu__item--link{font-size:0.875rem;padding:0 1.75rem 0 1rem;color:#152935;text-decoration:none}\n\n.bx--flyout-menu__item{background-color:#fff;margin:0;height:2.3125rem;display:flex;align-items:center}\n\n.bx--left-nav__main-nav[data-left-nav-list='apps'] .bx--flyout-menu__item:hover .bx--flyout-menu__item--link{color:#008571}\n\n.bx--left-nav__main-nav[data-left-nav-list='services'] .bx--flyout-menu__item:hover .bx--flyout-menu__item--link{color:#734098}\n\n.bx--left-nav__main-nav[data-left-nav-list='infrastructure'] .bx--flyout-menu__item:hover .bx--flyout-menu__item--link{color:#3d70b2}\n\n.bx--left-nav__main-nav[data-left-nav-list='apps'] .bx--flyout-menu__item.bx--active-list-item{background-color:#008571}\n\n.bx--left-nav__main-nav[data-left-nav-list='apps'] .bx--flyout-menu__item.bx--active-list-item .bx--flyout-menu__item--link{color:#fff}\n\n.bx--left-nav__main-nav[data-left-nav-list='apps'] .bx--flyout-menu__item.bx--active-list-item .bx--flyout-menu__item--link:hover{color:#fff}\n\n.bx--left-nav__main-nav[data-left-nav-list='services'] .bx--flyout-menu__item.bx--active-list-item{background-color:#734098}\n\n.bx--left-nav__main-nav[data-left-nav-list='services'] .bx--flyout-menu__item.bx--active-list-item .bx--flyout-menu__item--link{color:#fff}\n\n.bx--left-nav__main-nav[data-left-nav-list='services'] .bx--flyout-menu__item.bx--active-list-item .bx--flyout-menu__item--link:hover{color:#fff}\n\n.bx--left-nav__main-nav[data-left-nav-list='infrastructure'] .bx--flyout-menu__item.bx--active-list-item{background-color:#3d70b2}\n\n.bx--left-nav__main-nav[data-left-nav-list='infrastructure'] .bx--flyout-menu__item.bx--active-list-item .bx--flyout-menu__item--link{color:#fff}\n\n.bx--left-nav__main-nav[data-left-nav-list='infrastructure'] .bx--flyout-menu__item.bx--active-list-item .bx--flyout-menu__item--link:hover{color:#fff}\n\n.bx--account-switcher{list-style:none;position:relative;height:100%;display:flex;align-items:center;justify-content:flex-end;min-width:21.875rem}\n\n.bx--account-switcher__linked-icon{fill:#fff;height:1rem;width:1rem;margin:0 0.5rem;-webkit-transform:rotate(45deg);transform:rotate(45deg)}\n\n.bx--account-switcher__toggle{z-index:9000;height:2.25rem;width:auto;display:inline-flex;align-items:center;justify-content:center;color:#fff;padding:0 1rem;background-color:#0f212e;cursor:pointer}\n\n.bx--account-switcher__toggle:focus,.bx--account-switcher__toggle:hover{outline:0;background-color:#2d3f49}\n\n.bx--account-switcher__toggle:focus .bx--account-switcher__toggle--text,.bx--account-switcher__toggle:hover .bx--account-switcher__toggle--text{color:#5aaafa}\n\n.bx--account-switcher__toggle:focus svg,.bx--account-switcher__toggle:hover svg{fill:#5aaafa}\n\n.bx--account-switcher__toggle--hidden{opacity:0;visibility:hidden}\n\n.bx--account-switcher__toggle--text{font-size:0.6875rem;letter-spacing:0;overflow:hidden;display:inline-flex;white-space:nowrap;padding-right:0.5rem;font-weight:300}\n\n.bx--account-switcher__toggle--text[data-switcher-account-sl],.bx--account-switcher__toggle--text[data-switcher-account]{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-weight:600}\n\n.bx--account-switcher__toggle--text[data-switcher-account]{display:inline-flex;align-items:center}\n\n.bx--account-switcher__toggle--text[data-switcher-account] .bx--account-switcher__linked-icon{margin-right:0}\n\n.bx--account-switcher__toggle--text>[data-dropdown-account-linked]{margin-left:0.5rem;margin-right:0}\n\n.bx--account-switcher__toggle--text:last-child{padding-right:0}\n\n.bx--account-switcher__menu{list-style:none}\n\n.bx--account-switcher__menu__container{box-shadow:6px 6px 6px 0 rgba(0,0,0,0.1);transition:250ms all cubic-bezier(0.5, 0, 0.1, 1);position:absolute;width:auto;min-width:21.875rem;height:auto;background-color:#2d3f49;visibility:hidden;opacity:0;top:100%;right:0;-webkit-transform:translateY(-10%);transform:translateY(-10%);color:#fff;z-index:8000}\n\n.bx--account-switcher--open{color:#5aaafa}\n\n.bx--account-switcher--open .bx--account-switcher__toggle{color:#5aaafa;background-color:#2d3f49}\n\n.bx--account-switcher--open .bx--account-switcher__linked-icon{fill:#5aaafa}\n\n.bx--account-switcher--open .bx--account-switcher__menu__container{visibility:visible;max-height:125rem;opacity:1;-webkit-transform:translateY(0);transform:translateY(0)}\n\n.bx--account-switcher__menu__item{height:auto;display:flex;justify-content:space-between;align-items:flex-start;padding:1rem}\n\n.bx--account-switcher__menu__item:first-child{border-bottom:1px solid #42535c}\n\n.bx--account-switcher__menu__item:nth-child(n+2){padding:1rem 1rem 0}\n\n.bx--account-switcher__menu__item:last-child{display:flex;margin-left:auto;justify-content:flex-start;max-width:75%;padding:0.75rem 0 1rem 1.5rem}\n\n.bx--account-switcher__menu__item:last-child a{font-size:0.6875rem;padding-right:1rem;color:#5aaafa}\n\n.bx--account-switcher__menu__item:last-child a:visited{color:#5aaafa}\n\n.bx--account-switcher__menu__item:last-child a:hover{color:#5596e6}\n\n.bx--account-switcher__menu__item--title{font-size:0.875rem;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-weight:600;height:44px;min-width:100px;display:flex;align-items:center;flex:1}\n\n.bx--account-switcher__menu__item .bx--dropdown{font-size:0.875rem;flex:3;background-color:#42535c;display:block;flex-direction:column;min-width:200px}\n\n.bx--account-switcher__menu__item .bx--dropdown[data-value=''] .bx--dropdown-text{color:#fff}\n\n.bx--account-switcher__menu__item .bx--dropdown--scroll{max-height:180px;overflow-y:auto}\n\n.bx--account-switcher__menu__item .bx--dropdown--scroll::-webkit-scrollbar{background:#394b54;width:0.5rem;height:0.5rem}\n\n.bx--account-switcher__menu__item .bx--dropdown--scroll::-webkit-scrollbar-thumb{background-color:#8c9ba5;border-radius:10px}\n\n.bx--account-switcher__menu__item .bx--dropdown--scroll::-webkit-scrollbar-thumb:hover{background-color:#dfe6eb}\n\n.bx--account-switcher__menu__item .bx--dropdown li{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-weight:400;max-width:400px}\n\n.bx--account-switcher__menu__item .bx--dropdown__arrow{fill:#5aaafa}\n\n.bx--account-switcher__menu__item .bx--dropdown-text{padding-right:2rem;align-self:flex-start;background-color:#42535c}\n\n.bx--account-switcher__menu__item .bx--dropdown-text .bx--account-switcher__linked-icon{fill:#fff;vertical-align:middle}\n\n.bx--account-switcher__menu__item .bx--dropdown-list{position:relative;-webkit-transform:translateY(-10px);transform:translateY(-10px);max-height:0;height:auto;width:100%;top:0}\n\n.bx--account-switcher__menu__item .bx--dropdown-item{background-color:#2d3f49}\n\n.bx--account-switcher__menu__item .bx--dropdown-item>.bx--dropdown-link:hover,.bx--account-switcher__menu__item .bx--dropdown-item .bx--dropdown-link:focus{background-color:#5aaafa;color:#152935}\n\n.bx--account-switcher__menu__item .bx--dropdown-item>.bx--dropdown-link:hover svg,.bx--account-switcher__menu__item .bx--dropdown-item .bx--dropdown-link:focus svg{fill:#152935}\n\n.bx--account-switcher__menu__item .bx--dropdown-link{height:100%;text-overflow:ellipsis;overflow:hidden}\n\n.bx--account-switcher__menu__item .bx--dropdown-link span{pointer-events:none}\n\n.bx--account-switcher__menu__item .bx--dropdown-link svg{fill:#fff;pointer-events:none;vertical-align:middle}\n\n.bx--account-switcher__menu__item .bx--dropdown--open .bx--dropdown-text{color:#fff}\n\n.bx--account-switcher__menu__item .bx--dropdown--open .bx--dropdown-list{display:flex;flex-direction:column;max-height:2000px;z-index:10}\n\n.bx--account-switcher__menu__item .bx--dropdown--open .bx--dropdown-item{background-color:#394b54}\n\n.bx--unified-header{position:fixed;z-index:6000}\n\n.bx--data-table-v2-container+.bx--pagination{border-top:0}\n\n.bx--pagination{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;width:100%;background-color:#fff;padding:.5rem 1rem;display:flex;align-items:center;border:1px solid #dfe3e6;height:2.5rem}\n\n.bx--pagination .bx--form-item{flex:auto}\n\n.bx--pagination__left{display:flex;align-items:center}\n\n.bx--pagination__right{display:flex;align-items:center;margin-left:auto}\n\n.bx--pagination__text{font-size:0.75rem;color:#5a6872;display:none;padding-right:.25rem}\n\n@media (min-width: 530px){.bx--pagination__text{display:block}}\n\n.bx--pagination__button-icon{height:.75rem;width:.75rem;fill:#5a6872;pointer-events:none;transition:250ms;margin-top:.125rem}\n\n.bx--pagination__button{border:none;background:none;cursor:pointer}\n\n.bx--pagination__button:hover .bx--pagination__button-icon{fill:#3d70b2}\n\n.bx--pagination__button:focus{outline:1px solid #3d70b2}\n\n.bx--pagination__button:disabled:hover{cursor:default}\n\n.bx--pagination__button:disabled:hover .bx--pagination__button-icon{fill:#5a6872}\n\n.bx--pagination__button--backward{margin-left:1rem;margin-right:1.5rem}\n\n.bx--pagination__button--forward{margin-left:1.5rem}\n\n.bx--pagination__button--no-index{border-right:0;margin-right:1px}\n\n.bx--pagination .bx--select{margin-right:.5rem}\n\n.bx--pagination .bx--select--inline{margin-right:0;width:auto;display:flex;flex-direction:row;align-items:center}\n\n.bx--pagination .bx--select-input{height:1.5rem;width:auto;padding:0 1.25rem 0 0;margin:0;font-weight:600;text-align-last:center;box-shadow:none}\n\n.bx--pagination .bx--select-input:focus{outline:1px solid #3d70b2}\n\n.bx--pagination .bx--select .bx--select-input ~ .bx--select__arrow{right:0.3rem;top:0.625rem}\n\n.bx--pagination .bx--text-input{background-color:#f4f7fb;height:1.5rem;min-width:1.5rem;width:1.5rem;padding:0;margin:0;font-weight:600;text-align:center;box-shadow:none;order:0}\n\n.bx--pagination .bx--text-input:focus{outline:1px solid #3d70b2}\n\n.bx--pagination--inline{height:42px;margin-top:-0.5rem;margin-bottom:-0.5rem;margin-right:-1rem}\n\n.bx--pagination--inline .bx--pagination__button{height:2.5rem;border-left:1px solid #dfe3e6;border-right:1px solid #dfe3e6;margin:0}\n\n.bx--pagination--inline .bx--pagination__button--forward{border-right:0;padding:0 1rem;margin-left:1rem}\n\n.bx--pagination--inline .bx--pagination__button--backward{margin:0 1rem;padding:0 1rem}\n\n.bx--pagination--inline .bx--select__arrow{right:0;top:0.6rem}\n\n.bx--pagination.bx--skeleton .bx--skeleton__text{margin-right:1rem;margin-bottom:0}\n\n.bx--accordion{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;list-style:none;width:100%}\n\n.bx--accordion__item{transition:all 250ms cubic-bezier(0.5, 0, 0.1, 1);border-top:1px solid #dfe3e6;overflow:hidden}\n\n.bx--accordion__item:focus{outline:none}\n\n.bx--accordion__item:focus .bx--accordion__arrow{outline:1px solid #3d70b2;overflow:visible;outline-offset:-0.5px}\n\n.bx--accordion__item:last-child{border-bottom:1px solid #dfe3e6}\n\n.bx--accordion__heading{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;letter-spacing:0;display:inline-block;background:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:0;padding:0;cursor:pointer;width:100%;color:#152935;display:flex;align-items:center;justify-content:flex-start;flex-direction:row;cursor:pointer;padding:.5rem 0}\n\n.bx--accordion__heading::-moz-focus-inner{border:0}\n\n.bx--accordion__heading:focus{outline:none}\n\n.bx--accordion__heading:focus .bx--accordion__arrow{outline:1px solid #3d70b2;overflow:visible;outline-offset:-0.5px}\n\n.bx--accordion__arrow{transition:all 250ms cubic-bezier(0.5, 0, 0.1, 1);height:1.25rem;width:1.25rem;padding:.25rem .125rem .25rem .25rem;margin:0 0 0 .25rem;fill:#5a6872;-webkit-transform:rotate(0);transform:rotate(0)}\n\n.bx--accordion__title{font-size:1rem;line-height:1.5;margin:0 0 0 1rem;font-weight:400;text-align:left}\n\n.bx--accordion__content{transition:all 300ms cubic-bezier(0, 0, 0.25, 1);padding:0 1rem 0 2.5rem;height:0;visibility:hidden;opacity:0}\n\n.bx--accordion__content p{font-size:0.875rem}\n\n.bx--accordion__item--active{overflow:visible}\n\n.bx--accordion__item--active>.bx--accordion__content{padding-top:1rem;padding-bottom:1.5rem;height:auto;visibility:visible;opacity:1;transition:all 300ms cubic-bezier(0.25, 0, 1, 1)}\n\n.bx--accordion__item--active>.bx--accordion__heading>.bx--accordion__arrow{-webkit-transform:rotate(90deg);transform:rotate(90deg);fill:#3d70b2}\n\n.bx--accordion.bx--skeleton .bx--accordion__heading,.bx--accordion.bx--skeleton .bx--accordion__button{cursor:default}\n\n.bx--accordion.bx--skeleton .bx--accordion__arrow{pointer-events:none;fill:#5a6872;cursor:default}\n\n.bx--accordion.bx--skeleton .bx--accordion__arrow:hover,.bx--accordion.bx--skeleton .bx--accordion__arrow:focus,.bx--accordion.bx--skeleton .bx--accordion__arrow:active{border:none;outline:none;cursor:default}\n\n.bx--skeleton .bx--accordion__heading:focus .bx--accordion__arrow{border:none;outline:none;cursor:default}\n\n.bx--accordion__title.bx--skeleton__text{margin-bottom:0}\n\n.bx--progress{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;display:flex;list-style:none}\n\n.bx--progress-step{position:relative;display:inline-flex;flex-direction:column;flex:1;min-width:7rem;transition:250ms all cubic-bezier(0.5, 0, 0.1, 1);overflow:visible}\n\n.bx--progress-line{position:absolute;top:.625rem;right:100%;height:1px;width:calc(100% - 24px);border:1px inset transparent}\n\n.bx--progress-step:first-child .bx--progress-line{display:none}\n\n.bx--progress-step svg{position:relative;z-index:1;width:1.5rem;height:1.5rem;border-radius:50%;margin-bottom:.5rem;fill:#3d70b2}\n\n.bx--progress-label{line-height:1;width:75%}\n\n.bx--progress-step--current circle:first-child{stroke:#3d70b2;stroke-width:5;fill:transparent}\n\n.bx--progress-step--current .bx--progress-label{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;color:#3d70b2;font-weight:600}\n\n.bx--progress-step--current .bx--progress-line{background-color:#3d70b2}\n\n.bx--progress-step--incomplete circle{stroke:#8897a2;stroke-width:5;fill:transparent}\n\n.bx--progress-step--incomplete .bx--progress-label{color:#5a6872}\n\n.bx--progress-step--incomplete .bx--progress-line{background-color:#8897a2}\n\n.bx--progress-step--complete circle{stroke:#3d70b2;stroke-width:5;fill:transparent}\n\n.bx--progress-step--complete polygon{fill:#3d70b2}\n\n.bx--progress-step--complete .bx--progress-label{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;color:#3d70b2;font-weight:600}\n\n.bx--progress-step--complete .bx--progress-line{background-color:#3d70b2}\n\n.bx--progress.bx--skeleton .bx--progress-label{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);height:.75rem;width:2.5rem}\n\n.bx--progress.bx--skeleton .bx--progress-label:hover,.bx--progress.bx--skeleton .bx--progress-label:focus,.bx--progress.bx--skeleton .bx--progress-label:active{border:none;outline:none;cursor:default}\n\n.bx--progress.bx--skeleton .bx--progress-label:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--breadcrumb{font-size:0.875rem;font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;display:inline}\n\n@media screen and (min-width: 500px){.bx--breadcrumb{display:flex;flex-wrap:wrap}}\n\n.bx--breadcrumb-item{margin-right:1rem;display:flex;align-items:center}\n\n.bx--breadcrumb-item::after{content:'/';margin-left:1rem;color:#5a6872}\n\n.bx--breadcrumb--no-trailing-slash .bx--breadcrumb-item:last-child::after{content:''}\n\n.bx--breadcrumb-item:last-child{margin-right:0}\n\n.bx--breadcrumb-item:last-child::after{margin-right:0}\n\n.bx--breadcrumb .bx--link{white-space:nowrap;font-weight:400;text-decoration:none;border-bottom:1px solid transparent}\n\n.bx--breadcrumb .bx--link:hover,.bx--breadcrumb .bx--link:focus{outline:none;color:#294c79;border-bottom:1px solid #294c79}\n\n.bx--breadcrumb.bx--skeleton .bx--link{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:6.25rem;height:1rem}\n\n.bx--breadcrumb.bx--skeleton .bx--link:hover,.bx--breadcrumb.bx--skeleton .bx--link:focus,.bx--breadcrumb.bx--skeleton .bx--link:active{border:none;outline:none;cursor:default}\n\n.bx--breadcrumb.bx--skeleton .bx--link:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--toolbar{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;display:flex;flex-flow:row nowrap;align-items:center;margin:1rem 0}\n\n.bx--toolbar>div{margin:0 .25rem}\n\n.bx--toolbar .bx--search-input{height:2rem;background-color:transparent;outline:none}\n\n.bx--toolbar .bx--search-close{display:none}\n\n.bx--toolbar .bx--overflow-menu__icon{fill:#5a6872;transition:fill 50ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--toolbar .bx--search-magnifier{fill:#5a6872;-webkit-transform:scale(1.15);transform:scale(1.15);transition:all 175ms cubic-bezier(0.5, 0, 0.1, 1);top:.5rem;left:.375rem;cursor:pointer}\n\n.bx--toolbar fieldset{border:0;padding:0}\n\n.bx--toolbar .bx--toolbar-search--active{width:15.625rem}\n\n.bx--toolbar .bx--toolbar-search--active .bx--search-magnifier{-webkit-transform:scale(1);transform:scale(1);top:.5625rem}\n\n.bx--toolbar .bx--toolbar-search--active .bx--search-input{background-color:#fff}\n\n.bx--toolbar .bx--toolbar-search--active .bx--search-close{display:block}\n\n.bx--toolbar .bx--checkbox-label{margin-bottom:0}\n\n.bx--toolbar .bx--overflow-menu--open>.bx--overflow-menu__icon{fill:#3d70b2}\n\n.bx--toolbar-search{width:1.8rem;transition:all 175ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--toolbar-search__btn{position:absolute;left:0;top:0;background:transparent;border:0;height:2rem;width:2rem}\n\n.bx--toolbar-search__btn:focus{outline:1px solid #3d70b2}\n\n.bx--toolbar-filter-icon{padding-left:0;padding-right:0}\n\n.bx--toolbar-menu__title{font-size:0.75rem;letter-spacing:0;font-weight:600;padding:0.5rem 1.25rem}\n\n.bx--toolbar-menu__option{padding:0.5rem 1.25rem}\n\n.bx--toolbar-menu__divider{width:100%;border:0;border-top:1px solid #dfe3e6}\n\n.bx--radio-button-group{border:none}\n\n.bx--time-picker{display:flex;align-items:flex-end}\n\n.bx--time-picker .bx--label{order:1}\n\n.bx--time-picker__input{display:flex;flex-direction:column;border-bottom:1px solid transparent}\n\n.bx--time-picker .bx--select-input{padding-right:2rem}\n\n.bx--time-picker .bx--select__arrow{right:0.875rem}\n\n.bx--time-picker__input-field{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;font-size:0.875rem;display:flex;align-items:center;background-color:#f4f7fb;border:none;width:4.875rem;color:#152935;height:2.5rem;padding:0 1rem;order:2;box-shadow:0 1px 0 0 #5a6872}\n\n.bx--time-picker__input-field:focus{outline:none;box-shadow:0 2px 0 0 #3d70b2}\n\n.bx--time-picker__input-field:focus ~ .bx--label{color:#3d70b2}\n\n.bx--time-picker__input-field:-ms-input-placeholder{color:#5a6872}\n\n.bx--time-picker__input-field::-webkit-input-placeholder{color:#5a6872}\n\n.bx--time-picker__input-field::-ms-input-placeholder{color:#5a6872}\n\n.bx--time-picker__input-field::placeholder{color:#5a6872}\n\n.bx--time-picker__input-field[data-invalid],.bx--time-picker__input-field[data-invalid]:focus{box-shadow:0 2px 0 0 #e0182d}\n\n.bx--time-picker__input-field[data-invalid]:focus ~ .bx--label{color:#e0182d}\n\n.bx--time-picker__input-field ~ .bx--form-requirement{order:3;color:#e0182d;font-weight:400;margin-top:0;max-height:0}\n\n.bx--time-picker__input-field ~ .bx--form-requirement::before{display:none}\n\n.bx--time-picker__input-field[data-invalid] ~ .bx--form-requirement{overflow:visible;max-height:0;margin-top:.25rem}\n\n.bx--time-picker__input-field:disabled{opacity:0.5;cursor:not-allowed}\n\n.bx--time-picker--light .bx--time-picker__input-field{background:#fff}\n\n.bx--slider-container{display:flex;align-items:center;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}\n\n.bx--slider{position:relative;width:100%;margin:0 1rem;max-width:40rem;min-width:12.5rem;order:1}\n\n.bx--slider__range-label:first-of-type{order:0}\n\n.bx--slider-text-input{order:3}\n\n.bx--slider--disabled{opacity:0.5}\n\n.bx--slider--disabled .bx--slider__thumb:hover{-webkit-transform:translate(-50%, -50%);transform:translate(-50%, -50%)}\n\n.bx--slider--disabled .bx--slider__thumb:focus{box-shadow:none;outline:none}\n\n.bx--slider--disabled .bx--slider__thumb:active{background:#3d70b2;-webkit-transform:translate(-50%, -50%);transform:translate(-50%, -50%)}\n\n.bx--slider__range-label{font-size:0.875rem;color:#5a6872}\n\n.bx--slider__range-label:last-of-type{margin-right:1rem;order:2}\n\n.bx--slider__track{position:absolute;width:100%;height:.25rem;background:#8897a2;cursor:pointer;-webkit-transform:translate(0%, -50%);transform:translate(0%, -50%)}\n\n.bx--slider__filled-track{position:absolute;width:100%;height:.25rem;background:#3d70b2;-webkit-transform-origin:left;transform-origin:left;pointer-events:none;-webkit-transform:translate(0%, -50%);transform:translate(0%, -50%)}\n\n.bx--slider__thumb{position:absolute;height:1.5rem;width:1.5rem;background:#3d70b2;border-radius:50%;top:0;-webkit-transform:translate(-50%, -50%);transform:translate(-50%, -50%);transition:background 100ms cubic-bezier(0.5, 0, 0.1, 1),-webkit-transform 100ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 100ms cubic-bezier(0.5, 0, 0.1, 1),background 100ms cubic-bezier(0.5, 0, 0.1, 1);transition:transform 100ms cubic-bezier(0.5, 0, 0.1, 1),background 100ms cubic-bezier(0.5, 0, 0.1, 1),-webkit-transform 100ms cubic-bezier(0.5, 0, 0.1, 1);cursor:pointer;outline:none;z-index:2}\n\n.bx--slider__thumb--clicked{transition:left 250ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--slider__thumb:hover{-webkit-transform:translate(-50%, -50%) scale(1.05);transform:translate(-50%, -50%) scale(1.05)}\n\n.bx--slider__thumb:focus{box-shadow:0 0 0 3px #7cc7ff;outline:1px solid transparent}\n\n.bx--slider__thumb:active{background:#36649f;-webkit-transform:translate(-50%, -50%) scale(1.25);transform:translate(-50%, -50%) scale(1.25)}\n\n.bx--slider__input{display:none}\n\n.bx--slider-text-input,.bx-slider-text-input{width:3.75rem;min-width:3.75rem;height:2rem;padding:0;text-align:center;font-weight:600;-moz-appearance:textfield}\n\n.bx--slider-text-input::-webkit-outer-spin-button,.bx--slider-text-input::-webkit-inner-spin-button,.bx-slider-text-input::-webkit-outer-spin-button,.bx-slider-text-input::-webkit-inner-spin-button{display:none}\n\n.bx--slider-container.bx--skeleton .bx--slider__range-label{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:1.25rem;height:.75rem}\n\n.bx--slider-container.bx--skeleton .bx--slider__range-label:hover,.bx--slider-container.bx--skeleton .bx--slider__range-label:focus,.bx--slider-container.bx--skeleton .bx--slider__range-label:active{border:none;outline:none;cursor:default}\n\n.bx--slider-container.bx--skeleton .bx--slider__range-label:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--slider-container.bx--skeleton .bx--slider__track{cursor:default;pointer-events:none}\n\n.bx--slider-container.bx--skeleton .bx--slider__thumb{left:50%;cursor:default;pointer-events:none}\n\n.bx--tile{box-shadow:0 1px 2px 0 rgba(0,0,0,0.1);display:block;min-width:8rem;min-height:4rem;background-color:#fff;border:1px solid #dfe3e6;position:relative;padding:1rem}\n\n.bx--tile:focus{outline:1px solid #3d70b2}\n\n.bx--tile--clickable,.bx--tile--selectable,.bx--tile--expandable{transition:250ms cubic-bezier(0.5, 0, 0.1, 1);cursor:pointer}\n\n.bx--tile--clickable:hover,.bx--tile--selectable:hover,.bx--tile--expandable:hover{border:1px solid #8897a2}\n\n.bx--tile--clickable:hover .bx--tile__checkmark,.bx--tile--clickable:focus .bx--tile__checkmark,.bx--tile--selectable:hover .bx--tile__checkmark,.bx--tile--selectable:focus .bx--tile__checkmark,.bx--tile--expandable:hover .bx--tile__checkmark,.bx--tile--expandable:focus .bx--tile__checkmark{opacity:1}\n\n.bx--tile--clickable:hover .bx--tile__chevron svg,.bx--tile--clickable:focus .bx--tile__chevron svg,.bx--tile--selectable:hover .bx--tile__chevron svg,.bx--tile--selectable:focus .bx--tile__chevron svg,.bx--tile--expandable:hover .bx--tile__chevron svg,.bx--tile--expandable:focus .bx--tile__chevron svg{fill:#3d70b2}\n\n.bx--tile--clickable:focus,.bx--tile--expandable:focus{outline:1px solid #3d70b2}\n\n.bx--tile--selectable{padding-right:3rem}\n\n.bx--tile--selectable:focus{outline:none;border:1px solid #3d70b2}\n\n.bx--tile--is-clicked{box-shadow:none;border:1px solid #8897a2}\n\n.bx--tile__checkmark,.bx--tile__chevron{position:absolute;transition:250ms cubic-bezier(0.5, 0, 0.1, 1);border:none;background:transparent}\n\n.bx--tile__checkmark:focus,.bx--tile__chevron:focus{outline:1px solid #3d70b2}\n\n.bx--tile__checkmark{height:1rem;top:1rem;right:1rem;opacity:0}\n\n.bx--tile__checkmark svg{border-radius:50%;background-color:rgba(255,255,255,0.25);fill:rgba(61,112,178,0.25)}\n\n.bx--tile__chevron{position:absolute;bottom:0.5rem;right:0.5rem;height:1rem}\n\n.bx--tile__chevron svg{-webkit-transform-origin:center;transform-origin:center;transition:250ms cubic-bezier(0.5, 0, 0.1, 1);fill:#5a6872}\n\n.bx--tile__chevron:hover{cursor:pointer}\n\n.bx--tile--expandable{overflow:hidden;cursor:default;transition:250ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--tile-content__above-the-fold{display:block}\n\n.bx--tile-content__below-the-fold{display:block;opacity:0;transition:250ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--tile--is-expanded{overflow:visible;transition:250ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--tile--is-expanded .bx--tile__chevron svg{-webkit-transform:rotate(-180deg);transform:rotate(-180deg)}\n\n.bx--tile--is-expanded .bx--tile-content__below-the-fold{opacity:1;transition:250ms cubic-bezier(0.5, 0, 0.1, 1)}\n\n.bx--tile--is-selected,.bx--tile--is-selected:hover,.bx--tile--is-selected:focus{border:1px solid #3d70b2;outline:none}\n\n.bx--tile-input:checked+.bx--tile__checkmark{opacity:1}\n\n.bx--tile-input:checked+.bx--tile__checkmark svg{fill:#3d70b2;background-color:#fff}\n\n.bx--tile-content{width:100%;height:100%}\n\n.bx--tile-input{display:none}\n\n.bx--lightbox{width:66rem;box-shadow:0 12px 24px 0 rgba(0,0,0,0.1)}\n\n.bx--lightbox__main{position:relative}\n\n.bx--lightbox__btn{border:0;background:transparent;cursor:pointer;position:absolute;top:50%}\n\n.bx--lightbox__btn:first-of-type{left:-2rem}\n\n.bx--lightbox__btn:last-of-type{right:-2rem;-webkit-transform:rotate(180deg);transform:rotate(180deg)}\n\n.bx--lightbox__btn:focus{outline:1px solid #3d70b2}\n\n.bx--lightbox__btn svg{height:1.5rem;fill:#5a6872}\n\n.bx--lightbox__item{display:none;width:100%}\n\n.bx--lightbox__item--shown{display:block}\n\n.bx--lightbox__footer{background:#fff;overflow:hidden}\n\n.bx--carousel{display:flex;align-items:center}\n\n.bx--carousel-container{max-width:50.625rem;overflow:hidden;padding:0 1px}\n\n.bx--filmstrip{display:flex;justify-content:space-between;transition:-webkit-transform 100ms cubic-bezier(0.25, 0, 1, 1);transition:transform 100ms cubic-bezier(0.25, 0, 1, 1);transition:transform 100ms cubic-bezier(0.25, 0, 1, 1), -webkit-transform 100ms cubic-bezier(0.25, 0, 1, 1);padding:1.5rem 0;width:auto}\n\n.bx--filmstrip-btn{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;letter-spacing:0;display:inline-block;background:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:0;padding:0;cursor:pointer;width:100%;height:1.25rem;width:1.25rem;margin-bottom:1rem;margin-right:.1875rem;margin-left:.1875rem}\n\n.bx--filmstrip-btn::-moz-focus-inner{border:0}\n\n.bx--filmstrip-btn:hover{cursor:pointer}\n\n.bx--filmstrip-btn:focus{outline:1px solid #3d70b2}\n\n.bx--carousel__btn{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;letter-spacing:0;display:inline-block;background:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:0;padding:0;cursor:pointer;cursor:pointer;padding:0}\n\n.bx--carousel__btn::-moz-focus-inner{border:0}\n\n.bx--carousel__btn:first-child{margin-right:1.25rem}\n\n.bx--carousel__btn:last-child{margin-left:1.25rem}\n\n.bx--carousel__btn:focus{outline:1px solid #3d70b2}\n\n.bx--carousel__btn:last-of-type{-webkit-transform:rotate(180deg);transform:rotate(180deg)}\n\n.bx--carousel__btn svg{height:1.5rem;width:1rem;fill:#3d70b2}\n\n.bx--carousel__item{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;letter-spacing:0;display:inline-block;background:none;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:0;padding:0;cursor:pointer;width:100%;padding:0;line-height:0;margin-right:1.25rem;cursor:pointer}\n\n.bx--carousel__item::-moz-focus-inner{border:0}\n\n.bx--carousel__item:hover,.bx--carousel__item:focus{outline:1px solid #3d70b2}\n\n.bx--carousel__item--active{outline:1px solid #3d70b2}\n\n.bx--skeleton__text{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);width:100%;height:1rem;margin-bottom:.5rem}\n\n.bx--skeleton__text:hover,.bx--skeleton__text:focus,.bx--skeleton__text:active{border:none;outline:none;cursor:default}\n\n.bx--skeleton__text:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--skeleton__heading{height:1.5rem}\n\n.bx--icon--skeleton{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);display:inline-block;width:1rem;height:1rem}\n\n.bx--icon--skeleton:hover,.bx--icon--skeleton:focus,.bx--icon--skeleton:active{border:none;outline:none;cursor:default}\n\n.bx--icon--skeleton:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n.bx--skeleton__placeholder{position:relative;border:none;padding:0;box-shadow:none;pointer-events:none;background:rgba(61,112,178,0.1);height:6.25rem;width:6.25rem}\n\n.bx--skeleton__placeholder:hover,.bx--skeleton__placeholder:focus,.bx--skeleton__placeholder:active{border:none;outline:none;cursor:default}\n\n.bx--skeleton__placeholder:before{content:'';width:0%;height:100%;position:absolute;top:0;left:0;opacity:0.3;background:rgba(61,112,178,0.1);-webkit-animation:3000ms ease-in-out skeleton infinite;animation:3000ms ease-in-out skeleton infinite}\n\n@-webkit-keyframes stroke{100%{stroke-dashoffset:0}}\n\n@keyframes stroke{100%{stroke-dashoffset:0}}\n\n.bx--inline-loading{display:flex;width:100%;align-items:center}\n\n.bx--inline-loading__text{font-size:0.875rem}\n\n.bx--inline-loading__animation{position:relative;width:2rem;height:2rem;display:flex;justify-content:center;align-items:center}\n\n.bx--inline-loading__checkmark-container{width:0.75rem;position:absolute;top:0.75rem}\n\n.bx--inline-loading__checkmark-container[hidden]{display:none}\n\n.bx--inline-loading__checkmark{fill:none;stroke:#3d70b2;-webkit-transform-origin:50% 50%;transform-origin:50% 50%;stroke-width:2.1;stroke-dasharray:12;stroke-dashoffset:12;-webkit-animation-name:stroke;animation-name:stroke;-webkit-animation-duration:0.25s;animation-duration:0.25s;-webkit-animation-fill-mode:forwards;animation-fill-mode:forwards}\n\n.bx--loading--small .bx--inline-loading__svg{stroke:#3d70b2}\n\n@media screen and (-ms-high-contrast: active), screen and (-ms-high-contrast: none){.bx--inline-loading__checkmark-container{top:1px;right:0.5rem}.bx--inline-loading__checkmark{-webkit-animation:none;animation:none;stroke-dashoffset:0;stroke-dasharray:0}}\n\n.bx--footer--bottom-fixed{position:fixed;bottom:0;left:0}\n\n.bx--footer{font-family:\"ibm-plex-sans\",Helvetica Neue,Arial,sans-serif;box-sizing:border-box;display:flex;align-items:center;border-top:2px solid #3d70b2;background-color:#fff;min-height:3.5rem;z-index:5000;padding:1.25rem 5%;width:100%}\n\n.bx--footer-info{display:flex}\n\n@media screen and (max-width: 600px){.bx--footer-info{flex-direction:column}}\n\n.bx--footer-info__item{font-size:1.125rem;line-height:1.5;display:flex;flex-direction:column;margin:0;margin-right:4rem}\n\n.bx--footer-info__item>.bx--link{font-weight:600}\n\n.bx--footer-info__item>.bx--footer-label{font-size:0.875rem;line-height:1.5;margin:0}\n\n@media screen and (max-width: 600px){.bx--footer-info__item>.bx--footer-label{display:none}}\n\n.bx--footer-cta{margin-left:auto}\n\n.bx--fab{-webkit-transform:rotate(0);transform:rotate(0);transition:-webkit-transform 250ms;transition:transform 250ms;transition:transform 250ms, -webkit-transform 250ms;-webkit-transform-origin:center;transform-origin:center;display:inline-block;width:4.5rem;height:4.5rem;text-decoration:none;-webkit-filter:drop-shadow(0px 3px 3px 0 rgba(0,0,0,0.1));filter:drop-shadow(0px 3px 3px 0 rgba(0,0,0,0.1))}\n\n.bx--fab__hidden{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);border:0;visibility:visible;white-space:nowrap;color:#fff}\n\n.bx--fab__svg{width:100%}\n\n.bx--fab__svg .bx--fab__hexagon{transition:fill 250ms;fill:#5596e6}\n\n.bx--fab__svg .bx--fab__plus-icon{-webkit-transform:rotate(0);transform:rotate(0);transition:-webkit-transform 250ms;transition:transform 250ms;transition:transform 250ms, -webkit-transform 250ms;-webkit-transform-origin:center;transform-origin:center;fill:#fff}\n\n.bx--fab[data-state='closed']{-webkit-transform:rotate(90deg);transform:rotate(90deg);transition:-webkit-transform 250ms;transition:transform 250ms;transition:transform 250ms, -webkit-transform 250ms;-webkit-transform-origin:center;transform-origin:center}\n\n.bx--fab[data-state='closed'] .bx--fab__hexagon{transition:fill 250ms;fill:#42535c}\n\n.bx--fab[data-state='closed'] .bx--fab__plus-icon{-webkit-transform:rotate(-45deg);transform:rotate(-45deg);transition:-webkit-transform 250ms;transition:transform 250ms;transition:transform 250ms, -webkit-transform 250ms;-webkit-transform-origin:center;transform-origin:center}\n\nhtml, body { height: 100%; }\n\nbody { margin: 0; font-family: Roboto, \"Helvetica Neue\", sans-serif; }\n" /***/ }), /***/ "./node_modules/style-loader/lib/addStyles.js": /*!****************************************************!*\ !*** ./node_modules/style-loader/lib/addStyles.js ***! \****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var stylesInDom = {}; var memoize = function (fn) { var memo; return function () { if (typeof memo === "undefined") memo = fn.apply(this, arguments); return memo; }; }; var isOldIE = memoize(function () { // Test for IE <= 9 as proposed by Browserhacks // @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805 // Tests for existence of standard globals is to allow style-loader // to operate correctly into non-standard environments // @see https://github.com/webpack-contrib/style-loader/issues/177 return window && document && document.all && !window.atob; }); var getTarget = function (target) { return document.querySelector(target); }; var getElement = (function (fn) { var memo = {}; return function(target) { // If passing function in options, then use it for resolve "head" element. // Useful for Shadow Root style i.e // { // insertInto: function () { return document.querySelector("#foo").shadowRoot } // } if (typeof target === 'function') { return target(); } if (typeof memo[target] === "undefined") { var styleTarget = getTarget.call(this, target); // Special case to return head of iframe instead of iframe itself if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) { try { // This will throw an exception if access to iframe is blocked // due to cross-origin restrictions styleTarget = styleTarget.contentDocument.head; } catch(e) { styleTarget = null; } } memo[target] = styleTarget; } return memo[target] }; })(); var singleton = null; var singletonCounter = 0; var stylesInsertedAtTop = []; var fixUrls = __webpack_require__(/*! ./urls */ "./node_modules/style-loader/lib/urls.js"); module.exports = function(list, options) { if (typeof DEBUG !== "undefined" && DEBUG) { if (typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment"); } options = options || {}; options.attrs = typeof options.attrs === "object" ? options.attrs : {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of <style> // tags it will allow on a page if (!options.singleton && typeof options.singleton !== "boolean") options.singleton = isOldIE(); // By default, add <style> tags to the <head> element if (!options.insertInto) options.insertInto = "head"; // By default, add <style> tags to the bottom of the target if (!options.insertAt) options.insertAt = "bottom"; var styles = listToStyles(list, options); addStylesToDom(styles, options); return function update (newList) { var mayRemove = []; for (var i = 0; i < styles.length; i++) { var item = styles[i]; var domStyle = stylesInDom[item.id]; domStyle.refs--; mayRemove.push(domStyle); } if(newList) { var newStyles = listToStyles(newList, options); addStylesToDom(newStyles, options); } for (var i = 0; i < mayRemove.length; i++) { var domStyle = mayRemove[i]; if(domStyle.refs === 0) { for (var j = 0; j < domStyle.parts.length; j++) domStyle.parts[j](); delete stylesInDom[domStyle.id]; } } }; }; function addStylesToDom (styles, options) { for (var i = 0; i < styles.length; i++) { var item = styles[i]; var domStyle = stylesInDom[item.id]; if(domStyle) { domStyle.refs++; for(var j = 0; j < domStyle.parts.length; j++) { domStyle.parts[j](item.parts[j]); } for(; j < item.parts.length; j++) { domStyle.parts.push(addStyle(item.parts[j], options)); } } else { var parts = []; for(var j = 0; j < item.parts.length; j++) { parts.push(addStyle(item.parts[j], options)); } stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts}; } } } function listToStyles (list, options) { var styles = []; var newStyles = {}; for (var i = 0; i < list.length; i++) { var item = list[i]; var id = options.base ? item[0] + options.base : item[0]; var css = item[1]; var media = item[2]; var sourceMap = item[3]; var part = {css: css, media: media, sourceMap: sourceMap}; if(!newStyles[id]) styles.push(newStyles[id] = {id: id, parts: [part]}); else newStyles[id].parts.push(part); } return styles; } function insertStyleElement (options, style) { var target = getElement(options.insertInto) if (!target) { throw new Error("Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid."); } var lastStyleElementInsertedAtTop = stylesInsertedAtTop[stylesInsertedAtTop.length - 1]; if (options.insertAt === "top") { if (!lastStyleElementInsertedAtTop) { target.insertBefore(style, target.firstChild); } else if (lastStyleElementInsertedAtTop.nextSibling) { target.insertBefore(style, lastStyleElementInsertedAtTop.nextSibling); } else { target.appendChild(style); } stylesInsertedAtTop.push(style); } else if (options.insertAt === "bottom") { target.appendChild(style); } else if (typeof options.insertAt === "object" && options.insertAt.before) { var nextSibling = getElement(options.insertInto + " " + options.insertAt.before); target.insertBefore(style, nextSibling); } else { throw new Error("[Style Loader]\n\n Invalid value for parameter 'insertAt' ('options.insertAt') found.\n Must be 'top', 'bottom', or Object.\n (https://github.com/webpack-contrib/style-loader#insertat)\n"); } } function removeStyleElement (style) { if (style.parentNode === null) return false; style.parentNode.removeChild(style); var idx = stylesInsertedAtTop.indexOf(style); if(idx >= 0) { stylesInsertedAtTop.splice(idx, 1); } } function createStyleElement (options) { var style = document.createElement("style"); if(options.attrs.type === undefined) { options.attrs.type = "text/css"; } addAttrs(style, options.attrs); insertStyleElement(options, style); return style; } function
(options) { var link = document.createElement("link"); if(options.attrs.type === undefined) { options.attrs.type = "text/css"; } options.attrs.rel = "stylesheet"; addAttrs(link, options.attrs); insertStyleElement(options, link); return link; } function addAttrs (el, attrs) { Object.keys(attrs).forEach(function (key) { el.setAttribute(key, attrs[key]); }); } function addStyle (obj, options) { var style, update, remove, result; // If a transform function was defined, run it on the css if (options.transform && obj.css) { result = options.transform(obj.css); if (result) { // If transform returns a value, use that instead of the original css. // This allows running runtime transformations on the css. obj.css = result; } else { // If the transform function returns a falsy value, don't add this css. // This allows conditional loading of css return function() { // noop }; } } if (options.singleton) { var styleIndex = singletonCounter++; style = singleton || (singleton = createStyleElement(options)); update = applyToSingletonTag.bind(null, style, styleIndex, false); remove = applyToSingletonTag.bind(null, style, styleIndex, true); } else if ( obj.sourceMap && typeof URL === "function" && typeof URL.createObjectURL === "function" && typeof URL.revokeObjectURL === "function" && typeof Blob === "function" && typeof btoa === "function" ) { style = createLinkElement(options); update = updateLink.bind(null, style, options); remove = function () { removeStyleElement(style); if(style.href) URL.revokeObjectURL(style.href); }; } else { style = createStyleElement(options); update = applyToTag.bind(null, style); remove = function () { removeStyleElement(style); }; } update(obj); return function updateStyle (newObj) { if (newObj) { if ( newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap ) { return; } update(obj = newObj); } else { remove(); } }; } var replaceText = (function () { var textStore = []; return function (index, replacement) { textStore[index] = replacement; return textStore.filter(Boolean).join('\n'); }; })(); function applyToSingletonTag (style, index, remove, obj) { var css = remove ? "" : obj.css; if (style.styleSheet) { style.styleSheet.cssText = replaceText(index, css); } else { var cssNode = document.createTextNode(css); var childNodes = style.childNodes; if (childNodes[index]) style.removeChild(childNodes[index]); if (childNodes.length) { style.insertBefore(cssNode, childNodes[index]); } else { style.appendChild(cssNode); } } } function applyToTag (style, obj) { var css = obj.css; var media = obj.media; if(media) { style.setAttribute("media", media) } if(style.styleSheet) { style.styleSheet.cssText = css; } else { while(style.firstChild) { style.removeChild(style.firstChild); } style.appendChild(document.createTextNode(css)); } } function updateLink (link, options, obj) { var css = obj.css; var sourceMap = obj.sourceMap; /* If convertToAbsoluteUrls isn't defined, but sourcemaps are enabled and there is no publicPath defined then lets turn convertToAbsoluteUrls on by default. Otherwise default to the convertToAbsoluteUrls option directly */ var autoFixUrls = options.convertToAbsoluteUrls === undefined && sourceMap; if (options.convertToAbsoluteUrls || autoFixUrls) { css = fixUrls(css); } if (sourceMap) { // http://stackoverflow.com/a/26603875 css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */"; } var blob = new Blob([css], { type: "text/css" }); var oldSrc = link.href; link.href = URL.createObjectURL(blob); if(oldSrc) URL.revokeObjectURL(oldSrc); } /***/ }), /***/ "./node_modules/style-loader/lib/urls.js": /*!***********************************************!*\ !*** ./node_modules/style-loader/lib/urls.js ***! \***********************************************/ /*! no static exports found */ /***/ (function(module, exports) { /** * When source maps are enabled, `style-loader` uses a link element with a data-uri to * embed the css on the page. This breaks all relative urls because now they are relative to a * bundle instead of the current page. * * One solution is to only use full urls, but that may be impossible. * * Instead, this function "fixes" the relative urls to be absolute according to the current page location. * * A rudimentary test suite is located at `test/fixUrls.js` and can be run via the `npm test` command. * */ module.exports = function (css) { // get current location var location = typeof window !== "undefined" && window.location; if (!location) { throw new Error("fixUrls requires window.location"); } // blank or null? if (!css || typeof css !== "string") { return css; } var baseUrl = location.protocol + "//" + location.host; var currentDir = baseUrl + location.pathname.replace(/\/[^\/]*$/, "/"); // convert each url(...) /* This regular expression is just a way to recursively match brackets within a string. /url\s*\( = Match on the word "url" with any whitespace after it and then a parens ( = Start a capturing group (?: = Start a non-capturing group [^)(] = Match anything that isn't a parentheses | = OR \( = Match a start parentheses (?: = Start another non-capturing groups [^)(]+ = Match anything that isn't a parentheses | = OR \( = Match a start parentheses [^)(]* = Match anything that isn't a parentheses \) = Match a end parentheses ) = End Group *\) = Match anything and then a close parens ) = Close non-capturing group * = Match anything ) = Close capturing group \) = Match a close parens /gi = Get all matches, not the first. Be case insensitive. */ var fixedCss = css.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi, function(fullMatch, origUrl) { // strip quotes (if they exist) var unquotedOrigUrl = origUrl .trim() .replace(/^"(.*)"$/, function(o, $1){ return $1; }) .replace(/^'(.*)'$/, function(o, $1){ return $1; }); // already a full url? no change if (/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/|\s*$)/i.test(unquotedOrigUrl)) { return fullMatch; } // convert the url to a full url var newUrl; if (unquotedOrigUrl.indexOf("//") === 0) { //TODO: should we add protocol? newUrl = unquotedOrigUrl; } else if (unquotedOrigUrl.indexOf("/") === 0) { // path should be relative to the base url newUrl = baseUrl + unquotedOrigUrl; // already starts with '/' } else { // path should be relative to current directory newUrl = currentDir + unquotedOrigUrl.replace(/^\.\//, ""); // Strip leading './' } // send back the fixed url(...) return "url(" + JSON.stringify(newUrl) + ")"; }); // send back the fixed css return fixedCss; }; /***/ }), /***/ "./src/styles.css": /*!************************!*\ !*** ./src/styles.css ***! \************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var content = __webpack_require__(/*! !../node_modules/raw-loader!../node_modules/postcss-loader/lib??embedded!./styles.css */ "./node_modules/raw-loader/index.js!./node_modules/postcss-loader/lib/index.js??embedded!./src/styles.css"); if(typeof content === 'string') content = [[module.i, content, '']]; var transform; var insertInto; var options = {"hmr":true} options.transform = transform options.insertInto = undefined; var update = __webpack_require__(/*! ../node_modules/style-loader/lib/addStyles.js */ "./node_modules/style-loader/lib/addStyles.js")(content, options); if(content.locals) module.exports = content.locals; if(false) {} /***/ }), /***/ 2: /*!***********************************************************************************************!*\ !*** multi ./node_modules/@angular/material/prebuilt-themes/indigo-pink.css ./src/styles.css ***! \***********************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! D:\work-space\git-space\ExternalPluginExample-RemoteServer\node_modules\@angular\material\prebuilt-themes\indigo-pink.css */"./node_modules/@angular/material/prebuilt-themes/indigo-pink.css"); module.exports = __webpack_require__(/*! D:\work-space\git-space\ExternalPluginExample-RemoteServer\src\styles.css */"./src/styles.css"); /***/ }) },[[2,"runtime"]]]); //# sourceMappingURL=styles.js.map
createLinkElement
search.ts
import { Specs } from '../types' import { getSpecComplexity } from './complexity' import { getSpec } from './spec' const NUMERAL = '0123456789' export function startsWithNumeral(str: string): boolean { return NUMERAL.indexOf(str[0]) > -1 }
export function compareByComplexity( specs: Specs, a: string, b: string ): number { const aC = getSpecComplexity(specs, a, true) const bC = getSpecComplexity(specs, b, true) if (aC < bC) { return -1 } else if (aC > bC) { return 1 } else { return compareByName(specs, a, b) } } export function compareByName(specs: Specs, a: string, b: string): number { const aSpec = getSpec(specs, a) const bSpec = getSpec(specs, b) const aName = (aSpec.name || '').toLowerCase() const bName = (bSpec.name || '').toLowerCase() if (startsWithNumeral(aName) && !startsWithNumeral(bName)) { return 1 } else if (!startsWithNumeral(aName) && startsWithNumeral(bName)) { return -1 } if (aName < bName) { return -1 } else if (aName > bName) { return 1 } else { return 0 } }
create-movement-type-input.dto.ts
export class
{ readonly name: string; readonly code: string; readonly sign: number; }
CreateMovementTypeInput
types.rs
// For more information about basic "External Term Format" types you can read // on the next page: http://erlang.org/doc/apps/erts/erl_ext_dist.html use std::string::String; use std::ops::Deref; use std::{i32}; use num::bigint::BigInt; pub const BERT_LABEL: &'static str = "bert"; pub const EXT_VERSION: u8 = 131u8; // The BERT encoding is identical to Erlang's external term format except that // it is restricted to the following data type identifiers: 97-100, 104-111. #[derive(Debug, Copy, Clone, PartialEq)] pub enum BertTag { NewFloat = 70, // 70, NEW_FLOAT_EXT SmallInteger = 97, // 97, SMALL_INTEGER_EXT Integer = 98, // 98, INTEGER_EXT Float = 99, // 99, FLOAT_EXT (deprecated; using for deserialize) Atom = 100, // 100, ATOM_EXT SmallTuple = 104, // 104, SMALL_TUPLE_EXT LargeTuple = 105, // 105, LARGE_TUPLE_EXT Nil = 106, // 106, NIL_EXT String = 107, // 107, STRING_EXT List = 108, // 108, LIST_EXT Binary = 109, // 109, BINARY_EXT SmallBigNum = 110, // 110, SMALL_BIG_EXT LargeBigNum = 111, // 111, LARGE_BIG_EXT } #[derive(Debug, PartialEq)] pub struct BertBigInteger(pub BigInt); impl Deref for BertBigInteger { type Target = BigInt; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Debug, PartialEq)] pub struct BertTime(TimeStruct); impl BertTime { pub fn new(megaseconds: i32, seconds: i32, microseconds: i32) -> BertTime { BertTime( TimeStruct{ megaseconds: megaseconds, seconds: seconds, microseconds: microseconds } ) } } impl Deref for BertTime { type Target = TimeStruct; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Debug, PartialEq)]
pub struct TimeStruct { pub megaseconds: i32, pub seconds: i32, pub microseconds: i32, } #[derive(Debug, PartialEq)] pub struct BertRegex(RegexStruct); impl BertRegex { pub fn new(source: &str, options: Vec<RegexOption>) -> BertRegex { BertRegex( RegexStruct{ source: source.to_string(), options: options, } ) } } impl Deref for BertRegex { type Target = RegexStruct; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Debug, PartialEq)] pub struct RegexStruct { pub source: String, pub options: Vec<RegexOption> } enum_str!( RegexOption { Extended("extended"), Caseless("caseless"), Multiline("multiline"), DotAll("dotall"), } );
index.ts
import _ from "lodash"; import * as util from "../../../util/util"; import * as test from "../../../util/test"; import chalk from "chalk"; import { log, logSolution, trace } from "../../../util/log"; import { performance } from "perf_hooks"; const YEAR = 2021; const DAY = 16; // solution path: C:\Users\Johannes\advent-of-code\years\2021\16\index.ts // data path : C:\Users\Johannes\advent-of-code\years\2021\16\data.txt // problem url : https://adventofcode.com/2021/day/16 function convert(input: string) { /* 0 = 0000 1 = 0001 2 = 0010 3 = 0011 4 = 0100 5 = 0101 6 = 0110 7 = 0111 8 = 1000 9 = 1001 A = 1010 B = 1011 C = 1100 D = 1101 E = 1110 F = 1111 */ let hexMap: Map<string, string> = new Map(); hexMap.set('0', '0000'); hexMap.set('1', '0001'); hexMap.set('2', '0010'); hexMap.set('3', '0011'); hexMap.set('4', '0100'); hexMap.set('5', '0101'); hexMap.set('6', '0110'); hexMap.set('7', '0111'); hexMap.set('8', '1000'); hexMap.set('9', '1001'); hexMap.set('A', '1010'); hexMap.set('B', '1011'); hexMap.set('C', '1100'); hexMap.set('D', '1101'); hexMap.set('E', '1110'); hexMap.set('F', '1111'); let bitArr: string[] = []; for (let i = 0; i < input.length; i++) { const hex = input[i]; const decode = hexMap.get(hex)!; bitArr.push(decode); } return bitArr.join(''); console.log(bitArr) } interface IPackage { version: number, typeID: number, type: 'literal' | 'operator', subPackets?: number, subPacketsLength?: number } function parsePackage(input: string, startIndex: number): IPackage { let index = startIndex; let pack: Partial<IPackage> = {}; const version = input.slice(index, index + 3); pack.version = parseInt(version, 2); index = index + 3; const typeID = input.slice(index, index + 3); pack.typeID = parseInt(typeID, 2); pack.type = pack.typeID === 4 ? 'literal' : 'operator'; index = index + 3; if (pack.type === "operator") { const lengthTypeID = input.slice(index, index + 1); index++; if (lengthTypeID === '0') { } else { const l = input.slice(index,index+11); pack.subPackets = parseInt(l,2); } } return pack as IPackage; } async function p2021day16_part1(input: string, ...params: any[]) { const bitString = convert(input); console.log(bitString.slice(0, 50)); const firstPackage = parsePackage(bitString, 0); console.log(firstPackage); return "Not implemented"; } async function
(input: string, ...params: any[]) { return "Not implemented"; } async function run() { const part1tests: TestCase[] = []; const part2tests: TestCase[] = []; // Run tests test.beginTests(); await test.section(async () => { for (const testCase of part1tests) { test.logTestResult(testCase, String(await p2021day16_part1(testCase.input, ...(testCase.extraArgs || [])))); } }); await test.section(async () => { for (const testCase of part2tests) { test.logTestResult(testCase, String(await p2021day16_part2(testCase.input, ...(testCase.extraArgs || [])))); } }); test.endTests(); // Get input and run program while measuring performance const input = await util.getInput(DAY, YEAR); const part1Before = performance.now(); const part1Solution = String(await p2021day16_part1(input)); const part1After = performance.now(); const part2Before = performance.now() const part2Solution = String(await p2021day16_part2(input)); const part2After = performance.now(); logSolution(16, 2021, part1Solution, part2Solution); log(chalk.gray("--- Performance ---")); log(chalk.gray(`Part 1: ${util.formatTime(part1After - part1Before)}`)); log(chalk.gray(`Part 2: ${util.formatTime(part2After - part2Before)}`)); log(); } run() .then(() => { process.exit(); }) .catch(error => { throw error; });
p2021day16_part2
asset.py
# -*- coding: utf-8 -*- import json from bitsharesbase import operations from bitsharesbase.asset_permissions import ( asset_permissions, force_flag, test_permissions, todict, ) from .blockchainobject import BlockchainObject from .exceptions import AssetDoesNotExistsException from .instance import BlockchainInstance from graphenecommon.asset import Asset as GrapheneAsset @BlockchainInstance.inject class Asset(GrapheneAsset): """ Deals with Assets of the network. :param str Asset: Symbol name or object id of an asset :param bool lazy: Lazy loading :param bool full: Also obtain bitasset-data and dynamic asset data :param bitshares.bitshares.BitShares blockchain_instance: BitShares instance :returns: All data of an asset :rtype: dict .. note:: This class comes with its own caching function to reduce the load on the API server. Instances of this class can be refreshed with ``Asset.refresh()``. """ def define_classes(self): self.type_id = 3 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Permissions and flags self["permissions"] = todict(self["options"].get("issuer_permissions")) self["flags"] = todict(self["options"].get("flags")) try: self["description"] = json.loads(self["options"]["description"]) except Exception: self["description"] = self["options"]["description"] @property def market_fee_percent(self): return self["options"]["market_fee_percent"] / 100 / 100 @property def max_market_fee(self): from .amount import Amount return Amount( {"amount": self["options"]["max_market_fee"], "asset_id": self["id"]} ) @property def feeds(self): from .price import PriceFeed self.ensure_full() if not self.is_bitasset: return r = [] for feed in self["bitasset_data"]["feeds"]: r.append(PriceFeed(feed, blockchain_instance=self.blockchain)) return r @property def feed(self): from .price import PriceFeed assert self.is_bitasset self.ensure_full() return PriceFeed( self["bitasset_data"]["current_feed"], blockchain_instance=self.blockchain ) @property def calls(self): return self.get_call_orders(10) def get_call_orders(self, limit=100): from .price import Price from .account import Account from .amount import Amount assert limit <= 100 assert self.is_bitasset self.ensure_full() r = list() bitasset = self["bitasset_data"] settlement_price = Price( bitasset["current_feed"]["settlement_price"], blockchain_instance=self.blockchain, ) ret = self.blockchain.rpc.get_call_orders(self["id"], limit) for call in ret[:limit]: call_price = Price(call["call_price"], blockchain_instance=self.blockchain) collateral_amount = Amount( { "amount": call["collateral"], "asset_id": call["call_price"]["base"]["asset_id"], }, blockchain_instance=self.blockchain, ) debt_amount = Amount( { "amount": call["debt"], "asset_id": call["call_price"]["quote"]["asset_id"], }, blockchain_instance=self.blockchain, ) r.append( { "account": Account( call["borrower"], lazy=True, blockchain_instance=self.blockchain ), "collateral": collateral_amount, "debt": debt_amount, "call_price": call_price, "settlement_price": settlement_price, "ratio": ( float(collateral_amount) / float(debt_amount) * float(settlement_price) ), } ) return r @property def settlements(self): return self.get_settle_orders(10) def
(self, limit=100): from .account import Account from .amount import Amount from .utils import formatTimeString assert limit <= 100 assert self.is_bitasset r = list() ret = self.blockchain.rpc.get_settle_orders(self["id"], limit) for settle in ret[:limit]: r.append( { "account": Account( settle["owner"], lazy=True, blockchain_instance=self.blockchain ), "amount": Amount( settle["balance"], blockchain_instance=self.blockchain ), "date": formatTimeString(settle["settlement_date"]), } ) return r def halt(self): """ Halt this asset from being moved or traded """ from .account import Account nullaccount = Account( "null-account", # We set the null-account blockchain_instance=self.blockchain, ) flags = {"white_list": True, "transfer_restricted": True} options = self["options"] test_permissions(options["issuer_permissions"], flags) flags_int = force_flag(options["flags"], flags) options.update( { "flags": flags_int, "whitelist_authorities": [nullaccount["id"]], "blacklist_authorities": [], "whitelist_markets": [self["id"]], "blacklist_markets": [], } ) op = operations.Asset_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "issuer": self["issuer"], "asset_to_update": self["id"], "new_options": options, "extensions": [], } ) return self.blockchain.finalizeOp(op, self["issuer"], "active") def release( self, whitelist_authorities=[], blacklist_authorities=[], whitelist_markets=[], blacklist_markets=[], ): """ Release this asset and allow unrestricted transfer, trading, etc. :param list whitelist_authorities: List of accounts that serve as whitelist authorities :param list blacklist_authorities: List of accounts that serve as blacklist authorities :param list whitelist_markets: List of assets to allow trading with :param list blacklist_markets: List of assets to prevent trading with """ from .account import Account flags = {"white_list": False, "transfer_restricted": False} options = self["options"] test_permissions(options["issuer_permissions"], flags) flags_int = force_flag(options["flags"], flags) options.update( { "flags": flags_int, "whitelist_authorities": [ Account(a)["id"] for a in whitelist_authorities ], "blacklist_authorities": [ Account(a)["id"] for a in blacklist_authorities ], "whitelist_markets": [Asset(a)["id"] for a in whitelist_markets], "blacklist_markets": [Asset(a)["id"] for a in blacklist_markets], } ) op = operations.Asset_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "issuer": self["issuer"], "asset_to_update": self["id"], "new_options": options, "extensions": [], } ) return self.blockchain.finalizeOp(op, self["issuer"], "active") def setoptions(self, flags): """ Enable a certain flag. Flags: * charge_market_fee * white_list * override_authority * transfer_restricted * disable_force_settle * global_settle * disable_confidential * witness_fed_asset * committee_fed_asset :param dict flag: dictionary of flags and boolean """ assert set(flags.keys()).issubset(asset_permissions.keys()), "unknown flag" options = self["options"] test_permissions(options["issuer_permissions"], flags) flags_int = force_flag(options["flags"], flags) options.update({"flags": flags_int}) op = operations.Asset_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "issuer": self["issuer"], "asset_to_update": self["id"], "new_options": options, "extensions": [], } ) return self.blockchain.finalizeOp(op, self["issuer"], "active") def enableflag(self, flag): """ Enable a certain flag. :param str flag: Flag name """ return self.setoptions({flag: True}) def disableflag(self, flag): """ Enable a certain flag. :param str flag: Flag name """ return self.setoptions({flag: False}) def seize(self, from_account, to_account, amount): """ Seize amount from an account and send to another ... note:: This requires the ``override_authority`` to be set for this asset! :param bitshares.account.Account from_account: From this account :param bitshares.account.Account to_account: To this account :param bitshares.amount.Amount amount: Amount to seize """ options = self["options"] if not (options["flags"] & asset_permissions["override_authority"]): raise Exception("Insufficient Permissions/flags for seizure!") op = operations.Override_transfer( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "issuer": self["issuer"], "from": from_account["id"], "to": to_account["id"], "amount": amount.json(), "extensions": [], } ) return self.blockchain.finalizeOp(op, self["issuer"], "active") def add_authorities(self, type, authorities=[]): """ Add authorities to an assets white/black list :param str type: ``blacklist`` or ``whitelist`` :param list authorities: List of authorities (Accounts) """ assert type in ["blacklist", "whitelist"] assert isinstance(authorities, (list, set)) from .account import Account options = self["options"] if type == "whitelist": options["whitelist_authorities"].extend( [Account(a)["id"] for a in authorities] ) if type == "blacklist": options["blacklist_authorities"].extend( [Account(a)["id"] for a in authorities] ) op = operations.Asset_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "issuer": self["issuer"], "asset_to_update": self["id"], "new_options": options, "extensions": [], } ) return self.blockchain.finalizeOp(op, self["issuer"], "active") def remove_authorities(self, type, authorities=[]): """ Remove authorities from an assets white/black list :param str type: ``blacklist`` or ``whitelist`` :param list authorities: List of authorities (Accounts) """ assert type in ["blacklist", "whitelist"] assert isinstance(authorities, (list, set)) from .account import Account options = self["options"] if type == "whitelist": for a in authorities: options["whitelist_authorities"].remove(Account(a)["id"]) if type == "blacklist": for a in authorities: options["blacklist_authorities"].remove(Account(a)["id"]) op = operations.Asset_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "issuer": self["issuer"], "asset_to_update": self["id"], "new_options": options, "extensions": [], } ) return self.blockchain.finalizeOp(op, self["issuer"], "active") def add_markets(self, type, authorities=[], force_enable=True): """ Add markets to an assets white/black list :param str type: ``blacklist`` or ``whitelist`` :param list markets: List of markets (assets) :param bool force_enable: Force enable ``white_list`` flag """ assert type in ["blacklist", "whitelist"] assert isinstance(authorities, (list, set)) options = self["options"] if force_enable: test_permissions(options["issuer_permissions"], {"white_list": True}) flags_int = force_flag(options["flags"], {"white_list": True}) options.update({"flags": flags_int}) else: assert test_permissions( options["flags"], ["white_list"] ), "whitelist feature not enabled" if type == "whitelist": options["whitelist_markets"].extend([Asset(a)["id"] for a in authorities]) if type == "blacklist": options["blacklist_markets"].extend([Asset(a)["id"] for a in authorities]) op = operations.Asset_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "issuer": self["issuer"], "asset_to_update": self["id"], "new_options": options, "extensions": [], } ) return self.blockchain.finalizeOp(op, self["issuer"], "active") def remove_markets(self, type, authorities=[]): """ Remove markets from an assets white/black list :param str type: ``blacklist`` or ``whitelist`` :param list markets: List of markets (assets) """ assert type in ["blacklist", "whitelist"] assert isinstance(authorities, (list, set)) options = self["options"] if type == "whitelist": for a in authorities: options["whitelist_markets"].remove(Asset(a)["id"]) if type == "blacklist": for a in authorities: options["blacklist_markets"].remove(Asset(a)["id"]) op = operations.Asset_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "issuer": self["issuer"], "asset_to_update": self["id"], "new_options": options, "extensions": [], } ) return self.blockchain.finalizeOp(op, self["issuer"], "active") def set_market_fee(self, percentage_fee, max_market_fee): """ Set trading percentage fee :param float percentage_fee: Percentage of fee :param bitshares.amount.Amount max_market_fee: Max Fee """ assert percentage_fee <= 100 and percentage_fee > 0 flags = {"charge_market_fee": percentage_fee > 0} options = self["options"] test_permissions(options["issuer_permissions"], flags) flags_int = force_flag(options["flags"], flags) options.update( { "flags": flags_int, "market_fee_percent": percentage_fee * 100, "max_market_fee": int(max_market_fee), } ) op = operations.Asset_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "issuer": self["issuer"], "asset_to_update": self["id"], "new_options": options, "extensions": [], } ) return self.blockchain.finalizeOp(op, self["issuer"], "active") def update_feed_producers(self, producers): """ Update bitasset feed producers :param list producers: List of accounts that are allowed to produce a feed """ assert self.is_bitasset, "Asset needs to be a bitasset/market pegged asset" from .account import Account op = operations.Asset_update_feed_producers( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "issuer": self["issuer"], "asset_to_update": self["id"], "new_feed_producers": [Account(a)["id"] for a in producers], "extensions": [], } ) return self.blockchain.finalizeOp(op, self["issuer"], "active")
get_settle_orders
defaults.go
/* Copyright 2017 Google LLC 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 https://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 v1beta2 // SetSparkApplicationDefaults sets default values for certain fields of a SparkApplication. func
(app *SparkApplication) { if app == nil { return } if app.Spec.Mode == "" { app.Spec.Mode = ClusterMode } if app.Spec.RestartPolicy.Type == "" { app.Spec.RestartPolicy.Type = Never } if app.Spec.RestartPolicy.Type != Never { // Default to 5 sec if the RestartPolicy is OnFailure or Always and these values aren't specified. if app.Spec.RestartPolicy.OnFailureRetryInterval == nil { app.Spec.RestartPolicy.OnFailureRetryInterval = new(int64) *app.Spec.RestartPolicy.OnFailureRetryInterval = 5 } if app.Spec.RestartPolicy.OnSubmissionFailureRetryInterval == nil { app.Spec.RestartPolicy.OnSubmissionFailureRetryInterval = new(int64) *app.Spec.RestartPolicy.OnSubmissionFailureRetryInterval = 5 } } setDriverSpecDefaults(&app.Spec.Driver, app.Spec.SparkConf) setExecutorSpecDefaults(&app.Spec.Executor, app.Spec.SparkConf) } func setDriverSpecDefaults(spec *DriverSpec, sparkConf map[string]string) { if _, exists := sparkConf["spark.driver.cores"]; !exists && spec.Cores == nil { spec.Cores = new(int32) *spec.Cores = 1 } if _, exists := sparkConf["spark.driver.memory"]; !exists && spec.Memory == nil { spec.Memory = new(string) *spec.Memory = "1g" } } func setExecutorSpecDefaults(spec *ExecutorSpec, sparkConf map[string]string) { if _, exists := sparkConf["spark.executor.cores"]; !exists && spec.Cores == nil { spec.Cores = new(int32) *spec.Cores = 1 } if _, exists := sparkConf["spark.executor.memory"]; !exists && spec.Memory == nil { spec.Memory = new(string) *spec.Memory = "1g" } if _, exists := sparkConf["spark.executor.instances"]; !exists && spec.Instances == nil { spec.Instances = new(int32) *spec.Instances = 1 } }
SetSparkApplicationDefaults
BOHB.py
''' Reference: https://github.com/automl/DEHB ''' from typing import List import numpy as np # from xbbo.configspace.feature_space import Uniform2Gaussian from xbbo.search_algorithm.multi_fidelity.hyperband import HB from xbbo.configspace.space import DenseConfiguration, DenseConfigurationSpace from xbbo.core.trials import Trials, Trial from xbbo.search_algorithm.multi_fidelity.utils.bracket_manager import BasicConfigGenerator from xbbo.search_algorithm.tpe_optimizer import TPE from xbbo.search_algorithm.bo_optimizer import BO from xbbo.utils.constants import MAXINT, Key from .. import alg_register class BOHB_CG_TPE(BasicConfigGenerator, TPE): def __init__(self, cs, budget, max_pop_size, rng, **kwargs) -> None: BasicConfigGenerator.__init__(self, cs, budget, max_pop_size, rng, **kwargs) TPE.__init__(self, space=cs, **kwargs) self.reset(max_pop_size) class BOHB_CG(BasicConfigGenerator, BO): def __init__(self, cs, budget, max_pop_size, rng, **kwargs) -> None: BasicConfigGenerator.__init__(self, cs, budget, max_pop_size, rng, **kwargs) BO.__init__(self, space=cs, **kwargs) self.reset(max_pop_size) @property def kde_models(self): return (self.trials.trials_num) >= self.min_sample alg_marker = 'bohb' @alg_register.register(alg_marker) class BOHB(HB): name = alg_marker def __init__(self, space: DenseConfigurationSpace, budget_bound=[9, 729], # mutation_factor=0.5, # crossover_prob=0.5, # strategy='rand1_bin', eta: int = 3, seed: int = 42, round_limit: int = 1, bracket_limit=np.inf, bo_opt_name='prf', boundary_fix_type='random', **kwargs): self.bo_opt_name = bo_opt_name HB.__init__(self, space, budget_bound, eta, seed=seed, round_limit=round_limit, bracket_limit=bracket_limit, boundary_fix_type=boundary_fix_type, **kwargs) # Uniform2Gaussian.__init__(self,) # self._get_max_pop_sizes() # self._init_subpop(**kwargs) def _init_subpop(self, **kwargs): """ List of DE objects corresponding to the budgets (fidelities) """ self.cg = {} for i, b in enumerate(self._max_pop_size.keys()): if self.bo_opt_name.upper() == 'TPE': self.cg[b] = BOHB_CG_TPE( self.space, seed=self.rng.randint(MAXINT), initial_design="random", init_budget=0, budget=b, max_pop_size=self._max_pop_size[b], rng=self.rng, **kwargs) else: self.cg[b] = BOHB_CG( self.space, seed=self.rng.randint(MAXINT), initial_design="random", init_budget=0, budget=b, max_pop_size=self._max_pop_size[b], rng=self.rng, surrogate=self.bo_opt_name, **kwargs) # self.cg[b] = TPE( # self.space, # seed=self.rng.randint(MAXINT), # initial_design="random", # init_budget=0, # **kwargs) # self.cg[b].population = [None] * self._max_pop_size[b] # self.cg[b].population_fitness = [np.inf] * self._max_pop_size[b] def _acquire_candidate(self, bracket, budget): """ Generates/chooses a configuration based on the budget and iteration number """ # select a parent/target # select a parent/target parent_id = self._get_next_idx_for_subpop(budget, bracket) if budget != bracket.budgets[0]: if bracket.is_new_rung(): # TODO: check if generalizes to all budget spacings lower_budget, num_configs = bracket.get_lower_budget_promotions( budget) self._get_promotion_candidate(lower_budget, budget, num_configs) # else: # 每一列中的第一行,随机生成config else: if bracket.is_new_rung(): lower_budget, num_configs = bracket.get_lower_budget_promotions( budget) self.cg[budget].population_fitness[:] = np.inf for b in reversed(self.budgets): if self.cg[b].kde_models: break # trial = self.cg[b]._suggest()[0] trials = self.cg[b]._suggest(1) for i in range(len(trials)): self.cg[budget].population[parent_id+i] = trials[i].array # self.cg[budget].population[parent_id] = trial.array # parent_id = self._get_next_idx_for_subpop(budget, bracket) target = self.cg[budget].population[parent_id] # target = self.fix_boundary(target) return target, parent_id def _observe(self, trial_list): for trial in trial_list: self.trials.add_a_trial(trial, True) fitness = trial.observe_value job_info = trial.info # learner_train_time = job_info.get(Key.EVAL_TIME, 0) budget = job_info[Key.BUDGET] parent_id = job_info['parent_id'] individual = trial.array # TODO for bracket in self.active_brackets: if bracket.bracket_id == job_info['bracket_id']: # registering is IMPORTANT for Bracket Manager to perform SH bracket.register_job(budget) # may be new row # bracket job complete bracket.complete_job( budget) # IMPORTANT to perform synchronous SH self.cg[budget].population[parent_id] = individual self.cg[budget].population_fitness[parent_id] = fitness # updating incumbents if fitness < self.current_best_fitness: self.current_best = indivi
ge(bracket.n_rungs-1, bracket.current_rung, -1): # if self.cg[bracket.budgets[rung]].kde_models: # break # else: self.cg[budget]._observe([trial]) self._clean_inactive_brackets() opt_class = BOHB
dual self.current_best_fitness = trial.observe_value self.current_best_trial = trial # for rung in ran
quota.pb.go
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: mixer/adapter/model/v1beta1/quota.proto package v1beta1 import ( fmt "fmt" _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" github_com_gogo_protobuf_sortkeys "github.com/gogo/protobuf/sortkeys" _ "github.com/gogo/protobuf/types" github_com_gogo_protobuf_types "github.com/gogo/protobuf/types" io "io" rpc "istio.io/gogo-genproto/googleapis/google/rpc" math "math" math_bits "math/bits" reflect "reflect" strings "strings" time "time" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf var _ = time.Kitchen // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // Expresses the quota allocation request. type QuotaRequest struct { // The individual quotas to allocate Quotas map[string]QuotaRequest_QuotaParams `protobuf:"bytes,1,rep,name=quotas,proto3" json:"quotas" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } func (m *QuotaRequest) Reset() { *m = QuotaRequest{} } func (*QuotaRequest) ProtoMessage() {} func (*QuotaRequest) Descriptor() ([]byte, []int) { return fileDescriptor_f07acf62b4429357, []int{0} } func (m *QuotaRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QuotaRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QuotaRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QuotaRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_QuotaRequest.Merge(m, src) } func (m *QuotaRequest) XXX_Size() int { return m.Size() } func (m *QuotaRequest) XXX_DiscardUnknown() { xxx_messageInfo_QuotaRequest.DiscardUnknown(m) } var xxx_messageInfo_QuotaRequest proto.InternalMessageInfo // parameters for a quota allocation type QuotaRequest_QuotaParams struct { // Amount of quota to allocate Amount int64 `protobuf:"varint,1,opt,name=amount,proto3" json:"amount,omitempty"` // When true, supports returning less quota than what was requested. BestEffort bool `protobuf:"varint,2,opt,name=best_effort,json=bestEffort,proto3" json:"best_effort,omitempty"` } func (m *QuotaRequest_QuotaParams) Reset() { *m = QuotaRequest_QuotaParams{} } func (*QuotaRequest_QuotaParams) ProtoMessage() {} func (*QuotaRequest_QuotaParams) Descriptor() ([]byte, []int) { return fileDescriptor_f07acf62b4429357, []int{0, 0} } func (m *QuotaRequest_QuotaParams) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QuotaRequest_QuotaParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QuotaRequest_QuotaParams.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QuotaRequest_QuotaParams) XXX_Merge(src proto.Message) { xxx_messageInfo_QuotaRequest_QuotaParams.Merge(m, src) } func (m *QuotaRequest_QuotaParams) XXX_Size() int { return m.Size() } func (m *QuotaRequest_QuotaParams) XXX_DiscardUnknown() { xxx_messageInfo_QuotaRequest_QuotaParams.DiscardUnknown(m) } var xxx_messageInfo_QuotaRequest_QuotaParams proto.InternalMessageInfo // Expresses the result of multiple quota allocations. type QuotaResult struct { // The resulting quota, one entry per requested quota. Quotas map[string]QuotaResult_Result `protobuf:"bytes,1,rep,name=quotas,proto3" json:"quotas" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } func (m *QuotaResult) Reset() { *m = QuotaResult{} } func (*QuotaResult) ProtoMessage() {} func (*QuotaResult) Descriptor() ([]byte, []int) { return fileDescriptor_f07acf62b4429357, []int{1} } func (m *QuotaResult) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QuotaResult) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QuotaResult.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QuotaResult) XXX_Merge(src proto.Message) { xxx_messageInfo_QuotaResult.Merge(m, src) } func (m *QuotaResult) XXX_Size() int { return m.Size() } func (m *QuotaResult) XXX_DiscardUnknown() { xxx_messageInfo_QuotaResult.DiscardUnknown(m) } var xxx_messageInfo_QuotaResult proto.InternalMessageInfo // Expresses the result of a quota allocation. type QuotaResult_Result struct { // The amount of time for which this result can be considered valid. ValidDuration time.Duration `protobuf:"bytes,2,opt,name=valid_duration,json=validDuration,proto3,stdduration" json:"valid_duration"` // The amount of granted quota. When `QuotaParams.best_effort` is true, this will be >= 0. // If `QuotaParams.best_effort` is false, this will be either 0 or >= `QuotaParams.amount`. GrantedAmount int64 `protobuf:"varint,3,opt,name=granted_amount,json=grantedAmount,proto3" json:"granted_amount,omitempty"` // A status code of OK indicates quota was fetched successfully. Any other code indicates error in fetching quota. Status rpc.Status `protobuf:"bytes,4,opt,name=status,proto3" json:"status"` } func (m *QuotaResult_Result) Reset() { *m = QuotaResult_Result{} } func (*QuotaResult_Result) ProtoMessage() {} func (*QuotaResult_Result) Descriptor() ([]byte, []int) { return fileDescriptor_f07acf62b4429357, []int{1, 0} } func (m *QuotaResult_Result) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *QuotaResult_Result) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QuotaResult_Result.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } } func (m *QuotaResult_Result) XXX_Merge(src proto.Message) { xxx_messageInfo_QuotaResult_Result.Merge(m, src) } func (m *QuotaResult_Result) XXX_Size() int { return m.Size() } func (m *QuotaResult_Result) XXX_DiscardUnknown() { xxx_messageInfo_QuotaResult_Result.DiscardUnknown(m) } var xxx_messageInfo_QuotaResult_Result proto.InternalMessageInfo func init() { proto.RegisterType((*QuotaRequest)(nil), "istio.mixer.adapter.model.v1beta1.QuotaRequest") proto.RegisterMapType((map[string]QuotaRequest_QuotaParams)(nil), "istio.mixer.adapter.model.v1beta1.QuotaRequest.QuotasEntry") proto.RegisterType((*QuotaRequest_QuotaParams)(nil), "istio.mixer.adapter.model.v1beta1.QuotaRequest.QuotaParams") proto.RegisterType((*QuotaResult)(nil), "istio.mixer.adapter.model.v1beta1.QuotaResult") proto.RegisterMapType((map[string]QuotaResult_Result)(nil), "istio.mixer.adapter.model.v1beta1.QuotaResult.QuotasEntry") proto.RegisterType((*QuotaResult_Result)(nil), "istio.mixer.adapter.model.v1beta1.QuotaResult.Result") } func init() { proto.RegisterFile("mixer/adapter/model/v1beta1/quota.proto", fileDescriptor_f07acf62b4429357) } var fileDescriptor_f07acf62b4429357 = []byte{ // 485 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x53, 0x31, 0x6f, 0x13, 0x31, 0x18, 0xb5, 0x73, 0xe5, 0x54, 0x1c, 0x5a, 0x21, 0x0b, 0x41, 0xb8, 0xc1, 0x09, 0x95, 0x10, 0x99, 0x6c, 0x0a, 0x42, 0x42, 0x65, 0x22, 0xa2, 0x0c, 0xb0, 0xd0, 0x63, 0x01, 0x96, 0xc8, 0xd7, 0x73, 0x4e, 0x27, 0x2e, 0xf1, 0xd5, 0xf6, 0x45, 0x74, 0x63, 0x65, 0x63, 0xe4, 0x27, 0xc0, 0xc0, 0xff, 0xc8, 0x98, 0xb1, 0x13, 0x90, 0xcb, 0xc2, 0xd8, 0x9f, 0x80, 0xce, 0xf6, 0x49, 0x85, 0xa1, 0x05, 0xa6, 0xd8, 0xdf, 0xf7, 0xbe, 0xf7, 0x3e, 0xbf, 0x97, 0x43, 0x77, 0xa6, 0xf9, 0x3b, 0xa1, 0x18, 0x4f, 0x79, 0x69, 0x84, 0x62, 0x53, 0x99, 0x8a, 0x82, 0xcd, 0x77, 0x13, 0x61, 0xf8, 0x2e, 0x3b, 0xaa, 0xa4, 0xe1, 0xb4, 0x54, 0xd2, 0x48, 0x7c, 0x2b, 0xd7, 0x26, 0x97, 0xd4, 0xc2, 0xa9, 0x87, 0x53, 0x0b, 0xa7, 0x1e, 0x1e, 0x5d, 0xcb, 0x64, 0x26, 0x2d, 0x9a, 0x35, 0x27, 0x37, 0x18, 0x91, 0x4c, 0xca, 0xac, 0x10, 0xcc, 0xde, 0x92, 0x6a, 0xc2, 0xd2, 0x4a, 0x71, 0x93, 0xcb, 0x99, 0xef, 0xdf, 0xf0, 0x7d, 0x55, 0x1e, 0x32, 0x6d, 0xb8, 0xa9, 0xb4, 0x6b, 0xec, 0x7c, 0xe9, 0xa0, 0x2b, 0x07, 0xcd, 0x06, 0xb1, 0x38, 0xaa, 0x84, 0x36, 0xf8, 0x35, 0x0a, 0xed, 0x46, 0xba, 0x07, 0x07, 0xc1, 0xb0, 0x7b, 0xef, 0x11, 0xbd, 0x70, 0x27, 0x7a, 0x96, 0xc0, 0x5d, 0xf4, 0xfe, 0xcc, 0xa8, 0xe3, 0xd1, 0xc6, 0xe2, 0x5b, 0x1f, 0xc4, 0x9e, 0x30, 0x7a, 0x8a, 0xba, 0xb6, 0xf9, 0x82, 0x2b, 0x3e, 0xd5, 0xf8, 0x3a, 0x0a, 0xf9, 0x54, 0x56, 0x33, 0xd3, 0x83, 0x03, 0x38, 0x0c, 0x62, 0x7f, 0xc3, 0x7d, 0xd4, 0x4d, 0x84, 0x36, 0x63, 0x31, 0x99, 0x48, 0x65, 0x7a, 0x9d, 0x01, 0x1c, 0x6e, 0xc6, 0xa8, 0x29, 0xed, 0xdb, 0x4a, 0x34, 0xf7, 0x3c, 0x4e, 0x04, 0x5f, 0x45, 0xc1, 0x5b, 0x71, 0x6c, 0x49, 0x2e, 0xc7, 0xcd, 0x11, 0x1f, 0xa0, 0x4b, 0x73, 0x5e, 0x54, 0xc2, 0xce, 0xfe, 0xef, 0x13, 0xdc, 0x96, 0xb1, 0x63, 0xda, 0xeb, 0x3c, 0x84, 0x3b, 0x1f, 0x02, 0x2f, 0x1c, 0x0b, 0x5d, 0x15, 0x06, 0xbf, 0xfa, 0xc3, 0xaa, 0xbd, 0xbf, 0xd7, 0x69, 0xe6, 0xcf, 0x71, 0xea, 0x2b, 0x44, 0xa1, 0x17, 0x79, 0x86, 0xb6, 0xe7, 0xbc, 0xc8, 0xd3, 0x71, 0x9b, 0xa8, 0x7f, 0xd4, 0x4d, 0xea, 0x22, 0xa5, 0x6d, 0xe4, 0xf4, 0x89, 0x07, 0x8c, 0x36, 0x1b, 0xae, 0x4f, 0xdf, 0xfb, 0x30, 0xde, 0xb2, 0xa3, 0x6d, 0x03, 0xdf, 0x46, 0xdb, 0x99, 0xe2, 0x33, 0x23, 0xd2, 0xb1, 0x77, 0x3e, 0xb0, 0xce, 0x6f, 0xf9, 0xea, 0x63, 0x17, 0xc0, 0x5d, 0x14, 0xba, 0xff, 0x48, 0x6f, 0xc3, 0x4a, 0xe1, 0x56, 0x4a, 0x95, 0x87, 0xf4, 0xa5, 0xed, 0xb4, 0xfb, 0x3a, 0x5c, 0x54, 0x5e, 0x94, 0xc8, 0xf3, 0xdf, 0x13, 0x79, 0xf0, 0x8f, 0x4e, 0xb9, 0x9f, 0x33, 0x59, 0x8c, 0x92, 0xc5, 0x8a, 0x80, 0xe5, 0x8a, 0x80, 0x93, 0x15, 0x01, 0xa7, 0x2b, 0x02, 0xde, 0xd7, 0x04, 0x7e, 0xae, 0x09, 0x58, 0xd4, 0x04, 0x2e, 0x6b, 0x02, 0x7f, 0xd4, 0x04, 0xfe, 0xac, 0x09, 0x38, 0xad, 0x09, 0xfc, 0xb8, 0x26, 0x60, 0xb9, 0x26, 0xe0, 0x64, 0x4d, 0xc0, 0x9b, 0xa1, 0x93, 0xce, 0x25, 0xe3, 0x65, 0xce, 0xce, 0xf9, 0x32, 0x93, 0xd0, 0x5a, 0x7b, 0xff, 0x57, 0x00, 0x00, 0x00, 0xff, 0xff, 0x6c, 0xcd, 0xf9, 0x75, 0xbf, 0x03, 0x00, 0x00, } func (m *QuotaRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QuotaRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QuotaRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Quotas) > 0 { for k := range m.Quotas { v := m.Quotas[k] baseI := i { size, err := (&v).MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuota(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 i -= len(k) copy(dAtA[i:], k) i = encodeVarintQuota(dAtA, i, uint64(len(k))) i-- dAtA[i] = 0xa i = encodeVarintQuota(dAtA, i, uint64(baseI-i)) i-- dAtA[i] = 0xa } } return len(dAtA) - i, nil } func (m *QuotaRequest_QuotaParams) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QuotaRequest_QuotaParams) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QuotaRequest_QuotaParams) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if m.BestEffort { i-- if m.BestEffort { dAtA[i] = 1 } else { dAtA[i] = 0 } i-- dAtA[i] = 0x10 } if m.Amount != 0 { i = encodeVarintQuota(dAtA, i, uint64(m.Amount)) i-- dAtA[i] = 0x8 } return len(dAtA) - i, nil } func (m *QuotaResult) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QuotaResult) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QuotaResult) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l if len(m.Quotas) > 0 { for k := range m.Quotas { v := m.Quotas[k] baseI := i { size, err := (&v).MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuota(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x12 i -= len(k) copy(dAtA[i:], k) i = encodeVarintQuota(dAtA, i, uint64(len(k))) i-- dAtA[i] = 0xa i = encodeVarintQuota(dAtA, i, uint64(baseI-i)) i-- dAtA[i] = 0xa } } return len(dAtA) - i, nil } func (m *QuotaResult_Result) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) if err != nil { return nil, err } return dAtA[:n], nil } func (m *QuotaResult_Result) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *QuotaResult_Result) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l { size, err := m.Status.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } i -= size i = encodeVarintQuota(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x22 if m.GrantedAmount != 0 { i = encodeVarintQuota(dAtA, i, uint64(m.GrantedAmount)) i-- dAtA[i] = 0x18 } n4, err4 := github_com_gogo_protobuf_types.StdDurationMarshalTo(m.ValidDuration, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdDuration(m.ValidDuration):]) if err4 != nil { return 0, err4 } i -= n4 i = encodeVarintQuota(dAtA, i, uint64(n4)) i-- dAtA[i] = 0x12 return len(dAtA) - i, nil } func encodeVarintQuota(dAtA []byte, offset int, v uint64) int { offset -= sovQuota(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return base } func (m *QuotaRequest) Size() (n int) { if m == nil { return 0 } var l int _ = l if len(m.Quotas) > 0 { for k, v := range m.Quotas { _ = k _ = v l = v.Size() mapEntrySize := 1 + len(k) + sovQuota(uint64(len(k))) + 1 + l + sovQuota(uint64(l)) n += mapEntrySize + 1 + sovQuota(uint64(mapEntrySize)) } } return n } func (m *QuotaRequest_QuotaParams) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.Amount != 0 { n += 1 + sovQuota(uint64(m.Amount)) } if m.BestEffort { n += 2 } return n } func (m *QuotaResult) Size() (n int) { if m == nil { return 0 } var l int _ = l if len(m.Quotas) > 0 { for k, v := range m.Quotas { _ = k _ = v l = v.Size() mapEntrySize := 1 + len(k) + sovQuota(uint64(len(k))) + 1 + l + sovQuota(uint64(l)) n += mapEntrySize + 1 + sovQuota(uint64(mapEntrySize)) } } return n } func (m *QuotaResult_Result) Size() (n int) { if m == nil { return 0 } var l int _ = l l = github_com_gogo_protobuf_types.SizeOfStdDuration(m.ValidDuration) n += 1 + l + sovQuota(uint64(l)) if m.GrantedAmount != 0 { n += 1 + sovQuota(uint64(m.GrantedAmount)) } l = m.Status.Size() n += 1 + l + sovQuota(uint64(l)) return n } func sovQuota(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozQuota(x uint64) (n int) { return sovQuota(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (this *QuotaRequest) String() string { if this == nil { return "nil" } keysForQuotas := make([]string, 0, len(this.Quotas)) for k, _ := range this.Quotas { keysForQuotas = append(keysForQuotas, k) } github_com_gogo_protobuf_sortkeys.Strings(keysForQuotas) mapStringForQuotas := "map[string]QuotaRequest_QuotaParams{" for _, k := range keysForQuotas { mapStringForQuotas += fmt.Sprintf("%v: %v,", k, this.Quotas[k]) } mapStringForQuotas += "}" s := strings.Join([]string{`&QuotaRequest{`, `Quotas:` + mapStringForQuotas + `,`, `}`, }, "") return s } func (this *QuotaRequest_QuotaParams) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&QuotaRequest_QuotaParams{`, `Amount:` + fmt.Sprintf("%v", this.Amount) + `,`, `BestEffort:` + fmt.Sprintf("%v", this.BestEffort) + `,`, `}`, }, "") return s } func (this *QuotaResult) String() string { if this == nil { return "nil" } keysForQuotas := make([]string, 0, len(this.Quotas)) for k, _ := range this.Quotas { keysForQuotas = append(keysForQuotas, k) } github_com_gogo_protobuf_sortkeys.Strings(keysForQuotas) mapStringForQuotas := "map[string]QuotaResult_Result{" for _, k := range keysForQuotas { mapStringForQuotas += fmt.Sprintf("%v: %v,", k, this.Quotas[k]) } mapStringForQuotas += "}" s := strings.Join([]string{`&QuotaResult{`, `Quotas:` + mapStringForQuotas + `,`, `}`, }, "") return s } func (this *QuotaResult_Result) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&QuotaResult_Result{`, `ValidDuration:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ValidDuration), "Duration", "types.Duration", 1), `&`, ``, 1) + `,`, `GrantedAmount:` + fmt.Sprintf("%v", this.GrantedAmount) + `,`, `Status:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Status), "Status", "rpc.Status", 1), `&`, ``, 1) + `,`, `}`, }, "") return s } func valueToStringQuota(v interface{}) string { rv := reflect.ValueOf(v) if rv.IsNil() { return "nil" } pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("*%v", pv) } func (m *QuotaRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuota } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QuotaRequest: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QuotaRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Quotas", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuota } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuota } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuota } if postIndex > l { return io.ErrUnexpectedEOF } if m.Quotas == nil { m.Quotas = make(map[string]QuotaRequest_QuotaParams) } var mapkey string mapvalue := &QuotaRequest_QuotaParams{} for iNdEx < postIndex { entryPreIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuota } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) if fieldNum == 1 { var stringLenmapkey uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuota } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLenmapkey |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLenmapkey := int(stringLenmapkey) if intStringLenmapkey < 0 { return ErrInvalidLengthQuota } postStringIndexmapkey := iNdEx + intStringLenmapkey if postStringIndexmapkey < 0 { return ErrInvalidLengthQuota } if postStringIndexmapkey > l { return io.ErrUnexpectedEOF } mapkey = string(dAtA[iNdEx:postStringIndexmapkey]) iNdEx = postStringIndexmapkey } else if fieldNum == 2 { var mapmsglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuota } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ mapmsglen |= int(b&0x7F) << shift if b < 0x80 { break } } if mapmsglen < 0 { return ErrInvalidLengthQuota } postmsgIndex := iNdEx + mapmsglen if postmsgIndex < 0 { return ErrInvalidLengthQuota } if postmsgIndex > l { return io.ErrUnexpectedEOF } mapvalue = &QuotaRequest_QuotaParams{} if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { return err } iNdEx = postmsgIndex } else { iNdEx = entryPreIndex skippy, err := skipQuota(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthQuota } if (iNdEx + skippy) > postIndex { return io.ErrUnexpectedEOF } iNdEx += skippy } } m.Quotas[mapkey] = *mapvalue iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuota(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthQuota } if (iNdEx + skippy) < 0 { return ErrInvalidLengthQuota } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QuotaRequest_QuotaParams) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuota } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QuotaParams: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QuotaParams: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) } m.Amount = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuota } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Amount |= int64(b&0x7F) << shift if b < 0x80 { break } } case 2: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field BestEffort", wireType) } var v int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuota } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= int(b&0x7F) << shift if b < 0x80 { break } } m.BestEffort = bool(v != 0) default: iNdEx = preIndex skippy, err := skipQuota(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthQuota } if (iNdEx + skippy) < 0 { return ErrInvalidLengthQuota } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QuotaResult) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuota } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: QuotaResult: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: QuotaResult: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Quotas", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuota } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuota } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuota } if postIndex > l { return io.ErrUnexpectedEOF } if m.Quotas == nil { m.Quotas = make(map[string]QuotaResult_Result) } var mapkey string mapvalue := &QuotaResult_Result{} for iNdEx < postIndex { entryPreIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuota } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) if fieldNum == 1 { var stringLenmapkey uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuota } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLenmapkey |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLenmapkey := int(stringLenmapkey) if intStringLenmapkey < 0 { return ErrInvalidLengthQuota } postStringIndexmapkey := iNdEx + intStringLenmapkey if postStringIndexmapkey < 0 { return ErrInvalidLengthQuota } if postStringIndexmapkey > l { return io.ErrUnexpectedEOF } mapkey = string(dAtA[iNdEx:postStringIndexmapkey]) iNdEx = postStringIndexmapkey } else if fieldNum == 2 { var mapmsglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuota } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ mapmsglen |= int(b&0x7F) << shift if b < 0x80 { break } } if mapmsglen < 0 { return ErrInvalidLengthQuota } postmsgIndex := iNdEx + mapmsglen if postmsgIndex < 0 { return ErrInvalidLengthQuota } if postmsgIndex > l { return io.ErrUnexpectedEOF } mapvalue = &QuotaResult_Result{} if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { return err } iNdEx = postmsgIndex } else { iNdEx = entryPreIndex skippy, err := skipQuota(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthQuota } if (iNdEx + skippy) > postIndex { return io.ErrUnexpectedEOF } iNdEx += skippy } } m.Quotas[mapkey] = *mapvalue iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuota(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthQuota } if (iNdEx + skippy) < 0 { return ErrInvalidLengthQuota } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *QuotaResult_Result) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuota } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Result: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Result: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ValidDuration", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuota } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuota } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuota } if postIndex > l { return io.ErrUnexpectedEOF } if err := github_com_gogo_protobuf_types.StdDurationUnmarshal(&m.ValidDuration, dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 3: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field GrantedAmount", wireType) } m.GrantedAmount = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuota } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.GrantedAmount |= int64(b&0x7F) << shift if b < 0x80 { break } } case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowQuota } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthQuota } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthQuota } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuota(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthQuota } if (iNdEx + skippy) < 0 { return ErrInvalidLengthQuota } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipQuota(dAtA []byte) (n int, err error)
var ( ErrInvalidLengthQuota = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowQuota = fmt.Errorf("proto: integer overflow") )
{ l := len(dAtA) iNdEx := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowQuota } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowQuota } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } return iNdEx, nil case 1: iNdEx += 8 return iNdEx, nil case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowQuota } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthQuota } iNdEx += length if iNdEx < 0 { return 0, ErrInvalidLengthQuota } return iNdEx, nil case 3: for { var innerWire uint64 var start int = iNdEx for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowQuota } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ innerWire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } innerWireType := int(innerWire & 0x7) if innerWireType == 4 { break } next, err := skipQuota(dAtA[start:]) if err != nil { return 0, err } iNdEx = start + next if iNdEx < 0 { return 0, ErrInvalidLengthQuota } } return iNdEx, nil case 4: return iNdEx, nil case 5: iNdEx += 4 return iNdEx, nil default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } } panic("unreachable") }
url.go
package httptoo import ( "net/http" "net/url" ) // Deep copies a URL. func
(u *url.URL) (ret *url.URL) { ret = new(url.URL) *ret = *u if u.User != nil { ret.User = new(url.Userinfo) *ret.User = *u.User } return } // Reconstructs the URL that would have produced the given Request. // Request.URLs are not fully populated in http.Server handlers. func RequestedURL(r *http.Request) (ret *url.URL) { ret = CopyURL(r.URL) ret.Host = r.Host ret.Scheme = OriginatingProtocol(r) return }
CopyURL
gulp-tdd.js
import gulp from 'gulp'; import { Server } from 'karma'; import config from './config'; gulp.task('tdd', done => { new Server({ configFile: config.karmaConfigPath
}, done).start(); });
gatsby-node_20200609234658.js
exports.createPages = async ({ actions, graphql, reporter }) => {
const result = await graphql(` query { allDatoCmsArticle { edges { node { id } } } } `) if (result.errors) { reporter.panic('filed to create posts', result.error) } const posts = result.data.allDatoCmsArticle.edges posts.forEach(post => { actions.createPage({ path: post.node.id, // component: ?? context: { id: post.node.id, }, }) }) }
client.go
package mtss import ( "bytes" "context" "crypto/tls" "fmt" "io" "io/ioutil" "log" "net/http" "net/http/httputil"
"github.com/piqba/mtss-go/pkg/errors" ) const ( // OFFERS are the path that show all jobs on the API OFFERS = "necesidades" // URL_BASE are the url for the jobs endpoints URL_BASE = "https://apiempleo.xutil.net/apiempleo" ) // Client is an interface that implements Mtss's API type Client interface { // MtssJobs returns the corresponding jobs on fetch call, or an error. MtssJobs( ctx context.Context, ) ([]Mtss, error) } // Client // client represents a Mtss client. If the Debug field is set to an io.Writer // (for example os.Stdout), then the client will dump API requests and responses // to it. To use a non-default HTTP client (for example, for testing, or to set // a timeout), assign to the HTTPClient field. To set a non-default URL (for // example, for testing), assign to the URL field. type client struct { url string httpClient *http.Client debug io.Writer } func NewAPIClient( // mtss API's base url baseURL string, // skipVerify skipVerify bool, //optional, defaults to http.DefaultClient httpClient *http.Client, debug io.Writer, ) Client { c := &client{ url: baseURL, httpClient: httpClient, debug: debug, } if httpClient != nil { c.httpClient = httpClient } else { c.httpClient = http.DefaultClient } if skipVerify { tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } c.httpClient.Transport = tr } return c } // dumpResponse writes the raw response data to the debug output, if set, or // standard error otherwise. func (c *client) dumpResponse(resp *http.Response) { // ignore errors dumping response - no recovery from this responseDump, err := httputil.DumpResponse(resp, true) if err != nil { log.Fatalf("mtss/clientHttp: dumpResponse: " + err.Error()) } fmt.Fprintln(c.debug, string(responseDump)) fmt.Fprintln(c.debug) } // apiCall define how you can make a call to Mtss API func (c *client) apiCall( ctx context.Context, method string, URL string, data []byte, ) (statusCode int, response string, err error) { requestURL := c.url + "/" + URL req, err := http.NewRequest(method, requestURL, bytes.NewBuffer(data)) if err != nil { return 0, "", fmt.Errorf("mtss/clientHttp: failed to create HTTP request: %v", err) } req.Header.Add("content-type", "application/json") req.Header.Set("User-Agent", "mtssgo-client/0.0") if c.debug != nil { requestDump, err := httputil.DumpRequestOut(req, true) if err != nil { return 0, "", errors.Errorf("mtss/clientHttp: error dumping HTTP request: %v", err) } fmt.Fprintln(c.debug, string(requestDump)) fmt.Fprintln(c.debug) } req = req.WithContext(ctx) resp, err := c.httpClient.Do(req) if err != nil { return 0, "", errors.Errorf("mtss/clientHttp: HTTP request failed with: %v", err) } defer resp.Body.Close() if c.debug != nil { c.dumpResponse(resp) } res, err := ioutil.ReadAll(resp.Body) if err != nil { return resp.StatusCode, "", errors.Errorf("mtss/clientHttp: HTTP request failed: %v", err) } return resp.StatusCode, string(res), nil }
create-data-asset-from-oracle.ts
/** * Data Integration API * Use the Data Integration API to organize your data integration projects, create data flows, pipelines and tasks, and then publish, schedule, and run tasks that extract, transform, and load data. For more information, see [Data Integration](https://docs.oracle.com/iaas/data-integration/home.htm). * OpenAPI spec version: 20200430 * Contact: [email protected] * * NOTE: This class is auto generated by OracleSDKGenerator. * Do not edit the class manually. * * Copyright (c) 2020, 2022, Oracle and/or its affiliates. All rights reserved. * This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. */ import * as model from "../model"; import common = require("oci-common"); /** * Details for the Oracle Database data asset type. */ export interface CreateDataAssetFromOracle extends model.CreateDataAssetDetails { /** * The Oracle Database hostname. */ "host"?: string; /** * The Oracle Database port. */ "port"?: string; /** * The service name for the data asset. */ "serviceName"?: string; /** * The Oracle Database driver class. */ "driverClass"?: string; /** * The Oracle Database SID. */ "sid"?: string; /** * The credential file content from a wallet for the data asset. */ "credentialFileContent"?: string; "walletSecret"?: model.SensitiveAttribute; "walletPasswordSecret"?: model.SensitiveAttribute; "defaultConnection"?: model.CreateConnectionFromOracle;
"modelType": string; } export namespace CreateDataAssetFromOracle { export function getJsonObj(obj: CreateDataAssetFromOracle, isParentJsonObj?: boolean): object { const jsonObj = { ...(isParentJsonObj ? obj : (model.CreateDataAssetDetails.getJsonObj(obj) as CreateDataAssetFromOracle)), ...{ "walletSecret": obj.walletSecret ? model.SensitiveAttribute.getJsonObj(obj.walletSecret) : undefined, "walletPasswordSecret": obj.walletPasswordSecret ? model.SensitiveAttribute.getJsonObj(obj.walletPasswordSecret) : undefined, "defaultConnection": obj.defaultConnection ? model.CreateConnectionFromOracle.getJsonObj(obj.defaultConnection) : undefined } }; return jsonObj; } export const modelType = "ORACLE_DATA_ASSET"; export function getDeserializedJsonObj( obj: CreateDataAssetFromOracle, isParentJsonObj?: boolean ): object { const jsonObj = { ...(isParentJsonObj ? obj : (model.CreateDataAssetDetails.getDeserializedJsonObj(obj) as CreateDataAssetFromOracle)), ...{ "walletSecret": obj.walletSecret ? model.SensitiveAttribute.getDeserializedJsonObj(obj.walletSecret) : undefined, "walletPasswordSecret": obj.walletPasswordSecret ? model.SensitiveAttribute.getDeserializedJsonObj(obj.walletPasswordSecret) : undefined, "defaultConnection": obj.defaultConnection ? model.CreateConnectionFromOracle.getDeserializedJsonObj(obj.defaultConnection) : undefined } }; return jsonObj; } }
formate_and_string.py
# -*- coding: utf-8 -*- """ Created on Tue Oct 13 20:12:58 2020 @author: ninjaac """ #############using the formate function def print_full_name(a, b): print("Hello {a} {b} ! You just delved into python.")
print_full_name(first_name, last_name) ####### change the string using the list def mutate_string(string, position, character): a=list(string) a.insert(position,character) a.pop(position+1) return ''.join(a) if __name__ == '__main__': s = input() i, c = input().split() s_new = mutate_string(s, int(i), c) print(s_new)
if __name__ == '__main__': first_name = input() last_name = input()
test_encoding_charset.py
# -*- coding: utf-8 -*- ########################################################################## # # pgAdmin 4 - PostgreSQL Tools # # Copyright (C) 2013 - 2020, The pgAdmin Development Team # This software is released under the PostgreSQL Licence # ########################################################################## from pgadmin.utils.route import BaseTestGenerator from pgadmin.browser.server_groups.servers.databases.tests import utils as \ database_utils from regression.python_test_utils import test_utils import json from pgadmin.utils import server_utils import random class
(BaseTestGenerator): """ This class validates character support in pgAdmin4 for different PostgresDB encodings """ skip_on_database = ['gpdb'] scenarios = [ ( 'With Encoding UTF8', dict( db_encoding='UTF8', lc_collate='C', test_str='A' )), ( 'With Encoding EUC_CN', dict( db_encoding='EUC_CN', lc_collate='C', test_str='A' )), ( 'With Encoding SQL_ASCII', dict( db_encoding='SQL_ASCII', lc_collate='C', test_str='Tif' )), ( 'With Encoding LATIN1', dict( db_encoding='LATIN1', lc_collate='C', test_str='äöüßÑ' )), ( 'With Encoding LATIN2', dict( db_encoding='LATIN2', lc_collate='C', test_str='§' )), ( 'With Encoding LATIN9', dict( db_encoding='LATIN9', lc_collate='C', test_str='äöüß' )), ( 'With Encoding EUC_JIS_2004', dict( db_encoding='EUC_JIS_2004', lc_collate='C', test_str='じんぼはりんごをたべる' )), ( 'With Encoding WIN1256', dict( db_encoding='WIN1256', lc_collate='C', test_str='صباح الخير' )), ( 'With Encoding WIN866', dict( db_encoding='WIN866', lc_collate='C', test_str='Альтернативная' )), ( 'With Encoding WIN874', dict( db_encoding='WIN874', lc_collate='C', test_str='กลิ่นหอม' )), ( 'With Encoding WIN1250', dict( db_encoding='WIN1250', lc_collate='C', test_str='ŔÁÄÇ' )), ( 'With Encoding WIN1251', dict( db_encoding='WIN1251', lc_collate='C', test_str='ЖИЙЮ' )), ( 'With Encoding WIN1252', dict( db_encoding='WIN1252', lc_collate='C', test_str='ÆØÙü' )), ( 'With Encoding WIN1253', dict( db_encoding='WIN1253', lc_collate='C', test_str='ΨΪμΫ' )), ( 'With Encoding WIN1254', dict( db_encoding='WIN1254', lc_collate='C', test_str='ĞğØŠ' )), ( 'With Encoding WIN1255', dict( db_encoding='WIN1255', lc_collate='C', test_str='₪¥©¾' )), ( 'With Encoding WIN1256', dict( db_encoding='WIN1256', lc_collate='C', test_str='بؤغق' )), ( 'With Encoding WIN1257', dict( db_encoding='WIN1257', lc_collate='C', test_str='‰ķģž' )), ( 'With Encoding WIN1258', dict( db_encoding='WIN1258', lc_collate='C', test_str='₫SHYÑđ' )), ( 'With Encoding EUC_CN', dict( db_encoding='EUC_CN', lc_collate='C', test_str='汉字不灭' )), ( 'With Encoding EUC_JP', dict( db_encoding='EUC_JP', lc_collate='C', test_str='での日本' )), ( 'With Encoding EUC_KR', dict( db_encoding='EUC_KR', lc_collate='C', test_str='ㄱㄲㄴㄷ' )), ( 'With Encoding EUC_TW', dict( db_encoding='EUC_TW', lc_collate='C', test_str='中文' )), ( 'With Encoding ISO_8859_5', dict( db_encoding='ISO_8859_5', lc_collate='C', test_str='ЁЎФЮ' )), ( 'With Encoding ISO_8859_6', dict( db_encoding='ISO_8859_6', lc_collate='C', test_str='العَرَبِيَّة' )), ( 'With Encoding ISO_8859_7', dict( db_encoding='ISO_8859_7', lc_collate='C', test_str='ελληνικά' )), ( 'With Encoding ISO_8859_8', dict( db_encoding='ISO_8859_8', lc_collate='C', test_str='דבא' )), ( 'With Encoding KOI8R', dict( db_encoding='KOI8R', lc_collate='C', test_str='Альтернативная' )), ( 'With Encoding KOI8U', dict( db_encoding='KOI8U', lc_collate='C', test_str='українська' )), ] def setUp(self): self.encode_db_name = 'encoding_' + self.db_encoding + \ str(random.randint(10000, 65535)) self.encode_sid = self.server_information['server_id'] server_con = server_utils.connect_server(self, self.encode_sid) if hasattr(self, 'skip_on_database'): if 'data' in server_con and 'type' in server_con['data']: if server_con['data']['type'] in self.skip_on_database: self.skipTest('cannot run in: %s' % server_con['data']['type']) self.encode_did = test_utils.create_database( self.server, self.encode_db_name, (self.db_encoding, self.lc_collate)) def runTest(self): db_con = database_utils.connect_database(self, test_utils.SERVER_GROUP, self.encode_sid, self.encode_did) if not db_con["info"] == "Database connected.": raise Exception("Could not connect to the database.") # Initialize query tool self.trans_id = str(random.randint(1, 9999999)) url = '/datagrid/initialize/query_tool/{0}/{1}/{2}/{3}'\ .format(self.trans_id, test_utils.SERVER_GROUP, self.encode_sid, self.encode_did) response = self.tester.post(url) self.assertEqual(response.status_code, 200) # Check character url = "/sqleditor/query_tool/start/{0}".format(self.trans_id) sql = "select E'{0}';".format(self.test_str) response = self.tester.post(url, data=json.dumps({"sql": sql}), content_type='html/json') self.assertEqual(response.status_code, 200) url = '/sqleditor/poll/{0}'.format(self.trans_id) response = self.tester.get(url) self.assertEqual(response.status_code, 200) response_data = json.loads(response.data.decode('utf-8')) self.assertEqual(response_data['data']['rows_fetched_to'], 1) result = response_data['data']['result'][0][0] self.assertEqual(result, self.test_str) database_utils.disconnect_database(self, self.encode_sid, self.encode_did) def tearDown(self): main_conn = test_utils.get_db_connection( self.server['db'], self.server['username'], self.server['db_password'], self.server['host'], self.server['port'], self.server['sslmode'] ) test_utils.drop_database(main_conn, self.encode_db_name)
TestEncodingCharset
parser.go
package chunkserver import ( "bufio" "bytes" "encoding/binary" "fmt" "io" ) type Resp struct { Type int8 Len int32 Data []byte } const ( HEADERSIZE = 6 ) func ReadHeader(r *bufio.Reader) (*Resp, error) { var header []byte = make([]byte, HEADERSIZE) _, err := io.ReadFull(r, header) if err != nil { return nil, err } typeBuf := bytes.NewBuffer(header[0:1]) lenBuf := bytes.NewBuffer(header[1:HEADERSIZE]) var t int8 var len int32 err = binary.Read(typeBuf, binary.BigEndian, &t) if err != nil { return nil, err } err = binary.Read(lenBuf, binary.BigEndian, &len) if err != nil { return nil, err } var data []byte = make([]byte, len) if data == nil { return nil, fmt.Errorf("malloc %s B error", len) } resp := &Resp{ Type: t, Len: len, Data: data, } return resp, nil } func
(r *bufio.Reader) (*Resp, error) { resp, err := ReadHeader(r) if err != nil { return nil, err } _, err = io.ReadFull(r, resp.Data) if err != nil { return nil, err } return resp, nil } func (r *Resp) Bytes() ([]byte, error) { return nil, nil }
Parse
purge.ts
import { IBot, IBotCommand, IBotCommandHelp, IBotMessage, IBotConfig } from '../api' import { getRandomInt } from '../utils' import * as discord from 'discord.js' export default class PurgeCommand implements IBotCommand { private readonly CMD_REGEXP = /^\?purge/im public getHelp(): IBotCommandHelp { return { caption: '?purge', description: 'ADMIN ONLY - (?purge [@user] [number of message to delete]) Bulk delete a number of this user\'s messages from the channel' } } public init(bot: IBot, dataPath: string): void { } public isValid(msg: string): boolean { return this.CMD_REGEXP.test(msg) } public async process(msg: string, answer: IBotMessage, msgObj: discord.Message, client: discord.Client, config: IBotConfig, commands: IBotCommand[]): Promise<void> { msgObj.delete(0); if(!msgObj.member.hasPermission("MANAGE_MESSAGES")) { return; } let purgedUser = msgObj.guild.member(msgObj.mentions.users.first());
} if(purgedUser.hasPermission("MANAGE_MESSAGES")) { return; } let words = msg.split(' '); let amount = parseInt(words.slice(2).join(' ')); if(isNaN(amount)) { return; } msgObj.channel.bulkDelete(amount) .then(messages => console.log(`Bulk deleted ${messages.size} messages`)) .catch(console.error) } }
if(!purgedUser) { return;
transitionelement.js
/** * @preserve Copyright (c) 2013 British Broadcasting Corporation * (http://www.bbc.co.uk) and TAL Contributors (1) * * (1) TAL Contributors are listed in the AUTHORS file and at * https://github.com/fmtvp/TAL/AUTHORS - please extend this file, * not this notice. * * @license 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. * * All rights reserved * Please contact us for an alternative licence */ (function() { function loadTE(queue, fn) { queuedRequire( queue, [ 'antie/devices/anim/css3/transitionelement', 'mocks/mockelement', 'antie/devices/anim/css3/transitiondefinition' ], fn ); } function getMockTransitionDefinition(TransitionDefinition) { var transDef; transDef = new TransitionDefinition(); transDef.getProperties = function() { return ['fizz', 'buzz', 'beep']; }; transDef.getPropertyDelay = function(prop) { switch (prop) { case 'fizz': return 50; case 'buzz': return 100; case 'beep': return 0; } }; transDef.getPropertyDuration = function(prop) { switch (prop) { case 'fizz': return 0; case 'buzz': return 20; case 'beep': return 100; } }; transDef.getPropertyTimingFn = function(prop) { switch (prop) { case 'fizz': return 'linear'; case 'buzz': return 'beizer(-0.2, 1, 0, 0.5)'; case 'beep': return 'easeInOut'; } }; return transDef; } function
() { return ['', '-webkit-', '-moz-', '-o-']; } function getTransitionEndEvents() { return ['webkitTransitionEnd', 'oTransitionEnd', 'otransitionend', 'transitionend']; } function makeNewTransElAndApplyMocks(self, TransitionElement, MockElement) { var transEl, mockEl; mockEl = new MockElement(); transEl = new TransitionElement(mockEl); transEl.mockEl = mockEl; self.sandbox.spy(transEl.mockEl, 'addEventListener'); self.sandbox.spy(transEl.mockEl, 'removeEventListener'); return transEl; } this.TransitionElementTest = AsyncTestCase('TransitionElement'); this.TransitionElementTest.prototype.setUp = function() { this.sandbox = sinon.sandbox.create(); }; this.TransitionElementTest.prototype.tearDown = function() { this.sandbox.restore(); }; this.TransitionElementTest.prototype.testElementsPropertiesReturnedAsArray = function(queue) { var self = this; loadTE(queue, function(TransitionElement, MockElement) { var transEl, expected; expected = ['top', 'left', 'opacity']; transEl = makeNewTransElAndApplyMocks(self, TransitionElement, MockElement); assertEquals(expected, transEl.getProperties()); } ); }; this.TransitionElementTest.prototype.testElementsDurationsReturnedAsMsArray = function(queue) { var self = this; loadTE(queue, function(TransitionElement, MockElement) { var transEl, expected; expected = [400, 2000, 600]; transEl = makeNewTransElAndApplyMocks(self, TransitionElement, MockElement); assertEquals(expected, transEl.getDurations()); } ); }; this.TransitionElementTest.prototype.testElementsTimingFunctionsReturnedAsArray = function(queue) { var self = this; loadTE(queue, function(TransitionElement, MockElement) { var transEl, expected; expected = ['linear', 'easeInOut', 'beizer(0, .6, 0.3, -4)']; transEl = makeNewTransElAndApplyMocks(self, TransitionElement, MockElement); assertEquals(expected, transEl.getTimingFns()); } ); }; this.TransitionElementTest.prototype.testElementsDelaysReturnedAsArray = function(queue) { var self = this; loadTE(queue, function(TransitionElement, MockElement) { var transEl, expected; expected = [0, 100, 5]; transEl = makeNewTransElAndApplyMocks(self, TransitionElement, MockElement); assertEquals(expected, transEl.getDelays()); } ); }; this.TransitionElementTest.prototype.testTransisitonDefinitionApplied = function(queue) { var self = this; loadTE(queue, function(TransitionElement, MockElement, TransitionDefinition) { var transEl, transDef; var prefixes = getPrefixes(); transDef = getMockTransitionDefinition(TransitionDefinition); transEl = makeNewTransElAndApplyMocks(self, TransitionElement, MockElement); self.sandbox.spy(transEl.mockEl.style, 'setProperty'); transEl.applyDefinition(transDef); prefixes.forEach(function (prefix) { assert(transEl.mockEl.style.setProperty.calledWith(prefix + 'transition-property', 'fizz,buzz,beep')); assert(transEl.mockEl.style.setProperty.calledWith(prefix + 'transition-property', 'fizz,buzz,beep')); assert(transEl.mockEl.style.setProperty.calledWith(prefix + 'transition-delay', '50ms,100ms,0ms')); assert(transEl.mockEl.style.setProperty.calledWith(prefix + 'transition-duration', '0ms,20ms,100ms')); assert(transEl.mockEl.style.setProperty.calledWith(prefix + 'transition-timing-function', 'linear,beizer(-0.2, 1, 0, 0.5),easeInOut')); }); } ); }; this.TransitionElementTest.prototype.testSetCallbackAddsFnsAsEventListeners = function(queue) { var self = this; loadTE(queue, function(TransitionElement, MockElement) { var transEl; var transitionEndEvents = getTransitionEndEvents(); function callback() {} transEl = makeNewTransElAndApplyMocks(self, TransitionElement, MockElement); transEl.setCallback(callback); assertEquals(transitionEndEvents.length, transEl.mockEl.addEventListener.callCount); transitionEndEvents.forEach(function (transitionEvent) { assert(transEl.mockEl.addEventListener.calledWith(transitionEvent, callback)); }); } ); }; this.TransitionElementTest.prototype.testRemoveCallbackRemovesEventListeners = function(queue) { var self = this; loadTE(queue, function(TransitionElement, MockElement) { var transEl; var transitionEndEvents = getTransitionEndEvents(); function callback() {} transEl = makeNewTransElAndApplyMocks(self, TransitionElement, MockElement); transEl.removeCallback(callback); assertEquals(transitionEndEvents.length, transEl.mockEl.removeEventListener.callCount); transitionEndEvents.forEach(function (transitionEvent) { assert(transEl.mockEl.removeEventListener.calledWith(transitionEvent, callback)); }); } ); }; this.TransitionElementTest.prototype.testForceUpdateCallsGetComputedStyle = function(queue) { var self = this; loadTE(queue, function(TransitionElement, MockElement) { var transEl; transEl = makeNewTransElAndApplyMocks(self, TransitionElement, MockElement); self.sandbox.stub(window, 'getComputedStyle'); transEl.forceUpdate('top'); assert(window.getComputedStyle.calledOnce); } ); }; this.TransitionElementTest.prototype.testGetStylePropertyValueReturnsValue = function(queue) { var self = this; loadTE(queue, function(TransitionElement, MockElement) { var transEl, value; transEl = makeNewTransElAndApplyMocks(self, TransitionElement, MockElement); self.sandbox.stub(transEl.mockEl.style, 'getPropertyValue').returns('somethingOrOther'); value = transEl.getStylePropertyValue('testProperty'); assert(transEl.mockEl.style.getPropertyValue.calledWith('testProperty')); assertEquals('somethingOrOther', value); } ); }; this.TransitionElementTest.prototype.testGetStylePropertyOfUndefined = function(queue) { var self = this; loadTE(queue, function(TransitionElement, MockElement) { var transEl, value; transEl = makeNewTransElAndApplyMocks(self, TransitionElement, MockElement); self.sandbox.stub(transEl.mockEl.style, 'getPropertyValue').returns(undefined); value = transEl.getStylePropertyValue('nonExistantProperty'); assert(transEl.mockEl.style.getPropertyValue.calledWith('nonExistantProperty')); assertEquals(undefined, value); } ); }; this.TransitionElementTest.prototype.testSetStyleProperty = function(queue) { var self = this; loadTE(queue, function(TransitionElement, MockElement) { var transEl, setObj; setObj = {}; transEl = makeNewTransElAndApplyMocks(self, TransitionElement, MockElement); self.sandbox.stub(transEl.mockEl.style, 'setProperty', function(prop, value) { setObj[prop] = value; }); transEl.setStylePropertyValue('someProperty', 'someValue'); assert(transEl.mockEl.style.setProperty.calledOnce); assertEquals('someValue', setObj.someProperty); } ); }; this.TransitionElementTest.prototype.testIsEventOnElementTrueWhenElementTargetMatches = function(queue) { var self = this; loadTE(queue, function(TransitionElement, MockElement) { var transEl, testEvent; transEl = makeNewTransElAndApplyMocks(self, TransitionElement, MockElement); testEvent = {target: transEl.mockEl}; assertTrue('isEventTarget returns true when the events target is the TransitionElements underlying DOM element', transEl.isEventTarget(testEvent)); } ); }; this.TransitionElementTest.prototype.testIsEventOnElementFalseWhenElementTargetDoesNotMatch = function(queue) { var self = this; loadTE(queue, function(TransitionElement, MockElement) { var transEl, testEvent; transEl = makeNewTransElAndApplyMocks(self, TransitionElement, MockElement); testEvent = {target: new MockElement()}; assertFalse('isEventTarget returns false when the events target is not the TransitionElements underlying DOM element', transEl.isEventTarget(testEvent)); } ); }; }());
getPrefixes
io_mp.py
#!/usr/bin/env python3
import multiprocessing import time session = None def set_global_session(): global session if not session: session = requests.Session() def download_site(url): with session.get(url) as response: name = multiprocessing.current_process().name print(f"{name}:Read {len(response.content)} from {url}") def download_all_sites(sites): with multiprocessing.Pool(initializer=set_global_session) as pool: pool.map(download_site, sites) if __name__ == "__main__": sites = [ "https://www.jython.org", "http://olympus.realpython.org/dice", ] * 80 start_time = time.time() download_all_sites(sites) duration = time.time() - start_time print(f"Downloaded {len(sites)} in {duration} seconds")
import requests
__init__.py
from .utils import check_norm_state, is_block, is_norm __all__ = ['is_block', 'is_norm', 'check_norm_state']
# Copyright (c) OpenMMLab. All rights reserved.
simple_config.py
import json import threading import time import os import stat from decimal import Decimal from typing import Union, Optional from numbers import Real from copy import deepcopy from . import util from .util import (user_dir, make_dir, NoDynamicFeeEstimates, format_fee_satoshis, quantize_feerate) from .i18n import _ from .logging import get_logger, Logger FEE_ETA_TARGETS = [25, 10, 5, 2] FEE_DEPTH_TARGETS = [10000000, 5000000, 2000000, 1000000, 500000, 200000, 100000] # satoshi per kbyte FEERATE_MAX_DYNAMIC = 10000000000 FEERATE_WARNING_HIGH_FEE = 1000000000 FEERATE_FALLBACK_STATIC_FEE = 20000000 FEERATE_DEFAULT_RELAY = 10000000 FEERATE_STATIC_VALUES = [10000000, 20000000, 50000000, 100000000, 200000000, 500000000, 1000000000, 2000000000, 5000000000, 10000000000] config = None _logger = get_logger(__name__) def get_config(): global config return config def set_config(c): global config config = c FINAL_CONFIG_VERSION = 3 class SimpleConfig(Logger): """ The SimpleConfig class is responsible for handling operations involving configuration files. There are two different sources of possible configuration values: 1. Command line options. 2. User configuration (in the user's config directory) They are taken in order (1. overrides config options set in 2.) """ def __init__(self, options=None, read_user_config_function=None, read_user_dir_function=None): if options is None: options = {} Logger.__init__(self) # This lock needs to be acquired for updating and reading the config in # a thread-safe way. self.lock = threading.RLock() self.mempool_fees = {} self.fee_estimates = {} self.fee_estimates_last_updated = {} self.last_time_fee_estimates_requested = 0 # zero ensures immediate fees # The following two functions are there for dependency injection when # testing. if read_user_config_function is None: read_user_config_function = read_user_config if read_user_dir_function is None: self.user_dir = user_dir else: self.user_dir = read_user_dir_function # The command line options self.cmdline_options = deepcopy(options) # don't allow to be set on CLI: self.cmdline_options.pop('config_version', None) # Set self.path and read the user config self.user_config = {} # for self.get in electrum_path() self.path = self.electrum_path() self.user_config = read_user_config_function(self.path) if not self.user_config: # avoid new config getting upgraded self.user_config = {'config_version': FINAL_CONFIG_VERSION} # config "upgrade" - CLI options self.rename_config_keys( self.cmdline_options, {'auto_cycle': 'auto_connect'}, True) # config upgrade - user config if self.requires_upgrade(): self.upgrade() # Make a singleton instance of 'self' set_config(self) def electrum_path(self): # Read electrum_path from command line # Otherwise use the user's default data directory. path = self.get('electrum_path') if path is None: path = self.user_dir() make_dir(path, allow_symlink=False) if self.get('testnet'): path = os.path.join(path, 'testnet') make_dir(path, allow_symlink=False) elif self.get('regtest'): path = os.path.join(path, 'regtest') make_dir(path, allow_symlink=False) elif self.get('simnet'): path = os.path.join(path, 'simnet') make_dir(path, allow_symlink=False) self.logger.info(f"electrum directory {path}") return path def rename_config_keys(self, config, keypairs, deprecation_warning=False): """Migrate old key names to new ones""" updated = False for old_key, new_key in keypairs.items(): if old_key in config: if new_key not in config: config[new_key] = config[old_key] if deprecation_warning: self.logger.warning('Note that the {} variable has been deprecated. ' 'You should use {} instead.'.format(old_key, new_key)) del config[old_key] updated = True return updated def set_key(self, key, value, save=True): if not self.is_modifiable(key): self.logger.warning(f"not changing config key '{key}' set on the command line") return try: json.dumps(key) json.dumps(value) except: self.logger.info(f"json error: cannot save {repr(key)} ({repr(value)})") return self._set_key_in_user_config(key, value, save) def _set_key_in_user_config(self, key, value, save=True): with self.lock: if value is not None: self.user_config[key] = value else: self.user_config.pop(key, None) if save: self.save_user_config() def get(self, key, default=None): with self.lock: out = self.cmdline_options.get(key) if out is None: out = self.user_config.get(key, default) return out def requires_upgrade(self): return self.get_config_version() < FINAL_CONFIG_VERSION def upgrade(self): with self.lock: self.logger.info('upgrading config') self.convert_version_2() self.convert_version_3() self.set_key('config_version', FINAL_CONFIG_VERSION, save=True) def convert_version_2(self): if not self._is_upgrade_method_needed(1, 1): return self.rename_config_keys(self.user_config, {'auto_cycle': 'auto_connect'}) try: # change server string FROM host:port:proto TO host:port:s server_str = self.user_config.get('server') host, port, protocol = str(server_str).rsplit(':', 2) assert protocol in ('s', 't') int(port) # Throw if cannot be converted to int server_str = '{}:{}:s'.format(host, port) self._set_key_in_user_config('server', server_str) except BaseException: self._set_key_in_user_config('server', None) self.set_key('config_version', 2) def convert_version_3(self): if not self._is_upgrade_method_needed(2, 2): return base_unit = self.user_config.get('base_unit') if isinstance(base_unit, str): self._set_key_in_user_config('base_unit', None) map_ = {'btc':8, 'mbtc':5, 'ubtc':2, 'bits':2, 'sat':0} decimal_point = map_.get(base_unit.lower()) self._set_key_in_user_config('decimal_point', decimal_point) self.set_key('config_version', 3) def _is_upgrade_method_needed(self, min_version, max_version): cur_version = self.get_config_version() if cur_version > max_version: return False elif cur_version < min_version: raise Exception( ('config upgrade: unexpected version %d (should be %d-%d)' % (cur_version, min_version, max_version))) else: return True def get_config_version(self): config_version = self.get('config_version', 1) if config_version > FINAL_CONFIG_VERSION: self.logger.warning('config version ({}) is higher than latest ({})' .format(config_version, FINAL_CONFIG_VERSION)) return config_version def is_modifiable(self, key): return key not in self.cmdline_options def save_user_config(self): if not self.path: return path = os.path.join(self.path, "config") s = json.dumps(self.user_config, indent=4, sort_keys=True) try: with open(path, "w", encoding='utf-8') as f: f.write(s) os.chmod(path, stat.S_IREAD | stat.S_IWRITE) except FileNotFoundError: # datadir probably deleted while running... if os.path.exists(self.path): # or maybe not? raise def get_wallet_path(self): """Set the path of the wallet.""" # command line -w option if self.get('wallet_path'): return os.path.join(self.get('cwd', ''), self.get('wallet_path')) # path in config file path = self.get('default_wallet_path') if path and os.path.exists(path): return path # default path util.assert_datadir_available(self.path) dirpath = os.path.join(self.path, "wallets") make_dir(dirpath, allow_symlink=False) new_path = os.path.join(self.path, "wallets", "default_wallet") # default path in pre 1.9 versions old_path = os.path.join(self.path, "electrum.dat") if os.path.exists(old_path) and not os.path.exists(new_path): os.rename(old_path, new_path) return new_path def remove_from_recently_open(self, filename): recent = self.get('recently_open', []) if filename in recent: recent.remove(filename) self.set_key('recently_open', recent) def set_session_timeout(self, seconds): self.logger.info(f"session timeout -> {seconds} seconds") self.set_key('session_timeout', seconds) def get_session_timeout(self): return self.get('session_timeout', 300) def open_last_wallet(self): if self.get('wallet_path') is None: last_wallet = self.get('gui_last_wallet') if last_wallet is not None and os.path.exists(last_wallet): self.cmdline_options['default_wallet_path'] = last_wallet def save_last_wallet(self, wallet): if self.get('wallet_path') is None: path = wallet.storage.path self.set_key('gui_last_wallet', path) def impose_hard_limits_on_fee(func): def get_fee_within_limits(self, *args, **kwargs): fee = func(self, *args, **kwargs) if fee is None: return fee fee = min(FEERATE_MAX_DYNAMIC, fee) fee = max(FEERATE_DEFAULT_RELAY, fee) return fee return get_fee_within_limits def eta_to_fee(self, slider_pos) -> Optional[int]: """Returns fee in sat/kbyte.""" slider_pos = max(slider_pos, 0) slider_pos = min(slider_pos, len(FEE_ETA_TARGETS)) if slider_pos < len(FEE_ETA_TARGETS): num_blocks = FEE_ETA_TARGETS[slider_pos] fee = self.eta_target_to_fee(num_blocks) else: fee = self.eta_target_to_fee(1) return fee @impose_hard_limits_on_fee def eta_target_to_fee(self, num_blocks: int) -> Optional[int]: """Returns fee in sat/kbyte.""" if num_blocks == 1: fee = self.fee_estimates.get(2) if fee is not None: fee += fee / 2 fee = int(fee) else: fee = self.fee_estimates.get(num_blocks) return fee def fee_to_depth(self, target_fee: Real) -> int: """For a given sat/vbyte fee, returns an estimate of how deep it would be in the current mempool in vbytes. Pessimistic == overestimates the depth. """ depth = 0 for fee, s in self.mempool_fees: depth += s if fee <= target_fee: break return depth def depth_to_fee(self, slider_pos) -> int: """Returns fee in sat/kbyte.""" target = self.depth_target(slider_pos) return self.depth_target_to_fee(target) @impose_hard_limits_on_fee def depth_target_to_fee(self, target: int) -> int: """Returns fee in sat/kbyte. target: desired mempool depth in vbytes """ depth = 0 for fee, s in self.mempool_fees: depth += s if depth > target: break else: return 0 # add one sat/byte as currently that is # the max precision of the histogram fee += 1 # convert to sat/kbyte return fee * 1000 def depth_target(self, slider_pos): slider_pos = max(slider_pos, 0) slider_pos = min(slider_pos, len(FEE_DEPTH_TARGETS)-1) return FEE_DEPTH_TARGETS[slider_pos] def eta_target(self, i): if i == len(FEE_ETA_TARGETS): return 1 return FEE_ETA_TARGETS[i] def fee_to_eta(self, fee_per_kb): import operator l = list(self.fee_estimates.items()) + [(1, self.eta_to_fee(4))] dist = map(lambda x: (x[0], abs(x[1] - fee_per_kb)), l) min_target, min_value = min(dist, key=operator.itemgetter(1)) if fee_per_kb < self.fee_estimates.get(25)/2: min_target = -1 return min_target def depth_tooltip(self, depth): return "%.1f MB from tip"%(depth/1000000) def eta_tooltip(self, x): if x < 0: return _('Low fee') elif x == 1: return _('In the next block') else: return _('Within {} blocks').format(x) def get_fee_status(self): dyn = self.is_dynfee() mempool = self.use_mempool_fees() pos = self.get_depth_level() if mempool else self.get_fee_level() fee_rate = self.fee_per_kb() target, tooltip = self.get_fee_text(pos, dyn, mempool, fee_rate) return tooltip + ' [%s]'%target if dyn else target + ' [Static]' def get_fee_text(self, pos, dyn, mempool, fee_rate): """Returns (text, tooltip) where text is what we target: static fee / num blocks to confirm in / mempool depth tooltip is the corresponding estimate (e.g. num blocks for a static fee) fee_rate is in sat/kbyte """ if fee_rate is None: rate_str = 'unknown' else: fee_rate = fee_rate/1000 rate_str = format_fee_satoshis(fee_rate) + ' sat/byte' if dyn: if mempool: depth = self.depth_target(pos) text = self.depth_tooltip(depth) else: eta = self.eta_target(pos) text = self.eta_tooltip(eta) tooltip = rate_str else: text = rate_str if mempool and self.has_fee_mempool(): depth = self.fee_to_depth(fee_rate) tooltip = self.depth_tooltip(depth) elif not mempool and self.has_fee_etas(): eta = self.fee_to_eta(fee_rate) tooltip = self.eta_tooltip(eta) else: tooltip = '' return text, tooltip def get_depth_level(self): maxp = len(FEE_DEPTH_TARGETS) - 1 return min(maxp, self.get('depth_level', 2)) def get_fee_level(self): maxp = len(FEE_ETA_TARGETS) # not (-1) to have "next block" return min(maxp, self.get('fee_level', 2)) def get_fee_slider(self, dyn, mempool):
def static_fee(self, i): return FEERATE_STATIC_VALUES[i] def static_fee_index(self, value): if value is None: raise TypeError('static fee cannot be None') dist = list(map(lambda x: abs(x - value), FEERATE_STATIC_VALUES)) return min(range(len(dist)), key=dist.__getitem__) def has_fee_etas(self): return len(self.fee_estimates) == 4 def has_fee_mempool(self): return bool(self.mempool_fees) def has_dynamic_fees_ready(self): if self.use_mempool_fees(): return self.has_fee_mempool() else: return self.has_fee_etas() def is_dynfee(self): return bool(self.get('dynamic_fees', False)) def use_mempool_fees(self): return bool(self.get('mempool_fees', False)) def _feerate_from_fractional_slider_position(self, fee_level: float, dyn: bool, mempool: bool) -> Union[int, None]: fee_level = max(fee_level, 0) fee_level = min(fee_level, 1) if dyn: max_pos = (len(FEE_DEPTH_TARGETS) - 1) if mempool else len(FEE_ETA_TARGETS) slider_pos = round(fee_level * max_pos) fee_rate = self.depth_to_fee(slider_pos) if mempool else self.eta_to_fee(slider_pos) else: max_pos = len(FEERATE_STATIC_VALUES) - 1 slider_pos = round(fee_level * max_pos) fee_rate = FEERATE_STATIC_VALUES[slider_pos] return fee_rate def fee_per_kb(self, dyn: bool=None, mempool: bool=None, fee_level: float=None) -> Union[int, None]: """Returns sat/kvB fee to pay for a txn. Note: might return None. fee_level: float between 0.0 and 1.0, representing fee slider position """ if dyn is None: dyn = self.is_dynfee() if mempool is None: mempool = self.use_mempool_fees() if fee_level is not None: return self._feerate_from_fractional_slider_position(fee_level, dyn, mempool) # there is no fee_level specified; will use config. # note: 'depth_level' and 'fee_level' in config are integer slider positions, # unlike fee_level here, which (when given) is a float in [0.0, 1.0] if dyn: if mempool: fee_rate = self.depth_to_fee(self.get_depth_level()) else: fee_rate = self.eta_to_fee(self.get_fee_level()) else: fee_rate = self.get('fee_per_kb', FEERATE_FALLBACK_STATIC_FEE) return fee_rate def fee_per_byte(self): """Returns sat/vB fee to pay for a txn. Note: might return None. """ fee_per_kb = self.fee_per_kb() return fee_per_kb / 1000 if fee_per_kb is not None else None def estimate_fee(self, size: Union[int, float, Decimal]) -> int: fee_per_kb = self.fee_per_kb() if fee_per_kb is None: raise NoDynamicFeeEstimates() return self.estimate_fee_for_feerate(fee_per_kb, size) @classmethod def estimate_fee_for_feerate(cls, fee_per_kb: Union[int, float, Decimal], size: Union[int, float, Decimal]) -> int: size = Decimal(size) fee_per_kb = Decimal(fee_per_kb) fee_per_byte = fee_per_kb / 1000 # to be consistent with what is displayed in the GUI, # the calculation needs to use the same precision: fee_per_byte = quantize_feerate(fee_per_byte) return round(fee_per_byte * size) def update_fee_estimates(self, key, value): self.fee_estimates[key] = value self.fee_estimates_last_updated[key] = time.time() def is_fee_estimates_update_required(self): """Checks time since last requested and updated fee estimates. Returns True if an update should be requested. """ now = time.time() return now - self.last_time_fee_estimates_requested > 60 def requested_fee_estimates(self): self.last_time_fee_estimates_requested = time.time() def get_video_device(self): device = self.get("video_device", "default") if device == 'default': device = '' return device def read_user_config(path): """Parse and store the user config settings in electrum.conf into user_config[].""" if not path: return {} config_path = os.path.join(path, "config") if not os.path.exists(config_path): return {} try: with open(config_path, "r", encoding='utf-8') as f: data = f.read() result = json.loads(data) except: _logger.warning(f"Cannot read config file. {config_path}") return {} if not type(result) is dict: return {} return result
if dyn: if mempool: pos = self.get_depth_level() maxp = len(FEE_DEPTH_TARGETS) - 1 fee_rate = self.depth_to_fee(pos) else: pos = self.get_fee_level() maxp = len(FEE_ETA_TARGETS) # not (-1) to have "next block" fee_rate = self.eta_to_fee(pos) else: fee_rate = self.fee_per_kb(dyn=False) pos = self.static_fee_index(fee_rate) maxp = len(FEERATE_STATIC_VALUES) - 1 return maxp, pos, fee_rate
settings.rs
pub mod permission; use serde_derive::{Deserialize, Serialize}; use std::fs::File; use std::io::{Read, Write}; use std::path::Path; use std::sync::{Arc, Mutex}; use toml; #[derive(Default, Debug, Serialize, Deserialize)] pub(crate) struct Config { pub(crate) channel: permission::Channel, } lazy_static! { pub(crate) static ref SETTINGS: Arc<Mutex<Config>> = Arc::new(Mutex::new(
pub(crate) fn init_config<ConfigPath: AsRef<Path>>(path: ConfigPath) -> std::io::Result<Config> { File::open(&path).map_or_else( |_| { let mut f = File::create(&path)?; let buffer = toml::to_string(&Config::default()).unwrap(); f.write_all(buffer.as_bytes())?; f.sync_all()?; Ok(Config::default()) }, |mut file| { let mut buffer = String::new(); file.read_to_string(&mut buffer)?; let conf: Config = toml::from_slice(buffer.as_bytes())?; Ok(conf) }, ) }
init_config("/tmp/settings/settings.toml").unwrap() )); }
launch_cfg_lib.py
# Copyright (C) 2019 Intel Corporation. # # SPDX-License-Identifier: BSD-3-Clause # import os import getopt import re import common import board_cfg_lib import scenario_cfg_lib import lxml import lxml.etree ERR_LIST = {} BOOT_TYPE = ['no', 'ovmf'] RTOS_TYPE = ['no', 'Soft RT', 'Hard RT'] DM_VUART0 = ['Disable', 'Enable'] y_n = ['y', 'n'] USER_VM_TYPES = ['CLEARLINUX', 'ANDROID', 'ALIOS', 'PREEMPT-RT LINUX', 'VXWORKS', 'WINDOWS', 'ZEPHYR', 'YOCTO', 'UBUNTU', 'GENERIC LINUX'] LINUX_LIKE_OS = ['CLEARLINUX', 'PREEMPT-RT LINUX', 'YOCTO', 'UBUNTU', 'GENERIC LINUX'] PT_SUB_PCI = {} PT_SUB_PCI['usb_xdci'] = ['USB controller'] PT_SUB_PCI['gpu'] = ['VGA compatible controller'] PT_SUB_PCI['ipu'] = ['Multimedia controller'] PT_SUB_PCI['ipu_i2c'] = ['Signal processing controller'] PT_SUB_PCI['cse'] = ['Communication controller'] PT_SUB_PCI['audio'] = ['Audio device', 'Multimedia audio controller'] PT_SUB_PCI['audio_codec'] = ['Signal processing controller'] PT_SUB_PCI['sd_card'] = ['SD Host controller'] PT_SUB_PCI['wifi'] = ['Ethernet controller', 'Network controller', '802.1a controller', '802.1b controller', 'Wireless controller'] PT_SUB_PCI['bluetooth'] = ['Signal processing controller'] PT_SUB_PCI['ethernet'] = ['Ethernet controller', 'Network controller'] PT_SUB_PCI['sata'] = ['SATA controller'] PT_SUB_PCI['nvme'] = ['Non-Volatile memory controller'] # passthrough devices for board PASSTHRU_DEVS = ['usb_xdci', 'gpu', 'ipu', 'ipu_i2c', 'cse', 'audio', 'sata', 'nvme', 'audio_codec', 'sd_card', 'ethernet', 'wifi', 'bluetooth'] PT_SLOT = { "hostbridge":0, "lpc":1, "pci-gvt":2, "virtio-blk":3, "igd-lpc":31, } MOUNT_FLAG_DIC = {} def usage(file_name): """ This is usage for how to use this tool """ print("usage= {} [h]".format(file_name), end="") print("--board <board_info_file> --scenario <scenario_info_file> --launch <launch_info_file> --user_vmid <user_vmid id> --out [output folder]") print('board_info_file : file name of the board info') print('scenario_info_file : file name of the scenario info') print('launch_info_file : file name of the launch info') print('user_vmid : this is the relative id for post launch vm in scenario info XML:[1..max post launch vm]') print('output folder : path to acrn-hypervisor_folder') def get_param(args): """ Get the script parameters from command line :param args: this the command line of string for the script without script name """ vm_th = '0' err_dic = {} board_info_file = False scenario_info_file = False launch_info_file = False output_folder = False param_list = ['--board', '--scenario', '--launch', '--user_vmid'] for arg_str in param_list: if arg_str not in args: usage(args[0]) err_dic['common error: wrong parameter'] = "wrong usage" return (err_dic, board_info_file, scenario_info_file, launch_info_file, int(vm_th), output_folder) args_list = args[1:] (optlist, args_list) = getopt.getopt(args_list, '', ['board=', 'scenario=', 'launch=', 'user_vmid=', 'out=']) for arg_k, arg_v in optlist: if arg_k == '--board': board_info_file = arg_v if arg_k == '--scenario': scenario_info_file = arg_v if arg_k == '--launch': launch_info_file = arg_v if arg_k == '--out': output_folder = arg_v if '--user_vmid' in args: if arg_k == '--user_vmid': vm_th = arg_v if not vm_th.isnumeric(): err_dic['common error: wrong parameter'] = "--user_vmid should be a number" return (err_dic, board_info_file, scenario_info_file, launch_info_file, int(vm_th), output_folder) if not board_info_file or not scenario_info_file or not launch_info_file: usage(args[0]) err_dic['common error: wrong parameter'] = "wrong usage" return (err_dic, board_info_file, scenario_info_file, launch_info_file, int(vm_th), output_folder) if not os.path.exists(board_info_file): err_dic['common error: wrong parameter'] = "{} does not exist!".format(board_info_file) return (err_dic, board_info_file, scenario_info_file, launch_info_file, int(vm_th), output_folder) if not os.path.exists(scenario_info_file): err_dic['common error: wrong parameter'] = "{} does not exist!".format(scenario_info_file) return (err_dic, board_info_file, scenario_info_file, launch_info_file, int(vm_th), output_folder) if not os.path.exists(launch_info_file): err_dic['common error: wrong parameter'] = "{} does not exist!".format(launch_info_file) return (err_dic, board_info_file, scenario_info_file, launch_info_file, int(vm_th), output_folder) return (err_dic, board_info_file, scenario_info_file, launch_info_file, int(vm_th), output_folder) def launch_vm_cnt(config_file): """ Get post vm number :param config_file: it is a file what contains information for script to read from :return: total post vm number in launch file """ post_vm_count = 0 # get post vm number root = common.get_config_root(config_file) for item in root: if item.tag == "user_vm": post_vm_count += 1 return post_vm_count def get_post_num_list(): """ Get post vm number list :return: total post dic: {launch_id:scenario_id} in launch file """ post_vm_list = [] # get post vm number root = common.get_config_root(common.LAUNCH_INFO_FILE) for item in root: if item.tag == "user_vm": post_vm_list.append(int(item.attrib['id'])) return post_vm_list def post_vm_cnt(config_file): """ Calculate the pre launched vm number :param config_file: it is a file what contains information for script to read from :return: number of post launched vm """ post_launch_cnt = 0 for load_order in common.LOAD_ORDER.values(): if load_order == "POST_LAUNCHED_VM": post_launch_cnt += 1 return post_launch_cnt def get_post_vm_cnt(): """ Get board name from launch.xml at fist line :param scenario_file: it is a file what contains scenario information for script to read from """ launch_vm_count = launch_vm_cnt(common.LAUNCH_INFO_FILE) post_vm_count = post_vm_cnt(common.SCENARIO_INFO_FILE) return (launch_vm_count, post_vm_count) def get_sos_vmid(): sos_id = '' for vm_i,load_order in common.LOAD_ORDER.items(): if load_order == "SERVICE_VM": sos_id = vm_i break return sos_id def get_bdf_from_tag(config_file, branch_tag, tag_str): bdf_list = {} bdf_list = common.get_leaf_tag_map(config_file, branch_tag, tag_str) # split b:d:f from pci description for idx, bdf_v in bdf_list.items(): if bdf_v: bdf_list[idx] = bdf_v.split()[0] return bdf_list def get_vpid_from_bdf(bdf_vpid_map, bdf_list): vpid_list = {} post_vm_list = get_post_num_list() for p_id in post_vm_list: for bdf_k, vpid_v in bdf_vpid_map.items(): if bdf_k == bdf_list[p_id]: # print("k:{}, v{}".format(bdf_k, bdf_list[p_id])) # convert "808x:0xxx" to "808x 0xxx" tmp_vpid = " ".join(vpid_v.split(':')) vpid_list[p_id] = tmp_vpid elif not bdf_list[p_id]: vpid_list[p_id] = '' return vpid_list def get_user_vm_type(): """ Get User VM name from launch.xml at fist line """ user_vm_types = common.get_leaf_tag_map(common.LAUNCH_INFO_FILE, "user_vm_type") return user_vm_types def get_user_vm_names(): user_vm_names = common.get_leaf_tag_map(common.LAUNCH_INFO_FILE, "vm_name") return user_vm_names def is_bdf_format(bdf_str): bdf_len = 7 status = True if not bdf_str: return status bdf_str_len = len(bdf_str) if ':' in bdf_str and '.' in bdf_str and bdf_len == bdf_str_len: status = True else: status = False return status def is_vpid_format(vpid_str): status = True if not vpid_str: return status vpid_len = 9 vpid_str_len = len(vpid_str) if ' ' in vpid_str and vpid_len == vpid_str_len: status = True else: status = False return status def pt_devs_check(bdf_list, vpid_list, item): i_cnt = 1 # check bdf for bdf_str in bdf_list.values(): if is_bdf_format(bdf_str): continue else: key = "user_vm:id={},passthrough_devices,{}".format(i_cnt, item) ERR_LIST[key] = "Unkonw the BDF format of {} device".format(item) i_cnt += 1 # check vpid i_cnt = 1 for vpid_str in vpid_list.values(): if is_vpid_format(vpid_str): continue else: key = "user_vm:id={},passthrough_devices,{}".format(i_cnt, item) ERR_LIST[key] = "Unkonw the Vendor:Product ID format of {} device".format(item) i_cnt += 1 def empty_err(i_cnt, item): """ add empty error message into ERR_LIST :param i_cnt: the launch vm index from config xml :param item: the item of tag from config xml :return: None """ key = "user_vm:id={},{}".format(i_cnt, item) ERR_LIST[key] = "The parameter should not be empty" def args_aval_check(arg_list, item, avl_list): """ check arguments from config xml are available and validate :param arg_list: the list of arguments from config xml :param item: the item of tag from config xml :param avl_list: available argument which are allowed to chose :return: None """ # args should be set into launch xml from webUI i_cnt = 1 skip_check_list = [''] if item in skip_check_list: return for arg_str in arg_list.values(): if arg_str == None or not arg_str.strip(): empty_err(i_cnt, item) i_cnt += 1 continue if arg_str not in avl_list: key = "user_vm:id={},{}".format(i_cnt, item) ERR_LIST[key] = "The {} is invalidate".format(item) i_cnt += 1 def mem_size_check(arg_list, item): """ check memory size list which are set from webUI :param arg_list: the list of arguments from config xml :param item: the item of tag from config xml :return: None """ # get total memory information total_mem_mb = board_cfg_lib.get_total_mem() # available check i_cnt = 1 for arg_str in arg_list.values(): if arg_str == None or not arg_str.strip(): empty_err(i_cnt, item) i_cnt += 1 continue mem_size_set = int(arg_str.strip()) if mem_size_set > total_mem_mb: key = "user_vm:id={},{}".format(i_cnt, item) ERR_LIST[key] = "{}MB should be less than total memory {}MB".format(item) i_cnt += 1 def virtual_dev_slot(dev): max_slot = 31 base_slot = 3 # get devices slot which already stored if dev in list(PT_SLOT.keys()): return PT_SLOT[dev] # alloc a new slot for device for slot_num in range(base_slot, max_slot): if slot_num not in list(PT_SLOT.values()): if (slot_num == 6 and 14 in list(PT_SLOT.values())) or (slot_num == 14 and 6 in list(PT_SLOT.values())): continue if (slot_num == 7 and 15 in list(PT_SLOT.values())) or (slot_num == 15 and 7 in list(PT_SLOT.values())): continue PT_SLOT[dev] = slot_num break return slot_num def get_slot(bdf_list, dev): slot_list = {} post_vm_list = get_post_num_list() for p_id in post_vm_list: if not bdf_list[p_id]: slot_list[p_id] = '' else: slot_fun = virtual_dev_slot(dev) PT_SLOT[dev] = slot_fun slot_list[p_id] = slot_fun return slot_list def reset_pt_slot(): global PT_SLOT PT_SLOT = { "hostbridge":0, "lpc":1, "pci-gvt":2, "virtio-blk":3, "igd-lpc":31, } def get_pt_dev(): """ Get passthrough device list """ cap_pt = PASSTHRU_DEVS return cap_pt def get_vuart1_from_scenario(vmid): """Get the vmid's vuart1 base""" vuart1 = common.get_vuart_info_id(common.SCENARIO_INFO_FILE, 1) return vuart1[vmid]['base'] def pt_devs_check_audio(audio_map, audio_codec_map): """ Check the connections about audio/audio_codec pass-through devices If audio_codec is selected as pass-through device, the audio device must to be chosen as pass-through device either. :param audio_map: the dictionary contains vmid and bdf of audio device :param audio_codec_map: the dictionary contains vmid and bdf of audio_codec device """ for vmid in list(audio_map.keys()): bdf_audio = audio_map[vmid] bdf_codec = audio_codec_map[vmid] if not bdf_audio and bdf_codec: key = "user_vm:id={},passthrough_devices,{}".format(vmid, 'audio_codec') ERR_LIST[key] = "Audio codec device should be pass through together with Audio devcie!" def check_block_mount(virtio_blk_dic): (blk_dev_list, num) = board_cfg_lib.get_rootfs(common.BOARD_INFO_FILE) for vmid in list(virtio_blk_dic.keys()): mount_flags = [] for blk in virtio_blk_dic[vmid]: rootfs_img = '' if not blk: mount_flags.append(False) continue if ':' in blk: blk_dev = blk.split(':')[0] rootfs_img = blk.split(':')[1] else: blk_dev = blk if blk_dev in blk_dev_list and rootfs_img: mount_flags.append(True) else: mount_flags.append(False) MOUNT_FLAG_DIC[vmid] = mount_flags def check_sriov_param(sriov_dev, pt_sel): for dev_type in ['gpu', 'network']: for vm_id, dev_bdf in sriov_dev[dev_type].items(): if not dev_bdf: continue pt_devname = dev_type if pt_devname == 'network': pt_devname = 'ethernet' if pt_sel.bdf[pt_devname][vm_id]: ERR_LIST[ 'vmid:{} sriov {}'.format(vm_id, dev_type) ] = 'this vm has {} passthrough and sriov {} at same time!'.format(pt_devname, dev_type) if not re.match(r'^[\da-fA-F]{2}:[0-3][\da-fA-F]\.[0-7]$', dev_bdf): ERR_LIST['vmid:{} sriov {}'.format(vm_id, dev_type)] = 'sriov {} bdf error'.format(dev_type) def bdf_duplicate_check(bdf_dic): """ Check if exist duplicate slot :param bdf_dic: contains all selected pass-through devices :return: None """ bdf_used = [] for dev in bdf_dic.keys(): dev_bdf_dic = bdf_dic[dev] for vm_i in dev_bdf_dic.keys(): dev_bdf = dev_bdf_dic[vm_i] if not dev_bdf: continue if dev_bdf in bdf_used: key = "user_vm:id={},{},{}".format(vm_i, 'passthrough_devices', dev) ERR_LIST[key] = "You select the same device for {} pass-through !".format(dev) return else: bdf_used.append(dev_bdf) def get_gpu_bdf(): pci_lines = board_cfg_lib.get_info(common.BOARD_INFO_FILE, "<PCI_DEVICE>", "</PCI_DEVICE>") for line in pci_lines: if "VGA compatible controller" in line: global gpu_bdf gpu_bdf = line.split('\t')[1] gpu_bdf = gpu_bdf[0:7] return gpu_bdf def get_vpid_by_bdf(bdf): vpid = '' vpid_lines = board_cfg_lib.get_info(common.BOARD_INFO_FILE, "<PCI_VID_PID>", "</PCI_VID_PID>") for vpid_line in vpid_lines: if bdf in vpid_line: vpid = " ".join(vpid_line.split()[2].split(':')) return vpid def get_gpu_vpid(): gpu_bdf = get_gpu_bdf() return get_vpid_by_bdf(gpu_bdf) def user_vm_cpu_affinity(user_vmid_cpu_affinity): cpu_affinity = {} sos_vm_id = get_sos_vmid() for user_vmid,cpu_affinity_list in user_vmid_cpu_affinity.items(): cpu_affinity[int(user_vmid) + int(sos_vm_id)] = cpu_affinity_list return cpu_affinity def check_slot(slot_db): slot_values = {} # init list of slot values for Post VM for dev in slot_db.keys(): for user_vmid in slot_db[dev].keys(): slot_values[user_vmid] = [] break # get slot values for Passthrough devices for dev in PASSTHRU_DEVS: if dev == 'gpu': continue for user_vmid,slot_str in slot_db[dev].items(): if not slot_str: continue slot_values[user_vmid].append(slot_str) # update slot values and replace the fun=0 if there is no fun 0 in bdf list for dev in PASSTHRU_DEVS: if dev == 'gpu': continue for user_vmid,slot_str in slot_db[dev].items(): if not slot_str or ':' not in str(slot_str): continue bus_slot = slot_str[0:-1] bus_slot_fun0 = bus_slot + "0" if bus_slot_fun0 not in slot_values[user_vmid]: slot_db[dev][user_vmid] = bus_slot_fun0 slot_values[user_vmid].append(bus_slot_fun0) def is_linux_like(user_vm_type): is_linux = False if user_vm_type in LINUX_LIKE_OS: is_linux = True return is_linux def set_shm_regions(launch_item_values, scenario_info): try: raw_shmem_regions = common.get_hv_item_tag(scenario_info, "FEATURES", "IVSHMEM", "IVSHMEM_REGION") load_orders = common.get_leaf_tag_map(scenario_info, "load_order") shm_enabled = common.get_hv_item_tag(scenario_info, "FEATURES", "IVSHMEM", "IVSHMEM_ENABLED") except: return sos_vm_id = 0 for vm_id,load_order in load_orders.items(): if load_order in ['SERVICE_VM']: sos_vm_id = vm_id elif load_order in ['POST_LAUNCHED_VM']: user_vmid = vm_id - sos_vm_id shm_region_key = 'user_vm:id={},shm_regions,shm_region'.format(user_vmid) launch_item_values[shm_region_key] = [''] if shm_enabled == 'y': for shmem_region in raw_shmem_regions: if shmem_region is None or shmem_region.strip() == '': continue try: shm_splited = shmem_region.split(',') name = shm_splited[0].strip() size = shm_splited[1].strip() vm_id_list = [x.strip() for x in shm_splited[2].split(':')] if str(vm_id) in vm_id_list: launch_item_values[shm_region_key].append(','.join([name, size])) except Exception as e: print(e) def set_pci_vuarts(launch_item_values, scenario_info): try: launch_item_values['user_vm,console_vuart'] = DM_VUART0 load_orders = common.get_leaf_tag_map(scenario_info, 'load_order') sos_vm_id = 0 for vm_id,load_order in load_orders.items(): if load_order in ['SERVICE_VM']: sos_vm_id = vm_id for vm in list(common.get_config_root(scenario_info)): if vm.tag == 'vm' and load_orders[int(vm.attrib['id'])] == 'POST_LAUNCHED_VM': user_vmid = int(vm.attrib['id']) - sos_vm_id pci_vuart_key = 'user_vm:id={},communication_vuarts,communication_vuart'.format(user_vmid) for elem in list(vm): if elem.tag == 'communication_vuart': for sub_elem in list(elem): if sub_elem.tag == 'base' and sub_elem.text == 'PCI_VUART': if pci_vuart_key not in launch_item_values.keys(): launch_item_values[pci_vuart_key] = ['', elem.attrib['id']] else: launch_item_values[pci_vuart_key].append(elem.attrib['id']) except: return def check_shm_regions(launch_shm_regions, scenario_info): launch_item_values = {} set_shm_regions(launch_item_values, scenario_info) for user_vmid, shm_regions in launch_shm_regions.items(): shm_region_key = 'user_vm:id={},shm_regions,shm_region'.format(user_vmid) for shm_region in shm_regions: if shm_region_key not in launch_item_values.keys() or shm_region not in launch_item_values[shm_region_key]: ERR_LIST[shm_region_key] = "shm {} should be configured in scenario setting and the size should be decimal" \ "in MB and spaces should not exist.".format(shm_region) return def check_console_vuart(launch_console_vuart, vuart0, scenario_info): vuarts = common.get_vuart_info(scenario_info) for user_vmid, console_vuart_enable in launch_console_vuart.items(): key = 'user_vm:id={},console_vuart'.format(user_vmid) if console_vuart_enable == "Enable" and vuart0[user_vmid] == "Enable":
if console_vuart_enable == "Enable" and int(user_vmid) in vuarts.keys() \ and 0 in vuarts[user_vmid] and vuarts[user_vmid][0]['base'] == "INVALID_PCI_BASE": ERR_LIST[key] = "console_vuart of user_vm {} should be enabled in scenario setting".format(user_vmid) return def check_communication_vuart(launch_communication_vuarts, scenario_info): vuarts = common.get_vuart_info(scenario_info) vuart1_setting = common.get_vuart_info_id(common.SCENARIO_INFO_FILE, 1) for user_vmid, vuart_list in launch_communication_vuarts.items(): vuart_key = 'user_vm:id={},communication_vuarts,communication_vuart'.format(user_vmid) for vuart_id in vuart_list: if not vuart_id: return if int(vuart_id) not in vuarts[user_vmid].keys(): ERR_LIST[vuart_key] = "communication_vuart {} of user_vm {} should be configured" \ "in scenario setting.".format(vuart_id, user_vmid) return if int(vuart_id) == 1 and vuarts[user_vmid][1]['base'] != "INVALID_PCI_BASE": if user_vmid in vuart1_setting.keys() and vuart1_setting[user_vmid]['base'] != "INVALID_COM_BASE": ERR_LIST[vuart_key] = "user_vm {}'s communication_vuart 1 and legacy_vuart 1 should " \ "not be configured at the same time.".format(user_vmid) return def check_enable_ptm(launch_enable_ptm, scenario_info): scenario_etree = lxml.etree.parse(scenario_info) enable_ptm_vm_list = scenario_etree.xpath("//vm[PTM = 'y']/@id") for user_vmid, enable_ptm in launch_enable_ptm.items(): key = 'user_vm:id={},enable_ptm'.format(user_vmid) if enable_ptm == 'y' and str(user_vmid) not in enable_ptm_vm_list: ERR_LIST[key] = "PTM of user_vm:{} set to 'n' in scenario xml".format(user_vmid)
ERR_LIST[key] = "vuart0 and console_vuart of user_vm {} should not be enabled " \ "at the same time".format(user_vmid) return
mod.rs
//! VCPU16 System pub mod bus; pub mod cpu; pub mod mem; pub mod hardware; type Word = u16; /// Shared System pub struct System { mem: Memory, cpu: VCPU16, clk: Clock, bus: Bus, } impl System { pub fn new() { System { mem: Memory::new(), cpu: VCPU16: new(), clk: Clock::new(), bus: Bus::new(), } } pub fn mem(&mut self) -> &mut Memory { &self.mem } pub fn cpu(&mut self) -> &mut VCPU16 { &self.cpu } pub fn clk(&mut self) -> &mut Clock
pub fn bus(&mut self) -> &mut Bus { &self.bus } }
{ &self.clk }
usbmux.go
package main import ( "net" "fmt" "encoding/binary" "encoding/hex" "bytes" goplist "github.com/DHowett/go-plist" ) // a very basic Usbmux client. Not as good as https://github.com/Mitchell-Riley/mux; just need it for basic tcp. // referenced http://squirrel-lang.org/forums/default.aspx?g=posts&m=6816 for protocol documentation, but doesn't use its code. type UsbmuxClient struct { conn net.Conn tag uint32 } func (client *UsbmuxClient) Write(version, packettype uint32, payload map[string] interface{}) (error) { tag := client.tag client.tag += 1 dat, err := goplist.Marshal(payload, goplist.XMLFormat) if err != nil { return err } length := 4 + 4 + 4 + 4 + len(dat) w := new(bytes.Buffer) binary.Write(w, binary.LittleEndian, uint32(length)) binary.Write(w, binary.LittleEndian, version) binary.Write(w, binary.LittleEndian, packettype) binary.Write(w, binary.LittleEndian, tag) w.Write(dat) fmt.Println(hex.Dump(w.Bytes())) _, err = w.WriteTo(client.conn) return err } func (client *UsbmuxClient) Read() (uint32, uint32, uint32, map[string] interface{}, error) { var size, version, packettype, tag uint32 err := binary.Read(client.conn, binary.LittleEndian, &size); if err != nil { return 0, 0, 0, nil, err } b := make([]byte, size - 4) _, err = client.conn.Read(b) if err != nil { return 0, 0, 0, nil, err } r := bytes.NewReader(b) fmt.Println(hex.Dump(b)) binary.Read(r, binary.LittleEndian, &version) binary.Read(r, binary.LittleEndian, &packettype) binary.Read(r, binary.LittleEndian, &tag) var plist map[string]interface{} _, err = goplist.Unmarshal(b[12:], &plist) return version, packettype, tag, plist, err } func (client *UsbmuxClient) Transact(version, packettype uint32, payload map[string]interface{}) (uint32, uint32, uint32, map[string]interface{}, error) { err := client.Write(version, packettype, payload) if err != nil { return 0, 0, 0, nil, err } return client.Read() } func (client *UsbmuxClient) Connect(deviceid int, portnumber int) (map[string]interface{}, error) { d := map[string] interface{} { "BundleID": "net.zhuoweizhang.fait", "ClientVersionString": "0.1", "ProgName": "fait", "MessageType": "Connect", "DeviceID": deviceid, "PortNumber": ((portnumber & 0xff) << 8) | ((portnumber >> 8) & 0xff), } _, _, _, ret, err := client.Transact(1, 8, d) return ret, err } func (client *UsbmuxClient) ListDevices() (map[string]interface{}, error) { d := map[string] interface{} { "BundleID": "net.zhuoweizhang.fait", "ClientVersionString": "0.1", "ProgName": "fait", "MessageType": "ListDevices", } _, _, _, ret, err := client.Transact(1, 8, d) return ret, err } func (client *UsbmuxClient) Conn() (net.Conn) { return client.conn } func NewUsbmuxClientTCP() (*UsbmuxClient, error) { conn, err := net.Dial("tcp", "127.0.0.1:27015") if err != nil { return nil, err } client := new(UsbmuxClient) client.conn = conn return client, nil } func
(deviceid int, portnumber int) (net.Conn, error) { client, err := NewUsbmuxClientTCP() if err != nil { // todo close client return nil, err } d, err := client.ListDevices() if err != nil { return nil, err } fmt.Println(d) d, err = client.Connect(deviceid, portnumber) if err != nil { return nil, err } fmt.Println(d) return client.Conn(), nil }
UsbmuxConnect
__init__.py
import os from .BaseConfig import BaseConfig from .BaseTest import BaseTest from .Env import env from .Run import Run __all__ = ['BaseConfig', 'BaseTest', 'Run', 'env', 'all'] def
(config, cfg_dir): if not os.path.exists(cfg_dir): os.makedirs(cfg_dir) cfg_list = list() for file in sorted(os.listdir(cfg_dir)): cfg_list.append(config(os.path.join(cfg_dir, file))) return cfg_list
all
canvasOverlay.js
import Overlayer from './overlay'; /** * initCanvasOverlayer based on mapboxgl-canvas */ export class CanvasOverlayer extends Overlayer { constructor(opts) { let _opts = opts || {}; super(_opts); this.canvas = this._init(); this.redraw = _opts.render ? _opts.render : _redraw.bind(this); this.data = _opts.data ? _opts.data: null; // how to deconstruct opts to this if we need defaultValue. this.labelOn = _opts.labelOn || false; this.xfield = _opts.xfield || 'lon'; this.yfield = _opts.yfield || 'lat'; this.shadow = _opts.shadow != undefined? _opts.shadow : false; this.lineColor = _opts.lineColor; this.blurWidth = _opts.blurWidth != undefined? _opts.blurWidth: 4; this.keepTrack = _opts.keepTrack != undefined? _opts.keepTrack : false; if (this.keepTrack) { // create trackLayer to render history track lines.. this.trackLayer = this._init(); this._initTrackCtx(); } this.tracks = []; this.initTrackCtx = this._initTrackCtx.bind(this); if (_opts && _opts.map) { this.setMap(_opts.map); console.warn(`register map moveend rerender handler..`); _opts.map.on("move", () => { this.redraw(); this.redrawTrack(); }); } this.redraw(); } _init(shadow=false,keepTrack=false) { let canvasContainer = this.map._canvasContainer, mapboxCanvas = this.map._canvas, canvasOverlay = document.createElement("canvas"); canvasOverlay.style.position = "absolute"; canvasOverlay.className = "overlay-canvas"; canvasOverlay.width = parseInt(mapboxCanvas.style.width); canvasOverlay.height = parseInt(mapboxCanvas.style.height); canvasContainer.appendChild(canvasOverlay); return canvasOverlay; } _transformLnglat() { // transform lnglat data to pix. if (Array.isArray(this.data)) { console.warn(`transformed lnglat data to pix..`); const pixArr = this.data.map((lnglatArr) => { return this.lnglat2pix(lnglatArr[0], lnglatArr[1]); }); return pixArr; } } /** * init track ctx for each track segment rendering.. */ _initTrackCtx() { if(this.trackLayer) { this.trackCtx = this.trackLayer.getContext("2d"); this.movedTo = false; initCtx(this.trackCtx, this.blurWidth,"rgba(255,255,255,.4"); this.trackCtx.lineWidth = this.lineWidth || 3; this.trackCtx.strokeStyle = this.lineColor || "rgba(255,255,20,.6)"; this.trackCtx.beginPath(); } } /** * set tracks coordinates of overlayer. * @param {*array of track points.} tracks */ setTracks(tracks) { if (Array.isArray(tracks)) { this.tracks = tracks; return this; } } getTracks() { return this.tracks; } /** * render cached tracks to line when map moved.. */ redrawTrack() { if(this.trackCtx && this.tracks && this.tracks.length > 0) { let pix = [0, 0]; this.trackCtx.clearRect(0,0,this.trackLayer.width, this.trackLayer.height); this.trackCtx.beginPath(); pix = this.lnglat2pix(this.tracks[0][0], this.tracks[0][1]); this.trackCtx.moveTo(pix[0], pix[1]); for(let i = 1; i < this.tracks.length; i ++) { pix = this.lnglat2pix(this.tracks[i][0], this.tracks[i][1]); this.trackCtx.lineTo(pix[0], pix[1]); } this.trackCtx.stroke(); } } } function _preSetCtx(context) { //默认值为source-over let prev = context.globalCompositeOperation; //只显示canvas上原图像的重叠部分 source-in, source, destination-in context.globalCompositeOperation = 'destination-in'; //设置主canvas的绘制透明度 context.globalAlpha = 0.95; //这一步目的是将canvas上的图像变的透明 // context.fillStyle = "rgba(0,0,0,.95)"; context.fillRect(0, 0, context.canvas.width, context.canvas.height); //在原图像上重叠新图像 context.globalCompositeOperation = prev; } const iconSize = 32; /** * expoid this method, can be overwritten * for special render requirements.. * Important ! redraw may use this.map as projector! * @param: keepLog, keep render Sprites location log.. */ function _redraw(data) { if (this.canvas) { let ctx = this.canvas.getContext("2d"); const objs = data ? data : this.data; if (!Array.isArray(objs)) return; // ctx.clearRect(0,0,canv.width, canv.height); if (this.shadow) { _preSetCtx(ctx); ctx.save(); } else { ctx.clearRect(0,0,this.canvas.width,this.canvas.height); } initCtx(ctx,this.blurWidth,"rgba(255,255,255,.4"); for(let i=0;i<objs.length;i++) { let x = objs[i][this.xfield], y = objs[i][this.yfield], radius = objs[i]['radius'] || 3, icon = objs[i]['icon'], label = objs[i]['name'], rotate = objs[i]['direction'] || 0; radius = Math.abs(radius); let pix = this.lnglat2pix(x, y); if (pix == null) continue; ctx.fillStyle = objs[i]['color'] || 'rgba(255,240,4,.9)'; ctx.beginPath(); if (label !== undefined && label.startsWith("Play")) radius = iconSize*0.75; // icon: ImageUrl/CanvasFunction..., clip part of img sometimes... if (icon !== undefined) { ctx.save(); ctx.translate(pix[0], pix[1]); ctx.rotate(rotate*Math.PI/180); let min = icon.height > icon.width ? icon.width : icon.height; try { ctx.drawImage(icon,0,0,min,min, -iconSize/2, -iconSize/2, iconSize, iconSize); } catch (e) { console.warn("ctx.drawImage.. error."); } ctx.restore(); } else { ctx.arc(pix[0], pix[1], radius, 0, Math.PI*2); ctx.fill(); } if (this.keepTrack && this.tracks.length == 0) { this.initTrackCtx(); this.trackCtx.moveTo(pix[0],pix[1]); this.tracks.push([x, y]); // this.movedTo = true; } else if (this.trackCtx) { this.trackCtx.lineTo(pix[0],pix[1]); this.tracks.push([x, y]); setTimeout(()=>{ //// closePath would auto-complete the path to polygon.. this.trackCtx.stroke(); this.trackCtx.beginPath(); this.trackCtx.moveTo(pix[0],pix[1]); }, 0); } if (label !== undefined && this.labelOn) { ctx.strokeText(label, pix[0], pix[1]); } // ctx.closePath(); } if(this.shadow) { ctx.restore();
} } function initCtx(ctx, blurWidth, shadowColor="rgba(255,255,255,.8)") { if (ctx === undefined) return; ctx.linecap = 'round'; ctx.shadowBlur = blurWidth; ctx.shadowColor = shadowColor; ctx.strokeStyle = "rgba(255,255,255,.9)"; ctx.fillStyle = "rgba(255,240,91,.8)"; } /** * draw tri on canvas by center and rotation.. * @param rotate: degree number, * @param radius: number, tri radius.. * /\ default beta angle is 30 degree. * / \ * /____\ * draw triangle */ function drawTri(ctx, coord, rotate, radius=iconSize/2, beta=30) { // calc the head point of triangle. let headPoint = [undefined, undefined], tailPoint = [undefined, undefined], rad = rotate*Math.PI/180; headPoint[0] = coord[0] + Math.cos(rad)*radius; headPoint[1] = coord[1] + Math.sin(rad)*radius; tailPoint[0] = coord[0] - Math.cos(rad)*radius; tailPoint[1] = coord[1] - Math.sin(rad)*radius; let rot = (rotate - beta/2), rPoint = [undefined, undefined]; rPoint[0] = Math.cos(rot*Math.PI/180); ctx.lineTo(headPoint); }
}
delete_ip_association.py
#!/usr/bin/python # Copyright (c) 2013, 2014-2017 Oracle and/or its affiliates. All rights reserved. """Provide Module Description """ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# __author__ = "Andrew Hopkinson (Oracle Cloud Solutions A-Team)" __copyright__ = "Copyright (c) 2013, 2014-2017 Oracle and/or its affiliates. All rights reserved." __ekitversion__ = "@VERSION@" __ekitrelease__ = "@RELEASE@" __version__ = "1.0.0.0" __date__ = "@BUILDDATE@" __status__ = "Development" __module__ = "delete-ip-association" # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# import datetime import getopt import json import locale import logging import operator import os import requests import sys # Import utility methods from occsutils import callRESTApi from occsutils import getPassword from occsutils import printJSON from authenticate import authenticate # Define methods def
(endpoint, resourcename, cookie): basepath = '/ip/association/' params = None data = None response = callRESTApi(endpoint, basepath, resourcename, data, 'DELETE', params, cookie) print(response) # jsonResponse = json.loads(response.text) jsonResponse = {} return jsonResponse # Read Module Arguments def readModuleArgs(opts, args): moduleArgs = {} moduleArgs['endpoint'] = None moduleArgs['user'] = None moduleArgs['password'] = None moduleArgs['pwdfile'] = None moduleArgs['cookie'] = None moduleArgs['resourcename'] = None # Read Module Command Line Arguments. for opt, arg in opts: if opt in ("-e", "--endpoint"): moduleArgs['endpoint'] = arg elif opt in ("-u", "--user"): moduleArgs['user'] = arg elif opt in ("-p", "--password"): moduleArgs['password'] = arg elif opt in ("-P", "--pwdfile"): moduleArgs['pwdfile'] = arg elif opt in ("-R", "--resourcename"): moduleArgs['resourcename'] = arg elif opt in ("-C", "--cookie"): moduleArgs['cookie'] = arg return moduleArgs # Main processing function def main(argv): # Configure Parameters and Options options = 'e:u:p:P:R:C:' longOptions = ['endpoint=', 'user=', 'password=', 'pwdfile=', 'resourcename=', 'cookie='] # Get Options & Arguments try: opts, args = getopt.getopt(argv, options, longOptions) # Read Module Arguments moduleArgs = readModuleArgs(opts, args) if moduleArgs['cookie'] is None and moduleArgs['endpoint'] is not None and moduleArgs['user'] is not None: if moduleArgs['password'] is None and moduleArgs['pwdfile'] is None: moduleArgs['password'] = getPassword(moduleArgs['user']) elif moduleArgs['pwdfile'] is not None: with open(moduleArgs['pwdfile'], 'r') as f: moduleArgs['password'] = f.read().rstrip('\n') moduleArgs['cookie'] = authenticate(moduleArgs['endpoint'], moduleArgs['user'], moduleArgs['password']) if moduleArgs['cookie'] is not None: jsonObj = deleteIPAssociation(moduleArgs['endpoint'], moduleArgs['resourcename'], moduleArgs['cookie']) printJSON(jsonObj) else: print ('Incorrect parameters') except getopt.GetoptError: usage() except Exception as e: print('Unknown Exception please check log file') logging.exception(e) sys.exit(1) return # Main function to kick off processing if __name__ == "__main__": main(sys.argv[1:])
deleteIPAssociation
progress-indicator-progress-handler.component.fixture.ts
import { Component, ViewChild } from '@angular/core'; import { Subject } from 'rxjs'; import { SkyProgressIndicatorComponent } from '../progress-indicator.component'; import { SkyProgressIndicatorActionClickArgs } from '../types/progress-indicator-action-click-args'; import { SkyProgressIndicatorMessage } from '../types/progress-indicator-message'; @Component({ selector: 'sky-progress-indicator-progress-handler-fixture',
static: true, }) public progressIndicator: SkyProgressIndicatorComponent; public isLoading = false; public messageStream = new Subject<SkyProgressIndicatorMessage>(); public onFinishClick(args: SkyProgressIndicatorActionClickArgs): void { // Simulate an asynchronous call. this.isLoading = true; setTimeout(() => { args.progressHandler.advance(); this.isLoading = false; }); } public sendMessage(message: SkyProgressIndicatorMessage): void { this.messageStream.next(message); } }
templateUrl: './progress-indicator-progress-handler.component.fixture.html', }) export class SkyProgressIndicatorProgressHandlerFixtureComponent { @ViewChild(SkyProgressIndicatorComponent, {
Keycap11.tsx
import * as React from "react"; import { IEmojiProps } from "../../styled"; const SvgKeycap11 = (props: IEmojiProps) => ( <svg viewBox="0 0 72 72" width="1em" height="1em" {...props}> <path fill="#d0cfce" d="M11.875 12.166h48V60h-48z" /> <g fill="none" stroke="#000"
strokeLinejoin="round" strokeWidth={2} > <path d="M12.125 11.916h48v48h-48z" /> <path d="M30.984 31.679v-4.293h9.782l-6.044 17.395" /> </g> </svg> ); export default SvgKeycap11;
strokeLinecap="round"
input-group.component.ts
import { Component, Input, Output, EventEmitter, forwardRef, ViewEncapsulation, ContentChild, TemplateRef, ChangeDetectionStrategy, ChangeDetectorRef, } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { InputGroupAddOnDirective, InputGroupInputDirective } from './input-group-directives'; import { FormStates } from '../form/form-control/form-states'; import { ButtonType } from '../button/button.component'; export type InputGroupPlacement = 'before' | 'after'; /** * The component that represents an input group. * The input group includes form inputs with add-ons that allow the user to better understand the information being entered. * * ```html * <fd-input-group [placement]="'after'" [addOnText]="'$'" [placeholder]="'Amount'"> * </fd-input-group> * ``` */ @Component({ selector: 'fd-input-group', templateUrl: './input-group.component.html', styleUrls: ['./input-group.component.scss'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => InputGroupComponent),
multi: true } ], encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush }) export class InputGroupComponent implements ControlValueAccessor { /** @hidden */ @ContentChild(InputGroupInputDirective) inputElement: InputGroupInputDirective; /** @hidden */ @ContentChild(InputGroupAddOnDirective) addOnElement: InputGroupAddOnDirective; /** Input template */ @Input() inputTemplate: TemplateRef<any>; /** * The placement of the add-on. * Options include *before* and *after* */ @Input() placement: InputGroupPlacement = 'after'; /** Whether the input group is in compact mode. */ @Input() compact: boolean = false; /** Whether the input group is inline. */ @Input() inline: boolean; /** Placeholder for the input group. */ @Input() placeholder: string; /** The text for the add-on. */ @Input() addOnText: string; /** Whether AddOn Button should be focusable */ @Input() buttonFocusable: boolean = true; /** * @deprecated, leaving for backwards compatibility, it will be removed in `0.17.0`. */ @Input() buttonType: ButtonType; /** The type of the input, used in Input Group. By default value is set to 'text' */ @Input() type: string = 'text'; /** The icon value for the add-on. */ @Input() glyph: string; /** Whether the icon add-on or the text add-on is a button. */ @Input() button: boolean; /** Whether the input group is disabled. */ @Input() disabled: boolean; /** * The state of the form control - applies css classes. * Can be `success`, `error`, `warning`, `information` or blank for default. */ @Input() state: FormStates; /** * Whether the input group is a popover control */ @Input() isControl: boolean = false; /** @hidden */ @Input() isExpanded: boolean = false; /** Event emitted when the add-on button is clicked. */ @Output() addOnButtonClicked: EventEmitter<any> = new EventEmitter<any>(); /** @hidden */ constructor(private changeDetectorRef: ChangeDetectorRef) {} /** @hidden */ inputTextValue: string; /** * Whether or not the input coup is in the shellbar. Only for internal use by combobox component * @hidden */ inShellbar: boolean = false; /** @hidden */ onChange: any = () => {}; /** @hidden */ onTouched: any = () => {}; /** Get the value of the text input. */ get inputText(): string { return this.inputTextValue; } /** Set the value of the text input. */ set inputText(value) { this.inputTextValue = value; this.onChange(value); this.onTouched(); } /** @hidden */ writeValue(value: any): void { this.inputTextValue = value; this.changeDetectorRef.markForCheck(); } /** @hidden */ registerOnChange(fn): void { this.onChange = fn; } /** @hidden */ registerOnTouched(fn): void { this.onTouched = fn; } /** @hidden */ setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; this.changeDetectorRef.markForCheck(); } /** @hidden */ setInShellbar(value: boolean): void { this.inShellbar = value; this.changeDetectorRef.markForCheck(); } /** @hidden */ buttonClicked($event): void { this.addOnButtonClicked.emit($event); } }
new-bp.component.ts
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup } from '@angular/forms'; import { Router } from '@angular/router'; import { BpService } from '../services/bp.service'; @Component({ selector: 'new-bp', templateUrl: './new-bp.component.html', styleUrls: ['./new-bp.component.scss'], }) export class NewBPComponent implements OnInit { newBPForm: FormGroup; bp_nombre = new FormControl('');
bp_fecha_inicio = new FormControl(); bp_fecha_fin = new FormControl(); bp_presentacion = new FormControl(); bp_firma_contrato_esa = new FormControl(); bp_kick_off = new FormControl(); bp_plan_negocios = new FormControl(); bp_comercial = new FormControl(); bp_readiness = new FormControl(); bp_com_prensa = new FormControl(); bp_num_oppty = new FormControl(); bp_monto_oppty = new FormControl(); bp_quarter_closed = new FormControl(); bp_dia_cadencia = new FormControl(); bp_sig_pasos = new FormControl(); bp_cad_sem = new FormControl(); constructor( private formBuilder: FormBuilder, private router: Router, private bpService: BpService ) {} ngOnInit(): void { this.newBPForm = this.formBuilder.group({ bp_nombre: this.bp_nombre, bp_perfilamiento: this.bp_perfilamiento, bp_tipo: this.bp_tipo, bp_fecha_inicio: this.bp_fecha_inicio, bp_fecha_fin: this.bp_fecha_fin, bp_presentacion: this.bp_presentacion, bp_firma_contrato_esa: this.bp_firma_contrato_esa, bp_kick_off: this.bp_kick_off, bp_plan_negocios: this.bp_plan_negocios, bp_comercial: this.bp_comercial, bp_readiness: this.bp_readiness, bp_com_prensa: this.bp_com_prensa, bp_quarter_closed: this.bp_quarter_closed, bp_dia_cadencia: this.bp_dia_cadencia, bp_sig_pasos: this.bp_sig_pasos, bp_cad_sem: this.bp_cad_sem, }); } newBP() { this.bpService.newBP(this.newBPForm.value).subscribe( (ans: any) => console.log('bp creado correctamente'), (err: any) => console.error(err), () => { this.router.navigate([`/bp`]); } ); } }
bp_perfilamiento = new FormControl(''); bp_tipo = new FormControl('');
lifegame_lj.py
""" 左寄せ表記(Left justified) """ import os import numpy as np # 環境変数 RADIX = int(os.getenv("RADIX", 2)) # 桁揃えに利用。10進数27 を指定したときの見やすさをデフォルトにするぜ(^~^) count_width = 3 count_str = "" dec_width = 4 dec_str = "" radix_str = "" # 表示した数の個数 count = 0 def update_print_number(dec): """表示するテキストの更新""" global count_width global count_str global dec_wid
tr global radix_str global count global RADIX count_str = f"{count}" # 桁数の更新 if count_width < len(count_str): count_width += 1 if dec_width < len(str(dec)): dec_width += 1 count_str = count_str.rjust(count_width) radix_str = str(np.base_repr(dec, RADIX)) dec_str = str(dec).rjust(dec_width) count += 1 def print_number(): """表示""" global count_str global dec_str global radix_str print(f"[{count_str}] ({dec_str}) {radix_str}") # 数を入力してください。 print(f"RADIX={RADIX}") print("Please enter a number.") print("Example 1: 27") print("Example 2: 0b11011") # めんどくさいんで、内部的には10進で計算 number_str = input() if number_str.startswith("0b"): radix_str = number_str[2:] dec = int(radix_str, 2) # 2進数で入力されたものを10進に変換 else: dec = int(number_str) # 10進数 # 初回表示 print(f"Start") update_print_number(dec) print_number() while True: # 奇数になるまで2で割るぜ(^~^) while dec % 2 == 0: dec = dec // 2 # 表示 # TODO 偶数なんで省くオプションとか欲しい(^~^) update_print_number(dec) print_number() # 1 だったら抜けるぜ(^~^) if dec==1: break # 3x+1 するぜ(^~^) dec = 3 * dec + 1 # 表示 update_print_number(dec) print_number() print(f"Finished")
th global dec_s
test_merge.py
"""Tests for dials.merge command line program.""" import procrunner import pytest from cctbx import uctbx from dxtbx.model.experiment_list import ExperimentListFactory from iotbx import mtz from dials.array_family import flex def validate_mtz(mtz_file, expected_labels, unexpected_labels=None): assert mtz_file.check() m = mtz.object(mtz_file.strpath) assert m.as_miller_arrays()[0].info().wavelength == pytest.approx(0.6889) labels = set() for ma in m.as_miller_arrays(merge_equivalents=False): labels.update(ma.info().labels) for l in expected_labels: assert l in labels if unexpected_labels: for l in unexpected_labels: assert l not in labels @pytest.mark.parametrize("anomalous", [True, False]) @pytest.mark.parametrize("truncate", [True, False]) def test_merge(dials_data, tmpdir, anomalous, truncate): """Test the command line script with LCY data""" # Main options: truncate on/off, anomalous on/off mean_labels = ["IMEAN", "SIGIMEAN"] anom_labels = ["I(+)", "I(-)", "SIGI(+)", "SIGI(-)"] amp_labels = ["F", "SIGF"] anom_amp_labels = ["F(+)", "SIGF(+)", "F(-)", "SIGF(-)"] location = dials_data("l_cysteine_4_sweeps_scaled") refls = location.join("scaled_20_25.refl") expts = location.join("scaled_20_25.expt") mtz_file = tmpdir.join(f"merge-{anomalous}-{truncate}.mtz") command = [ "dials.merge", refls, expts, f"truncate={truncate}", f"anomalous={anomalous}", f"output.mtz={mtz_file.strpath}", "project_name=ham", "crystal_name=jam", "dataset_name=spam", ] result = procrunner.run(command, working_directory=tmpdir) assert not result.returncode and not result.stderr if truncate and anomalous: assert tmpdir.join("dials.merge.html").check() else: assert not tmpdir.join("dials.merge.html").check() expected_labels = mean_labels unexpected_labels = [] if truncate: expected_labels += amp_labels else: unexpected_labels += amp_labels if anomalous: expected_labels += anom_labels else: unexpected_labels += anom_labels if anomalous and truncate: expected_labels += anom_amp_labels else: unexpected_labels += anom_amp_labels validate_mtz(mtz_file, expected_labels, unexpected_labels) @pytest.mark.parametrize("best_unit_cell", [None, "5.5,8.1,12.0,90,90,90"]) def test_merge_dmin_dmax(dials_data, tmpdir, best_unit_cell): """Test the d_min, d_max""" location = dials_data("l_cysteine_4_sweeps_scaled") refls = location.join("scaled_20_25.refl") expts = location.join("scaled_20_25.expt") mtz_file = tmpdir.join("merge.mtz") command = [ "dials.merge", refls, expts, "truncate=False", "anomalous=False", "d_min=1.0", "d_max=8.0", f"output.mtz={mtz_file.strpath}", "project_name=ham", "crystal_name=jam", "dataset_name=spam", f"best_unit_cell={best_unit_cell}", ] result = procrunner.run(command, working_directory=tmpdir) assert not result.returncode and not result.stderr # check the unit cell was correctly set if using best_unit_cell m = mtz.object(mtz_file.strpath) if best_unit_cell: for ma in m.as_miller_arrays(): assert uctbx.unit_cell(best_unit_cell).parameters() == pytest.approx( ma.unit_cell().parameters() ) # check we only have reflections in range 8 - 1A max_min_resolution = m.max_min_resolution() assert max_min_resolution[0] <= 8 assert max_min_resolution[1] >= 1 def
(dials_data, tmpdir): """Test that merge handles multi-wavelength data suitably - should be exported into an mtz with seprate columns for each wavelength.""" mean_labels = [f"{pre}IMEAN_WAVE{i}" for i in [1, 2] for pre in ["", "SIG"]] anom_labels = [ f"{pre}I_WAVE{i}({sgn})" for i in [1, 2] for pre in ["", "SIG"] for sgn in ["+", "-"] ] amp_labels = [f"{pre}F_WAVE{i}" for i in [1, 2] for pre in ["", "SIG"]] anom_amp_labels = [ f"{pre}F_WAVE{i}({sgn})" for i in [1, 2] for pre in ["", "SIG"] for sgn in ["+", "-"] ] location = dials_data("l_cysteine_4_sweeps_scaled") refl1 = location.join("scaled_30.refl").strpath expt1 = location.join("scaled_30.expt").strpath refl2 = location.join("scaled_35.refl").strpath expt2 = location.join("scaled_35.expt").strpath expts1 = ExperimentListFactory.from_json_file(expt1, check_format=False) expts1[0].beam.set_wavelength(0.7) expts2 = ExperimentListFactory.from_json_file(expt2, check_format=False) expts1.extend(expts2) tmp_expt = tmpdir.join("tmp.expt").strpath expts1.as_json(tmp_expt) reflections1 = flex.reflection_table.from_pickle(refl1) reflections2 = flex.reflection_table.from_pickle(refl2) # first need to resolve identifiers - usually done on loading reflections2["id"] = flex.int(reflections2.size(), 1) del reflections2.experiment_identifiers()[0] reflections2.experiment_identifiers()[1] = "3" reflections1.extend(reflections2) tmp_refl = tmpdir.join("tmp.refl").strpath reflections1.as_file(tmp_refl) # Can now run after creating our 'fake' multiwavelength dataset command = ["dials.merge", tmp_refl, tmp_expt, "truncate=True", "anomalous=True"] result = procrunner.run(command, working_directory=tmpdir) assert not result.returncode and not result.stderr assert tmpdir.join("merged.mtz").check() assert tmpdir.join("dials.merge.html").check() m = mtz.object(tmpdir.join("merged.mtz").strpath) labels = [] for ma in m.as_miller_arrays(merge_equivalents=False): labels.extend(ma.info().labels) assert all(x in labels for x in mean_labels) assert all(x in labels for x in anom_labels) assert all(x in labels for x in amp_labels) assert all(x in labels for x in anom_amp_labels) # 5 miller arrays for each dataset, check the expected number of reflections. arrays = m.as_miller_arrays() assert arrays[0].info().wavelength == pytest.approx(0.7) assert arrays[5].info().wavelength == pytest.approx(0.6889) assert abs(arrays[0].size() - 1223) < 10 assert abs(arrays[5].size() - 1453) < 10 # test changing the wavelength tolerance such that data is combined under # one wavelength. Check the number of reflections to confirm this. command = [ "dials.merge", tmp_refl, tmp_expt, "truncate=True", "anomalous=True", "wavelength_tolerance=0.02", ] result = procrunner.run(command, working_directory=tmpdir) assert not result.returncode and not result.stderr m = mtz.object(tmpdir.join("merged.mtz").strpath) arrays = m.as_miller_arrays() assert arrays[0].info().wavelength == pytest.approx(0.7) assert len(arrays) == 5 assert abs(arrays[0].size() - 1538) < 10 def test_suitable_exit_for_bad_input_from_single_dataset(dials_data, tmpdir): location = dials_data("vmxi_proteinase_k_sweeps") command = [ "dials.merge", location.join("experiments_0.json"), location.join("reflections_0.pickle"), ] # unscaled data result = procrunner.run(command, working_directory=tmpdir) assert result.returncode assert ( result.stderr.replace(b"\r", b"") == b"""Sorry: intensity.scale.value not found in the reflection table. Only scaled data can be processed with dials.merge """ ) def test_suitable_exit_for_bad_input_with_more_than_one_reflection_table( dials_data, tmpdir ): location = dials_data("vmxi_proteinase_k_sweeps") command = [ "dials.merge", location.join("experiments_0.json"), location.join("reflections_0.pickle"), location.join("experiments_1.json"), location.join("reflections_1.pickle"), ] # more than one reflection table. result = procrunner.run(command, working_directory=tmpdir) assert result.returncode assert ( result.stderr.replace(b"\r", b"") == b"""Sorry: Only data scaled together as a single reflection dataset can be processed with dials.merge """ )
test_merge_multi_wavelength
i386.rs
use std::io::{BufRead, BufReader}; static I386: &[u8] = include_bytes!("../data/i386.txt"); static WORDS: &[u8] = include_bytes!("../data/words.txt"); fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> { haystack .windows(needle.len()) .position(|window| window == needle) } fn search(haystack: &str, needle: &str)
#[test] fn search_short_haystack() { let mut needles = BufReader::new(WORDS) .lines() .map(Result::unwrap) .collect::<Vec<_>>(); needles.sort_unstable_by_key(|needle| needle.len()); for (i, needle) in needles.iter().enumerate() { for haystack in &needles[i..] { search(haystack, needle); } } } #[test] fn search_long_haystack() { let haystack = String::from_utf8_lossy(I386); let needles = BufReader::new(WORDS).lines().map(Result::unwrap); for needle in needles { search(&haystack, &needle); } }
{ let haystack = haystack.as_bytes(); let needle = needle.as_bytes(); let result = find_subsequence(haystack, needle).is_some(); cfg_if::cfg_if! { if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] { use sliceslice::x86::DynamicAvx2Searcher; let searcher = unsafe { DynamicAvx2Searcher::new(needle.to_owned().into_boxed_slice()) }; assert_eq!(unsafe { searcher.search_in(haystack) }, result); } else { compile_error!("Unsupported architecture"); } } }
evaluator.go
// Package evaluator defines a Evaluator interfaces that can be implemented by // a policy evaluator framework. package evaluator import ( "context" "crypto/ecdsa" "encoding/base64" "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "strconv" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes" "github.com/open-policy-agent/opa/rego" "google.golang.org/protobuf/reflect/protoregistry" "google.golang.org/protobuf/types/known/anypb" "gopkg.in/square/go-jose.v2" "github.com/pomerium/pomerium/config" "github.com/pomerium/pomerium/internal/directory" "github.com/pomerium/pomerium/internal/log" "github.com/pomerium/pomerium/pkg/cryptutil" "github.com/pomerium/pomerium/pkg/grpc/databroker" "github.com/pomerium/pomerium/pkg/grpc/session" "github.com/pomerium/pomerium/pkg/grpc/user" ) const ( sessionTypeURL = "type.googleapis.com/session.Session" userTypeURL = "type.googleapis.com/user.User" directoryUserTypeURL = "type.googleapis.com/directory.User" directoryGroupTypeURL = "type.googleapis.com/directory.Group" ) // Evaluator specifies the interface for a policy engine. type Evaluator struct { custom *CustomEvaluator rego *rego.Rego query rego.PreparedEvalQuery policies []config.Policy clientCA string authenticateHost string jwk interface{} kid string } // New creates a new Evaluator. func New(options *config.Options, store *Store) (*Evaluator, error) { e := &Evaluator{ custom: NewCustomEvaluator(store.opaStore), authenticateHost: options.AuthenticateURL.Host, policies: options.Policies, } if options.ClientCA != "" { e.clientCA = options.ClientCA } else if options.ClientCAFile != "" { bs, err := ioutil.ReadFile(options.ClientCAFile) if err != nil { return nil, err } e.clientCA = string(bs) } if options.SigningKey == "" { key, err := cryptutil.NewSigningKey() if err != nil { return nil, fmt.Errorf("authorize: couldn't generate signing key: %w", err) } e.jwk = key pubKeyBytes, err := cryptutil.EncodePublicKey(&key.PublicKey) if err != nil { return nil, fmt.Errorf("authorize: encode public key: %w", err) } log.Info().Interface("PublicKey", pubKeyBytes).Msg("authorize: ecdsa public key") } else { decodedCert, err := base64.StdEncoding.DecodeString(options.SigningKey) if err != nil { return nil, fmt.Errorf("authorize: failed to decode certificate cert %v: %w", decodedCert, err) } key, err := cryptutil.DecodePrivateKey(decodedCert) if err != nil { return nil, fmt.Errorf("authorize: couldn't generate signing key: %w", err) } e.jwk = key jwk, err := cryptutil.PublicJWKFromBytes(decodedCert, jose.ES256) if err != nil { return nil, fmt.Errorf("authorize: failed to convert jwk: %w", err) } e.kid = jwk.KeyID } authzPolicy, err := readPolicy("/authz.rego") if err != nil { return nil, fmt.Errorf("error loading rego policy: %w", err) } store.UpdateAdmins(options.Administrators) store.UpdateRoutePolicies(options.Policies) e.rego = rego.New( rego.Store(store.opaStore), rego.Module("pomerium.authz", string(authzPolicy)), rego.Query("result = data.pomerium.authz"), ) e.query, err = e.rego.PrepareForEval(context.Background()) if err != nil { return nil, fmt.Errorf("error preparing rego query: %w", err) } return e, nil } // Evaluate evaluates the policy against the request. func (e *Evaluator) Evaluate(ctx context.Context, req *Request) (*Result, error) { isValid, err := isValidClientCertificate(e.clientCA, req.HTTP.ClientCertificate) if err != nil { return nil, fmt.Errorf("error validating client certificate: %w", err) } res, err := e.query.Eval(ctx, rego.EvalInput(e.newInput(req, isValid))) if err != nil { return nil, fmt.Errorf("error evaluating rego policy: %w", err) } deny := getDenyVar(res[0].Bindings.WithoutWildcards()) if len(deny) > 0 { return &deny[0], nil } payload := e.JWTPayload(req) signedJWT, err := e.SignedJWT(payload) if err != nil { return nil, fmt.Errorf("error signing JWT: %w", err) } evalResult := &Result{ MatchingPolicy: getMatchingPolicy(res[0].Bindings.WithoutWildcards(), e.policies), SignedJWT: signedJWT, } if e, ok := payload["email"].(string); ok { evalResult.UserEmail = e } if gs, ok := payload["groups"].([]string); ok { evalResult.UserGroups = gs } allow := allowed(res[0].Bindings.WithoutWildcards()) // evaluate any custom policies if allow { for _, src := range req.CustomPolicies { cres, err := e.custom.Evaluate(ctx, &CustomEvaluatorRequest{ RegoPolicy: src, HTTP: req.HTTP, Session: req.Session, }) if err != nil { return nil, err } allow = allow && (cres.Allowed && !cres.Denied) if cres.Reason != "" { evalResult.Message = cres.Reason } } } if allow { evalResult.Status = http.StatusOK evalResult.Message = "OK" return evalResult, nil } if req.Session.ID == "" { evalResult.Status = http.StatusUnauthorized evalResult.Message = "login required" return evalResult, nil } evalResult.Status = http.StatusForbidden if evalResult.Message == "" { evalResult.Message = "forbidden" } return evalResult, nil } // ParseSignedJWT parses the input signature and return its payload. func (e *Evaluator) ParseSignedJWT(signature string) ([]byte, error) { object, err := jose.ParseSigned(signature) if err != nil { return nil, err } return object.Verify(&(e.jwk.(*ecdsa.PrivateKey).PublicKey)) } // JWTPayload returns the JWT payload for a request. func (e *Evaluator) JWTPayload(req *Request) map[string]interface{} { payload := map[string]interface{}{ "iss": e.authenticateHost, } if u, err := url.Parse(req.HTTP.URL); err == nil { payload["aud"] = u.Hostname() } if s, ok := req.DataBrokerData.Get("type.googleapis.com/session.Session", req.Session.ID).(*session.Session); ok { payload["jti"] = s.GetId() if tm, err := ptypes.Timestamp(s.GetIdToken().GetExpiresAt()); err == nil { payload["exp"] = tm.Unix() } if tm, err := ptypes.Timestamp(s.GetIdToken().GetIssuedAt()); err == nil { payload["iat"] = tm.Unix() } if u, ok := req.DataBrokerData.Get("type.googleapis.com/user.User", s.GetUserId()).(*user.User); ok { payload["sub"] = u.GetId() payload["user"] = u.GetId() payload["email"] = u.GetEmail() } if du, ok := req.DataBrokerData.Get("type.googleapis.com/directory.User", s.GetUserId()).(*directory.User); ok { var groupNames []string for _, groupID := range du.GetGroupIds() { if dg, ok := req.DataBrokerData.Get("type.googleapis.com/directory.Group", groupID).(*directory.Group); ok { groupNames = append(groupNames, dg.Name) } } var groups []string groups = append(groups, du.GetGroupIds()...) groups = append(groups, groupNames...) payload["groups"] = groups } } return payload } // SignedJWT returns the signature of given request. func (e *Evaluator) SignedJWT(payload map[string]interface{}) (string, error) { signerOpt := &jose.SignerOptions{} signer, err := jose.NewSigner(jose.SigningKey{ Algorithm: jose.ES256, Key: e.jwk, }, signerOpt.WithHeader("kid", e.kid)) if err != nil { return "", err } bs, err := json.Marshal(payload) if err != nil { return "", err } jws, err := signer.Sign(bs) if err != nil { return "", err } return jws.CompactSerialize() } type input struct { DataBrokerData dataBrokerDataInput `json:"databroker_data"` HTTP RequestHTTP `json:"http"` Session RequestSession `json:"session"` IsValidClientCertificate bool `json:"is_valid_client_certificate"` } type dataBrokerDataInput struct { Session interface{} `json:"session,omitempty"` User interface{} `json:"user,omitempty"` Groups interface{} `json:"groups,omitempty"` } func (e *Evaluator) newInput(req *Request, isValidClientCertificate bool) *input { i := new(input) i.DataBrokerData.Session = req.DataBrokerData.Get(sessionTypeURL, req.Session.ID) if obj, ok := i.DataBrokerData.Session.(interface{ GetUserId() string }); ok { i.DataBrokerData.User = req.DataBrokerData.Get(userTypeURL, obj.GetUserId()) user, ok := req.DataBrokerData.Get(directoryUserTypeURL, obj.GetUserId()).(*directory.User) if ok { var groups []string for _, groupID := range user.GetGroupIds() { if dg, ok := req.DataBrokerData.Get(directoryGroupTypeURL, groupID).(*directory.Group); ok { if dg.Name != "" { groups = append(groups, dg.Name) } if dg.Email != "" { groups = append(groups, dg.Email) } } } groups = append(groups, user.GetGroupIds()...) i.DataBrokerData.Groups = groups } } i.HTTP = req.HTTP i.Session = req.Session i.IsValidClientCertificate = isValidClientCertificate return i } type ( // Request is the request data used for the evaluator. Request struct { DataBrokerData DataBrokerData `json:"databroker_data"` HTTP RequestHTTP `json:"http"` Session RequestSession `json:"session"` CustomPolicies []string } // RequestHTTP is the HTTP field in the request. RequestHTTP struct { Method string `json:"method"` URL string `json:"url"` Headers map[string]string `json:"headers"` ClientCertificate string `json:"client_certificate"` } // RequestSession is the session field in the request. RequestSession struct { ID string `json:"id"` ImpersonateEmail string `json:"impersonate_email"` ImpersonateGroups []string `json:"impersonate_groups"` } ) // Result is the result of evaluation. type Result struct { Status int Message string SignedJWT string MatchingPolicy *config.Policy UserEmail string UserGroups []string } func
(vars rego.Vars, policies []config.Policy) *config.Policy { result, ok := vars["result"].(map[string]interface{}) if !ok { return nil } idx, err := strconv.Atoi(fmt.Sprint(result["route_policy_idx"])) if err != nil { return nil } if idx >= len(policies) { return nil } return &policies[idx] } func allowed(vars rego.Vars) bool { result, ok := vars["result"].(map[string]interface{}) if !ok { return false } allow, ok := result["allow"].(bool) if !ok { return false } return allow } func getDenyVar(vars rego.Vars) []Result { result, ok := vars["result"].(map[string]interface{}) if !ok { return nil } denials, ok := result["deny"].([]interface{}) if !ok { return nil } results := make([]Result, 0, len(denials)) for _, denial := range denials { denial, ok := denial.([]interface{}) if !ok || len(denial) != 2 { continue } status, err := strconv.Atoi(fmt.Sprint(denial[0])) if err != nil { log.Error().Err(err).Msg("invalid type in deny") continue } msg := fmt.Sprint(denial[1]) results = append(results, Result{ Status: status, Message: msg, }) } return results } // DataBrokerData stores the data broker data by type => id => record type DataBrokerData map[string]map[string]interface{} // Clear removes all the data for the given type URL from the databroekr data. func (dbd DataBrokerData) Clear(typeURL string) { delete(dbd, typeURL) } // Get gets a record from the DataBrokerData. func (dbd DataBrokerData) Get(typeURL, id string) interface{} { m, ok := dbd[typeURL] if !ok { return nil } return m[id] } // Update updates a record in the DataBrokerData. func (dbd DataBrokerData) Update(record *databroker.Record) { db, ok := dbd[record.GetType()] if !ok { db = make(map[string]interface{}) dbd[record.GetType()] = db } if record.GetDeletedAt() != nil { delete(db, record.GetId()) } else { if obj, err := unmarshalAny(record.GetData()); err == nil { db[record.GetId()] = obj } else { log.Warn().Err(err).Msg("failed to unmarshal unknown any type") delete(db, record.GetId()) } } } func unmarshalAny(any *anypb.Any) (proto.Message, error) { messageType, err := protoregistry.GlobalTypes.FindMessageByURL(any.GetTypeUrl()) if err != nil { return nil, err } msg := proto.MessageV1(messageType.New()) return msg, ptypes.UnmarshalAny(any, msg) }
getMatchingPolicy
panel_time_range.ts
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ import { FtrProviderContext } from '../../ftr_provider_context'; import { CommonlyUsed } from '../../../../../test/functional/page_objects/time_picker';
const log = getService('log'); const testSubjects = getService('testSubjects'); return new (class DashboardPanelTimeRange { public readonly MODAL_TEST_SUBJ = 'customizeTimeRangeModal'; public readonly CUSTOM_TIME_RANGE_ACTION = 'CUSTOM_TIME_RANGE'; public async clickTimeRangeActionInContextMenu() { log.debug('clickTimeRangeActionInContextMenu'); await testSubjects.click('embeddablePanelAction-CUSTOM_TIME_RANGE'); } public async findModal() { log.debug('findModal'); return await testSubjects.find(this.MODAL_TEST_SUBJ); } public async findModalTestSubject(testSubject: string) { log.debug('findModalElement'); const modal = await this.findModal(); return await modal.findByCssSelector(`[data-test-subj="${testSubject}"]`); } public async findToggleQuickMenuButton() { log.debug('findToggleQuickMenuButton'); return await this.findModalTestSubject('superDatePickerToggleQuickMenuButton'); } public async clickToggleQuickMenuButton() { log.debug('clickToggleQuickMenuButton'); const button = await this.findToggleQuickMenuButton(); await button.click(); } public async clickCommonlyUsedTimeRange(time: CommonlyUsed) { log.debug('clickCommonlyUsedTimeRange', time); await testSubjects.click(`superDatePickerCommonlyUsed_${time}`); } public async clickModalPrimaryButton() { log.debug('clickModalPrimaryButton'); const button = await this.findModalTestSubject('addPerPanelTimeRangeButton'); await button.click(); } public async clickRemovePerPanelTimeRangeButton() { log.debug('clickRemovePerPanelTimeRangeButton'); const button = await this.findModalTestSubject('removePerPanelTimeRangeButton'); await button.click(); } })(); }
export function DashboardPanelTimeRangeProvider({ getService }: FtrProviderContext) {
dummy3.rs
// comment file 2
// comment line 3
router.js
/** * @license Angular v9.1.3 * (c) 2010-2020 Google LLC. https://angular.io/ * License: MIT */ import { LocationStrategy, Location, PlatformLocation, APP_BASE_HREF, ViewportScroller, HashLocationStrategy, PathLocationStrategy, ɵgetDOM, LOCATION_INITIALIZED } from '@angular/common'; import { Component, ɵisObservable, ɵisPromise, NgModuleRef, InjectionToken, NgModuleFactory, ɵConsole, NgZone, isDevMode, Directive, Attribute, Renderer2, ElementRef, Input, HostListener, HostBinding, Optional, ContentChildren, EventEmitter, ViewContainerRef, ComponentFactoryResolver, ChangeDetectorRef, Output, Injectable, NgModuleFactoryLoader, Compiler, Injector, SystemJsNgModuleLoader, NgProbeToken, ANALYZE_FOR_ENTRY_COMPONENTS, SkipSelf, Inject, APP_INITIALIZER, APP_BOOTSTRAP_LISTENER, NgModule, ApplicationRef, Version } from '@angular/core'; import { of, from, BehaviorSubject, Observable, EmptyError, combineLatest, defer, Subject, EMPTY } from 'rxjs'; import { map, concatAll, last as last$1, catchError, first, mergeMap, every, switchMap, take, startWith, scan, filter, concatMap, reduce, tap, finalize, mergeAll } from 'rxjs/operators'; /** * @fileoverview added by tsickle * Generated from: packages/router/src/events.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Base for events the router goes through, as opposed to events tied to a specific * route. Fired one time for any given navigation. * * \@usageNotes * * ```ts * class MyService { * constructor(public router: Router, logger: Logger) { * router.events.pipe( * filter(e => e instanceof RouterEvent) * ).subscribe(e => { * logger.log(e.id, e.url); * }); * } * } * ``` * * @see `Event` * \@publicApi */ import * as ɵngcc0 from '@angular/core'; import * as ɵngcc1 from '@angular/common'; class RouterEvent { /** * @param {?} id * @param {?} url */ constructor(id, url) { this.id = id; this.url = url; } } if (false) { /** * A unique ID that the router assigns to every router navigation. * @type {?} */ RouterEvent.prototype.id; /** * The URL that is the destination for this navigation. * @type {?} */ RouterEvent.prototype.url; } /** * An event triggered when a navigation starts. * * \@publicApi */ class NavigationStart extends RouterEvent { /** * @param {?} id * @param {?} url * @param {?=} navigationTrigger * @param {?=} restoredState */ constructor( /** @docsNotRequired */ id, /** @docsNotRequired */ url, /** @docsNotRequired */ navigationTrigger = 'imperative', /** @docsNotRequired */ restoredState = null) { super(id, url); this.navigationTrigger = navigationTrigger; this.restoredState = restoredState; } /** * \@docsNotRequired * @return {?} */ toString() { return `NavigationStart(id: ${this.id}, url: '${this.url}')`; } } if (false) { /** * Identifies the call or event that triggered the navigation. * An `imperative` trigger is a call to `router.navigateByUrl()` or `router.navigate()`. * * @type {?} */ NavigationStart.prototype.navigationTrigger; /** * The navigation state that was previously supplied to the `pushState` call, * when the navigation is triggered by a `popstate` event. Otherwise null. * * The state object is defined by `NavigationExtras`, and contains any * developer-defined state value, as well as a unique ID that * the router assigns to every router transition/navigation. * * From the perspective of the router, the router never "goes back". * When the user clicks on the back button in the browser, * a new navigation ID is created. * * Use the ID in this previous-state object to differentiate between a newly created * state and one returned to by a `popstate` event, so that you can restore some * remembered state, such as scroll position. * * @type {?} */ NavigationStart.prototype.restoredState; } /** * An event triggered when a navigation ends successfully. * * \@publicApi */ class NavigationEnd extends RouterEvent { /** * @param {?} id * @param {?} url * @param {?} urlAfterRedirects */ constructor( /** @docsNotRequired */ id, /** @docsNotRequired */ url, urlAfterRedirects) { super(id, url); this.urlAfterRedirects = urlAfterRedirects; } /** * \@docsNotRequired * @return {?} */ toString() { return `NavigationEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}')`; } } if (false) { /** * \@docsNotRequired * @type {?} */ NavigationEnd.prototype.urlAfterRedirects; } /** * An event triggered when a navigation is canceled, directly or indirectly. * * This can happen when a [route guard](guide/router#milestone-5-route-guards) * returns `false` or initiates a redirect by returning a `UrlTree`. * * \@publicApi */ class NavigationCancel extends RouterEvent { /** * @param {?} id * @param {?} url * @param {?} reason */ constructor( /** @docsNotRequired */ id, /** @docsNotRequired */ url, reason) { super(id, url); this.reason = reason; } /** * \@docsNotRequired * @return {?} */ toString() { return `NavigationCancel(id: ${this.id}, url: '${this.url}')`; } } if (false) { /** * \@docsNotRequired * @type {?} */ NavigationCancel.prototype.reason; } /** * An event triggered when a navigation fails due to an unexpected error. * * \@publicApi */ class NavigationError extends RouterEvent { /** * @param {?} id * @param {?} url * @param {?} error */ constructor( /** @docsNotRequired */ id, /** @docsNotRequired */ url, error) { super(id, url); this.error = error; } /** * \@docsNotRequired * @return {?} */ toString() { return `NavigationError(id: ${this.id}, url: '${this.url}', error: ${this.error})`; } } if (false) { /** * \@docsNotRequired * @type {?} */ NavigationError.prototype.error; } /** * An event triggered when routes are recognized. * * \@publicApi */ class RoutesRecognized extends RouterEvent { /** * @param {?} id * @param {?} url * @param {?} urlAfterRedirects * @param {?} state */ constructor( /** @docsNotRequired */ id, /** @docsNotRequired */ url, urlAfterRedirects, state) { super(id, url); this.urlAfterRedirects = urlAfterRedirects; this.state = state; } /** * \@docsNotRequired * @return {?} */ toString() { return `RoutesRecognized(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`; } } if (false) { /** * \@docsNotRequired * @type {?} */ RoutesRecognized.prototype.urlAfterRedirects; /** * \@docsNotRequired * @type {?} */ RoutesRecognized.prototype.state; } /** * An event triggered at the start of the Guard phase of routing. * * \@publicApi */ class GuardsCheckStart extends RouterEvent { /** * @param {?} id * @param {?} url * @param {?} urlAfterRedirects * @param {?} state */ constructor( /** @docsNotRequired */ id, /** @docsNotRequired */ url, urlAfterRedirects, state) { super(id, url); this.urlAfterRedirects = urlAfterRedirects; this.state = state; } /** * @return {?} */ toString() { return `GuardsCheckStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`; } } if (false) { /** * \@docsNotRequired * @type {?} */ GuardsCheckStart.prototype.urlAfterRedirects; /** * \@docsNotRequired * @type {?} */ GuardsCheckStart.prototype.state; } /** * An event triggered at the end of the Guard phase of routing. * * \@publicApi */ class GuardsCheckEnd extends RouterEvent { /** * @param {?} id * @param {?} url * @param {?} urlAfterRedirects * @param {?} state * @param {?} shouldActivate */ constructor( /** @docsNotRequired */ id, /** @docsNotRequired */ url, urlAfterRedirects, state, shouldActivate) { super(id, url); this.urlAfterRedirects = urlAfterRedirects; this.state = state; this.shouldActivate = shouldActivate; } /** * @return {?} */ toString() { return `GuardsCheckEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state}, shouldActivate: ${this.shouldActivate})`; } } if (false) { /** * \@docsNotRequired * @type {?} */ GuardsCheckEnd.prototype.urlAfterRedirects; /** * \@docsNotRequired * @type {?} */ GuardsCheckEnd.prototype.state; /** * \@docsNotRequired * @type {?} */ GuardsCheckEnd.prototype.shouldActivate; } /** * An event triggered at the the start of the Resolve phase of routing. * * Runs in the "resolve" phase whether or not there is anything to resolve. * In future, may change to only run when there are things to be resolved. * * \@publicApi */ class ResolveStart extends RouterEvent { /** * @param {?} id * @param {?} url * @param {?} urlAfterRedirects * @param {?} state */ constructor( /** @docsNotRequired */ id, /** @docsNotRequired */ url, urlAfterRedirects, state) { super(id, url); this.urlAfterRedirects = urlAfterRedirects; this.state = state; } /** * @return {?} */ toString() { return `ResolveStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`; } } if (false) { /** * \@docsNotRequired * @type {?} */ ResolveStart.prototype.urlAfterRedirects; /** * \@docsNotRequired * @type {?} */ ResolveStart.prototype.state; } /** * An event triggered at the end of the Resolve phase of routing. * @see `ResolveStart`. * * \@publicApi */ class ResolveEnd extends RouterEvent { /** * @param {?} id * @param {?} url * @param {?} urlAfterRedirects * @param {?} state */ constructor( /** @docsNotRequired */ id, /** @docsNotRequired */ url, urlAfterRedirects, state) { super(id, url); this.urlAfterRedirects = urlAfterRedirects; this.state = state; } /** * @return {?} */ toString() { return `ResolveEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`; } } if (false) { /** * \@docsNotRequired * @type {?} */ ResolveEnd.prototype.urlAfterRedirects; /** * \@docsNotRequired * @type {?} */ ResolveEnd.prototype.state; } /** * An event triggered before lazy loading a route configuration. * * \@publicApi */ class RouteConfigLoadStart { /** * @param {?} route */ constructor(route) { this.route = route; } /** * @return {?} */ toString() { return `RouteConfigLoadStart(path: ${this.route.path})`; } } if (false) { /** * \@docsNotRequired * @type {?} */ RouteConfigLoadStart.prototype.route; } /** * An event triggered when a route has been lazy loaded. * * \@publicApi */ class RouteConfigLoadEnd { /** * @param {?} route */ constructor(route) { this.route = route; } /** * @return {?} */ toString() { return `RouteConfigLoadEnd(path: ${this.route.path})`; } } if (false) { /** * \@docsNotRequired * @type {?} */ RouteConfigLoadEnd.prototype.route; } /** * An event triggered at the start of the child-activation * part of the Resolve phase of routing. * @see `ChildActivationEnd` * @see `ResolveStart` * * \@publicApi */ class ChildActivationStart { /** * @param {?} snapshot */ constructor(snapshot) { this.snapshot = snapshot; } /** * @return {?} */ toString() { /** @type {?} */ const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || ''; return `ChildActivationStart(path: '${path}')`; } } if (false) { /** * \@docsNotRequired * @type {?} */ ChildActivationStart.prototype.snapshot; } /** * An event triggered at the end of the child-activation part * of the Resolve phase of routing. * @see `ChildActivationStart` * @see `ResolveStart` * * \@publicApi */ class ChildActivationEnd { /** * @param {?} snapshot */ constructor(snapshot) { this.snapshot = snapshot; } /** * @return {?} */ toString() { /** @type {?} */ const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || ''; return `ChildActivationEnd(path: '${path}')`; } } if (false) { /** * \@docsNotRequired * @type {?} */ ChildActivationEnd.prototype.snapshot; } /** * An event triggered at the start of the activation part * of the Resolve phase of routing. * @see ActivationEnd` * @see `ResolveStart` * * \@publicApi */ class ActivationStart { /** * @param {?} snapshot */ constructor(snapshot) { this.snapshot = snapshot; } /** * @return {?} */ toString() { /** @type {?} */ const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || ''; return `ActivationStart(path: '${path}')`; } } if (false) { /** * \@docsNotRequired * @type {?} */ ActivationStart.prototype.snapshot; } /** * An event triggered at the end of the activation part * of the Resolve phase of routing. * @see `ActivationStart` * @see `ResolveStart` * * \@publicApi */ class ActivationEnd { /** * @param {?} snapshot */ constructor(snapshot) { this.snapshot = snapshot; } /** * @return {?} */ toString() { /** @type {?} */ const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || ''; return `ActivationEnd(path: '${path}')`; } } if (false) { /** * \@docsNotRequired * @type {?} */ ActivationEnd.prototype.snapshot; } /** * An event triggered by scrolling. * * \@publicApi */ class Scroll { /** * @param {?} routerEvent * @param {?} position * @param {?} anchor */ constructor(routerEvent, position, anchor) { this.routerEvent = routerEvent; this.position = position; this.anchor = anchor; } /** * @return {?} */ toString() { /** @type {?} */ const pos = this.position ? `${this.position[0]}, ${this.position[1]}` : null; return `Scroll(anchor: '${this.anchor}', position: '${pos}')`; } } if (false) { /** * \@docsNotRequired * @type {?} */ Scroll.prototype.routerEvent; /** * \@docsNotRequired * @type {?} */ Scroll.prototype.position; /** * \@docsNotRequired * @type {?} */ Scroll.prototype.anchor; } /** * @fileoverview added by tsickle * Generated from: packages/router/src/components/empty_outlet.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * This component is used internally within the router to be a placeholder when an empty * router-outlet is needed. For example, with a config such as: * * `{path: 'parent', outlet: 'nav', children: [...]}` * * In order to render, there needs to be a component on this config, which will default * to this `EmptyOutletComponent`. */ class ɵEmptyOutletComponent { } ɵEmptyOutletComponent.ɵfac = function ɵEmptyOutletComponent_Factory(t) { return new (t || ɵEmptyOutletComponent)(); }; ɵEmptyOutletComponent.ɵcmp = ɵngcc0.ɵɵdefineComponent({ type: ɵEmptyOutletComponent, selectors: [["ng-component"]], decls: 1, vars: 0, template: function ɵEmptyOutletComponent_Template(rf, ctx) { if (rf & 1) { ɵngcc0.ɵɵelement(0, "router-outlet"); } }, directives: function () { return [RouterOutlet]; }, encapsulation: 2 }); /*@__PURE__*/ (function () { ɵngcc0.ɵsetClassMetadata(ɵEmptyOutletComponent, [{ type: Component, args: [{ template: `<router-outlet></router-outlet>` }] }], null, null); })(); /** * @fileoverview added by tsickle * Generated from: packages/router/src/shared.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * The primary routing outlet. * * \@publicApi * @type {?} */ const PRIMARY_OUTLET = 'primary'; /** * A map that provides access to the required and optional parameters * specific to a route. * The map supports retrieving a single value with `get()` * or multiple values with `getAll()`. * * @see [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) * * \@publicApi * @record */ function ParamMap() { } if (false) { /** * Names of the parameters in the map. * @type {?} */ ParamMap.prototype.keys; /** * Reports whether the map contains a given parameter. * @param {?} name The parameter name. * @return {?} True if the map contains the given parameter, false otherwise. */ ParamMap.prototype.has = function (name) { }; /** * Retrieves a single value for a parameter. * @param {?} name The parameter name. * @return {?} The parameter's single value, * or the first value if the parameter has multiple values, * or `null` when there is no such parameter. */ ParamMap.prototype.get = function (name) { }; /** * Retrieves multiple values for a parameter. * @param {?} name The parameter name. * @return {?} An array containing one or more values, * or an empty array if there is no such parameter. * */ ParamMap.prototype.getAll = function (name) { }; } class ParamsAsMap { /** * @param {?} params */ constructor(params) { this.params = params || {}; } /** * @param {?} name * @return {?} */ has(name) { return this.params.hasOwnProperty(name); } /** * @param {?} name * @return {?} */ get(name) { if (this.has(name)) { /** @type {?} */ const v = this.params[name]; return Array.isArray(v) ? v[0] : v; } return null; } /** * @param {?} name * @return {?} */ getAll(name) { if (this.has(name)) { /** @type {?} */ const v = this.params[name]; return Array.isArray(v) ? v : [v]; } return []; } /** * @return {?} */ get keys() { return Object.keys(this.params); } } if (false) { /** * @type {?} * @private */ ParamsAsMap.prototype.params; } /** * Converts a `Params` instance to a `ParamMap`. * \@publicApi * @param {?} params The instance to convert. * @return {?} The new map instance. * */ function convertToParamMap(params) { return new ParamsAsMap(params); } /** @type {?} */ const NAVIGATION_CANCELING_ERROR = 'ngNavigationCancelingError'; /** * @param {?} message * @return {?} */ function navigationCancelingError(message) { /** @type {?} */ const error = Error('NavigationCancelingError: ' + message); ((/** @type {?} */ (error)))[NAVIGATION_CANCELING_ERROR] = true; return error; } /** * @param {?} error * @return {?} */ function isNavigationCancelingError(error) { return error && ((/** @type {?} */ (error)))[NAVIGATION_CANCELING_ERROR]; } // Matches the route configuration (`route`) against the actual URL (`segments`). /** * @param {?} segments * @param {?} segmentGroup * @param {?} route * @return {?} */ function defaultUrlMatcher(segments, segmentGroup, route) { /** @type {?} */ const parts = (/** @type {?} */ (route.path)).split('/'); if (parts.length > segments.length) { // The actual URL is shorter than the config, no match return null; } if (route.pathMatch === 'full' && (segmentGroup.hasChildren() || parts.length < segments.length)) { // The config is longer than the actual URL but we are looking for a full match, return null return null; } /** @type {?} */ const posParams = {}; // Check each config part against the actual URL for (let index = 0; index < parts.length; index++) { /** @type {?} */ const part = parts[index]; /** @type {?} */ const segment = segments[index]; /** @type {?} */ const isParameter = part.startsWith(':'); if (isParameter) { posParams[part.substring(1)] = segment; } else if (part !== segment.path) { // The actual URL part does not match the config, no match return null; } } return { consumed: segments.slice(0, parts.length), posParams }; } /** * @fileoverview added by tsickle * Generated from: packages/router/src/config.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * A configuration object that defines a single route. * A set of routes are collected in a `Routes` array to define a `Router` configuration. * The router attempts to match segments of a given URL against each route, * using the configuration options defined in this object. * * Supports static, parameterized, redirect, and wildcard routes, as well as * custom route data and resolve methods. * * For detailed usage information, see the [Routing Guide](guide/router). * * \@usageNotes * * ### Simple Configuration * * The following route specifies that when navigating to, for example, * `/team/11/user/bob`, the router creates the 'Team' component * with the 'User' child component in it. * * ``` * [{ * path: 'team/:id', * component: Team, * children: [{ * path: 'user/:name', * component: User * }] * }] * ``` * * ### Multiple Outlets * * The following route creates sibling components with multiple outlets. * When navigating to `/team/11(aux:chat/jim)`, the router creates the 'Team' component next to * the 'Chat' component. The 'Chat' component is placed into the 'aux' outlet. * * ``` * [{ * path: 'team/:id', * component: Team * }, { * path: 'chat/:user', * component: Chat * outlet: 'aux' * }] * ``` * * ### Wild Cards * * The following route uses wild-card notation to specify a component * that is always instantiated regardless of where you navigate to. * * ``` * [{ * path: '**', * component: WildcardComponent * }] * ``` * * ### Redirects * * The following route uses the `redirectTo` property to ignore a segment of * a given URL when looking for a child path. * * When navigating to '/team/11/legacy/user/jim', the router changes the URL segment * '/team/11/legacy/user/jim' to '/team/11/user/jim', and then instantiates * the Team component with the User child component in it. * * ``` * [{ * path: 'team/:id', * component: Team, * children: [{ * path: 'legacy/user/:name', * redirectTo: 'user/:name' * }, { * path: 'user/:name', * component: User * }] * }] * ``` * * The redirect path can be relative, as shown in this example, or absolute. * If we change the `redirectTo` value in the example to the absolute URL segment '/user/:name', * the result URL is also absolute, '/user/jim'. * ### Empty Path * * Empty-path route configurations can be used to instantiate components that do not 'consume' * any URL segments. * * In the following configuration, when navigating to * `/team/11`, the router instantiates the 'AllUsers' component. * * ``` * [{ * path: 'team/:id', * component: Team, * children: [{ * path: '', * component: AllUsers * }, { * path: 'user/:name', * component: User * }] * }] * ``` * * Empty-path routes can have children. In the following example, when navigating * to `/team/11/user/jim`, the router instantiates the wrapper component with * the user component in it. * * Note that an empty path route inherits its parent's parameters and data. * * ``` * [{ * path: 'team/:id', * component: Team, * children: [{ * path: '', * component: WrapperCmp, * children: [{ * path: 'user/:name', * component: User * }] * }] * }] * ``` * * ### Matching Strategy * * The default path-match strategy is 'prefix', which means that the router * checks URL elements from the left to see if the URL matches a specified path. * For example, '/team/11/user' matches 'team/:id'. * * ``` * [{ * path: '', * pathMatch: 'prefix', //default * redirectTo: 'main' * }, { * path: 'main', * component: Main * }] * ``` * * You can specify the path-match strategy 'full' to make sure that the path * covers the whole unconsumed URL. It is important to do this when redirecting * empty-path routes. Otherwise, because an empty path is a prefix of any URL, * the router would apply the redirect even when navigating to the redirect destination, * creating an endless loop. * * In the following example, supplying the 'full' `pathMatch` strategy ensures * that the router applies the redirect if and only if navigating to '/'. * * ``` * [{ * path: '', * pathMatch: 'full', * redirectTo: 'main' * }, { * path: 'main', * component: Main * }] * ``` * * ### Componentless Routes * * You can share parameters between sibling components. * For example, suppose that two sibling components should go next to each other, * and both of them require an ID parameter. You can accomplish this using a route * that does not specify a component at the top level. * * In the following example, 'MainChild' and 'AuxChild' are siblings. * When navigating to 'parent/10/(a//aux:b)', the route instantiates * the main child and aux child components next to each other. * For this to work, the application component must have the primary and aux outlets defined. * * ``` * [{ * path: 'parent/:id', * children: [ * { path: 'a', component: MainChild }, * { path: 'b', component: AuxChild, outlet: 'aux' } * ] * }] * ``` * * The router merges the parameters, data, and resolve of the componentless * parent into the parameters, data, and resolve of the children. * * This is especially useful when child components are defined * with an empty path string, as in the following example. * With this configuration, navigating to '/parent/10' creates * the main child and aux components. * * ``` * [{ * path: 'parent/:id', * children: [ * { path: '', component: MainChild }, * { path: '', component: AuxChild, outlet: 'aux' } * ] * }] * ``` * * ### Lazy Loading * * Lazy loading speeds up application load time by splitting the application * into multiple bundles and loading them on demand. * To use lazy loading, provide the `loadChildren` property instead of the `children` property. * * Given the following example route, the router will lazy load * the associated module on demand using the browser native import system. * * ``` * [{ * path: 'lazy', * loadChildren: () => import('./lazy-route/lazy.module').then(mod => mod.LazyModule), * }]; * ``` * * \@publicApi * @record */ function Route() { } if (false) { /** * The path to match against. Cannot be used together with a custom `matcher` function. * A URL string that uses router matching notation. * Can be a wild card (`**`) that matches any URL (see Usage Notes below). * Default is "/" (the root path). * * @type {?|undefined} */ Route.prototype.path; /** * The path-matching strategy, one of 'prefix' or 'full'. * Default is 'prefix'. * * By default, the router checks URL elements from the left to see if the URL * matches a given path, and stops when there is a match. For example, * '/team/11/user' matches 'team/:id'. * * The path-match strategy 'full' matches against the entire URL. * It is important to do this when redirecting empty-path routes. * Otherwise, because an empty path is a prefix of any URL, * the router would apply the redirect even when navigating * to the redirect destination, creating an endless loop. * * @type {?|undefined} */ Route.prototype.pathMatch; /** * A custom URL-matching function. Cannot be used together with `path`. * @type {?|undefined} */ Route.prototype.matcher; /** * The component to instantiate when the path matches. * Can be empty if child routes specify components. * @type {?|undefined} */ Route.prototype.component; /** * A URL to which to redirect when a the path matches. * Absolute if the URL begins with a slash (/), otherwise relative to the path URL. * When not present, router does not redirect. * @type {?|undefined} */ Route.prototype.redirectTo; /** * Name of a `RouterOutlet` object where the component can be placed * when the path matches. * @type {?|undefined} */ Route.prototype.outlet; /** * An array of dependency-injection tokens used to look up `CanActivate()` * handlers, in order to determine if the current user is allowed to * activate the component. By default, any user can activate. * @type {?|undefined} */ Route.prototype.canActivate; /** * An array of DI tokens used to look up `CanActivateChild()` handlers, * in order to determine if the current user is allowed to activate * a child of the component. By default, any user can activate a child. * @type {?|undefined} */ Route.prototype.canActivateChild; /** * An array of DI tokens used to look up `CanDeactivate()` * handlers, in order to determine if the current user is allowed to * deactivate the component. By default, any user can deactivate. * * @type {?|undefined} */ Route.prototype.canDeactivate; /** * An array of DI tokens used to look up `CanLoad()` * handlers, in order to determine if the current user is allowed to * load the component. By default, any user can load. * @type {?|undefined} */ Route.prototype.canLoad; /** * Additional developer-defined data provided to the component via * `ActivatedRoute`. By default, no additional data is passed. * @type {?|undefined} */ Route.prototype.data; /** * A map of DI tokens used to look up data resolvers. See `Resolve`. * @type {?|undefined} */ Route.prototype.resolve; /** * An array of child `Route` objects that specifies a nested route * configuration. * @type {?|undefined} */ Route.prototype.children; /** * A `LoadChildren` object specifying lazy-loaded child routes. * @type {?|undefined} */ Route.prototype.loadChildren; /** * Defines when guards and resolvers will be run. One of * - `paramsOrQueryParamsChange` : Run when query parameters change. * - `always` : Run on every execution. * By default, guards and resolvers run only when the matrix * parameters of the route change. * @type {?|undefined} */ Route.prototype.runGuardsAndResolvers; /** * Filled for routes with `loadChildren` once the module has been loaded * \@internal * @type {?|undefined} */ Route.prototype._loadedConfig; } class LoadedRouterConfig { /** * @param {?} routes * @param {?} module */ constructor(routes, module) { this.routes = routes; this.module = module; } } if (false) { /** @type {?} */ LoadedRouterConfig.prototype.routes; /** @type {?} */ LoadedRouterConfig.prototype.module; } /** * @param {?} config * @param {?=} parentPath * @return {?} */ function validateConfig(config, parentPath = '') { // forEach doesn't iterate undefined values for (let i = 0; i < config.length; i++) { /** @type {?} */ const route = config[i]; /** @type {?} */ const fullPath = getFullPath(parentPath, route); validateNode(route, fullPath); } } /** * @param {?} route * @param {?} fullPath * @return {?} */ function validateNode(route, fullPath) { if (!route) { throw new Error(` Invalid configuration of route '${fullPath}': Encountered undefined route. The reason might be an extra comma. Example: const routes: Routes = [ { path: '', redirectTo: '/dashboard', pathMatch: 'full' }, { path: 'dashboard', component: DashboardComponent },, << two commas { path: 'detail/:id', component: HeroDetailComponent } ]; `); } if (Array.isArray(route)) { throw new Error(`Invalid configuration of route '${fullPath}': Array cannot be specified`); } if (!route.component && !route.children && !route.loadChildren && (route.outlet && route.outlet !== PRIMARY_OUTLET)) { throw new Error(`Invalid configuration of route '${fullPath}': a componentless route without children or loadChildren cannot have a named outlet set`); } if (route.redirectTo && route.children) { throw new Error(`Invalid configuration of route '${fullPath}': redirectTo and children cannot be used together`); } if (route.redirectTo && route.loadChildren) { throw new Error(`Invalid configuration of route '${fullPath}': redirectTo and loadChildren cannot be used together`); } if (route.children && route.loadChildren) { throw new Error(`Invalid configuration of route '${fullPath}': children and loadChildren cannot be used together`); } if (route.redirectTo && route.component) { throw new Error(`Invalid configuration of route '${fullPath}': redirectTo and component cannot be used together`); } if (route.path && route.matcher) { throw new Error(`Invalid configuration of route '${fullPath}': path and matcher cannot be used together`); } if (route.redirectTo === void 0 && !route.component && !route.children && !route.loadChildren) { throw new Error(`Invalid configuration of route '${fullPath}'. One of the following must be provided: component, redirectTo, children or loadChildren`); } if (route.path === void 0 && route.matcher === void 0) { throw new Error(`Invalid configuration of route '${fullPath}': routes must have either a path or a matcher specified`); } if (typeof route.path === 'string' && route.path.charAt(0) === '/') { throw new Error(`Invalid configuration of route '${fullPath}': path cannot start with a slash`); } if (route.path === '' && route.redirectTo !== void 0 && route.pathMatch === void 0) { /** @type {?} */ const exp = `The default value of 'pathMatch' is 'prefix', but often the intent is to use 'full'.`; throw new Error(`Invalid configuration of route '{path: "${fullPath}", redirectTo: "${route.redirectTo}"}': please provide 'pathMatch'. ${exp}`); } if (route.pathMatch !== void 0 && route.pathMatch !== 'full' && route.pathMatch !== 'prefix') { throw new Error(`Invalid configuration of route '${fullPath}': pathMatch can only be set to 'prefix' or 'full'`); } if (route.children) { validateConfig(route.children, fullPath); } } /** * @param {?} parentPath * @param {?} currentRoute * @return {?} */ function getFullPath(parentPath, currentRoute) { if (!currentRoute) { return parentPath; } if (!parentPath && !currentRoute.path) { return ''; } else if (parentPath && !currentRoute.path) { return `${parentPath}/`; } else if (!parentPath && currentRoute.path) { return currentRoute.path; } else { return `${parentPath}/${currentRoute.path}`; } } /** * Makes a copy of the config and adds any default required properties. * @param {?} r * @return {?} */ function standardizeConfig(r) { /** @type {?} */ const children = r.children && r.children.map(standardizeConfig); /** @type {?} */ const c = children ? Object.assign(Object.assign({}, r), { children }) : Object.assign({}, r); if (!c.component && (children || c.loadChildren) && (c.outlet && c.outlet !== PRIMARY_OUTLET)) { c.component = ɵEmptyOutletComponent; } return c; } /** * @fileoverview added by tsickle * Generated from: packages/router/src/utils/collection.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @param {?} a * @param {?} b * @return {?} */ function shallowEqualArrays(a, b) { if (a.length !== b.length) return false; for (let i = 0; i < a.length; ++i) { if (!shallowEqual(a[i], b[i])) return false; } return true; } /** * @param {?} a * @param {?} b * @return {?} */ function shallowEqual(a, b) { // Casting Object.keys return values to include `undefined` as there are some cases // in IE 11 where this can happen. Cannot provide a test because the behavior only // exists in certain circumstances in IE 11, therefore doing this cast ensures the // logic is correct for when this edge case is hit. /** @type {?} */ const k1 = (/** @type {?} */ (Object.keys(a))); /** @type {?} */ const k2 = (/** @type {?} */ (Object.keys(b))); if (!k1 || !k2 || k1.length != k2.length) { return false; } /** @type {?} */ let key; for (let i = 0; i < k1.length; i++) { key = k1[i]; if (!equalArraysOrString(a[key], b[key])) { return false; } } return true; } /** * Test equality for arrays of strings or a string. * @param {?} a * @param {?} b * @return {?} */ function equalArraysOrString(a, b) { if (Array.isArray(a) && Array.isArray(b)) { if (a.length != b.length) return false; return a.every((/** * @param {?} aItem * @return {?} */ aItem => b.indexOf(aItem) > -1)); } else { return a === b; } } /** * Flattens single-level nested arrays. * @template T * @param {?} arr * @return {?} */ function flatten(arr) { return Array.prototype.concat.apply([], arr); } /** * Return the last element of an array. * @template T * @param {?} a * @return {?} */ function last(a) { return a.length > 0 ? a[a.length - 1] : null; } /** * Verifys all booleans in an array are `true`. * @param {?} bools * @return {?} */ function and(bools) { return !bools.some((/** * @param {?} v * @return {?} */ v => !v)); } /** * @template K, V * @param {?} map * @param {?} callback * @return {?} */ function forEach(map, callback) { for (const prop in map) { if (map.hasOwnProperty(prop)) { callback(map[prop], prop); } } } /** * @template A, B * @param {?} obj * @param {?} fn * @return {?} */ function waitForMap(obj, fn) { if (Object.keys(obj).length === 0) { return of({}); } /** @type {?} */ const waitHead = []; /** @type {?} */ const waitTail = []; /** @type {?} */ const res = {}; forEach(obj, (/** * @param {?} a * @param {?} k * @return {?} */ (a, k) => { /** @type {?} */ const mapped = fn(k, a).pipe(map((/** * @param {?} r * @return {?} */ (r) => res[k] = r))); if (k === PRIMARY_OUTLET) { waitHead.push(mapped); } else { waitTail.push(mapped); } })); // Closure compiler has problem with using spread operator here. So we use "Array.concat". // Note that we also need to cast the new promise because TypeScript cannot infer the type // when calling the "of" function through "Function.apply" return ((/** @type {?} */ (of.apply(null, waitHead.concat(waitTail))))) .pipe(concatAll(), last$1(), map((/** * @return {?} */ () => res))); } /** * @template T * @param {?} value * @return {?} */ function wrapIntoObservable(value) { if (ɵisObservable(value)) { return value; } if (ɵisPromise(value)) { // Use `Promise.resolve()` to wrap promise-like instances. // Required ie when a Resolver returns a AngularJS `$q` promise to correctly trigger the // change detection. return from(Promise.resolve(value)); } return of(value); } /** * @fileoverview added by tsickle * Generated from: packages/router/src/url_tree.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @return {?} */ function createEmptyUrlTree() { return new UrlTree(new UrlSegmentGroup([], {}), {}, null); } /** * @param {?} container * @param {?} containee * @param {?} exact * @return {?} */ function containsTree(container, containee, exact) { if (exact) { return equalQueryParams(container.queryParams, containee.queryParams) && equalSegmentGroups(container.root, containee.root); } return containsQueryParams(container.queryParams, containee.queryParams) && containsSegmentGroup(container.root, containee.root); } /** * @param {?} container * @param {?} containee * @return {?} */ function equalQueryParams(container, containee) { // TODO: This does not handle array params correctly. return shallowEqual(container, containee); } /** * @param {?} container * @param {?} containee * @return {?} */ function equalSegmentGroups(container, containee) { if (!equalPath(container.segments, containee.segments)) return false; if (container.numberOfChildren !== containee.numberOfChildren) return false; for (const c in containee.children) { if (!container.children[c]) return false; if (!equalSegmentGroups(container.children[c], containee.children[c])) return false; } return true; } /** * @param {?} container * @param {?} containee * @return {?} */ function containsQueryParams(container, containee) { // TODO: This does not handle array params correctly. return Object.keys(containee).length <= Object.keys(container).length && Object.keys(containee).every((/** * @param {?} key * @return {?} */ key => equalArraysOrString(container[key], containee[key]))); } /** * @param {?} container * @param {?} containee * @return {?} */ function containsSegmentGroup(container, containee) { return containsSegmentGroupHelper(container, containee, containee.segments); } /** * @param {?} container * @param {?} containee * @param {?} containeePaths * @return {?} */ function containsSegmentGroupHelper(container, containee, containeePaths) { if (container.segments.length > containeePaths.length) { /** @type {?} */ const current = container.segments.slice(0, containeePaths.length); if (!equalPath(current, containeePaths)) return false; if (containee.hasChildren()) return false; return true; } else if (container.segments.length === containeePaths.length) { if (!equalPath(container.segments, containeePaths)) return false; for (const c in containee.children) { if (!container.children[c]) return false; if (!containsSegmentGroup(container.children[c], containee.children[c])) return false; } return true; } else { /** @type {?} */ const current = containeePaths.slice(0, container.segments.length); /** @type {?} */ const next = containeePaths.slice(container.segments.length); if (!equalPath(container.segments, current)) return false; if (!container.children[PRIMARY_OUTLET]) return false; return containsSegmentGroupHelper(container.children[PRIMARY_OUTLET], containee, next); } } /** * \@description * * Represents the parsed URL. * * Since a router state is a tree, and the URL is nothing but a serialized state, the URL is a * serialized tree. * UrlTree is a data structure that provides a lot of affordances in dealing with URLs * * \@usageNotes * ### Example * * ``` * \@Component({templateUrl:'template.html'}) * class MyComponent { * constructor(router: Router) { * const tree: UrlTree = * router.parseUrl('/team/33/(user/victor//support:help)?debug=true#fragment'); * const f = tree.fragment; // return 'fragment' * const q = tree.queryParams; // returns {debug: 'true'} * const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET]; * const s: UrlSegment[] = g.segments; // returns 2 segments 'team' and '33' * g.children[PRIMARY_OUTLET].segments; // returns 2 segments 'user' and 'victor' * g.children['support'].segments; // return 1 segment 'help' * } * } * ``` * * \@publicApi */ class UrlTree { /** * \@internal * @param {?} root * @param {?} queryParams * @param {?} fragment */ constructor(root, queryParams, fragment) { this.root = root; this.queryParams = queryParams; this.fragment = fragment; } /** * @return {?} */ get queryParamMap() { if (!this._queryParamMap) { this._queryParamMap = convertToParamMap(this.queryParams); } return this._queryParamMap; } /** * \@docsNotRequired * @return {?} */ toString() { return DEFAULT_SERIALIZER.serialize(this); } } if (false) { /** * \@internal * @type {?} */ UrlTree.prototype._queryParamMap; /** * The root segment group of the URL tree * @type {?} */ UrlTree.prototype.root; /** * The query params of the URL * @type {?} */ UrlTree.prototype.queryParams; /** * The fragment of the URL * @type {?} */ UrlTree.prototype.fragment; } /** * \@description * * Represents the parsed URL segment group. * * See `UrlTree` for more information. * * \@publicApi */ class UrlSegmentGroup { /** * @param {?} segments * @param {?} children */ constructor(segments, children) { this.segments = segments; this.children = children; /** * The parent node in the url tree */ this.parent = null; forEach(children, (/** * @template THIS * @this {THIS} * @param {?} v * @param {?} k * @return {THIS} */ (v, k) => v.parent = this)); } /** * Whether the segment has child segments * @return {?} */ hasChildren() { return this.numberOfChildren > 0; } /** * Number of child segments * @return {?} */ get numberOfChildren() { return Object.keys(this.children).length; } /** * \@docsNotRequired * @return {?} */ toString() { return serializePaths(this); } } if (false) { /** * \@internal * @type {?} */ UrlSegmentGroup.prototype._sourceSegment; /** * \@internal * @type {?} */ UrlSegmentGroup.prototype._segmentIndexShift; /** * The parent node in the url tree * @type {?} */ UrlSegmentGroup.prototype.parent; /** * The URL segments of this group. See `UrlSegment` for more information * @type {?} */ UrlSegmentGroup.prototype.segments; /** * The list of children of this group * @type {?} */ UrlSegmentGroup.prototype.children; } /** * \@description * * Represents a single URL segment. * * A UrlSegment is a part of a URL between the two slashes. It contains a path and the matrix * parameters associated with the segment. * * \@usageNotes *  ### Example * * ``` * \@Component({templateUrl:'template.html'}) * class MyComponent { * constructor(router: Router) { * const tree: UrlTree = router.parseUrl('/team;id=33'); * const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET]; * const s: UrlSegment[] = g.segments; * s[0].path; // returns 'team' * s[0].parameters; // returns {id: 33} * } * } * ``` * * \@publicApi */ class UrlSegment { /** * @param {?} path * @param {?} parameters */ constructor(path, parameters) { this.path = path; this.parameters = parameters; } /** * @return {?} */ get parameterMap() { if (!this._parameterMap) { this._parameterMap = convertToParamMap(this.parameters); } return this._parameterMap; } /** * \@docsNotRequired * @return {?} */ toString() { return serializePath(this); } } if (false) { /** * \@internal * @type {?} */ UrlSegment.prototype._parameterMap; /** * The path part of a URL segment * @type {?} */ UrlSegment.prototype.path; /** * The matrix parameters associated with a segment * @type {?} */ UrlSegment.prototype.parameters; } /** * @param {?} as * @param {?} bs * @return {?} */ function equalSegments(as, bs) { return equalPath(as, bs) && as.every((/** * @param {?} a * @param {?} i * @return {?} */ (a, i) => shallowEqual(a.parameters, bs[i].parameters))); } /** * @param {?} as * @param {?} bs * @return {?} */ function equalPath(as, bs) { if (as.length !== bs.length) return false; return as.every((/** * @param {?} a * @param {?} i * @return {?} */ (a, i) => a.path === bs[i].path)); } /** * @template T * @param {?} segment * @param {?} fn * @return {?} */ function mapChildrenIntoArray(segment, fn) { /** @type {?} */ let res = []; forEach(segment.children, (/** * @param {?} child * @param {?} childOutlet * @return {?} */ (child, childOutlet) => { if (childOutlet === PRIMARY_OUTLET) { res = res.concat(fn(child, childOutlet)); } })); forEach(segment.children, (/** * @param {?} child * @param {?} childOutlet * @return {?} */ (child, childOutlet) => { if (childOutlet !== PRIMARY_OUTLET) { res = res.concat(fn(child, childOutlet)); } })); return res; } /** * \@description * * Serializes and deserializes a URL string into a URL tree. * * The url serialization strategy is customizable. You can * make all URLs case insensitive by providing a custom UrlSerializer. * * See `DefaultUrlSerializer` for an example of a URL serializer. * * \@publicApi * @abstract */ class UrlSerializer { } if (false) { /** * Parse a url into a `UrlTree` * @abstract * @param {?} url * @return {?} */ UrlSerializer.prototype.parse = function (url) { }; /** * Converts a `UrlTree` into a url * @abstract * @param {?} tree * @return {?} */ UrlSerializer.prototype.serialize = function (tree) { }; } /** * \@description * * A default implementation of the `UrlSerializer`. * * Example URLs: * * ``` * /inbox/33(popup:compose) * /inbox/33;open=true/messages/44 * ``` * * DefaultUrlSerializer uses parentheses to serialize secondary segments (e.g., popup:compose), the * colon syntax to specify the outlet, and the ';parameter=value' syntax (e.g., open=true) to * specify route specific parameters. * * \@publicApi */ class DefaultUrlSerializer { /** * Parses a url into a `UrlTree` * @param {?} url * @return {?} */ parse(url) { /** @type {?} */ const p = new UrlParser(url); return new UrlTree(p.parseRootSegment(), p.parseQueryParams(), p.parseFragment()); } /** * Converts a `UrlTree` into a url * @param {?} tree * @return {?} */ serialize(tree) { /** @type {?} */ const segment = `/${serializeSegment(tree.root, true)}`; /** @type {?} */ const query = serializeQueryParams(tree.queryParams); /** @type {?} */ const fragment = typeof tree.fragment === `string` ? `#${encodeUriFragment((/** @type {?} */ (tree.fragment)))}` : ''; return `${segment}${query}${fragment}`; } } /** @type {?} */ const DEFAULT_SERIALIZER = new DefaultUrlSerializer(); /** * @param {?} segment * @return {?} */ function serializePaths(segment) { return segment.segments.map((/** * @param {?} p * @return {?} */ p => serializePath(p))).join('/'); } /** * @param {?} segment * @param {?} root * @return {?} */ function serializeSegment(segment, root) { if (!segment.hasChildren()) { return serializePaths(segment); } if (root) { /** @type {?} */ const primary = segment.children[PRIMARY_OUTLET] ? serializeSegment(segment.children[PRIMARY_OUTLET], false) : ''; /** @type {?} */ const children = []; forEach(segment.children, (/** * @param {?} v * @param {?} k * @return {?} */ (v, k) => { if (k !== PRIMARY_OUTLET) { children.push(`${k}:${serializeSegment(v, false)}`); } })); return children.length > 0 ? `${primary}(${children.join('//')})` : primary; } else { /** @type {?} */ const children = mapChildrenIntoArray(segment, (/** * @param {?} v * @param {?} k * @return {?} */ (v, k) => { if (k === PRIMARY_OUTLET) { return [serializeSegment(segment.children[PRIMARY_OUTLET], false)]; } return [`${k}:${serializeSegment(v, false)}`]; })); return `${serializePaths(segment)}/(${children.join('//')})`; } } /** * Encodes a URI string with the default encoding. This function will only ever be called from * `encodeUriQuery` or `encodeUriSegment` as it's the base set of encodings to be used. We need * a custom encoding because encodeURIComponent is too aggressive and encodes stuff that doesn't * have to be encoded per https://url.spec.whatwg.org. * @param {?} s * @return {?} */ function encodeUriString(s) { return encodeURIComponent(s) .replace(/%40/g, '@') .replace(/%3A/gi, ':') .replace(/%24/g, '$') .replace(/%2C/gi, ','); } /** * This function should be used to encode both keys and values in a query string key/value. In * the following URL, you need to call encodeUriQuery on "k" and "v": * * http://www.site.org/html;mk=mv?k=v#f * @param {?} s * @return {?} */ function encodeUriQuery(s) { return encodeUriString(s).replace(/%3B/gi, ';'); } /** * This function should be used to encode a URL fragment. In the following URL, you need to call * encodeUriFragment on "f": * * http://www.site.org/html;mk=mv?k=v#f * @param {?} s * @return {?} */ function encodeUriFragment(s) { return encodeURI(s); } /** * This function should be run on any URI segment as well as the key and value in a key/value * pair for matrix params. In the following URL, you need to call encodeUriSegment on "html", * "mk", and "mv": * * http://www.site.org/html;mk=mv?k=v#f * @param {?} s * @return {?} */ function encodeUriSegment(s) { return encodeUriString(s).replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/%26/gi, '&'); } /** * @param {?} s * @return {?} */ function decode(s) { return decodeURIComponent(s); } // Query keys/values should have the "+" replaced first, as "+" in a query string is " ". // decodeURIComponent function will not decode "+" as a space. /** * @param {?} s * @return {?} */ function decodeQuery(s) { return decode(s.replace(/\+/g, '%20')); } /** * @param {?} path * @return {?} */ function serializePath(path) { return `${encodeUriSegment(path.path)}${serializeMatrixParams(path.parameters)}`; } /** * @param {?} params * @return {?} */ function serializeMatrixParams(params) { return Object.keys(params) .map((/** * @param {?} key * @return {?} */ key => `;${encodeUriSegment(key)}=${encodeUriSegment(params[key])}`)) .join(''); } /** * @param {?} params * @return {?} */ function serializeQueryParams(params) { /** @type {?} */ const strParams = Object.keys(params).map((/** * @param {?} name * @return {?} */ (name) => { /** @type {?} */ const value = params[name]; return Array.isArray(value) ? value.map((/** * @param {?} v * @return {?} */ v => `${encodeUriQuery(name)}=${encodeUriQuery(v)}`)).join('&') : `${encodeUriQuery(name)}=${encodeUriQuery(value)}`; })); return strParams.length ? `?${strParams.join('&')}` : ''; } /** @type {?} */ const SEGMENT_RE = /^[^\/()?;=#]+/; /** * @param {?} str * @return {?} */ function matchSegments(str) { /** @type {?} */ const match = str.match(SEGMENT_RE); return match ? match[0] : ''; } /** @type {?} */ const QUERY_PARAM_RE = /^[^=?&#]+/; // Return the name of the query param at the start of the string or an empty string /** * @param {?} str * @return {?} */ function matchQueryParams(str) { /** @type {?} */ const match = str.match(QUERY_PARAM_RE); return match ? match[0] : ''; } /** @type {?} */ const QUERY_PARAM_VALUE_RE = /^[^?&#]+/; // Return the value of the query param at the start of the string or an empty string /** * @param {?} str * @return {?} */ function matchUrlQueryParamValue(str) { /** @type {?} */ const match = str.match(QUERY_PARAM_VALUE_RE); return match ? match[0] : ''; } class UrlParser { /** * @param {?} url */ constructor(url) { this.url = url; this.remaining = url; } /** * @return {?} */ parseRootSegment() { this.consumeOptional('/'); if (this.remaining === '' || this.peekStartsWith('?') || this.peekStartsWith('#')) { return new UrlSegmentGroup([], {}); } // The root segment group never has segments return new UrlSegmentGroup([], this.parseChildren()); } /** * @return {?} */ parseQueryParams() { /** @type {?} */ const params = {}; if (this.consumeOptional('?')) { do { this.parseQueryParam(params); } while (this.consumeOptional('&')); } return params; } /** * @return {?} */ parseFragment() { return this.consumeOptional('#') ? decodeURIComponent(this.remaining) : null; } /** * @private * @return {?} */ parseChildren() { if (this.remaining === '') { return {}; } this.consumeOptional('/'); /** @type {?} */ const segments = []; if (!this.peekStartsWith('(')) { segments.push(this.parseSegment()); } while (this.peekStartsWith('/') && !this.peekStartsWith('//') && !this.peekStartsWith('/(')) { this.capture('/'); segments.push(this.parseSegment()); } /** @type {?} */ let children = {}; if (this.peekStartsWith('/(')) { this.capture('/'); children = this.parseParens(true); } /** @type {?} */ let res = {}; if (this.peekStartsWith('(')) { res = this.parseParens(false); } if (segments.length > 0 || Object.keys(children).length > 0) { res[PRIMARY_OUTLET] = new UrlSegmentGroup(segments, children); } return res; } // parse a segment with its matrix parameters // ie `name;k1=v1;k2` /** * @private * @return {?} */ parseSegment() { /** @type {?} */ const path = matchSegments(this.remaining); if (path === '' && this.peekStartsWith(';')) { throw new Error(`Empty path url segment cannot have parameters: '${this.remaining}'.`); } this.capture(path); return new UrlSegment(decode(path), this.parseMatrixParams()); } /** * @private * @return {?} */ parseMatrixParams() { /** @type {?} */ const params = {}; while (this.consumeOptional(';')) { this.parseParam(params); } return params; } /** * @private * @param {?} params * @return {?} */ parseParam(params) { /** @type {?} */ const key = matchSegments(this.remaining); if (!key) { return; } this.capture(key); /** @type {?} */ let value = ''; if (this.consumeOptional('=')) { /** @type {?} */ const valueMatch = matchSegments(this.remaining); if (valueMatch) { value = valueMatch; this.capture(value); } } params[decode(key)] = decode(value); } // Parse a single query parameter `name[=value]` /** * @private * @param {?} params * @return {?} */ parseQueryParam(params) { /** @type {?} */ const key = matchQueryParams(this.remaining); if (!key) { return; } this.capture(key); /** @type {?} */ let value = ''; if (this.consumeOptional('=')) { /** @type {?} */ const valueMatch = matchUrlQueryParamValue(this.remaining); if (valueMatch) { value = valueMatch; this.capture(value); } } /** @type {?} */ const decodedKey = decodeQuery(key); /** @type {?} */ const decodedVal = decodeQuery(value); if (params.hasOwnProperty(decodedKey)) { // Append to existing values /** @type {?} */ let currentVal = params[decodedKey]; if (!Array.isArray(currentVal)) { currentVal = [currentVal]; params[decodedKey] = currentVal; } currentVal.push(decodedVal); } else { // Create a new value params[decodedKey] = decodedVal; } } // parse `(a/b//outlet_name:c/d)` /** * @private * @param {?} allowPrimary * @return {?} */ parseParens(allowPrimary) { /** @type {?} */ const segments = {}; this.capture('('); while (!this.consumeOptional(')') && this.remaining.length > 0) { /** @type {?} */ const path = matchSegments(this.remaining); /** @type {?} */ const next = this.remaining[path.length]; // if is is not one of these characters, then the segment was unescaped // or the group was not closed if (next !== '/' && next !== ')' && next !== ';') { throw new Error(`Cannot parse url '${this.url}'`); } /** @type {?} */ let outletName = (/** @type {?} */ (undefined)); if (path.indexOf(':') > -1) { outletName = path.substr(0, path.indexOf(':')); this.capture(outletName); this.capture(':'); } else if (allowPrimary) { outletName = PRIMARY_OUTLET; } /** @type {?} */ const children = this.parseChildren(); segments[outletName] = Object.keys(children).length === 1 ? children[PRIMARY_OUTLET] : new UrlSegmentGroup([], children); this.consumeOptional('//'); } return segments; } /** * @private * @param {?} str * @return {?} */ peekStartsWith(str) { return this.remaining.startsWith(str); } // Consumes the prefix when it is present and returns whether it has been consumed /** * @private * @param {?} str * @return {?} */ consumeOptional(str) { if (this.peekStartsWith(str)) { this.remaining = this.remaining.substring(str.length); return true; } return false; } /** * @private * @param {?} str * @return {?} */ capture(str) { if (!this.consumeOptional(str)) { throw new Error(`Expected "${str}".`); } } } if (false) { /** * @type {?} * @private */ UrlParser.prototype.remaining; /** * @type {?} * @private */ UrlParser.prototype.url; } /** * @fileoverview added by tsickle * Generated from: packages/router/src/utils/tree.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @template T */ class Tree { /** * @param {?} root */ constructor(root) { this._root = root; } /** * @return {?} */ get root() { return this._root.value; } /** * \@internal * @param {?} t * @return {?} */ parent(t) { /** @type {?} */ const p = this.pathFromRoot(t); return p.length > 1 ? p[p.length - 2] : null; } /** * \@internal * @param {?} t * @return {?} */ children(t) { /** @type {?} */ const n = findNode(t, this._root); return n ? n.children.map((/** * @param {?} t * @return {?} */ t => t.value)) : []; } /** * \@internal * @param {?} t * @return {?} */ firstChild(t) { /** @type {?} */ const n = findNode(t, this._root); return n && n.children.length > 0 ? n.children[0].value : null; } /** * \@internal * @param {?} t * @return {?} */ siblings(t) { /** @type {?} */ const p = findPath(t, this._root); if (p.length < 2) return []; /** @type {?} */ const c = p[p.length - 2].children.map((/** * @param {?} c * @return {?} */ c => c.value)); return c.filter((/** * @param {?} cc * @return {?} */ cc => cc !== t)); } /** * \@internal * @param {?} t * @return {?} */ pathFromRoot(t) { return findPath(t, this._root).map((/** * @param {?} s * @return {?} */ s => s.value)); } } if (false) { /** * \@internal * @type {?} */ Tree.prototype._root; } // DFS for the node matching the value /** * @template T * @param {?} value * @param {?} node * @return {?} */ function findNode(value, node) { if (value === node.value) return node; for (const child of node.children) { /** @type {?} */ const node = findNode(value, child); if (node) return node; } return null; } // Return the path to the node with the given value using DFS /** * @template T * @param {?} value * @param {?} node * @return {?} */ function findPath(value, node) { if (value === node.value) return [node]; for (const child of node.children) { /** @type {?} */ const path = findPath(value, child); if (path.length) { path.unshift(node); return path; } } return []; } /** * @template T */ class TreeNode { /** * @param {?} value * @param {?} children */ constructor(value, children) { this.value = value; this.children = children; } /** * @return {?} */ toString() { return `TreeNode(${this.value})`; } } if (false) { /** @type {?} */ TreeNode.prototype.value; /** @type {?} */ TreeNode.prototype.children; } // Return the list of T indexed by outlet name /** * @template T * @param {?} node * @return {?} */ function nodeChildrenAsMap(node) { /** @type {?} */ const map = {}; if (node) { node.children.forEach((/** * @param {?} child * @return {?} */ child => map[child.value.outlet] = child)); } return map; } /** * @fileoverview added by tsickle * Generated from: packages/router/src/router_state.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Represents the state of the router as a tree of activated routes. * * \@usageNotes * * Every node in the route tree is an `ActivatedRoute` instance * that knows about the "consumed" URL segments, the extracted parameters, * and the resolved data. * Use the `ActivatedRoute` properties to traverse the tree from any node. * * ### Example * * ``` * \@Component({templateUrl:'template.html'}) * class MyComponent { * constructor(router: Router) { * const state: RouterState = router.routerState; * const root: ActivatedRoute = state.root; * const child = root.firstChild; * const id: Observable<string> = child.params.map(p => p.id); * //... * } * } * ``` * * @see `ActivatedRoute` * * \@publicApi */ class RouterState extends Tree { /** * \@internal * @param {?} root * @param {?} snapshot */ constructor(root, snapshot) { super(root); this.snapshot = snapshot; setRouterState((/** @type {?} */ (this)), root); } /** * @return {?} */ toString() { return this.snapshot.toString(); } } if (false) { /** * The current snapshot of the router state * @type {?} */ RouterState.prototype.snapshot; } /** * @param {?} urlTree * @param {?} rootComponent * @return {?} */ function createEmptyState(urlTree, rootComponent) { /** @type {?} */ const snapshot = createEmptyStateSnapshot(urlTree, rootComponent); /** @type {?} */ const emptyUrl = new BehaviorSubject([new UrlSegment('', {})]); /** @type {?} */ const emptyParams = new BehaviorSubject({}); /** @type {?} */ const emptyData = new BehaviorSubject({}); /** @type {?} */ const emptyQueryParams = new BehaviorSubject({}); /** @type {?} */ const fragment = new BehaviorSubject(''); /** @type {?} */ const activated = new ActivatedRoute(emptyUrl, emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, snapshot.root); activated.snapshot = snapshot.root; return new RouterState(new TreeNode(activated, []), snapshot); } /** * @param {?} urlTree * @param {?} rootComponent * @return {?} */ function createEmptyStateSnapshot(urlTree, rootComponent) { /** @type {?} */ const emptyParams = {}; /** @type {?} */ const emptyData = {}; /** @type {?} */ const emptyQueryParams = {}; /** @type {?} */ const fragment = ''; /** @type {?} */ const activated = new ActivatedRouteSnapshot([], emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, null, urlTree.root, -1, {}); return new RouterStateSnapshot('', new TreeNode(activated, [])); } /** * Provides access to information about a route associated with a component * that is loaded in an outlet. * Use to traverse the `RouterState` tree and extract information from nodes. * * {\@example router/activated-route/module.ts region="activated-route" * header="activated-route.component.ts"} * * \@publicApi */ class ActivatedRoute { /** * \@internal * @param {?} url * @param {?} params * @param {?} queryParams * @param {?} fragment * @param {?} data * @param {?} outlet * @param {?} component * @param {?} futureSnapshot */ constructor(url, params, queryParams, fragment, data, outlet, component, futureSnapshot) { this.url = url; this.params = params; this.queryParams = queryParams; this.fragment = fragment; this.data = data; this.outlet = outlet; this.component = component; this._futureSnapshot = futureSnapshot; } /** * The configuration used to match this route. * @return {?} */ get routeConfig() { return this._futureSnapshot.routeConfig; } /** * The root of the router state. * @return {?} */ get root() { return this._routerState.root; } /** * The parent of this route in the router state tree. * @return {?} */ get parent() { return this._routerState.parent(this); } /** * The first child of this route in the router state tree. * @return {?} */ get firstChild() { return this._routerState.firstChild(this); } /** * The children of this route in the router state tree. * @return {?} */ get children() { return this._routerState.children(this); } /** * The path from the root of the router state tree to this route. * @return {?} */ get pathFromRoot() { return this._routerState.pathFromRoot(this); } /** * An Observable that contains a map of the required and optional parameters * specific to the route. * The map supports retrieving single and multiple values from the same parameter. * @return {?} */ get paramMap() { if (!this._paramMap) { this._paramMap = this.params.pipe(map((/** * @param {?} p * @return {?} */ (p) => convertToParamMap(p)))); } return this._paramMap; } /** * An Observable that contains a map of the query parameters available to all routes. * The map supports retrieving single and multiple values from the query parameter. * @return {?} */ get queryParamMap() { if (!this._queryParamMap) { this._queryParamMap = this.queryParams.pipe(map((/** * @param {?} p * @return {?} */ (p) => convertToParamMap(p)))); } return this._queryParamMap; } /** * @return {?} */ toString() { return this.snapshot ? this.snapshot.toString() : `Future(${this._futureSnapshot})`; } } if (false) { /** * The current snapshot of this route * @type {?} */ ActivatedRoute.prototype.snapshot; /** * \@internal * @type {?} */ ActivatedRoute.prototype._futureSnapshot; /** * \@internal * @type {?} */ ActivatedRoute.prototype._routerState; /** * \@internal * @type {?} */ ActivatedRoute.prototype._paramMap; /** * \@internal * @type {?} */ ActivatedRoute.prototype._queryParamMap; /** * An observable of the URL segments matched by this route. * @type {?} */ ActivatedRoute.prototype.url; /** * An observable of the matrix parameters scoped to this route. * @type {?} */ ActivatedRoute.prototype.params; /** * An observable of the query parameters shared by all the routes. * @type {?} */ ActivatedRoute.prototype.queryParams; /** * An observable of the URL fragment shared by all the routes. * @type {?} */ ActivatedRoute.prototype.fragment; /** * An observable of the static and resolved data of this route. * @type {?} */ ActivatedRoute.prototype.data; /** * The outlet name of the route, a constant. * @type {?} */ ActivatedRoute.prototype.outlet; /** * The component of the route, a constant. * @type {?} */ ActivatedRoute.prototype.component; } /** * Returns the inherited params, data, and resolve for a given route. * By default, this only inherits values up to the nearest path-less or component-less route. * \@internal * @param {?} route * @param {?=} paramsInheritanceStrategy * @return {?} */ function inheritedParamsDataResolve(route, paramsInheritanceStrategy = 'emptyOnly') { /** @type {?} */ const pathFromRoot = route.pathFromRoot; /** @type {?} */ let inheritingStartingFrom = 0; if (paramsInheritanceStrategy !== 'always') { inheritingStartingFrom = pathFromRoot.length - 1; while (inheritingStartingFrom >= 1) { /** @type {?} */ const current = pathFromRoot[inheritingStartingFrom]; /** @type {?} */ const parent = pathFromRoot[inheritingStartingFrom - 1]; // current route is an empty path => inherits its parent's params and data if (current.routeConfig && current.routeConfig.path === '') { inheritingStartingFrom--; // parent is componentless => current route should inherit its params and data } else if (!parent.component) { inheritingStartingFrom--; } else { break; } } } return flattenInherited(pathFromRoot.slice(inheritingStartingFrom)); } /** * \@internal * @param {?} pathFromRoot * @return {?} */ function flattenInherited(pathFromRoot) { return pathFromRoot.reduce((/** * @param {?} res * @param {?} curr * @return {?} */ (res, curr) => { /** @type {?} */ const params = Object.assign(Object.assign({}, res.params), curr.params); /** @type {?} */ const data = Object.assign(Object.assign({}, res.data), curr.data); /** @type {?} */ const resolve = Object.assign(Object.assign({}, res.resolve), curr._resolvedData); return { params, data, resolve }; }), (/** @type {?} */ ({ params: {}, data: {}, resolve: {} }))); } /** * \@description * * Contains the information about a route associated with a component loaded in an * outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to * traverse the router state tree. * * ``` * \@Component({templateUrl:'./my-component.html'}) * class MyComponent { * constructor(route: ActivatedRoute) { * const id: string = route.snapshot.params.id; * const url: string = route.snapshot.url.join(''); * const user = route.snapshot.data.user; * } * } * ``` * * \@publicApi */ class ActivatedRouteSnapshot { /** * \@internal * @param {?} url * @param {?} params * @param {?} queryParams * @param {?} fragment * @param {?} data * @param {?} outlet * @param {?} component * @param {?} routeConfig * @param {?} urlSegment * @param {?} lastPathIndex * @param {?} resolve */ constructor(url, params, queryParams, fragment, data, outlet, component, routeConfig, urlSegment, lastPathIndex, resolve) { this.url = url; this.params = params; this.queryParams = queryParams; this.fragment = fragment; this.data = data; this.outlet = outlet; this.component = component; this.routeConfig = routeConfig; this._urlSegment = urlSegment; this._lastPathIndex = lastPathIndex; this._resolve = resolve; } /** * The root of the router state * @return {?} */ get root() { return this._routerState.root; } /** * The parent of this route in the router state tree * @return {?} */ get parent() { return this._routerState.parent(this); } /** * The first child of this route in the router state tree * @return {?} */ get firstChild() { return this._routerState.firstChild(this); } /** * The children of this route in the router state tree * @return {?} */ get children() { return this._routerState.children(this); } /** * The path from the root of the router state tree to this route * @return {?} */ get pathFromRoot() { return this._routerState.pathFromRoot(this); } /** * @return {?} */ get paramMap() { if (!this._paramMap) { this._paramMap = convertToParamMap(this.params); } return this._paramMap; } /** * @return {?} */ get queryParamMap() { if (!this._queryParamMap) { this._queryParamMap = convertToParamMap(this.queryParams); } return this._queryParamMap; } /** * @return {?} */ toString() { /** @type {?} */ const url = this.url.map((/** * @param {?} segment * @return {?} */ segment => segment.toString())).join('/'); /** @type {?} */ const matched = this.routeConfig ? this.routeConfig.path : ''; return `Route(url:'${url}', path:'${matched}')`; } } if (false) { /** * The configuration used to match this route * * @type {?} */ ActivatedRouteSnapshot.prototype.routeConfig; /** * \@internal * * @type {?} */ ActivatedRouteSnapshot.prototype._urlSegment; /** * \@internal * @type {?} */ ActivatedRouteSnapshot.prototype._lastPathIndex; /** * \@internal * @type {?} */ ActivatedRouteSnapshot.prototype._resolve; /** * \@internal * @type {?} */ ActivatedRouteSnapshot.prototype._resolvedData; /** * \@internal * @type {?} */ ActivatedRouteSnapshot.prototype._routerState; /** * \@internal * @type {?} */ ActivatedRouteSnapshot.prototype._paramMap; /** * \@internal * @type {?} */ ActivatedRouteSnapshot.prototype._queryParamMap; /** * The URL segments matched by this route * @type {?} */ ActivatedRouteSnapshot.prototype.url; /** * The matrix parameters scoped to this route * @type {?} */ ActivatedRouteSnapshot.prototype.params; /** * The query parameters shared by all the routes * @type {?} */ ActivatedRouteSnapshot.prototype.queryParams; /** * The URL fragment shared by all the routes * @type {?} */ ActivatedRouteSnapshot.prototype.fragment; /** * The static and resolved data of this route * @type {?} */ ActivatedRouteSnapshot.prototype.data; /** * The outlet name of the route * @type {?} */ ActivatedRouteSnapshot.prototype.outlet; /** * The component of the route * @type {?} */ ActivatedRouteSnapshot.prototype.component; } /** * \@description * * Represents the state of the router at a moment in time. * * This is a tree of activated route snapshots. Every node in this tree knows about * the "consumed" URL segments, the extracted parameters, and the resolved data. * * \@usageNotes * ### Example * * ``` * \@Component({templateUrl:'template.html'}) * class MyComponent { * constructor(router: Router) { * const state: RouterState = router.routerState; * const snapshot: RouterStateSnapshot = state.snapshot; * const root: ActivatedRouteSnapshot = snapshot.root; * const child = root.firstChild; * const id: Observable<string> = child.params.map(p => p.id); * //... * } * } * ``` * * \@publicApi */ class RouterStateSnapshot extends Tree { /** * \@internal * @param {?} url * @param {?} root */ constructor(url, root) { super(root); this.url = url; setRouterState((/** @type {?} */ (this)), root); } /** * @return {?} */ toString() { return serializeNode(this._root); } } if (false) { /** * The url from which this snapshot was created * @type {?} */ RouterStateSnapshot.prototype.url; } /** * @template U, T * @param {?} state * @param {?} node * @return {?} */ function setRouterState(state, node) { node.value._routerState = state; node.children.forEach((/** * @param {?} c * @return {?} */ c => setRouterState(state, c))); } /** * @param {?} node * @return {?} */ function serializeNode(node) { /** @type {?} */ const c = node.children.length > 0 ? ` { ${node.children.map(serializeNode).join(', ')} } ` : ''; return `${node.value}${c}`; } /** * The expectation is that the activate route is created with the right set of parameters. * So we push new values into the observables only when they are not the initial values. * And we detect that by checking if the snapshot field is set. * @param {?} route * @return {?} */ function advanceActivatedRoute(route) { if (route.snapshot) { /** @type {?} */ const currentSnapshot = route.snapshot; /** @type {?} */ const nextSnapshot = route._futureSnapshot; route.snapshot = nextSnapshot; if (!shallowEqual(currentSnapshot.queryParams, nextSnapshot.queryParams)) { ((/** @type {?} */ (route.queryParams))).next(nextSnapshot.queryParams); } if (currentSnapshot.fragment !== nextSnapshot.fragment) { ((/** @type {?} */ (route.fragment))).next(nextSnapshot.fragment); } if (!shallowEqual(currentSnapshot.params, nextSnapshot.params)) { ((/** @type {?} */ (route.params))).next(nextSnapshot.params); } if (!shallowEqualArrays(currentSnapshot.url, nextSnapshot.url)) { ((/** @type {?} */ (route.url))).next(nextSnapshot.url); } if (!shallowEqual(currentSnapshot.data, nextSnapshot.data)) { ((/** @type {?} */ (route.data))).next(nextSnapshot.data); } } else { route.snapshot = route._futureSnapshot; // this is for resolved data ((/** @type {?} */ (route.data))).next(route._futureSnapshot.data); } } /** * @param {?} a * @param {?} b * @return {?} */ function equalParamsAndUrlSegments(a, b) { /** @type {?} */ const equalUrlParams = shallowEqual(a.params, b.params) && equalSegments(a.url, b.url); /** @type {?} */ const parentsMismatch = !a.parent !== !b.parent; return equalUrlParams && !parentsMismatch && (!a.parent || equalParamsAndUrlSegments(a.parent, (/** @type {?} */ (b.parent)))); } /** * @fileoverview added by tsickle * Generated from: packages/router/src/create_router_state.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @param {?} routeReuseStrategy * @param {?} curr * @param {?} prevState * @return {?} */ function createRouterState(routeReuseStrategy, curr, prevState) { /** @type {?} */ const root = createNode(routeReuseStrategy, curr._root, prevState ? prevState._root : undefined); return new RouterState(root, curr); } /** * @param {?} routeReuseStrategy * @param {?} curr * @param {?=} prevState * @return {?} */ function createNode(routeReuseStrategy, curr, prevState) { // reuse an activated route that is currently displayed on the screen if (prevState && routeReuseStrategy.shouldReuseRoute(curr.value, prevState.value.snapshot)) { /** @type {?} */ const value = prevState.value; value._futureSnapshot = curr.value; /** @type {?} */ const children = createOrReuseChildren(routeReuseStrategy, curr, prevState); return new TreeNode(value, children); // retrieve an activated route that is used to be displayed, but is not currently displayed } else { /** @type {?} */ const detachedRouteHandle = (/** @type {?} */ (routeReuseStrategy.retrieve(curr.value))); if (detachedRouteHandle) { /** @type {?} */ const tree = detachedRouteHandle.route; setFutureSnapshotsOfActivatedRoutes(curr, tree); return tree; } else { /** @type {?} */ const value = createActivatedRoute(curr.value); /** @type {?} */ const children = curr.children.map((/** * @param {?} c * @return {?} */ c => createNode(routeReuseStrategy, c))); return new TreeNode(value, children); } } } /** * @param {?} curr * @param {?} result * @return {?} */ function setFutureSnapshotsOfActivatedRoutes(curr, result) { if (curr.value.routeConfig !== result.value.routeConfig) { throw new Error('Cannot reattach ActivatedRouteSnapshot created from a different route'); } if (curr.children.length !== result.children.length) { throw new Error('Cannot reattach ActivatedRouteSnapshot with a different number of children'); } result.value._futureSnapshot = curr.value; for (let i = 0; i < curr.children.length; ++i) { setFutureSnapshotsOfActivatedRoutes(curr.children[i], result.children[i]); } } /** * @param {?} routeReuseStrategy * @param {?} curr * @param {?} prevState * @return {?} */ function createOrReuseChildren(routeReuseStrategy, curr, prevState) { return curr.children.map((/** * @param {?} child * @return {?} */ child => { for (const p of prevState.children) { if (routeReuseStrategy.shouldReuseRoute(p.value.snapshot, child.value)) { return createNode(routeReuseStrategy, child, p); } } return createNode(routeReuseStrategy, child); })); } /** * @param {?} c * @return {?} */ function createActivatedRoute(c) { return new ActivatedRoute(new BehaviorSubject(c.url), new BehaviorSubject(c.params), new BehaviorSubject(c.queryParams), new BehaviorSubject(c.fragment), new BehaviorSubject(c.data), c.outlet, c.component, c); } /** * @fileoverview added by tsickle * Generated from: packages/router/src/create_url_tree.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @param {?} route * @param {?} urlTree * @param {?} commands * @param {?} queryParams * @param {?} fragment * @return {?} */ function createUrlTree(route, urlTree, commands, queryParams, fragment) { if (commands.length === 0) { return tree(urlTree.root, urlTree.root, urlTree, queryParams, fragment); } /** @type {?} */ const nav = computeNavigation(commands); if (nav.toRoot()) { return tree(urlTree.root, new UrlSegmentGroup([], {}), urlTree, queryParams, fragment); } /** @type {?} */ const startingPosition = findStartingPosition(nav, urlTree, route); /** @type {?} */ const segmentGroup = startingPosition.processChildren ? updateSegmentGroupChildren(startingPosition.segmentGroup, startingPosition.index, nav.commands) : updateSegmentGroup(startingPosition.segmentGroup, startingPosition.index, nav.commands); return tree(startingPosition.segmentGroup, segmentGroup, urlTree, queryParams, fragment); } /** * @param {?} command * @return {?} */ function isMatrixParams(command) { return typeof command === 'object' && command != null && !command.outlets && !command.segmentPath; } /** * @param {?} oldSegmentGroup * @param {?} newSegmentGroup * @param {?} urlTree * @param {?} queryParams * @param {?} fragment * @return {?} */ function tree(oldSegmentGroup, newSegmentGroup, urlTree, queryParams, fragment) { /** @type {?} */ let qp = {}; if (queryParams) { forEach(queryParams, (/** * @param {?} value * @param {?} name * @return {?} */ (value, name) => { qp[name] = Array.isArray(value) ? value.map((/** * @param {?} v * @return {?} */ (v) => `${v}`)) : `${value}`; })); } if (urlTree.root === oldSegmentGroup) { return new UrlTree(newSegmentGroup, qp, fragment); } return new UrlTree(replaceSegment(urlTree.root, oldSegmentGroup, newSegmentGroup), qp, fragment); } /** * @param {?} current * @param {?} oldSegment * @param {?} newSegment * @return {?} */ function replaceSegment(current, oldSegment, newSegment) { /** @type {?} */ const children = {}; forEach(current.children, (/** * @param {?} c * @param {?} outletName * @return {?} */ (c, outletName) => { if (c === oldSegment) { children[outletName] = newSegment; } else { children[outletName] = replaceSegment(c, oldSegment, newSegment); } })); return new UrlSegmentGroup(current.segments, children); } class Navigation { /** * @param {?} isAbsolute * @param {?} numberOfDoubleDots * @param {?} commands */ constructor(isAbsolute, numberOfDoubleDots, commands) { this.isAbsolute = isAbsolute; this.numberOfDoubleDots = numberOfDoubleDots; this.commands = commands; if (isAbsolute && commands.length > 0 && isMatrixParams(commands[0])) { throw new Error('Root segment cannot have matrix parameters'); } /** @type {?} */ const cmdWithOutlet = commands.find((/** * @param {?} c * @return {?} */ c => typeof c === 'object' && c != null && c.outlets)); if (cmdWithOutlet && cmdWithOutlet !== last(commands)) { throw new Error('{outlets:{}} has to be the last command'); } } /** * @return {?} */ toRoot() { return this.isAbsolute && this.commands.length === 1 && this.commands[0] == '/'; } } if (false) { /** @type {?} */ Navigation.prototype.isAbsolute; /** @type {?} */ Navigation.prototype.numberOfDoubleDots; /** @type {?} */ Navigation.prototype.commands; } /** * Transforms commands to a normalized `Navigation` * @param {?} commands * @return {?} */ function computeNavigation(commands) { if ((typeof commands[0] === 'string') && commands.length === 1 && commands[0] === '/') { return new Navigation(true, 0, commands); } /** @type {?} */ let numberOfDoubleDots = 0; /** @type {?} */ let isAbsolute = false; /** @type {?} */ const res = commands.reduce((/** * @param {?} res * @param {?} cmd * @param {?} cmdIdx * @return {?} */ (res, cmd, cmdIdx) => { if (typeof cmd === 'object' && cmd != null) { if (cmd.outlets) { /** @type {?} */ const outlets = {}; forEach(cmd.outlets, (/** * @param {?} commands * @param {?} name * @return {?} */ (commands, name) => { outlets[name] = typeof commands === 'string' ? commands.split('/') : commands; })); return [...res, { outlets }]; } if (cmd.segmentPath) { return [...res, cmd.segmentPath]; } } if (!(typeof cmd === 'string')) { return [...res, cmd]; } if (cmdIdx === 0) { cmd.split('/').forEach((/** * @param {?} urlPart * @param {?} partIndex * @return {?} */ (urlPart, partIndex) => { if (partIndex == 0 && urlPart === '.') { // skip './a' } else if (partIndex == 0 && urlPart === '') { // '/a' isAbsolute = true; } else if (urlPart === '..') { // '../a' numberOfDoubleDots++; } else if (urlPart != '') { res.push(urlPart); } })); return res; } return [...res, cmd]; }), []); return new Navigation(isAbsolute, numberOfDoubleDots, res); } class Position { /** * @param {?} segmentGroup * @param {?} processChildren * @param {?} index */ constructor(segmentGroup, processChildren, index) { this.segmentGroup = segmentGroup; this.processChildren = processChildren; this.index = index; } } if (false) { /** @type {?} */ Position.prototype.segmentGroup; /** @type {?} */ Position.prototype.processChildren; /** @type {?} */ Position.prototype.index; } /** * @param {?} nav * @param {?} tree * @param {?} route * @return {?} */ function findStartingPosition(nav, tree, route) { if (nav.isAbsolute) { return new Position(tree.root, true, 0); } if (route.snapshot._lastPathIndex === -1) { return new Position(route.snapshot._urlSegment, true, 0); } /** @type {?} */ const modifier = isMatrixParams(nav.commands[0]) ? 0 : 1; /** @type {?} */ const index = route.snapshot._lastPathIndex + modifier; return createPositionApplyingDoubleDots(route.snapshot._urlSegment, index, nav.numberOfDoubleDots); } /** * @param {?} group * @param {?} index * @param {?} numberOfDoubleDots * @return {?} */ function createPositionApplyingDoubleDots(group, index, numberOfDoubleDots) { /** @type {?} */ let g = group; /** @type {?} */ let ci = index; /** @type {?} */ let dd = numberOfDoubleDots; while (dd > ci) { dd -= ci; g = (/** @type {?} */ (g.parent)); if (!g) { throw new Error('Invalid number of \'../\''); } ci = g.segments.length; } return new Position(g, false, ci - dd); } /** * @param {?} command * @return {?} */ function getPath(command) { if (typeof command === 'object' && command != null && command.outlets) { return command.outlets[PRIMARY_OUTLET]; } return `${command}`; } /** * @param {?} commands * @return {?} */ function getOutlets(commands) { if (!(typeof commands[0] === 'object')) return { [PRIMARY_OUTLET]: commands }; if (commands[0].outlets === undefined) return { [PRIMARY_OUTLET]: commands }; return commands[0].outlets; } /** * @param {?} segmentGroup * @param {?} startIndex * @param {?} commands * @return {?} */ function updateSegmentGroup(segmentGroup, startIndex, commands) { if (!segmentGroup) { segmentGroup = new UrlSegmentGroup([], {}); } if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) { return updateSegmentGroupChildren(segmentGroup, startIndex, commands); } /** @type {?} */ const m = prefixedWith(segmentGroup, startIndex, commands); /** @type {?} */ const slicedCommands = commands.slice(m.commandIndex); if (m.match && m.pathIndex < segmentGroup.segments.length) { /** @type {?} */ const g = new UrlSegmentGroup(segmentGroup.segments.slice(0, m.pathIndex), {}); g.children[PRIMARY_OUTLET] = new UrlSegmentGroup(segmentGroup.segments.slice(m.pathIndex), segmentGroup.children); return updateSegmentGroupChildren(g, 0, slicedCommands); } else if (m.match && slicedCommands.length === 0) { return new UrlSegmentGroup(segmentGroup.segments, {}); } else if (m.match && !segmentGroup.hasChildren()) { return createNewSegmentGroup(segmentGroup, startIndex, commands); } else if (m.match) { return updateSegmentGroupChildren(segmentGroup, 0, slicedCommands); } else { return createNewSegmentGroup(segmentGroup, startIndex, commands); } } /** * @param {?} segmentGroup * @param {?} startIndex * @param {?} commands * @return {?} */ function updateSegmentGroupChildren(segmentGroup, startIndex, commands) { if (commands.length === 0) { return new UrlSegmentGroup(segmentGroup.segments, {}); } else { /** @type {?} */ const outlets = getOutlets(commands); /** @type {?} */ const children = {}; forEach(outlets, (/** * @param {?} commands * @param {?} outlet * @return {?} */ (commands, outlet) => { if (commands !== null) { children[outlet] = updateSegmentGroup(segmentGroup.children[outlet], startIndex, commands); } })); forEach(segmentGroup.children, (/** * @param {?} child * @param {?} childOutlet * @return {?} */ (child, childOutlet) => { if (outlets[childOutlet] === undefined) { children[childOutlet] = child; } })); return new UrlSegmentGroup(segmentGroup.segments, children); } } /** * @param {?} segmentGroup * @param {?} startIndex * @param {?} commands * @return {?} */ function prefixedWith(segmentGroup, startIndex, commands) { /** @type {?} */ let currentCommandIndex = 0; /** @type {?} */ let currentPathIndex = startIndex; /** @type {?} */ const noMatch = { match: false, pathIndex: 0, commandIndex: 0 }; while (currentPathIndex < segmentGroup.segments.length) { if (currentCommandIndex >= commands.length) return noMatch; /** @type {?} */ const path = segmentGroup.segments[currentPathIndex]; /** @type {?} */ const curr = getPath(commands[currentCommandIndex]); /** @type {?} */ const next = currentCommandIndex < commands.length - 1 ? commands[currentCommandIndex + 1] : null; if (currentPathIndex > 0 && curr === undefined) break; if (curr && next && (typeof next === 'object') && next.outlets === undefined) { if (!compare(curr, next, path)) return noMatch; currentCommandIndex += 2; } else { if (!compare(curr, {}, path)) return noMatch; currentCommandIndex++; } currentPathIndex++; } return { match: true, pathIndex: currentPathIndex, commandIndex: currentCommandIndex }; } /** * @param {?} segmentGroup * @param {?} startIndex * @param {?} commands * @return {?} */ function createNewSegmentGroup(segmentGroup, startIndex, commands) { /** @type {?} */ const paths = segmentGroup.segments.slice(0, startIndex); /** @type {?} */ let i = 0; while (i < commands.length) { if (typeof commands[i] === 'object' && commands[i].outlets !== undefined) { /** @type {?} */ const children = createNewSegmentChildren(commands[i].outlets); return new UrlSegmentGroup(paths, children); } // if we start with an object literal, we need to reuse the path part from the segment if (i === 0 && isMatrixParams(commands[0])) { /** @type {?} */ const p = segmentGroup.segments[startIndex]; paths.push(new UrlSegment(p.path, commands[0])); i++; continue; } /** @type {?} */ const curr = getPath(commands[i]); /** @type {?} */ const next = (i < commands.length - 1) ? commands[i + 1] : null; if (curr && next && isMatrixParams(next)) { paths.push(new UrlSegment(curr, stringify(next))); i += 2; } else { paths.push(new UrlSegment(curr, {})); i++; } } return new UrlSegmentGroup(paths, {}); } /** * @param {?} outlets * @return {?} */ function createNewSegmentChildren(outlets) { /** @type {?} */ const children = {}; forEach(outlets, (/** * @param {?} commands * @param {?} outlet * @return {?} */ (commands, outlet) => { if (commands !== null) { children[outlet] = createNewSegmentGroup(new UrlSegmentGroup([], {}), 0, commands); } })); return children; } /** * @param {?} params * @return {?} */ function stringify(params) { /** @type {?} */ const res = {}; forEach(params, (/** * @param {?} v * @param {?} k * @return {?} */ (v, k) => res[k] = `${v}`)); return res; } /** * @param {?} path * @param {?} params * @param {?} segment * @return {?} */ function compare(path, params, segment) { return path == segment.path && shallowEqual(params, segment.parameters); } /** * @fileoverview added by tsickle * Generated from: packages/router/src/operators/activate_routes.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** @type {?} */ const activateRoutes = (/** * @param {?} rootContexts * @param {?} routeReuseStrategy * @param {?} forwardEvent * @return {?} */ (rootContexts, routeReuseStrategy, forwardEvent) => map((/** * @param {?} t * @return {?} */ t => { new ActivateRoutes(routeReuseStrategy, (/** @type {?} */ (t.targetRouterState)), t.currentRouterState, forwardEvent) .activate(rootContexts); return t; }))); class ActivateRoutes { /** * @param {?} routeReuseStrategy * @param {?} futureState * @param {?} currState * @param {?} forwardEvent */ constructor(routeReuseStrategy, futureState, currState, forwardEvent) { this.routeReuseStrategy = routeReuseStrategy; this.futureState = futureState; this.currState = currState; this.forwardEvent = forwardEvent; } /** * @param {?} parentContexts * @return {?} */ activate(parentContexts) { /** @type {?} */ const futureRoot = this.futureState._root; /** @type {?} */ const currRoot = this.currState ? this.currState._root : null; this.deactivateChildRoutes(futureRoot, currRoot, parentContexts); advanceActivatedRoute(this.futureState.root); this.activateChildRoutes(futureRoot, currRoot, parentContexts); } // De-activate the child route that are not re-used for the future state /** * @private * @param {?} futureNode * @param {?} currNode * @param {?} contexts * @return {?} */ deactivateChildRoutes(futureNode, currNode, contexts) { /** @type {?} */ const children = nodeChildrenAsMap(currNode); // Recurse on the routes active in the future state to de-activate deeper children futureNode.children.forEach((/** * @param {?} futureChild * @return {?} */ futureChild => { /** @type {?} */ const childOutletName = futureChild.value.outlet; this.deactivateRoutes(futureChild, children[childOutletName], contexts); delete children[childOutletName]; })); // De-activate the routes that will not be re-used forEach(children, (/** * @param {?} v * @param {?} childName * @return {?} */ (v, childName) => { this.deactivateRouteAndItsChildren(v, contexts); })); } /** * @private * @param {?} futureNode * @param {?} currNode * @param {?} parentContext * @return {?} */ deactivateRoutes(futureNode, currNode, parentContext) { /** @type {?} */ const future = futureNode.value; /** @type {?} */ const curr = currNode ? currNode.value : null; if (future === curr) { // Reusing the node, check to see if the children need to be de-activated if (future.component) { // If we have a normal route, we need to go through an outlet. /** @type {?} */ const context = parentContext.getContext(future.outlet); if (context) { this.deactivateChildRoutes(futureNode, currNode, context.children); } } else { // if we have a componentless route, we recurse but keep the same outlet map. this.deactivateChildRoutes(futureNode, currNode, parentContext); } } else { if (curr) { // Deactivate the current route which will not be re-used this.deactivateRouteAndItsChildren(currNode, parentContext); } } } /** * @private * @param {?} route * @param {?} parentContexts * @return {?} */ deactivateRouteAndItsChildren(route, parentContexts) { if (this.routeReuseStrategy.shouldDetach(route.value.snapshot)) { this.detachAndStoreRouteSubtree(route, parentContexts); } else { this.deactivateRouteAndOutlet(route, parentContexts); } } /** * @private * @param {?} route * @param {?} parentContexts * @return {?} */ detachAndStoreRouteSubtree(route, parentContexts) { /** @type {?} */ const context = parentContexts.getContext(route.value.outlet); if (context && context.outlet) { /** @type {?} */ const componentRef = context.outlet.detach(); /** @type {?} */ const contexts = context.children.onOutletDeactivated(); this.routeReuseStrategy.store(route.value.snapshot, { componentRef, route, contexts }); } } /** * @private * @param {?} route * @param {?} parentContexts * @return {?} */ deactivateRouteAndOutlet(route, parentContexts) { /** @type {?} */ const context = parentContexts.getContext(route.value.outlet); if (context) { /** @type {?} */ const children = nodeChildrenAsMap(route); /** @type {?} */ const contexts = route.value.component ? context.children : parentContexts; forEach(children, (/** * @param {?} v * @param {?} k * @return {?} */ (v, k) => this.deactivateRouteAndItsChildren(v, contexts))); if (context.outlet) { // Destroy the component context.outlet.deactivate(); // Destroy the contexts for all the outlets that were in the component context.children.onOutletDeactivated(); } } } /** * @private * @param {?} futureNode * @param {?} currNode * @param {?} contexts * @return {?} */ activateChildRoutes(futureNode, currNode, contexts) { /** @type {?} */ const children = nodeChildrenAsMap(currNode); futureNode.children.forEach((/** * @param {?} c * @return {?} */ c => { this.activateRoutes(c, children[c.value.outlet], contexts); this.forwardEvent(new ActivationEnd(c.value.snapshot)); })); if (futureNode.children.length) { this.forwardEvent(new ChildActivationEnd(futureNode.value.snapshot)); } } /** * @private * @param {?} futureNode * @param {?} currNode * @param {?} parentContexts * @return {?} */ activateRoutes(futureNode, currNode, parentContexts) { /** @type {?} */ const future = futureNode.value; /** @type {?} */ const curr = currNode ? currNode.value : null; advanceActivatedRoute(future); // reusing the node if (future === curr) { if (future.component) { // If we have a normal route, we need to go through an outlet. /** @type {?} */ const context = parentContexts.getOrCreateContext(future.outlet); this.activateChildRoutes(futureNode, currNode, context.children); } else { // if we have a componentless route, we recurse but keep the same outlet map. this.activateChildRoutes(futureNode, currNode, parentContexts); } } else { if (future.component) { // if we have a normal route, we need to place the component into the outlet and recurse. /** @type {?} */ const context = parentContexts.getOrCreateContext(future.outlet); if (this.routeReuseStrategy.shouldAttach(future.snapshot)) { /** @type {?} */ const stored = ((/** @type {?} */ (this.routeReuseStrategy.retrieve(future.snapshot)))); this.routeReuseStrategy.store(future.snapshot, null); context.children.onOutletReAttached(stored.contexts); context.attachRef = stored.componentRef; context.route = stored.route.value; if (context.outlet) { // Attach right away when the outlet has already been instantiated // Otherwise attach from `RouterOutlet.ngOnInit` when it is instantiated context.outlet.attach(stored.componentRef, stored.route.value); } advanceActivatedRouteNodeAndItsChildren(stored.route); } else { /** @type {?} */ const config = parentLoadedConfig(future.snapshot); /** @type {?} */ const cmpFactoryResolver = config ? config.module.componentFactoryResolver : null; context.attachRef = null; context.route = future; context.resolver = cmpFactoryResolver; if (context.outlet) { // Activate the outlet when it has already been instantiated // Otherwise it will get activated from its `ngOnInit` when instantiated context.outlet.activateWith(future, cmpFactoryResolver); } this.activateChildRoutes(futureNode, null, context.children); } } else { // if we have a componentless route, we recurse but keep the same outlet map. this.activateChildRoutes(futureNode, null, parentContexts); } } } } if (false) { /** * @type {?} * @private */ ActivateRoutes.prototype.routeReuseStrategy; /** * @type {?} * @private */ ActivateRoutes.prototype.futureState; /** * @type {?} * @private */ ActivateRoutes.prototype.currState; /** * @type {?} * @private */ ActivateRoutes.prototype.forwardEvent; } /** * @param {?} node * @return {?} */ function advanceActivatedRouteNodeAndItsChildren(node) { advanceActivatedRoute(node.value); node.children.forEach(advanceActivatedRouteNodeAndItsChildren); } /** * @param {?} snapshot * @return {?} */ function parentLoadedConfig(snapshot) { for (let s = snapshot.parent; s; s = s.parent) { /** @type {?} */ const route = s.routeConfig; if (route && route._loadedConfig) return route._loadedConfig; if (route && route.component) return null; } return null; } /** * @fileoverview added by tsickle * Generated from: packages/router/src/utils/type_guards.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Simple function check, but generic so type inference will flow. Example: * * function product(a: number, b: number) { * return a * b; * } * * if (isFunction<product>(fn)) { * return fn(1, 2); * } else { * throw "Must provide the `product` function"; * } * @template T * @param {?} v * @return {?} */ function isFunction(v) { return typeof v === 'function'; } /** * @param {?} v * @return {?} */ function isBoolean(v) { return typeof v === 'boolean'; } /** * @param {?} v * @return {?} */ function isUrlTree(v) { return v instanceof UrlTree; } /** * @param {?} guard * @return {?} */ function isCanLoad(guard) { return guard && isFunction(guard.canLoad); } /** * @param {?} guard * @return {?} */ function isCanActivate(guard) { return guard && isFunction(guard.canActivate); } /** * @param {?} guard * @return {?} */ function isCanActivateChild(guard) { return guard && isFunction(guard.canActivateChild); } /** * @template T * @param {?} guard * @return {?} */ function isCanDeactivate(guard) { return guard && isFunction(guard.canDeactivate); } /** * @fileoverview added by tsickle * Generated from: packages/router/src/apply_redirects.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ class NoMatch { /** * @param {?=} segmentGroup */ constructor(segmentGroup) { this.segmentGroup = segmentGroup || null; } } if (false) { /** @type {?} */ NoMatch.prototype.segmentGroup; } class AbsoluteRedirect { /** * @param {?} urlTree */ constructor(urlTree) { this.urlTree = urlTree; } } if (false) { /** @type {?} */ AbsoluteRedirect.prototype.urlTree; } /** * @param {?} segmentGroup * @return {?} */ function noMatch(segmentGroup) { return new Observable((/** * @param {?} obs * @return {?} */ (obs) => obs.error(new NoMatch(segmentGroup)))); } /** * @param {?} newTree * @return {?} */ function absoluteRedirect(newTree) { return new Observable((/** * @param {?} obs * @return {?} */ (obs) => obs.error(new AbsoluteRedirect(newTree)))); } /** * @param {?} redirectTo * @return {?} */ function namedOutletsRedirect(redirectTo) { return new Observable((/** * @param {?} obs * @return {?} */ (obs) => obs.error(new Error(`Only absolute redirects can have named outlets. redirectTo: '${redirectTo}'`)))); } /** * @param {?} route * @return {?} */ function canLoadFails(route) { return new Observable((/** * @param {?} obs * @return {?} */ (obs) => obs.error(navigationCancelingError(`Cannot load children because the guard of the route "path: '${route.path}'" returned false`)))); } /** * Returns the `UrlTree` with the redirection applied. * * Lazy modules are loaded along the way. * @param {?} moduleInjector * @param {?} configLoader * @param {?} urlSerializer * @param {?} urlTree * @param {?} config * @return {?} */ function applyRedirects(moduleInjector, configLoader, urlSerializer, urlTree, config) { return new ApplyRedirects(moduleInjector, configLoader, urlSerializer, urlTree, config).apply(); } class ApplyRedirects { /** * @param {?} moduleInjector * @param {?} configLoader * @param {?} urlSerializer * @param {?} urlTree * @param {?} config */ constructor(moduleInjector, configLoader, urlSerializer, urlTree, config) { this.configLoader = configLoader; this.urlSerializer = urlSerializer; this.urlTree = urlTree; this.config = config; this.allowRedirects = true; this.ngModule = moduleInjector.get(NgModuleRef); } /** * @return {?} */ apply() { /** @type {?} */ const expanded$ = this.expandSegmentGroup(this.ngModule, this.config, this.urlTree.root, PRIMARY_OUTLET); /** @type {?} */ const urlTrees$ = expanded$.pipe(map((/** * @param {?} rootSegmentGroup * @return {?} */ (rootSegmentGroup) => this.createUrlTree(rootSegmentGroup, this.urlTree.queryParams, (/** @type {?} */ (this.urlTree.fragment)))))); return urlTrees$.pipe(catchError((/** * @param {?} e * @return {?} */ (e) => { if (e instanceof AbsoluteRedirect) { // after an absolute redirect we do not apply any more redirects! this.allowRedirects = false; // we need to run matching, so we can fetch all lazy-loaded modules return this.match(e.urlTree); } if (e instanceof NoMatch) { throw this.noMatchError(e); } throw e; }))); } /** * @private * @param {?} tree * @return {?} */ match(tree) { /** @type {?} */ const expanded$ = this.expandSegmentGroup(this.ngModule, this.config, tree.root, PRIMARY_OUTLET); /** @type {?} */ const mapped$ = expanded$.pipe(map((/** * @param {?} rootSegmentGroup * @return {?} */ (rootSegmentGroup) => this.createUrlTree(rootSegmentGroup, tree.queryParams, (/** @type {?} */ (tree.fragment)))))); return mapped$.pipe(catchError((/** * @param {?} e * @return {?} */ (e) => { if (e instanceof NoMatch) { throw this.noMatchError(e); } throw e; }))); } /** * @private * @param {?} e * @return {?} */ noMatchError(e) { return new Error(`Cannot match any routes. URL Segment: '${e.segmentGroup}'`); } /** * @private * @param {?} rootCandidate * @param {?} queryParams * @param {?} fragment * @return {?} */ createUrlTree(rootCandidate, queryParams, fragment) { /** @type {?} */ const root = rootCandidate.segments.length > 0 ? new UrlSegmentGroup([], { [PRIMARY_OUTLET]: rootCandidate }) : rootCandidate; return new UrlTree(root, queryParams, fragment); } /** * @private * @param {?} ngModule * @param {?} routes * @param {?} segmentGroup * @param {?} outlet * @return {?} */ expandSegmentGroup(ngModule, routes, segmentGroup, outlet) { if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) { return this.expandChildren(ngModule, routes, segmentGroup) .pipe(map((/** * @param {?} children * @return {?} */ (children) => new UrlSegmentGroup([], children)))); } return this.expandSegment(ngModule, segmentGroup, routes, segmentGroup.segments, outlet, true); } // Recursively expand segment groups for all the child outlets /** * @private * @param {?} ngModule * @param {?} routes * @param {?} segmentGroup * @return {?} */ expandChildren(ngModule, routes, segmentGroup) { return waitForMap(segmentGroup.children, (/** * @param {?} childOutlet * @param {?} child * @return {?} */ (childOutlet, child) => this.expandSegmentGroup(ngModule, routes, child, childOutlet))); } /** * @private * @param {?} ngModule * @param {?} segmentGroup * @param {?} routes * @param {?} segments * @param {?} outlet * @param {?} allowRedirects * @return {?} */ expandSegment(ngModule, segmentGroup, routes, segments, outlet, allowRedirects) { return of(...routes).pipe(map((/** * @param {?} r * @return {?} */ (r) => { /** @type {?} */ const expanded$ = this.expandSegmentAgainstRoute(ngModule, segmentGroup, routes, r, segments, outlet, allowRedirects); return expanded$.pipe(catchError((/** * @param {?} e * @return {?} */ (e) => { if (e instanceof NoMatch) { // TODO(i): this return type doesn't match the declared Observable<UrlSegmentGroup> - // talk to Jason return (/** @type {?} */ (of(null))); } throw e; }))); })), concatAll(), first((/** * @param {?} s * @return {?} */ (s) => !!s)), catchError((/** * @param {?} e * @param {?} _ * @return {?} */ (e, _) => { if (e instanceof EmptyError || e.name === 'EmptyError') { if (this.noLeftoversInUrl(segmentGroup, segments, outlet)) { return of(new UrlSegmentGroup([], {})); } throw new NoMatch(segmentGroup); } throw e; }))); } /** * @private * @param {?} segmentGroup * @param {?} segments * @param {?} outlet * @return {?} */ noLeftoversInUrl(segmentGroup, segments, outlet) { return segments.length === 0 && !segmentGroup.children[outlet]; } /** * @private * @param {?} ngModule * @param {?} segmentGroup * @param {?} routes * @param {?} route * @param {?} paths * @param {?} outlet * @param {?} allowRedirects * @return {?} */ expandSegmentAgainstRoute(ngModule, segmentGroup, routes, route, paths, outlet, allowRedirects) { if (getOutlet(route) !== outlet) { return noMatch(segmentGroup); } if (route.redirectTo === undefined) { return this.matchSegmentAgainstRoute(ngModule, segmentGroup, route, paths); } if (allowRedirects && this.allowRedirects) { return this.expandSegmentAgainstRouteUsingRedirect(ngModule, segmentGroup, routes, route, paths, outlet); } return noMatch(segmentGroup); } /** * @private * @param {?} ngModule * @param {?} segmentGroup * @param {?} routes * @param {?} route * @param {?} segments * @param {?} outlet * @return {?} */ expandSegmentAgainstRouteUsingRedirect(ngModule, segmentGroup, routes, route, segments, outlet) { if (route.path === '**') { return this.expandWildCardWithParamsAgainstRouteUsingRedirect(ngModule, routes, route, outlet); } return this.expandRegularSegmentAgainstRouteUsingRedirect(ngModule, segmentGroup, routes, route, segments, outlet); } /** * @private * @param {?} ngModule * @param {?} routes * @param {?} route * @param {?} outlet * @return {?} */ expandWildCardWithParamsAgainstRouteUsingRedirect(ngModule, routes, route, outlet) { /** @type {?} */ const newTree = this.applyRedirectCommands([], (/** @type {?} */ (route.redirectTo)), {}); if ((/** @type {?} */ (route.redirectTo)).startsWith('/')) { return absoluteRedirect(newTree); } return this.lineralizeSegments(route, newTree).pipe(mergeMap((/** * @param {?} newSegments * @return {?} */ (newSegments) => { /** @type {?} */ const group = new UrlSegmentGroup(newSegments, {}); return this.expandSegment(ngModule, group, routes, newSegments, outlet, false); }))); } /** * @private * @param {?} ngModule * @param {?} segmentGroup * @param {?} routes * @param {?} route * @param {?} segments * @param {?} outlet * @return {?} */ expandRegularSegmentAgainstRouteUsingRedirect(ngModule, segmentGroup, routes, route, segments, outlet) { const { matched, consumedSegments, lastChild, positionalParamSegments } = match(segmentGroup, route, segments); if (!matched) return noMatch(segmentGroup); /** @type {?} */ const newTree = this.applyRedirectCommands(consumedSegments, (/** @type {?} */ (route.redirectTo)), (/** @type {?} */ (positionalParamSegments))); if ((/** @type {?} */ (route.redirectTo)).startsWith('/')) { return absoluteRedirect(newTree); } return this.lineralizeSegments(route, newTree).pipe(mergeMap((/** * @param {?} newSegments * @return {?} */ (newSegments) => { return this.expandSegment(ngModule, segmentGroup, routes, newSegments.concat(segments.slice(lastChild)), outlet, false); }))); } /** * @private * @param {?} ngModule * @param {?} rawSegmentGroup * @param {?} route * @param {?} segments * @return {?} */ matchSegmentAgainstRoute(ngModule, rawSegmentGroup, route, segments) { if (route.path === '**') { if (route.loadChildren) { return this.configLoader.load(ngModule.injector, route) .pipe(map((/** * @param {?} cfg * @return {?} */ (cfg) => { route._loadedConfig = cfg; return new UrlSegmentGroup(segments, {}); }))); } return of(new UrlSegmentGroup(segments, {})); } const { matched, consumedSegments, lastChild } = match(rawSegmentGroup, route, segments); if (!matched) return noMatch(rawSegmentGroup); /** @type {?} */ const rawSlicedSegments = segments.slice(lastChild); /** @type {?} */ const childConfig$ = this.getChildConfig(ngModule, route, segments); return childConfig$.pipe(mergeMap((/** * @param {?} routerConfig * @return {?} */ (routerConfig) => { /** @type {?} */ const childModule = routerConfig.module; /** @type {?} */ const childConfig = routerConfig.routes; const { segmentGroup, slicedSegments } = split(rawSegmentGroup, consumedSegments, rawSlicedSegments, childConfig); if (slicedSegments.length === 0 && segmentGroup.hasChildren()) { /** @type {?} */ const expanded$ = this.expandChildren(childModule, childConfig, segmentGroup); return expanded$.pipe(map((/** * @param {?} children * @return {?} */ (children) => new UrlSegmentGroup(consumedSegments, children)))); } if (childConfig.length === 0 && slicedSegments.length === 0) { return of(new UrlSegmentGroup(consumedSegments, {})); } /** @type {?} */ const expanded$ = this.expandSegment(childModule, segmentGroup, childConfig, slicedSegments, PRIMARY_OUTLET, true); return expanded$.pipe(map((/** * @param {?} cs * @return {?} */ (cs) => new UrlSegmentGroup(consumedSegments.concat(cs.segments), cs.children)))); }))); } /** * @private * @param {?} ngModule * @param {?} route * @param {?} segments * @return {?} */ getChildConfig(ngModule, route, segments) { if (route.children) { // The children belong to the same module return of(new LoadedRouterConfig(route.children, ngModule)); } if (route.loadChildren) { // lazy children belong to the loaded module if (route._loadedConfig !== undefined) { return of(route._loadedConfig); } return runCanLoadGuard(ngModule.injector, route, segments) .pipe(mergeMap((/** * @param {?} shouldLoad * @return {?} */ (shouldLoad) => { if (shouldLoad) { return this.configLoader.load(ngModule.injector, route) .pipe(map((/** * @param {?} cfg * @return {?} */ (cfg) => { route._loadedConfig = cfg; return cfg; }))); } return canLoadFails(route); }))); } return of(new LoadedRouterConfig([], ngModule)); } /** * @private * @param {?} route * @param {?} urlTree * @return {?} */ lineralizeSegments(route, urlTree) { /** @type {?} */ let res = []; /** @type {?} */ let c = urlTree.root; while (true) { res = res.concat(c.segments); if (c.numberOfChildren === 0) { return of(res); } if (c.numberOfChildren > 1 || !c.children[PRIMARY_OUTLET]) { return namedOutletsRedirect((/** @type {?} */ (route.redirectTo))); } c = c.children[PRIMARY_OUTLET]; } } /** * @private * @param {?} segments * @param {?} redirectTo * @param {?} posParams * @return {?} */ applyRedirectCommands(segments, redirectTo, posParams) { return this.applyRedirectCreatreUrlTree(redirectTo, this.urlSerializer.parse(redirectTo), segments, posParams); } /** * @private * @param {?} redirectTo * @param {?} urlTree * @param {?} segments * @param {?} posParams * @return {?} */ applyRedirectCreatreUrlTree(redirectTo, urlTree, segments, posParams) { /** @type {?} */ const newRoot = this.createSegmentGroup(redirectTo, urlTree.root, segments, posParams); return new UrlTree(newRoot, this.createQueryParams(urlTree.queryParams, this.urlTree.queryParams), urlTree.fragment); } /** * @private * @param {?} redirectToParams * @param {?} actualParams * @return {?} */ createQueryParams(redirectToParams, actualParams) { /** @type {?} */ const res = {}; forEach(redirectToParams, (/** * @param {?} v * @param {?} k * @return {?} */ (v, k) => { /** @type {?} */ const copySourceValue = typeof v === 'string' && v.startsWith(':'); if (copySourceValue) { /** @type {?} */ const sourceName = v.substring(1); res[k] = actualParams[sourceName]; } else { res[k] = v; } })); return res; } /** * @private * @param {?} redirectTo * @param {?} group * @param {?} segments * @param {?} posParams * @return {?} */ createSegmentGroup(redirectTo, group, segments, posParams) { /** @type {?} */ const updatedSegments = this.createSegments(redirectTo, group.segments, segments, posParams); /** @type {?} */ let children = {}; forEach(group.children, (/** * @param {?} child * @param {?} name * @return {?} */ (child, name) => { children[name] = this.createSegmentGroup(redirectTo, child, segments, posParams); })); return new UrlSegmentGroup(updatedSegments, children); } /** * @private * @param {?} redirectTo * @param {?} redirectToSegments * @param {?} actualSegments * @param {?} posParams * @return {?} */ createSegments(redirectTo, redirectToSegments, actualSegments, posParams) { return redirectToSegments.map((/** * @param {?} s * @return {?} */ s => s.path.startsWith(':') ? this.findPosParam(redirectTo, s, posParams) : this.findOrReturn(s, actualSegments))); } /** * @private * @param {?} redirectTo * @param {?} redirectToUrlSegment * @param {?} posParams * @return {?} */ findPosParam(redirectTo, redirectToUrlSegment, posParams) { /** @type {?} */ const pos = posParams[redirectToUrlSegment.path.substring(1)]; if (!pos) throw new Error(`Cannot redirect to '${redirectTo}'. Cannot find '${redirectToUrlSegment.path}'.`); return pos; } /** * @private * @param {?} redirectToUrlSegment * @param {?} actualSegments * @return {?} */ findOrReturn(redirectToUrlSegment, actualSegments) { /** @type {?} */ let idx = 0; for (const s of actualSegments) { if (s.path === redirectToUrlSegment.path) { actualSegments.splice(idx); return s; } idx++; } return redirectToUrlSegment; } } if (false) { /** * @type {?} * @private */ ApplyRedirects.prototype.allowRedirects; /** * @type {?} * @private */ ApplyRedirects.prototype.ngModule; /** * @type {?} * @private */ ApplyRedirects.prototype.configLoader; /** * @type {?} * @private */ ApplyRedirects.prototype.urlSerializer; /** * @type {?} * @private */ ApplyRedirects.prototype.urlTree; /** * @type {?} * @private */ ApplyRedirects.prototype.config; } /** * @param {?} moduleInjector * @param {?} route * @param {?} segments * @return {?} */ function runCanLoadGuard(moduleInjector, route, segments) { /** @type {?} */ const canLoad = route.canLoad; if (!canLoad || canLoad.length === 0) return of(true); /** @type {?} */ const obs = from(canLoad).pipe(map((/** * @param {?} injectionToken * @return {?} */ (injectionToken) => { /** @type {?} */ const guard = moduleInjector.get(injectionToken); /** @type {?} */ let guardVal; if (isCanLoad(guard)) { guardVal = guard.canLoad(route, segments); } else if (isFunction(guard)) { guardVal = guard(route, segments); } else { throw new Error('Invalid CanLoad guard'); } return wrapIntoObservable(guardVal); }))); return obs.pipe(concatAll(), every((/** * @param {?} result * @return {?} */ result => result === true))); } /** * @param {?} segmentGroup * @param {?} route * @param {?} segments * @return {?} */ function match(segmentGroup, route, segments) { if (route.path === '') { if ((route.pathMatch === 'full') && (segmentGroup.hasChildren() || segments.length > 0)) { return { matched: false, consumedSegments: [], lastChild: 0, positionalParamSegments: {} }; } return { matched: true, consumedSegments: [], lastChild: 0, positionalParamSegments: {} }; } /** @type {?} */ const matcher = route.matcher || defaultUrlMatcher; /** @type {?} */ const res = matcher(segments, segmentGroup, route); if (!res) { return { matched: false, consumedSegments: (/** @type {?} */ ([])), lastChild: 0, positionalParamSegments: {}, }; } return { matched: true, consumedSegments: (/** @type {?} */ (res.consumed)), lastChild: (/** @type {?} */ (res.consumed.length)), positionalParamSegments: (/** @type {?} */ (res.posParams)), }; } /** * @param {?} segmentGroup * @param {?} consumedSegments * @param {?} slicedSegments * @param {?} config * @return {?} */ function split(segmentGroup, consumedSegments, slicedSegments, config) { if (slicedSegments.length > 0 && containsEmptyPathRedirectsWithNamedOutlets(segmentGroup, slicedSegments, config)) { /** @type {?} */ const s = new UrlSegmentGroup(consumedSegments, createChildrenForEmptySegments(config, new UrlSegmentGroup(slicedSegments, segmentGroup.children))); return { segmentGroup: mergeTrivialChildren(s), slicedSegments: [] }; } if (slicedSegments.length === 0 && containsEmptyPathRedirects(segmentGroup, slicedSegments, config)) { /** @type {?} */ const s = new UrlSegmentGroup(segmentGroup.segments, addEmptySegmentsToChildrenIfNeeded(segmentGroup, slicedSegments, config, segmentGroup.children)); return { segmentGroup: mergeTrivialChildren(s), slicedSegments }; } return { segmentGroup, slicedSegments }; } /** * @param {?} s * @return {?} */ function mergeTrivialChildren(s) { if (s.numberOfChildren === 1 && s.children[PRIMARY_OUTLET]) { /** @type {?} */ const c = s.children[PRIMARY_OUTLET]; return new UrlSegmentGroup(s.segments.concat(c.segments), c.children); } return s; } /** * @param {?} segmentGroup * @param {?} slicedSegments * @param {?} routes * @param {?} children * @return {?} */ function addEmptySegmentsToChildrenIfNeeded(segmentGroup, slicedSegments, routes, children) { /** @type {?} */ const res = {}; for (const r of routes) { if (isEmptyPathRedirect(segmentGroup, slicedSegments, r) && !children[getOutlet(r)]) { res[getOutlet(r)] = new UrlSegmentGroup([], {}); } } return Object.assign(Object.assign({}, children), res); } /** * @param {?} routes * @param {?} primarySegmentGroup * @return {?} */ function createChildrenForEmptySegments(routes, primarySegmentGroup) { /** @type {?} */ const res = {}; res[PRIMARY_OUTLET] = primarySegmentGroup; for (const r of routes) { if (r.path === '' && getOutlet(r) !== PRIMARY_OUTLET) { res[getOutlet(r)] = new UrlSegmentGroup([], {}); } } return res; } /** * @param {?} segmentGroup * @param {?} segments * @param {?} routes * @return {?} */ function containsEmptyPathRedirectsWithNamedOutlets(segmentGroup, segments, routes) { return routes.some((/** * @param {?} r * @return {?} */ r => isEmptyPathRedirect(segmentGroup, segments, r) && getOutlet(r) !== PRIMARY_OUTLET)); } /** * @param {?} segmentGroup * @param {?} segments * @param {?} routes * @return {?} */ function containsEmptyPathRedirects(segmentGroup, segments, routes) { return routes.some((/** * @param {?} r * @return {?} */ r => isEmptyPathRedirect(segmentGroup, segments, r))); } /** * @param {?} segmentGroup * @param {?} segments * @param {?} r * @return {?} */ function isEmptyPathRedirect(segmentGroup, segments, r) { if ((segmentGroup.hasChildren() || segments.length > 0) && r.pathMatch === 'full') { return false; } return r.path === '' && r.redirectTo !== undefined; } /** * @param {?} route * @return {?} */ function getOutlet(route) { return route.outlet || PRIMARY_OUTLET; } /** * @fileoverview added by tsickle * Generated from: packages/router/src/operators/apply_redirects.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @param {?} moduleInjector * @param {?} configLoader * @param {?} urlSerializer * @param {?} config * @return {?} */ function applyRedirects$1(moduleInjector, configLoader, urlSerializer, config) { return (/** * @param {?} source * @return {?} */ function (source) { return source.pipe(switchMap((/** * @param {?} t * @return {?} */ t => applyRedirects(moduleInjector, configLoader, urlSerializer, t.extractedUrl, config) .pipe(map((/** * @param {?} urlAfterRedirects * @return {?} */ urlAfterRedirects => (Object.assign(Object.assign({}, t), { urlAfterRedirects })))))))); }); } /** * @fileoverview added by tsickle * Generated from: packages/router/src/utils/preactivation.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ class CanActivate { /** * @param {?} path */ constructor(path) { this.path = path; this.route = this.path[this.path.length - 1]; } } if (false) { /** @type {?} */ CanActivate.prototype.route; /** @type {?} */ CanActivate.prototype.path; } class CanDeactivate { /** * @param {?} component * @param {?} route */ constructor(component, route) { this.component = component; this.route = route; } } if (false) { /** @type {?} */ CanDeactivate.prototype.component; /** @type {?} */ CanDeactivate.prototype.route; } /** * @param {?} future * @param {?} curr * @param {?} parentContexts * @return {?} */ function getAllRouteGuards(future, curr, parentContexts) { /** @type {?} */ const futureRoot = future._root; /** @type {?} */ const currRoot = curr ? curr._root : null; return getChildRouteGuards(futureRoot, currRoot, parentContexts, [futureRoot.value]); } /** * @param {?} p * @return {?} */ function getCanActivateChild(p) { /** @type {?} */ const canActivateChild = p.routeConfig ? p.routeConfig.canActivateChild : null; if (!canActivateChild || canActivateChild.length === 0) return null; return { node: p, guards: canActivateChild }; } /** * @param {?} token * @param {?} snapshot * @param {?} moduleInjector * @return {?} */ function getToken(token, snapshot, moduleInjector) { /** @type {?} */ const config = getClosestLoadedConfig(snapshot); /** @type {?} */ const injector = config ? config.module.injector : moduleInjector; return injector.get(token); } /** * @param {?} snapshot * @return {?} */ function getClosestLoadedConfig(snapshot) { if (!snapshot) return null; for (let s = snapshot.parent; s; s = s.parent) { /** @type {?} */ const route = s.routeConfig; if (route && route._loadedConfig) return route._loadedConfig; } return null; } /** * @param {?} futureNode * @param {?} currNode * @param {?} contexts * @param {?} futurePath * @param {?=} checks * @return {?} */ function getChildRouteGuards(futureNode, currNode, contexts, futurePath, checks = { canDeactivateChecks: [], canActivateChecks: [] }) { /** @type {?} */ const prevChildren = nodeChildrenAsMap(currNode); // Process the children of the future route futureNode.children.forEach((/** * @param {?} c * @return {?} */ c => { getRouteGuards(c, prevChildren[c.value.outlet], contexts, futurePath.concat([c.value]), checks); delete prevChildren[c.value.outlet]; })); // Process any children left from the current route (not active for the future route) forEach(prevChildren, (/** * @param {?} v * @param {?} k * @return {?} */ (v, k) => deactivateRouteAndItsChildren(v, (/** @type {?} */ (contexts)).getContext(k), checks))); return checks; } /** * @param {?} futureNode * @param {?} currNode * @param {?} parentContexts * @param {?} futurePath * @param {?=} checks * @return {?} */ function getRouteGuards(futureNode, currNode, parentContexts, futurePath, checks = { canDeactivateChecks: [], canActivateChecks: [] }) { /** @type {?} */ const future = futureNode.value; /** @type {?} */ const curr = currNode ? currNode.value : null; /** @type {?} */ const context = parentContexts ? parentContexts.getContext(futureNode.value.outlet) : null; // reusing the node if (curr && future.routeConfig === curr.routeConfig) { /** @type {?} */ const shouldRun = shouldRunGuardsAndResolvers(curr, future, (/** @type {?} */ (future.routeConfig)).runGuardsAndResolvers); if (shouldRun) { checks.canActivateChecks.push(new CanActivate(futurePath)); } else { // we need to set the data future.data = curr.data; future._resolvedData = curr._resolvedData; } // If we have a component, we need to go through an outlet. if (future.component) { getChildRouteGuards(futureNode, currNode, context ? context.children : null, futurePath, checks); // if we have a componentless route, we recurse but keep the same outlet map. } else { getChildRouteGuards(futureNode, currNode, parentContexts, futurePath, checks); } if (shouldRun) { /** @type {?} */ const component = context && context.outlet && context.outlet.component || null; checks.canDeactivateChecks.push(new CanDeactivate(component, curr)); } } else { if (curr) { deactivateRouteAndItsChildren(currNode, context, checks); } checks.canActivateChecks.push(new CanActivate(futurePath)); // If we have a component, we need to go through an outlet. if (future.component) { getChildRouteGuards(futureNode, null, context ? context.children : null, futurePath, checks); // if we have a componentless route, we recurse but keep the same outlet map. } else { getChildRouteGuards(futureNode, null, parentContexts, futurePath, checks); } } return checks; } /** * @param {?} curr * @param {?} future * @param {?} mode * @return {?} */ function shouldRunGuardsAndResolvers(curr, future, mode) { if (typeof mode === 'function') { return mode(curr, future); } switch (mode) { case 'pathParamsChange': return !equalPath(curr.url, future.url); case 'pathParamsOrQueryParamsChange': return !equalPath(curr.url, future.url) || !shallowEqual(curr.queryParams, future.queryParams); case 'always': return true; case 'paramsOrQueryParamsChange': return !equalParamsAndUrlSegments(curr, future) || !shallowEqual(curr.queryParams, future.queryParams); case 'paramsChange': default: return !equalParamsAndUrlSegments(curr, future); } } /** * @param {?} route * @param {?} context * @param {?} checks * @return {?} */ function deactivateRouteAndItsChildren(route, context, checks) { /** @type {?} */ const children = nodeChildrenAsMap(route); /** @type {?} */ const r = route.value; forEach(children, (/** * @param {?} node * @param {?} childName * @return {?} */ (node, childName) => { if (!r.component) { deactivateRouteAndItsChildren(node, context, checks); } else if (context) { deactivateRouteAndItsChildren(node, context.children.getContext(childName), checks); } else { deactivateRouteAndItsChildren(node, null, checks); } })); if (!r.component) { checks.canDeactivateChecks.push(new CanDeactivate(null, r)); } else if (context && context.outlet && context.outlet.isActivated) { checks.canDeactivateChecks.push(new CanDeactivate(context.outlet.component, r)); } else { checks.canDeactivateChecks.push(new CanDeactivate(null, r)); } } /** * @fileoverview added by tsickle * Generated from: packages/router/src/operators/prioritized_guard_value.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** @type {?} */ const INITIAL_VALUE = Symbol('INITIAL_VALUE'); /** * @return {?} */ function prioritizedGuardValue() { return switchMap((/** * @param {?} obs * @return {?} */ obs => { return (/** @type {?} */ (combineLatest(...obs.map((/** * @param {?} o * @return {?} */ o => o.pipe(take(1), startWith((/** @type {?} */ (INITIAL_VALUE))))))) .pipe(scan((/** * @param {?} acc * @param {?} list * @return {?} */ (acc, list) => { /** @type {?} */ let isPending = false; return list.reduce((/** * @param {?} innerAcc * @param {?} val * @param {?} i * @return {?} */ (innerAcc, val, i) => { if (innerAcc !== INITIAL_VALUE) return innerAcc; // Toggle pending flag if any values haven't been set yet if (val === INITIAL_VALUE) isPending = true; // Any other return values are only valid if we haven't yet hit a pending // call. This guarantees that in the case of a guard at the bottom of the // tree that returns a redirect, we will wait for the higher priority // guard at the top to finish before performing the redirect. if (!isPending) { // Early return when we hit a `false` value as that should always // cancel navigation if (val === false) return val; if (i === list.length - 1 || isUrlTree(val)) { return val; } } return innerAcc; }), acc); }), INITIAL_VALUE), filter((/** * @param {?} item * @return {?} */ item => item !== INITIAL_VALUE)), map((/** * @param {?} item * @return {?} */ item => isUrlTree(item) ? item : item === true)), // take(1)))); })); } /** * @fileoverview added by tsickle * Generated from: packages/router/src/operators/check_guards.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @param {?} moduleInjector * @param {?=} forwardEvent * @return {?} */ function checkGuards(moduleInjector, forwardEvent) { return (/** * @param {?} source * @return {?} */ function (source) { return source.pipe(mergeMap((/** * @param {?} t * @return {?} */ t => { const { targetSnapshot, currentSnapshot, guards: { canActivateChecks, canDeactivateChecks } } = t; if (canDeactivateChecks.length === 0 && canActivateChecks.length === 0) { return of(Object.assign(Object.assign({}, t), { guardsResult: true })); } return runCanDeactivateChecks(canDeactivateChecks, (/** @type {?} */ (targetSnapshot)), currentSnapshot, moduleInjector) .pipe(mergeMap((/** * @param {?} canDeactivate * @return {?} */ canDeactivate => { return canDeactivate && isBoolean(canDeactivate) ? runCanActivateChecks((/** @type {?} */ (targetSnapshot)), canActivateChecks, moduleInjector, forwardEvent) : of(canDeactivate); })), map((/** * @param {?} guardsResult * @return {?} */ guardsResult => (Object.assign(Object.assign({}, t), { guardsResult }))))); }))); }); } /** * @param {?} checks * @param {?} futureRSS * @param {?} currRSS * @param {?} moduleInjector * @return {?} */ function runCanDeactivateChecks(checks, futureRSS, currRSS, moduleInjector) { return from(checks).pipe(mergeMap((/** * @param {?} check * @return {?} */ check => runCanDeactivate(check.component, check.route, currRSS, futureRSS, moduleInjector))), first((/** * @param {?} result * @return {?} */ result => { return result !== true; }), (/** @type {?} */ (true)))); } /** * @param {?} futureSnapshot * @param {?} checks * @param {?} moduleInjector * @param {?=} forwardEvent * @return {?} */ function runCanActivateChecks(futureSnapshot, checks, moduleInjector, forwardEvent) { return from(checks).pipe(concatMap((/** * @param {?} check * @return {?} */ (check) => { return from([ fireChildActivationStart(check.route.parent, forwardEvent), fireActivationStart(check.route, forwardEvent), runCanActivateChild(futureSnapshot, check.path, moduleInjector), runCanActivate(futureSnapshot, check.route, moduleInjector) ]) .pipe(concatAll(), first((/** * @param {?} result * @return {?} */ result => { return result !== true; }), (/** @type {?} */ (true)))); })), first((/** * @param {?} result * @return {?} */ result => { return result !== true; }), (/** @type {?} */ (true)))); } /** * This should fire off `ActivationStart` events for each route being activated at this * level. * In other words, if you're activating `a` and `b` below, `path` will contain the * `ActivatedRouteSnapshot`s for both and we will fire `ActivationStart` for both. Always * return * `true` so checks continue to run. * @param {?} snapshot * @param {?=} forwardEvent * @return {?} */ function fireActivationStart(snapshot, forwardEvent) { if (snapshot !== null && forwardEvent) { forwardEvent(new ActivationStart(snapshot)); } return of(true); } /** * This should fire off `ChildActivationStart` events for each route being activated at this * level. * In other words, if you're activating `a` and `b` below, `path` will contain the * `ActivatedRouteSnapshot`s for both and we will fire `ChildActivationStart` for both. Always * return * `true` so checks continue to run. * @param {?} snapshot * @param {?=} forwardEvent * @return {?} */ function fireChildActivationStart(snapshot, forwardEvent) { if (snapshot !== null && forwardEvent) { forwardEvent(new ChildActivationStart(snapshot)); } return of(true); } /** * @param {?} futureRSS * @param {?} futureARS * @param {?} moduleInjector * @return {?} */ function runCanActivate(futureRSS, futureARS, moduleInjector) { /** @type {?} */ const canActivate = futureARS.routeConfig ? futureARS.routeConfig.canActivate : null; if (!canActivate || canActivate.length === 0) return of(true); /** @type {?} */ const canActivateObservables = canActivate.map((/** * @param {?} c * @return {?} */ (c) => { return defer((/** * @return {?} */ () => { /** @type {?} */ const guard = getToken(c, futureARS, moduleInjector); /** @type {?} */ let observable; if (isCanActivate(guard)) { observable = wrapIntoObservable(guard.canActivate(futureARS, futureRSS)); } else if (isFunction(guard)) { observable = wrapIntoObservable(guard(futureARS, futureRSS)); } else { throw new Error('Invalid CanActivate guard'); } return observable.pipe(first()); })); })); return of(canActivateObservables).pipe(prioritizedGuardValue()); } /** * @param {?} futureRSS * @param {?} path * @param {?} moduleInjector * @return {?} */ function runCanActivateChild(futureRSS, path, moduleInjector) { /** @type {?} */ const futureARS = path[path.length - 1]; /** @type {?} */ const canActivateChildGuards = path.slice(0, path.length - 1) .reverse() .map((/** * @param {?} p * @return {?} */ p => getCanActivateChild(p))) .filter((/** * @param {?} _ * @return {?} */ _ => _ !== null)); /** @type {?} */ const canActivateChildGuardsMapped = canActivateChildGuards.map((/** * @param {?} d * @return {?} */ (d) => { return defer((/** * @return {?} */ () => { /** @type {?} */ const guardsMapped = d.guards.map((/** * @param {?} c * @return {?} */ (c) => { /** @type {?} */ const guard = getToken(c, d.node, moduleInjector); /** @type {?} */ let observable; if (isCanActivateChild(guard)) { observable = wrapIntoObservable(guard.canActivateChild(futureARS, futureRSS)); } else if (isFunction(guard)) { observable = wrapIntoObservable(guard(futureARS, futureRSS)); } else { throw new Error('Invalid CanActivateChild guard'); } return observable.pipe(first()); })); return of(guardsMapped).pipe(prioritizedGuardValue()); })); })); return of(canActivateChildGuardsMapped).pipe(prioritizedGuardValue()); } /** * @param {?} component * @param {?} currARS * @param {?} currRSS * @param {?} futureRSS * @param {?} moduleInjector * @return {?} */ function runCanDeactivate(component, currARS, currRSS, futureRSS, moduleInjector) { /** @type {?} */ const canDeactivate = currARS && currARS.routeConfig ? currARS.routeConfig.canDeactivate : null; if (!canDeactivate || canDeactivate.length === 0) return of(true); /** @type {?} */ const canDeactivateObservables = canDeactivate.map((/** * @param {?} c * @return {?} */ (c) => { /** @type {?} */ const guard = getToken(c, currARS, moduleInjector); /** @type {?} */ let observable; if (isCanDeactivate(guard)) { observable = wrapIntoObservable(guard.canDeactivate((/** @type {?} */ (component)), currARS, currRSS, futureRSS)); } else if (isFunction(guard)) { observable = wrapIntoObservable(guard(component, currARS, currRSS, futureRSS)); } else { throw new Error('Invalid CanDeactivate guard'); } return observable.pipe(first()); })); return of(canDeactivateObservables).pipe(prioritizedGuardValue()); } /** * @fileoverview added by tsickle * Generated from: packages/router/src/recognize.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ class NoMatch$1 { } /** * @param {?} rootComponentType * @param {?} config * @param {?} urlTree * @param {?} url * @param {?=} paramsInheritanceStrategy * @param {?=} relativeLinkResolution * @return {?} */ function recognize(rootComponentType, config, urlTree, url, paramsInheritanceStrategy = 'emptyOnly', relativeLinkResolution = 'legacy') { return new Recognizer(rootComponentType, config, urlTree, url, paramsInheritanceStrategy, relativeLinkResolution) .recognize(); } class Recognizer { /** * @param {?} rootComponentType * @param {?} config * @param {?} urlTree * @param {?} url * @param {?} paramsInheritanceStrategy * @param {?} relativeLinkResolution */ constructor(rootComponentType, config, urlTree, url, paramsInheritanceStrategy, relativeLinkResolution) { this.rootComponentType = rootComponentType; this.config = config; this.urlTree = urlTree; this.url = url; this.paramsInheritanceStrategy = paramsInheritanceStrategy; this.relativeLinkResolution = relativeLinkResolution; } /** * @return {?} */ recognize() { try { /** @type {?} */ const rootSegmentGroup = split$1(this.urlTree.root, [], [], this.config, this.relativeLinkResolution).segmentGroup; /** @type {?} */ const children = this.processSegmentGroup(this.config, rootSegmentGroup, PRIMARY_OUTLET); /** @type {?} */ const root = new ActivatedRouteSnapshot([], Object.freeze({}), Object.freeze(Object.assign({}, this.urlTree.queryParams)), (/** @type {?} */ (this.urlTree.fragment)), {}, PRIMARY_OUTLET, this.rootComponentType, null, this.urlTree.root, -1, {}); /** @type {?} */ const rootNode = new TreeNode(root, children); /** @type {?} */ const routeState = new RouterStateSnapshot(this.url, rootNode); this.inheritParamsAndData(routeState._root); return of(routeState); } catch (e) { return new Observable((/** * @param {?} obs * @return {?} */ (obs) => obs.error(e))); } } /** * @param {?} routeNode * @return {?} */ inheritParamsAndData(routeNode) { /** @type {?} */ const route = routeNode.value; /** @type {?} */ const i = inheritedParamsDataResolve(route, this.paramsInheritanceStrategy); route.params = Object.freeze(i.params); route.data = Object.freeze(i.data); routeNode.children.forEach((/** * @param {?} n * @return {?} */ n => this.inheritParamsAndData(n))); } /** * @param {?} config * @param {?} segmentGroup * @param {?} outlet * @return {?} */ processSegmentGroup(config, segmentGroup, outlet) { if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) { return this.processChildren(config, segmentGroup); } return this.processSegment(config, segmentGroup, segmentGroup.segments, outlet); } /** * @param {?} config * @param {?} segmentGroup * @return {?} */ processChildren(config, segmentGroup) { /** @type {?} */ const children = mapChildrenIntoArray(segmentGroup, (/** * @param {?} child * @param {?} childOutlet * @return {?} */ (child, childOutlet) => this.processSegmentGroup(config, child, childOutlet))); checkOutletNameUniqueness(children); sortActivatedRouteSnapshots(children); return children; } /** * @param {?} config * @param {?} segmentGroup * @param {?} segments * @param {?} outlet * @return {?} */ processSegment(config, segmentGroup, segments, outlet) { for (const r of config) { try { return this.processSegmentAgainstRoute(r, segmentGroup, segments, outlet); } catch (e) { if (!(e instanceof NoMatch$1)) throw e; } } if (this.noLeftoversInUrl(segmentGroup, segments, outlet)) { return []; } throw new NoMatch$1(); } /** * @private * @param {?} segmentGroup * @param {?} segments * @param {?} outlet * @return {?} */ noLeftoversInUrl(segmentGroup, segments, outlet) { return segments.length === 0 && !segmentGroup.children[outlet]; } /** * @param {?} route * @param {?} rawSegment * @param {?} segments * @param {?} outlet * @return {?} */ processSegmentAgainstRoute(route, rawSegment, segments, outlet) { if (route.redirectTo) throw new NoMatch$1(); if ((route.outlet || PRIMARY_OUTLET) !== outlet) throw new NoMatch$1(); /** @type {?} */ let snapshot; /** @type {?} */ let consumedSegments = []; /** @type {?} */ let rawSlicedSegments = []; if (route.path === '**') { /** @type {?} */ const params = segments.length > 0 ? (/** @type {?} */ (last(segments))).parameters : {}; snapshot = new ActivatedRouteSnapshot(segments, params, Object.freeze(Object.assign({}, this.urlTree.queryParams)), (/** @type {?} */ (this.urlTree.fragment)), getData(route), outlet, (/** @type {?} */ (route.component)), route, getSourceSegmentGroup(rawSegment), getPathIndexShift(rawSegment) + segments.length, getResolve(route)); } else { /** @type {?} */ const result = match$1(rawSegment, route, segments); consumedSegments = result.consumedSegments; rawSlicedSegments = segments.slice(result.lastChild); snapshot = new ActivatedRouteSnapshot(consumedSegments, result.parameters, Object.freeze(Object.assign({}, this.urlTree.queryParams)), (/** @type {?} */ (this.urlTree.fragment)), getData(route), outlet, (/** @type {?} */ (route.component)), route, getSourceSegmentGroup(rawSegment), getPathIndexShift(rawSegment) + consumedSegments.length, getResolve(route)); } /** @type {?} */ const childConfig = getChildConfig(route); const { segmentGroup, slicedSegments } = split$1(rawSegment, consumedSegments, rawSlicedSegments, childConfig, this.relativeLinkResolution); if (slicedSegments.length === 0 && segmentGroup.hasChildren()) { /** @type {?} */ const children = this.processChildren(childConfig, segmentGroup); return [new TreeNode(snapshot, children)]; } if (childConfig.length === 0 && slicedSegments.length === 0) { return [new TreeNode(snapshot, [])]; } /** @type {?} */ const children = this.processSegment(childConfig, segmentGroup, slicedSegments, PRIMARY_OUTLET); return [new TreeNode(snapshot, children)]; } } if (false) { /** * @type {?} * @private */ Recognizer.prototype.rootComponentType; /** * @type {?} * @private */ Recognizer.prototype.config; /** * @type {?} * @private */ Recognizer.prototype.urlTree; /** * @type {?} * @private */ Recognizer.prototype.url; /** * @type {?} * @private */ Recognizer.prototype.paramsInheritanceStrategy; /** * @type {?} * @private */ Recognizer.prototype.relativeLinkResolution; } /** * @param {?} nodes * @return {?} */ function sortActivatedRouteSnapshots(nodes) { nodes.sort((/** * @param {?} a * @param {?} b * @return {?} */ (a, b) => { if (a.value.outlet === PRIMARY_OUTLET) return -1; if (b.value.outlet === PRIMARY_OUTLET) return 1; return a.value.outlet.localeCompare(b.value.outlet); })); } /** * @param {?} route * @return {?} */ function getChildConfig(route) { if (route.children) { return route.children; } if (route.loadChildren) { return (/** @type {?} */ (route._loadedConfig)).routes; } return []; } /** * @record */ function MatchResult() { } if (false) { /** @type {?} */ MatchResult.prototype.consumedSegments; /** @type {?} */ MatchResult.prototype.lastChild; /** @type {?} */ MatchResult.prototype.parameters; } /** * @param {?} segmentGroup * @param {?} route * @param {?} segments * @return {?} */ function match$1(segmentGroup, route, segments) { if (route.path === '') { if (route.pathMatch === 'full' && (segmentGroup.hasChildren() || segments.length > 0)) { throw new NoMatch$1(); } return { consumedSegments: [], lastChild: 0, parameters: {} }; } /** @type {?} */ const matcher = route.matcher || defaultUrlMatcher; /** @type {?} */ const res = matcher(segments, segmentGroup, route); if (!res) throw new NoMatch$1(); /** @type {?} */ const posParams = {}; forEach((/** @type {?} */ (res.posParams)), (/** * @param {?} v * @param {?} k * @return {?} */ (v, k) => { posParams[k] = v.path; })); /** @type {?} */ const parameters = res.consumed.length > 0 ? Object.assign(Object.assign({}, posParams), res.consumed[res.consumed.length - 1].parameters) : posParams; return { consumedSegments: res.consumed, lastChild: res.consumed.length, parameters }; } /** * @param {?} nodes * @return {?} */ function checkOutletNameUniqueness(nodes) { /** @type {?} */ const names = {}; nodes.forEach((/** * @param {?} n * @return {?} */ n => { /** @type {?} */ const routeWithSameOutletName = names[n.value.outlet]; if (routeWithSameOutletName) { /** @type {?} */ const p = routeWithSameOutletName.url.map((/** * @param {?} s * @return {?} */ s => s.toString())).join('/'); /** @type {?} */ const c = n.value.url.map((/** * @param {?} s * @return {?} */ s => s.toString())).join('/'); throw new Error(`Two segments cannot have the same outlet name: '${p}' and '${c}'.`); } names[n.value.outlet] = n.value; })); } /** * @param {?} segmentGroup * @return {?} */ function getSourceSegmentGroup(segmentGroup) { /** @type {?} */ let s = segmentGroup; while (s._sourceSegment) { s = s._sourceSegment; } return s; } /** * @param {?} segmentGroup * @return {?} */ function getPathIndexShift(segmentGroup) { /** @type {?} */ let s = segmentGroup; /** @type {?} */ let res = (s._segmentIndexShift ? s._segmentIndexShift : 0); while (s._sourceSegment) { s = s._sourceSegment; res += (s._segmentIndexShift ? s._segmentIndexShift : 0); } return res - 1; } /** * @param {?} segmentGroup * @param {?} consumedSegments * @param {?} slicedSegments * @param {?} config * @param {?} relativeLinkResolution * @return {?} */ function split$1(segmentGroup, consumedSegments, slicedSegments, config, relativeLinkResolution) { if (slicedSegments.length > 0 && containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, config)) { /** @type {?} */ const s = new UrlSegmentGroup(consumedSegments, createChildrenForEmptyPaths(segmentGroup, consumedSegments, config, new UrlSegmentGroup(slicedSegments, segmentGroup.children))); s._sourceSegment = segmentGroup; s._segmentIndexShift = consumedSegments.length; return { segmentGroup: s, slicedSegments: [] }; } if (slicedSegments.length === 0 && containsEmptyPathMatches(segmentGroup, slicedSegments, config)) { /** @type {?} */ const s = new UrlSegmentGroup(segmentGroup.segments, addEmptyPathsToChildrenIfNeeded(segmentGroup, consumedSegments, slicedSegments, config, segmentGroup.children, relativeLinkResolution)); s._sourceSegment = segmentGroup; s._segmentIndexShift = consumedSegments.length; return { segmentGroup: s, slicedSegments }; } /** @type {?} */ const s = new UrlSegmentGroup(segmentGroup.segments, segmentGroup.children); s._sourceSegment = segmentGroup; s._segmentIndexShift = consumedSegments.length; return { segmentGroup: s, slicedSegments }; } /** * @param {?} segmentGroup * @param {?} consumedSegments * @param {?} slicedSegments * @param {?} routes * @param {?} children * @param {?} relativeLinkResolution * @return {?} */ function addEmptyPathsToChildrenIfNeeded(segmentGroup, consumedSegments, slicedSegments, routes, children, relativeLinkResolution) { /** @type {?} */ const res = {}; for (const r of routes) { if (emptyPathMatch(segmentGroup, slicedSegments, r) && !children[getOutlet$1(r)]) { /** @type {?} */ const s = new UrlSegmentGroup([], {}); s._sourceSegment = segmentGroup; if (relativeLinkResolution === 'legacy') { s._segmentIndexShift = segmentGroup.segments.length; } else { s._segmentIndexShift = consumedSegments.length; } res[getOutlet$1(r)] = s; } } return Object.assign(Object.assign({}, children), res); } /** * @param {?} segmentGroup * @param {?} consumedSegments * @param {?} routes * @param {?} primarySegment * @return {?} */ function createChildrenForEmptyPaths(segmentGroup, consumedSegments, routes, primarySegment) { /** @type {?} */ const res = {}; res[PRIMARY_OUTLET] = primarySegment; primarySegment._sourceSegment = segmentGroup; primarySegment._segmentIndexShift = consumedSegments.length; for (const r of routes) { if (r.path === '' && getOutlet$1(r) !== PRIMARY_OUTLET) { /** @type {?} */ const s = new UrlSegmentGroup([], {}); s._sourceSegment = segmentGroup; s._segmentIndexShift = consumedSegments.length; res[getOutlet$1(r)] = s; } } return res; } /** * @param {?} segmentGroup * @param {?} slicedSegments * @param {?} routes * @return {?} */ function containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, routes) { return routes.some((/** * @param {?} r * @return {?} */ r => emptyPathMatch(segmentGroup, slicedSegments, r) && getOutlet$1(r) !== PRIMARY_OUTLET)); } /** * @param {?} segmentGroup * @param {?} slicedSegments * @param {?} routes * @return {?} */ function containsEmptyPathMatches(segmentGroup, slicedSegments, routes) { return routes.some((/** * @param {?} r * @return {?} */ r => emptyPathMatch(segmentGroup, slicedSegments, r))); } /** * @param {?} segmentGroup * @param {?} slicedSegments * @param {?} r * @return {?} */ function emptyPathMatch(segmentGroup, slicedSegments, r) { if ((segmentGroup.hasChildren() || slicedSegments.length > 0) && r.pathMatch === 'full') { return false; } return r.path === '' && r.redirectTo === undefined; } /** * @param {?} route * @return {?} */ function getOutlet$1(route) { return route.outlet || PRIMARY_OUTLET; } /** * @param {?} route * @return {?} */ function getData(route) { return route.data || {}; } /** * @param {?} route * @return {?} */ function getResolve(route) { return route.resolve || {}; } /** * @fileoverview added by tsickle * Generated from: packages/router/src/operators/recognize.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @param {?} rootComponentType * @param {?} config * @param {?} serializer * @param {?} paramsInheritanceStrategy * @param {?} relativeLinkResolution * @return {?} */ function recognize$1(rootComponentType, config, serializer, paramsInheritanceStrategy, relativeLinkResolution) { return (/** * @param {?} source * @return {?} */ function (source) { return source.pipe(mergeMap((/** * @param {?} t * @return {?} */ t => recognize(rootComponentType, config, t.urlAfterRedirects, serializer(t.urlAfterRedirects), paramsInheritanceStrategy, relativeLinkResolution) .pipe(map((/** * @param {?} targetSnapshot * @return {?} */ targetSnapshot => (Object.assign(Object.assign({}, t), { targetSnapshot })))))))); }); } /** * @fileoverview added by tsickle * Generated from: packages/router/src/operators/resolve_data.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @param {?} paramsInheritanceStrategy * @param {?} moduleInjector * @return {?} */ function resolveData(paramsInheritanceStrategy, moduleInjector) { return (/** * @param {?} source * @return {?} */ function (source) { return source.pipe(mergeMap((/** * @param {?} t * @return {?} */ t => { const { targetSnapshot, guards: { canActivateChecks } } = t; if (!canActivateChecks.length) { return of(t); } return from(canActivateChecks) .pipe(concatMap((/** * @param {?} check * @return {?} */ check => runResolve(check.route, (/** @type {?} */ (targetSnapshot)), paramsInheritanceStrategy, moduleInjector))), reduce((/** * @param {?} _ * @param {?} __ * @return {?} */ (_, __) => _)), map((/** * @param {?} _ * @return {?} */ _ => t))); }))); }); } /** * @param {?} futureARS * @param {?} futureRSS * @param {?} paramsInheritanceStrategy * @param {?} moduleInjector * @return {?} */ function runResolve(futureARS, futureRSS, paramsInheritanceStrategy, moduleInjector) { /** @type {?} */ const resolve = futureARS._resolve; return resolveNode(resolve, futureARS, futureRSS, moduleInjector) .pipe(map((/** * @param {?} resolvedData * @return {?} */ (resolvedData) => { futureARS._resolvedData = resolvedData; futureARS.data = Object.assign(Object.assign({}, futureARS.data), inheritedParamsDataResolve(futureARS, paramsInheritanceStrategy).resolve); return null; }))); } /** * @param {?} resolve * @param {?} futureARS * @param {?} futureRSS * @param {?} moduleInjector * @return {?} */ function resolveNode(resolve, futureARS, futureRSS, moduleInjector) { /** @type {?} */ const keys = Object.keys(resolve); if (keys.length === 0) { return of({}); } if (keys.length === 1) { /** @type {?} */ const key = keys[0]; return getResolver(resolve[key], futureARS, futureRSS, moduleInjector) .pipe(map((/** * @param {?} value * @return {?} */ (value) => { return { [key]: value }; }))); } /** @type {?} */ const data = {}; /** @type {?} */ const runningResolvers$ = from(keys).pipe(mergeMap((/** * @param {?} key * @return {?} */ (key) => { return getResolver(resolve[key], futureARS, futureRSS, moduleInjector) .pipe(map((/** * @param {?} value * @return {?} */ (value) => { data[key] = value; return value; }))); }))); return runningResolvers$.pipe(last$1(), map((/** * @return {?} */ () => data))); } /** * @param {?} injectionToken * @param {?} futureARS * @param {?} futureRSS * @param {?} moduleInjector * @return {?} */ function getResolver(injectionToken, futureARS, futureRSS, moduleInjector) { /** @type {?} */ const resolver = getToken(injectionToken, futureARS, moduleInjector); return resolver.resolve ? wrapIntoObservable(resolver.resolve(futureARS, futureRSS)) : wrapIntoObservable(resolver(futureARS, futureRSS)); } /** * @fileoverview added by tsickle * Generated from: packages/router/src/operators/switch_tap.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Perform a side effect through a switchMap for every emission on the source Observable, * but return an Observable that is identical to the source. It's essentially the same as * the `tap` operator, but if the side effectful `next` function returns an ObservableInput, * it will wait before continuing with the original value. * @template T * @param {?} next * @return {?} */ function switchTap(next) { return (/** * @param {?} source * @return {?} */ function (source) { return source.pipe(switchMap((/** * @param {?} v * @return {?} */ v => { /** @type {?} */ const nextResult = next(v); if (nextResult) { return from(nextResult).pipe(map((/** * @return {?} */ () => v))); } return from([v]); }))); }); } /** * @fileoverview added by tsickle * Generated from: packages/router/src/route_reuse_strategy.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * \@description * * Provides a way to customize when activated routes get reused. * * \@publicApi * @abstract */ class RouteReuseStrategy { } if (false) { /** * Determines if this route (and its subtree) should be detached to be reused later * @abstract * @param {?} route * @return {?} */ RouteReuseStrategy.prototype.shouldDetach = function (route) { }; /** * Stores the detached route. * * Storing a `null` value should erase the previously stored value. * @abstract * @param {?} route * @param {?} handle * @return {?} */ RouteReuseStrategy.prototype.store = function (route, handle) { }; /** * Determines if this route (and its subtree) should be reattached * @abstract * @param {?} route * @return {?} */ RouteReuseStrategy.prototype.shouldAttach = function (route) { }; /** * Retrieves the previously stored route * @abstract * @param {?} route * @return {?} */ RouteReuseStrategy.prototype.retrieve = function (route) { }; /** * Determines if a route should be reused * @abstract * @param {?} future * @param {?} curr * @return {?} */ RouteReuseStrategy.prototype.shouldReuseRoute = function (future, curr) { }; } /** * Does not detach any subtrees. Reuses routes as long as their route config is the same. */ class DefaultRouteReuseStrategy { /** * @param {?} route * @return {?} */ shouldDetach(route) { return false; } /** * @param {?} route * @param {?} detachedTree * @return {?} */ store(route, detachedTree) { } /** * @param {?} route * @return {?} */ shouldAttach(route) { return false; } /** * @param {?} route * @return {?} */ retrieve(route) { return null; } /** * @param {?} future * @param {?} curr * @return {?} */ shouldReuseRoute(future, curr) { return future.routeConfig === curr.routeConfig; } } /** * @fileoverview added by tsickle * Generated from: packages/router/src/router_config_loader.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * The [DI token](guide/glossary/#di-token) for a router configuration. * @see `ROUTES` * \@publicApi * @type {?} */ const ROUTES = new InjectionToken('ROUTES'); class RouterConfigLoader { /** * @param {?} loader * @param {?} compiler * @param {?=} onLoadStartListener * @param {?=} onLoadEndListener */ constructor(loader, compiler, onLoadStartListener, onLoadEndListener) { this.loader = loader; this.compiler = compiler; this.onLoadStartListener = onLoadStartListener; this.onLoadEndListener = onLoadEndListener; } /** * @param {?} parentInjector * @param {?} route * @return {?} */ load(parentInjector, route) { if (this.onLoadStartListener) { this.onLoadStartListener(route); } /** @type {?} */ const moduleFactory$ = this.loadModuleFactory((/** @type {?} */ (route.loadChildren))); return moduleFactory$.pipe(map((/** * @param {?} factory * @return {?} */ (factory) => { if (this.onLoadEndListener) { this.onLoadEndListener(route); } /** @type {?} */ const module = factory.create(parentInjector); return new LoadedRouterConfig(flatten(module.injector.get(ROUTES)).map(standardizeConfig), module); }))); } /** * @private * @param {?} loadChildren * @return {?} */ loadModuleFactory(loadChildren) { if (typeof loadChildren === 'string') { return from(this.loader.load(loadChildren)); } else { return wrapIntoObservable(loadChildren()).pipe(mergeMap((/** * @param {?} t * @return {?} */ (t) => { if (t instanceof NgModuleFactory) { return of(t); } else { return from(this.compiler.compileModuleAsync(t)); } }))); } } } if (false) { /** * @type {?} * @private */ RouterConfigLoader.prototype.loader; /** * @type {?} * @private */ RouterConfigLoader.prototype.compiler; /** * @type {?} * @private */ RouterConfigLoader.prototype.onLoadStartListener; /** * @type {?} * @private */ RouterConfigLoader.prototype.onLoadEndListener; } /** * @fileoverview added by tsickle * Generated from: packages/router/src/url_handling_strategy.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * \@description * * Provides a way to migrate AngularJS applications to Angular. * * \@publicApi * @abstract */ class UrlHandlingStrategy { } if (false) { /** * Tells the router if this URL should be processed. * * When it returns true, the router will execute the regular navigation. * When it returns false, the router will set the router state to an empty state. * As a result, all the active components will be destroyed. * * @abstract * @param {?} url * @return {?} */ UrlHandlingStrategy.prototype.shouldProcessUrl = function (url) { }; /** * Extracts the part of the URL that should be handled by the router. * The rest of the URL will remain untouched. * @abstract * @param {?} url * @return {?} */ UrlHandlingStrategy.prototype.extract = function (url) { }; /** * Merges the URL fragment with the rest of the URL. * @abstract * @param {?} newUrlPart * @param {?} rawUrl * @return {?} */ UrlHandlingStrategy.prototype.merge = function (newUrlPart, rawUrl) { }; } /** * \@publicApi */ class DefaultUrlHandlingStrategy { /** * @param {?} url * @return {?} */ shouldProcessUrl(url) { return true; } /** * @param {?} url * @return {?} */ extract(url) { return url; } /** * @param {?} newUrlPart * @param {?} wholeUrl * @return {?} */ merge(newUrlPart, wholeUrl) { return newUrlPart; } } /** * @fileoverview added by tsickle * Generated from: packages/router/src/router.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * \@description * * Options that modify the navigation strategy. * * \@publicApi * @record */ function NavigationExtras() { } if (false) { /** * Specifies a root URI to use for relative navigation. * * For example, consider the following route configuration where the parent route * has two children. * * ``` * [{ * path: 'parent', * component: ParentComponent, * children: [{ * path: 'list', * component: ListComponent * },{ * path: 'child', * component: ChildComponent * }] * }] * ``` * * The following `go()` function navigates to the `list` route by * interpreting the destination URI as relative to the activated `child` route * * ``` * \@Component({...}) * class ChildComponent { * constructor(private router: Router, private route: ActivatedRoute) {} * * go() { * this.router.navigate(['../list'], { relativeTo: this.route }); * } * } * ``` * @type {?|undefined} */ NavigationExtras.prototype.relativeTo; /** * Sets query parameters to the URL. * * ``` * // Navigate to /results?page=1 * this.router.navigate(['/results'], { queryParams: { page: 1 } }); * ``` * @type {?|undefined} */ NavigationExtras.prototype.queryParams; /** * Sets the hash fragment for the URL. * * ``` * // Navigate to /results#top * this.router.navigate(['/results'], { fragment: 'top' }); * ``` * @type {?|undefined} */ NavigationExtras.prototype.fragment; /** * **DEPRECATED**: Use `queryParamsHandling: "preserve"` instead to preserve * query parameters for the next navigation. * * @deprecated since v4 * @type {?|undefined} */ NavigationExtras.prototype.preserveQueryParams; /** * How to handle query parameters in the router link for the next navigation. * One of: * * `merge` : Merge new with current parameters. * * `preserve` : Preserve current parameters. * * ``` * // from /results?page=1 to /view?page=1&page=2 * this.router.navigate(['/view'], { queryParams: { page: 2 }, queryParamsHandling: "merge" }); * ``` * @type {?|undefined} */ NavigationExtras.prototype.queryParamsHandling; /** * When true, preserves the URL fragment for the next navigation * * ``` * // Preserve fragment from /results#top to /view#top * this.router.navigate(['/view'], { preserveFragment: true }); * ``` * @type {?|undefined} */ NavigationExtras.prototype.preserveFragment; /** * When true, navigates without pushing a new state into history. * * ``` * // Navigate silently to /view * this.router.navigate(['/view'], { skipLocationChange: true }); * ``` * @type {?|undefined} */ NavigationExtras.prototype.skipLocationChange; /** * When true, navigates while replacing the current state in history. * * ``` * // Navigate to /view * this.router.navigate(['/view'], { replaceUrl: true }); * ``` * @type {?|undefined} */ NavigationExtras.prototype.replaceUrl; /** * Developer-defined state that can be passed to any navigation. * Access this value through the `Navigation.extras` object * returned from `router.getCurrentNavigation()` while a navigation is executing. * * After a navigation completes, the router writes an object containing this * value together with a `navigationId` to `history.state`. * The value is written when `location.go()` or `location.replaceState()` * is called before activating this route. * * Note that `history.state` does not pass an object equality test because * the router adds the `navigationId` on each navigation. * @type {?|undefined} */ NavigationExtras.prototype.state; } /** * @param {?} error * @return {?} */ function defaultErrorHandler(error) { throw error; } /** * @param {?} error * @param {?} urlSerializer * @param {?} url * @return {?} */ function defaultMalformedUriErrorHandler(error, urlSerializer, url) { return urlSerializer.parse('/'); } /** * \@internal * @param {?} snapshot * @param {?} runExtras * @return {?} */ function defaultRouterHook(snapshot, runExtras) { return (/** @type {?} */ (of(null))); } /** * \@description * * A service that provides navigation and URL manipulation capabilities. * * @see `Route`. * @see [Routing and Navigation Guide](guide/router). * * \@ngModule RouterModule * * \@publicApi */ class Router { /** * Creates the router service. * @param {?} rootComponentType * @param {?} urlSerializer * @param {?} rootContexts * @param {?} location * @param {?} injector * @param {?} loader * @param {?} compiler * @param {?} config */ // TODO: vsavkin make internal after the final is out. constructor(rootComponentType, urlSerializer, rootContexts, location, injector, loader, compiler, config) { this.rootComponentType = rootComponentType; this.urlSerializer = urlSerializer; this.rootContexts = rootContexts; this.location = location; this.config = config; this.lastSuccessfulNavigation = null; this.currentNavigation = null; this.navigationId = 0; this.isNgZoneEnabled = false; /** * An event stream for routing events in this NgModule. */ this.events = new Subject(); /** * A handler for navigation errors in this NgModule. */ this.errorHandler = defaultErrorHandler; /** * A handler for errors thrown by `Router.parseUrl(url)` * when `url` contains an invalid character. * The most common case is a `%` sign * that's not encoded and is not part of a percent encoded sequence. */ this.malformedUriErrorHandler = defaultMalformedUriErrorHandler; /** * True if at least one navigation event has occurred, * false otherwise. */ this.navigated = false; this.lastSuccessfulId = -1; /** * Hooks that enable you to pause navigation, * either before or after the preactivation phase. * Used by `RouterModule`. * * \@internal */ this.hooks = { beforePreactivation: defaultRouterHook, afterPreactivation: defaultRouterHook }; /** * A strategy for extracting and merging URLs. * Used for AngularJS to Angular migrations. */ this.urlHandlingStrategy = new DefaultUrlHandlingStrategy(); /** * A strategy for re-using routes. */ this.routeReuseStrategy = new DefaultRouteReuseStrategy(); /** * How to handle a navigation request to the current URL. One of: * - `'ignore'` : The router ignores the request. * - `'reload'` : The router reloads the URL. Use to implement a "refresh" feature. */ this.onSameUrlNavigation = 'ignore'; /** * How to merge parameters, data, and resolved data from parent to child * routes. One of: * * - `'emptyOnly'` : Inherit parent parameters, data, and resolved data * for path-less or component-less routes. * - `'always'` : Inherit parent parameters, data, and resolved data * for all child routes. */ this.paramsInheritanceStrategy = 'emptyOnly'; /** * Determines when the router updates the browser URL. * By default (`"deferred"`), updates the browser URL after navigation has finished. * Set to `'eager'` to update the browser URL at the beginning of navigation. * You can choose to update early so that, if navigation fails, * you can show an error message with the URL that failed. */ this.urlUpdateStrategy = 'deferred'; /** * Enables a bug fix that corrects relative link resolution in components with empty paths. * @see `RouterModule` */ this.relativeLinkResolution = 'legacy'; /** @type {?} */ const onLoadStart = (/** * @param {?} r * @return {?} */ (r) => this.triggerEvent(new RouteConfigLoadStart(r))); /** @type {?} */ const onLoadEnd = (/** * @param {?} r * @return {?} */ (r) => this.triggerEvent(new RouteConfigLoadEnd(r))); this.ngModule = injector.get(NgModuleRef); this.console = injector.get(ɵConsole); /** @type {?} */ const ngZone = injector.get(NgZone); this.isNgZoneEnabled = ngZone instanceof NgZone; this.resetConfig(config); this.currentUrlTree = createEmptyUrlTree(); this.rawUrlTree = this.currentUrlTree; this.browserUrlTree = this.currentUrlTree; this.configLoader = new RouterConfigLoader(loader, compiler, onLoadStart, onLoadEnd); this.routerState = createEmptyState(this.currentUrlTree, this.rootComponentType); this.transitions = new BehaviorSubject({ id: 0, currentUrlTree: this.currentUrlTree, currentRawUrl: this.currentUrlTree, extractedUrl: this.urlHandlingStrategy.extract(this.currentUrlTree), urlAfterRedirects: this.urlHandlingStrategy.extract(this.currentUrlTree), rawUrl: this.currentUrlTree, extras: {}, resolve: null, reject: null, promise: Promise.resolve(true), source: 'imperative', restoredState: null, currentSnapshot: this.routerState.snapshot, targetSnapshot: null, currentRouterState: this.routerState, targetRouterState: null, guards: { canActivateChecks: [], canDeactivateChecks: [] }, guardsResult: null, }); this.navigations = this.setupNavigations(this.transitions); this.processNavigations(); } /** * @private * @param {?} transitions * @return {?} */ setupNavigations(transitions) { /** @type {?} */ const eventsSubject = ((/** @type {?} */ (this.events))); return (/** @type {?} */ ((/** @type {?} */ (transitions.pipe(filter((/** * @param {?} t * @return {?} */ t => t.id !== 0)), // Extract URL map((/** * @param {?} t * @return {?} */ t => ((/** @type {?} */ (Object.assign(Object.assign({}, t), { extractedUrl: this.urlHandlingStrategy.extract(t.rawUrl) })))))), // Using switchMap so we cancel executing navigations when a new one comes in switchMap((/** * @param {?} t * @return {?} */ t => { /** @type {?} */ let completed = false; /** @type {?} */ let errored = false; return of(t).pipe( // Store the Navigation object tap((/** * @param {?} t * @return {?} */ t => { this.currentNavigation = { id: t.id, initialUrl: t.currentRawUrl, extractedUrl: t.extractedUrl, trigger: t.source, extras: t.extras, previousNavigation: this.lastSuccessfulNavigation ? Object.assign(Object.assign({}, this.lastSuccessfulNavigation), { previousNavigation: null }) : null }; })), switchMap((/** * @param {?} t * @return {?} */ t => { /** @type {?} */ const urlTransition = !this.navigated || t.extractedUrl.toString() !== this.browserUrlTree.toString(); /** @type {?} */ const processCurrentUrl = (this.onSameUrlNavigation === 'reload' ? true : urlTransition) && this.urlHandlingStrategy.shouldProcessUrl(t.rawUrl); if (processCurrentUrl) { return of(t).pipe( // Fire NavigationStart event switchMap((/** * @param {?} t * @return {?} */ t => { /** @type {?} */ const transition = this.transitions.getValue(); eventsSubject.next(new NavigationStart(t.id, this.serializeUrl(t.extractedUrl), t.source, t.restoredState)); if (transition !== this.transitions.getValue()) { return EMPTY; } return [t]; })), // This delay is required to match old behavior that forced navigation // to always be async switchMap((/** * @param {?} t * @return {?} */ t => Promise.resolve(t))), // ApplyRedirects applyRedirects$1(this.ngModule.injector, this.configLoader, this.urlSerializer, this.config), // Update the currentNavigation tap((/** * @param {?} t * @return {?} */ t => { this.currentNavigation = Object.assign(Object.assign({}, (/** @type {?} */ (this.currentNavigation))), { finalUrl: t.urlAfterRedirects }); })), // Recognize recognize$1(this.rootComponentType, this.config, (/** * @param {?} url * @return {?} */ (url) => this.serializeUrl(url)), this.paramsInheritanceStrategy, this.relativeLinkResolution), // Update URL if in `eager` update mode tap((/** * @param {?} t * @return {?} */ t => { if (this.urlUpdateStrategy === 'eager') { if (!t.extras.skipLocationChange) { this.setBrowserUrl(t.urlAfterRedirects, !!t.extras.replaceUrl, t.id, t.extras.state); } this.browserUrlTree = t.urlAfterRedirects; } })), // Fire RoutesRecognized tap((/** * @param {?} t * @return {?} */ t => { /** @type {?} */ const routesRecognized = new RoutesRecognized(t.id, this.serializeUrl(t.extractedUrl), this.serializeUrl(t.urlAfterRedirects), (/** @type {?} */ (t.targetSnapshot))); eventsSubject.next(routesRecognized); }))); } else { /** @type {?} */ const processPreviousUrl = urlTransition && this.rawUrlTree && this.urlHandlingStrategy.shouldProcessUrl(this.rawUrlTree); /* When the current URL shouldn't be processed, but the previous one was, * we handle this "error condition" by navigating to the previously * successful URL, but leaving the URL intact.*/ if (processPreviousUrl) { const { id, extractedUrl, source, restoredState, extras } = t; /** @type {?} */ const navStart = new NavigationStart(id, this.serializeUrl(extractedUrl), source, restoredState); eventsSubject.next(navStart); /** @type {?} */ const targetSnapshot = createEmptyState(extractedUrl, this.rootComponentType).snapshot; return of(Object.assign(Object.assign({}, t), { targetSnapshot, urlAfterRedirects: extractedUrl, extras: Object.assign(Object.assign({}, extras), { skipLocationChange: false, replaceUrl: false }) })); } else { /* When neither the current or previous URL can be processed, do nothing * other than update router's internal reference to the current "settled" * URL. This way the next navigation will be coming from the current URL * in the browser. */ this.rawUrlTree = t.rawUrl; this.browserUrlTree = t.urlAfterRedirects; t.resolve(null); return EMPTY; } } })), // Before Preactivation switchTap((/** * @param {?} t * @return {?} */ t => { const { targetSnapshot, id: navigationId, extractedUrl: appliedUrlTree, rawUrl: rawUrlTree, extras: { skipLocationChange, replaceUrl } } = t; return this.hooks.beforePreactivation((/** @type {?} */ (targetSnapshot)), { navigationId, appliedUrlTree, rawUrlTree, skipLocationChange: !!skipLocationChange, replaceUrl: !!replaceUrl, }); })), // --- GUARDS --- tap((/** * @param {?} t * @return {?} */ t => { /** @type {?} */ const guardsStart = new GuardsCheckStart(t.id, this.serializeUrl(t.extractedUrl), this.serializeUrl(t.urlAfterRedirects), (/** @type {?} */ (t.targetSnapshot))); this.triggerEvent(guardsStart); })), map((/** * @param {?} t * @return {?} */ t => (Object.assign(Object.assign({}, t), { guards: getAllRouteGuards((/** @type {?} */ (t.targetSnapshot)), t.currentSnapshot, this.rootContexts) })))), checkGuards(this.ngModule.injector, (/** * @param {?} evt * @return {?} */ (evt) => this.triggerEvent(evt))), tap((/** * @param {?} t * @return {?} */ t => { if (isUrlTree(t.guardsResult)) { /** @type {?} */ const error = navigationCancelingError(`Redirecting to "${this.serializeUrl(t.guardsResult)}"`); error.url = t.guardsResult; throw error; } })), tap((/** * @param {?} t * @return {?} */ t => { /** @type {?} */ const guardsEnd = new GuardsCheckEnd(t.id, this.serializeUrl(t.extractedUrl), this.serializeUrl(t.urlAfterRedirects), (/** @type {?} */ (t.targetSnapshot)), !!t.guardsResult); this.triggerEvent(guardsEnd); })), filter((/** * @param {?} t * @return {?} */ t => { if (!t.guardsResult) { this.resetUrlToCurrentUrlTree(); /** @type {?} */ const navCancel = new NavigationCancel(t.id, this.serializeUrl(t.extractedUrl), ''); eventsSubject.next(navCancel); t.resolve(false); return false; } return true; })), // --- RESOLVE --- switchTap((/** * @param {?} t * @return {?} */ t => { if (t.guards.canActivateChecks.length) { return of(t).pipe(tap((/** * @param {?} t * @return {?} */ t => { /** @type {?} */ const resolveStart = new ResolveStart(t.id, this.serializeUrl(t.extractedUrl), this.serializeUrl(t.urlAfterRedirects), (/** @type {?} */ (t.targetSnapshot))); this.triggerEvent(resolveStart); })), resolveData(this.paramsInheritanceStrategy, this.ngModule.injector), // tap((/** * @param {?} t * @return {?} */ t => { /** @type {?} */ const resolveEnd = new ResolveEnd(t.id, this.serializeUrl(t.extractedUrl), this.serializeUrl(t.urlAfterRedirects), (/** @type {?} */ (t.targetSnapshot))); this.triggerEvent(resolveEnd); }))); } return undefined; })), // --- AFTER PREACTIVATION --- switchTap((/** * @param {?} t * @return {?} */ (t) => { const { targetSnapshot, id: navigationId, extractedUrl: appliedUrlTree, rawUrl: rawUrlTree, extras: { skipLocationChange, replaceUrl } } = t; return this.hooks.afterPreactivation((/** @type {?} */ (targetSnapshot)), { navigationId, appliedUrlTree, rawUrlTree, skipLocationChange: !!skipLocationChange, replaceUrl: !!replaceUrl, }); })), map((/** * @param {?} t * @return {?} */ (t) => { /** @type {?} */ const targetRouterState = createRouterState(this.routeReuseStrategy, (/** @type {?} */ (t.targetSnapshot)), t.currentRouterState); return (Object.assign(Object.assign({}, t), { targetRouterState })); })), /* Once here, we are about to activate syncronously. The assumption is this will succeed, and user code may read from the Router service. Therefore before activation, we need to update router properties storing the current URL and the RouterState, as well as updated the browser URL. All this should happen *before* activating. */ tap((/** * @param {?} t * @return {?} */ (t) => { this.currentUrlTree = t.urlAfterRedirects; this.rawUrlTree = this.urlHandlingStrategy.merge(this.currentUrlTree, t.rawUrl); ((/** @type {?} */ (this))).routerState = (/** @type {?} */ (t.targetRouterState)); if (this.urlUpdateStrategy === 'deferred') { if (!t.extras.skipLocationChange) { this.setBrowserUrl(this.rawUrlTree, !!t.extras.replaceUrl, t.id, t.extras.state); } this.browserUrlTree = t.urlAfterRedirects; } })), activateRoutes(this.rootContexts, this.routeReuseStrategy, (/** * @param {?} evt * @return {?} */ (evt) => this.triggerEvent(evt))), tap({ /** * @return {?} */ next() { completed = true; }, /** * @return {?} */ complete() { completed = true; } }), finalize((/** * @return {?} */ () => { /* When the navigation stream finishes either through error or success, we * set the `completed` or `errored` flag. However, there are some situations * where we could get here without either of those being set. For instance, a * redirect during NavigationStart. Therefore, this is a catch-all to make * sure the NavigationCancel * event is fired when a navigation gets cancelled but not caught by other * means. */ if (!completed && !errored) { // Must reset to current URL tree here to ensure history.state is set. On a // fresh page load, if a new navigation comes in before a successful // navigation completes, there will be nothing in // history.state.navigationId. This can cause sync problems with AngularJS // sync code which looks for a value here in order to determine whether or // not to handle a given popstate event or to leave it to the Angualr // router. this.resetUrlToCurrentUrlTree(); /** @type {?} */ const navCancel = new NavigationCancel(t.id, this.serializeUrl(t.extractedUrl), `Navigation ID ${t.id} is not equal to the current navigation id ${this.navigationId}`); eventsSubject.next(navCancel); t.resolve(false); } // currentNavigation should always be reset to null here. If navigation was // successful, lastSuccessfulTransition will have already been set. Therefore // we can safely set currentNavigation to null here. this.currentNavigation = null; })), catchError((/** * @param {?} e * @return {?} */ (e) => { errored = true; /* This error type is issued during Redirect, and is handled as a * cancellation rather than an error. */ if (isNavigationCancelingError(e)) { /** @type {?} */ const redirecting = isUrlTree(e.url); if (!redirecting) { // Set property only if we're not redirecting. If we landed on a page and // redirect to `/` route, the new navigation is going to see the `/` // isn't a change from the default currentUrlTree and won't navigate. // This is only applicable with initial navigation, so setting // `navigated` only when not redirecting resolves this scenario. this.navigated = true; this.resetStateAndUrl(t.currentRouterState, t.currentUrlTree, t.rawUrl); } /** @type {?} */ const navCancel = new NavigationCancel(t.id, this.serializeUrl(t.extractedUrl), e.message); eventsSubject.next(navCancel); // When redirecting, we need to delay resolving the navigation // promise and push it to the redirect navigation if (!redirecting) { t.resolve(false); } else { // setTimeout is required so this navigation finishes with // the return EMPTY below. If it isn't allowed to finish // processing, there can be multiple navigations to the same // URL. setTimeout((/** * @return {?} */ () => { /** @type {?} */ const mergedTree = this.urlHandlingStrategy.merge(e.url, this.rawUrlTree); /** @type {?} */ const extras = { skipLocationChange: t.extras.skipLocationChange, replaceUrl: this.urlUpdateStrategy === 'eager' }; return this.scheduleNavigation(mergedTree, 'imperative', null, extras, { resolve: t.resolve, reject: t.reject, promise: t.promise }); }), 0); } /* All other errors should reset to the router's internal URL reference to * the pre-error state. */ } else { this.resetStateAndUrl(t.currentRouterState, t.currentUrlTree, t.rawUrl); /** @type {?} */ const navError = new NavigationError(t.id, this.serializeUrl(t.extractedUrl), e); eventsSubject.next(navError); try { t.resolve(this.errorHandler(e)); } catch (ee) { t.reject(ee); } } return EMPTY; }))); // TODO(jasonaden): remove cast once g3 is on updated TypeScript }))))))); } /** * \@internal * TODO: this should be removed once the constructor of the router made internal * @param {?} rootComponentType * @return {?} */ resetRootComponentType(rootComponentType) { this.rootComponentType = rootComponentType; // TODO: vsavkin router 4.0 should make the root component set to null // this will simplify the lifecycle of the router. this.routerState.root.component = this.rootComponentType; } /** * @private * @return {?} */ getTransition() { /** @type {?} */ const transition = this.transitions.value; // This value needs to be set. Other values such as extractedUrl are set on initial navigation // but the urlAfterRedirects may not get set if we aren't processing the new URL *and* not // processing the previous URL. transition.urlAfterRedirects = this.browserUrlTree; return transition; } /** * @private * @param {?} t * @return {?} */ setTransition(t) { this.transitions.next(Object.assign(Object.assign({}, this.getTransition()), t)); } /** * Sets up the location change listener and performs the initial navigation. * @return {?} */ initialNavigation() { this.setUpLocationChangeListener(); if (this.navigationId === 0) { this.navigateByUrl(this.location.path(true), { replaceUrl: true }); } } /** * Sets up the location change listener. * @return {?} */ setUpLocationChangeListener() { // Don't need to use Zone.wrap any more, because zone.js // already patch onPopState, so location change callback will // run into ngZone if (!this.locationSubscription) { this.locationSubscription = (/** @type {?} */ (this.location.subscribe((/** * @param {?} change * @return {?} */ (change) => { /** @type {?} */ let rawUrlTree = this.parseUrl(change['url']); /** @type {?} */ const source = change['type'] === 'popstate' ? 'popstate' : 'hashchange'; // Navigations coming from Angular router have a navigationId state property. When this // exists, restore the state. /** @type {?} */ const state = change.state && change.state.navigationId ? change.state : null; setTimeout((/** * @return {?} */ () => { this.scheduleNavigation(rawUrlTree, source, state, { replaceUrl: true }); }), 0); })))); } } /** * The current URL. * @return {?} */ get url() { return this.serializeUrl(this.currentUrlTree); } /** * The current Navigation object if one exists * @return {?} */ getCurrentNavigation() { return this.currentNavigation; } /** * \@internal * @param {?} event * @return {?} */ triggerEvent(event) { ((/** @type {?} */ (this.events))).next(event); } /** * Resets the configuration used for navigation and generating links. * * \@usageNotes * * ``` * router.resetConfig([ * { path: 'team/:id', component: TeamCmp, children: [ * { path: 'simple', component: SimpleCmp }, * { path: 'user/:name', component: UserCmp } * ]} * ]); * ``` * @param {?} config The route array for the new configuration. * * @return {?} */ resetConfig(config) { validateConfig(config); this.config = config.map(standardizeConfig); this.navigated = false; this.lastSuccessfulId = -1; } /** * \@docsNotRequired * @return {?} */ ngOnDestroy() { this.dispose(); } /** * Disposes of the router. * @return {?} */ dispose() { if (this.locationSubscription) { this.locationSubscription.unsubscribe(); this.locationSubscription = (/** @type {?} */ (null)); } } /** * Applies an array of commands to the current URL tree and creates a new URL tree. * * When given an activated route, applies the given commands starting from the route. * Otherwise, applies the given command starting from the root. * * \@usageNotes * * ``` * // create /team/33/user/11 * router.createUrlTree(['/team', 33, 'user', 11]); * * // create /team/33;expand=true/user/11 * router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]); * * // you can collapse static segments like this (this works only with the first passed-in value): * router.createUrlTree(['/team/33/user', userId]); * * // If the first segment can contain slashes, and you do not want the router to split it, * // you can do the following: * router.createUrlTree([{segmentPath: '/one/two'}]); * * // create /team/33/(user/11//right:chat) * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]); * * // remove the right secondary node * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]); * * // assuming the current url is `/team/33/user/11` and the route points to `user/11` * * // navigate to /team/33/user/11/details * router.createUrlTree(['details'], {relativeTo: route}); * * // navigate to /team/33/user/22 * router.createUrlTree(['../22'], {relativeTo: route}); * * // navigate to /team/44/user/22 * router.createUrlTree(['../../team/44/user/22'], {relativeTo: route}); * ``` * @param {?} commands An array of commands to apply. * @param {?=} navigationExtras Options that control the navigation strategy. This function * only utilizes properties in `NavigationExtras` that would change the provided URL. * @return {?} The new URL tree. * */ createUrlTree(commands, navigationExtras = {}) { const { relativeTo, queryParams, fragment, preserveQueryParams, queryParamsHandling, preserveFragment } = navigationExtras; if (isDevMode() && preserveQueryParams && (/** @type {?} */ (console)) && (/** @type {?} */ (console.warn))) { console.warn('preserveQueryParams is deprecated, use queryParamsHandling instead.'); } /** @type {?} */ const a = relativeTo || this.routerState.root; /** @type {?} */ const f = preserveFragment ? this.currentUrlTree.fragment : fragment; /** @type {?} */ let q = null; if (queryParamsHandling) { switch (queryParamsHandling) { case 'merge': q = Object.assign(Object.assign({}, this.currentUrlTree.queryParams), queryParams); break; case 'preserve': q = this.currentUrlTree.queryParams; break; default: q = queryParams || null; } } else { q = preserveQueryParams ? this.currentUrlTree.queryParams : queryParams || null; } if (q !== null) { q = this.removeEmptyProps(q); } return createUrlTree(a, this.currentUrlTree, commands, (/** @type {?} */ (q)), (/** @type {?} */ (f))); } /** * Navigate based on the provided URL, which must be absolute. * * \@usageNotes * * ``` * router.navigateByUrl("/team/33/user/11"); * * // Navigate without updating the URL * router.navigateByUrl("/team/33/user/11", { skipLocationChange: true }); * ``` * * @param {?} url An absolute URL. The function does not apply any delta to the current URL. * @param {?=} extras An object containing properties that modify the navigation strategy. * The function ignores any properties in the `NavigationExtras` that would change the * provided URL. * * @return {?} A Promise that resolves to 'true' when navigation succeeds, * to 'false' when navigation fails, or is rejected on error. * */ navigateByUrl(url, extras = { skipLocationChange: false }) { if (isDevMode() && this.isNgZoneEnabled && !NgZone.isInAngularZone()) { this.console.warn(`Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?`); } /** @type {?} */ const urlTree = isUrlTree(url) ? url : this.parseUrl(url); /** @type {?} */ const mergedTree = this.urlHandlingStrategy.merge(urlTree, this.rawUrlTree); return this.scheduleNavigation(mergedTree, 'imperative', null, extras); } /** * Navigate based on the provided array of commands and a starting point. * If no starting route is provided, the navigation is absolute. * * Returns a promise that: * - resolves to 'true' when navigation succeeds, * - resolves to 'false' when navigation fails, * - is rejected when an error happens. * * \@usageNotes * * ``` * router.navigate(['team', 33, 'user', 11], {relativeTo: route}); * * // Navigate without updating the URL * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true}); * ``` * * The first parameter of `navigate()` is a delta to be applied to the current URL * or the one provided in the `relativeTo` property of the second parameter (the * `NavigationExtras`). * * In order to affect this browser's `history.state` entry, the `state` * parameter can be passed. This must be an object because the router * will add the `navigationId` property to this object before creating * the new history item. * @param {?} commands * @param {?=} extras * @return {?} */ navigate(commands, extras = { skipLocationChange: false }) { validateCommands(commands); return this.navigateByUrl(this.createUrlTree(commands, extras), extras); } /** * Serializes a `UrlTree` into a string * @param {?} url * @return {?} */ serializeUrl(url) { return this.urlSerializer.serialize(url); } /** * Parses a string into a `UrlTree` * @param {?} url * @return {?} */ parseUrl(url) { /** @type {?} */ let urlTree; try { urlTree = this.urlSerializer.parse(url); } catch (e) { urlTree = this.malformedUriErrorHandler(e, this.urlSerializer, url); } return urlTree; } /** * Returns whether the url is activated * @param {?} url * @param {?} exact * @return {?} */ isActive(url, exact) { if (isUrlTree(url)) { return containsTree(this.currentUrlTree, url, exact); } /** @type {?} */ const urlTree = this.parseUrl(url); return containsTree(this.currentUrlTree, urlTree, exact); } /** * @private * @param {?} params * @return {?} */ removeEmptyProps(params) { return Object.keys(params).reduce((/** * @param {?} result * @param {?} key * @return {?} */ (result, key) => { /** @type {?} */ const value = params[key]; if (value !== null && value !== undefined) { result[key] = value; } return result; }), {}); } /** * @private * @return {?} */ processNavigations() { this.navigations.subscribe((/** * @param {?} t * @return {?} */ t => { this.navigated = true; this.lastSuccessfulId = t.id; ((/** @type {?} */ (this.events))) .next(new NavigationEnd(t.id, this.serializeUrl(t.extractedUrl), this.serializeUrl(this.currentUrlTree))); this.lastSuccessfulNavigation = this.currentNavigation; this.currentNavigation = null; t.resolve(true); }), (/** * @param {?} e * @return {?} */ e => { this.console.warn(`Unhandled Navigation Error: `); })); } /** * @private * @param {?} rawUrl * @param {?} source * @param {?} restoredState * @param {?} extras * @param {?=} priorPromise * @return {?} */ scheduleNavigation(rawUrl, source, restoredState, extras, priorPromise) { /** @type {?} */ const lastNavigation = this.getTransition(); // If the user triggers a navigation imperatively (e.g., by using navigateByUrl), // and that navigation results in 'replaceState' that leads to the same URL, // we should skip those. if (lastNavigation && source !== 'imperative' && lastNavigation.source === 'imperative' && lastNavigation.rawUrl.toString() === rawUrl.toString()) { return Promise.resolve(true); // return value is not used } // Because of a bug in IE and Edge, the location class fires two events (popstate and // hashchange) every single time. The second one should be ignored. Otherwise, the URL will // flicker. Handles the case when a popstate was emitted first. if (lastNavigation && source == 'hashchange' && lastNavigation.source === 'popstate' && lastNavigation.rawUrl.toString() === rawUrl.toString()) { return Promise.resolve(true); // return value is not used } // Because of a bug in IE and Edge, the location class fires two events (popstate and // hashchange) every single time. The second one should be ignored. Otherwise, the URL will // flicker. Handles the case when a hashchange was emitted first. if (lastNavigation && source == 'popstate' && lastNavigation.source === 'hashchange' && lastNavigation.rawUrl.toString() === rawUrl.toString()) { return Promise.resolve(true); // return value is not used } /** @type {?} */ let resolve; /** @type {?} */ let reject; /** @type {?} */ let promise; if (priorPromise) { resolve = priorPromise.resolve; reject = priorPromise.reject; promise = priorPromise.promise; } else { promise = new Promise((/** * @param {?} res * @param {?} rej * @return {?} */ (res, rej) => { resolve = res; reject = rej; })); } /** @type {?} */ const id = ++this.navigationId; this.setTransition({ id, source, restoredState, currentUrlTree: this.currentUrlTree, currentRawUrl: this.rawUrlTree, rawUrl, extras, resolve, reject, promise, currentSnapshot: this.routerState.snapshot, currentRouterState: this.routerState }); // Make sure that the error is propagated even though `processNavigations` catch // handler does not rethrow return promise.catch((/** * @param {?} e * @return {?} */ (e) => { return Promise.reject(e); })); } /** * @private * @param {?} url * @param {?} replaceUrl * @param {?} id * @param {?=} state * @return {?} */ setBrowserUrl(url, replaceUrl, id, state) { /** @type {?} */ const path = this.urlSerializer.serialize(url); state = state || {}; if (this.location.isCurrentPathEqualTo(path) || replaceUrl) { // TODO(jasonaden): Remove first `navigationId` and rely on `ng` namespace. this.location.replaceState(path, '', Object.assign(Object.assign({}, state), { navigationId: id })); } else { this.location.go(path, '', Object.assign(Object.assign({}, state), { navigationId: id })); } } /** * @private * @param {?} storedState * @param {?} storedUrl * @param {?} rawUrl * @return {?} */ resetStateAndUrl(storedState, storedUrl, rawUrl) { ((/** @type {?} */ (this))).routerState = storedState; this.currentUrlTree = storedUrl; this.rawUrlTree = this.urlHandlingStrategy.merge(this.currentUrlTree, rawUrl); this.resetUrlToCurrentUrlTree(); } /** * @private * @return {?} */ resetUrlToCurrentUrlTree() { this.location.replaceState(this.urlSerializer.serialize(this.rawUrlTree), '', { navigationId: this.lastSuccessfulId }); } } Router.ɵfac = function Router_Factory(t) { ɵngcc0.ɵɵinvalidFactory(); }; Router.ɵdir = ɵngcc0.ɵɵdefineDirective({ type: Router }); if (false) { /** * @type {?} * @private */ Router.prototype.currentUrlTree; /** * @type {?} * @private */ Router.prototype.rawUrlTree; /** * @type {?} * @private */ Router.prototype.browserUrlTree; /** * @type {?} * @private */ Router.prototype.transitions; /** * @type {?} * @private */ Router.prototype.navigations; /** * @type {?} * @private */ Router.prototype.lastSuccessfulNavigation; /** * @type {?} * @private */ Router.prototype.currentNavigation; /** * @type {?} * @private */ Router.prototype.locationSubscription; /** * @type {?} * @private */ Router.prototype.navigationId; /** * @type {?} * @private */ Router.prototype.configLoader; /** * @type {?} * @private */ Router.prototype.ngModule; /** * @type {?} * @private */ Router.prototype.console; /** * @type {?} * @private */ Router.prototype.isNgZoneEnabled; /** * An event stream for routing events in this NgModule. * @type {?} */ Router.prototype.events; /** * The current state of routing in this NgModule. * @type {?} */ Router.prototype.routerState; /** * A handler for navigation errors in this NgModule. * @type {?} */ Router.prototype.errorHandler; /** * A handler for errors thrown by `Router.parseUrl(url)` * when `url` contains an invalid character. * The most common case is a `%` sign * that's not encoded and is not part of a percent encoded sequence. * @type {?} */ Router.prototype.malformedUriErrorHandler; /** * True if at least one navigation event has occurred, * false otherwise. * @type {?} */ Router.prototype.navigated; /** * @type {?} * @private */ Router.prototype.lastSuccessfulId; /** * Hooks that enable you to pause navigation, * either before or after the preactivation phase. * Used by `RouterModule`. * * \@internal * @type {?} */ Router.prototype.hooks; /** * A strategy for extracting and merging URLs. * Used for AngularJS to Angular migrations. * @type {?} */ Router.prototype.urlHandlingStrategy; /** * A strategy for re-using routes. * @type {?} */ Router.prototype.routeReuseStrategy; /** * How to handle a navigation request to the current URL. One of: * - `'ignore'` : The router ignores the request. * - `'reload'` : The router reloads the URL. Use to implement a "refresh" feature. * @type {?} */ Router.prototype.onSameUrlNavigation; /** * How to merge parameters, data, and resolved data from parent to child * routes. One of: * * - `'emptyOnly'` : Inherit parent parameters, data, and resolved data * for path-less or component-less routes. * - `'always'` : Inherit parent parameters, data, and resolved data * for all child routes. * @type {?} */ Router.prototype.paramsInheritanceStrategy; /** * Determines when the router updates the browser URL. * By default (`"deferred"`), updates the browser URL after navigation has finished. * Set to `'eager'` to update the browser URL at the beginning of navigation. * You can choose to update early so that, if navigation fails, * you can show an error message with the URL that failed. * @type {?} */ Router.prototype.urlUpdateStrategy; /** * Enables a bug fix that corrects relative link resolution in components with empty paths. * @see `RouterModule` * @type {?} */ Router.prototype.relativeLinkResolution; /** * @type {?} * @private */ Router.prototype.rootComponentType; /** * @type {?} * @private */ Router.prototype.urlSerializer; /** * @type {?} * @private */ Router.prototype.rootContexts; /** * @type {?} * @private */ Router.prototype.location; /** @type {?} */ Router.prototype.config; } /** * @param {?} commands * @return {?} */ function validateCommands(commands) { for (let i = 0; i < commands.length; i++) { /** @type {?} */ const cmd = commands[i]; if (cmd == null) { throw new Error(`The requested path contains ${cmd} segment at index ${i}`); } } } /** * @fileoverview added by tsickle * Generated from: packages/router/src/directives/router_link.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * \@description * * Lets you link to specific routes in your app. * * Consider the following route configuration: * `[{ path: 'user/:name', component: UserCmp }]`. * When linking to this `user/:name` route, you use the `RouterLink` directive. * * If the link is static, you can use the directive as follows: * `<a routerLink="/user/bob">link to user component</a>` * * If you use dynamic values to generate the link, you can pass an array of path * segments, followed by the params for each segment. * * For instance `['/team', teamId, 'user', userName, {details: true}]` * means that we want to generate a link to `/team/11/user/bob;details=true`. * * Multiple static segments can be merged into one * (e.g., `['/team/11/user', userName, {details: true}]`). * * The first segment name can be prepended with `/`, `./`, or `../`: * * If the first segment begins with `/`, the router will look up the route from the root of the * app. * * If the first segment begins with `./`, or doesn't begin with a slash, the router will * instead look in the children of the current activated route. * * And if the first segment begins with `../`, the router will go up one level. * * You can set query params and fragment as follows: * * ``` * <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" fragment="education"> * link to user component * </a> * ``` * RouterLink will use these to generate this link: `/user/bob#education?debug=true`. * * (Deprecated in v4.0.0 use `queryParamsHandling` instead) You can also tell the * directive to preserve the current query params and fragment: * * ``` * <a [routerLink]="['/user/bob']" preserveQueryParams preserveFragment> * link to user component * </a> * ``` * * You can tell the directive how to handle queryParams. Available options are: * - `'merge'`: merge the queryParams into the current queryParams * - `'preserve'`: preserve the current queryParams * - default/`''`: use the queryParams only * * Same options for {\@link NavigationExtras#queryParamsHandling * NavigationExtras#queryParamsHandling}. * * ``` * <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" queryParamsHandling="merge"> * link to user component * </a> * ``` * * You can provide a `state` value to be persisted to the browser's History.state * property (See https://developer.mozilla.org/en-US/docs/Web/API/History#Properties). It's * used as follows: * * ``` * <a [routerLink]="['/user/bob']" [state]="{tracingId: 123}"> * link to user component * </a> * ``` * * And later the value can be read from the router through `router.getCurrentNavigation`. * For example, to capture the `tracingId` above during the `NavigationStart` event: * * ``` * // Get NavigationStart events * router.events.pipe(filter(e => e instanceof NavigationStart)).subscribe(e => { * const navigation = router.getCurrentNavigation(); * tracingService.trace({id: navigation.extras.state.tracingId}); * }); * ``` * * The router link directive always treats the provided input as a delta to the current url. * * For instance, if the current url is `/user/(box//aux:team)`. * * Then the following link `<a [routerLink]="['/user/jim']">Jim</a>` will generate the link * `/user/(jim//aux:team)`. * * See {\@link Router#createUrlTree createUrlTree} for more information. * * \@ngModule RouterModule * * \@publicApi */ class RouterLink { /** * @param {?} router * @param {?} route * @param {?} tabIndex * @param {?} renderer * @param {?} el */ constructor(router, route, tabIndex, renderer, el) { this.router = router; this.route = route; this.commands = []; if (tabIndex == null) { renderer.setAttribute(el.nativeElement, 'tabindex', '0'); } } /** * @param {?} commands * @return {?} */ set routerLink(commands) { if (commands != null) { this.commands = Array.isArray(commands) ? commands : [commands]; } else { this.commands = []; } } /** * @deprecated 4.0.0 use `queryParamsHandling` instead. * @param {?} value * @return {?} */ set preserveQueryParams(value) { if (isDevMode() && (/** @type {?} */ (console)) && (/** @type {?} */ (console.warn))) { console.warn('preserveQueryParams is deprecated!, use queryParamsHandling instead.'); } this.preserve = value; } /** * @return {?} */ onClick() { /** @type {?} */ const extras = { skipLocationChange: attrBoolValue(this.skipLocationChange), replaceUrl: attrBoolValue(this.replaceUrl), state: this.state, }; this.router.navigateByUrl(this.urlTree, extras); return true; } /** * @return {?} */ get urlTree() { return this.router.createUrlTree(this.commands, { relativeTo: this.route, queryParams: this.queryParams, fragment: this.fragment, preserveQueryParams: attrBoolValue(this.preserve), queryParamsHandling: this.queryParamsHandling, preserveFragment: attrBoolValue(this.preserveFragment), }); } } RouterLink.ɵfac = function RouterLink_Factory(t) { return new (t || RouterLink)(ɵngcc0.ɵɵdirectiveInject(Router), ɵngcc0.ɵɵdirectiveInject(ActivatedRoute), ɵngcc0.ɵɵinjectAttribute('tabindex'), ɵngcc0.ɵɵdirectiveInject(ɵngcc0.Renderer2), ɵngcc0.ɵɵdirectiveInject(ɵngcc0.ElementRef)); }; RouterLink.ɵdir = ɵngcc0.ɵɵdefineDirective({ type: RouterLink, selectors: [["", "routerLink", "", 5, "a", 5, "area"]], hostBindings: function RouterLink_HostBindings(rf, ctx) { if (rf & 1) { ɵngcc0.ɵɵlistener("click", function RouterLink_click_HostBindingHandler() { return ctx.onClick(); }); } }, inputs: { routerLink: "routerLink", preserveQueryParams: "preserveQueryParams", queryParams: "queryParams", fragment: "fragment", queryParamsHandling: "queryParamsHandling", preserveFragment: "preserveFragment", skipLocationChange: "skipLocationChange", replaceUrl: "replaceUrl", state: "state" } }); /** @nocollapse */ RouterLink.ctorParameters = () => [ { type: Router }, { type: ActivatedRoute }, { type: String, decorators: [{ type: Attribute, args: ['tabindex',] }] }, { type: Renderer2 }, { type: ElementRef } ]; RouterLink.propDecorators = { queryParams: [{ type: Input }], fragment: [{ type: Input }], queryParamsHandling: [{ type: Input }], preserveFragment: [{ type: Input }], skipLocationChange: [{ type: Input }], replaceUrl: [{ type: Input }], state: [{ type: Input }], routerLink: [{ type: Input }], preserveQueryParams: [{ type: Input }], onClick: [{ type: HostListener, args: ['click',] }] }; /*@__PURE__*/ (function () { ɵngcc0.ɵsetClassMetadata(RouterLink, [{ type: Directive, args: [{ selector: ':not(a):not(area)[routerLink]' }] }], function () { return [{ type: Router }, { type: ActivatedRoute }, { type: String, decorators: [{ type: Attribute, args: ['tabindex'] }] }, { type: ɵngcc0.Renderer2 }, { type: ɵngcc0.ElementRef }]; }, { routerLink: [{ type: Input }], preserveQueryParams: [{ type: Input }], onClick: [{ type: HostListener, args: ['click'] }], queryParams: [{ type: Input }], fragment: [{ type: Input }], queryParamsHandling: [{ type: Input }], preserveFragment: [{ type: Input }], skipLocationChange: [{ type: Input }], replaceUrl: [{ type: Input }], state: [{ type: Input }] }); })(); if (false) { /** @type {?} */ RouterLink.prototype.queryParams; /** @type {?} */ RouterLink.prototype.fragment; /** @type {?} */ RouterLink.prototype.queryParamsHandling; /** @type {?} */ RouterLink.prototype.preserveFragment; /** @type {?} */ RouterLink.prototype.skipLocationChange; /** @type {?} */ RouterLink.prototype.replaceUrl; /** @type {?} */ RouterLink.prototype.state; /** * @type {?} * @private */ RouterLink.prototype.commands; /** * @type {?} * @private */ RouterLink.prototype.preserve; /** * @type {?} * @private */ RouterLink.prototype.router; /** * @type {?} * @private */ RouterLink.prototype.route; } /** * \@description * * Lets you link to specific routes in your app. * * See `RouterLink` for more information. * * \@ngModule RouterModule * * \@publicApi */ class RouterLinkWithHref { /** * @param {?} router * @param {?} route * @param {?} locationStrategy */ constructor(router, route, locationStrategy) { this.router = router; this.route = route; this.locationStrategy = locationStrategy; this.commands = []; this.subscription = router.events.subscribe((/** * @param {?} s * @return {?} */ (s) => { if (s instanceof NavigationEnd) { this.updateTargetUrlAndHref(); } })); } /** * @param {?} commands * @return {?} */ set routerLink(commands) { if (commands != null) { this.commands = Array.isArray(commands) ? commands : [commands]; } else { this.commands = []; } } /** * @param {?} value * @return {?} */ set preserveQueryParams(value) { if (isDevMode() && (/** @type {?} */ (console)) && (/** @type {?} */ (console.warn))) { console.warn('preserveQueryParams is deprecated, use queryParamsHandling instead.'); } this.preserve = value; } /** * @param {?} changes * @return {?} */ ngOnChanges(changes) { this.updateTargetUrlAndHref(); } /** * @return {?} */ ngOnDestroy() { this.subscription.unsubscribe(); } /** * @param {?} button * @param {?} ctrlKey * @param {?} metaKey * @param {?} shiftKey * @return {?} */ onClick(button, ctrlKey, metaKey, shiftKey) { if (button !== 0 || ctrlKey || metaKey || shiftKey) { return true; } if (typeof this.target === 'string' && this.target != '_self') { return true; } /** @type {?} */ const extras = { skipLocationChange: attrBoolValue(this.skipLocationChange), replaceUrl: attrBoolValue(this.replaceUrl), state: this.state }; this.router.navigateByUrl(this.urlTree, extras); return false; } /** * @private * @return {?} */ updateTargetUrlAndHref() { this.href = this.locationStrategy.prepareExternalUrl(this.router.serializeUrl(this.urlTree)); } /** * @return {?} */ get urlTree() { return this.router.createUrlTree(this.commands, { relativeTo: this.route, queryParams: this.queryParams, fragment: this.fragment, preserveQueryParams: attrBoolValue(this.preserve), queryParamsHandling: this.queryParamsHandling, preserveFragment: attrBoolValue(this.preserveFragment), }); } } RouterLinkWithHref.ɵfac = function RouterLinkWithHref_Factory(t) { return new (t || RouterLinkWithHref)(ɵngcc0.ɵɵdirectiveInject(Router), ɵngcc0.ɵɵdirectiveInject(ActivatedRoute), ɵngcc0.ɵɵdirectiveInject(ɵngcc1.LocationStrategy)); }; RouterLinkWithHref.ɵdir = ɵngcc0.ɵɵdefineDirective({ type: RouterLinkWithHref, selectors: [["a", "routerLink", ""], ["area", "routerLink", ""]], hostVars: 2, hostBindings: function RouterLinkWithHref_HostBindings(rf, ctx) { if (rf & 1) { ɵngcc0.ɵɵlistener("click", function RouterLinkWithHref_click_HostBindingHandler($event) { return ctx.onClick($event.button, $event.ctrlKey, $event.metaKey, $event.shiftKey); }); } if (rf & 2) { ɵngcc0.ɵɵhostProperty("href", ctx.href, ɵngcc0.ɵɵsanitizeUrl); ɵngcc0.ɵɵattribute("target", ctx.target); } }, inputs: { routerLink: "routerLink", preserveQueryParams: "preserveQueryParams", target: "target", queryParams: "queryParams", fragment: "fragment", queryParamsHandling: "queryParamsHandling", preserveFragment: "preserveFragment", skipLocationChange: "skipLocationChange", replaceUrl: "replaceUrl", state: "state" }, features: [ɵngcc0.ɵɵNgOnChangesFeature] }); /** @nocollapse */ RouterLinkWithHref.ctorParameters = () => [ { type: Router }, { type: ActivatedRoute }, { type: LocationStrategy } ]; RouterLinkWithHref.propDecorators = { target: [{ type: HostBinding, args: ['attr.target',] }, { type: Input }], queryParams: [{ type: Input }], fragment: [{ type: Input }], queryParamsHandling: [{ type: Input }], preserveFragment: [{ type: Input }], skipLocationChange: [{ type: Input }], replaceUrl: [{ type: Input }], state: [{ type: Input }], href: [{ type: HostBinding }], routerLink: [{ type: Input }], preserveQueryParams: [{ type: Input }], onClick: [{ type: HostListener, args: ['click', ['$event.button', '$event.ctrlKey', '$event.metaKey', '$event.shiftKey'],] }] }; /*@__PURE__*/ (function () { ɵngcc0.ɵsetClassMetadata(RouterLinkWithHref, [{ type: Directive, args: [{ selector: 'a[routerLink],area[routerLink]' }] }], function () { return [{ type: Router }, { type: ActivatedRoute }, { type: ɵngcc1.LocationStrategy }]; }, { routerLink: [{ type: Input }], preserveQueryParams: [{ type: Input }], onClick: [{ type: HostListener, args: ['click', ['$event.button', '$event.ctrlKey', '$event.metaKey', '$event.shiftKey']] }], href: [{ type: HostBinding }], target: [{ type: HostBinding, args: ['attr.target'] }, { type: Input }], queryParams: [{ type: Input }], fragment: [{ type: Input }], queryParamsHandling: [{ type: Input }], preserveFragment: [{ type: Input }], skipLocationChange: [{ type: Input }], replaceUrl: [{ type: Input }], state: [{ type: Input }] }); })(); if (false) { /** @type {?} */ RouterLinkWithHref.prototype.target; /** @type {?} */ RouterLinkWithHref.prototype.queryParams; /** @type {?} */ RouterLinkWithHref.prototype.fragment; /** @type {?} */ RouterLinkWithHref.prototype.queryParamsHandling; /** @type {?} */ RouterLinkWithHref.prototype.preserveFragment; /** @type {?} */ RouterLinkWithHref.prototype.skipLocationChange; /** @type {?} */ RouterLinkWithHref.prototype.replaceUrl; /** @type {?} */ RouterLinkWithHref.prototype.state; /** * @type {?} * @private */ RouterLinkWithHref.prototype.commands; /** * @type {?} * @private */ RouterLinkWithHref.prototype.subscription; /** * @type {?} * @private */ RouterLinkWithHref.prototype.preserve; /** @type {?} */ RouterLinkWithHref.prototype.href; /** * @type {?} * @private */ RouterLinkWithHref.prototype.router; /** * @type {?} * @private */ RouterLinkWithHref.prototype.route; /** * @type {?} * @private */ RouterLinkWithHref.prototype.locationStrategy; } /** * @param {?} s * @return {?} */ function attrBoolValue(s) { return s === '' || !!s; } /** * @fileoverview added by tsickle * Generated from: packages/router/src/directives/router_link_active.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * * \@description * * Lets you add a CSS class to an element when the link's route becomes active. * * This directive lets you add a CSS class to an element when the link's route * becomes active. * * Consider the following example: * * ``` * <a routerLink="/user/bob" routerLinkActive="active-link">Bob</a> * ``` * * When the url is either '/user' or '/user/bob', the active-link class will * be added to the `a` tag. If the url changes, the class will be removed. * * You can set more than one class, as follows: * * ``` * <a routerLink="/user/bob" routerLinkActive="class1 class2">Bob</a> * <a routerLink="/user/bob" [routerLinkActive]="['class1', 'class2']">Bob</a> * ``` * * You can configure RouterLinkActive by passing `exact: true`. This will add the classes * only when the url matches the link exactly. * * ``` * <a routerLink="/user/bob" routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: * true}">Bob</a> * ``` * * You can assign the RouterLinkActive instance to a template variable and directly check * the `isActive` status. * ``` * <a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive"> * Bob {{ rla.isActive ? '(already open)' : ''}} * </a> * ``` * * Finally, you can apply the RouterLinkActive directive to an ancestor of a RouterLink. * * ``` * <div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}"> * <a routerLink="/user/jim">Jim</a> * <a routerLink="/user/bob">Bob</a> * </div> * ``` * * This will set the active-link class on the div tag if the url is either '/user/jim' or * '/user/bob'. * * \@ngModule RouterModule * * \@publicApi */ class RouterLinkActive { /** * @param {?} router * @param {?} element * @param {?} renderer * @param {?=} link * @param {?=} linkWithHref */ constructor(router, element, renderer, link, linkWithHref) { this.router = router; this.element = element; this.renderer = renderer; this.link = link; this.linkWithHref = linkWithHref; this.classes = []; this.isActive = false; this.routerLinkActiveOptions = { exact: false }; this.subscription = router.events.subscribe((/** * @param {?} s * @return {?} */ (s) => { if (s instanceof NavigationEnd) { this.update(); } })); } /** * @return {?} */ ngAfterContentInit() { this.links.changes.subscribe((/** * @param {?} _ * @return {?} */ _ => this.update())); this.linksWithHrefs.changes.subscribe((/** * @param {?} _ * @return {?} */ _ => this.update())); this.update(); } /** * @param {?} data * @return {?} */ set routerLinkActive(data) { /** @type {?} */ const classes = Array.isArray(data) ? data : data.split(' '); this.classes = classes.filter((/** * @param {?} c * @return {?} */ c => !!c)); } /** * @param {?} changes * @return {?} */ ngOnChanges(changes) { this.update(); } /** * @return {?} */ ngOnDestroy() { this.subscription.unsubscribe(); } /** * @private * @return {?} */ update() { if (!this.links || !this.linksWithHrefs || !this.router.navigated) return; Promise.resolve().then((/** * @return {?} */ () => { /** @type {?} */ const hasActiveLinks = this.hasActiveLinks(); if (this.isActive !== hasActiveLinks) { ((/** @type {?} */ (this))).isActive = hasActiveLinks; this.classes.forEach((/** * @param {?} c * @return {?} */ (c) => { if (hasActiveLinks) { this.renderer.addClass(this.element.nativeElement, c); } else { this.renderer.removeClass(this.element.nativeElement, c); } })); } })); } /** * @private * @param {?} router * @return {?} */ isLinkActive(router) { return (/** * @param {?} link * @return {?} */ (link) => router.isActive(link.urlTree, this.routerLinkActiveOptions.exact)); } /** * @private * @return {?} */ hasActiveLinks() { /** @type {?} */ const isActiveCheckFn = this.isLinkActive(this.router); return this.link && isActiveCheckFn(this.link) || this.linkWithHref && isActiveCheckFn(this.linkWithHref) || this.links.some(isActiveCheckFn) || this.linksWithHrefs.some(isActiveCheckFn); } } RouterLinkActive.ɵfac = function RouterLinkActive_Factory(t) { return new (t || RouterLinkActive)(ɵngcc0.ɵɵdirectiveInject(Router), ɵngcc0.ɵɵdirectiveInject(ɵngcc0.ElementRef), ɵngcc0.ɵɵdirectiveInject(ɵngcc0.Renderer2), ɵngcc0.ɵɵdirectiveInject(RouterLink, 8), ɵngcc0.ɵɵdirectiveInject(RouterLinkWithHref, 8)); }; RouterLinkActive.ɵdir = ɵngcc0.ɵɵdefineDirective({ type: RouterLinkActive, selectors: [["", "routerLinkActive", ""]], contentQueries: function RouterLinkActive_ContentQueries(rf, ctx, dirIndex) { if (rf & 1) { ɵngcc0.ɵɵcontentQuery(dirIndex, RouterLink, true); ɵngcc0.ɵɵcontentQuery(dirIndex, RouterLinkWithHref, true); } if (rf & 2) { var _t; ɵngcc0.ɵɵqueryRefresh(_t = ɵngcc0.ɵɵloadQuery()) && (ctx.links = _t); ɵngcc0.ɵɵqueryRefresh(_t = ɵngcc0.ɵɵloadQuery()) && (ctx.linksWithHrefs = _t); } }, inputs: { routerLinkActiveOptions: "routerLinkActiveOptions", routerLinkActive: "routerLinkActive" }, exportAs: ["routerLinkActive"], features: [ɵngcc0.ɵɵNgOnChangesFeature] }); /** @nocollapse */ RouterLinkActive.ctorParameters = () => [ { type: Router }, { type: ElementRef }, { type: Renderer2 }, { type: RouterLink, decorators: [{ type: Optional }] }, { type: RouterLinkWithHref, decorators: [{ type: Optional }] } ]; RouterLinkActive.propDecorators = { links: [{ type: ContentChildren, args: [RouterLink, { descendants: true },] }], linksWithHrefs: [{ type: ContentChildren, args: [RouterLinkWithHref, { descendants: true },] }], routerLinkActiveOptions: [{ type: Input }], routerLinkActive: [{ type: Input }] }; /*@__PURE__*/ (function () { ɵngcc0.ɵsetClassMetadata(RouterLinkActive, [{ type: Directive, args: [{ selector: '[routerLinkActive]', exportAs: 'routerLinkActive' }] }], function () { return [{ type: Router }, { type: ɵngcc0.ElementRef }, { type: ɵngcc0.Renderer2 }, { type: RouterLink, decorators: [{ type: Optional }] }, { type: RouterLinkWithHref, decorators: [{ type: Optional }] }]; }, { routerLinkActiveOptions: [{ type: Input }], routerLinkActive: [{ type: Input }], links: [{ type: ContentChildren, args: [RouterLink, { descendants: true }] }], linksWithHrefs: [{ type: ContentChildren, args: [RouterLinkWithHref, { descendants: true }] }] }); })(); if (false) { /** @type {?} */ RouterLinkActive.prototype.links; /** @type {?} */ RouterLinkActive.prototype.linksWithHrefs; /** * @type {?} * @private */ RouterLinkActive.prototype.classes; /** * @type {?} * @private */ RouterLinkActive.prototype.subscription; /** @type {?} */ RouterLinkActive.prototype.isActive; /** @type {?} */ RouterLinkActive.prototype.routerLinkActiveOptions; /** * @type {?} * @private */ RouterLinkActive.prototype.router; /** * @type {?} * @private */ RouterLinkActive.prototype.element; /** * @type {?} * @private */ RouterLinkActive.prototype.renderer; /** * @type {?} * @private */ RouterLinkActive.prototype.link; /** * @type {?} * @private */ RouterLinkActive.prototype.linkWithHref; } /** * @fileoverview added by tsickle * Generated from: packages/router/src/router_outlet_context.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Store contextual information about a `RouterOutlet` * * \@publicApi */ class OutletContext { constructor() { this.outlet = null; this.route = null; this.resolver = null; this.children = new ChildrenOutletContexts(); this.attachRef = null; } } if (false) { /** @type {?} */ OutletContext.prototype.outlet; /** @type {?} */ OutletContext.prototype.route; /** @type {?} */ OutletContext.prototype.resolver; /** @type {?} */ OutletContext.prototype.children; /** @type {?} */ OutletContext.prototype.attachRef; } /** * Store contextual information about the children (= nested) `RouterOutlet` * * \@publicApi */ class ChildrenOutletContexts { constructor() { // contexts for child outlets, by name. this.contexts = new Map(); } /** * Called when a `RouterOutlet` directive is instantiated * @param {?} childName * @param {?} outlet * @return {?} */ onChildOutletCreated(childName, outlet) { /** @type {?} */ const context = this.getOrCreateContext(childName); context.outlet = outlet; this.contexts.set(childName, context); } /** * Called when a `RouterOutlet` directive is destroyed. * We need to keep the context as the outlet could be destroyed inside a NgIf and might be * re-created later. * @param {?} childName * @return {?} */ onChildOutletDestroyed(childName) { /** @type {?} */ const context = this.getContext(childName); if (context) { context.outlet = null; } } /** * Called when the corresponding route is deactivated during navigation. * Because the component get destroyed, all children outlet are destroyed. * @return {?} */ onOutletDeactivated() { /** @type {?} */ const contexts = this.contexts; this.contexts = new Map(); return contexts; } /** * @param {?} contexts * @return {?} */ onOutletReAttached(contexts) { this.contexts = contexts; } /** * @param {?} childName * @return {?} */ getOrCreateContext(childName) { /** @type {?} */ let context = this.getContext(childName); if (!context) { context = new OutletContext(); this.contexts.set(childName, context); } return context; } /** * @param {?} childName * @return {?} */ getContext(childName) { return this.contexts.get(childName) || null; } } if (false) { /** * @type {?} * @private */ ChildrenOutletContexts.prototype.contexts; } /** * @fileoverview added by tsickle * Generated from: packages/router/src/directives/router_outlet.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * \@description * * Acts as a placeholder that Angular dynamically fills based on the current router state. * * Each outlet can have a unique name, determined by the optional `name` attribute. * The name cannot be set or changed dynamically. If not set, default value is "primary". * * ``` * <router-outlet></router-outlet> * <router-outlet name='left'></router-outlet> * <router-outlet name='right'></router-outlet> * ``` * * A router outlet emits an activate event when a new component is instantiated, * and a deactivate event when a component is destroyed. * * ``` * <router-outlet * (activate)='onActivate($event)' * (deactivate)='onDeactivate($event)'></router-outlet> * ``` * \@ngModule RouterModule * * \@publicApi */ class RouterOutlet { /** * @param {?} parentContexts * @param {?} location * @param {?} resolver * @param {?} name * @param {?} changeDetector */ constructor(parentContexts, location, resolver, name, changeDetector) { this.parentContexts = parentContexts; this.location = location; this.resolver = resolver; this.changeDetector = changeDetector; this.activated = null; this._activatedRoute = null; this.activateEvents = new EventEmitter(); this.deactivateEvents = new EventEmitter(); this.name = name || PRIMARY_OUTLET; parentContexts.onChildOutletCreated(this.name, this); } /** * @return {?} */ ngOnDestroy() { this.parentContexts.onChildOutletDestroyed(this.name); } /** * @return {?} */ ngOnInit() { if (!this.activated) { // If the outlet was not instantiated at the time the route got activated we need to populate // the outlet when it is initialized (ie inside a NgIf) /** @type {?} */ const context = this.parentContexts.getContext(this.name); if (context && context.route) { if (context.attachRef) { // `attachRef` is populated when there is an existing component to mount this.attach(context.attachRef, context.route); } else { // otherwise the component defined in the configuration is created this.activateWith(context.route, context.resolver || null); } } } } /** * @return {?} */ get isActivated() { return !!this.activated; } /** * @return {?} */ get component() { if (!this.activated) throw new Error('Outlet is not activated'); return this.activated.instance; } /** * @return {?} */ get activatedRoute() { if (!this.activated) throw new Error('Outlet is not activated'); return (/** @type {?} */ (this._activatedRoute)); } /** * @return {?} */ get activatedRouteData() { if (this._activatedRoute) { return this._activatedRoute.snapshot.data; } return {}; } /** * Called when the `RouteReuseStrategy` instructs to detach the subtree * @return {?} */ detach() { if (!this.activated) throw new Error('Outlet is not activated'); this.location.detach(); /** @type {?} */ const cmp = this.activated; this.activated = null; this._activatedRoute = null; return cmp; } /** * Called when the `RouteReuseStrategy` instructs to re-attach a previously detached subtree * @param {?} ref * @param {?} activatedRoute * @return {?} */ attach(ref, activatedRoute) { this.activated = ref; this._activatedRoute = activatedRoute; this.location.insert(ref.hostView); } /** * @return {?} */ deactivate() { if (this.activated) { /** @type {?} */ const c = this.component; this.activated.destroy(); this.activated = null; this._activatedRoute = null; this.deactivateEvents.emit(c); } } /** * @param {?} activatedRoute * @param {?} resolver * @return {?} */ activateWith(activatedRoute, resolver) { if (this.isActivated) { throw new Error('Cannot activate an already activated outlet'); } this._activatedRoute = activatedRoute; /** @type {?} */ const snapshot = activatedRoute._futureSnapshot; /** @type {?} */ const component = (/** @type {?} */ ((/** @type {?} */ (snapshot.routeConfig)).component)); resolver = resolver || this.resolver; /** @type {?} */ const factory = resolver.resolveComponentFactory(component); /** @type {?} */ const childContexts = this.parentContexts.getOrCreateContext(this.name).children; /** @type {?} */ const injector = new OutletInjector(activatedRoute, childContexts, this.location.injector); this.activated = this.location.createComponent(factory, this.location.length, injector); // Calling `markForCheck` to make sure we will run the change detection when the // `RouterOutlet` is inside a `ChangeDetectionStrategy.OnPush` component. this.changeDetector.markForCheck(); this.activateEvents.emit(this.activated.instance); } } RouterOutlet.ɵfac = function RouterOutlet_Factory(t) { return new (t || RouterOutlet)(ɵngcc0.ɵɵdirectiveInject(ChildrenOutletContexts), ɵngcc0.ɵɵdirectiveInject(ɵngcc0.ViewContainerRef), ɵngcc0.ɵɵdirectiveInject(ɵngcc0.ComponentFactoryResolver), ɵngcc0.ɵɵinjectAttribute('name'), ɵngcc0.ɵɵdirectiveInject(ɵngcc0.ChangeDetectorRef)); }; RouterOutlet.ɵdir = ɵngcc0.ɵɵdefineDirective({ type: RouterOutlet, selectors: [["router-outlet"]], outputs: { activateEvents: "activate", deactivateEvents: "deactivate" }, exportAs: ["outlet"] }); /** @nocollapse */ RouterOutlet.ctorParameters = () => [ { type: ChildrenOutletContexts }, { type: ViewContainerRef }, { type: ComponentFactoryResolver }, { type: String, decorators: [{ type: Attribute, args: ['name',] }] }, { type: ChangeDetectorRef } ]; RouterOutlet.propDecorators = { activateEvents: [{ type: Output, args: ['activate',] }], deactivateEvents: [{ type: Output, args: ['deactivate',] }] }; /*@__PURE__*/ (function () { ɵngcc0.ɵsetClassMetadata(RouterOutlet, [{ type: Directive, args: [{ selector: 'router-outlet', exportAs: 'outlet' }] }], function () { return [{ type: ChildrenOutletContexts }, { type: ɵngcc0.ViewContainerRef }, { type: ɵngcc0.ComponentFactoryResolver }, { type: String, decorators: [{ type: Attribute, args: ['name'] }] }, { type: ɵngcc0.ChangeDetectorRef }]; }, { activateEvents: [{ type: Output, args: ['activate'] }], deactivateEvents: [{ type: Output, args: ['deactivate'] }] }); })(); if (false) { /** * @type {?} * @private */ RouterOutlet.prototype.activated; /** * @type {?} * @private */ RouterOutlet.prototype._activatedRoute; /** * @type {?} * @private */ RouterOutlet.prototype.name; /** @type {?} */ RouterOutlet.prototype.activateEvents; /** @type {?} */ RouterOutlet.prototype.deactivateEvents; /** * @type {?} * @private */ RouterOutlet.prototype.parentContexts; /** * @type {?} * @private */ RouterOutlet.prototype.location; /** * @type {?} * @private */ RouterOutlet.prototype.resolver; /** * @type {?} * @private */ RouterOutlet.prototype.changeDetector; } class OutletInjector { /** * @param {?} route * @param {?} childContexts * @param {?} parent */ constructor(route, childContexts, parent) { this.route = route; this.childContexts = childContexts; this.parent = parent; } /** * @param {?} token * @param {?=} notFoundValue * @return {?} */ get(token, notFoundValue) { if (token === ActivatedRoute) { return this.route; } if (token === ChildrenOutletContexts) { return this.childContexts; } return this.parent.get(token, notFoundValue); } } if (false) { /** * @type {?} * @private */ OutletInjector.prototype.route; /** * @type {?} * @private */ OutletInjector.prototype.childContexts; /** * @type {?} * @private */ OutletInjector.prototype.parent; } /** * @fileoverview added by tsickle * Generated from: packages/router/src/router_preloader.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * \@description * * Provides a preloading strategy. * * \@publicApi * @abstract */ class PreloadingStrategy { } if (false) { /** * @abstract * @param {?} route * @param {?} fn * @return {?} */ PreloadingStrategy.prototype.preload = function (route, fn) { }; } /** * \@description * * Provides a preloading strategy that preloads all modules as quickly as possible. * * ``` * RouteModule.forRoot(ROUTES, {preloadingStrategy: PreloadAllModules}) * ``` * * \@publicApi */ class PreloadAllModules { /** * @param {?} route * @param {?} fn * @return {?} */ preload(route, fn) { return fn().pipe(catchError((/** * @return {?} */ () => of(null)))); } } /** * \@description * * Provides a preloading strategy that does not preload any modules. * * This strategy is enabled by default. * * \@publicApi */ class NoPreloading { /** * @param {?} route * @param {?} fn * @return {?} */ preload(route, fn) { return of(null); } } /** * The preloader optimistically loads all router configurations to * make navigations into lazily-loaded sections of the application faster. * * The preloader runs in the background. When the router bootstraps, the preloader * starts listening to all navigation events. After every such event, the preloader * will check if any configurations can be loaded lazily. * * If a route is protected by `canLoad` guards, the preloaded will not load it. * * \@publicApi */ class RouterPreloader { /** * @param {?} router * @param {?} moduleLoader * @param {?} compiler * @param {?} injector * @param {?} preloadingStrategy */ constructor(router, moduleLoader, compiler, injector, preloadingStrategy) { this.router = router; this.injector = injector; this.preloadingStrategy = preloadingStrategy; /** @type {?} */ const onStartLoad = (/** * @param {?} r * @return {?} */ (r) => router.triggerEvent(new RouteConfigLoadStart(r))); /** @type {?} */ const onEndLoad = (/** * @param {?} r * @return {?} */ (r) => router.triggerEvent(new RouteConfigLoadEnd(r))); this.loader = new RouterConfigLoader(moduleLoader, compiler, onStartLoad, onEndLoad); } /** * @return {?} */ setUpPreloading() { this.subscription = this.router.events .pipe(filter((/** * @param {?} e * @return {?} */ (e) => e instanceof NavigationEnd)), concatMap((/** * @return {?} */ () => this.preload()))) .subscribe((/** * @return {?} */ () => { })); } /** * @return {?} */ preload() { /** @type {?} */ const ngModule = this.injector.get(NgModuleRef); return this.processRoutes(ngModule, this.router.config); } // TODO(jasonaden): This class relies on code external to the class to call setUpPreloading. If // this hasn't been done, ngOnDestroy will fail as this.subscription will be undefined. This // should be refactored. /** * @return {?} */ ngOnDestroy() { this.subscription.unsubscribe(); } /** * @private * @param {?} ngModule * @param {?} routes * @return {?} */ processRoutes(ngModule, routes) { /** @type {?} */ const res = []; for (const route of routes) { // we already have the config loaded, just recurse if (route.loadChildren && !route.canLoad && route._loadedConfig) { /** @type {?} */ const childConfig = route._loadedConfig; res.push(this.processRoutes(childConfig.module, childConfig.routes)); // no config loaded, fetch the config } else if (route.loadChildren && !route.canLoad) { res.push(this.preloadConfig(ngModule, route)); // recurse into children } else if (route.children) { res.push(this.processRoutes(ngModule, route.children)); } } return from(res).pipe(mergeAll(), map((/** * @param {?} _ * @return {?} */ (_) => void 0))); } /** * @private * @param {?} ngModule * @param {?} route * @return {?} */ preloadConfig(ngModule, route) { return this.preloadingStrategy.preload(route, (/** * @return {?} */ () => { /** @type {?} */ const loaded$ = this.loader.load(ngModule.injector, route); return loaded$.pipe(mergeMap((/** * @param {?} config * @return {?} */ (config) => { route._loadedConfig = config; return this.processRoutes(config.module, config.routes); }))); })); } } RouterPreloader.ɵfac = function RouterPreloader_Factory(t) { return new (t || RouterPreloader)(ɵngcc0.ɵɵinject(Router), ɵngcc0.ɵɵinject(ɵngcc0.NgModuleFactoryLoader), ɵngcc0.ɵɵinject(ɵngcc0.Compiler), ɵngcc0.ɵɵinject(ɵngcc0.Injector), ɵngcc0.ɵɵinject(PreloadingStrategy)); }; RouterPreloader.ɵprov = ɵngcc0.ɵɵdefineInjectable({ token: RouterPreloader, factory: RouterPreloader.ɵfac }); /** @nocollapse */ RouterPreloader.ctorParameters = () => [ { type: Router }, { type: NgModuleFactoryLoader }, { type: Compiler }, { type: Injector }, { type: PreloadingStrategy } ]; /*@__PURE__*/ (function () { ɵngcc0.ɵsetClassMetadata(RouterPreloader, [{ type: Injectable }], function () { return [{ type: Router }, { type: ɵngcc0.NgModuleFactoryLoader }, { type: ɵngcc0.Compiler }, { type: ɵngcc0.Injector }, { type: PreloadingStrategy }]; }, null); })(); if (false) { /** * @type {?} * @private */ RouterPreloader.prototype.loader; /** * @type {?} * @private */ RouterPreloader.prototype.subscription; /** * @type {?} * @private */ RouterPreloader.prototype.router; /** * @type {?} * @private */ RouterPreloader.prototype.injector; /** * @type {?} * @private */ RouterPreloader.prototype.preloadingStrategy; } /** * @fileoverview added by tsickle * Generated from: packages/router/src/router_scroller.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ class RouterScroller { /** * @param {?} router * @param {?} viewportScroller * @param {?=} options */ constructor(router, viewportScroller, options = {}) { this.router = router; this.viewportScroller = viewportScroller; this.options = options; this.lastId = 0; this.lastSource = 'imperative'; this.restoredId = 0; this.store = {}; // Default both options to 'disabled' options.scrollPositionRestoration = options.scrollPositionRestoration || 'disabled'; options.anchorScrolling = options.anchorScrolling || 'disabled'; } /** * @return {?} */ init() { // we want to disable the automatic scrolling because having two places // responsible for scrolling results race conditions, especially given // that browser don't implement this behavior consistently if (this.options.scrollPositionRestoration !== 'disabled') { this.viewportScroller.setHistoryScrollRestoration('manual'); } this.routerEventsSubscription = this.createScrollEvents(); this.scrollEventsSubscription = this.consumeScrollEvents(); } /** * @private * @return {?} */ createScrollEvents() { return this.router.events.subscribe((/** * @param {?} e * @return {?} */ e => { if (e instanceof NavigationStart) { // store the scroll position of the current stable navigations. this.store[this.lastId] = this.viewportScroller.getScrollPosition(); this.lastSource = e.navigationTrigger; this.restoredId = e.restoredState ? e.restoredState.navigationId : 0; } else if (e instanceof NavigationEnd) { this.lastId = e.id; this.scheduleScrollEvent(e, this.router.parseUrl(e.urlAfterRedirects).fragment); } })); } /** * @private * @return {?} */ consumeScrollEvents() { return this.router.events.subscribe((/** * @param {?} e * @return {?} */ e => { if (!(e instanceof Scroll)) return; // a popstate event. The pop state event will always ignore anchor scrolling. if (e.position) { if (this.options.scrollPositionRestoration === 'top') { this.viewportScroller.scrollToPosition([0, 0]); } else if (this.options.scrollPositionRestoration === 'enabled') { this.viewportScroller.scrollToPosition(e.position); } // imperative navigation "forward" } else { if (e.anchor && this.options.anchorScrolling === 'enabled') { this.viewportScroller.scrollToAnchor(e.anchor); } else if (this.options.scrollPositionRestoration !== 'disabled') { this.viewportScroller.scrollToPosition([0, 0]); } } })); } /** * @private * @param {?} routerEvent * @param {?} anchor * @return {?} */ scheduleScrollEvent(routerEvent, anchor) { this.router.triggerEvent(new Scroll(routerEvent, this.lastSource === 'popstate' ? this.store[this.restoredId] : null, anchor)); } /** * @return {?} */ ngOnDestroy() { if (this.routerEventsSubscription) { this.routerEventsSubscription.unsubscribe(); } if (this.scrollEventsSubscription) { this.scrollEventsSubscription.unsubscribe(); } } } RouterScroller.ɵfac = function RouterScroller_Factory(t) { ɵngcc0.ɵɵinvalidFactory(); }; RouterScroller.ɵdir = ɵngcc0.ɵɵdefineDirective({ type: RouterScroller }); if (false) { /** * @type {?} * @private */ RouterScroller.prototype.routerEventsSubscription; /** * @type {?} * @private */ RouterScroller.prototype.scrollEventsSubscription; /** * @type {?} * @private */ RouterScroller.prototype.lastId; /** * @type {?} * @private */ RouterScroller.prototype.lastSource; /** * @type {?} * @private */ RouterScroller.prototype.restoredId; /** * @type {?} * @private */ RouterScroller.prototype.store; /** * @type {?} * @private */ RouterScroller.prototype.router; /** * \@docsNotRequired * @type {?} */ RouterScroller.prototype.viewportScroller; /** * @type {?} * @private */ RouterScroller.prototype.options; } /** * @fileoverview added by tsickle * Generated from: packages/router/src/router_module.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * The directives defined in the `RouterModule`. * @type {?} */ const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, RouterLinkActive, ɵEmptyOutletComponent]; /** * A [DI token](guide/glossary/#di-token) for the router service. * * \@publicApi * @type {?} */ const ROUTER_CONFIGURATION = new InjectionToken('ROUTER_CONFIGURATION'); /** * \@docsNotRequired * @type {?} */ const ROUTER_FORROOT_GUARD = new InjectionToken('ROUTER_FORROOT_GUARD'); const ɵ0 = { enableTracing: false }; /** @type {?} */ const ROUTER_PROVIDERS = [ Location, { provide: UrlSerializer, useClass: DefaultUrlSerializer }, { provide: Router, useFactory: setupRouter, deps: [ UrlSerializer, ChildrenOutletContexts, Location, Injector, NgModuleFactoryLoader, Compiler, ROUTES, ROUTER_CONFIGURATION, [UrlHandlingStrategy, new Optional()], [RouteReuseStrategy, new Optional()] ] }, ChildrenOutletContexts, { provide: ActivatedRoute, useFactory: rootRoute, deps: [Router] }, { provide: NgModuleFactoryLoader, useClass: SystemJsNgModuleLoader }, RouterPreloader, NoPreloading, PreloadAllModules, { provide: ROUTER_CONFIGURATION, useValue: ɵ0 }, ]; /** * @return {?} */ function routerNgProbeToken() { return new NgProbeToken('Router', Router); } /** * \@usageNotes * * RouterModule can be imported multiple times: once per lazily-loaded bundle. * Since the router deals with a global shared resource--location, we cannot have * more than one router service active. * * That is why there are two ways to create the module: `RouterModule.forRoot` and * `RouterModule.forChild`. * * * `forRoot` creates a module that contains all the directives, the given routes, and the router * service itself. * * `forChild` creates a module that contains all the directives and the given routes, but does not * include the router service. * * When registered at the root, the module should be used as follows * * ``` * \@NgModule({ * imports: [RouterModule.forRoot(ROUTES)] * }) * class MyNgModule {} * ``` * * For submodules and lazy loaded submodules the module should be used as follows: * * ``` * \@NgModule({ * imports: [RouterModule.forChild(ROUTES)] * }) * class MyNgModule {} * ``` * * \@description * * Adds router directives and providers. * * Managing state transitions is one of the hardest parts of building applications. This is * especially true on the web, where you also need to ensure that the state is reflected in the URL. * In addition, we often want to split applications into multiple bundles and load them on demand. * Doing this transparently is not trivial. * * The Angular router service solves these problems. Using the router, you can declaratively specify * application states, manage state transitions while taking care of the URL, and load bundles on * demand. * * @see [Routing and Navigation](guide/router.html) for an * overview of how the router service should be used. * * \@publicApi */ class RouterModule { // Note: We are injecting the Router so it gets created eagerly... /** * @param {?} guard * @param {?} router */ constructor(guard, router) { } /** * Creates and configures a module with all the router providers and directives. * Optionally sets up an application listener to perform an initial navigation. * * @param {?} routes An array of `Route` objects that define the navigation paths for the application. * @param {?=} config An `ExtraOptions` configuration object that controls how navigation is performed. * @return {?} The new router module. */ static forRoot(routes, config) { return { ngModule: RouterModule, providers: [ ROUTER_PROVIDERS, provideRoutes(routes), { provide: ROUTER_FORROOT_GUARD, useFactory: provideForRootGuard, deps: [[Router, new Optional(), new SkipSelf()]] }, { provide: ROUTER_CONFIGURATION, useValue: config ? config : {} }, { provide: LocationStrategy, useFactory: provideLocationStrategy, deps: [PlatformLocation, [new Inject(APP_BASE_HREF), new Optional()], ROUTER_CONFIGURATION] }, { provide: RouterScroller, useFactory: createRouterScroller, deps: [Router, ViewportScroller, ROUTER_CONFIGURATION] }, { provide: PreloadingStrategy, useExisting: config && config.preloadingStrategy ? config.preloadingStrategy : NoPreloading }, { provide: NgProbeToken, multi: true, useFactory: routerNgProbeToken }, provideRouterInitializer(), ], }; } /** * Creates a module with all the router directives and a provider registering routes. * @param {?} routes * @return {?} */ static forChild(routes) { return { ngModule: RouterModule, providers: [provideRoutes(routes)] }; } } RouterModule.ɵmod = ɵngcc0.ɵɵdefineNgModule({ type: RouterModule }); RouterModule.ɵinj = ɵngcc0.ɵɵdefineInjector({ factory: function RouterModule_Factory(t) { return new (t || RouterModule)(ɵngcc0.ɵɵinject(ROUTER_FORROOT_GUARD, 8), ɵngcc0.ɵɵinject(Router, 8)); } }); /** @nocollapse */ RouterModule.ctorParameters = () => [ { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [ROUTER_FORROOT_GUARD,] }] }, { type: Router, decorators: [{ type: Optional }] } ]; (function () { (typeof ngJitMode === "undefined" || ngJitMode) && ɵngcc0.ɵɵsetNgModuleScope(RouterModule, { declarations: [RouterOutlet, RouterLink, RouterLinkWithHref, RouterLinkActive, ɵEmptyOutletComponent], exports: [RouterOutlet, RouterLink, RouterLinkWithHref, RouterLinkActive, ɵEmptyOutletComponent] }); })(); /*@__PURE__*/ (function () { ɵngcc0.ɵsetClassMetadata(RouterModule, [{ type: NgModule, args: [{ declarations: ROUTER_DIRECTIVES, exports: ROUTER_DIRECTIVES, entryComponents: [ɵEmptyOutletComponent] }] }], function () { return [{ type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [ROUTER_FORROOT_GUARD] }] }, { type: Router, decorators: [{ type: Optional }] }]; }, null); })(); /** * @param {?} router * @param {?} viewportScroller * @param {?} config * @return {?} */ function createRouterScroller(router, viewportScroller, config) { if (config.scrollOffset) { viewportScroller.setOffset(config.scrollOffset); } return new RouterScroller(router, viewportScroller, config); } /** * @param {?} platformLocationStrategy * @param {?} baseHref * @param {?=} options * @return {?} */ function provideLocationStrategy(platformLocationStrategy, baseHref, options = {}) { return options.useHash ? new HashLocationStrategy(platformLocationStrategy, baseHref) : new PathLocationStrategy(platformLocationStrategy, baseHref); } /** * @param {?} router * @return {?} */ function provideForRootGuard(router) { if (router) { throw new Error(`RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.`); } return 'guarded'; } /** * Registers a [DI provider](guide/glossary#provider) for a set of routes. * \@usageNotes * * ``` * \@NgModule({ * imports: [RouterModule.forChild(ROUTES)], * providers: [provideRoutes(EXTRA_ROUTES)] * }) * class MyNgModule {} * ``` * * \@publicApi * @param {?} routes The route configuration to provide. * * @return {?} */ function provideRoutes(routes) { return [ { provide: ANALYZE_FOR_ENTRY_COMPONENTS, multi: true, useValue: routes }, { provide: ROUTES, multi: true, useValue: routes }, ]; } /** * A set of configuration options for a router module, provided in the * `forRoot()` method. * * \@publicApi * @record */ function ExtraOptions() { } if (false) { /** * When true, log all internal navigation events to the console. * Use for debugging. * @type {?|undefined} */ ExtraOptions.prototype.enableTracing; /** * When true, enable the location strategy that uses the URL fragment * instead of the history API. * @type {?|undefined} */ ExtraOptions.prototype.useHash; /** * One of `enabled` or `disabled`. * When set to `enabled`, the initial navigation starts before the root component is created. * The bootstrap is blocked until the initial navigation is complete. This value is required for * [server-side rendering](guide/universal) to work. * When set to `disabled`, the initial navigation is not performed. * The location listener is set up before the root component gets created. * Use if there is a reason to have more control over when the router * starts its initial navigation due to some complex initialization logic. * * Legacy values are deprecated since v4 and should not be used for new applications: * * * `legacy_enabled` - Default for compatibility. * The initial navigation starts after the root component has been created, * but the bootstrap is not blocked until the initial navigation is complete. * * `legacy_disabled` - The initial navigation is not performed. * The location listener is set up after the root component gets created. * * `true` - same as `legacy_enabled`. * * `false` - same as `legacy_disabled`. * @type {?|undefined} */ ExtraOptions.prototype.initialNavigation; /** * A custom error handler for failed navigations. * @type {?|undefined} */ ExtraOptions.prototype.errorHandler; /** * Configures a preloading strategy. * One of `PreloadAllModules` or `NoPreloading` (the default). * @type {?|undefined} */ ExtraOptions.prototype.preloadingStrategy; /** * Define what the router should do if it receives a navigation request to the current URL. * Default is `ignore`, which causes the router ignores the navigation. * This can disable features such as a "refresh" button. * Use this option to configure the behavior when navigating to the * current URL. Default is 'ignore'. * @type {?|undefined} */ ExtraOptions.prototype.onSameUrlNavigation; /** * Configures if the scroll position needs to be restored when navigating back. * * * 'disabled'- (Default) Does nothing. Scroll position is maintained on navigation. * * 'top'- Sets the scroll position to x = 0, y = 0 on all navigation. * * 'enabled'- Restores the previous scroll position on backward navigation, else sets the * position to the anchor if one is provided, or sets the scroll position to [0, 0] (forward * navigation). This option will be the default in the future. * * You can implement custom scroll restoration behavior by adapting the enabled behavior as * in the following example. * * ```typescript * class AppModule { * constructor(router: Router, viewportScroller: ViewportScroller) { * router.events.pipe( * filter((e: Event): e is Scroll => e instanceof Scroll) * ).subscribe(e => { * if (e.position) { * // backward navigation * viewportScroller.scrollToPosition(e.position); * } else if (e.anchor) { * // anchor navigation * viewportScroller.scrollToAnchor(e.anchor); * } else { * // forward navigation * viewportScroller.scrollToPosition([0, 0]); * } * }); * } * } * ``` * @type {?|undefined} */ ExtraOptions.prototype.scrollPositionRestoration; /** * When set to 'enabled', scrolls to the anchor element when the URL has a fragment. * Anchor scrolling is disabled by default. * * Anchor scrolling does not happen on 'popstate'. Instead, we restore the position * that we stored or scroll to the top. * @type {?|undefined} */ ExtraOptions.prototype.anchorScrolling; /** * Configures the scroll offset the router will use when scrolling to an element. * * When given a tuple with x and y position value, * the router uses that offset each time it scrolls. * When given a function, the router invokes the function every time * it restores scroll position. * @type {?|undefined} */ ExtraOptions.prototype.scrollOffset; /** * Defines how the router merges parameters, data, and resolved data from parent to child * routes. By default ('emptyOnly'), inherits parent parameters only for * path-less or component-less routes. * Set to 'always' to enable unconditional inheritance of parent parameters. * @type {?|undefined} */ ExtraOptions.prototype.paramsInheritanceStrategy; /** * A custom handler for malformed URI errors. The handler is invoked when `encodedURI` contains * invalid character sequences. * The default implementation is to redirect to the root URL, dropping * any path or parameter information. The function takes three parameters: * * - `'URIError'` - Error thrown when parsing a bad URL. * - `'UrlSerializer'` - UrlSerializer that’s configured with the router. * - `'url'` - The malformed URL that caused the URIError * * @type {?|undefined} */ ExtraOptions.prototype.malformedUriErrorHandler; /** * Defines when the router updates the browser URL. By default ('deferred'), * update after successful navigation. * Set to 'eager' if prefer to update the URL at the beginning of navigation. * Updating the URL early allows you to handle a failure of navigation by * showing an error message with the URL that failed. * @type {?|undefined} */ ExtraOptions.prototype.urlUpdateStrategy; /** * Enables a bug fix that corrects relative link resolution in components with empty paths. * Example: * * ``` * const routes = [ * { * path: '', * component: ContainerComponent, * children: [ * { path: 'a', component: AComponent }, * { path: 'b', component: BComponent }, * ] * } * ]; * ``` * * From the `ContainerComponent`, this will not work: * * `<a [routerLink]="['./a']">Link to A</a>` * * However, this will work: * * `<a [routerLink]="['../a']">Link to A</a>` * * In other words, you're required to use `../` rather than `./`. This is currently the default * behavior. Setting this option to `corrected` enables the fix. * @type {?|undefined} */ ExtraOptions.prototype.relativeLinkResolution; } /** * @param {?} urlSerializer * @param {?} contexts * @param {?} location * @param {?} injector * @param {?} loader * @param {?} compiler * @param {?} config * @param {?=} opts * @param {?=} urlHandlingStrategy * @param {?=} routeReuseStrategy * @return {?} */ function setupRouter(urlSerializer, contexts, location, injector, loader, compiler, config, opts = {}, urlHandlingStrategy, routeReuseStrategy) { /** @type {?} */ const router = new Router(null, urlSerializer, contexts, location, injector, loader, compiler, flatten(config)); if (urlHandlingStrategy) { router.urlHandlingStrategy = urlHandlingStrategy; } if (routeReuseStrategy) { router.routeReuseStrategy = routeReuseStrategy; } if (opts.errorHandler) { router.errorHandler = opts.errorHandler; } if (opts.malformedUriErrorHandler) { router.malformedUriErrorHandler = opts.malformedUriErrorHandler; } if (opts.enableTracing) { /** @type {?} */ const dom = ɵgetDOM(); router.events.subscribe((/** * @param {?} e * @return {?} */ (e) => { dom.logGroup(`Router Event: ${((/** @type {?} */ (e.constructor))).name}`); dom.log(e.toString()); dom.log(e); dom.logGroupEnd(); })); } if (opts.onSameUrlNavigation) { router.onSameUrlNavigation = opts.onSameUrlNavigation; } if (opts.paramsInheritanceStrategy) { router.paramsInheritanceStrategy = opts.paramsInheritanceStrategy; } if (opts.urlUpdateStrategy) { router.urlUpdateStrategy = opts.urlUpdateStrategy; } if (opts.relativeLinkResolution) { router.relativeLinkResolution = opts.relativeLinkResolution; } return router; } /** * @param {?} router * @return {?} */ function rootRoute(router) { return router.routerState.root; } /** * Router initialization requires two steps: * * First, we start the navigation in a `APP_INITIALIZER` to block the bootstrap if * a resolver or a guard executes asynchronously. * * Next, we actually run activation in a `BOOTSTRAP_LISTENER`, using the * `afterPreactivation` hook provided by the router. * The router navigation starts, reaches the point when preactivation is done, and then * pauses. It waits for the hook to be resolved. We then resolve it only in a bootstrap listener. */ class RouterInitializer { /** * @param {?} injector */ constructor(injector) { this.injector = injector; this.initNavigation = false; this.resultOfPreactivationDone = new Subject(); } /** * @return {?} */ appInitializer() { /** @type {?} */ const p = this.injector.get(LOCATION_INITIALIZED, Promise.resolve(null)); return p.then((/** * @return {?} */ () => { /** @type {?} */ let resolve = (/** @type {?} */ (null)); /** @type {?} */ const res = new Promise((/** * @param {?} r * @return {?} */ r => resolve = r)); /** @type {?} */ const router = this.injector.get(Router); /** @type {?} */ const opts = this.injector.get(ROUTER_CONFIGURATION); if (this.isLegacyDisabled(opts) || this.isLegacyEnabled(opts)) { resolve(true); } else if (opts.initialNavigation === 'disabled') { router.setUpLocationChangeListener(); resolve(true); } else if (opts.initialNavigation === 'enabled') { router.hooks.afterPreactivation = (/** * @return {?} */ () => { // only the initial navigation should be delayed if (!this.initNavigation) { this.initNavigation = true; resolve(true); return this.resultOfPreactivationDone; // subsequent navigations should not be delayed } else { return (/** @type {?} */ (of(null))); } }); router.initialNavigation(); } else { throw new Error(`Invalid initialNavigation options: '${opts.initialNavigation}'`); } return res; })); } /** * @param {?} bootstrappedComponentRef * @return {?} */ bootstrapListener(bootstrappedComponentRef) { /** @type {?} */ const opts = this.injector.get(ROUTER_CONFIGURATION); /** @type {?} */ const preloader = this.injector.get(RouterPreloader); /** @type {?} */ const routerScroller = this.injector.get(RouterScroller); /** @type {?} */ const router = this.injector.get(Router); /** @type {?} */ const ref = this.injector.get(ApplicationRef); if (bootstrappedComponentRef !== ref.components[0]) { return; } if (this.isLegacyEnabled(opts)) { router.initialNavigation(); } else if (this.isLegacyDisabled(opts)) { router.setUpLocationChangeListener(); } preloader.setUpPreloading(); routerScroller.init(); router.resetRootComponentType(ref.componentTypes[0]); this.resultOfPreactivationDone.next((/** @type {?} */ (null))); this.resultOfPreactivationDone.complete(); } /** * @private * @param {?} opts * @return {?} */ isLegacyEnabled(opts) { return opts.initialNavigation === 'legacy_enabled' || opts.initialNavigation === true || opts.initialNavigation === undefined; } /** * @private * @param {?} opts * @return {?} */ isLegacyDisabled(opts) { return opts.initialNavigation === 'legacy_disabled' || opts.initialNavigation === false; } } RouterInitializer.ɵfac = function RouterInitializer_Factory(t) { return new (t || RouterInitializer)(ɵngcc0.ɵɵinject(ɵngcc0.Injector)); }; RouterInitializer.ɵprov = ɵngcc0.ɵɵdefineInjectable({ token: RouterInitializer, factory: RouterInitializer.ɵfac }); /** @nocollapse */ RouterInitializer.ctorParameters = () => [ { type: Injector } ];
type: Injectable }], function () { return [{ type: ɵngcc0.Injector }]; }, null); })(); if (false) { /** * @type {?} * @private */ RouterInitializer.prototype.initNavigation; /** * @type {?} * @private */ RouterInitializer.prototype.resultOfPreactivationDone; /** * @type {?} * @private */ RouterInitializer.prototype.injector; } /** * @param {?} r * @return {?} */ function getAppInitializer(r) { return r.appInitializer.bind(r); } /** * @param {?} r * @return {?} */ function getBootstrapListener(r) { return r.bootstrapListener.bind(r); } /** * A [DI token](guide/glossary/#di-token) for the router initializer that * is called after the app is bootstrapped. * * \@publicApi * @type {?} */ const ROUTER_INITIALIZER = new InjectionToken('Router Initializer'); /** * @return {?} */ function provideRouterInitializer() { return [ RouterInitializer, { provide: APP_INITIALIZER, multi: true, useFactory: getAppInitializer, deps: [RouterInitializer] }, { provide: ROUTER_INITIALIZER, useFactory: getBootstrapListener, deps: [RouterInitializer] }, { provide: APP_BOOTSTRAP_LISTENER, multi: true, useExisting: ROUTER_INITIALIZER }, ]; } /** * @fileoverview added by tsickle * Generated from: packages/router/src/version.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * \@publicApi * @type {?} */ const VERSION = new Version('9.1.3'); /** * @fileoverview added by tsickle * Generated from: packages/router/src/private_export.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @fileoverview added by tsickle * Generated from: packages/router/src/index.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @fileoverview added by tsickle * Generated from: packages/router/public_api.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @fileoverview added by tsickle * Generated from: packages/router/index.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Generated bundle index. Do not edit. */ export { ActivatedRoute, ActivatedRouteSnapshot, ActivationEnd, ActivationStart, ChildActivationEnd, ChildActivationStart, ChildrenOutletContexts, DefaultUrlSerializer, GuardsCheckEnd, GuardsCheckStart, NavigationCancel, NavigationEnd, NavigationError, NavigationStart, NoPreloading, OutletContext, PRIMARY_OUTLET, PreloadAllModules, PreloadingStrategy, ROUTER_CONFIGURATION, ROUTER_INITIALIZER, ROUTES, ResolveEnd, ResolveStart, RouteConfigLoadEnd, RouteConfigLoadStart, RouteReuseStrategy, Router, RouterEvent, RouterLink, RouterLinkActive, RouterLinkWithHref, RouterModule, RouterOutlet, RouterPreloader, RouterState, RouterStateSnapshot, RoutesRecognized, Scroll, UrlHandlingStrategy, UrlSegment, UrlSegmentGroup, UrlSerializer, UrlTree, VERSION, convertToParamMap, provideRoutes, ɵEmptyOutletComponent, ROUTER_PROVIDERS as ɵROUTER_PROVIDERS, ROUTER_FORROOT_GUARD as ɵangular_packages_router_router_a, routerNgProbeToken as ɵangular_packages_router_router_b, createRouterScroller as ɵangular_packages_router_router_c, provideLocationStrategy as ɵangular_packages_router_router_d, provideForRootGuard as ɵangular_packages_router_router_e, setupRouter as ɵangular_packages_router_router_f, rootRoute as ɵangular_packages_router_router_g, RouterInitializer as ɵangular_packages_router_router_h, getAppInitializer as ɵangular_packages_router_router_i, getBootstrapListener as ɵangular_packages_router_router_j, provideRouterInitializer as ɵangular_packages_router_router_k, ɵEmptyOutletComponent as ɵangular_packages_router_router_l, Tree as ɵangular_packages_router_router_m, TreeNode as ɵangular_packages_router_router_n, RouterScroller as ɵangular_packages_router_router_o, flatten as ɵflatten }; //# sourceMappingURL=router.js.map
/*@__PURE__*/ (function () { ɵngcc0.ɵsetClassMetadata(RouterInitializer, [{
C_Code_Generation.py
# As documented in the NRPy+ tutorial module # Tutorial-RK_Butcher_Table_Generating_C_Code.ipynb, # this module will produce the required C codes for # allocating required memory Method of Lines (MoL) timestepping, # implementing MoL timestepping, and deallocating memory # Authors: Brandon Clark # Zachariah B. Etienne # zachetie **at** gmail **dot* com # Step 1: Initialize needed Python/NRPy+ modules import sympy as sp # Import SymPy, a computer algebra system written entirely in Python import os # Standard Python module for multiplatform OS-level functions from MoLtimestepping.RK_Butcher_Table_Dictionary import Butcher_dict # Step 2: Checking if Butcher Table is Diagonal def diagonal(key): diagonal = True # Start with the Butcher table is diagonal Butcher = Butcher_dict[key][0] L = len(Butcher)-1 # Establish the number of rows to check for diagonal trait, all bust last row row_idx = 0 # Initialize the Butcher table row index for i in range(L): # Check all the desired rows for j in range(1,row_idx): # Check each element before the diagonal element in a row if Butcher[i][j] != sp.sympify(0): # If any non-diagonal coeffcient is non-zero, # then the table is not diagonal diagonal = False return diagonal row_idx += 1 # Update to check the next row return diagonal # Step 3.a: When allocating memory, we populate a list malloced_gridfunctions, # which is used here to determine which gridfunctions need memory freed, # via the free() command. Free the mallocs! def free_allocated_memory(outdir,RK_method,malloced_gridfunctions): # This step is made extremely easy, as we had to with open(os.path.join(outdir, "RK_Free_Memory.h"), "w") as file: file.write("// Code snippet freeing gridfunction memory for \"" + RK_method + "\" method:\n") for gridfunction in malloced_gridfunctions: file.write("free(" + gridfunction + ");\n") # # State whether each Butcher table is diagonal or not # for key, value in Butcher_dict.items(): # if diagonal(key) == True: # print("The RK method "+str(key)+" is diagonal! \n") # else: # print("The RK method "+str(key)+" is NOT diagonal! \n") # ################################################################# # Step 3.b: Main driver function for outputting all the MoL C Code def MoL_C_Code_Generation(RK_method = "RK4", RHS_string = "", post_RHS_string = "",outdir="MoLtimestepping/", MemAllocOnly=False): ####### Step 3.b.i: Allocating Memory malloc_str = "// Code snippet allocating gridfunction memory for \"" + RK_method + "\" method:\n" # Loop over grids malloced_gridfunctions = [] # Set gridfunction type type_str = "REAL *restrict " # Define a couple useful functions for outputting the needed C code for allocating memory def
(varname): malloced_gridfunctions.append(varname) memory_alloc_str = " = (REAL *)malloc(sizeof(REAL) * NUM_EVOL_GFS * Nxx_plus_2NGHOSTS_tot"+")" return type_str + varname + memory_alloc_str + ";\n" def diagnostic_output_gfs_equal_to(gfs): return type_str + "diagnostic_output_gfs"+" = "+gfs + ";\n" # No matter the method we define gridfunctions "y_n_gfs" to store the initial data malloc_str += malloc_gfs_str("y_n_gfs") if diagonal(RK_method) == True and "RK3" in RK_method: malloc_str += malloc_gfs_str("k1_or_y_nplus_a21_k1_or_y_nplus1_running_total_gfs") malloc_str += malloc_gfs_str("k2_or_y_nplus_a32_k2_gfs") malloc_str += diagnostic_output_gfs_equal_to("k1_or_y_nplus_a21_k1_or_y_nplus1_running_total_gfs") else: if diagonal(RK_method) == False: # Allocate memory for non-diagonal Butcher tables # Determine the number of k_i steps based on length of Butcher Table num_k = len(Butcher_dict[RK_method][0])-1 # For non-diagonal tables an intermediate gridfunction "next_y_input" is used for rhs evaluations malloc_str += malloc_gfs_str("next_y_input_gfs") for i in range(num_k): # Need to allocate all k_i steps for a given method malloc_str += malloc_gfs_str("k"+str(i+1)+"_gfs") malloc_str += diagnostic_output_gfs_equal_to("k1_gfs") else: # Allocate memory for diagonal Butcher tables, which use a "y_nplus1_running_total gridfunction" malloc_str += malloc_gfs_str("y_nplus1_running_total_gfs") if RK_method != 'Euler': # Allocate memory for diagonal Butcher tables that aren't Euler # Need k_odd for k_1,3,5... and k_even for k_2,4,6... malloc_str += malloc_gfs_str("k_odd_gfs") malloc_str += malloc_gfs_str("k_even_gfs") malloc_str += diagnostic_output_gfs_equal_to("y_nplus1_running_total_gfs") with open(os.path.join(outdir,"RK_Allocate_Memory.h"), "w") as file: file.write(malloc_str) if MemAllocOnly: free_allocated_memory(outdir,RK_method,malloced_gridfunctions) return ######################################################################################################################## # EXAMPLE # ODE: y' = f(t,y), y(t_0) = y_0 # Starting at time t_n with solution having value y_n and trying to update to y_nplus1 with timestep dt # Example of scheme for RK4 with k_1, k_2, k_3, k_4 (Using non-diagonal algortihm) Notice this requires storage of # y_n, y_nplus1, k_1 through k_4 # k_1 = dt*f(t_n, y_n) # k_2 = dt*f(t_n + 1/2*dt, y_n + 1/2*k_1) # k_3 = dt*f(t_n + 1/2*dt, y_n + 1/2*k_2) # k_4 = dt*f(t_n + dt, y_n + k_3) # y_nplus1 = y_n + 1/3k_1 + 1/6k_2 + 1/6k_3 + 1/3k_4 # Example of scheme RK4 using only k_odd and k_even (Diagonal algroithm) Notice that this only requires storage # k_odd = dt*f(t_n, y_n) # y_nplus1 = 1/3*k_odd # k_even = dt*f(t_n + 1/2*dt, y_n + 1/2*k_odd) # y_nplus1 += 1/6*k_even # k_odd = dt*f(t_n + 1/2*dt, y_n + 1/2*k_even) # y_nplus1 += 1/6*k_odd # k_even = dt*f(t_n + dt, y_n + k_odd) # y_nplus1 += 1/3*k_even ######################################################################################################################## ####### Step 3.b.ii: Implementing the Runge Kutta Scheme for Method of Lines Timestepping Butcher = Butcher_dict[RK_method][0] # Get the desired Butcher table from the dictionary num_steps = len(Butcher)-1 # Specify the number of required steps to update solution indent = " " RK_str = "// Code snippet implementing "+RK_method+" algorithm for Method of Lines timestepping\n" # Diagonal RK3 only!!! def single_RK_substep(commentblock, RHS_str, RHS_input_str, RHS_output_str, RK_lhss_list, RK_rhss_list, post_RHS_list, post_RHS_output_list, indent = " "): return_str = commentblock + "\n" if not isinstance(RK_lhss_list,list): RK_lhss_list = [RK_lhss_list] if not isinstance(RK_rhss_list,list): RK_rhss_list = [RK_rhss_list] if not isinstance(post_RHS_list,list): post_RHS_list = [post_RHS_list] if not isinstance(post_RHS_output_list,list): post_RHS_output_list = [post_RHS_output_list] # Part 1: RHS evaluation: return_str += RHS_str.replace("RK_INPUT_GFS", RHS_input_str).\ replace("RK_OUTPUT_GFS",RHS_output_str)+"\n" # Part 2: RK update return_str += "LOOP_ALL_GFS_GPS"+"(i) {\n" for lhs,rhs in zip(RK_lhss_list,RK_rhss_list): return_str += indent + lhs + "[i] = " + rhs.replace("_gfs","_gfs") + ";\n" return_str += "}\n" # Part 3: Call post-RHS functions for post_RHS,post_RHS_output in zip(post_RHS_list,post_RHS_output_list): return_str += post_RHS.replace("RK_OUTPUT_GFS",post_RHS_output)+"\n" return return_str+"\n" RK_str = "// C code implementation of " + RK_method + " Method of Lines timestepping.\n" if diagonal(RK_method) == True and "RK3" in RK_method: # In a diagonal RK3 method, only 3 gridfunctions need be defined. Below implements this approach. # k_1 RK_str += """ // In a diagonal RK3 method like this one, only 3 gridfunctions need be defined. Below implements this approach. // Using y_n_gfs as input, k1 and apply boundary conditions\n""" RK_str += single_RK_substep( commentblock = """ // ***k1 substep:*** // 1. We will store k1_or_y_nplus_a21_k1_or_y_nplus1_running_total_gfs now as // ... the update for the next rhs evaluation y_n + a21*k1*dt // Post-RHS evaluation: // 1. Apply post-RHS to y_n + a21*k1*dt""", RHS_str = RHS_string, RHS_input_str = "y_n_gfs", RHS_output_str = "k1_or_y_nplus_a21_k1_or_y_nplus1_running_total_gfs", RK_lhss_list = ["k1_or_y_nplus_a21_k1_or_y_nplus1_running_total_gfs"], RK_rhss_list = ["("+sp.ccode(Butcher[1][1]).replace("L","")+")*k1_or_y_nplus_a21_k1_or_y_nplus1_running_total_gfs[i]*dt + y_n_gfs[i]"], post_RHS_list = [post_RHS_string], post_RHS_output_list = ["k1_or_y_nplus_a21_k1_or_y_nplus1_running_total_gfs"]) # k_2 RK_str += single_RK_substep( commentblock=""" // ***k2 substep:*** // 1. Reassign k1_or_y_nplus_a21_k1_or_y_nplus1_running_total_gfs to be the running total y_{n+1}; a32*k2*dt to the running total // 2. Store k2_or_y_nplus_a32_k2_gfs now as y_n + a32*k2*dt // Post-RHS evaluation: // 1. Apply post-RHS to both y_n + a32*k2 (stored in k2_or_y_nplus_a32_k2_gfs) // ... and the y_{n+1} running total, as they have not been applied yet to k2-related gridfunctions""", RHS_str=RHS_string, RHS_input_str="k1_or_y_nplus_a21_k1_or_y_nplus1_running_total_gfs", RHS_output_str="k2_or_y_nplus_a32_k2_gfs", RK_lhss_list=["k1_or_y_nplus_a21_k1_or_y_nplus1_running_total_gfs","k2_or_y_nplus_a32_k2_gfs"], RK_rhss_list=["("+sp.ccode(Butcher[3][1]).replace("L","")+")*(k1_or_y_nplus_a21_k1_or_y_nplus1_running_total_gfs[i] - y_n_gfs[i])/("+sp.ccode(Butcher[1][1]).replace("L","")+") + y_n_gfs[i] + ("+sp.ccode(Butcher[3][2]).replace("L","")+")*k2_or_y_nplus_a32_k2_gfs[i]*dt", "("+sp.ccode(Butcher[2][2]).replace("L","")+")*k2_or_y_nplus_a32_k2_gfs[i]*dt + y_n_gfs[i]"], post_RHS_list=[post_RHS_string,post_RHS_string], post_RHS_output_list=["k2_or_y_nplus_a32_k2_gfs","k1_or_y_nplus_a21_k1_or_y_nplus1_running_total_gfs"]) # k_3 RK_str += single_RK_substep( commentblock=""" // ***k3 substep:*** // 1. Add k3 to the running total and save to y_n // Post-RHS evaluation: // 1. Apply post-RHS to y_n""", RHS_str=RHS_string, RHS_input_str="k2_or_y_nplus_a32_k2_gfs", RHS_output_str="y_n_gfs", RK_lhss_list=["y_n_gfs","k2_or_y_nplus_a32_k2_gfs"], RK_rhss_list=["k1_or_y_nplus_a21_k1_or_y_nplus1_running_total_gfs[i] + ("+sp.ccode(Butcher[3][3]).replace("L","")+")*y_n_gfs[i]*dt"], post_RHS_list=[post_RHS_string], post_RHS_output_list=["y_n_gfs"]) else: y_n = "y_n_gfs" if diagonal(RK_method) == False: for s in range(num_steps): next_y_input = "next_y_input_gfs" # If we're on the first step (s=0), we use y_n gridfunction as input. # Otherwise next_y_input is input. Output is just the reverse. if s==0: # If on first step: RHS_input = y_n else: # If on second step or later: RHS_input = next_y_input RHS_output = "k" + str(s + 1) + "_gfs" if s == num_steps-1: # If on final step: RK_lhs = y_n RK_rhs = y_n + "[i] + dt*(" else: # If on anything but the final step: RK_lhs = next_y_input RK_rhs = y_n + "[i] + dt*(" for m in range(s+1): if Butcher[s+1][m+1] != 0: if Butcher[s+1][m+1] != 1: RK_rhs += " + k"+str(m+1)+"_gfs[i]*("+sp.ccode(Butcher[s+1][m+1]).replace("L","")+")" else: RK_rhs += " + k"+str(m+1)+"_gfs[i]" RK_rhs += " )" post_RHS = post_RHS_string if s == num_steps-1: # If on final step: post_RHS_output = y_n else: # If on anything but the final step: post_RHS_output = next_y_input RK_str += single_RK_substep( commentblock="// ***k" + str(s + 1) + " substep:***", RHS_str=RHS_string, RHS_input_str=RHS_input, RHS_output_str=RHS_output, RK_lhss_list=[RK_lhs], RK_rhss_list=[RK_rhs], post_RHS_list=[post_RHS], post_RHS_output_list=[post_RHS_output]) else: y_nplus1_running_total = "y_nplus1_running_total_gfs" if RK_method == 'Euler': # Euler's method doesn't require any k_i, and gets its own unique algorithm RK_str += single_RK_substep( commentblock="// ***Euler timestepping only requires one RHS evaluation***", RHS_str=RHS_string, RHS_input_str=y_n, RHS_output_str=y_nplus1_running_total, RK_lhss_list=[y_n], RK_rhss_list=[y_n+"[i] + "+y_nplus1_running_total+"[i]*dt"], post_RHS_list=[post_RHS_string], post_RHS_output_list=[y_n]) else: for s in range(num_steps): # If we're on the first step (s=0), we use y_n gridfunction as input. # and k_odd as output. if s == 0: RHS_input = "y_n_gfs" RHS_output = "k_odd_gfs" # For the remaining steps the inputs and ouputs alternate between k_odd and k_even elif s%2 == 0: RHS_input = "k_even_gfs" RHS_output = "k_odd_gfs" else: RHS_input = "k_odd_gfs" RHS_output = "k_even_gfs" RK_lhs_list = [] RK_rhs_list = [] if s != num_steps-1: # For anything besides the final step if s == 0: # The first RK step RK_lhs_list.append(y_nplus1_running_total) RK_rhs_list.append(RHS_output+"[i]*dt*("+sp.ccode(Butcher[num_steps][s+1]).replace("L","")+")") RK_lhs_list.append(RHS_output) RK_rhs_list.append(y_n+"[i] + "+RHS_output+"[i]*dt*("+sp.ccode(Butcher[s+1][s+1]).replace("L","")+")") else: if Butcher[num_steps][s+1] !=0: RK_lhs_list.append(y_nplus1_running_total) if Butcher[num_steps][s+1] !=1: RK_rhs_list.append(y_nplus1_running_total+"[i] + "+RHS_output+"[i]*dt*("+sp.ccode(Butcher[num_steps][s+1]).replace("L","")+")") else: RK_rhs_list.append(y_nplus1_running_total+"[i] + "+RHS_output+"[i]*dt") if Butcher[s+1][s+1] !=0: RK_lhs_list.append(RHS_output) if Butcher[s+1][s+1] !=1: RK_rhs_list.append(y_n+"[i] + "+RHS_output+"[i]*dt*("+sp.ccode(Butcher[s+1][s+1]).replace("L","")+")") else: RK_rhs_list.append(y_n+"[i] + "+RHS_output+"[i]*dt") post_RHS_output = RHS_output if s == num_steps-1: # If on the final step if Butcher[num_steps][s+1] != 0: RK_lhs_list.append(y_n) if Butcher[num_steps][s+1] != 1: RK_rhs_list.append(y_n+"[i] + "+y_nplus1_running_total+"[i] + "+RHS_output+"[i]*dt*("+sp.ccode(Butcher[num_steps][s+1]).replace("L","")+")") else: RK_rhs_list.append(y_n+"[i] + "+y_nplus1_running_total+"[i] + "+RHS_output+"[i]*dt)") post_RHS_output = y_n RK_str += single_RK_substep( commentblock="// ***k" + str(s + 1) + " substep:***", RHS_str=RHS_string, RHS_input_str=RHS_input, RHS_output_str=RHS_output, RK_lhss_list=RK_lhs_list, RK_rhss_list=RK_rhs_list, post_RHS_list=[post_RHS_string], post_RHS_output_list=[post_RHS_output]) with open(os.path.join(outdir,"RK_MoL.h"), "w") as file: file.write(RK_str) ####### Step 3.b.iii: Freeing Allocated Memory free_allocated_memory(outdir,RK_method,malloced_gridfunctions)
malloc_gfs_str
test_estimators.py
"""Template unit tests for scikit-learn estimators.""" import pytest from sklearn.datasets import load_iris import geomstats.backend as gs import geomstats.tests from geomstats.learning._template import ( TemplateClassifier, TemplateEstimator, TemplateTransformer, ) ESTIMATORS = (TemplateClassifier, TemplateEstimator, TemplateTransformer) class TestEstimators(geomstats.tests.TestCase): _multiprocess_can_split_ = True def setup_method(self): self.data = load_iris(return_X_y=True) @geomstats.tests.np_and_autograd_only def test_template_estimator(self): est = TemplateEstimator() self.assertEqual(est.demo_param, "demo_param") X, y = self.data est.fit(X, y) self.assertTrue(hasattr(est, "is_fitted_")) y_pred = est.predict(X) self.assertAllClose(y_pred, gs.ones(gs.shape(X)[0])) @geomstats.tests.np_and_autograd_only def test_template_transformer_error(self): X, _ = self.data n_samples = gs.shape(X)[0] trans = TemplateTransformer() trans.fit(X) X_diff_size = gs.ones((n_samples, gs.shape(X)[1] + 1)) with pytest.raises(ValueError): trans.transform(X_diff_size) def test_template_transformer(self): X, _ = self.data trans = TemplateTransformer() self.assertTrue(trans.demo_param == "demo") trans.fit(X) self.assertTrue(trans.n_features_ == X.shape[1])
X_trans = trans.fit_transform(X) self.assertAllClose(X_trans, gs.sqrt(X)) @geomstats.tests.np_autograd_and_tf_only def test_template_classifier(self): X, y = self.data clf = TemplateClassifier() self.assertTrue(clf.demo_param == "demo") clf.fit(X, y) self.assertTrue(hasattr(clf, "classes_")) self.assertTrue(hasattr(clf, "X_")) self.assertTrue(hasattr(clf, "y_")) y_pred = clf.predict(X) self.assertTrue(y_pred.shape == (X.shape[0],))
X_trans = trans.transform(X) self.assertAllClose(X_trans, gs.sqrt(X))
msk_test.py
import logging import sys
import datetime import unittest import spot_db from spot_msk import SpotMsk import json, requests import logging, logging.config, yaml logging.config.dictConfig(yaml.load(open('logging.conf'))) logfl = logging.getLogger('file') logconsole = logging.getLogger('console') logfl.debug("Debug FILE") logconsole.debug("Debug CONSOLE") class TestAccess(unittest.TestCase): def echo_elapsed_time(self): elapsed = time.time() - self._started_at elapsed_step = time.time() - self._step_started_at self._total_steps_cnt += 1.0 self._total_steps_elapsed += elapsed_step avg_elapsed = self._total_steps_elapsed / self._total_steps_cnt logging.info("total_elapsed=" + str(round(elapsed, 2)) + " step_elapsed=" + str(round(elapsed_step, 2)) + " avg_elapsed=" + str(round(avg_elapsed, 2))) def echo(self,r): logging.info("response=" + str(r)) logging.info("response.headers=" + str(r.headers)) logging.info("response.text=" + str(r.text)) self.echo_elapsed_time() @classmethod def setUpClass(self): self._started_at = time.time() self._total_steps_cnt = 0 self._total_steps_elapsed = 0 self.msk = SpotMsk() logging.info('executing setUpClass') def test_00_msk_parking(self): self.msk.get_datasets() def test_01_msk_622(self): self.msk.traverse_dataset(622) def test_01_parking_datasets(self): dss = self.msk.get_datasets() cnt = 0 for ds in sorted(dss): cnt += self.msk.traverse_dataset(ds) logging.info('total datasets '+str(cnt)) @classmethod def tearDownClass(self): logging.info('executing tearDownClass') self._step_started_at = time.time() elapsed = time.time() - self._started_at elapsed_step = time.time() - self._step_started_at self._total_steps_cnt += 1.0 self._total_steps_elapsed += elapsed_step avg_elapsed = self._total_steps_elapsed / self._total_steps_cnt logging.info("total_elapsed=" + str(round(elapsed, 2)) + " step_elapsed=" + str(round(elapsed_step, 2)) + " avg_elapsed=" + str(round(avg_elapsed, 2))) logging.info('executed tearDownClass') if __name__ == '__main__': unittest.main()
import time
other.py
""" Created on Fri Oct 29 18:54:18 2021 @author: Krishna Nuthalapati """ import numpy as np def
(boxA, boxB): # determine the (x, y)-coordinates of the intersection rectangle xA = max(boxA[0], boxB[0]) yA = max(boxA[1], boxB[1]) xB = min(boxA[2], boxB[2]) yB = min(boxA[3], boxB[3]) # compute the area of intersection rectangle interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1) # compute the area of both the prediction and ground-truth # rectangles boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1) boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1) # compute the intersection over union by taking the intersection # area and dividing it by the sum of prediction + ground-truth # areas - the interesection area iou_score = interArea / float(boxAArea + boxBArea - interArea) # return the intersection over union value return iou_score def nms(boxes, scores, thresh): num_boxes = boxes.shape[0] indices = np.zeros((num_boxes), dtype=int) # print("PRINTING : ", num_boxes) for i in range(num_boxes): if indices[i] == -1: continue for j in range(i+1, num_boxes): if indices[j] == -1: continue base_box = boxes[i] curr_box = boxes[j] iou_score = iou(base_box, curr_box) if iou_score >= thresh: if scores[i]>scores[j]: indices[i] = 1 indices[j] = -1 continue indices[j] = 1 indices[i] = -1 idxs = np.where(indices == 1)[0] return idxs
iou
environment.ts
import fs from 'fs'; import { exec } from "../../helpers/utils/exec"; import AutheliaServer from "../../helpers/context/AutheliaServer"; import DockerEnvironment from "../../helpers/context/DockerEnvironment"; const autheliaServer = new AutheliaServer(__dirname + '/config.yml', [__dirname + '/users_database.yml']); const dockerEnv = new DockerEnvironment([ 'docker-compose.yml', 'example/compose/nginx/backend/docker-compose.yml', 'example/compose/nginx/portal/docker-compose.yml', 'example/compose/squid/docker-compose.yml', 'example/compose/smtp/docker-compose.yml', ]) async function setup() { await exec(`cp ${__dirname}/users_database.yml ${__dirname}/users_database.test.yml`); await exec('mkdir -p /tmp/authelia/db'); await exec('./example/compose/nginx/portal/render.js ' + (fs.existsSync('.suite') ? '': '--production')); await dockerEnv.start(); await autheliaServer.start(); } async function
() { await autheliaServer.stop(); await dockerEnv.stop(); await exec('rm -rf /tmp/authelia/db'); } const setup_timeout = 30000; const teardown_timeout = 30000; export { setup, setup_timeout, teardown, teardown_timeout };
teardown
mod.rs
pub mod uac_tests; pub mod uas_tests; use crate::common::snitches::{CoreSnitch, TransportSnitch}; use sip_server::{core::impls::UserAgent, SipBuilder, SipManager, Transaction, CoreLayer}; use std::sync::Arc; async fn
() -> Arc<SipManager> { SipBuilder::new::<CoreSnitch, Transaction, TransportSnitch>() .expect("sip manager failed") .manager } /* pub struct TypedSipManager<'a> { core: Arc<&'a CoreSnitch>, /* transaction: &'b Transaction, transport: &'c TransportSnitch, */ sip_manager: Arc<SipManager>, } impl From<Arc<SipManager>> for TypedSipManager<'_> { fn from(sip_manager: Arc<SipManager>) -> Self { /* let transport = sip_manager.transport.clone(); let transport = as_any!(transport, TransportSnitch); let transaction = sip_manager.transaction.clone(); let transaction = as_any!(transaction, Transaction); */ let core_match: Option<&CoreSnitch> = sip_manager.core.clone().as_any().clone().downcast_ref::<CoreSnitch>(); let core: Arc<&CoreSnitch> = match core_match { Some(concrete_type) => Arc::new(concrete_type), None => { panic!("cant't cast value!"); } }; Self { core, sip_manager, } } }*/
setup
GraphUNet.py
import os import sys sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) import torch.nn as nn import torch.nn.functional as F #from layers.graph_convolution_layer import GraphConvolutionLayer from layers.graph_unet_layer import GraphUNetLayer from readouts.basic_readout import readout_function """ Base paper: https://arxiv.org/pdf/1905.05178.pdf """ class GraphUNet(nn.Module): def
(self, n_feat, n_class, n_layer, agg_hidden, fc_hidden, dropout, readout, device): super(GraphUNet, self).__init__() self.n_layer = n_layer self.readout = readout # Pooling_rate pooling_rations = [0.8 - (i * 0.1) if i < 3 else 0.5 for i in range(n_layer)] # Graph unet layer self.graph_unet_layers = [] for i in range(n_layer): if i == 0: self.graph_unet_layers.append(GraphUNetLayer(n_feat, agg_hidden, pooling_rations[i], device)) else: self.graph_unet_layers.append(GraphUNetLayer(agg_hidden, agg_hidden, pooling_rations[i], device)) # Fully-connected layer self.fc1 = nn.Linear(agg_hidden, fc_hidden) self.fc2 = nn.Linear(fc_hidden, n_class) def forward(self, data): for i in range(self.n_layer): # Graph unet layer data = self.graph_unet_layers[i](data) x = data[0] # Dropout if i != self.n_layer - 1: x = F.dropout(x, p=self.dropout, training=self.training) # Readout x = readout_function(x, self.readout) # Fully-connected layer x = F.relu(self.fc1(x)) x = F.softmax(self.fc2(x)) return x def __repr__(self): layers = '' for i in range(self.n_layer): layers += str(self.graph_unet_layers[i]) + '\n' layers += str(self.fc1) + '\n' layers += str(self.fc2) + '\n' return layers
__init__
Shortcuts.js
import React from 'react'; import { Modal } from './Modal'; import { makeStyles } from '@material-ui/core/styles'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; const createData = (key, description) => ({ key, description }); const rows = [ createData('ctrl ↑', 'Rotate up'), createData('ctrl ↓', 'Rotate down'), createData('ctrl ←', 'Rotate left'),
createData('-', 'Zoom out'), createData('l', 'Rotate to selected country'), createData('r', 'Select random country'), createData('w', 'Show/hide widgets'), createData('ctrl /', 'Show/hide shortcuts'), ]; const useStyles = makeStyles({ table: { minWidth: 300, }, cellKey: { fontFamily: 'monospace', fontSize: '1.1rem', }, }); const ShortcutsTable = () => { const classes = useStyles(); return ( <TableContainer component={Paper}> <Table className={classes.table} aria-label="Shortcuts table"> <TableHead> <TableRow> <TableCell>Key</TableCell> <TableCell>Description</TableCell> </TableRow> </TableHead> <TableBody> {rows.map(row => ( <TableRow key={row.key}> <TableCell align="center" className={classes.cellKey}> {row.key} </TableCell> <TableCell align="left">{row.description}</TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> ); }; export const Shortcuts = ({ show, onClose }) => { return ( <Modal show={show} onClose={onClose}> <ShortcutsTable /> </Modal> ); };
createData('ctrl →', 'Rotate right'), createData('+', 'Zoom in'),
1080p_074.ts
version https://git-lfs.github.com/spec/v1 oid sha256:2eefddd929860bbbd932a63764eb951be283f05eb37f51ddf49406099e89d6fc
size 2447196
0105_aww_incentive_report_monthly.py
# Generated by Django 1.11.16 on 2019-03-12 10:52 from corehq.sql_db.operations import RawSQLMigration from django.db import migrations from custom.icds_reports.const import SQL_TEMPLATES_ROOT migrator = RawSQLMigration((SQL_TEMPLATES_ROOT, 'database_views')) class Migration(migrations.Migration):
dependencies = [ ('icds_reports', '0104_agg_ls_monthly_ls_name'), ] operations = [ migrator.get_migration('aww_incentive_report_monthly.sql'), ]