file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
matrix.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2020 Alibaba Group Holding Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np from collections.abc import Iterable from .core import issparse, get_array_module, cp, cps, \ get_sparse_module, naked, sps, splinalg from .array import SparseNDArray, SparseArray def zeros_sparse_matrix(shape, dtype=float, gpu=False): m = sps if not gpu else cps return SparseMatrix(m.csr_matrix(shape, dtype=np.dtype(dtype))) def diag_sparse_matrix(v, k=0, gpu=False): v = naked(v) if gpu and get_array_module(v) is not cp: v = cp.asarray(v) if not gpu and get_array_module(v) is not np: v = v.get() if v.ndim == 1: sparse_m = sps if not gpu else cps m = n = v.size + k mat = sparse_m.spdiags(v[None], [k], m, n, format='csr') return SparseMatrix(mat) else: assert v.ndim == 2 sparse_m = sps if not gpu else cps sparse_eye = sparse_m.eye(v.shape[0], v.shape[1], k=k) mat = sparse_eye.multiply(v).tocoo() size = sparse_eye.nnz col = mat.col - max(k, 0) row = get_array_module(col).zeros((len(col),)) return SparseNDArray(sparse_m.csr_matrix((mat.data, (row, col)), shape=(1, size)), shape=(size,)) def eye_sparse_matrix(N, M=None, k=0, dtype=float, gpu=False): m = sps if not gpu else cps return SparseMatrix(m.eye(N, n=M, k=k, dtype=dtype, format='csr')) def triu_sparse_matrix(m, k=0, gpu=False): m = naked(m) if gpu and get_array_module(m) is not cp: m = cp.asarray(m) if not gpu and get_array_module(m) is not np: m = m.get() sparse_m = sps if not gpu else cps mat = sparse_m.triu(m, k=k) return SparseMatrix(mat) def tril_sparse_matrix(m, k=0, gpu=False): m = naked(m) if gpu and get_array_module(m) is not cp: m = cp.asarray(m) if not gpu and get_array_module(m) is not np: m = m.get() sparse_m = sps if not gpu else cps mat = sparse_m.tril(m, k=k) return SparseMatrix(mat) def where(cond, x, y): cond, x, y = [SparseMatrix(i) if issparse(i) else i for i in (cond, x, y)] return cond * x + (cond * (-y) + y) def lu_sparse_matrix(a): a = naked(a) a = a.tocsc() super_lu = splinalg.splu(a, permc_spec="NATURAL", diag_pivot_thresh=0, options={"SymmetricMode": True}) l = super_lu.L u = super_lu.U p = sps.lil_matrix(a.shape) p[super_lu.perm_r.copy(), np.arange(a.shape[1])] = 1 return SparseMatrix(p), SparseMatrix(l), SparseMatrix(u), def solve_triangular_sparse_matrix(a, b, lower=False, sparse=True): a = naked(a) b = b.toarray() if issparse(b) else b x = splinalg.spsolve_triangular(a, b, lower=lower) if sparse: spx = sps.csr_matrix(x).reshape(x.shape[0], 1) if len(x.shape) == 1 else sps.csr_matrix(x) return SparseNDArray(spx, shape=x.shape) else: return x class SparseMatrix(SparseArray): __slots__ = 'spmatrix', def __init__(self, spmatrix, shape=()): if shape and len(shape) != 2: raise ValueError('Only accept 2-d array') if isinstance(spmatrix, SparseMatrix): self.spmatrix = spmatrix.spmatrix else: self.spmatrix = spmatrix.tocsr() @property def shape(self): return self.spmatrix.shape def transpose(self, axes=None): assert axes is None or tuple(axes) == (1, 0) return SparseMatrix(self.spmatrix.transpose()) @property def T(self): return SparseMatrix(self.spmatrix.T) def dot(self, other, sparse=True): other_shape = other.shape try: other = naked(other) except TypeError: return NotImplemented if sparse: if len(other_shape) == 1: x = self.spmatrix.dot(other.T) else: x = self.spmatrix.dot(other) else: a = self.spmatrix.toarray() if issparse(other): other = other.toarray().reshape(other_shape) x = a.dot(other) if issparse(x): shape = (x.shape[0],) if len(other_shape) == 1 else x.shape return SparseNDArray(x, shape=shape) return get_array_module(x).asarray(x) def concatenate(self, other, axis=0): try: other = naked(other) except TypeError: return NotImplemented if issparse(other): xps = get_sparse_module(self.spmatrix) if axis not in (0, 1): raise ValueError('axis can only be 0 or 1') method = xps.vstack if axis == 0 else xps.hstack x = method((self.spmatrix, other)) else: xp = get_array_module(self.spmatrix) x = xp.concatenate((self.spmatrix.toarray(), other), axis=axis) if issparse(x): return SparseMatrix(x) return get_array_module(x).asarray(x) def _reduction(self, method_name, axis=None, dtype=None, keepdims=None, todense=False, **kw): # TODO: support keepdims
if isinstance(axis, tuple): if sorted(axis) != [0, 1]: assert len(axis) == 1 axis = axis[0] else: axis = None if todense: x = self.spmatrix.toarray() x = getattr(get_array_module(x), method_name)(x, axis=axis, **kw) else: x = getattr(self.spmatrix, method_name)(axis=axis, **kw) if not isinstance(axis, Iterable): axis = (axis,) axis = list(range(len(self.shape))) if axis is None else axis shape = tuple(s if i not in axis else 1 for i, s in enumerate(self.shape) if keepdims or i not in axis) m = get_array_module(x) if issparse(x): return SparseNDArray(x, shape=shape) if m.isscalar(x): if keepdims: return m.array([x])[0].reshape((1,) * self.ndim) else: return m.array([x])[0] else: return m.asarray(x).reshape(shape)
markdown-to-html.ts
import marked from 'marked'; import glob from 'glob'; import { promisify } from 'util'; import path from 'path'; import fs from 'fs'; import url from 'url'; import { rimraf, mkdirp } from '@stencil/utils'; import { collectHeadingMetadata, changeCodeCreation, localizeMarkdownLink } from './markdown-renderer'; import frontMatter from 'front-matter'; import fetch from 'node-fetch'; import { SiteStructureItem, MarkdownContent } from '../src/global/definitions'; const readFile = promisify(fs.readFile); const writeFile = promisify(fs.writeFile); const globAsync = promisify(glob); const DESTINATION_DIR = './src/assets/docs'; const SOURCE_DIR = './src/docs'; const SITE_STRUCTURE_FILE= './src/assets/docs-structure.json'; (async function() { const siteStructure = await readFile(SITE_STRUCTURE_FILE, { encoding: 'utf8' }); const siteStructureJson: SiteStructureItem[] = JSON.parse(siteStructure); console.log(`running glob: ${SOURCE_DIR}/**/*.md`); const files = await globAsync(`${SOURCE_DIR}/**/*.md`, {}); await rimraf(DESTINATION_DIR); const filePromises = files.map(async (filePath) => { if (filePath === './src/docs/README.md') { return Promise.resolve(); } let htmlContents = ''; let markdownMetadata: MarkdownContent = {}; const jsonFileName = path.relative(SOURCE_DIR, filePath); const destinationFileName = path.join( DESTINATION_DIR, path.dirname(jsonFileName), path.basename(jsonFileName, '.md') + '.json' ); markdownMetadata.headings = []; const markdownContents = await readFile(filePath, { encoding: 'utf8' }); try { let parsedMarkdown = frontMatter(markdownContents); parsedMarkdown = await getGithubData(filePath, parsedMarkdown); const renderer = new marked.Renderer(); collectHeadingMetadata(renderer, markdownMetadata); changeCodeCreation(renderer); localizeMarkdownLink(renderer, destinationFileName.replace('src',''), siteStructureJson); htmlContents = marked(parsedMarkdown.body, { renderer, headerIds: true }); await mkdirp(path.join( DESTINATION_DIR, path.dirname(jsonFileName) )); await writeFile(destinationFileName, JSON.stringify({ ...parsedMarkdown.attributes, ...markdownMetadata, srcPath: filePath, content: htmlContents }), { encoding: 'utf8' }); } catch (e) { console.error(filePath); throw e; } }); await Promise.all(filePromises); console.log(`successfully converted ${filePromises.length} files`); })(); async function getGithubData(filePath: string, parsedMarkdown: any) { const since = new Date('2018-06-01').toISOString(); try { const request = await fetch(url.format({
pathname: 'repos/ionic-team/stencil-site/commits', query: { access_token: process.env.GITHUB_TOKEN, since: since, path: filePath } })); const commits = await request.json(); const contributors = Array.from(new Set(commits.map(commit => commit.author.login))); const lastUpdated = commits.length ? commits[0].commit.author.date : since; const attributes = parsedMarkdown.attributes = parsedMarkdown.attributes || {}; attributes.lastUpdated = lastUpdated; attributes.contributors = attributes.contributors || []; contributors.forEach(contributor => { if (!attributes.contributors.includes(contributor)) { attributes.contributors.push(contributor); } }); console.log('filePath:', filePath, 'contributors:', attributes.contributors.length, 'lastUpdated:', lastUpdated); } catch (e) { console.log(e); } return parsedMarkdown; }
protocol: 'https', hostname: 'api.github.com',
general.py
from collections.abc import Callable import warnings import numpy as np from scipy.optimize import fsolve from ..core import Function, find_roots, ConstantFunction from ..eigenfunctions import SecondOrderOperator from ..placeholder import (ScalarFunction, TestFunction, FieldVariable, ScalarTerm, IntegralTerm, Input, Product) from ..simulation import WeakFormulation __all__ = ["compute_rad_robin_eigenfrequencies", "eliminate_advection_term", "get_parabolic_dirichlet_weak_form", "get_parabolic_robin_weak_form", "get_in_domain_transformation_matrix"] def compute_rad_robin_eigenfrequencies(param, l, n_roots=10, show_plot=False): r""" Return the first :code:`n_roots` eigenfrequencies :math:`\omega` (and eigenvalues :math:`\lambda`) .. math:: \omega = \sqrt{-\frac{a_1^2}{4a_2^2}+\frac{a_0-\lambda}{a_2}} to the eigenvalue problem .. math:: a_2\varphi''(z) + a_1&\varphi'(z) + a_0\varphi(z) = \lambda\varphi(z) \\ \varphi'(0) &= \alpha\varphi(0) \\ \varphi'(l) &= -\beta\varphi(l). Args: param (array_like): :math:`\Big( a_2, a_1, a_0, \alpha, \beta \Big)^T` l (numbers.Number): Right boundary value of the domain :math:`[0,l]\ni z`. n_roots (int): Amount of eigenfrequencies to be compute. show_plot (bool): A plot window of the characteristic equation appears if it is :code:`True`. Return: tuple --> two numpy.ndarrays of length :code:`nroots`: .. math:: \Big(\big[\omega_1,...,\omega_\text{n\_roots}\Big], \Big[\lambda_1,...,\lambda_\text{n\_roots}\big]\Big) """ a2, a1, a0, alpha, beta = param eta = -a1 / 2. / a2 def characteristic_equation(om): if np.round(om, 200) != 0.: zero = (alpha + beta) * np.cos(om * l) + ((eta + beta) * (alpha - eta) / om - om) * np.sin(om * l) else: zero = (alpha + beta) * np.cos(om * l) + (eta + beta) * (alpha - eta) * l - om * np.sin(om * l) return zero def complex_characteristic_equation(om): if np.round(om, 200) != 0.: zero = (alpha + beta) * np.cosh(om * l) + ((eta + beta) * (alpha - eta) / om + om) * np.sinh(om * l) else: zero = (alpha + beta) * np.cosh(om * l) + (eta + beta) * (alpha - eta) * l + om * np.sinh(om * l) return zero # assume 1 root per pi/l (safety factor = 3) om_end = 3 * n_roots * np.pi / l start_values = np.arange(0, om_end, .1) om = find_roots(characteristic_equation, start_values, 2 * n_roots, rtol=l*1e-6).tolist() # delete all around om = 0 om.reverse() for i in range(np.sum(np.array(om) < np.pi / l / 2e1)): om.pop() om.reverse() # if om = 0 is a root then add 0 to the list zero_limit = alpha + beta + (eta + beta) * (alpha - eta) * l if np.round(zero_limit, 6 + int(np.log10(l))) == 0.: om.insert(0, 0.) # regard complex roots om_squared = np.power(om, 2).tolist() complex_root = fsolve(complex_characteristic_equation, om_end) if np.round(complex_root, 6 + int(np.log10(l))) != 0.: om_squared.insert(0, -complex_root[0] ** 2) # basically complex eigenfrequencies om = np.sqrt(np.array(om_squared).astype(complex)) if len(om) < n_roots: raise ValueError("RadRobinEigenvalues.compute_eigen_frequencies()" "can not find enough roots") eig_frequencies = om[:n_roots] eig_values = a0 - a2 * eig_frequencies ** 2 - a1 ** 2 / 4. / a2 return eig_frequencies, eig_values def eliminate_advection_term(param, domain_end): r""" This method performs a transformation .. math:: \tilde x(z,t)=x(z,t) e^{\int_0^z \frac{a_1(\bar z)}{2 a_2}\,d\bar z} , on the system, which eliminates the advection term :math:`a_1 x(z,t)` from a reaction-advection-diffusion equation of the type: .. math:: \dot x(z,t) = a_2 x''(z,t) + a_1(z) x'(z,t) + a_0(z) x(z,t) . The boundary can be given by robin .. math:: x'(0,t) = \alpha x(0,t), \quad x'(l,t) = -\beta x(l,t) , dirichlet .. math:: x(0,t) = 0, \quad x(l,t) = 0 or mixed boundary conditions. Args: param (array_like): :math:`\Big( a_2, a_1, a_0, \alpha, \beta \Big)^T` domain_end (float): upper bound of the spatial domain Raises: TypeError: If :math:`a_1(z)` is callable but no derivative handle is defined for it. Return: SecondOrderOperator or tuple: Parameters .. math:: \big(a_2, \tilde a_1=0, \tilde a_0(z), \tilde \alpha, \tilde \beta \big) for the transformed system .. math:: \dot{\tilde{x}}(z,t) = a_2 \tilde x''(z,t) + \tilde a_0(z) \tilde x(z,t) and the corresponding boundary conditions (:math:`\alpha` and/or :math:`\beta` set to None by dirichlet boundary condition). """ # TODO remove this compatibility wrapper and promote use of new Operator # class over the entire toolbox. if isinstance(param, SecondOrderOperator): a2 = param.a2 a1 = param.a1 a0 = param.a0 alpha = -param.alpha0 beta = param.beta0 else: if not isinstance(param, (tuple, list)) or not len(param) == 5: raise TypeError("pyinduct.utils.transform_2_intermediate(): " "argument param must from type tuple or list") a2, a1, a0, alpha, beta = param if isinstance(a1, Function): if not isinstance(a0, Callable): a0_z = ConstantFunction(a0) else: a0_z = a0 def a0_n(z): return a0_z(z) - a1(z) ** 2 / 4 / a2 - a1.derive(1)(z) / 2 else: a0_n = a0 - a1 ** 2 / 4 / a2 if alpha is None: alpha_n = None elif isinstance(a1, Callable): alpha_n = a1(0) / 2. / a2 + alpha else: alpha_n = a1 / 2. / a2 + alpha if beta is None: beta_n = None elif isinstance(a1, Function): beta_n = -a1(domain_end) / 2. / a2 + beta else: beta_n = -a1 / 2. / a2 + beta a2_n = a2 a1_n = 0 # TODO see above. if isinstance(param, SecondOrderOperator): return SecondOrderOperator(a2=a2_n, a1=0, a0=a0_n, alpha1=param.beta1, alpha0=-alpha_n, beta1=param.beta1, beta0=beta_n) else: return a2_n, a1_n, a0_n, alpha_n, beta_n def get_parabolic_dirichlet_weak_form(init_func_label, test_func_label, input_handle, param, spatial_domain):
def get_parabolic_robin_weak_form(shape_base_label, test_base_label, input_handle, param, spatial_domain, actuation_type_point=None): r""" Provide the weak formulation for the diffusion system with advection term, reaction term, robin boundary condition and robin actuation. .. math:: :nowrap: \begin{align*} \dot x(z,t) &= a_2 x''(z,t) + a_1(z) x'(z,t) + a_0(z) x(z,t), && z\in (0, l) \\ x'(0,t) &= \alpha x(0,t) \\ x'(l,t) &= -\beta x(l,t) + u(t) \end{align*} Args: shape_base_label (str): State space base label test_base_label (str): Test base label input_handle (:py:class:`.SimulationInput`): System input param (array-like): List of parameters: - :math:`a_2` (numbers.Number) ~ diffusion coefficient - :math:`a_1(z)` (callable) ~ advection coefficient - :math:`a_0(z)` (callable) ~ reaction coefficient - :math:`\alpha, \beta` (numbers.Number) ~ constants for robin boundary conditions spatial_domain (tuple): Limits of the spatial domain :math:`(0,l) \ni z` actuation_type_point (numbers.number): Here you can shift the point of actuation from :math:`z=l` to a other point in the spatial domain. Returns: tuple: - :py:class:`.WeakFormulation` - strings for the created base lables for the advection and reaction coefficient """ if actuation_type_point is None: actuation_type_point = spatial_domain[1] a2, a1, a0, alpha, beta = param l = spatial_domain[1] # init ScalarFunction for a1 and a0 to handle spatially varying coefficients created_base_labels = (shape_base_label + "a0_z", shape_base_label + "a1_z") a0_z = ScalarFunction.from_scalar(a0, created_base_labels[0]) a1_z = ScalarFunction.from_scalar(a1, created_base_labels[1]) x = FieldVariable(shape_base_label) x_dt = x.derive(temp_order=1) x_dz = x.derive(spat_order=1) psi = TestFunction(test_base_label, order=0) psi_dz = psi.derive(1) # integral terms int1 = IntegralTerm(Product(x_dt, psi), spatial_domain) int2 = IntegralTerm(Product(x_dz, psi_dz), spatial_domain, a2) int3 = IntegralTerm(Product(Product(x_dz, a1_z), psi), spatial_domain, -1) int4 = IntegralTerm(Product(Product(x, a0_z), psi), spatial_domain, -1) # scalar terms s1 = ScalarTerm(Product(x(0), psi(0)), a2 * alpha) s2 = ScalarTerm(Product(x(l), psi(l)), a2 * beta) terms = [int1, int2, int3, int4, s1, s2] # consider input if given if input_handle is not None: terms.append(ScalarTerm( Product(Input(input_handle), psi(actuation_type_point)), -a2)) # derive state-space system weak_form = WeakFormulation( terms, name="parabolic_robin_{}_{}".format(param, shape_base_label)) return weak_form, created_base_labels def get_in_domain_transformation_matrix(k1, k2, mode='n_plus_1'): r""" Returns the transformation matrix M. M is one part of a transformation .. math:: x = My + Ty where x is the field variable of an interior point controlled parabolic system and y is the field variable of an boundary controlled parabolic system. T is a (Fredholm-) integral transformation (which can be approximated with M). Args: k1: k2: mode: Available modes - `n_plus_1`: M.shape = :math:`(n+1,n+1), w = (w(0),...,w(n))^T, w \in {x,y}` - `2n`: M.shape = (2n,2n), :math:`w = (w(0),...,w(n),...,w(1))^T, w \in {x,y}` Return: numpy.array: Transformation matrix M. """ if not all(isinstance(i, (int, float)) for i in [k1, k2]): raise TypeError("TypeErrorMessage") if not all(i % 1 == 0 for i in [k1, k2]): raise TypeError("TypeErrorMessage") n = k1 + k2 if k1 + k2 != n or n < 2 or k1 < 0 or k2 < 0: raise ValueError("The sum of two positive integers k1 and k2 must be n.") if (k1 != 0 and k2 != 0) and n % 2 == 0: warnings.warn("Transformation matrix M is not invertible.") mod_diag = lambda n, k: np.diag(np.ones(n - np.abs(k)), k) if mode == 'n_plus_1': M = np.zeros((n + 1, n + 1)) if k2 < n: M += mod_diag(n + 1, k2) + mod_diag(n + 1, -k2) if k2 != 0: M += np.fliplr(mod_diag(n + 1, n - k2) + mod_diag(n + 1, -n + k2)) elif mode == '2n': M = mod_diag(2 * n, k2) + mod_diag(2 * n, -k2) + mod_diag(2 * n, n + k1) + mod_diag(2 * n, -n - k1) else: raise ValueError("String in variable 'mode' not understood.") return M * 0.5
""" Return the weak formulation of a parabolic 2nd order system, using an inhomogeneous dirichlet boundary at both sides. Args: init_func_label(str): Label of shape base to use. test_func_label(str): Label of test base to use. input_handle(:py:class:`.SimulationInput`): Input. param(tuple): Parameters of the spatial operator. spatial_domain(tuple): Spatial domain of the problem. # spatial_domain(:py:class:`.Domain`): Spatial domain of the # problem. Returns: :py:class:`.WeakFormulation`: Weak form of the system. """ a2, a1, a0, alpha, beta = param l = spatial_domain[1] x = FieldVariable(init_func_label) x_dt = x.derive(temp_order=1) x_dz = x.derive(spat_order=1) x_ddz = x.derive(spat_order=2) psi = TestFunction(test_func_label) psi_dz = psi.derive(1) psi_ddz = psi.derive(2) # integral terms int1 = IntegralTerm(Product(x_dt, psi), spatial_domain) int2 = IntegralTerm(Product(x, psi_ddz), spatial_domain, -a2) int2h = IntegralTerm(Product(x_ddz, psi), spatial_domain, -a2) int3 = IntegralTerm(Product(x, psi_dz), spatial_domain, a1) int4 = IntegralTerm(Product(x, psi), spatial_domain, -a0) if input_handle is None: # homogeneous case return WeakFormulation([int1, int2h, int3, int4], name="parabolic_dirichlet_hom") # scalar terms s1 = ScalarTerm(Product(Input(input_handle), psi_dz(l)), a2) s2 = ScalarTerm(Product(Input(input_handle), psi(l)), -a1) s3 = ScalarTerm(Product(x_dz(l), psi(l)), -a2) s4 = ScalarTerm(Product(x_dz(0), psi(0)), a2) return WeakFormulation([int1, int2, int3, int4, s1, s2, s3, s4], name="parabolic_dirichlet")
traceback.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 runtime import ( "runtime/internal/atomic" "runtime/internal/sys" "unsafe" ) // The code in this file implements stack trace walking for all architectures. // The most important fact about a given architecture is whether it uses a link register. // On systems with link registers, the prologue for a non-leaf function stores the // incoming value of LR at the bottom of the newly allocated stack frame. // On systems without link registers, the architecture pushes a return PC during // the call instruction, so the return PC ends up above the stack frame. // In this file, the return PC is always called LR, no matter how it was found. // // To date, the opposite of a link register architecture is an x86 architecture. // This code may need to change if some other kind of non-link-register // architecture comes along. // // The other important fact is the size of a pointer: on 32-bit systems the LR // takes up only 4 bytes on the stack, while on 64-bit systems it takes up 8 bytes. // Typically this is ptrSize. // // As an exception, amd64p32 has ptrSize == 4 but the CALL instruction still // stores an 8-byte return PC onto the stack. To accommodate this, we use regSize // as the size of the architecture-pushed return PC. // // usesLR is defined below in terms of minFrameSize, which is defined in // arch_$GOARCH.go. ptrSize and regSize are defined in stubs.go. const usesLR = sys.MinFrameSize > 0 var ( // initialized in tracebackinit goexitPC uintptr jmpdeferPC uintptr mcallPC uintptr morestackPC uintptr mstartPC uintptr rt0_goPC uintptr sigpanicPC uintptr runfinqPC uintptr bgsweepPC uintptr forcegchelperPC uintptr timerprocPC uintptr gcBgMarkWorkerPC uintptr systemstack_switchPC uintptr systemstackPC uintptr cgocallback_gofuncPC uintptr gogoPC uintptr externalthreadhandlerp uintptr // initialized elsewhere ) func tracebackinit() { // Go variable initialization happens late during runtime startup. // Instead of initializing the variables above in the declarations, // schedinit calls this function so that the variables are // initialized and available earlier in the startup sequence. goexitPC = funcPC(goexit) jmpdeferPC = funcPC(jmpdefer) mcallPC = funcPC(mcall) morestackPC = funcPC(morestack) mstartPC = funcPC(mstart) rt0_goPC = funcPC(rt0_go) sigpanicPC = funcPC(sigpanic) runfinqPC = funcPC(runfinq) bgsweepPC = funcPC(bgsweep) forcegchelperPC = funcPC(forcegchelper) timerprocPC = funcPC(timerproc) gcBgMarkWorkerPC = funcPC(gcBgMarkWorker) systemstack_switchPC = funcPC(systemstack_switch) systemstackPC = funcPC(systemstack) cgocallback_gofuncPC = funcPC(cgocallback_gofunc) // used by sigprof handler gogoPC = funcPC(gogo) } // Traceback over the deferred function calls. // Report them like calls that have been invoked but not started executing yet. func tracebackdefers(gp *g, callback func(*stkframe, unsafe.Pointer) bool, v unsafe.Pointer) { var frame stkframe for d := gp._defer; d != nil; d = d.link { fn := d.fn if fn == nil { // Defer of nil function. Args don't matter. frame.pc = 0 frame.fn = funcInfo{} frame.argp = 0 frame.arglen = 0 frame.argmap = nil } else { frame.pc = fn.fn f := findfunc(frame.pc) if !f.valid() { print("runtime: unknown pc in defer ", hex(frame.pc), "\n") throw("unknown pc") } frame.fn = f frame.argp = uintptr(deferArgs(d)) frame.arglen, frame.argmap = getArgInfo(&frame, f, true, fn) } frame.continpc = frame.pc if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) { return } } } // Generic traceback. Handles runtime stack prints (pcbuf == nil), // the runtime.Callers function (pcbuf != nil), as well as the garbage // collector (callback != nil). A little clunky to merge these, but avoids // duplicating the code and all its subtlety. func gentraceback(pc0, sp0, lr0 uintptr, gp *g, skip int, pcbuf *uintptr, max int, callback func(*stkframe, unsafe.Pointer) bool, v unsafe.Pointer, flags uint) int { if goexitPC == 0 { throw("gentraceback before goexitPC initialization") } g := getg() if g == gp && g == g.m.curg { // The starting sp has been passed in as a uintptr, and the caller may // have other uintptr-typed stack references as well. // If during one of the calls that got us here or during one of the // callbacks below the stack must be grown, all these uintptr references // to the stack will not be updated, and gentraceback will continue // to inspect the old stack memory, which may no longer be valid. // Even if all the variables were updated correctly, it is not clear that // we want to expose a traceback that begins on one stack and ends // on another stack. That could confuse callers quite a bit. // Instead, we require that gentraceback and any other function that // accepts an sp for the current goroutine (typically obtained by // calling getcallersp) must not run on that goroutine's stack but // instead on the g0 stack. throw("gentraceback cannot trace user goroutine on its own stack") } level, _, _ := gotraceback() if pc0 == ^uintptr(0) && sp0 == ^uintptr(0) { // Signal to fetch saved values from gp. if gp.syscallsp != 0 { pc0 = gp.syscallpc sp0 = gp.syscallsp if usesLR { lr0 = 0 } } else { pc0 = gp.sched.pc sp0 = gp.sched.sp if usesLR { lr0 = gp.sched.lr } } } nprint := 0 var frame stkframe frame.pc = pc0 frame.sp = sp0 if usesLR { frame.lr = lr0 } waspanic := false cgoCtxt := gp.cgoCtxt printing := pcbuf == nil && callback == nil _defer := gp._defer for _defer != nil && _defer.sp == _NoArgs { _defer = _defer.link } // If the PC is zero, it's likely a nil function call. // Start in the caller's frame. if frame.pc == 0 { if usesLR { frame.pc = *(*uintptr)(unsafe.Pointer(frame.sp)) frame.lr = 0 } else { frame.pc = uintptr(*(*sys.Uintreg)(unsafe.Pointer(frame.sp))) frame.sp += sys.RegSize } } f := findfunc(frame.pc) if !f.valid() { if callback != nil { print("runtime: unknown pc ", hex(frame.pc), "\n") throw("unknown pc") } return 0 } frame.fn = f var cache pcvalueCache n := 0 for n < max { // Typically: // pc is the PC of the running function. // sp is the stack pointer at that program counter. // fp is the frame pointer (caller's stack pointer) at that program counter, or nil if unknown. // stk is the stack containing sp. // The caller's program counter is lr, unless lr is zero, in which case it is *(uintptr*)sp. f = frame.fn if f.pcsp == 0 { // No frame information, must be external function, like race support. // See golang.org/issue/13568. break } // Found an actual function. // Derive frame pointer and link register. if frame.fp == 0 { // We want to jump over the systemstack switch. If we're running on the // g0, this systemstack is at the top of the stack. // if we're not on g0 or there's a no curg, then this is a regular call. sp := frame.sp if flags&_TraceJumpStack != 0 && f.entry == systemstackPC && gp == g.m.g0 && gp.m.curg != nil { sp = gp.m.curg.sched.sp frame.sp = sp cgoCtxt = gp.m.curg.cgoCtxt } frame.fp = sp + uintptr(funcspdelta(f, frame.pc, &cache)) if !usesLR { // On x86, call instruction pushes return PC before entering new function. frame.fp += sys.RegSize } } var flr funcInfo if topofstack(f) { frame.lr = 0 flr = funcInfo{} } else if usesLR && f.entry == jmpdeferPC { // jmpdefer modifies SP/LR/PC non-atomically. // If a profiling interrupt arrives during jmpdefer, // the stack unwind may see a mismatched register set // and get confused. Stop if we see PC within jmpdefer // to avoid that confusion. // See golang.org/issue/8153. if callback != nil { throw("traceback_arm: found jmpdefer when tracing with callback") } frame.lr = 0 } else { var lrPtr uintptr if usesLR { if n == 0 && frame.sp < frame.fp || frame.lr == 0 { lrPtr = frame.sp frame.lr = *(*uintptr)(unsafe.Pointer(lrPtr)) } } else { if frame.lr == 0 { lrPtr = frame.fp - sys.RegSize frame.lr = uintptr(*(*sys.Uintreg)(unsafe.Pointer(lrPtr))) } } flr = findfunc(frame.lr) if !flr.valid() { // This happens if you get a profiling interrupt at just the wrong time. // In that context it is okay to stop early. // But if callback is set, we're doing a garbage collection and must // get everything, so crash loudly. if callback != nil { print("runtime: unexpected return pc for ", funcname(f), " called from ", hex(frame.lr), "\n") throw("unknown caller pc") } } } frame.varp = frame.fp if !usesLR { // On x86, call instruction pushes return PC before entering new function. frame.varp -= sys.RegSize } // If framepointer_enabled and there's a frame, then // there's a saved bp here. if framepointer_enabled && GOARCH == "amd64" && frame.varp > frame.sp { frame.varp -= sys.RegSize } // Derive size of arguments. // Most functions have a fixed-size argument block, // so we can use metadata about the function f. // Not all, though: there are some variadic functions // in package runtime and reflect, and for those we use call-specific // metadata recorded by f's caller. if callback != nil || printing { frame.argp = frame.fp + sys.MinFrameSize frame.arglen, frame.argmap = getArgInfo(&frame, f, callback != nil, nil) } // Determine frame's 'continuation PC', where it can continue. // Normally this is the return address on the stack, but if sigpanic // is immediately below this function on the stack, then the frame // stopped executing due to a trap, and frame.pc is probably not // a safe point for looking up liveness information. In this panicking case, // the function either doesn't return at all (if it has no defers or if the // defers do not recover) or it returns from one of the calls to // deferproc a second time (if the corresponding deferred func recovers). // It suffices to assume that the most recent deferproc is the one that // returns; everything live at earlier deferprocs is still live at that one. frame.continpc = frame.pc if waspanic { if _defer != nil && _defer.sp == frame.sp { frame.continpc = _defer.pc } else { frame.continpc = 0 } } // Unwind our local defer stack past this frame. for _defer != nil && (_defer.sp == frame.sp || _defer.sp == _NoArgs) { _defer = _defer.link } if skip > 0 { skip-- goto skipped } if pcbuf != nil { (*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = frame.pc } if callback != nil { if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) { return n } } if printing { // assume skip=0 for printing if (flags&_TraceRuntimeFrames) != 0 || showframe(f, gp, nprint == 0) { // Print during crash. // main(0x1, 0x2, 0x3) // /home/rsc/go/src/runtime/x.go:23 +0xf // tracepc := frame.pc // back up to CALL instruction for funcline. if (n > 0 || flags&_TraceTrap == 0) && frame.pc > f.entry && !waspanic { tracepc-- } file, line := funcline(f, tracepc)
inldata := funcdata(f, _FUNCDATA_InlTree) if inldata != nil { inltree := (*[1 << 20]inlinedCall)(inldata) ix := pcdatavalue(f, _PCDATA_InlTreeIndex, tracepc, nil) for ix != -1 { name := funcnameFromNameoff(f, inltree[ix].func_) print(name, "(...)\n") print("\t", file, ":", line, "\n") file = funcfile(f, inltree[ix].file) line = inltree[ix].line ix = inltree[ix].parent } } name := funcname(f) if name == "runtime.gopanic" { name = "panic" } print(name, "(") argp := (*[100]uintptr)(unsafe.Pointer(frame.argp)) for i := uintptr(0); i < frame.arglen/sys.PtrSize; i++ { if i >= 10 { print(", ...") break } if i != 0 { print(", ") } print(hex(argp[i])) } print(")\n") print("\t", file, ":", line) if frame.pc > f.entry { print(" +", hex(frame.pc-f.entry)) } if g.m.throwing > 0 && gp == g.m.curg || level >= 2 { print(" fp=", hex(frame.fp), " sp=", hex(frame.sp)) } print("\n") nprint++ } } n++ skipped: if f.entry == cgocallback_gofuncPC && len(cgoCtxt) > 0 { ctxt := cgoCtxt[len(cgoCtxt)-1] cgoCtxt = cgoCtxt[:len(cgoCtxt)-1] // skip only applies to Go frames. // callback != nil only used when we only care // about Go frames. if skip == 0 && callback == nil { n = tracebackCgoContext(pcbuf, printing, ctxt, n, max) } } waspanic = f.entry == sigpanicPC // Do not unwind past the bottom of the stack. if !flr.valid() { break } // Unwind to next frame. frame.fn = flr frame.pc = frame.lr frame.lr = 0 frame.sp = frame.fp frame.fp = 0 frame.argmap = nil // On link register architectures, sighandler saves the LR on stack // before faking a call to sigpanic. if usesLR && waspanic { x := *(*uintptr)(unsafe.Pointer(frame.sp)) frame.sp += sys.MinFrameSize if GOARCH == "arm64" { // arm64 needs 16-byte aligned SP, always frame.sp += sys.PtrSize } f = findfunc(frame.pc) frame.fn = f if !f.valid() { frame.pc = x } else if funcspdelta(f, frame.pc, &cache) == 0 { frame.lr = x } } } if printing { n = nprint } // If callback != nil, we're being called to gather stack information during // garbage collection or stack growth. In that context, require that we used // up the entire defer stack. If not, then there is a bug somewhere and the // garbage collection or stack growth may not have seen the correct picture // of the stack. Crash now instead of silently executing the garbage collection // or stack copy incorrectly and setting up for a mysterious crash later. // // Note that panic != nil is okay here: there can be leftover panics, // because the defers on the panic stack do not nest in frame order as // they do on the defer stack. If you have: // // frame 1 defers d1 // frame 2 defers d2 // frame 3 defers d3 // frame 4 panics // frame 4's panic starts running defers // frame 5, running d3, defers d4 // frame 5 panics // frame 5's panic starts running defers // frame 6, running d4, garbage collects // frame 6, running d2, garbage collects // // During the execution of d4, the panic stack is d4 -> d3, which // is nested properly, and we'll treat frame 3 as resumable, because we // can find d3. (And in fact frame 3 is resumable. If d4 recovers // and frame 5 continues running, d3, d3 can recover and we'll // resume execution in (returning from) frame 3.) // // During the execution of d2, however, the panic stack is d2 -> d3, // which is inverted. The scan will match d2 to frame 2 but having // d2 on the stack until then means it will not match d3 to frame 3. // This is okay: if we're running d2, then all the defers after d2 have // completed and their corresponding frames are dead. Not finding d3 // for frame 3 means we'll set frame 3's continpc == 0, which is correct // (frame 3 is dead). At the end of the walk the panic stack can thus // contain defers (d3 in this case) for dead frames. The inversion here // always indicates a dead frame, and the effect of the inversion on the // scan is to hide those dead frames, so the scan is still okay: // what's left on the panic stack are exactly (and only) the dead frames. // // We require callback != nil here because only when callback != nil // do we know that gentraceback is being called in a "must be correct" // context as opposed to a "best effort" context. The tracebacks with // callbacks only happen when everything is stopped nicely. // At other times, such as when gathering a stack for a profiling signal // or when printing a traceback during a crash, everything may not be // stopped nicely, and the stack walk may not be able to complete. // It's okay in those situations not to use up the entire defer stack: // incomplete information then is still better than nothing. if callback != nil && n < max && _defer != nil { if _defer != nil { print("runtime: g", gp.goid, ": leftover defer sp=", hex(_defer.sp), " pc=", hex(_defer.pc), "\n") } for _defer = gp._defer; _defer != nil; _defer = _defer.link { print("\tdefer ", _defer, " sp=", hex(_defer.sp), " pc=", hex(_defer.pc), "\n") } throw("traceback has leftover defers") } if callback != nil && n < max && frame.sp != gp.stktopsp { print("runtime: g", gp.goid, ": frame.sp=", hex(frame.sp), " top=", hex(gp.stktopsp), "\n") print("\tstack=[", hex(gp.stack.lo), "-", hex(gp.stack.hi), "] n=", n, " max=", max, "\n") throw("traceback did not unwind completely") } return n } // reflectMethodValue is a partial duplicate of reflect.makeFuncImpl // and reflect.methodValue. type reflectMethodValue struct { fn uintptr stack *bitvector // args bitmap } // getArgInfo returns the argument frame information for a call to f // with call frame frame. // // This is used for both actual calls with active stack frames and for // deferred calls that are not yet executing. If this is an actual // call, ctxt must be nil (getArgInfo will retrieve what it needs from // the active stack frame). If this is a deferred call, ctxt must be // the function object that was deferred. func getArgInfo(frame *stkframe, f funcInfo, needArgMap bool, ctxt *funcval) (arglen uintptr, argmap *bitvector) { arglen = uintptr(f.args) if needArgMap && f.args == _ArgsSizeUnknown { // Extract argument bitmaps for reflect stubs from the calls they made to reflect. switch funcname(f) { case "reflect.makeFuncStub", "reflect.methodValueCall": // These take a *reflect.methodValue as their // context register. var mv *reflectMethodValue if ctxt != nil { // This is not an actual call, but a // deferred call. The function value // is itself the *reflect.methodValue. mv = (*reflectMethodValue)(unsafe.Pointer(ctxt)) } else { // This is a real call that took the // *reflect.methodValue as its context // register and immediately saved it // to 0(SP). Get the methodValue from // 0(SP). arg0 := frame.sp + sys.MinFrameSize mv = *(**reflectMethodValue)(unsafe.Pointer(arg0)) } if mv.fn != f.entry { print("runtime: confused by ", funcname(f), "\n") throw("reflect mismatch") } bv := mv.stack arglen = uintptr(bv.n * sys.PtrSize) argmap = bv } } return } // tracebackCgoContext handles tracing back a cgo context value, from // the context argument to setCgoTraceback, for the gentraceback // function. It returns the new value of n. func tracebackCgoContext(pcbuf *uintptr, printing bool, ctxt uintptr, n, max int) int { var cgoPCs [32]uintptr cgoContextPCs(ctxt, cgoPCs[:]) var arg cgoSymbolizerArg anySymbolized := false for _, pc := range cgoPCs { if pc == 0 || n >= max { break } if pcbuf != nil { (*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc } if printing { if cgoSymbolizer == nil { print("non-Go function at pc=", hex(pc), "\n") } else { c := printOneCgoTraceback(pc, max-n, &arg) n += c - 1 // +1 a few lines down anySymbolized = true } } n++ } if anySymbolized { arg.pc = 0 callCgoSymbolizer(&arg) } return n } func printcreatedby(gp *g) { // Show what created goroutine, except main goroutine (goid 1). pc := gp.gopc f := findfunc(pc) if f.valid() && showframe(f, gp, false) && gp.goid != 1 { print("created by ", funcname(f), "\n") tracepc := pc // back up to CALL instruction for funcline. if pc > f.entry { tracepc -= sys.PCQuantum } file, line := funcline(f, tracepc) print("\t", file, ":", line) if pc > f.entry { print(" +", hex(pc-f.entry)) } print("\n") } } func traceback(pc, sp, lr uintptr, gp *g) { traceback1(pc, sp, lr, gp, 0) } // tracebacktrap is like traceback but expects that the PC and SP were obtained // from a trap, not from gp->sched or gp->syscallpc/gp->syscallsp or getcallerpc/getcallersp. // Because they are from a trap instead of from a saved pair, // the initial PC must not be rewound to the previous instruction. // (All the saved pairs record a PC that is a return address, so we // rewind it into the CALL instruction.) func tracebacktrap(pc, sp, lr uintptr, gp *g) { traceback1(pc, sp, lr, gp, _TraceTrap) } func traceback1(pc, sp, lr uintptr, gp *g, flags uint) { // If the goroutine is in cgo, and we have a cgo traceback, print that. if iscgo && gp.m != nil && gp.m.ncgo > 0 && gp.syscallsp != 0 && gp.m.cgoCallers != nil && gp.m.cgoCallers[0] != 0 { // Lock cgoCallers so that a signal handler won't // change it, copy the array, reset it, unlock it. // We are locked to the thread and are not running // concurrently with a signal handler. // We just have to stop a signal handler from interrupting // in the middle of our copy. atomic.Store(&gp.m.cgoCallersUse, 1) cgoCallers := *gp.m.cgoCallers gp.m.cgoCallers[0] = 0 atomic.Store(&gp.m.cgoCallersUse, 0) printCgoTraceback(&cgoCallers) } var n int if readgstatus(gp)&^_Gscan == _Gsyscall { // Override registers if blocked in system call. pc = gp.syscallpc sp = gp.syscallsp flags &^= _TraceTrap } // Print traceback. By default, omits runtime frames. // If that means we print nothing at all, repeat forcing all frames printed. n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags) if n == 0 && (flags&_TraceRuntimeFrames) == 0 { n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags|_TraceRuntimeFrames) } if n == _TracebackMaxFrames { print("...additional frames elided...\n") } printcreatedby(gp) } func callers(skip int, pcbuf []uintptr) int { sp := getcallersp(unsafe.Pointer(&skip)) pc := getcallerpc(unsafe.Pointer(&skip)) gp := getg() var n int systemstack(func() { n = gentraceback(pc, sp, 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0) }) return n } func gcallers(gp *g, skip int, pcbuf []uintptr) int { return gentraceback(^uintptr(0), ^uintptr(0), 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0) } func showframe(f funcInfo, gp *g, firstFrame bool) bool { g := getg() if g.m.throwing > 0 && gp != nil && (gp == g.m.curg || gp == g.m.caughtsig.ptr()) { return true } level, _, _ := gotraceback() name := funcname(f) // Special case: always show runtime.gopanic frame // in the middle of a stack trace, so that we can // see the boundary between ordinary code and // panic-induced deferred code. // See golang.org/issue/5832. if name == "runtime.gopanic" && !firstFrame { return true } return level > 1 || f.valid() && contains(name, ".") && (!hasprefix(name, "runtime.") || isExportedRuntime(name)) } // isExportedRuntime reports whether name is an exported runtime function. // It is only for runtime functions, so ASCII A-Z is fine. func isExportedRuntime(name string) bool { const n = len("runtime.") return len(name) > n && name[:n] == "runtime." && 'A' <= name[n] && name[n] <= 'Z' } var gStatusStrings = [...]string{ _Gidle: "idle", _Grunnable: "runnable", _Grunning: "running", _Gsyscall: "syscall", _Gwaiting: "waiting", _Gdead: "dead", _Gcopystack: "copystack", } func goroutineheader(gp *g) { gpstatus := readgstatus(gp) isScan := gpstatus&_Gscan != 0 gpstatus &^= _Gscan // drop the scan bit // Basic string status var status string if 0 <= gpstatus && gpstatus < uint32(len(gStatusStrings)) { status = gStatusStrings[gpstatus] } else { status = "???" } // Override. if gpstatus == _Gwaiting && gp.waitreason != "" { status = gp.waitreason } // approx time the G is blocked, in minutes var waitfor int64 if (gpstatus == _Gwaiting || gpstatus == _Gsyscall) && gp.waitsince != 0 { waitfor = (nanotime() - gp.waitsince) / 60e9 } print("goroutine ", gp.goid, " [", status) if isScan { print(" (scan)") } if waitfor >= 1 { print(", ", waitfor, " minutes") } if gp.lockedm != nil { print(", locked to thread") } print("]:\n") } func tracebackothers(me *g) { level, _, _ := gotraceback() // Show the current goroutine first, if we haven't already. g := getg() gp := g.m.curg if gp != nil && gp != me { print("\n") goroutineheader(gp) traceback(^uintptr(0), ^uintptr(0), 0, gp) } lock(&allglock) for _, gp := range allgs { if gp == me || gp == g.m.curg || readgstatus(gp) == _Gdead || isSystemGoroutine(gp) && level < 2 { continue } print("\n") goroutineheader(gp) // Note: gp.m == g.m occurs when tracebackothers is // called from a signal handler initiated during a // systemstack call. The original G is still in the // running state, and we want to print its stack. if gp.m != g.m && readgstatus(gp)&^_Gscan == _Grunning { print("\tgoroutine running on other thread; stack unavailable\n") printcreatedby(gp) } else { traceback(^uintptr(0), ^uintptr(0), 0, gp) } } unlock(&allglock) } // Does f mark the top of a goroutine stack? func topofstack(f funcInfo) bool { pc := f.entry return pc == goexitPC || pc == mstartPC || pc == mcallPC || pc == morestackPC || pc == rt0_goPC || externalthreadhandlerp != 0 && pc == externalthreadhandlerp } // isSystemGoroutine reports whether the goroutine g must be omitted in // stack dumps and deadlock detector. func isSystemGoroutine(gp *g) bool { pc := gp.startpc return pc == runfinqPC && !fingRunning || pc == bgsweepPC || pc == forcegchelperPC || pc == timerprocPC || pc == gcBgMarkWorkerPC } // SetCgoTraceback records three C functions to use to gather // traceback information from C code and to convert that traceback // information into symbolic information. These are used when printing // stack traces for a program that uses cgo. // // The traceback and context functions may be called from a signal // handler, and must therefore use only async-signal safe functions. // The symbolizer function may be called while the program is // crashing, and so must be cautious about using memory. None of the // functions may call back into Go. // // The context function will be called with a single argument, a // pointer to a struct: // // struct { // Context uintptr // } // // In C syntax, this struct will be // // struct { // uintptr_t Context; // }; // // If the Context field is 0, the context function is being called to // record the current traceback context. It should record in the // Context field whatever information is needed about the current // point of execution to later produce a stack trace, probably the // stack pointer and PC. In this case the context function will be // called from C code. // // If the Context field is not 0, then it is a value returned by a // previous call to the context function. This case is called when the // context is no longer needed; that is, when the Go code is returning // to its C code caller. This permits the context function to release // any associated resources. // // While it would be correct for the context function to record a // complete a stack trace whenever it is called, and simply copy that // out in the traceback function, in a typical program the context // function will be called many times without ever recording a // traceback for that context. Recording a complete stack trace in a // call to the context function is likely to be inefficient. // // The traceback function will be called with a single argument, a // pointer to a struct: // // struct { // Context uintptr // SigContext uintptr // Buf *uintptr // Max uintptr // } // // In C syntax, this struct will be // // struct { // uintptr_t Context; // uintptr_t SigContext; // uintptr_t* Buf; // uintptr_t Max; // }; // // The Context field will be zero to gather a traceback from the // current program execution point. In this case, the traceback // function will be called from C code. // // Otherwise Context will be a value previously returned by a call to // the context function. The traceback function should gather a stack // trace from that saved point in the program execution. The traceback // function may be called from an execution thread other than the one // that recorded the context, but only when the context is known to be // valid and unchanging. The traceback function may also be called // deeper in the call stack on the same thread that recorded the // context. The traceback function may be called multiple times with // the same Context value; it will usually be appropriate to cache the // result, if possible, the first time this is called for a specific // context value. // // If the traceback function is called from a signal handler on a Unix // system, SigContext will be the signal context argument passed to // the signal handler (a C ucontext_t* cast to uintptr_t). This may be // used to start tracing at the point where the signal occurred. If // the traceback function is not called from a signal handler, // SigContext will be zero. // // Buf is where the traceback information should be stored. It should // be PC values, such that Buf[0] is the PC of the caller, Buf[1] is // the PC of that function's caller, and so on. Max is the maximum // number of entries to store. The function should store a zero to // indicate the top of the stack, or that the caller is on a different // stack, presumably a Go stack. // // Unlike runtime.Callers, the PC values returned should, when passed // to the symbolizer function, return the file/line of the call // instruction. No additional subtraction is required or appropriate. // // The symbolizer function will be called with a single argument, a // pointer to a struct: // // struct { // PC uintptr // program counter to fetch information for // File *byte // file name (NUL terminated) // Lineno uintptr // line number // Func *byte // function name (NUL terminated) // Entry uintptr // function entry point // More uintptr // set non-zero if more info for this PC // Data uintptr // unused by runtime, available for function // } // // In C syntax, this struct will be // // struct { // uintptr_t PC; // char* File; // uintptr_t Lineno; // char* Func; // uintptr_t Entry; // uintptr_t More; // uintptr_t Data; // }; // // The PC field will be a value returned by a call to the traceback // function. // // The first time the function is called for a particular traceback, // all the fields except PC will be 0. The function should fill in the // other fields if possible, setting them to 0/nil if the information // is not available. The Data field may be used to store any useful // information across calls. The More field should be set to non-zero // if there is more information for this PC, zero otherwise. If More // is set non-zero, the function will be called again with the same // PC, and may return different information (this is intended for use // with inlined functions). If More is zero, the function will be // called with the next PC value in the traceback. When the traceback // is complete, the function will be called once more with PC set to // zero; this may be used to free any information. Each call will // leave the fields of the struct set to the same values they had upon // return, except for the PC field when the More field is zero. The // function must not keep a copy of the struct pointer between calls. // // When calling SetCgoTraceback, the version argument is the version // number of the structs that the functions expect to receive. // Currently this must be zero. // // The symbolizer function may be nil, in which case the results of // the traceback function will be displayed as numbers. If the // traceback function is nil, the symbolizer function will never be // called. The context function may be nil, in which case the // traceback function will only be called with the context field set // to zero. If the context function is nil, then calls from Go to C // to Go will not show a traceback for the C portion of the call stack. // // SetCgoTraceback should be called only once, ideally from an init function. func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer) { if version != 0 { panic("unsupported version") } if cgoTraceback != nil && cgoTraceback != traceback || cgoContext != nil && cgoContext != context || cgoSymbolizer != nil && cgoSymbolizer != symbolizer { panic("call SetCgoTraceback only once") } cgoTraceback = traceback cgoContext = context cgoSymbolizer = symbolizer // The context function is called when a C function calls a Go // function. As such it is only called by C code in runtime/cgo. if _cgo_set_context_function != nil { cgocall(_cgo_set_context_function, context) } } var cgoTraceback unsafe.Pointer var cgoContext unsafe.Pointer var cgoSymbolizer unsafe.Pointer // cgoTracebackArg is the type passed to cgoTraceback. type cgoTracebackArg struct { context uintptr sigContext uintptr buf *uintptr max uintptr } // cgoContextArg is the type passed to the context function. type cgoContextArg struct { context uintptr } // cgoSymbolizerArg is the type passed to cgoSymbolizer. type cgoSymbolizerArg struct { pc uintptr file *byte lineno uintptr funcName *byte entry uintptr more uintptr data uintptr } // cgoTraceback prints a traceback of callers. func printCgoTraceback(callers *cgoCallers) { if cgoSymbolizer == nil { for _, c := range callers { if c == 0 { break } print("non-Go function at pc=", hex(c), "\n") } return } var arg cgoSymbolizerArg for _, c := range callers { if c == 0 { break } printOneCgoTraceback(c, 0x7fffffff, &arg) } arg.pc = 0 callCgoSymbolizer(&arg) } // printOneCgoTraceback prints the traceback of a single cgo caller. // This can print more than one line because of inlining. // Returns the number of frames printed. func printOneCgoTraceback(pc uintptr, max int, arg *cgoSymbolizerArg) int { c := 0 arg.pc = pc for { if c > max { break } callCgoSymbolizer(arg) if arg.funcName != nil { // Note that we don't print any argument // information here, not even parentheses. // The symbolizer must add that if appropriate. println(gostringnocopy(arg.funcName)) } else { println("non-Go function") } print("\t") if arg.file != nil { print(gostringnocopy(arg.file), ":", arg.lineno, " ") } print("pc=", hex(pc), "\n") c++ if arg.more == 0 { break } } return c } // callCgoSymbolizer calls the cgoSymbolizer function. func callCgoSymbolizer(arg *cgoSymbolizerArg) { call := cgocall if panicking > 0 || getg().m.curg != getg() { // We do not want to call into the scheduler when panicking // or when on the system stack. call = asmcgocall } if msanenabled { msanwrite(unsafe.Pointer(arg), unsafe.Sizeof(cgoSymbolizerArg{})) } call(cgoSymbolizer, noescape(unsafe.Pointer(arg))) } // cgoContextPCs gets the PC values from a cgo traceback. func cgoContextPCs(ctxt uintptr, buf []uintptr) { if cgoTraceback == nil { return } call := cgocall if panicking > 0 || getg().m.curg != getg() { // We do not want to call into the scheduler when panicking // or when on the system stack. call = asmcgocall } arg := cgoTracebackArg{ context: ctxt, buf: (*uintptr)(noescape(unsafe.Pointer(&buf[0]))), max: uintptr(len(buf)), } if msanenabled { msanwrite(unsafe.Pointer(&arg), unsafe.Sizeof(arg)) } call(cgoTraceback, noescape(unsafe.Pointer(&arg))) }
0019_add_non_ministerial_departments.py
from django.db import migrations from api.metadata.constants import OrganisationType ORGANISATIONS = [ { "name": "The Charity Commission", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS }, { "name": "Competition and Markets Authority", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS }, { "name": "Crown Prosecution Service", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS }, { "name": "Food Standards Agency", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS }, { "name": "Forestry Commission", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS }, { "name": "Government Actuary's Department", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS }, { "name": "Government Legal Department", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS }, { "name": "HM Land Registry", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS }, { "name": "HM Revenue & Customs", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS }, { "name": "NS&I", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS }, { "name": "The National Archives", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS }, { "name": "National Crime Agency", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS }, { "name": "Office of Rail and Road", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS }, { "name": "Ofgem", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS }, { "name": "Ofqual", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS }, { "name": "Ofsted", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS }, { "name": "Serious Fraud Office", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS }, { "name": "Supreme Court of the United Kingdom", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS }, { "name": "UK Statistics Authority", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS }, { "name": "The Water Services Regulation Authority", "organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS } ] def create_organisations(apps, schema_editor): Organisation = apps.get_model("metadata", "Organisation") for item in ORGANISATIONS: Organisation.objects.create(**item) def delete_organisations(apps, schema_editor):
class Migration(migrations.Migration): dependencies = [ ("metadata", "0018_auto_20201118_1133"), ] operations = [ migrations.RunPython(create_organisations, reverse_code=delete_organisations), ]
Organisation = apps.get_model("metadata", "Organisation") for item in ORGANISATIONS: Organisation.objects.delete(**item)
statuses.rs
use crate::errors::Error; use serde::Serialize; use std::{borrow::Cow, convert::Into}; mod bool_qs_serialize { use serde::Serializer; pub fn is_false(b: &bool) -> bool { !*b } pub fn serialize<S: Serializer>(b: &bool, s: S) -> Result<S::Ok, S::Error> { if *b { s.serialize_i64(1) } else { s.serialize_i64(0) } } } /// Builder for making a client.statuses() call /// /// # Example /// /// ``` /// # extern crate elefren; /// # use elefren::StatusesRequest; /// let request = StatusesRequest::new() /// .only_media() /// .pinned() /// .since_id("foo"); /// # assert_eq!(&request.to_querystring().expect("Couldn't serialize qs")[..], "?only_media=1&pinned=1&since_id=foo"); /// ``` #[derive(Clone, Debug, Default, PartialEq, Serialize)] pub struct StatusesRequest<'a> { #[serde(skip_serializing_if = "bool_qs_serialize::is_false")] #[serde(serialize_with = "bool_qs_serialize::serialize")] only_media: bool, #[serde(skip_serializing_if = "bool_qs_serialize::is_false")] #[serde(serialize_with = "bool_qs_serialize::serialize")] exclude_replies: bool, #[serde(skip_serializing_if = "bool_qs_serialize::is_false")] #[serde(serialize_with = "bool_qs_serialize::serialize")] pinned: bool, #[serde(skip_serializing_if = "Option::is_none")] max_id: Option<Cow<'a, str>>, #[serde(skip_serializing_if = "Option::is_none")] since_id: Option<Cow<'a, str>>, #[serde(skip_serializing_if = "Option::is_none")] limit: Option<usize>, #[serde(skip_serializing_if = "Option::is_none")] min_id: Option<Cow<'a, str>>, #[serde(skip_serializing_if = "bool_qs_serialize::is_false")] #[serde(serialize_with = "bool_qs_serialize::serialize")] exclude_reblogs: bool, } impl<'a> Into<Option<StatusesRequest<'a>>> for &'a mut StatusesRequest<'a> { fn into(self) -> Option<StatusesRequest<'a>> { Some(StatusesRequest { only_media: self.only_media, exclude_replies: self.exclude_replies, pinned: self.pinned, max_id: self.max_id.clone(), since_id: self.since_id.clone(), limit: self.limit, min_id: self.min_id.clone(), exclude_reblogs: self.exclude_reblogs, }) } } impl<'a> StatusesRequest<'a> { /// Construct a new `StatusesRequest` object /// /// # Example /// /// ``` /// # extern crate elefren; /// # use elefren::StatusesRequest; /// let request = StatusesRequest::new(); /// ``` pub fn new() -> Self { Self::default() } /// Set the `?only_media=1` flag for the .statuses() request /// /// # Example /// /// ``` /// # extern crate elefren; /// # use elefren::StatusesRequest; /// let mut request = StatusesRequest::new(); /// assert_eq!(&request.only_media().to_querystring().expect("Couldn't serialize qs"), "?only_media=1"); pub fn only_media(mut self) -> Self { self.only_media = true; self } /// Set the `?exclude_reblogs=1` flag for the .statuses() request /// /// # Example /// /// ``` /// # extern crate elefren; /// # use elefren::StatusesRequest; /// let mut request = StatusesRequest::new(); /// assert_eq!( /// &request /// .exclude_reblogs() /// .to_querystring() /// .expect("Couldn't serialize qs"), /// "?exclude_reblogs=1" /// ); /// ``` pub fn exclude_reblogs(mut self) -> Self { self.exclude_reblogs = true; self } /// Set the `?exclude_replies=1` flag for the .statuses() request /// /// # Example /// /// ``` /// # extern crate elefren; /// # use elefren::StatusesRequest; /// let mut request = StatusesRequest::new(); /// assert_eq!( /// &request /// .exclude_replies() /// .to_querystring() /// .expect("Couldn't serialize qs"), /// "?exclude_replies=1" /// ); /// ``` pub fn exclude_replies(mut self) -> Self { self.exclude_replies = true; self } /// Set the `?pinned=1` flag for the .statuses() request /// /// # Example /// /// ``` /// # extern crate elefren; /// # use elefren::StatusesRequest; /// let mut request = StatusesRequest::new(); /// assert_eq!( /// &request /// .pinned() /// .to_querystring() /// .expect("Couldn't serialize qs"), /// "?pinned=1" /// ); /// ``` pub fn pinned(mut self) -> Self { self.pinned = true; self } /// Set the `?max_id=:max_id` flag for the .statuses() request /// /// # Example /// /// ``` /// # extern crate elefren; /// # use elefren::StatusesRequest; /// let mut request = StatusesRequest::new(); /// assert_eq!( /// &request /// .max_id("foo") /// .to_querystring() /// .expect("Couldn't serialize qs"), /// "?max_id=foo" /// ); /// ``` pub fn
<S: Into<Cow<'a, str>>>(mut self, max_id: S) -> Self { self.max_id = Some(max_id.into()); self } /// Set the `?since_id=:since_id` flag for the .statuses() request /// /// # Example /// /// ``` /// # extern crate elefren; /// # use elefren::StatusesRequest; /// let mut request = StatusesRequest::new(); /// assert_eq!( /// &request /// .since_id("foo") /// .to_querystring() /// .expect("Couldn't serialize qs"), /// "?since_id=foo" /// ); /// ``` pub fn since_id<S: Into<Cow<'a, str>>>(mut self, since_id: S) -> Self { self.since_id = Some(since_id.into()); self } /// Set the `?limit=:limit` flag for the .statuses() request /// /// # Example /// /// ``` /// # extern crate elefren; /// # use elefren::StatusesRequest; /// let mut request = StatusesRequest::new(); /// assert_eq!( /// &request /// .limit(10) /// .to_querystring() /// .expect("Couldn't serialize qs"), /// "?limit=10" /// ); /// ``` pub fn limit(mut self, limit: usize) -> Self { self.limit = Some(limit); self } /// Set the `?min_id=:min_id` flag for the .statuses() request /// /// # Example /// /// ``` /// # extern crate elefren; /// # use elefren::StatusesRequest; /// let mut request = StatusesRequest::new(); /// assert_eq!( /// &request /// .min_id("foobar") /// .to_querystring() /// .expect("Couldn't serialize qs"), /// "?min_id=foobar" /// ); /// ``` pub fn min_id<S: Into<Cow<'a, str>>>(mut self, min_id: S) -> Self { self.min_id = Some(min_id.into()); self } /// Turns this builder into a querystring /// /// # Example /// /// ``` /// # extern crate elefren; /// # use elefren::StatusesRequest; /// let mut request = StatusesRequest::new(); /// assert_eq!( /// &request /// .limit(10) /// .pinned() /// .to_querystring() /// .expect("Couldn't serialize qs"), /// "?pinned=1&limit=10" /// ); /// ``` pub fn to_querystring(&self) -> Result<String, Error> { Ok(format!("?{}", serde_qs::to_string(&self)?)) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_new() { let request = StatusesRequest::new(); assert_eq!( request, StatusesRequest { only_media: false, exclude_replies: false, pinned: false, max_id: None, since_id: None, limit: None, min_id: None, exclude_reblogs: false, } ); } #[test] fn test_only_media() { let request = StatusesRequest::new().only_media(); assert_eq!( request, StatusesRequest { only_media: true, exclude_replies: false, pinned: false, max_id: None, since_id: None, limit: None, min_id: None, exclude_reblogs: false, } ); } #[test] fn test_exclude_replies() { let request = StatusesRequest::new().exclude_replies(); assert_eq!( request, StatusesRequest { only_media: false, exclude_replies: true, pinned: false, max_id: None, since_id: None, limit: None, min_id: None, exclude_reblogs: false, } ); } #[test] fn test_pinned() { let request = StatusesRequest::new().pinned(); assert_eq!( request, StatusesRequest { only_media: false, exclude_replies: false, pinned: true, max_id: None, since_id: None, limit: None, min_id: None, exclude_reblogs: false, } ); } #[test] fn test_max_id() { let request = StatusesRequest::new().max_id("foo"); assert_eq!( request, StatusesRequest { only_media: false, exclude_replies: false, pinned: false, max_id: Some("foo".into()), since_id: None, limit: None, min_id: None, exclude_reblogs: false, } ); } #[test] fn test_since_id() { let request = StatusesRequest::new().since_id("foo"); assert_eq!( request, StatusesRequest { only_media: false, exclude_replies: false, pinned: false, max_id: None, since_id: Some("foo".into()), limit: None, min_id: None, exclude_reblogs: false, } ); } #[test] fn test_limit() { let request = StatusesRequest::new().limit(42); assert_eq!( request, StatusesRequest { only_media: false, exclude_replies: false, pinned: false, max_id: None, since_id: None, limit: Some(42), min_id: None, exclude_reblogs: false, } ); } #[test] fn test_min_id() { let request = StatusesRequest::new().min_id("foo"); assert_eq!( request, StatusesRequest { only_media: false, exclude_replies: false, pinned: false, max_id: None, since_id: None, limit: None, min_id: Some("foo".into()), exclude_reblogs: false, } ); } #[test] fn test_to_querystring() { macro_rules! qs_test { (| $r:ident | $b:block, $expected:expr) => {{ let $r = StatusesRequest::new(); let $r = $b; let qs = $r .to_querystring() .expect("Failed to serialize querystring"); assert_eq!(&qs, $expected); }}; } qs_test!(|request| { request.only_media() }, "?only_media=1"); qs_test!( |request| { request.exclude_replies() }, "?exclude_replies=1" ); qs_test!(|request| { request.pinned() }, "?pinned=1"); qs_test!(|request| { request.max_id("foo") }, "?max_id=foo"); qs_test!(|request| { request.since_id("foo") }, "?since_id=foo"); qs_test!(|request| { request.limit(42) }, "?limit=42"); qs_test!( |request| { request.only_media().exclude_replies() }, "?only_media=1&exclude_replies=1" ); qs_test!( |request| { request.only_media().pinned() }, "?only_media=1&pinned=1" ); qs_test!( |request| { request.only_media().max_id("foo") }, "?only_media=1&max_id=foo" ); qs_test!( |request| { request.only_media().since_id("foo") }, "?only_media=1&since_id=foo" ); qs_test!( |request| { request.only_media().limit(42) }, "?only_media=1&limit=42" ); qs_test!( |request| { request.exclude_replies().only_media() }, "?only_media=1&exclude_replies=1" ); qs_test!( |request| { request.exclude_replies().pinned() }, "?exclude_replies=1&pinned=1" ); qs_test!( |request| { request.exclude_replies().max_id("foo") }, "?exclude_replies=1&max_id=foo" ); qs_test!( |request| { request.exclude_replies().since_id("foo") }, "?exclude_replies=1&since_id=foo" ); qs_test!( |request| { request.exclude_replies().limit(42) }, "?exclude_replies=1&limit=42" ); qs_test!( |request| { request.pinned().only_media() }, "?only_media=1&pinned=1" ); qs_test!( |request| { request.pinned().exclude_replies() }, "?exclude_replies=1&pinned=1" ); qs_test!( |request| { request.pinned().max_id("foo") }, "?pinned=1&max_id=foo" ); qs_test!( |request| { request.pinned().since_id("foo") }, "?pinned=1&since_id=foo" ); qs_test!( |request| { request.pinned().limit(42) }, "?pinned=1&limit=42" ); qs_test!( |request| { request.max_id("foo").only_media() }, "?only_media=1&max_id=foo" ); qs_test!( |request| { request.max_id("foo").exclude_replies() }, "?exclude_replies=1&max_id=foo" ); qs_test!( |request| { request.max_id("foo").pinned() }, "?pinned=1&max_id=foo" ); qs_test!( |request| { request.max_id("foo").since_id("foo") }, "?max_id=foo&since_id=foo" ); qs_test!( |request| { request.max_id("foo").limit(42) }, "?max_id=foo&limit=42" ); qs_test!( |request| { request.since_id("foo").only_media() }, "?only_media=1&since_id=foo" ); qs_test!( |request| { request.since_id("foo").exclude_replies() }, "?exclude_replies=1&since_id=foo" ); qs_test!( |request| { request.since_id("foo").pinned() }, "?pinned=1&since_id=foo" ); qs_test!( |request| { request.since_id("foo").max_id("foo") }, "?max_id=foo&since_id=foo" ); qs_test!( |request| { request.since_id("foo").limit(42) }, "?since_id=foo&limit=42" ); qs_test!( |request| { request.limit(42).only_media() }, "?only_media=1&limit=42" ); qs_test!( |request| { request.limit(42).exclude_replies() }, "?exclude_replies=1&limit=42" ); qs_test!( |request| { request.limit(42).pinned() }, "?pinned=1&limit=42" ); qs_test!( |request| { request.limit(42).max_id("foo") }, "?max_id=foo&limit=42" ); qs_test!( |request| { request.limit(42).since_id("foo") }, "?since_id=foo&limit=42" ); } }
max_id
notify.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 notify import ( "encoding/json" "fmt" "io" "io/ioutil" "net/http" "strings" "time" "github.com/blang/semver" "github.com/golang/glog" "github.com/pkg/errors" "github.com/spf13/viper" "github.com/stackfoundation/sandbox/core/pkg/minikube/config" "github.com/stackfoundation/sandbox/core/pkg/minikube/constants" "github.com/stackfoundation/sandbox/core/pkg/version" ) const updateLinkPrefix = "https://github.com/kubernetes/minikube/releases/tag/v" var ( timeLayout = time.RFC1123 lastUpdateCheckFilePath = constants.MakeMiniPath("last_update_check") ) func MaybePrintUpdateTextFromGithub(output io.Writer) { MaybePrintUpdateText(output, constants.GithubMinikubeReleasesURL, lastUpdateCheckFilePath) } func MaybePrintUpdateText(output io.Writer, url string, lastUpdatePath string) { if !shouldCheckURLVersion(lastUpdatePath) { return } latestVersion, err := getLatestVersionFromURL(url) if err != nil { glog.Errorln(err) return } localVersion, err := version.GetSemverVersion() if err != nil { glog.Errorln(err) return } if localVersion.Compare(latestVersion) < 0 { writeTimeToFile(lastUpdateCheckFilePath, time.Now().UTC()) fmt.Fprintf(output, `There is a newer version of minikube available (%s%s). Download it here: %s%s To disable this notification, run the following: minikube config set WantUpdateNotification false `, version.VersionPrefix, latestVersion, updateLinkPrefix, latestVersion) } } func shouldCheckURLVersion(filePath string) bool { if !viper.GetBool(config.WantUpdateNotification) { return false } lastUpdateTime := getTimeFromFileIfExists(filePath) if time.Since(lastUpdateTime).Hours() < viper.GetFloat64(config.ReminderWaitPeriodInHours) { return false } return true } type Release struct { Name string Checksums map[string]string } type Releases []Release func getJson(url string, target *Releases) error { r, err := http.Get(url) if err != nil { return errors.Wrap(err, "Error getting minikube version url via http") } defer r.Body.Close() return json.NewDecoder(r.Body).Decode(target) } func getLatestVersionFromURL(url string) (semver.Version, error) { r, err := GetAllVersionsFromURL(url) if err != nil { return semver.Version{}, err } return semver.Make(strings.TrimPrefix(r[0].Name, version.VersionPrefix)) } func GetAllVersionsFromURL(url string) (Releases, error) { var releases Releases glog.Infof("Checking for updates...") if err := getJson(url, &releases); err != nil { return releases, errors.Wrap(err, "Error getting json from minikube version url") } if len(releases) == 0 { return releases, errors.Errorf("There were no json releases at the url specified: %s", url) } return releases, nil
if err != nil { return errors.Wrap(err, "Error writing current update time to file: ") } return nil } func getTimeFromFileIfExists(path string) time.Time { lastUpdateCheckTime, err := ioutil.ReadFile(path) if err != nil { return time.Time{} } timeInFile, err := time.Parse(timeLayout, string(lastUpdateCheckTime)) if err != nil { return time.Time{} } return timeInFile }
} func writeTimeToFile(path string, inputTime time.Time) error { err := ioutil.WriteFile(path, []byte(inputTime.Format(timeLayout)), 0644)
rnd_loss.py
from typing import Dict, List import torch import torch.nn.functional as F def
(states: torch.Tensor, actions: torch.Tensor, next_states: torch.Tensor, log_probs_old: torch.Tensor, ext_returns: torch.Tensor, ext_advantages: torch.Tensor, std_ext_advantages: torch.Tensor, int_returns: torch.Tensor, int_advantages: torch.Tensor, std_int_advantages: torch.Tensor, target_random_features: torch.Tensor, states_mean: torch.Tensor, states_std: torch.Tensor, model: torch.nn.Module, pred_intr_model: torch.nn.Module, intrinsic_reward_ratio: float, ratio_clip: float, entropy_weight: float, value_weight: float, rnd_weight: float, rnd_obs_clip: float, summary_writer: object = None, iteration_count: int = 0, rnn_states: Dict[str, Dict[str, List[torch.Tensor]]] = None) -> torch.Tensor: ''' Computes the loss of an actor critic model using the loss function from equation (9) in the paper: Proximal Policy Optimization Algorithms: https://arxiv.org/abs/1707.06347 :param states: Dimension: batch_size x state_size: States visited by the agent. :param actions: Dimension: batch_size x action_size. Actions which the agent took at every state in :param states: with the same index. :param log_probs_old: Dimension: batch_size x 1. Log probability of taking the action with the same index in :param actions:. Used to compute the policy probability ratio. Refer to original paper equation (6) :param ext_returns: Dimension: batch_size x 1. Empirical returns obtained via calculating the discounted return from the environment's rewards :param ext_advantages: Dimension: batch_size x 1. Estimated advantage function for every state and action in :param states: and :param actions: (respectively) with the same index. :param std_ext_advantages: Dimension: batch_size x 1. Estimated standardized advantage function for every state and action in :param states: and :param actions: (respectively) with the same index. :param int_returns: Dimension: batch_size x 1. Empirical intrinsic returns obtained via calculating the discounted intrinsic return from the intrinsic rewards. :param int_advantages: Dimension: batch_size x 1. Estimated intrisinc advantage function for every state and action in :param states: and :param actions: (respectively) with the same index. :param std_int_advantages: Dimension: batch_size x 1. Estimated standardized intrinsic advantage function for every state and action in :param states: and :param actions: (respectively) with the same index. :param target_random_features: target random features used to compute the intrinsic rewards. :param states_mean: mean over the previous training step's states. :param states_std: standard deviation over the previous training step's states. :param model: torch.nn.Module used to compute the policy probability ratio as specified in equation (6) of original paper. :param predict_intr_model: intrinsic reward prediction model. :param intrinsic_reward_ratio: ratio of intrinsic reward to extrinsic reward. :param ratio_clip: Epsilon value used to clip the policy ratio's value. This parameter acts as the radius of the Trust Region. Refer to original paper equation (7). :param entropy_weight: Coefficient to be used for the entropy bonus for the loss function. Refer to original paper eq (9) :param value_weight: Coefficient to be used for the value loss for the loss function. Refer to original paper eq (9) :param rnd_weight: Coefficient to be used for the rnd loss for the loss function. :param rnn_states: The :param model: can be made up of different submodules. Some of these submodules will feature an LSTM architecture. This parameter is a dictionary which maps recurrent submodule names to a dictionary which contains 2 lists of tensors, each list corresponding to the 'hidden' and 'cell' states of the LSTM submodules. These tensors are used by the :param model: when calculating the policy probability ratio. ''' advantages = ext_advantages + intrinsic_reward_ratio*int_advantages std_advantages = std_ext_advantages + intrinsic_reward_ratio*std_int_advantages prediction = model(states, actions, rnn_states=rnn_states) ratio = torch.exp((prediction['log_pi_a'] - log_probs_old)) obj = ratio * std_advantages obj_clipped = torch.clamp(ratio, 1.0 - ratio_clip, 1.0 + ratio_clip) * std_advantages policy_val = -torch.min(obj, obj_clipped).mean() entropy_val = prediction['ent'].mean() policy_loss = policy_val - entropy_weight * entropy_val # L^{clip} and L^{S} from original paper #policy_loss = -torch.min(obj, obj_clipped).mean() - entropy_weight * prediction['ent'].mean() # L^{clip} and L^{S} from original paper # Random Network Distillation loss: norm_next_states = (next_states-states_mean) / (states_std+1e-8) if rnd_obs_clip > 1e-1: norm_next_states = torch.clamp( norm_next_states, -rnd_obs_clip, rnd_obs_clip) pred_random_features = pred_intr_model(norm_next_states) # Clamping: #pred_random_features = torch.clamp(pred_random_features, -1e20, 1e20) #target_random_features = torch.clamp(target_random_features, -1e20, 1e20) # Softmax: #pred_random_features = F.softmax(pred_random_features) # Losses: #int_reward_loss = torch.nn.functional.smooth_l1_loss(target_random_features.detach(), pred_random_features) int_reward_loss = torch.nn.functional.mse_loss( pred_random_features, target_random_features.detach()) #ext_returns = torch.clamp(ext_returns, -1e10, 1e10) #int_returns = torch.clamp(int_returns, -1e10, 1e10) #prediction['v'] = torch.clamp(prediction['v'], -1e10, 1e10) #prediction['int_v'] = torch.clamp(prediction['int_v'], -1e10, 1e10) #ext_v_loss = torch.nn.functional.smooth_l1_loss(ext_returns, prediction['v']) #int_v_loss = torch.nn.functional.smooth_l1_loss(int_returns, prediction['int_v']) ext_v_loss = torch.nn.functional.mse_loss(input=prediction['v'], target=ext_returns) int_v_loss = torch.nn.functional.mse_loss(input=prediction['int_v'], target=int_returns) value_loss = (ext_v_loss + int_v_loss) #value_loss = ext_v_loss rnd_loss = int_reward_loss total_loss = policy_loss + rnd_weight * rnd_loss + value_weight * value_loss #total_loss = policy_loss + value_weight * value_loss if summary_writer is not None: summary_writer.add_scalar('Training/RatioMean', ratio.mean().cpu().item(), iteration_count) #summary_writer.add_histogram('Training/Ratio', ratio.cpu(), iteration_count) summary_writer.add_scalar('Training/ExtAdvantageMean', ext_advantages.mean().cpu().item(), iteration_count) summary_writer.add_scalar('Training/IntAdvantageMean', int_advantages.mean().cpu().item(), iteration_count) summary_writer.add_scalar('Training/AdvantageMean', advantages.mean().cpu().item(), iteration_count) #summary_writer.add_histogram('Training/ExtAdvantage', ext_advantages.cpu(), iteration_count) #summary_writer.add_histogram('Training/IntAdvantage', int_advantages.cpu(), iteration_count) #summary_writer.add_histogram('Training/Advantage', advantages.cpu(), iteration_count) summary_writer.add_scalar('Training/RNDLoss', int_reward_loss.cpu().item(), iteration_count) summary_writer.add_scalar('Training/ExtVLoss', ext_v_loss.cpu().item(), iteration_count) summary_writer.add_scalar('Training/IntVLoss', int_v_loss.cpu().item(), iteration_count) summary_writer.add_scalar('Training/MeanVValues', prediction['v'].cpu().mean().item(), iteration_count) summary_writer.add_scalar('Training/MeanReturns', ext_returns.cpu().mean().item(), iteration_count) summary_writer.add_scalar('Training/StdVValues', prediction['v'].cpu().std().item(), iteration_count) summary_writer.add_scalar('Training/StdReturns', ext_returns.cpu().std().item(), iteration_count) summary_writer.add_scalar('Training/MeanIntVValues', prediction['int_v'].cpu().mean().item(), iteration_count) summary_writer.add_scalar('Training/MeanIntReturns', int_returns.cpu().mean().item(), iteration_count) summary_writer.add_scalar('Training/StdIntVValues', prediction['int_v'].cpu().std().item(), iteration_count) summary_writer.add_scalar('Training/StdIntReturns', int_returns.cpu().std().item(), iteration_count) summary_writer.add_scalar('Training/ValueLoss', value_loss.cpu().item(), iteration_count) summary_writer.add_scalar('Training/PolicyVal', policy_val.cpu().item(), iteration_count) summary_writer.add_scalar('Training/EntropyVal', entropy_val.cpu().item(), iteration_count) summary_writer.add_scalar('Training/PolicyLoss', policy_loss.cpu().item(), iteration_count) summary_writer.add_scalar('Training/TotalLoss', total_loss.cpu().item(), iteration_count) return total_loss
compute_loss
mod.rs
use std::path::Path; mod connect; mod journal_mode; mod parse; use crate::connection::LogSettings; pub use journal_mode::SqliteJournalMode; use std::{borrow::Cow, time::Duration}; /// Options and flags which can be used to configure a SQLite connection. /// /// A value of `SqliteConnectOptions` can be parsed from a connection URI, /// as described by [SQLite](https://www.sqlite.org/uri.html). /// /// | URI | Description | /// | -- | -- | /// `sqlite::memory:` | Open an in-memory database. | /// `sqlite:data.db` | Open the file `data.db` in the current directory. | /// `sqlite://data.db` | Open the file `data.db` in the current directory. | /// `sqlite:///data.db` | Open the file `data.db` from the root (`/`) directory. | /// `sqlite://data.db?mode=ro` | Open the file `data.db` for read-only access. | /// /// # Example /// /// ```rust,no_run /// # use sqlx_core as sqlx; /// # use sqlx_core::connection::ConnectOptions; /// # use sqlx_core::error::Error; /// use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode}; /// use std::str::FromStr; /// /// # fn main() { /// # #[cfg(feature = "_rt-async-std")] /// # sqlx_rt::async_std::task::block_on::<_, Result<(), Error>>(async move { /// let conn = SqliteConnectOptions::from_str("sqlite://data.db")? /// .journal_mode(SqliteJournalMode::Wal) /// .read_only(true) /// .connect().await?; /// # Ok(()) /// # }).unwrap(); /// # } /// ``` #[derive(Clone, Debug)] pub struct SqliteConnectOptions { pub(crate) filename: Cow<'static, Path>, pub(crate) in_memory: bool, pub(crate) read_only: bool, pub(crate) create_if_missing: bool, pub(crate) journal_mode: SqliteJournalMode, pub(crate) foreign_keys: bool, pub(crate) shared_cache: bool, pub(crate) statement_cache_capacity: usize, pub(crate) busy_timeout: Duration, pub(crate) log_settings: LogSettings, } impl Default for SqliteConnectOptions { fn default() -> Self { Self::new() } } impl SqliteConnectOptions { pub fn new() -> Self { Self { filename: Cow::Borrowed(Path::new(":memory:")), in_memory: false, read_only: false, create_if_missing: false, foreign_keys: true, shared_cache: false, statement_cache_capacity: 100, journal_mode: SqliteJournalMode::Wal, busy_timeout: Duration::from_secs(5), log_settings: Default::default(), } } /// Sets the name of the database file. pub fn filename(mut self, filename: impl AsRef<Path>) -> Self { self.filename = Cow::Owned(filename.as_ref().to_owned()); self } /// Set the enforcement of [foreign key constriants](https://www.sqlite.org/pragma.html#pragma_foreign_keys).
/// /// By default, this is enabled. pub fn foreign_keys(mut self, on: bool) -> Self { self.foreign_keys = on; self } /// Sets the [journal mode](https://www.sqlite.org/pragma.html#pragma_journal_mode) for the database connection. /// /// The default journal mode is WAL. For most use cases this can be significantly faster but /// there are [disadvantages](https://www.sqlite.org/wal.html). pub fn journal_mode(mut self, mode: SqliteJournalMode) -> Self { self.journal_mode = mode; self } /// Sets the [access mode](https://www.sqlite.org/c3ref/open.html) to open the database /// for read-only access. pub fn read_only(mut self, read_only: bool) -> Self { self.read_only = read_only; self } /// Sets the [access mode](https://www.sqlite.org/c3ref/open.html) to create the database file /// if the file does not exist. /// /// By default, a new file **will not be** created if one is not found. pub fn create_if_missing(mut self, create: bool) -> Self { self.create_if_missing = create; self } /// Sets the capacity of the connection's statement cache in a number of stored /// distinct statements. Caching is handled using LRU, meaning when the /// amount of queries hits the defined limit, the oldest statement will get /// dropped. /// /// The default cache capacity is 100 statements. pub fn statement_cache_capacity(mut self, capacity: usize) -> Self { self.statement_cache_capacity = capacity; self } /// Sets a timeout value to wait when the database is locked, before /// returning a busy timeout error. /// /// The default busy timeout is 5 seconds. pub fn busy_timeout(mut self, timeout: Duration) -> Self { self.busy_timeout = timeout; self } }
parameter.py
# Copyright (c) Meta Platforms, Inc. and affiliates.
from enum import auto, Enum from typing import NamedTuple, Optional class Parameter(NamedTuple): class Kind(Enum): ARG = auto() VARARG = auto() KWARG = auto() name: str annotation: Optional[str] kind: Kind def __eq__(self, other: "Parameter") -> bool: if not isinstance(other, self.__class__): return False return self.name == other.name
# # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree.
user_identities.go
/* * CircleCI API * * The CircleCI API is a fully-featured JSON API that allows you to access all information and trigger all actions in CircleCI. * * API version: v1.1 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */
type UserIdentities struct { Github *GitHubIdentitiy `json:"github,omitempty"` Bitbucket *Identitiy `json:"bitbucket,omitempty"` Google *Identitiy `json:"google,omitempty"` }
package circleci
read.rs
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // Version 2, December 2004 // // Copyleft (ↄ) meh. <[email protected]> | http://meh.schizofreni.co // // Everyone is permitted to copy and distribute verbatim or modified // copies of this license document, and changing it is allowed as long // as the name is changed. // // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION // // 0. You just DO WHAT THE FUCK YOU WANT TO. use std::{ fs::File, io::{BufReader, Cursor, Read, Seek}, path::Path, }; use crate::{ buffer::Buffer, color, decoder::{self, Decoder}, error::{self, Error}, format::{self, Format}, pixel, }; /// Load an image from an input stream, guessing its format. /// /// # Example /// /// ``` /// use std::fs::File; /// /// use picto::read; /// use picto::color::Rgb; /// /// read::from::<Rgb, u8, _>(File::open("tests/boat.xyz").unwrap()).unwrap(); /// ``` pub fn from<P, C, R>(mut input: R) -> error::Result<Buffer<P, C, Vec<C>>> where P: From<color::Rgb> + From<color::Rgba> + From<color::Luma> + From<color::Lumaa>, P: pixel::Write<C>, C: pixel::Channel, R: Read + Seek, { let format = format::guess(input.by_ref()).ok_or(Error::Format("unsupported image format".into()))?; with_format(input, format) } /// Load an image from memory, guessing its format. /// /// # Example /// /// ``` /// use std::fs::File; /// use std::io::Read; /// /// use picto::read; /// use picto::color::Rgb; /// /// let mut buffer = Vec::new(); /// let mut file = File::open("tests/boat.xyz").unwrap(); /// file.read_to_end(&mut buffer).unwrap(); /// /// read::from_memory::<Rgb, u8, _>(buffer).unwrap(); /// ``` pub fn from_memory<P, C, R>(input: R) -> error::Result<Buffer<P, C, Vec<C>>> where P: From<color::Rgb> + From<color::Rgba> + From<color::Luma> + From<color::Lumaa>, P: pixel::Write<C>, C: pixel::Channel, R: AsRef<[u8]>, { from(Cursor::new(input)) } /// Load an image from the given path, guessing its format. /// /// # Example /// /// ``` /// use picto::read; /// use picto::color::Rgb; /// /// read::from_path::<Rgb, u8, _>("tests/boat.xyz").unwrap(); /// ``` pub fn from_path<P, C, R>(path: R) -> error::Result<Buffer<P, C, Vec<C>>> where P: From<color::Rgb> + From<color::Rgba> + From<color::Luma> + From<color::Lumaa>, P: pixel::Write<C>, C: pixel::Channel, R: AsRef<Path>, { from(BufReader::new(File::open(path)?)) } /// Load an image from an input stream with the given format. /// /// # Example /// /// ``` /// use std::fs::File; /// /// use picto::read; /// use picto::color::Rgb; /// use picto::Format; /// /// read::with_format::<Rgb, u8, _>(File::open("tests/boat.xyz").unwrap(), Format::Xyz).unwrap(); /// ``` pub fn with_format<P, C, R>(input: R, format: Format) -> error::Result<Buffer<P, C, Vec<C>>> where P: From<color::Rgb> + From<color::Rgba> + From<color::Luma> + From<color::Lumaa>, P: pixel::Write<C>, C: pixel::Channel, R: Read + Seek, { match format { #[cfg(feature = "png")] Format::Png => png(input, |_| {}), #[cfg(feature = "jpeg")] Format::Jpeg => jpeg(input, |_| {}), #[cfg(feature = "bmp")] Format::Bmp => bmp(input, |_| {}), #[cfg(feature = "tga")] Format::Tga => tga(input, |_| {}), #[cfg(feature = "gif")] Format::Gif => gif(input, |_| {}), #[cfg(feature = "xyz")] Format::Xyz => xyz(input, |_| {}), _ => Err(Error::Unsupported("unsupported image format".into())), } } /// Load a PNG image from an input stream, with the ability to set parameters /// on the decoder. #[cfg(feature = "png")] #[inline] pub fn png<P, C, F, R>(input: R, func: F) -> error::Result<Buffer<P, C, Vec<C>>> where P: From<color::Rgb> + From<color::Rgba> + From<color::Luma> + From<color::Lumaa>, P: pixel::Write<C>, C: pixel::Channel, F: FnOnce(&mut decoder::png::Decoder<R>), R: Read, { let mut decoder = decoder::png::Decoder::new(input); func(&mut decoder); decoder.frame() } /// Load a JPEG image from an input stream, with the ability to set parameters /// on the decoder. #[cfg(feature = "jpeg")] #[inline] pub fn jpeg<P, C, F, R>(input: R, func: F) -> error::Result<Buffer<P, C, Vec<C>>> where P: From<color::Rgb> + From<color::Luma>, P: pixel::Write<C>, C: pixel::Channel, F: FnOnce(&mut decoder::jpeg::Decoder<R>), R: Read, { let mut decoder = decoder::jpeg::Decoder::new(input); func(&mut decoder); decoder.frame() } /// Load a BMP image from an input stream, with the ability to set parameters /// on the decoder. #[cfg(feature = "bmp")] #[inline] pub fn bmp<P, C, F, R>(input: R, func: F) -> error::Result<Buffer<P, C, Vec<C>>> where P: From<color::Rgb> + From<color::Rgba>, P: pixel::Write<C>, C: pixel::Channel, F: FnOnce(&mut decoder::bmp::Decoder<R>), R: Read + Seek, { let mut decoder = decoder::bmp::Decoder::new(input); func(&mut decoder); decoder.frame() } /// Load a TGA image from an input stream, with the ability to set parameters /// on the decoder. #[cfg(feature = "tga")] #[inline] pub fn tga<P, C, F, R>(input: R, func: F) -> error::Result<Buffer<P, C, Vec<C>>> where P: From<color::Rgb> + From<color::Rgba> + From<color::Luma> + From<color::Lumaa>, P: pixel::Write<C>, C: pixel::Channel, F: FnOnce(&mut decoder::tga::Decoder<R>), R: Read + Seek, { let mut decoder = decoder::tga::Decoder::new(input); func(&mut decoder); decoder.frame() } /// Load a GIF image from an input stream, with the ability to set parameters /// on the decoder. #[cfg(feature = "gif")] #[inline] pub fn gif<P, C, F, R>(input: R, func: F) -> error::Result<Buffer<P, C, Vec<C>>> where P: From<color::Rgb> + From<color::Rgba> + From<color::Luma> + From<color::Lumaa>, P: pixel::Write<C>, C: pixel::Channel, F: FnOnce(&mut decoder::gif::Decoder<R>), R: Read, { let mut decoder = decoder::gif::Decoder::new(input); func(&mut decoder); decoder.frame() } /// Load an XYZ image from an input stream, with the ability to set parameters /// on the decoder. #[cfg(feature = "xyz")] #[inline] pub fn xyz<P, C, F, R>(input: R, func: F) -> error::Result<Buffer<P, C, Vec<C>>> where P: From<color::Rgb> + From<color::Rgba>, P: pixel::Write<C>, C: pixel::Channel, F: FnOnce(&mut decoder::xyz::Decoder<R>), R: Read, {
let mut decoder = decoder::xyz::Decoder::new(input); func(&mut decoder); decoder.frame() }
menu.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-menu', templateUrl: './menu.component.html' }) export class MenuComponent { nav: Nav[] = [ { link: '/home', name:'Home', exact: true, admin: false },
admin: false }, { link: '/sobre', name:'Sobre', exact: true, admin: false }, { link: '/produtos', name:'Produtos', exact: false, admin: false }, { link: '/filmes', name: 'Filmes', exact: false, admin: false }, { link: '/bar', name: 'Bar', exact: false, admin: false }, { link: '/todo', name: 'To Do', exact: false, admin: false }, { link: '/contador', name: 'Contador', exact: false, admin: false }, { link: '/admin', name:'Admin', exact: false, admin: false } ]; } interface Nav{ link: string; name: string; exact: boolean; admin:boolean; }
{ link: '/cadastro', name:'Cadastro', exact: true,
peer.go
package peer import ( "github.com/hedianbin/godcoin/protocol" "github.com/hedianbin/godcoin/util/hashx" ) // Peer extends the node to maintain state shared by the server type Peer struct { node *Node boardcastQueue chan *RequestInfo singleQueue chan *RequestInfo receiveQueue chan *Request messageHandler MessageHandle continueHash *hashx.Hash } func
(listenAddr, seedAddr string, msgHandler MessageHandle) *Peer{ p := new(Peer) p.singleQueue = make(chan *RequestInfo, 10) p.boardcastQueue = make(chan *RequestInfo, 10) p.receiveQueue = make(chan *Request, 10) p.messageHandler = msgHandler p.node = NewNode(listenAddr, seedAddr, p.boardcastQueue, p.receiveQueue, p.singleQueue) return p } func (p *Peer) StartListen() error{ go p.ReciveMessage() return p.node.startNode() } func (p *Peer) GetSeedAddr() string{ return p.node.seedAddr } // GetListenAddr get peer listen addr func (p *Peer) GetListenAddr() string{ return p.node.listenAddr } // BroadcastMessage send message to all downstream nodes and seed node func (p *Peer) SendSingleMessage(msg protocol.Message){ req := &RequestInfo{ Data:msg, FromAddr:msg.GetFromAddr(), } p.singleQueue <- req } // BroadcastMessage send message to all downstream nodes and seed node func (p *Peer) BroadcastMessage(msg protocol.Message){ p.boardcastQueue <- &RequestInfo{ Data:msg, FromAddr:"", } } // RouteMessage send message to all downstream nodes and seed node without source node func (p *Peer) SendRouteMessage(msg protocol.Message){ p.boardcastQueue <- &RequestInfo{ Data:msg, FromAddr:msg.GetFromAddr(), } }
NewPeer
unit.rs
use serde::{Deserialize, Serialize}; use crate::prototypes::{Prototype, Visitor}; use crate::types::*; // TODO: Import only specific types #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Unit { /// attack_parameters :: AttackParameters attack_parameters: AttackParameters,
/// distraction_cooldown :: uint32 distraction_cooldown: u32, /// movement_speed :: float movement_speed: f32, /// pollution_to_join_attack :: float pollution_to_join_attack: f32, /// run_animation :: RotatedAnimation run_animation: RotatedAnimation, /// vision_distance :: double vision_distance: f64, /// affected_by_tiles :: bool (optional) affected_by_tiles: Option<bool>, /// ai_settings :: UnitAISettings (optional) ai_settings: Option<UnitAISettings>, /// alternative_attacking_frame_sequence :: table (optional) alternative_attacking_frame_sequence: Option<Vec<Todo>>, /// can_open_gates :: bool (optional) can_open_gates: Option<bool>, /// dying_sound :: Sound (optional) dying_sound: Option<Sound>, /// has_belt_immunity :: bool (optional) has_belt_immunity: Option<bool>, /// light :: LightDefinition (optional) light: Option<LightDefinition>, /// max_pursue_distance :: double (optional) max_pursue_distance: Option<f64>, /// min_pursue_time :: uint32 (optional) min_pursue_time: Option<u32>, /// move_while_shooting :: bool (optional) move_while_shooting: Option<bool>, /// radar_range :: uint32 (optional) radar_range: Option<u32>, /// render_layer :: RenderLayer (optional) render_layer: Option<RenderLayer>, /// rotation_speed :: float (optional) rotation_speed: Option<f32>, /// running_sound_animation_positions :: table (array) of float (optional) running_sound_animation_positions: Option<Vec<f32>>, /// spawning_time_modifier :: double (optional) spawning_time_modifier: Option<f64>, /// walking_sound :: Sound (optional) walking_sound: Option<Sound>, } impl Prototype for Unit { const TYPE: Option<&'static str> = Some("unit"); }
/// distance_per_frame :: float distance_per_frame: f32,
job_creator.go
package quarksjob import ( "context" "fmt" "path/filepath" "github.com/pkg/errors" batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" crc "sigs.k8s.io/controller-runtime/pkg/client" qjv1a1 "code.cloudfoundry.org/quarks-job/pkg/kube/apis/quarksjob/v1alpha1" "code.cloudfoundry.org/quarks-job/pkg/kube/util/config" "code.cloudfoundry.org/quarks-job/pkg/kube/util/reference" sharedcfg "code.cloudfoundry.org/quarks-utils/pkg/config" "code.cloudfoundry.org/quarks-utils/pkg/ctxlog" "code.cloudfoundry.org/quarks-utils/pkg/names" vss "code.cloudfoundry.org/quarks-utils/pkg/versionedsecretstore" ) const ( outputPersistDirName = "output-persist-dir" outputPersistDirMountPath = "/mnt/output-persist/" mountPath = "/mnt/quarks/" // EnvNamespace is the namespace in which the jobs run, used by // persist-output to create the secrets EnvNamespace = "WATCH_NAMESPACE" ) type setOwnerReferenceFunc func(owner, object metav1.Object, scheme *runtime.Scheme) error // NewJobCreator returns a new job creator func NewJobCreator(client crc.Client, scheme *runtime.Scheme, f setOwnerReferenceFunc, config *config.Config, store vss.VersionedSecretStore) JobCreator
// JobCreator is the interface that wraps the basic Create method. type JobCreator interface { Create(ctx context.Context, qJob qjv1a1.QuarksJob, namespace string) (retry bool, err error) } type jobCreatorImpl struct { client crc.Client scheme *runtime.Scheme setOwnerReference setOwnerReferenceFunc config *config.Config store vss.VersionedSecretStore } // Create satisfies the JobCreator interface. It creates a Job to complete ExJob. It returns the // retry if one of the references are not present. func (j jobCreatorImpl) Create(ctx context.Context, qJob qjv1a1.QuarksJob, namespace string) (bool, error) { template := qJob.Spec.Template.DeepCopy() serviceAccountVolume, serviceAccountVolumeMount, err := j.serviceAccountMount(ctx, namespace, j.config.ServiceAccount) if err != nil { return false, err } // Set serviceaccount to the container template.Spec.Template.Spec.Volumes = append(template.Spec.Template.Spec.Volumes, *serviceAccountVolume) ctxlog.Debugf(ctx, "Add persist output container, using DOCKER_IMAGE_TAG=%s", sharedcfg.GetOperatorDockerImage()) // Create a container for persisting output outputPersistContainer := corev1.Container{ Name: "output-persist", Image: sharedcfg.GetOperatorDockerImage(), ImagePullPolicy: sharedcfg.GetOperatorImagePullPolicy(), Args: []string{"persist-output"}, Env: []corev1.EnvVar{ { Name: EnvNamespace, Value: namespace, }, }, VolumeMounts: []corev1.VolumeMount{*serviceAccountVolumeMount}, } // Loop through containers and add quarks logging volume specs. for containerIndex, container := range template.Spec.Template.Spec.Containers { // Add pod volume specs to the pod podVolumeSpec := corev1.Volume{ Name: names.Sanitize(fmt.Sprintf("%s%s", "output-", container.Name)), VolumeSource: corev1.VolumeSource{EmptyDir: &corev1.EmptyDirVolumeSource{}}, } template.Spec.Template.Spec.Volumes = append(template.Spec.Template.Spec.Volumes, podVolumeSpec) // Add container volume specs to container containerVolumeMountSpec := corev1.VolumeMount{ Name: names.Sanitize(fmt.Sprintf("%s%s", "output-", container.Name)), MountPath: mountPath, } template.Spec.Template.Spec.Containers[containerIndex].VolumeMounts = append(template.Spec.Template.Spec.Containers[containerIndex].VolumeMounts, containerVolumeMountSpec) // Add container volume spec to output persist container containerVolumeMountSpec.MountPath = filepath.Join(mountPath, container.Name) outputPersistContainer.VolumeMounts = append(outputPersistContainer.VolumeMounts, containerVolumeMountSpec) } // Add output persist container to the pod template template.Spec.Template.Spec.Containers = append(template.Spec.Template.Spec.Containers, outputPersistContainer) if template.Spec.Template.Labels == nil { template.Spec.Template.Labels = map[string]string{} } template.Spec.Template.Labels[qjv1a1.LabelQJobName] = qJob.Name if err := j.store.SetSecretReferences(ctx, qJob.Namespace, &template.Spec.Template.Spec); err != nil { return false, err } // Validate quarks job configmap and secrets references err = j.validateReferences(ctx, qJob) if err != nil { if apierrors.IsNotFound(err) { // Requeue the job without error. return true, nil } return false, err } // Create k8s job name, err := names.JobName(qJob.Name) if err != nil { return false, errors.Wrapf(err, "could not generate job name for qJob '%s'", qJob.Name) } job := &batchv1.Job{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: qJob.Namespace, Labels: map[string]string{qjv1a1.LabelQJobName: qJob.Name}, }, Spec: template.Spec, } if err := j.setOwnerReference(&qJob, job, j.scheme); err != nil { return false, ctxlog.WithEvent(&qJob, "SetOwnerReferenceError").Errorf(ctx, "failed to set owner reference on job for '%s': %s", qJob.Name, err) } if err := j.client.Create(ctx, job); err != nil { if apierrors.IsAlreadyExists(err) { ctxlog.WithEvent(&qJob, "AlreadyRunning").Infof(ctx, "Skip '%s': already running", qJob.Name) // Don't requeue the job. return false, nil } return true, err } return false, nil } func (j jobCreatorImpl) validateReferences(ctx context.Context, qJob qjv1a1.QuarksJob) error { configMaps := reference.ReferencedConfigMaps(qJob) configMap := &corev1.ConfigMap{} for configMapName := range configMaps { if err := j.client.Get(ctx, crc.ObjectKey{Name: configMapName, Namespace: qJob.Namespace}, configMap); err != nil { if apierrors.IsNotFound(err) { ctxlog.Debugf(ctx, "Skip create job '%s' due to configMap '%s' not found", qJob.Name, configMapName) } return err } } secrets := reference.ReferencedSecrets(qJob) secret := &corev1.Secret{} for secretName := range secrets { if err := j.client.Get(ctx, crc.ObjectKey{Name: secretName, Namespace: qJob.Namespace}, secret); err != nil { if apierrors.IsNotFound(err) { ctxlog.Debugf(ctx, "Skip create job '%s' due to secret '%s' not found", qJob.Name, secretName) } return err } } return nil }
{ return jobCreatorImpl{ client: client, scheme: scheme, setOwnerReference: f, config: config, store: store, } }
buffer.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.hexToBuffer = exports.bufferToHex = exports.bufferToBigNumberString = exports.bigNumberToBuffer = void 0; var _browserifyBignum = _interopRequireDefault(require("browserify-bignum")); function
(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* * Copyright © 2018 Lisk Foundation * * See the LICENSE file at the top-level directory of this distribution * for licensing information. * * Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation, * no part of this software, including this file, may be copied, modified, * propagated, or distributed except according to the terms contained in the * LICENSE file. * * Removal or modification of this copyright notice is prohibited. * */ var bigNumberToBuffer = function bigNumberToBuffer(bignumber, size) { return new _browserifyBignum.default(bignumber).toBuffer({ size: size, endian: 'big' }); }; exports.bigNumberToBuffer = bigNumberToBuffer; var bufferToBigNumberString = function bufferToBigNumberString(bigNumberBuffer) { return _browserifyBignum.default.fromBuffer(bigNumberBuffer).toString(); }; exports.bufferToBigNumberString = bufferToBigNumberString; var bufferToHex = function bufferToHex(buffer) { return Buffer.from(buffer).toString('hex'); }; exports.bufferToHex = bufferToHex; var hexRegex = /^[0-9a-f]+/i; var hexToBuffer = function hexToBuffer(hex) { var argumentName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'Argument'; if (typeof hex !== 'string') { throw new TypeError("".concat(argumentName, " must be a string.")); } var matchedHex = (hex.match(hexRegex) || [])[0]; if (!matchedHex || matchedHex.length !== hex.length) { throw new TypeError("".concat(argumentName, " must be a valid hex string.")); } // tslint:disable-next-line no-magic-numbers if (matchedHex.length % 2 !== 0) { throw new TypeError("".concat(argumentName, " must have a valid length of hex string.")); } return Buffer.from(matchedHex, 'hex'); }; exports.hexToBuffer = hexToBuffer; //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9ibG9ja2NoYWluL2NyeXB0by9idWZmZXIudHMiXSwibmFtZXMiOlsiYmlnTnVtYmVyVG9CdWZmZXIiLCJiaWdudW1iZXIiLCJzaXplIiwiQmlnTnVtIiwidG9CdWZmZXIiLCJlbmRpYW4iLCJidWZmZXJUb0JpZ051bWJlclN0cmluZyIsImJpZ051bWJlckJ1ZmZlciIsImZyb21CdWZmZXIiLCJ0b1N0cmluZyIsImJ1ZmZlclRvSGV4IiwiYnVmZmVyIiwiQnVmZmVyIiwiZnJvbSIsImhleFJlZ2V4IiwiaGV4VG9CdWZmZXIiLCJoZXgiLCJhcmd1bWVudE5hbWUiLCJUeXBlRXJyb3IiLCJtYXRjaGVkSGV4IiwibWF0Y2giLCJsZW5ndGgiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7QUFjQTs7OztBQWRBOzs7Ozs7Ozs7Ozs7OztBQWdCTyxJQUFNQSxpQkFBaUIsR0FBRyxTQUFwQkEsaUJBQW9CLENBQUNDLFNBQUQsRUFBb0JDLElBQXBCO0FBQUEsU0FDaEMsSUFBSUMseUJBQUosQ0FBV0YsU0FBWCxFQUFzQkcsUUFBdEIsQ0FBK0I7QUFBRUYsSUFBQUEsSUFBSSxFQUFKQSxJQUFGO0FBQVFHLElBQUFBLE1BQU0sRUFBRTtBQUFoQixHQUEvQixDQURnQztBQUFBLENBQTFCOzs7O0FBR0EsSUFBTUMsdUJBQXVCLEdBQUcsU0FBMUJBLHVCQUEwQixDQUFDQyxlQUFEO0FBQUEsU0FDdENKLDBCQUFPSyxVQUFQLENBQWtCRCxlQUFsQixFQUFtQ0UsUUFBbkMsRUFEc0M7QUFBQSxDQUFoQzs7OztBQUdBLElBQU1DLFdBQVcsR0FBRyxTQUFkQSxXQUFjLENBQUNDLE1BQUQ7QUFBQSxTQUMxQkMsTUFBTSxDQUFDQyxJQUFQLENBQVlGLE1BQVosRUFBb0JGLFFBQXBCLENBQTZCLEtBQTdCLENBRDBCO0FBQUEsQ0FBcEI7OztBQUdQLElBQU1LLFFBQVEsR0FBRyxhQUFqQjs7QUFDTyxJQUFNQyxXQUFXLEdBQUcsU0FBZEEsV0FBYyxDQUFDQyxHQUFELEVBQW9EO0FBQUEsTUFBdENDLFlBQXNDLHVFQUF2QixVQUF1Qjs7QUFDOUUsTUFBSSxPQUFPRCxHQUFQLEtBQWUsUUFBbkIsRUFBNkI7QUFDNUIsVUFBTSxJQUFJRSxTQUFKLFdBQWlCRCxZQUFqQix3QkFBTjtBQUNBOztBQUNELE1BQU1FLFVBQVUsR0FBRyxDQUFDSCxHQUFHLENBQUNJLEtBQUosQ0FBVU4sUUFBVixLQUF1QixFQUF4QixFQUE0QixDQUE1QixDQUFuQjs7QUFDQSxNQUFJLENBQUNLLFVBQUQsSUFBZUEsVUFBVSxDQUFDRSxNQUFYLEtBQXNCTCxHQUFHLENBQUNLLE1BQTdDLEVBQXFEO0FBQ3BELFVBQU0sSUFBSUgsU0FBSixXQUFpQkQsWUFBakIsa0NBQU47QUFDQSxHQVA2RSxDQVE5RTs7O0FBQ0EsTUFBSUUsVUFBVSxDQUFDRSxNQUFYLEdBQW9CLENBQXBCLEtBQTBCLENBQTlCLEVBQWlDO0FBQ2hDLFVBQU0sSUFBSUgsU0FBSixXQUNGRCxZQURFLDhDQUFOO0FBR0E7O0FBRUQsU0FBT0wsTUFBTSxDQUFDQyxJQUFQLENBQVlNLFVBQVosRUFBd0IsS0FBeEIsQ0FBUDtBQUNBLENBaEJNIiwic291cmNlc0NvbnRlbnQiOlsiLypcbiAqIENvcHlyaWdodCDCqSAyMDE4IExpc2sgRm91bmRhdGlvblxuICpcbiAqIFNlZSB0aGUgTElDRU5TRSBmaWxlIGF0IHRoZSB0b3AtbGV2ZWwgZGlyZWN0b3J5IG9mIHRoaXMgZGlzdHJpYnV0aW9uXG4gKiBmb3IgbGljZW5zaW5nIGluZm9ybWF0aW9uLlxuICpcbiAqIFVubGVzcyBvdGhlcndpc2UgYWdyZWVkIGluIGEgY3VzdG9tIGxpY2Vuc2luZyBhZ3JlZW1lbnQgd2l0aCB0aGUgTGlzayBGb3VuZGF0aW9uLFxuICogbm8gcGFydCBvZiB0aGlzIHNvZnR3YXJlLCBpbmNsdWRpbmcgdGhpcyBmaWxlLCBtYXkgYmUgY29waWVkLCBtb2RpZmllZCxcbiAqIHByb3BhZ2F0ZWQsIG9yIGRpc3RyaWJ1dGVkIGV4Y2VwdCBhY2NvcmRpbmcgdG8gdGhlIHRlcm1zIGNvbnRhaW5lZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZS5cbiAqXG4gKiBSZW1vdmFsIG9yIG1vZGlmaWNhdGlvbiBvZiB0aGlzIGNvcHlyaWdodCBub3RpY2UgaXMgcHJvaGliaXRlZC5cbiAqXG4gKi9cbmltcG9ydCBCaWdOdW0gZnJvbSAnYnJvd3NlcmlmeS1iaWdudW0nO1xuXG5leHBvcnQgY29uc3QgYmlnTnVtYmVyVG9CdWZmZXIgPSAoYmlnbnVtYmVyOiBzdHJpbmcsIHNpemU6IG51bWJlcikgPT5cblx0bmV3IEJpZ051bShiaWdudW1iZXIpLnRvQnVmZmVyKHsgc2l6ZSwgZW5kaWFuOiAnYmlnJyB9KTtcblxuZXhwb3J0IGNvbnN0IGJ1ZmZlclRvQmlnTnVtYmVyU3RyaW5nID0gKGJpZ051bWJlckJ1ZmZlcjogQnVmZmVyKTogc3RyaW5nID0+XG5cdEJpZ051bS5mcm9tQnVmZmVyKGJpZ051bWJlckJ1ZmZlcikudG9TdHJpbmcoKTtcblxuZXhwb3J0IGNvbnN0IGJ1ZmZlclRvSGV4ID0gKGJ1ZmZlcjogQnVmZmVyKTogc3RyaW5nID0+XG5cdEJ1ZmZlci5mcm9tKGJ1ZmZlcikudG9TdHJpbmcoJ2hleCcpO1xuXG5jb25zdCBoZXhSZWdleCA9IC9eWzAtOWEtZl0rL2k7XG5leHBvcnQgY29uc3QgaGV4VG9CdWZmZXIgPSAoaGV4OiBzdHJpbmcsIGFyZ3VtZW50TmFtZSA9ICdBcmd1bWVudCcpOiBCdWZmZXIgPT4ge1xuXHRpZiAodHlwZW9mIGhleCAhPT0gJ3N0cmluZycpIHtcblx0XHR0aHJvdyBuZXcgVHlwZUVycm9yKGAke2FyZ3VtZW50TmFtZX0gbXVzdCBiZSBhIHN0cmluZy5gKTtcblx0fVxuXHRjb25zdCBtYXRjaGVkSGV4ID0gKGhleC5tYXRjaChoZXhSZWdleCkgfHwgW10pWzBdO1xuXHRpZiAoIW1hdGNoZWRIZXggfHwgbWF0Y2hlZEhleC5sZW5ndGggIT09IGhleC5sZW5ndGgpIHtcblx0XHR0aHJvdyBuZXcgVHlwZUVycm9yKGAke2FyZ3VtZW50TmFtZX0gbXVzdCBiZSBhIHZhbGlkIGhleCBzdHJpbmcuYCk7XG5cdH1cblx0Ly8gdHNsaW50OmRpc2FibGUtbmV4dC1saW5lIG5vLW1hZ2ljLW51bWJlcnNcblx0aWYgKG1hdGNoZWRIZXgubGVuZ3RoICUgMiAhPT0gMCkge1xuXHRcdHRocm93IG5ldyBUeXBlRXJyb3IoXG5cdFx0XHRgJHthcmd1bWVudE5hbWV9IG11c3QgaGF2ZSBhIHZhbGlkIGxlbmd0aCBvZiBoZXggc3RyaW5nLmAsXG5cdFx0KTtcblx0fVxuXG5cdHJldHVybiBCdWZmZXIuZnJvbShtYXRjaGVkSGV4LCAnaGV4Jyk7XG59O1xuIl19
_interopRequireDefault
lib.rs
#[macro_use] extern crate log; #[cfg(test)] #[macro_use] extern crate pest; #[cfg(not(test))] extern crate pest; #[macro_use] extern crate pest_derive; extern crate codegen; extern crate failure; extern crate heck; extern crate regex; #[macro_use] extern crate lazy_static; use codegen::{Field, Scope, Struct}; use failure::Error; use heck::{CamelCase, SnakeCase}; use pest::iterators::Pairs; use pest::Parser; use regex::Regex; use std::boxed::Box; use std::collections::HashSet; use std::fmt; use std::fs::File; use std::io::prelude::*; use std::path::PathBuf; #[derive(Parser)] #[grammar = "aws_go_events.pest"] pub struct AwsGoEventsParser; #[derive(Debug, Clone, PartialEq)] pub struct GoCode(String); impl fmt::Display for GoCode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } #[derive(Debug, Clone)] pub struct RustCode(Scope); impl RustCode { pub fn new(text: String) -> Self { RustCode(Scope::new().raw(&text).clone()) } pub fn scope(&self) -> codegen::Scope { self.0.clone() } pub fn push_module(&mut self, m: codegen::Module) -> &mut Self { self.0.push_module(m); self } } impl fmt::Display for RustCode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0.to_string()) } } impl PartialEq for RustCode { fn eq(&self, other: &RustCode) -> bool { self.0.to_string() == other.to_string() } } pub fn parse_go_file(path: &PathBuf) -> Result<(GoCode, RustCode), Error> { debug!("Parsing path: {:?}", &path.display()); // Read the go code. let mut f = File::open(path)?; let mut go_code = String::new(); f.read_to_string(&mut go_code)?; debug!("\n{}\n", go_code); // parse the go code into rust code. Ok(parse_go_string(go_code)?) } fn add_sorted_imports(scope: &mut Scope, libraries: &HashSet<String>) { // Stable sort the libraries. let mut ordered_libs: Vec<String> = libraries.iter().cloned().collect(); ordered_libs.sort(); // Import required libraries. for lib in ordered_libs { // Lame. let parts: Vec<&str> = lib.rsplitn(2, "::").collect(); scope.import(parts[1], parts[0]); } } pub fn parse_go_string(go_source: String) -> Result<(GoCode, RustCode), Error> { let source = go_source.clone(); let pairs = AwsGoEventsParser::parse(Rule::aws_go_events, &source.trim()) .unwrap_or_else(|e| panic!("{}", e)); let mut scope = Scope::new(); for pair in pairs { match pair.as_rule() { Rule::struct_def => { let (parsed_struct, required_libraries) = parse_struct(pair.into_inner())?; scope.push_struct(parsed_struct); add_sorted_imports(&mut scope, &required_libraries); } Rule::type_alias => { let alias = parse_type_alias(pair.into_inner())?; if let Some((name, target)) = alias { add_sorted_imports(&mut scope, &target.libraries); // XXX: Add type definition support to `codegen` for a in target.annotations { scope.raw(&format!("#[{}]", a)); } scope.raw(&format!("pub type {} = {};", name, target.value)); } } // Skip some things for now. Rule::any_comment | Rule::constant_def | Rule::package_def | Rule::import | Rule::import_multiple | Rule::function | Rule::enum_options => { debug!("Skipping: {}", pair.clone().into_span().as_str()); () } _ => { panic!( "Unexpected item at top-level:\n{:?}\n{}", pair.clone(), pair.clone().into_span().as_str() ); } } } debug!("{}", &scope.to_string()); /* let formatted_code = rustfmt_nightly::format_code_block(&scope.to_string(), &rustfmt_nightly::Config::default()) .expect("formatted code"); */ Ok((GoCode(go_source), RustCode(scope))) } #[derive(Debug, Clone)] struct FieldDef { name: String, json_name: Option<String>, comments: Vec<String>, omit_empty: bool, go_type: GoType, } fn parse_comment(c: &str) -> String { c.replacen("//", "", 1).trim().to_string() } fn parse_type_alias(pairs: Pairs<Rule>) -> Result<Option<(String, RustType)>, Error> { debug!("Parsing type alias"); let mut value = None; for pair in pairs { match pair.as_rule() { Rule::local_type_alias => { value = parse_local_type_alias(pair.into_inner())?; } Rule::package_type_alias => { value = parse_package_type_alias(pair.into_inner())?; } _ => unreachable!(), } } Ok(value) } fn parse_local_type_alias(pairs: Pairs<Rule>) -> Result<Option<(String, RustType)>, Error> { debug!("Parsing local type alias"); let mut name: Option<String> = None; let mut target: Option<GoType> = None; for pair in pairs { let span = pair.clone().into_span(); match pair.as_rule() { Rule::ident => name = Some(mangle(span.as_str())), Rule::type_alias_target => { target = Some(parse_go_type(pair.into_inner())?); } _ => unreachable!(), } } let name = name.expect("parsed name"); let target = target.expect("parsed target"); Ok(Some((name, translate_go_type_to_rust_type(target)?))) } fn parse_package_type_alias(pairs: Pairs<Rule>) -> Result<Option<(String, RustType)>, Error> { debug!("Parsing package type alias"); let mut name: Option<String> = None; let mut target: Option<GoType> = None; for pair in pairs { let span = pair.clone().into_span(); let value = span.as_str(); match pair.as_rule() { Rule::ident => name = Some(mangle(span.as_str())), Rule::package_ident => { target = Some(parse_go_package_ident(value)?); } _ => unreachable!(), } } let name = name.expect("parsed name"); let target = target.expect("parsed target"); Ok(Some((name, translate_go_type_to_rust_type(target)?))) } fn parse_struct(pairs: Pairs<Rule>) -> Result<(codegen::Struct, HashSet<String>), Error> { debug!("Parsing struct"); let mut name: Option<String> = None; let mut fields: Vec<FieldDef> = Vec::new(); let mut comments: Vec<String> = Vec::new(); for pair in pairs { let span = pair.clone().into_span(); match pair.as_rule() { Rule::doc_comment => { comments.push(parse_comment(span.as_str())); } Rule::struct_preamble => { name = Some(parse_struct_preamble(pair.into_inner())?); } Rule::struct_fields => { fields = parse_struct_fields(pair.into_inner())?; } _ => unreachable!(), } } let struct_name = name.expect("parsed name"); let mut rust_struct = Struct::new(&struct_name.to_camel_case()); // Make it public. rust_struct.vis("pub"); // Add some derives. rust_struct.derive("Debug"); rust_struct.derive("Clone"); rust_struct.derive("PartialEq"); rust_struct.derive("Deserialize"); rust_struct.derive("Serialize"); if !comments.is_empty() { let annotated_comments: Vec<String> = comments .iter_mut() .map(|x| x.replace(&struct_name, &format!("`{}`", &struct_name.to_camel_case()))) .collect(); rust_struct.doc(&annotated_comments.join("\n")); } lazy_static! { static ref HASHMAP_RE: Regex = Regex::new("^HashMap<.+>$").expect("regex to compile"); } let mut libraries: HashSet<String> = HashSet::new(); for f in fields { // Translate the name. let member_name = mangle(&f.name.to_snake_case()); // Extract the code and the libraries from the result. let mut rust_data = translate_go_type_to_rust_type(f.go_type)?; for lib in rust_data.libraries.iter() { libraries.insert(lib.clone()); } let mut rust_type = rust_data.value; // Make fields optional if they are optional in the json. if f.omit_empty { // We don't do this for HashMaps as they are handled special below. if !HASHMAP_RE.is_match(&rust_type) { rust_type = format!("Option<{}>", rust_type); } } if let Some(rename) = f.json_name.clone() { if rename != member_name { rust_data .annotations .push(format!("#[serde(rename = \"{}\")]", rename)); } } let mut field_defs = vec![]; // Go converts null strings to "". Let consumers choose how they want // to handle that. if rust_type == "String" { libraries.insert("custom_serde::*".to_string()); let mut string_as_option = Field::new(&member_name, "Option<String>"); string_as_option.annotation(vec![ "#[cfg(not(feature = \"string-null-empty\"))]", "#[serde(deserialize_with = \"deserialize_lambda_string\")]", "#[serde(default)]", ]); field_defs.push(string_as_option); let mut string_as_empty = Field::new(&member_name, &rust_type); string_as_empty.annotation(vec![ "#[cfg(feature = \"string-null-empty\")]", "#[serde(deserialize_with = \"deserialize_lambda_string\")]", "#[serde(default)]", ]); field_defs.push(string_as_empty); } else if HASHMAP_RE.is_match(&rust_type) { libraries.insert("custom_serde::*".to_string()); // We default to an empty `HashMap` regardless. let mut map_as_empty = Field::new(&member_name, &rust_type); map_as_empty.annotation(vec![ "#[serde(deserialize_with = \"deserialize_lambda_map\")]", "#[serde(default)]", ]); field_defs.push(map_as_empty); } else { field_defs = vec![Field::new(&member_name, &rust_type)]; } for mut field in field_defs { // Fields are public. field.vis("pub"); if !f.comments.is_empty() { field.doc(&f.comments.join("\n")); } if !rust_data.annotations.is_empty() { let mut all_annotations: Vec<String> = field.get_annotation(); let mut new_annotations: Vec<String> = rust_data.annotations.clone(); all_annotations.append(&mut new_annotations); field.annotation(all_annotations.iter().map(String::as_str).collect()); } rust_struct.push_field(field); } } Ok((rust_struct, libraries)) } fn parse_struct_preamble(pairs: Pairs<Rule>) -> Result<String, Error> { debug!("Parsing struct preamble"); let mut name: Option<String> = None; for pair in pairs { let span = pair.clone().into_span(); match pair.as_rule() { Rule::struct_name => { name = Some(span.as_str().to_string()); } _ => unimplemented!(), } } Ok(name.expect("structs always have a name")) } fn
(pairs: Pairs<Rule>) -> Result<Vec<FieldDef>, Error> { debug!("Parsing struct fields"); let mut fields: Vec<FieldDef> = Vec::new(); for pair in pairs { match pair.as_rule() { Rule::struct_field => fields.push(parse_struct_field(pair.into_inner())?), _ => unimplemented!(), } } Ok(fields) } fn parse_struct_field(pairs: Pairs<Rule>) -> Result<FieldDef, Error> { debug!("Parsing struct field"); let mut name: Option<String> = None; let mut json: Option<JsonMapping> = None; let mut go_type: Option<GoType> = None; let mut comments: Vec<String> = vec![]; let mut is_pointer = false; for pair in pairs { debug!("{:?}", pair); let span = pair.clone().into_span(); match pair.as_rule() { Rule::ident => name = Some(mangle(span.as_str())), Rule::json_mapping => json = Some(parse_json_mapping(pair.into_inner())?), Rule::pointer => is_pointer = true, Rule::struct_field_type => go_type = Some(parse_go_type(pair.into_inner())?), Rule::doc_comment => comments.push(parse_comment(span.as_str())), _ => unimplemented!(), } } let json_name = if let Some(j) = json.clone() { Some(j.name) } else { None }; let mut omit_empty = if let Some(j) = json.clone() { // We omit empty (aka use an Option) if the JSON says so. j.omit_empty } else { // By default we don't omit empty. false }; if is_pointer { // If given a pointer, it can be `nil` and essentially empty. omit_empty = true } // Parse inline comment after json definition. if let Some(j) = json { if let Some(inline_comment) = j.comment { if !comments.is_empty() { // Append inline comment with a blank comment line before it. comments.push("".to_string()); } comments.push(inline_comment) } }; Ok(FieldDef { name: name.expect("fields have names"), json_name, comments, omit_empty, go_type: go_type.expect("fields have types"), }) } #[derive(Debug, Clone)] struct JsonMapping { name: String, comment: Option<String>, omit_empty: bool, } fn parse_json_mapping(pairs: Pairs<Rule>) -> Result<JsonMapping, Error> { debug!("Parsing json mapping"); let mut name: Option<String> = None; let mut comment: Option<String> = None; let mut omit_empty = false; for pair in pairs { debug!("{:?}", pair); let span = pair.clone().into_span(); match pair.as_rule() { Rule::json_name => name = Some(span.as_str().to_string()), Rule::any_comment => comment = Some(parse_comment(span.as_str())), Rule::omit_empty => omit_empty = true, _ => unimplemented!(), } } Ok(JsonMapping { name: name.expect("json mappings always have a name"), comment, omit_empty, }) } #[derive(Debug, Clone)] enum GoType { StringType, IntType, UnsignedIntType, FloatType, BoolType, ByteType, UserDefined(String), ArrayType(Box<GoType>), MapType(Box<GoType>, Box<GoType>), InterfaceType, TimeType, TimestampMillisecondsType, TimestampSecondsType, JsonRawType, } struct RustType { annotations: Vec<String>, libraries: HashSet<String>, value: String, } fn parse_go_type(pairs: Pairs<Rule>) -> Result<GoType, Error> { debug!("Parsing go type"); let mut go_type: Option<GoType> = None; for pair in pairs { debug!("{:?}", pair); let value = pair.clone().into_span().as_str(); go_type = match pair.as_rule() { Rule::array => Some(parse_go_type_array(pair.into_inner())?), Rule::primitive => Some(parse_go_type_primitive(value)?), Rule::ident => Some(parse_go_ident(value)?), Rule::package_ident => Some(parse_go_package_ident(value)?), Rule::map => Some(parse_go_type_map(pair.into_inner())?), Rule::interface => Some(parse_go_type_interface(value)?), _ => unimplemented!(), }; } Ok(go_type.expect("parsing go type")) } fn parse_go_type_array(pairs: Pairs<Rule>) -> Result<GoType, Error> { debug!("Parsing go array"); let mut go_type: Option<GoType> = None; for pair in pairs { debug!("{:?}", pair); let value = pair.clone().into_span().as_str(); go_type = match pair.as_rule() { Rule::primitive => Some(GoType::ArrayType(Box::new(parse_go_type_primitive(value)?))), Rule::ident => Some(GoType::ArrayType(Box::new(GoType::UserDefined( value.to_string(), )))), Rule::map => Some(GoType::ArrayType(Box::new(parse_go_type_map( pair.into_inner(), )?))), Rule::array => Some(GoType::ArrayType(Box::new(parse_go_type_array( pair.into_inner(), )?))), _ => unimplemented!(), }; } Ok(go_type.expect("parsing go array")) } fn parse_go_type_map(pairs: Pairs<Rule>) -> Result<GoType, Error> { debug!("Parsing go map"); let mut key_type: Option<GoType> = None; let mut value_type: Option<GoType> = None; for pair in pairs { debug!("{:?}", pair); let value = pair.clone().into_span().as_str(); match pair.as_rule() { Rule::key_type => key_type = Some(parse_go_type_primitive(value)?), Rule::value_type => value_type = Some(parse_go_type(pair.into_inner())?), _ => unimplemented!(), }; } Ok(GoType::MapType( Box::new(key_type.expect("parsing map key")), Box::new(value_type.expect("parsing map value")), )) } fn parse_go_type_interface(_t: &str) -> Result<GoType, Error> { // For now we don't parse. Ok(GoType::InterfaceType) } fn parse_go_type_primitive(t: &str) -> Result<GoType, Error> { match t { "string" => Ok(GoType::StringType), "int" | "int32" | "int64" => Ok(GoType::IntType), "uint" | "uint32" | "uint64" => Ok(GoType::UnsignedIntType), "float" | "float32" | "float64" => Ok(GoType::FloatType), "bool" => Ok(GoType::BoolType), "byte" => Ok(GoType::ByteType), _ => unimplemented!("missing go type primitive"), } } fn parse_go_ident(t: &str) -> Result<GoType, Error> { match t { "MilliSecondsEpochTime" => Ok(GoType::TimestampMillisecondsType), "SecondsEpochTime" => Ok(GoType::TimestampSecondsType), _ => Ok(GoType::UserDefined(t.to_string())), } } fn parse_go_package_ident(t: &str) -> Result<GoType, Error> { match t { "time.Time" => Ok(GoType::TimeType), "json.RawMessage" => Ok(GoType::JsonRawType), _ => unimplemented!("missing go package ident mapping"), } } fn mangle(s: &str) -> String { // TODO: Add more keywords. match s { "ref" => "ref_".to_string(), "type" => "type_".to_string(), _ => s.to_string(), } } fn make_rust_type_with_no_libraries(value: &str) -> RustType { RustType { annotations: vec![], value: value.to_string(), libraries: HashSet::new(), } } fn translate_go_type_to_rust_type(go_type: GoType) -> Result<RustType, Error> { let rust_type = match &go_type { GoType::StringType => make_rust_type_with_no_libraries("String"), GoType::BoolType => make_rust_type_with_no_libraries("bool"), GoType::ByteType => make_rust_type_with_no_libraries("u8"), GoType::IntType => make_rust_type_with_no_libraries("i64"), GoType::UnsignedIntType => make_rust_type_with_no_libraries("u64"), GoType::FloatType => make_rust_type_with_no_libraries("f64"), GoType::UserDefined(x) => make_rust_type_with_no_libraries(&x.to_camel_case()), GoType::ArrayType(x) => { let mut i = translate_go_type_to_rust_type(*x.clone())?; let mut libraries = HashSet::new(); libraries.insert("super::super::encodings::Base64Data".to_string()); if i.value == "u8" { // Handle []u8 special, as it is base64 encoded. RustType { annotations: vec![], value: "Base64Data".to_string(), libraries: libraries, } } else { RustType { annotations: vec![], value: format!("Vec<{}>", i.value), libraries: i.libraries, } } } GoType::MapType(k, v) => { let key_data = translate_go_type_to_rust_type(*k.clone())?; let value_data = translate_go_type_to_rust_type(*v.clone())?; let key_libs: HashSet<String> = key_data.libraries.iter().cloned().collect(); let value_libs: HashSet<String> = value_data.libraries.iter().cloned().collect(); let mut libraries: HashSet<String> = key_libs.union(&value_libs).cloned().collect(); libraries.insert("std::collections::HashMap".to_string()); RustType { annotations: vec![], value: format!("HashMap<{}, {}>", key_data.value, value_data.value), libraries, } } // For now we treat interfaces as a generic JSON value and make callers // deal with it. GoType::InterfaceType => { let mut libraries = HashSet::new(); libraries.insert("serde_json::Value".to_string()); RustType { annotations: vec![], value: "Value".to_string(), libraries, } } GoType::JsonRawType => { let mut libraries = HashSet::new(); libraries.insert("serde_json::Value".to_string()); RustType { annotations: vec![], value: "Value".to_string(), libraries, } } GoType::TimestampSecondsType => { let mut libraries = HashSet::new(); libraries.insert("super::super::encodings::SecondTimestamp".to_string()); RustType { annotations: vec![], value: "SecondTimestamp".to_string(), libraries, } } GoType::TimestampMillisecondsType => { let mut libraries = HashSet::new(); libraries.insert("super::super::encodings::MillisecondTimestamp".to_string()); RustType { annotations: vec![], value: "MillisecondTimestamp".to_string(), libraries, } } GoType::TimeType => { // No need for custom deserialization as Go's time.Time type // deserializes to chrono's default format. Neat. let mut libraries = HashSet::new(); libraries.insert("chrono::DateTime".to_string()); libraries.insert("chrono::Utc".to_string()); RustType { annotations: vec![], value: "DateTime<Utc>".to_string(), libraries, } } }; Ok(rust_type) } #[cfg(test)] mod tests { use super::*; mod primitives { use super::*; #[test] fn test_parses_array() { parses_to! { parser: AwsGoEventsParser, input: "[]bool", rule: Rule::array, tokens: [ array(0, 6, [ primitive(2, 6, [ boolean(2, 6), ]), ]), ] }; parses_to! { parser: AwsGoEventsParser, input: "[]blah", rule: Rule::array, tokens: [ array(0, 6, [ ident(2, 6), ]), ] }; } #[test] fn test_parses_map() { parses_to! { parser: AwsGoEventsParser, input: "map[string]interface{}", rule: Rule::map, tokens: [ map(0, 22, [ key_type(4, 10, [ primitive(4, 10, [ string(4, 10), ]), ]), value_type(11, 22, [ interface(11, 22), ]), ]), ] }; } } mod directives { use super::*; #[test] fn test_parses_package_def() { parses_to! { parser: AwsGoEventsParser, input: "package foo", rule: Rule::package_def, tokens: [ package_def(0, 11, [ ident(8, 11), ]), ] }; } #[test] fn test_parses_struct_def() { parses_to! { parser: AwsGoEventsParser, input: "type MyFoo struct {}", rule: Rule::struct_def, tokens: [ struct_def(0, 20, [ struct_preamble(0, 17, [ struct_name(5, 10, [ ident(5, 10), ]), ]), ]), ] }; parses_to! { parser: AwsGoEventsParser, input: "type MyFoo struct { foo string }", rule: Rule::struct_def, tokens: [ struct_def(0, 32, [ struct_preamble(0, 17, [ struct_name(5, 10, [ ident(5, 10), ]), ]), struct_fields(20, 31, [ struct_field(20, 31, [ ident(20, 23), struct_field_type(24, 30, [ primitive(24, 30, [ string(24, 30) ]), ]), ]), ]), ]), ] }; parses_to! { parser: AwsGoEventsParser, input: r#"type MyFoo struct { foo string bar int }"#, rule: Rule::struct_def, tokens: [ struct_def(0, 92, [ struct_preamble(0, 17, [ struct_name(5, 10, [ ident(5, 10), ]), ]), struct_fields(38, 74, [ struct_field(38, 48, [ ident(38, 41), struct_field_type(42, 48, [ primitive(42, 48, [ string(42, 48) ]), ]), ]), struct_field(67, 74, [ ident(67, 70), struct_field_type(71, 74, [ primitive(71, 74, [ int(71, 74) ]), ]), ]), ]), ]), ] }; } #[test] fn test_parses_struct_field() { parses_to! { parser: AwsGoEventsParser, input: "EventVersion string", rule: Rule::struct_field, tokens: [ struct_field(0, 19, [ ident(0, 12), struct_field_type(13, 19, [ primitive(13, 19, [ string(13, 19), ]), ]), ]), ] }; parses_to! { parser: AwsGoEventsParser, input: "EventVersion bool", rule: Rule::struct_field, tokens: [ struct_field(0, 17, [ ident(0, 12), struct_field_type(13, 17, [ primitive(13, 17, [ boolean(13, 17), ]), ]), ]), ] }; parses_to! { parser: AwsGoEventsParser, input: "EventVersion *bool", rule: Rule::struct_field, tokens: [ struct_field(0, 18, [ ident(0, 12), pointer(13, 14), struct_field_type(14, 18, [ primitive(14, 18, [ boolean(14, 18), ]), ]), ]), ] }; parses_to! { parser: AwsGoEventsParser, input: "EventVersion MyType", rule: Rule::struct_field, tokens: [ struct_field(0, 19, [ ident(0, 12), struct_field_type(13, 19, [ ident(13, 19), ]), ]), ] }; } #[test] fn test_parses_json_mapping() { parses_to! { parser: AwsGoEventsParser, input: "`json:\"fooBar\"`", rule: Rule::json_mapping, tokens: [ json_mapping(0, 15, [ json_name(7, 13), ]), ] }; parses_to! { parser: AwsGoEventsParser, input: "`json:\"foo-x\"`", rule: Rule::json_mapping, tokens: [ json_mapping(0, 14, [ json_name(7, 12), ]), ] }; parses_to! { parser: AwsGoEventsParser, input: "`json:\"foo.x\"`", rule: Rule::json_mapping, tokens: [ json_mapping(0, 14, [ json_name(7, 12), ]), ] }; parses_to! { parser: AwsGoEventsParser, input: "`json:\"foo,omitempty\"`", rule: Rule::json_mapping, tokens: [ json_mapping(0, 22, [ json_name(7, 10), omit_empty(10, 20), ]), ] }; parses_to! { parser: AwsGoEventsParser, input: "`json:\"fooBar\"` // whatever", rule: Rule::json_mapping, tokens: [ json_mapping(0, 27, [ json_name(7, 13), any_comment(16, 27), ]), ] }; } #[test] fn test_parses_import() { parses_to! { parser: AwsGoEventsParser, input: "import \"foo\"", rule: Rule::import, tokens: [ import(0, 12, [ import_package(7, 12, [ package_name(8, 11), ]), ]), ] }; parses_to! { parser: AwsGoEventsParser, input: "import \"a/b\"", rule: Rule::import, tokens: [ import(0, 12, [ import_package(7, 12, [ package_name(8, 11), ]), ]), ] }; } #[test] fn test_parses_mutiple_imports() { parses_to! { parser: AwsGoEventsParser, input: "import (\n\"foo\"\n \"bar\"\n)", rule: Rule::import_multiple, tokens: [ import_multiple(0, 23, [ import_package(9, 14, [ package_name(10, 13), ]), import_package(16, 21, [ package_name(17, 20), ]), ]), ] }; } } }
parse_struct_fields
config.go
package main /* Copyright (c) IBM Corporation 2016 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 Contributors: Mark Taylor - Initial Contribution */ import ( "bufio" "flag" log "github.com/Sirupsen/logrus" "mqmetric" "os" "strings" ) type mqInfluxConfig struct { qMgrName string replyQ string monitoredQueues string monitoredQueuesFile string cc mqmetric.ConnectionConfig databaseName string databaseAddress string userid string password string passwordFile string interval string maxErrors int logLevel string } var config mqInfluxConfig /* initConfig parses the command line parameters. */ func initConfig()
{ flag.StringVar(&config.qMgrName, "ibmmq.queueManager", "", "Queue Manager name") flag.StringVar(&config.replyQ, "ibmmq.replyQueue", "SYSTEM.DEFAULT.MODEL.QUEUE", "Reply Queue to collect data") flag.StringVar(&config.monitoredQueues, "ibmmq.monitoredQueues", "", "Patterns of queues to monitor") flag.StringVar(&config.monitoredQueuesFile, "ibmmq.monitoredQueuesFile", "", "File with patterns of queues to monitor") flag.BoolVar(&config.cc.ClientMode, "ibmmq.client", false, "Connect as MQ client") flag.StringVar(&config.databaseName, "ibmmq.databaseName", "", "Name of database") flag.StringVar(&config.databaseAddress, "ibmmq.databaseAddress", "", "Address of database eg http://example.com:8086") flag.StringVar(&config.userid, "ibmmq.databaseUserID", "", "UserID to access the database") flag.StringVar(&config.interval, "ibmmq.interval", "10", "How many seconds between each collection") flag.StringVar(&config.passwordFile, "ibmmq.pwFile", "", "Where is password help temporarily") flag.IntVar(&config.maxErrors, "ibmmq.maxErrors", 100, "Maximum number of errors communicating with server before considered fatal") flag.StringVar(&config.logLevel, "log.level", "error", "Log level - debug, info, error") flag.Parse() if config.monitoredQueuesFile != "" { config.monitoredQueues = mqmetric.ReadPatterns(config.monitoredQueuesFile) } // Read password from a file if there is a userid on the command line // Delete the file after reading it. if config.userid != "" { config.userid = strings.TrimSpace(config.userid) f, err := os.Open(config.passwordFile) if err != nil { log.Fatalf("Opening file %s: %s", f, err) } defer os.Remove(config.passwordFile) defer f.Close() scanner := bufio.NewScanner(f) scanner.Scan() p := scanner.Text() err = scanner.Err() if err != nil { log.Fatalf("Reading file %s: %s", f, err) } config.password = strings.TrimSpace(p) } }
elementext.rs
//! SVD Element Extensions. //! This module is extends xmltree::Element objects with convenience methods use xmltree::Element; use crate::types::{BoolParse, Parse}; use crate::error::*; /// Defines extensions for implementation over xmltree::Element pub trait ElementExt { fn get_child_text_opt<K>(&self, k: K) -> Result<Option<String>> where String: PartialEq<K>; fn get_child_text<K>(&self, k: K) -> Result<String> where String: PartialEq<K>, K: core::fmt::Display + Clone; fn get_text(&self) -> Result<String>; fn get_child_elem<'a>(&'a self, n: &str) -> Result<&'a Element>; fn get_child_u32(&self, n: &str) -> Result<u32>; fn get_child_bool(&self, n: &str) -> Result<bool>; fn merge(&self, n: &Self) -> Self; fn debug(&self); } /// Implements extensions for xmltree::Element impl ElementExt for Element { fn get_child_text_opt<K>(&self, k: K) -> Result<Option<String>> where String: PartialEq<K>, { if let Some(child) = self.get_child(k) { Ok(Some(child.get_text().map(|s| s.to_owned())?)) } else { Ok(None) } } fn get_child_text<K>(&self, k: K) -> Result<String> where String: PartialEq<K>, K: core::fmt::Display + Clone, { self.get_child_text_opt(k.clone())? .ok_or_else(|| SVDError::MissingTag(self.clone(), format!("{}", k)).into()) } /// Get text contained by an XML Element fn get_text(&self) -> Result<String> { match self.text.as_ref() { Some(s) => Ok(s.clone()), // FIXME: Doesn't look good because SVDError doesn't format by itself. We already // capture the element and this information can be used for getting the name // This would fix ParseError None => Err(SVDError::EmptyTag(self.clone(), self.name.clone()).into()), } } /// Get a named child element from an XML Element fn get_child_elem<'a>(&'a self, n: &str) -> Result<&'a Element> { match self.get_child(n) { Some(s) => Ok(s), None => Err(SVDError::MissingTag(self.clone(), n.to_string()).into()), } } /// Get a u32 value from a named child element fn get_child_u32(&self, n: &str) -> Result<u32> { let s = self.get_child_elem(n)?; u32::parse(&s).context(SVDError::ParseError(self.clone())) } /// Get a bool value from a named child element fn get_child_bool(&self, n: &str) -> Result<bool>
// Merges the children of two elements, maintaining the name and description of the first fn merge(&self, r: &Self) -> Self { let mut n = self.clone(); for c in &r.children { n.children.push(c.clone()); } n } fn debug(&self) { println!("<{}>", self.name); for c in &self.children { println!("{}: {:?}", c.name, c.text) } println!("</{}>", self.name); } }
{ let s = self.get_child_elem(n)?; BoolParse::parse(s) }
ERC165.spec.ts
import { use, expect } from 'chai'; import { waffle } from 'hardhat'; import { keccak256 } from '@ethersproject/keccak256'; import { BigNumber } from '@ethersproject/bignumber'; import BasicERC165JSON from '../../_artifacts/contracts/erc/ERC165/BasicERC165.sol/BasicERC165.json'; import ERC165StorageJSON from '../../_artifacts/contracts/erc/ERC165/ERC165.sol/ERC165Storage.json'; import ERC165AdvanceStorageJSON from '../../_artifacts/contracts/erc/ERC165/AdvanceERC165.sol/ERC165AdvanceStorage.json'; import { ERC165Storage, BasicERC165, ERC165AdvanceStorage, } from '../../_types'; use(waffle.solidity); function
(str: string): string { const re = /^0x[a-z0-9]{8}/i; return keccak256(Buffer.from(str)).match(re)?.[0] || ''; } // interface ID const supportsInterfaceID = interfaceId('supportsInterface(bytes4)'); const getID = interfaceId('get()'); const setID = interfaceId('set(uint32)'); const IAdvanceStorageID = BigNumber.from(getID).xor(BigNumber.from(setID)).toHexString(); describe('BasicERC165', () => { let contract: BasicERC165; const [wallet] = waffle.provider.getWallets(); it('supportsInterface', async () => { contract = await waffle.deployContract(wallet, BasicERC165JSON) as BasicERC165; expect(await contract.supportsInterface(supportsInterfaceID)).to.be.true; }); }); describe('ERC165Storage', () => { let contract: ERC165Storage; const [wallet] = waffle.provider.getWallets(); before(async () => { contract = await waffle.deployContract(wallet, ERC165StorageJSON) as ERC165Storage; }); it('supportsInterface', async () => { expect(await contract.supportsInterface(supportsInterfaceID)).to.be.true; }); it('get', async () => { expect(await contract.supportsInterface(getID)).to.be.true; }); it('set', async () => { expect(await contract.supportsInterface(setID)).to.be.true; }); }) describe('ERC165AdvanceStorage', () => { let contract: ERC165AdvanceStorage; const [wallet] = waffle.provider.getWallets(); before(async () => { contract = await waffle.deployContract(wallet, ERC165AdvanceStorageJSON) as ERC165AdvanceStorage; }); it('supportsInterface', async () => { expect(await contract.supportsInterface(supportsInterfaceID)).to.be.true; }); it('type(IAdvanceStorage).interfaceId', async () => { expect(await contract.supportsInterface(IAdvanceStorageID)).to.be.true; }); })
interfaceId
get.py
# Python import logging # Genie from genie.metaparser.util.exceptions import SchemaEmptyParserError log = logging.getLogger(__name__) def get_lacp_member(device, port_channel, count, member, intf_list, internal=False): """ This API parse's 'show lacp internal/neighbor' commands and return requested member Args: device (`obj`): Device object port_channel (`str`): Port channel name count (`int`): Required interface count member (`str`): Specify one of them to search ‘interface’, ‘port_num’, ‘oper_key’ or ‘partner_id’ ex.) member=‘interface’ intf_list(`list'): List of interfaces internal (`bool`): True = internal command and False = neighbor command Returns: If success, returns member value or None """ if (internal == True): out = device.parse("show lacp internal") else: out = device.parse("show lacp neighbor") port_channel = port_channel.capitalize() if ( out and "interfaces" in out and port_channel in out["interfaces"] and "members" in out["interfaces"][port_channel] ): for intf in out["interfaces"][port_channel]["members"]: if out["interfaces"][port_channel]["members"][intf][member]: if member == "partner_id": res = out["interfaces"][port_channel]["members"][intf][member] #The example value in res: 50f7.22b2.f200 res1 = ''.join([res[i] for i in range(len(res)) if res[i] != '.']) #The example value in res1: 50f722b2f200 res2 = ':'.join(res1[i:i + 2] for i in range(0, len(res1), 2)) #The example value in res2: 50.f7.22.b2.f2.00 return res2 elif member == "interface": ifs = out["interfaces"][port_channel]["members"][intf][member] if ifs == intf_list[count]: return ifs else: temp = "interface" ifs = out["interfaces"][port_channel]["members"][intf][temp] if ifs == intf_list[count]: return out["interfaces"][port_channel]["members"][intf][member] return None def get_lacp_sys_id(device): """ This API parse's 'show lacp sys-id' command and return sys id Args: device (`obj`): Device object Returns: Returns system id """ res = device.execute("show lacp sys-id") #cli output for 'show lacp sys-id' example res: 32768, 70d3.7984.aa80 res = ''.join([res[i] for i in range(len(res)) if i > 6]) #Now the value in res: 70d3.7984.aa80 res1 = ''.join([res[i] for i in range(len(res)) if res[i] != '.']) #Now the value in res1 : 70d37984aa80 sys_id = ':'.join(res1[i:i + 2] for i in range(0, len(res1), 2)) #After adding dots at required places sys id as 70:d3:79:84:aa:80 return sys_id def get_lacp_intf_count(device, port_channel): """ This API parse 'show lacp internal' command and return number of member interfaces Args: device (`obj`): Device object port_channel (`str`): Port channel name Returns: Returns interface count """ try: out = device.parse("show lacp internal") except SchemaEmptyParserError: return 0 port_channel = port_channel.capitalize() count = 0 if ( out and "interfaces" in out and port_channel in out["interfaces"] and "members" in out["interfaces"][port_channel] ): for intf in out["interfaces"][port_channel]["members"]: if out["interfaces"][port_channel]["members"][intf]: temp = "interface" ifs = out["interfaces"][port_channel]["members"][intf][temp] count = count + 1 return count def get_lacp_intf_list(device, port_channel): """ This API parse 'show lacp internal' command and return interface list Args:
Returns: Returns interface list """ try: out = device.parse("show lacp internal") except SchemaEmptyParserError: return [] port_channel = port_channel.capitalize() intf_list = [] if ( out and "interfaces" in out and port_channel in out["interfaces"] and "members" in out["interfaces"][port_channel] ): for intf in out["interfaces"][port_channel]["members"]: if out["interfaces"][port_channel]["members"][intf]: temp = "interface" ifs = out["interfaces"][port_channel]["members"][intf][temp] intf_list.append(ifs) return intf_list
device (`obj`): Device object port_channel (`str`): Port channel name
importer.py
import importlib from typing import Any class
(Exception): pass def import_from_string(import_str: str) -> Any: module_str, _, attrs_str = import_str.partition(":") if not module_str or not attrs_str: message = ( 'Import string "{import_str}" must be in format "<module>:<attribute>".' ) raise ImportFromStringError(message.format(import_str=import_str)) try: module = importlib.import_module(module_str) except ImportError as exc: if exc.name != module_str: raise exc from None message = 'Could not import module "{module_str}".' raise ImportFromStringError(message.format(module_str=module_str)) instance = module try: for attr_str in attrs_str.split("."): instance = getattr(instance, attr_str) except AttributeError as exc: message = 'Attribute "{attrs_str}" not found in module "{module_str}".' raise ImportFromStringError( message.format(attrs_str=attrs_str, module_str=module_str) ) return instance
ImportFromStringError
ReducerCombiner.js
import Auth from "./AuthReducer"; import { combineReducers } from "redux";
import Eventdata from "./EventReducer"; import CreateEventForm from "./CreateEventFormReducer"; const allreducers = combineReducers({ Auth: Auth, Eventdata: Eventdata, CreateEventForm: CreateEventForm, }); export default allreducers;
graph_partitioning1.py
import numpy as np from sklearn.cluster import KMeans import time from scipy.sparse.linalg import eigs from scipy.sparse import csr_matrix class Graph: def __init__(self, data_name): self.filename = data_name self.n = None self.k = None self.edges = self.form_graph() # self.e = None # number of edges self.adj = None # adjacency list self.lap = None self.U = None self.labels = None def form_graph(self): ''' form a graph from the .txt file :param file: data file :return: graph, in the shape used latter n, k ''' with open('./data/{}'.format(self.filename), 'r') as f: first_line = f.readline()[:-1] # remove '\n' at the end meta = first_line.split(' ') yield int(meta[2]), int(meta[-1]) for i, edge in enumerate(f.readlines()): s, t = edge[:-1].split(' ') yield int(s), int(t) def generate_adj(self): ''' generate the adjacency matrix of a graph :param graph: the edges of a graph :param n: the number of vertices in this graph :return: adjacency matrix ''' a = time.time() self.n, self.k = next(self.edges) adj = [set() for _ in range(self.n)] for s, t in self.edges: adj[s].add(t) adj[t].add(s) b = time.time() print('Generate adjacency matrix cost: {}s'.format(b-a)) return adj def generate_lap(self):
def get_U(self): ''' Using scipy.sparse.linalg.eigs to calculate matrix U that we need for kmeans algorithm :param lap: laplacian matrix :param k: a number :return: matrix U ''' s = time.time() self.lap = csr_matrix(self.lap) _, first_k = eigs(self.lap, self.k, sigma=0) U = first_k.real # normalize U x = np.linalg.norm(U) U = U / x t = time.time() print('Generate U cost: {}s'.format(t - s)) return U def k_means(self): ''' Using K-means algorithm to cluster the data :param data: n points :param k: number of clusters :return: clusters ''' s = time.time() kmeans = KMeans(n_clusters=self.k, algorithm='auto') kmeans.fit(self.U) t = time.time() print('Run k-means algorithm cost: {}s'.format(t - s)) return kmeans.labels_ def write_clusters(self): ''' return the clusters of vertices :param labels: labels generated from kmeans method :return: clusters ''' with open('./result/{}_res.txt'.format(self.filename[:-4]), 'w') as f: for i, l in enumerate(self.labels): f.write('{} {}\n'.format(i, l)) def main(self): self.adj = self.generate_adj() self.generate_lap() self.U = self.get_U() self.labels = self.k_means() self.write_clusters() if __name__ == '__main__': graph = Graph('soc-Epinions1.txt') graph.main()
''' From adjacency matrix and diagonal matrix build Laplacian matrix :param dia: diagonal matrix :param adj: adjacency matrix :return: Laplacian matrix ''' a = time.time() self.lap = np.ndarray((self.n, self.n)) for i, row in enumerate(self.adj): row_dia = np.zeros(self.n) row_dia[i] = len(row) row_adj = [1 if j in row else 0 for j in range(self.n)] self.lap[i] = row_dia - row_adj x = np.linalg.norm(self.lap) self.lap = self.lap / x b = time.time() print('Genearte Laplacian matrix cost: {}s'.format(b-a))
page.go
// Copyright 2019 The Hugo 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 hugolib import ( "bytes" "fmt" "html/template" "os" "path" "path/filepath" "sort" "strings" "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/hugofs/files" "github.com/bep/gitmap" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/parser/pageparser" "github.com/pkg/errors" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/source" "github.com/spf13/cast" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/resource" ) var ( _ page.Page = (*pageState)(nil) _ collections.Grouper = (*pageState)(nil) _ collections.Slicer = (*pageState)(nil) ) var ( pageTypesProvider = resource.NewResourceTypesProvider(media.OctetType, pageResourceType) nopPageOutput = &pageOutput{ pagePerOutputProviders: nopPagePerOutput, ContentProvider: page.NopPage, TableOfContentsProvider: page.NopPage, } ) // pageContext provides contextual information about this page, for error // logging and similar. type pageContext interface { posOffset(offset int) text.Position wrapError(err error) error getContentConverter() converter.Converter } // wrapErr adds some context to the given error if possible. func wrapErr(err error, ctx interface{}) error
type pageSiteAdapter struct { p page.Page s *Site } func (pa pageSiteAdapter) GetPage(ref string) (page.Page, error) { p, err := pa.s.getPageNew(pa.p, ref) if p == nil { // The nil struct has meaning in some situations, mostly to avoid breaking // existing sites doing $nilpage.IsDescendant($p), which will always return // false. p = page.NilPage } return p, err } type pageState struct { // This slice will be of same length as the number of global slice of output // formats (for all sites). pageOutputs []*pageOutput // This will be shifted out when we start to render a new output format. *pageOutput // Common for all output formats. *pageCommon } // Eq returns whether the current page equals the given page. // This is what's invoked when doing `{{ if eq $page $otherPage }}` func (p *pageState) Eq(other interface{}) bool { pp, err := unwrapPage(other) if err != nil { return false } return p == pp } func (p *pageState) GitInfo() *gitmap.GitInfo { return p.gitInfo } // GetTerms gets the terms defined on this page in the given taxonomy. func (p *pageState) GetTerms(taxonomy string) page.Pages { taxonomy = strings.ToLower(taxonomy) m := p.s.pageMap prefix := cleanTreeKey(taxonomy) var self string if p.IsHome() { // TODO(bep) make this less magical, see taxonomyEntries.Insert. self = "/" + page.KindHome } else if p.treeRef != nil { self = p.treeRef.key } var pas page.Pages m.taxonomies.WalkPrefixListable(prefix, func(s string, n *contentNode) bool { if _, found := m.taxonomyEntries.Get(s + self); found { pas = append(pas, n.p) } return false }) page.SortByDefault(pas) return pas } func (p *pageState) MarshalJSON() ([]byte, error) { return page.MarshalPageToJSON(p) } func (p *pageState) getPages() page.Pages { b := p.bucket if b == nil { return nil } return b.getPages() } func (p *pageState) getPagesRecursive() page.Pages { b := p.bucket if b == nil { return nil } return b.getPagesRecursive() } func (p *pageState) getPagesAndSections() page.Pages { b := p.bucket if b == nil { return nil } return b.getPagesAndSections() } func (p *pageState) RegularPagesRecursive() page.Pages { p.regularPagesRecursiveInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindSection: pages = p.getPagesRecursive() default: pages = p.RegularPages() } p.regularPagesRecursive = pages }) return p.regularPagesRecursive } func (p *pageState) PagesRecursive() page.Pages { return nil } func (p *pageState) RegularPages() page.Pages { p.regularPagesInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindPage: case page.KindSection, page.KindHome, page.KindTaxonomyTerm: pages = p.getPages() case page.KindTaxonomy: all := p.Pages() for _, p := range all { if p.IsPage() { pages = append(pages, p) } } default: pages = p.s.RegularPages() } p.regularPages = pages }) return p.regularPages } func (p *pageState) Pages() page.Pages { p.pagesInit.Do(func() { var pages page.Pages switch p.Kind() { case page.KindPage: case page.KindSection, page.KindHome: pages = p.getPagesAndSections() case page.KindTaxonomy: pages = p.bucket.getTaxonomyEntries() case page.KindTaxonomyTerm: pages = p.bucket.getTaxonomies() default: pages = p.s.Pages() } p.pages = pages }) return p.pages } // RawContent returns the un-rendered source content without // any leading front matter. func (p *pageState) RawContent() string { if p.source.parsed == nil { return "" } start := p.source.posMainContent if start == -1 { start = 0 } return string(p.source.parsed.Input()[start:]) } func (p *pageState) sortResources() { sort.SliceStable(p.resources, func(i, j int) bool { ri, rj := p.resources[i], p.resources[j] if ri.ResourceType() < rj.ResourceType() { return true } p1, ok1 := ri.(page.Page) p2, ok2 := rj.(page.Page) if ok1 != ok2 { return ok2 } if ok1 { return page.DefaultPageSort(p1, p2) } // Make sure not to use RelPermalink or any of the other methods that // trigger lazy publishing. return ri.Name() < rj.Name() }) } func (p *pageState) Resources() resource.Resources { p.resourcesInit.Do(func() { p.sortResources() if len(p.m.resourcesMetadata) > 0 { resources.AssignMetadata(p.m.resourcesMetadata, p.resources...) p.sortResources() } }) return p.resources } func (p *pageState) HasShortcode(name string) bool { if p.shortcodeState == nil { return false } return p.shortcodeState.nameSet[name] } func (p *pageState) Site() page.Site { return p.s.Info } func (p *pageState) String() string { if sourceRef := p.sourceRef(); sourceRef != "" { return fmt.Sprintf("Page(%s)", sourceRef) } return fmt.Sprintf("Page(%q)", p.Title()) } // IsTranslated returns whether this content file is translated to // other language(s). func (p *pageState) IsTranslated() bool { p.s.h.init.translations.Do() return len(p.translations) > 0 } // TranslationKey returns the key used to map language translations of this page. // It will use the translationKey set in front matter if set, or the content path and // filename (excluding any language code and extension), e.g. "about/index". // The Page Kind is always prepended. func (p *pageState) TranslationKey() string { p.translationKeyInit.Do(func() { if p.m.translationKey != "" { p.translationKey = p.Kind() + "/" + p.m.translationKey } else if p.IsPage() && !p.File().IsZero() { p.translationKey = path.Join(p.Kind(), filepath.ToSlash(p.File().Dir()), p.File().TranslationBaseName()) } else if p.IsNode() { p.translationKey = path.Join(p.Kind(), p.SectionsPath()) } }) return p.translationKey } // AllTranslations returns all translations, including the current Page. func (p *pageState) AllTranslations() page.Pages { p.s.h.init.translations.Do() return p.allTranslations } // Translations returns the translations excluding the current Page. func (p *pageState) Translations() page.Pages { p.s.h.init.translations.Do() return p.translations } func (ps *pageState) initCommonProviders(pp pagePaths) error { if ps.IsPage() { ps.posNextPrev = &nextPrev{init: ps.s.init.prevNext} ps.posNextPrevSection = &nextPrev{init: ps.s.init.prevNextInSection} ps.InSectionPositioner = newPagePositionInSection(ps.posNextPrevSection) ps.Positioner = newPagePosition(ps.posNextPrev) } ps.OutputFormatsProvider = pp ps.targetPathDescriptor = pp.targetPathDescriptor ps.RefProvider = newPageRef(ps) ps.SitesProvider = ps.s.Info return nil } func (p *pageState) createRenderHooks(f output.Format) (*hooks.Render, error) { layoutDescriptor := p.getLayoutDescriptor() layoutDescriptor.RenderingHook = true layoutDescriptor.LayoutOverride = false layoutDescriptor.Layout = "" layoutDescriptor.Kind = "render-link" linkTempl, linkTemplFound, err := p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return nil, err } layoutDescriptor.Kind = "render-image" imgTempl, imgTemplFound, err := p.s.Tmpl().LookupLayout(layoutDescriptor, f) if err != nil { return nil, err } var linkRenderer hooks.LinkRenderer var imageRenderer hooks.LinkRenderer if linkTemplFound { linkRenderer = contentLinkRenderer{ templateHandler: p.s.Tmpl(), Provider: linkTempl.(tpl.Info), templ: linkTempl, } } if imgTemplFound { imageRenderer = contentLinkRenderer{ templateHandler: p.s.Tmpl(), Provider: imgTempl.(tpl.Info), templ: imgTempl, } } return &hooks.Render{ LinkRenderer: linkRenderer, ImageRenderer: imageRenderer, }, nil } func (p *pageState) getLayoutDescriptor() output.LayoutDescriptor { p.layoutDescriptorInit.Do(func() { var section string sections := p.SectionsEntries() switch p.Kind() { case page.KindSection: if len(sections) > 0 { section = sections[0] } case page.KindTaxonomyTerm, page.KindTaxonomy: b := p.getTreeRef().n section = b.viewInfo.name.singular default: } p.layoutDescriptor = output.LayoutDescriptor{ Kind: p.Kind(), Type: p.Type(), Lang: p.Language().Lang, Layout: p.Layout(), Section: section, } }) return p.layoutDescriptor } func (p *pageState) resolveTemplate(layouts ...string) (tpl.Template, bool, error) { f := p.outputFormat() if len(layouts) == 0 { selfLayout := p.selfLayoutForOutput(f) if selfLayout != "" { templ, found := p.s.Tmpl().Lookup(selfLayout) return templ, found, nil } } d := p.getLayoutDescriptor() if len(layouts) > 0 { d.Layout = layouts[0] d.LayoutOverride = true } return p.s.Tmpl().LookupLayout(d, f) } // This is serialized func (p *pageState) initOutputFormat(isRenderingSite bool, idx int) error { if err := p.shiftToOutputFormat(isRenderingSite, idx); err != nil { return err } return nil } // Must be run after the site section tree etc. is built and ready. func (p *pageState) initPage() error { if _, err := p.init.Do(); err != nil { return err } return nil } func (p *pageState) renderResources() (err error) { p.resourcesPublishInit.Do(func() { var toBeDeleted []int for i, r := range p.Resources() { if _, ok := r.(page.Page); ok { // Pages gets rendered with the owning page but we count them here. p.s.PathSpec.ProcessingStats.Incr(&p.s.PathSpec.ProcessingStats.Pages) continue } src, ok := r.(resource.Source) if !ok { err = errors.Errorf("Resource %T does not support resource.Source", src) return } if err := src.Publish(); err != nil { if os.IsNotExist(err) { // The resource has been deleted from the file system. // This should be extremely rare, but can happen on live reload in server // mode when the same resource is member of different page bundles. toBeDeleted = append(toBeDeleted, i) } else { p.s.Log.ERROR.Printf("Failed to publish Resource for page %q: %s", p.pathOrTitle(), err) } } else { p.s.PathSpec.ProcessingStats.Incr(&p.s.PathSpec.ProcessingStats.Files) } } for _, i := range toBeDeleted { p.deleteResource(i) } }) return } func (p *pageState) deleteResource(i int) { p.resources = append(p.resources[:i], p.resources[i+1:]...) } func (p *pageState) getTargetPaths() page.TargetPaths { return p.targetPaths() } func (p *pageState) setTranslations(pages page.Pages) { p.allTranslations = pages page.SortByLanguage(p.allTranslations) translations := make(page.Pages, 0) for _, t := range p.allTranslations { if !t.Eq(p) { translations = append(translations, t) } } p.translations = translations } func (p *pageState) AlternativeOutputFormats() page.OutputFormats { f := p.outputFormat() var o page.OutputFormats for _, of := range p.OutputFormats() { if of.Format.NotAlternative || of.Format.Name == f.Name { continue } o = append(o, of) } return o } type renderStringOpts struct { Display string Markup string } var defualtRenderStringOpts = renderStringOpts{ Display: "inline", Markup: "", // Will inherit the page's value when not set. } func (p *pageState) RenderString(args ...interface{}) (template.HTML, error) { if len(args) < 1 || len(args) > 2 { return "", errors.New("want 1 or 2 arguments") } var s string opts := defualtRenderStringOpts sidx := 1 if len(args) == 1 { sidx = 0 } else { m, ok := args[0].(map[string]interface{}) if !ok { return "", errors.New("first argument must be a map") } if err := mapstructure.WeakDecode(m, &opts); err != nil { return "", errors.WithMessage(err, "failed to decode options") } } var err error s, err = cast.ToStringE(args[sidx]) if err != nil { return "", err } conv := p.getContentConverter() if opts.Markup != "" && opts.Markup != p.m.markup { var err error // TODO(bep) consider cache conv, err = p.m.newContentConverter(p, opts.Markup, nil) if err != nil { return "", p.wrapError(err) } } c, err := p.pageOutput.cp.renderContentWithConverter(conv, []byte(s), false) if err != nil { return "", p.wrapError(err) } b := c.Bytes() if opts.Display == "inline" { // We may have to rethink this in the future when we get other // renderers. b = p.s.ContentSpec.TrimShortHTML(b) } return template.HTML(string(b)), nil } func (p *pageState) addDependency(dep identity.Provider) { if !p.s.running() || p.pageOutput.cp == nil { return } p.pageOutput.cp.dependencyTracker.Add(dep) } func (p *pageState) RenderWithTemplateInfo(info tpl.Info, layout ...string) (template.HTML, error) { p.addDependency(info) return p.Render(layout...) } func (p *pageState) Render(layout ...string) (template.HTML, error) { templ, found, err := p.resolveTemplate(layout...) if err != nil { return "", p.wrapError(err) } if !found { return "", nil } p.addDependency(templ.(tpl.Info)) res, err := executeToString(p.s.Tmpl(), templ, p) if err != nil { return "", p.wrapError(errors.Wrapf(err, "failed to execute template %q v", layout)) } return template.HTML(res), nil } // wrapError adds some more context to the given error if possible/needed func (p *pageState) wrapError(err error) error { if _, ok := err.(*herrors.ErrorWithFileContext); ok { // Preserve the first file context. return err } var filename string if !p.File().IsZero() { filename = p.File().Filename() } err, _ = herrors.WithFileContextForFile( err, filename, filename, p.s.SourceSpec.Fs.Source, herrors.SimpleLineMatcher) return err } func (p *pageState) getContentConverter() converter.Converter { var err error p.m.contentConverterInit.Do(func() { markup := p.m.markup if markup == "html" { // Only used for shortcode inner content. markup = "markdown" } p.m.contentConverter, err = p.m.newContentConverter(p, markup, p.m.renderingConfigOverrides) }) if err != nil { p.s.Log.ERROR.Println("Failed to create content converter:", err) } return p.m.contentConverter } func (p *pageState) mapContent(bucket *pagesMapBucket, meta *pageMeta) error { s := p.shortcodeState rn := &pageContentMap{ items: make([]interface{}, 0, 20), } iter := p.source.parsed.Iterator() fail := func(err error, i pageparser.Item) error { return p.parseError(err, iter.Input(), i.Pos) } // the parser is guaranteed to return items in proper order or fail, so … // … it's safe to keep some "global" state var currShortcode shortcode var ordinal int var frontMatterSet bool Loop: for { it := iter.Next() switch { case it.Type == pageparser.TypeIgnore: case it.IsFrontMatter(): f := pageparser.FormatFromFrontMatterType(it.Type) m, err := metadecoders.Default.UnmarshalToMap(it.Val, f) if err != nil { if fe, ok := err.(herrors.FileError); ok { return herrors.ToFileErrorWithOffset(fe, iter.LineNumber()-1) } else { return err } } if err := meta.setMetadata(bucket, p, m); err != nil { return err } frontMatterSet = true next := iter.Peek() if !next.IsDone() { p.source.posMainContent = next.Pos } if !p.s.shouldBuild(p) { // Nothing more to do. return nil } case it.Type == pageparser.TypeLeadSummaryDivider: posBody := -1 f := func(item pageparser.Item) bool { if posBody == -1 && !item.IsDone() { posBody = item.Pos } if item.IsNonWhitespace() { p.truncated = true // Done return false } return true } iter.PeekWalk(f) p.source.posSummaryEnd = it.Pos p.source.posBodyStart = posBody p.source.hasSummaryDivider = true if meta.markup != "html" { // The content will be rendered by Blackfriday or similar, // and we need to track the summary. rn.AddReplacement(internalSummaryDividerPre, it) } // Handle shortcode case it.IsLeftShortcodeDelim(): // let extractShortcode handle left delim (will do so recursively) iter.Backup() currShortcode, err := s.extractShortcode(ordinal, 0, iter) if err != nil { return fail(errors.Wrap(err, "failed to extract shortcode"), it) } currShortcode.pos = it.Pos currShortcode.length = iter.Current().Pos - it.Pos if currShortcode.placeholder == "" { currShortcode.placeholder = createShortcodePlaceholder("s", currShortcode.ordinal) } if currShortcode.name != "" { s.nameSet[currShortcode.name] = true } if currShortcode.params == nil { var s []string currShortcode.params = s } currShortcode.placeholder = createShortcodePlaceholder("s", ordinal) ordinal++ s.shortcodes = append(s.shortcodes, currShortcode) rn.AddShortcode(currShortcode) case it.Type == pageparser.TypeEmoji: if emoji := helpers.Emoji(it.ValStr()); emoji != nil { rn.AddReplacement(emoji, it) } else { rn.AddBytes(it) } case it.IsEOF(): break Loop case it.IsError(): err := fail(errors.WithStack(errors.New(it.ValStr())), it) currShortcode.err = err return err default: rn.AddBytes(it) } } if !frontMatterSet { // Page content without front matter. Assign default front matter from // cascades etc. if err := meta.setMetadata(bucket, p, nil); err != nil { return err } } p.cmap = rn return nil } func (p *pageState) errorf(err error, format string, a ...interface{}) error { if herrors.UnwrapErrorWithFileContext(err) != nil { // More isn't always better. return err } args := append([]interface{}{p.Language().Lang, p.pathOrTitle()}, a...) format = "[%s] page %q: " + format if err == nil { errors.Errorf(format, args...) return fmt.Errorf(format, args...) } return errors.Wrapf(err, format, args...) } func (p *pageState) outputFormat() (f output.Format) { if p.pageOutput == nil { panic("no pageOutput") } return p.pageOutput.f } func (p *pageState) parseError(err error, input []byte, offset int) error { if herrors.UnwrapFileError(err) != nil { // Use the most specific location. return err } pos := p.posFromInput(input, offset) return herrors.NewFileError("md", -1, pos.LineNumber, pos.ColumnNumber, err) } func (p *pageState) pathOrTitle() string { if !p.File().IsZero() { return p.File().Filename() } if p.Path() != "" { return p.Path() } return p.Title() } func (p *pageState) posFromPage(offset int) text.Position { return p.posFromInput(p.source.parsed.Input(), offset) } func (p *pageState) posFromInput(input []byte, offset int) text.Position { lf := []byte("\n") input = input[:offset] lineNumber := bytes.Count(input, lf) + 1 endOfLastLine := bytes.LastIndex(input, lf) return text.Position{ Filename: p.pathOrTitle(), LineNumber: lineNumber, ColumnNumber: offset - endOfLastLine, Offset: offset, } } func (p *pageState) posOffset(offset int) text.Position { return p.posFromInput(p.source.parsed.Input(), offset) } // shiftToOutputFormat is serialized. The output format idx refers to the // full set of output formats for all sites. func (p *pageState) shiftToOutputFormat(isRenderingSite bool, idx int) error { if err := p.initPage(); err != nil { return err } if len(p.pageOutputs) == 1 { idx = 0 } p.pageOutput = p.pageOutputs[idx] if p.pageOutput == nil { panic(fmt.Sprintf("pageOutput is nil for output idx %d", idx)) } // Reset any built paginator. This will trigger when re-rendering pages in // server mode. if isRenderingSite && p.pageOutput.paginator != nil && p.pageOutput.paginator.current != nil { p.pageOutput.paginator.reset() } if isRenderingSite { cp := p.pageOutput.cp if cp == nil { // Look for content to reuse. for i := 0; i < len(p.pageOutputs); i++ { if i == idx { continue } po := p.pageOutputs[i] if po.cp != nil && po.cp.reuse { cp = po.cp break } } } if cp == nil { var err error cp, err = newPageContentOutput(p, p.pageOutput) if err != nil { return err } } p.pageOutput.initContentProvider(cp) p.pageOutput.cp = cp } return nil } // sourceRef returns the reference used by GetPage and ref/relref shortcodes to refer to // this page. It is prefixed with a "/". // // For pages that have a source file, it is returns the path to this file as an // absolute path rooted in this site's content dir. // For pages that do not (sections witout content page etc.), it returns the // virtual path, consistent with where you would add a source file. func (p *pageState) sourceRef() string { if !p.File().IsZero() { sourcePath := p.File().Path() if sourcePath != "" { return "/" + filepath.ToSlash(sourcePath) } } if len(p.SectionsEntries()) > 0 { // no backing file, return the virtual source path return "/" + p.SectionsPath() } return "" } func (s *Site) sectionsFromFile(fi source.File) []string { dirname := fi.Dir() dirname = strings.Trim(dirname, helpers.FilePathSeparator) if dirname == "" { return nil } parts := strings.Split(dirname, helpers.FilePathSeparator) if fii, ok := fi.(*fileInfo); ok { if len(parts) > 0 && fii.FileInfo().Meta().Classifier() == files.ContentClassLeaf { // my-section/mybundle/index.md => my-section return parts[:len(parts)-1] } } return parts }
{ if pc, ok := ctx.(pageContext); ok { return pc.wrapError(err) } return err }
config.tsx
/* * 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. */ // import React from 'react'; import { genBusinessFields } from '@/components/AccessHelper'; export const getFormContent = ({ editing, initialValues }) => genBusinessFields( [ 'middlewareType', 'inlongGroupId', 'mqResourceObj', 'name', 'cnName', 'inCharges', 'description', 'queueModule', 'topicPartitionNum', 'dailyRecords', 'dailyStorage', 'peakRecords', 'maxLength',
'mqExtInfo.retentionTime', 'mqExtInfo.ttl', 'mqExtInfo.retentionSize', ], initialValues, ).map(item => ({ ...item, type: transType(editing, item, initialValues), suffix: typeof item.suffix === 'object' && !editing ? { ...item.suffix, type: 'text', } : item.suffix, extra: null, })); function transType(editing: boolean, conf, initialValues) { const arr = [ { name: [ 'middlewareType', 'queueModule', 'topicPartitionNum', 'name', 'dailyRecords', 'dailyStorage', 'peakRecords', 'maxLength', ], as: 'text', active: true, }, { name: [ 'cnName', 'description', 'inCharges', // 'mqExtInfo.ensemble', 'mqExtInfo.writeQuorum', 'mqExtInfo.ackQuorum', 'mqExtInfo.retentionTime', 'mqExtInfo.ttl', 'mqExtInfo.retentionSize', ], as: 'text', active: !editing, }, ].reduce((acc, cur) => { return acc.concat(Array.isArray(cur.name) ? cur.name.map(name => ({ ...cur, name })) : cur); }, []); const map = new Map(arr.map(item => [item.name, item])); if (map.has(conf.name)) { const item = map.get(conf.name); return item.active ? item.as : conf.type; } return conf.type; }
// 'mqExtInfo.ensemble', 'mqExtInfo.writeQuorum', 'mqExtInfo.ackQuorum',
binary_clock.py
import robocup import constants import play import enum import behavior import main import skills.move import plays.testing.line_up import time # Maintains the state of the ball's position by keeping track of which # half the ball is on and prints on both entering a given state and # continuously during the execution of a given state. class BinaryClock(play.Play): class State(enum.Enum): # Define your states here. # eg: some_state = 0 # ----------------------- pass # remove this once you have put in your states def __init__(self): super().__init__(continuous=True) # This is a local variable of this class # Refer to it with self.current_time self.current_time = time.localtime().tm_min # Register the states you defined using 'add_state'. # eg: self.add_state(WhichHalf.State.<???>, # behavior.Behavior.State.running) # ---------------------------------------------------- # Add your state transitions using 'add_transition'. # eg: self.add_transition(behavior.Behavior.State.start, # self.State.<???>, lambda: True, # 'immediately') # eg: self.add_transition(self.State.<???>, self.State.<???>, # lambda: <???>, # 'state change message') # ------------------------------------------------------------ # EXAMPLE TRANSITION, YOU MAY WANT TO REPLACE THIS self.add_transition(behavior.Behavior.State.start, behavior.Behavior.State.running, lambda: True, 'immediately') # Define your own 'on_enter' and 'execute' functions here. # eg: def on_enter_<???>(self): # print('Something?') # eg: def execute_<???>(self): # print('Something?') # ---------------------------------------------------------
# Demo of moving to a point. def on_enter_running(self): move_point = robocup.Point(0, constants.Field.Length / 2) self.add_subbehavior(skills.move.Move(move_point), 'test move')
stream.go
package gmf /* #cgo pkg-config: libavformat libavcodec #include "libavformat/avformat.h" #include "libavcodec/avcodec.h" */ import "C" import ( "fmt" ) type Stream struct { avStream *C.struct_AVStream cc *CodecCtx SwsCtx *SwsCtx SwrCtx *SwrCtx AvFifo *AVAudioFifo DstFrame *Frame Pts int64 Resampler func(*Stream, []*Frame, bool) []*Frame Rescaler func(*Stream, []*Frame) []*Frame CgoMemoryManage } func (s *Stream) Free() { if s.SwsCtx != nil { s.SwsCtx.Free() } if s.DstFrame != nil { s.DstFrame.Free() } if s.SwrCtx != nil { s.SwrCtx.Free() } if s.AvFifo != nil { s.AvFifo.Free() } } func (s *Stream) DumpContexCodec(codec *CodecCtx) { ret := C.avcodec_parameters_from_context(s.avStream.codecpar, codec.avCodecCtx) if ret < 0 { panic("Failed to copy context from input to output stream codec context\n") } } func (s *Stream) SetCodecFlags() { s.avStream.codec.flags |= C.AV_CODEC_FLAG_GLOBAL_HEADER } func (s *Stream) CodecCtx() *CodecCtx { if s.IsCodecCtxSet() { return s.cc } c, err := FindDecoder(int(s.avStream.codec.codec_id)) if err != nil { return nil // return fmt.Errorf("error initializing codec for stream '%d' - %s", s.Index(), err) } s.cc = &CodecCtx{ codec: c, avCodecCtx: s.avStream.codec, } s.cc.Open(nil) return s.cc } func (s *Stream) SetCodecCtx(cc *CodecCtx) { if cc == nil { panic("Codec context is not initialized.") } Retain(cc) //just Retain .not need Release,it can free memory by C.avformat_free_context() @ format.go Free(). s.avStream.codec = cc.avCodecCtx if s.cc != nil { s.cc.avCodecCtx = cc.avCodecCtx } } func (s *Stream) SetCodecParameters(cp *CodecParameters) error { if cp == nil || cp.avCodecParameters == nil
s.avStream.codecpar = cp.avCodecParameters return nil } func (s *Stream) IsCodecCtxSet() bool { return (s.cc != nil) } func (s *Stream) Index() int { return int(s.avStream.index) } func (s *Stream) Id() int { return int(s.avStream.id) } func (s *Stream) NbFrames() int { if int(s.avStream.nb_frames) == 0 { return 1 } return int(s.avStream.nb_frames) } func (s *Stream) TimeBase() AVRational { return AVRational(s.avStream.time_base) } func (s *Stream) Type() int32 { return s.CodecCtx().Type() } func (s *Stream) IsAudio() bool { return (s.Type() == AVMEDIA_TYPE_AUDIO) } func (s *Stream) IsVideo() bool { return (s.Type() == AVMEDIA_TYPE_VIDEO) } func (s *Stream) Duration() int64 { return int64(s.avStream.duration) } func (s *Stream) SetTimeBase(val AVR) *Stream { s.avStream.time_base.num = C.int(val.Num) s.avStream.time_base.den = C.int(val.Den) return s } func (s *Stream) GetRFrameRate() AVRational { return AVRational(s.avStream.r_frame_rate) } func (s *Stream) SetRFrameRate(val AVR) { s.avStream.r_frame_rate.num = C.int(val.Num) s.avStream.r_frame_rate.den = C.int(val.Den) } func (s *Stream) GetAvgFrameRate() AVRational { return AVRational(s.avStream.avg_frame_rate) } func (s *Stream) GetStartTime() int64 { return int64(s.avStream.start_time) } func (s *Stream) GetCodecPar() *CodecParameters { cp := NewCodecParameters() cp.avCodecParameters = s.avStream.codecpar return cp } func (s *Stream) CopyCodecPar(cp *CodecParameters) error { ret := int(C.avcodec_parameters_copy(s.avStream.codecpar, cp.avCodecParameters)) if ret < 0 { return AvError(ret) } return nil }
{ return fmt.Errorf("codec parameters are not initialized") }
parallel_text_dataset.py
# Copyright 2020 ByteDance Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from abc import ABCMeta, abstractmethod import six import tensorflow as tf from absl import logging from neurst.data.datasets import register_dataset from neurst.data.datasets.dataset import TFRecordDataset from neurst.data.datasets.text_gen_dataset import TextGenDataset from neurst.utils.compat import DataStatus from neurst.utils.flags_core import Flag @six.add_metaclass(ABCMeta) class AbstractParallelDataset(TextGenDataset): """ The abstract dataset for parallel text. The element spec must be { 'feature': tf.TensorSpec(shape=(None,), dtype=tf.int64), 'label': tf.TensorSpec(shape=(None,), dtype=tf.int64) } """ def __init__(self): self._sources = None super(AbstractParallelDataset, self).__init__() @property @abstractmethod def status(self) -> str: raise NotImplementedError @abstractmethod def build_iterator(self, map_func=None, shard_id=0, total_shards=1): """ Returns the iterator of the dataset. Args: map_func: A function mapping a dataset element to another dataset element. shard_id: Generator yields on the `shard_id`-th shard of the whole dataset. total_shards: The number of total shards. """ raise NotImplementedError @property def
(self): """ Returns a list of source texts. """ return self._sources @register_dataset("parallel_text") class ParallelTextDataset(AbstractParallelDataset): def __init__(self, args): """ Initializes the dataset. """ super(ParallelTextDataset, self).__init__() self._src_file = args["src_file"] assert self._src_file, "`src_file` must be provided for ParallelTextDataset." self._trg_file = args["trg_file"] self._data_is_processed = args["data_is_processed"] @staticmethod def class_or_method_args(): return [ Flag("src_file", dtype=Flag.TYPE.STRING, help="The source text file"), Flag("trg_file", dtype=Flag.TYPE.STRING, help="The target text file"), Flag("data_is_processed", dtype=Flag.TYPE.BOOLEAN, help="Whether the text data is already processed."), ] @property def status(self): if self._data_is_processed: return DataStatus.PROCESSED return DataStatus.RAW def build_iterator(self, map_func=None, shard_id=0, total_shards=1): """ Reads data from files and returns the iterator. Args: map_func: A function mapping a dataset element to another dataset element. shard_id: Generator yields on the `shard_id`-th shard of the whole dataset. total_shards: The number of total shards. """ if total_shards > 1: total_samples = self.num_samples samples_per_part = total_samples // total_shards range_begin = samples_per_part * shard_id if shard_id == total_shards - 1: range_end = total_samples + 1 logging.info(f"Iterate on dataset from {range_begin} " f"to the end (total {total_samples}).") else: range_end = range_begin + samples_per_part logging.info(f"Iterate on dataset from {range_begin} " f"to {range_end} (total {total_samples}).") def gen(): fsrc = tf.io.gfile.GFile(self._src_file) ftrg = None if self._trg_file is None else tf.io.gfile.GFile(self._trg_file) n = 0 for src in fsrc: n += 1 data = {"feature": src.strip()} if ftrg is not None: data["label"] = ftrg.readline().strip() if total_shards > 1: if n < range_begin: continue if n >= range_end: break if map_func is not None: data = map_func(data) yield data fsrc.close() if ftrg is not None: ftrg.close() return gen @property def sources(self): """ Returns a list of sources. """ if self._sources is None and self._src_file: with tf.io.gfile.GFile(self._src_file) as fp: self._sources = [line.strip() for line in fp] return self._sources @property def targets(self): """ Returns a list of targets. """ if self._targets is None and self._trg_file: with tf.io.gfile.GFile(self._trg_file) as fp: self._targets = [line.strip() for line in fp] return self._targets @register_dataset("parallel_tfrecord") class ParallelTFRecordDataset(TFRecordDataset, AbstractParallelDataset): @property def status(self): return DataStatus.PROJECTED @property def fields(self): return {"feature": tf.io.VarLenFeature(tf.int64), "label": tf.io.VarLenFeature(tf.int64)}
sources
deserializers.go
// Code generated by smithy-go-codegen DO NOT EDIT. package amplify import ( "bytes" "context" "encoding/json" "fmt" "github.com/aws/aws-sdk-go-v2/aws/protocol/restjson" "github.com/aws/aws-sdk-go-v2/service/amplify/types" smithy "github.com/aws/smithy-go" smithyio "github.com/aws/smithy-go/io" "github.com/aws/smithy-go/middleware" "github.com/aws/smithy-go/ptr" smithytime "github.com/aws/smithy-go/time" smithyhttp "github.com/aws/smithy-go/transport/http" "io" "strings" ) type awsRestjson1_deserializeOpCreateApp struct { } func (*awsRestjson1_deserializeOpCreateApp) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpCreateApp) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorCreateApp(response, &metadata) } output := &CreateAppOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentCreateAppOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorCreateApp(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("DependentServiceFailureException", errorCode): return awsRestjson1_deserializeErrorDependentServiceFailureException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("LimitExceededException", errorCode): return awsRestjson1_deserializeErrorLimitExceededException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentCreateAppOutput(v **CreateAppOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *CreateAppOutput if *v == nil { sv = &CreateAppOutput{} } else { sv = *v } for key, value := range shape { switch key { case "app": if err := awsRestjson1_deserializeDocumentApp(&sv.App, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpCreateBackendEnvironment struct { } func (*awsRestjson1_deserializeOpCreateBackendEnvironment) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpCreateBackendEnvironment) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorCreateBackendEnvironment(response, &metadata) } output := &CreateBackendEnvironmentOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentCreateBackendEnvironmentOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorCreateBackendEnvironment(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("LimitExceededException", errorCode): return awsRestjson1_deserializeErrorLimitExceededException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentCreateBackendEnvironmentOutput(v **CreateBackendEnvironmentOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *CreateBackendEnvironmentOutput if *v == nil { sv = &CreateBackendEnvironmentOutput{} } else { sv = *v } for key, value := range shape { switch key { case "backendEnvironment": if err := awsRestjson1_deserializeDocumentBackendEnvironment(&sv.BackendEnvironment, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpCreateBranch struct { } func (*awsRestjson1_deserializeOpCreateBranch) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpCreateBranch) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorCreateBranch(response, &metadata) } output := &CreateBranchOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentCreateBranchOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorCreateBranch(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("DependentServiceFailureException", errorCode): return awsRestjson1_deserializeErrorDependentServiceFailureException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("LimitExceededException", errorCode): return awsRestjson1_deserializeErrorLimitExceededException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentCreateBranchOutput(v **CreateBranchOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *CreateBranchOutput if *v == nil { sv = &CreateBranchOutput{} } else { sv = *v } for key, value := range shape { switch key { case "branch": if err := awsRestjson1_deserializeDocumentBranch(&sv.Branch, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpCreateDeployment struct { } func (*awsRestjson1_deserializeOpCreateDeployment) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpCreateDeployment) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorCreateDeployment(response, &metadata) } output := &CreateDeploymentOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentCreateDeploymentOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorCreateDeployment(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("LimitExceededException", errorCode): return awsRestjson1_deserializeErrorLimitExceededException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentCreateDeploymentOutput(v **CreateDeploymentOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *CreateDeploymentOutput if *v == nil { sv = &CreateDeploymentOutput{} } else { sv = *v } for key, value := range shape { switch key { case "fileUploadUrls": if err := awsRestjson1_deserializeDocumentFileUploadUrls(&sv.FileUploadUrls, value); err != nil { return err } case "jobId": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected JobId to be of type string, got %T instead", value) } sv.JobId = ptr.String(jtv) } case "zipUploadUrl": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected UploadUrl to be of type string, got %T instead", value) } sv.ZipUploadUrl = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpCreateDomainAssociation struct { } func (*awsRestjson1_deserializeOpCreateDomainAssociation) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpCreateDomainAssociation) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorCreateDomainAssociation(response, &metadata) } output := &CreateDomainAssociationOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentCreateDomainAssociationOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorCreateDomainAssociation(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("DependentServiceFailureException", errorCode): return awsRestjson1_deserializeErrorDependentServiceFailureException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("LimitExceededException", errorCode): return awsRestjson1_deserializeErrorLimitExceededException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentCreateDomainAssociationOutput(v **CreateDomainAssociationOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *CreateDomainAssociationOutput if *v == nil { sv = &CreateDomainAssociationOutput{} } else { sv = *v } for key, value := range shape { switch key { case "domainAssociation": if err := awsRestjson1_deserializeDocumentDomainAssociation(&sv.DomainAssociation, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpCreateWebhook struct { } func (*awsRestjson1_deserializeOpCreateWebhook) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpCreateWebhook) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorCreateWebhook(response, &metadata) } output := &CreateWebhookOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentCreateWebhookOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorCreateWebhook(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("DependentServiceFailureException", errorCode): return awsRestjson1_deserializeErrorDependentServiceFailureException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("LimitExceededException", errorCode): return awsRestjson1_deserializeErrorLimitExceededException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentCreateWebhookOutput(v **CreateWebhookOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *CreateWebhookOutput if *v == nil { sv = &CreateWebhookOutput{} } else { sv = *v } for key, value := range shape { switch key { case "webhook": if err := awsRestjson1_deserializeDocumentWebhook(&sv.Webhook, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpDeleteApp struct { } func (*awsRestjson1_deserializeOpDeleteApp) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpDeleteApp) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorDeleteApp(response, &metadata) } output := &DeleteAppOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentDeleteAppOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorDeleteApp(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("DependentServiceFailureException", errorCode): return awsRestjson1_deserializeErrorDependentServiceFailureException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentDeleteAppOutput(v **DeleteAppOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *DeleteAppOutput if *v == nil { sv = &DeleteAppOutput{} } else { sv = *v } for key, value := range shape { switch key { case "app": if err := awsRestjson1_deserializeDocumentApp(&sv.App, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpDeleteBackendEnvironment struct { } func (*awsRestjson1_deserializeOpDeleteBackendEnvironment) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpDeleteBackendEnvironment) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorDeleteBackendEnvironment(response, &metadata) } output := &DeleteBackendEnvironmentOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentDeleteBackendEnvironmentOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorDeleteBackendEnvironment(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("DependentServiceFailureException", errorCode): return awsRestjson1_deserializeErrorDependentServiceFailureException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentDeleteBackendEnvironmentOutput(v **DeleteBackendEnvironmentOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *DeleteBackendEnvironmentOutput if *v == nil { sv = &DeleteBackendEnvironmentOutput{} } else { sv = *v } for key, value := range shape { switch key { case "backendEnvironment": if err := awsRestjson1_deserializeDocumentBackendEnvironment(&sv.BackendEnvironment, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpDeleteBranch struct { } func (*awsRestjson1_deserializeOpDeleteBranch) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpDeleteBranch) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorDeleteBranch(response, &metadata) } output := &DeleteBranchOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentDeleteBranchOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorDeleteBranch(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("DependentServiceFailureException", errorCode): return awsRestjson1_deserializeErrorDependentServiceFailureException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentDeleteBranchOutput(v **DeleteBranchOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *DeleteBranchOutput if *v == nil { sv = &DeleteBranchOutput{} } else { sv = *v } for key, value := range shape { switch key { case "branch": if err := awsRestjson1_deserializeDocumentBranch(&sv.Branch, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpDeleteDomainAssociation struct { } func (*awsRestjson1_deserializeOpDeleteDomainAssociation) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpDeleteDomainAssociation) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorDeleteDomainAssociation(response, &metadata) } output := &DeleteDomainAssociationOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentDeleteDomainAssociationOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorDeleteDomainAssociation(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("DependentServiceFailureException", errorCode): return awsRestjson1_deserializeErrorDependentServiceFailureException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentDeleteDomainAssociationOutput(v **DeleteDomainAssociationOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *DeleteDomainAssociationOutput if *v == nil { sv = &DeleteDomainAssociationOutput{} } else { sv = *v } for key, value := range shape { switch key { case "domainAssociation": if err := awsRestjson1_deserializeDocumentDomainAssociation(&sv.DomainAssociation, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpDeleteJob struct { } func (*awsRestjson1_deserializeOpDeleteJob) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpDeleteJob) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorDeleteJob(response, &metadata) } output := &DeleteJobOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentDeleteJobOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorDeleteJob(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("LimitExceededException", errorCode): return awsRestjson1_deserializeErrorLimitExceededException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentDeleteJobOutput(v **DeleteJobOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *DeleteJobOutput if *v == nil { sv = &DeleteJobOutput{} } else { sv = *v } for key, value := range shape { switch key { case "jobSummary": if err := awsRestjson1_deserializeDocumentJobSummary(&sv.JobSummary, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpDeleteWebhook struct { } func (*awsRestjson1_deserializeOpDeleteWebhook) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpDeleteWebhook) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorDeleteWebhook(response, &metadata) } output := &DeleteWebhookOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentDeleteWebhookOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorDeleteWebhook(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("LimitExceededException", errorCode): return awsRestjson1_deserializeErrorLimitExceededException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentDeleteWebhookOutput(v **DeleteWebhookOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *DeleteWebhookOutput if *v == nil { sv = &DeleteWebhookOutput{} } else { sv = *v } for key, value := range shape { switch key { case "webhook": if err := awsRestjson1_deserializeDocumentWebhook(&sv.Webhook, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpGenerateAccessLogs struct { } func (*awsRestjson1_deserializeOpGenerateAccessLogs) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpGenerateAccessLogs) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorGenerateAccessLogs(response, &metadata) } output := &GenerateAccessLogsOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentGenerateAccessLogsOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorGenerateAccessLogs(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentGenerateAccessLogsOutput(v **GenerateAccessLogsOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *GenerateAccessLogsOutput if *v == nil { sv = &GenerateAccessLogsOutput{} } else { sv = *v } for key, value := range shape { switch key { case "logUrl": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected LogUrl to be of type string, got %T instead", value) } sv.LogUrl = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpGetApp struct { } func (*awsRestjson1_deserializeOpGetApp) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpGetApp) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorGetApp(response, &metadata) } output := &GetAppOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentGetAppOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorGetApp(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentGetAppOutput(v **GetAppOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *GetAppOutput if *v == nil { sv = &GetAppOutput{} } else { sv = *v } for key, value := range shape { switch key { case "app": if err := awsRestjson1_deserializeDocumentApp(&sv.App, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpGetArtifactUrl struct { } func (*awsRestjson1_deserializeOpGetArtifactUrl) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpGetArtifactUrl) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorGetArtifactUrl(response, &metadata) } output := &GetArtifactUrlOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentGetArtifactUrlOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorGetArtifactUrl(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("LimitExceededException", errorCode): return awsRestjson1_deserializeErrorLimitExceededException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentGetArtifactUrlOutput(v **GetArtifactUrlOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *GetArtifactUrlOutput if *v == nil { sv = &GetArtifactUrlOutput{} } else { sv = *v } for key, value := range shape { switch key { case "artifactId": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected ArtifactId to be of type string, got %T instead", value) } sv.ArtifactId = ptr.String(jtv) } case "artifactUrl": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected ArtifactUrl to be of type string, got %T instead", value) } sv.ArtifactUrl = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpGetBackendEnvironment struct { } func (*awsRestjson1_deserializeOpGetBackendEnvironment) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpGetBackendEnvironment) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorGetBackendEnvironment(response, &metadata) } output := &GetBackendEnvironmentOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentGetBackendEnvironmentOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorGetBackendEnvironment(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentGetBackendEnvironmentOutput(v **GetBackendEnvironmentOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *GetBackendEnvironmentOutput if *v == nil { sv = &GetBackendEnvironmentOutput{} } else { sv = *v } for key, value := range shape { switch key { case "backendEnvironment": if err := awsRestjson1_deserializeDocumentBackendEnvironment(&sv.BackendEnvironment, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpGetBranch struct { } func (*awsRestjson1_deserializeOpGetBranch) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpGetBranch) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorGetBranch(response, &metadata) } output := &GetBranchOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentGetBranchOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorGetBranch(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentGetBranchOutput(v **GetBranchOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *GetBranchOutput if *v == nil { sv = &GetBranchOutput{} } else { sv = *v } for key, value := range shape { switch key { case "branch": if err := awsRestjson1_deserializeDocumentBranch(&sv.Branch, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpGetDomainAssociation struct { } func (*awsRestjson1_deserializeOpGetDomainAssociation) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpGetDomainAssociation) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorGetDomainAssociation(response, &metadata) } output := &GetDomainAssociationOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentGetDomainAssociationOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorGetDomainAssociation(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentGetDomainAssociationOutput(v **GetDomainAssociationOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *GetDomainAssociationOutput if *v == nil { sv = &GetDomainAssociationOutput{} } else { sv = *v } for key, value := range shape { switch key { case "domainAssociation": if err := awsRestjson1_deserializeDocumentDomainAssociation(&sv.DomainAssociation, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpGetJob struct { } func (*awsRestjson1_deserializeOpGetJob) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpGetJob) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorGetJob(response, &metadata) } output := &GetJobOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentGetJobOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorGetJob(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("LimitExceededException", errorCode): return awsRestjson1_deserializeErrorLimitExceededException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentGetJobOutput(v **GetJobOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *GetJobOutput if *v == nil { sv = &GetJobOutput{} } else { sv = *v } for key, value := range shape { switch key { case "job": if err := awsRestjson1_deserializeDocumentJob(&sv.Job, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpGetWebhook struct { } func (*awsRestjson1_deserializeOpGetWebhook) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpGetWebhook) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorGetWebhook(response, &metadata) } output := &GetWebhookOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentGetWebhookOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorGetWebhook(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("LimitExceededException", errorCode): return awsRestjson1_deserializeErrorLimitExceededException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentGetWebhookOutput(v **GetWebhookOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *GetWebhookOutput if *v == nil { sv = &GetWebhookOutput{} } else { sv = *v } for key, value := range shape { switch key { case "webhook": if err := awsRestjson1_deserializeDocumentWebhook(&sv.Webhook, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpListApps struct { } func (*awsRestjson1_deserializeOpListApps) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpListApps) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorListApps(response, &metadata) } output := &ListAppsOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentListAppsOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorListApps(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentListAppsOutput(v **ListAppsOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *ListAppsOutput if *v == nil { sv = &ListAppsOutput{} } else { sv = *v } for key, value := range shape { switch key { case "apps": if err := awsRestjson1_deserializeDocumentApps(&sv.Apps, value); err != nil { return err } case "nextToken": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected NextToken to be of type string, got %T instead", value) } sv.NextToken = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpListArtifacts struct { } func (*awsRestjson1_deserializeOpListArtifacts) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpListArtifacts) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorListArtifacts(response, &metadata) } output := &ListArtifactsOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentListArtifactsOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorListArtifacts(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("LimitExceededException", errorCode): return awsRestjson1_deserializeErrorLimitExceededException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentListArtifactsOutput(v **ListArtifactsOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *ListArtifactsOutput if *v == nil { sv = &ListArtifactsOutput{} } else { sv = *v } for key, value := range shape { switch key { case "artifacts": if err := awsRestjson1_deserializeDocumentArtifacts(&sv.Artifacts, value); err != nil { return err } case "nextToken": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected NextToken to be of type string, got %T instead", value) } sv.NextToken = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpListBackendEnvironments struct { } func (*awsRestjson1_deserializeOpListBackendEnvironments) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpListBackendEnvironments) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorListBackendEnvironments(response, &metadata) } output := &ListBackendEnvironmentsOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentListBackendEnvironmentsOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorListBackendEnvironments(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentListBackendEnvironmentsOutput(v **ListBackendEnvironmentsOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *ListBackendEnvironmentsOutput if *v == nil { sv = &ListBackendEnvironmentsOutput{} } else { sv = *v } for key, value := range shape { switch key { case "backendEnvironments": if err := awsRestjson1_deserializeDocumentBackendEnvironments(&sv.BackendEnvironments, value); err != nil { return err } case "nextToken": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected NextToken to be of type string, got %T instead", value) } sv.NextToken = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpListBranches struct { } func (*awsRestjson1_deserializeOpListBranches) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpListBranches) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorListBranches(response, &metadata) } output := &ListBranchesOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentListBranchesOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorListBranches(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentListBranchesOutput(v **ListBranchesOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *ListBranchesOutput if *v == nil { sv = &ListBranchesOutput{} } else { sv = *v } for key, value := range shape { switch key { case "branches": if err := awsRestjson1_deserializeDocumentBranches(&sv.Branches, value); err != nil { return err } case "nextToken": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected NextToken to be of type string, got %T instead", value) } sv.NextToken = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpListDomainAssociations struct { } func (*awsRestjson1_deserializeOpListDomainAssociations) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpListDomainAssociations) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorListDomainAssociations(response, &metadata) } output := &ListDomainAssociationsOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentListDomainAssociationsOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorListDomainAssociations(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentListDomainAssociationsOutput(v **ListDomainAssociationsOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *ListDomainAssociationsOutput if *v == nil { sv = &ListDomainAssociationsOutput{} } else { sv = *v } for key, value := range shape { switch key { case "domainAssociations": if err := awsRestjson1_deserializeDocumentDomainAssociations(&sv.DomainAssociations, value); err != nil { return err } case "nextToken": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected NextToken to be of type string, got %T instead", value) } sv.NextToken = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpListJobs struct { } func (*awsRestjson1_deserializeOpListJobs) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpListJobs) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorListJobs(response, &metadata) } output := &ListJobsOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentListJobsOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorListJobs(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("LimitExceededException", errorCode): return awsRestjson1_deserializeErrorLimitExceededException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentListJobsOutput(v **ListJobsOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *ListJobsOutput if *v == nil { sv = &ListJobsOutput{} } else { sv = *v } for key, value := range shape { switch key { case "jobSummaries": if err := awsRestjson1_deserializeDocumentJobSummaries(&sv.JobSummaries, value); err != nil { return err } case "nextToken": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected NextToken to be of type string, got %T instead", value) } sv.NextToken = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpListTagsForResource struct { } func (*awsRestjson1_deserializeOpListTagsForResource) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpListTagsForResource) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorListTagsForResource(response, &metadata) } output := &ListTagsForResourceOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentListTagsForResourceOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorListTagsForResource(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("ResourceNotFoundException", errorCode): return awsRestjson1_deserializeErrorResourceNotFoundException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentListTagsForResourceOutput(v **ListTagsForResourceOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *ListTagsForResourceOutput if *v == nil { sv = &ListTagsForResourceOutput{} } else { sv = *v } for key, value := range shape { switch key { case "tags": if err := awsRestjson1_deserializeDocumentTagMap(&sv.Tags, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpListWebhooks struct { } func (*awsRestjson1_deserializeOpListWebhooks) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpListWebhooks) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorListWebhooks(response, &metadata) } output := &ListWebhooksOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentListWebhooksOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorListWebhooks(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("LimitExceededException", errorCode): return awsRestjson1_deserializeErrorLimitExceededException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentListWebhooksOutput(v **ListWebhooksOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *ListWebhooksOutput if *v == nil { sv = &ListWebhooksOutput{} } else { sv = *v } for key, value := range shape { switch key { case "nextToken": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected NextToken to be of type string, got %T instead", value) } sv.NextToken = ptr.String(jtv) } case "webhooks": if err := awsRestjson1_deserializeDocumentWebhooks(&sv.Webhooks, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpStartDeployment struct { } func (*awsRestjson1_deserializeOpStartDeployment) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpStartDeployment) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorStartDeployment(response, &metadata) } output := &StartDeploymentOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentStartDeploymentOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorStartDeployment(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("LimitExceededException", errorCode): return awsRestjson1_deserializeErrorLimitExceededException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentStartDeploymentOutput(v **StartDeploymentOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *StartDeploymentOutput if *v == nil { sv = &StartDeploymentOutput{} } else { sv = *v } for key, value := range shape { switch key { case "jobSummary": if err := awsRestjson1_deserializeDocumentJobSummary(&sv.JobSummary, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpStartJob struct { } func (*awsRestjson1_deserializeOpStartJob) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpStartJob) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorStartJob(response, &metadata) } output := &StartJobOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentStartJobOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorStartJob(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("LimitExceededException", errorCode): return awsRestjson1_deserializeErrorLimitExceededException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentStartJobOutput(v **StartJobOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *StartJobOutput if *v == nil { sv = &StartJobOutput{} } else { sv = *v } for key, value := range shape { switch key { case "jobSummary": if err := awsRestjson1_deserializeDocumentJobSummary(&sv.JobSummary, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpStopJob struct { } func (*awsRestjson1_deserializeOpStopJob) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpStopJob) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorStopJob(response, &metadata) } output := &StopJobOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentStopJobOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorStopJob(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("LimitExceededException", errorCode): return awsRestjson1_deserializeErrorLimitExceededException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentStopJobOutput(v **StopJobOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *StopJobOutput if *v == nil { sv = &StopJobOutput{} } else { sv = *v } for key, value := range shape { switch key { case "jobSummary": if err := awsRestjson1_deserializeDocumentJobSummary(&sv.JobSummary, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpTagResource struct { } func (*awsRestjson1_deserializeOpTagResource) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpTagResource) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorTagResource(response, &metadata) } output := &TagResourceOutput{} out.Result = output return out, metadata, err } func awsRestjson1_deserializeOpErrorTagResource(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("ResourceNotFoundException", errorCode): return awsRestjson1_deserializeErrorResourceNotFoundException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } type awsRestjson1_deserializeOpUntagResource struct { } func (*awsRestjson1_deserializeOpUntagResource) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpUntagResource) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorUntagResource(response, &metadata) } output := &UntagResourceOutput{} out.Result = output return out, metadata, err } func awsRestjson1_deserializeOpErrorUntagResource(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("ResourceNotFoundException", errorCode): return awsRestjson1_deserializeErrorResourceNotFoundException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } type awsRestjson1_deserializeOpUpdateApp struct { } func (*awsRestjson1_deserializeOpUpdateApp) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpUpdateApp) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorUpdateApp(response, &metadata) } output := &UpdateAppOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentUpdateAppOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorUpdateApp(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentUpdateAppOutput(v **UpdateAppOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *UpdateAppOutput if *v == nil { sv = &UpdateAppOutput{} } else { sv = *v } for key, value := range shape { switch key { case "app": if err := awsRestjson1_deserializeDocumentApp(&sv.App, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpUpdateBranch struct { } func (*awsRestjson1_deserializeOpUpdateBranch) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpUpdateBranch) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorUpdateBranch(response, &metadata) } output := &UpdateBranchOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentUpdateBranchOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorUpdateBranch(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("DependentServiceFailureException", errorCode): return awsRestjson1_deserializeErrorDependentServiceFailureException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentUpdateBranchOutput(v **UpdateBranchOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *UpdateBranchOutput if *v == nil { sv = &UpdateBranchOutput{} } else { sv = *v } for key, value := range shape { switch key { case "branch": if err := awsRestjson1_deserializeDocumentBranch(&sv.Branch, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpUpdateDomainAssociation struct { } func (*awsRestjson1_deserializeOpUpdateDomainAssociation) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpUpdateDomainAssociation) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorUpdateDomainAssociation(response, &metadata) } output := &UpdateDomainAssociationOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentUpdateDomainAssociationOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorUpdateDomainAssociation(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("DependentServiceFailureException", errorCode): return awsRestjson1_deserializeErrorDependentServiceFailureException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentUpdateDomainAssociationOutput(v **UpdateDomainAssociationOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *UpdateDomainAssociationOutput if *v == nil { sv = &UpdateDomainAssociationOutput{} } else { sv = *v } for key, value := range shape { switch key { case "domainAssociation": if err := awsRestjson1_deserializeDocumentDomainAssociation(&sv.DomainAssociation, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } type awsRestjson1_deserializeOpUpdateWebhook struct { } func (*awsRestjson1_deserializeOpUpdateWebhook) ID() string { return "OperationDeserializer" } func (m *awsRestjson1_deserializeOpUpdateWebhook) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( out middleware.DeserializeOutput, metadata middleware.Metadata, err error, ) { out, metadata, err = next.HandleDeserialize(ctx, in) if err != nil { return out, metadata, err } response, ok := out.RawResponse.(*smithyhttp.Response) if !ok { return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} } if response.StatusCode < 200 || response.StatusCode >= 300 { return out, metadata, awsRestjson1_deserializeOpErrorUpdateWebhook(response, &metadata) } output := &UpdateWebhookOutput{} out.Result = output var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(response.Body, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return out, metadata, err } err = awsRestjson1_deserializeOpDocumentUpdateWebhookOutput(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) return out, metadata, &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), Snapshot: snapshot.Bytes(), } } return out, metadata, err } func awsRestjson1_deserializeOpErrorUpdateWebhook(response *smithyhttp.Response, metadata *middleware.Metadata) error { var errorBuffer bytes.Buffer if _, err := io.Copy(&errorBuffer, response.Body); err != nil { return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} } errorBody := bytes.NewReader(errorBuffer.Bytes()) errorCode := "UnknownError" errorMessage := errorCode code := response.Header.Get("X-Amzn-ErrorType") if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() code, message, err := restjson.GetErrorInfo(decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) if len(code) != 0 { errorCode = restjson.SanitizeErrorCode(code) } if len(message) != 0 { errorMessage = message } switch { case strings.EqualFold("BadRequestException", errorCode): return awsRestjson1_deserializeErrorBadRequestException(response, errorBody) case strings.EqualFold("DependentServiceFailureException", errorCode): return awsRestjson1_deserializeErrorDependentServiceFailureException(response, errorBody) case strings.EqualFold("InternalFailureException", errorCode): return awsRestjson1_deserializeErrorInternalFailureException(response, errorBody) case strings.EqualFold("NotFoundException", errorCode): return awsRestjson1_deserializeErrorNotFoundException(response, errorBody) case strings.EqualFold("UnauthorizedException", errorCode): return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) default: genericError := &smithy.GenericAPIError{ Code: errorCode, Message: errorMessage, } return genericError } } func awsRestjson1_deserializeOpDocumentUpdateWebhookOutput(v **UpdateWebhookOutput, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *UpdateWebhookOutput if *v == nil { sv = &UpdateWebhookOutput{} } else { sv = *v } for key, value := range shape { switch key { case "webhook": if err := awsRestjson1_deserializeDocumentWebhook(&sv.Webhook, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeErrorBadRequestException(response *smithyhttp.Response, errorBody *bytes.Reader) error { output := &types.BadRequestException{} var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } err := awsRestjson1_deserializeDocumentBadRequestException(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) return output } func awsRestjson1_deserializeErrorDependentServiceFailureException(response *smithyhttp.Response, errorBody *bytes.Reader) error { output := &types.DependentServiceFailureException{} var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } err := awsRestjson1_deserializeDocumentDependentServiceFailureException(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) return output } func awsRestjson1_deserializeErrorInternalFailureException(response *smithyhttp.Response, errorBody *bytes.Reader) error { output := &types.InternalFailureException{} var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } err := awsRestjson1_deserializeDocumentInternalFailureException(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) return output } func awsRestjson1_deserializeErrorLimitExceededException(response *smithyhttp.Response, errorBody *bytes.Reader) error { output := &types.LimitExceededException{} var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } err := awsRestjson1_deserializeDocumentLimitExceededException(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) return output } func awsRestjson1_deserializeErrorNotFoundException(response *smithyhttp.Response, errorBody *bytes.Reader) error { output := &types.NotFoundException{} var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } err := awsRestjson1_deserializeDocumentNotFoundException(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) return output } func awsRestjson1_deserializeErrorResourceNotFoundException(response *smithyhttp.Response, errorBody *bytes.Reader) error { output := &types.ResourceNotFoundException{} var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } err := awsRestjson1_deserializeDocumentResourceNotFoundException(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) return output } func awsRestjson1_deserializeErrorUnauthorizedException(response *smithyhttp.Response, errorBody *bytes.Reader) error { output := &types.UnauthorizedException{} var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) decoder := json.NewDecoder(body) decoder.UseNumber() var shape interface{} if err := decoder.Decode(&shape); err != nil && err != io.EOF { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } err := awsRestjson1_deserializeDocumentUnauthorizedException(&output, shape) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) err = &smithy.DeserializationError{ Err: fmt.Errorf("failed to decode response body, %w", err), Snapshot: snapshot.Bytes(), } return err } errorBody.Seek(0, io.SeekStart) return output } func awsRestjson1_deserializeDocumentApp(v **types.App, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.App if *v == nil { sv = &types.App{} } else { sv = *v } for key, value := range shape { switch key { case "appArn": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected AppArn to be of type string, got %T instead", value) } sv.AppArn = ptr.String(jtv) } case "appId": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected AppId to be of type string, got %T instead", value) } sv.AppId = ptr.String(jtv) } case "autoBranchCreationConfig": if err := awsRestjson1_deserializeDocumentAutoBranchCreationConfig(&sv.AutoBranchCreationConfig, value); err != nil { return err } case "autoBranchCreationPatterns": if err := awsRestjson1_deserializeDocumentAutoBranchCreationPatterns(&sv.AutoBranchCreationPatterns, value); err != nil { return err } case "basicAuthCredentials": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected BasicAuthCredentials to be of type string, got %T instead", value) } sv.BasicAuthCredentials = ptr.String(jtv) } case "buildSpec": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected BuildSpec to be of type string, got %T instead", value) } sv.BuildSpec = ptr.String(jtv) } case "createTime": if value != nil { switch jtv := value.(type) { case json.Number: f64, err := jtv.Float64() if err != nil { return err } sv.CreateTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) default: return fmt.Errorf("expected CreateTime to be a JSON Number, got %T instead", value) } } case "customHeaders": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected CustomHeaders to be of type string, got %T instead", value) } sv.CustomHeaders = ptr.String(jtv) } case "customRules": if err := awsRestjson1_deserializeDocumentCustomRules(&sv.CustomRules, value); err != nil { return err } case "defaultDomain": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected DefaultDomain to be of type string, got %T instead", value) } sv.DefaultDomain = ptr.String(jtv) } case "description": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected Description to be of type string, got %T instead", value) } sv.Description = ptr.String(jtv) } case "enableAutoBranchCreation": if value != nil { jtv, ok := value.(bool) if !ok { return fmt.Errorf("expected EnableAutoBranchCreation to be of type *bool, got %T instead", value) } sv.EnableAutoBranchCreation = ptr.Bool(jtv) } case "enableBasicAuth": if value != nil { jtv, ok := value.(bool) if !ok { return fmt.Errorf("expected EnableBasicAuth to be of type *bool, got %T instead", value) } sv.EnableBasicAuth = ptr.Bool(jtv) } case "enableBranchAutoBuild": if value != nil { jtv, ok := value.(bool) if !ok { return fmt.Errorf("expected EnableBranchAutoBuild to be of type *bool, got %T instead", value) } sv.EnableBranchAutoBuild = ptr.Bool(jtv) } case "enableBranchAutoDeletion": if value != nil { jtv, ok := value.(bool) if !ok { return fmt.Errorf("expected EnableBranchAutoDeletion to be of type *bool, got %T instead", value) } sv.EnableBranchAutoDeletion = ptr.Bool(jtv) } case "environmentVariables": if err := awsRestjson1_deserializeDocumentEnvironmentVariables(&sv.EnvironmentVariables, value); err != nil { return err } case "iamServiceRoleArn": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected ServiceRoleArn to be of type string, got %T instead", value) } sv.IamServiceRoleArn = ptr.String(jtv) } case "name": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected Name to be of type string, got %T instead", value) } sv.Name = ptr.String(jtv) } case "platform": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected Platform to be of type string, got %T instead", value) } sv.Platform = types.Platform(jtv) } case "productionBranch": if err := awsRestjson1_deserializeDocumentProductionBranch(&sv.ProductionBranch, value); err != nil { return err } case "repository": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected Repository to be of type string, got %T instead", value) } sv.Repository = ptr.String(jtv) } case "tags": if err := awsRestjson1_deserializeDocumentTagMap(&sv.Tags, value); err != nil { return err } case "updateTime": if value != nil { switch jtv := value.(type) { case json.Number: f64, err := jtv.Float64() if err != nil { return err } sv.UpdateTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) default: return fmt.Errorf("expected UpdateTime to be a JSON Number, got %T instead", value) } } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentApps(v *[]types.App, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.([]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var cv []types.App if *v == nil { cv = []types.App{} } else { cv = *v } for _, value := range shape { var col types.App destAddr := &col if err := awsRestjson1_deserializeDocumentApp(&destAddr, value); err != nil { return err } col = *destAddr cv = append(cv, col) } *v = cv return nil } func awsRestjson1_deserializeDocumentArtifact(v **types.Artifact, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.Artifact if *v == nil { sv = &types.Artifact{} } else { sv = *v } for key, value := range shape { switch key { case "artifactFileName": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected ArtifactFileName to be of type string, got %T instead", value) } sv.ArtifactFileName = ptr.String(jtv) } case "artifactId": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected ArtifactId to be of type string, got %T instead", value) } sv.ArtifactId = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentArtifacts(v *[]types.Artifact, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.([]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var cv []types.Artifact if *v == nil { cv = []types.Artifact{} } else { cv = *v } for _, value := range shape { var col types.Artifact destAddr := &col if err := awsRestjson1_deserializeDocumentArtifact(&destAddr, value); err != nil { return err } col = *destAddr cv = append(cv, col) } *v = cv return nil } func awsRestjson1_deserializeDocumentAssociatedResources(v *[]string, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.([]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var cv []string if *v == nil { cv = []string{} } else { cv = *v } for _, value := range shape { var col string if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected AssociatedResource to be of type string, got %T instead", value) } col = jtv } cv = append(cv, col) } *v = cv return nil } func awsRestjson1_deserializeDocumentAutoBranchCreationConfig(v **types.AutoBranchCreationConfig, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.AutoBranchCreationConfig if *v == nil { sv = &types.AutoBranchCreationConfig{} } else { sv = *v } for key, value := range shape { switch key { case "basicAuthCredentials": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected BasicAuthCredentials to be of type string, got %T instead", value) } sv.BasicAuthCredentials = ptr.String(jtv) } case "buildSpec": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected BuildSpec to be of type string, got %T instead", value) } sv.BuildSpec = ptr.String(jtv) } case "enableAutoBuild": if value != nil { jtv, ok := value.(bool) if !ok { return fmt.Errorf("expected EnableAutoBuild to be of type *bool, got %T instead", value) } sv.EnableAutoBuild = ptr.Bool(jtv) } case "enableBasicAuth": if value != nil { jtv, ok := value.(bool) if !ok { return fmt.Errorf("expected EnableBasicAuth to be of type *bool, got %T instead", value) } sv.EnableBasicAuth = ptr.Bool(jtv) } case "enablePerformanceMode": if value != nil { jtv, ok := value.(bool) if !ok { return fmt.Errorf("expected EnablePerformanceMode to be of type *bool, got %T instead", value) } sv.EnablePerformanceMode = ptr.Bool(jtv) } case "enablePullRequestPreview": if value != nil { jtv, ok := value.(bool) if !ok { return fmt.Errorf("expected EnablePullRequestPreview to be of type *bool, got %T instead", value) } sv.EnablePullRequestPreview = ptr.Bool(jtv) } case "environmentVariables": if err := awsRestjson1_deserializeDocumentEnvironmentVariables(&sv.EnvironmentVariables, value); err != nil { return err } case "framework": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected Framework to be of type string, got %T instead", value) } sv.Framework = ptr.String(jtv) } case "pullRequestEnvironmentName": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected PullRequestEnvironmentName to be of type string, got %T instead", value) } sv.PullRequestEnvironmentName = ptr.String(jtv) } case "stage": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected Stage to be of type string, got %T instead", value) } sv.Stage = types.Stage(jtv) } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentAutoBranchCreationPatterns(v *[]string, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.([]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var cv []string if *v == nil { cv = []string{} } else { cv = *v } for _, value := range shape { var col string if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected AutoBranchCreationPattern to be of type string, got %T instead", value) } col = jtv } cv = append(cv, col) } *v = cv return nil } func awsRestjson1_deserializeDocumentAutoSubDomainCreationPatterns(v *[]string, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.([]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var cv []string if *v == nil { cv = []string{} } else { cv = *v } for _, value := range shape { var col string if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected AutoSubDomainCreationPattern to be of type string, got %T instead", value) } col = jtv } cv = append(cv, col) } *v = cv return nil } func awsRestjson1_deserializeDocumentBackendEnvironment(v **types.BackendEnvironment, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.BackendEnvironment if *v == nil { sv = &types.BackendEnvironment{} } else { sv = *v } for key, value := range shape { switch key { case "backendEnvironmentArn": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected BackendEnvironmentArn to be of type string, got %T instead", value) } sv.BackendEnvironmentArn = ptr.String(jtv) } case "createTime": if value != nil { switch jtv := value.(type) { case json.Number: f64, err := jtv.Float64() if err != nil { return err } sv.CreateTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) default: return fmt.Errorf("expected CreateTime to be a JSON Number, got %T instead", value) } } case "deploymentArtifacts": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected DeploymentArtifacts to be of type string, got %T instead", value) } sv.DeploymentArtifacts = ptr.String(jtv) } case "environmentName": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected EnvironmentName to be of type string, got %T instead", value) } sv.EnvironmentName = ptr.String(jtv) } case "stackName": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected StackName to be of type string, got %T instead", value) } sv.StackName = ptr.String(jtv) } case "updateTime": if value != nil { switch jtv := value.(type) { case json.Number: f64, err := jtv.Float64() if err != nil { return err } sv.UpdateTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) default: return fmt.Errorf("expected UpdateTime to be a JSON Number, got %T instead", value) } } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentBackendEnvironments(v *[]types.BackendEnvironment, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.([]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var cv []types.BackendEnvironment if *v == nil { cv = []types.BackendEnvironment{} } else { cv = *v } for _, value := range shape { var col types.BackendEnvironment destAddr := &col if err := awsRestjson1_deserializeDocumentBackendEnvironment(&destAddr, value); err != nil { return err } col = *destAddr cv = append(cv, col) } *v = cv return nil } func awsRestjson1_deserializeDocumentBadRequestException(v **types.BadRequestException, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.BadRequestException if *v == nil { sv = &types.BadRequestException{} } else { sv = *v } for key, value := range shape { switch key { case "message": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) } sv.Message = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentBranch(v **types.Branch, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.Branch if *v == nil { sv = &types.Branch{} } else { sv = *v } for key, value := range shape { switch key { case "activeJobId": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected ActiveJobId to be of type string, got %T instead", value) } sv.ActiveJobId = ptr.String(jtv) } case "associatedResources": if err := awsRestjson1_deserializeDocumentAssociatedResources(&sv.AssociatedResources, value); err != nil { return err } case "backendEnvironmentArn": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected BackendEnvironmentArn to be of type string, got %T instead", value) } sv.BackendEnvironmentArn = ptr.String(jtv) } case "basicAuthCredentials": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected BasicAuthCredentials to be of type string, got %T instead", value) } sv.BasicAuthCredentials = ptr.String(jtv) } case "branchArn": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected BranchArn to be of type string, got %T instead", value) } sv.BranchArn = ptr.String(jtv) } case "branchName": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected BranchName to be of type string, got %T instead", value) } sv.BranchName = ptr.String(jtv) } case "buildSpec": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected BuildSpec to be of type string, got %T instead", value) } sv.BuildSpec = ptr.String(jtv) } case "createTime": if value != nil { switch jtv := value.(type) { case json.Number: f64, err := jtv.Float64() if err != nil { return err } sv.CreateTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) default: return fmt.Errorf("expected CreateTime to be a JSON Number, got %T instead", value) } } case "customDomains": if err := awsRestjson1_deserializeDocumentCustomDomains(&sv.CustomDomains, value); err != nil { return err } case "description": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected Description to be of type string, got %T instead", value) } sv.Description = ptr.String(jtv) } case "destinationBranch": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected BranchName to be of type string, got %T instead", value) } sv.DestinationBranch = ptr.String(jtv) } case "displayName": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected DisplayName to be of type string, got %T instead", value) } sv.DisplayName = ptr.String(jtv) } case "enableAutoBuild": if value != nil { jtv, ok := value.(bool) if !ok { return fmt.Errorf("expected EnableAutoBuild to be of type *bool, got %T instead", value) } sv.EnableAutoBuild = ptr.Bool(jtv) } case "enableBasicAuth": if value != nil { jtv, ok := value.(bool) if !ok { return fmt.Errorf("expected EnableBasicAuth to be of type *bool, got %T instead", value) } sv.EnableBasicAuth = ptr.Bool(jtv) } case "enableNotification": if value != nil { jtv, ok := value.(bool) if !ok { return fmt.Errorf("expected EnableNotification to be of type *bool, got %T instead", value) } sv.EnableNotification = ptr.Bool(jtv) } case "enablePerformanceMode": if value != nil { jtv, ok := value.(bool) if !ok { return fmt.Errorf("expected EnablePerformanceMode to be of type *bool, got %T instead", value) } sv.EnablePerformanceMode = ptr.Bool(jtv) } case "enablePullRequestPreview": if value != nil { jtv, ok := value.(bool) if !ok { return fmt.Errorf("expected EnablePullRequestPreview to be of type *bool, got %T instead", value) } sv.EnablePullRequestPreview = ptr.Bool(jtv) } case "environmentVariables": if err := awsRestjson1_deserializeDocumentEnvironmentVariables(&sv.EnvironmentVariables, value); err != nil { return err } case "framework": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected Framework to be of type string, got %T instead", value) } sv.Framework = ptr.String(jtv) } case "pullRequestEnvironmentName": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected PullRequestEnvironmentName to be of type string, got %T instead", value) } sv.PullRequestEnvironmentName = ptr.String(jtv) } case "sourceBranch": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected BranchName to be of type string, got %T instead", value) } sv.SourceBranch = ptr.String(jtv) } case "stage": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected Stage to be of type string, got %T instead", value) } sv.Stage = types.Stage(jtv) } case "tags": if err := awsRestjson1_deserializeDocumentTagMap(&sv.Tags, value); err != nil { return err } case "thumbnailUrl": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected ThumbnailUrl to be of type string, got %T instead", value) } sv.ThumbnailUrl = ptr.String(jtv) } case "totalNumberOfJobs": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected TotalNumberOfJobs to be of type string, got %T instead", value) } sv.TotalNumberOfJobs = ptr.String(jtv) } case "ttl": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected TTL to be of type string, got %T instead", value) } sv.Ttl = ptr.String(jtv) } case "updateTime": if value != nil { switch jtv := value.(type) { case json.Number: f64, err := jtv.Float64() if err != nil { return err } sv.UpdateTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) default: return fmt.Errorf("expected UpdateTime to be a JSON Number, got %T instead", value) } } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentBranches(v *[]types.Branch, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.([]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var cv []types.Branch if *v == nil { cv = []types.Branch{} } else { cv = *v } for _, value := range shape { var col types.Branch destAddr := &col if err := awsRestjson1_deserializeDocumentBranch(&destAddr, value); err != nil { return err } col = *destAddr cv = append(cv, col) } *v = cv return nil } func awsRestjson1_deserializeDocumentCustomDomains(v *[]string, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.([]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var cv []string if *v == nil { cv = []string{} } else { cv = *v } for _, value := range shape { var col string if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected CustomDomain to be of type string, got %T instead", value) } col = jtv } cv = append(cv, col) } *v = cv return nil } func awsRestjson1_deserializeDocumentCustomRule(v **types.CustomRule, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.CustomRule if *v == nil { sv = &types.CustomRule{} } else { sv = *v } for key, value := range shape { switch key { case "condition": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected Condition to be of type string, got %T instead", value) } sv.Condition = ptr.String(jtv) } case "source": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected Source to be of type string, got %T instead", value) } sv.Source = ptr.String(jtv)
case "status": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected Status to be of type string, got %T instead", value) } sv.Status = ptr.String(jtv) } case "target": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected Target to be of type string, got %T instead", value) } sv.Target = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentCustomRules(v *[]types.CustomRule, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.([]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var cv []types.CustomRule if *v == nil { cv = []types.CustomRule{} } else { cv = *v } for _, value := range shape { var col types.CustomRule destAddr := &col if err := awsRestjson1_deserializeDocumentCustomRule(&destAddr, value); err != nil { return err } col = *destAddr cv = append(cv, col) } *v = cv return nil } func awsRestjson1_deserializeDocumentDependentServiceFailureException(v **types.DependentServiceFailureException, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.DependentServiceFailureException if *v == nil { sv = &types.DependentServiceFailureException{} } else { sv = *v } for key, value := range shape { switch key { case "message": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) } sv.Message = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentDomainAssociation(v **types.DomainAssociation, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.DomainAssociation if *v == nil { sv = &types.DomainAssociation{} } else { sv = *v } for key, value := range shape { switch key { case "autoSubDomainCreationPatterns": if err := awsRestjson1_deserializeDocumentAutoSubDomainCreationPatterns(&sv.AutoSubDomainCreationPatterns, value); err != nil { return err } case "autoSubDomainIAMRole": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected AutoSubDomainIAMRole to be of type string, got %T instead", value) } sv.AutoSubDomainIAMRole = ptr.String(jtv) } case "certificateVerificationDNSRecord": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected CertificateVerificationDNSRecord to be of type string, got %T instead", value) } sv.CertificateVerificationDNSRecord = ptr.String(jtv) } case "domainAssociationArn": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected DomainAssociationArn to be of type string, got %T instead", value) } sv.DomainAssociationArn = ptr.String(jtv) } case "domainName": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected DomainName to be of type string, got %T instead", value) } sv.DomainName = ptr.String(jtv) } case "domainStatus": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected DomainStatus to be of type string, got %T instead", value) } sv.DomainStatus = types.DomainStatus(jtv) } case "enableAutoSubDomain": if value != nil { jtv, ok := value.(bool) if !ok { return fmt.Errorf("expected EnableAutoSubDomain to be of type *bool, got %T instead", value) } sv.EnableAutoSubDomain = ptr.Bool(jtv) } case "statusReason": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected StatusReason to be of type string, got %T instead", value) } sv.StatusReason = ptr.String(jtv) } case "subDomains": if err := awsRestjson1_deserializeDocumentSubDomains(&sv.SubDomains, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentDomainAssociations(v *[]types.DomainAssociation, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.([]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var cv []types.DomainAssociation if *v == nil { cv = []types.DomainAssociation{} } else { cv = *v } for _, value := range shape { var col types.DomainAssociation destAddr := &col if err := awsRestjson1_deserializeDocumentDomainAssociation(&destAddr, value); err != nil { return err } col = *destAddr cv = append(cv, col) } *v = cv return nil } func awsRestjson1_deserializeDocumentEnvironmentVariables(v *map[string]string, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var mv map[string]string if *v == nil { mv = map[string]string{} } else { mv = *v } for key, value := range shape { var parsedVal string if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected EnvValue to be of type string, got %T instead", value) } parsedVal = jtv } mv[key] = parsedVal } *v = mv return nil } func awsRestjson1_deserializeDocumentFileUploadUrls(v *map[string]string, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var mv map[string]string if *v == nil { mv = map[string]string{} } else { mv = *v } for key, value := range shape { var parsedVal string if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected UploadUrl to be of type string, got %T instead", value) } parsedVal = jtv } mv[key] = parsedVal } *v = mv return nil } func awsRestjson1_deserializeDocumentInternalFailureException(v **types.InternalFailureException, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.InternalFailureException if *v == nil { sv = &types.InternalFailureException{} } else { sv = *v } for key, value := range shape { switch key { case "message": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) } sv.Message = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentJob(v **types.Job, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.Job if *v == nil { sv = &types.Job{} } else { sv = *v } for key, value := range shape { switch key { case "steps": if err := awsRestjson1_deserializeDocumentSteps(&sv.Steps, value); err != nil { return err } case "summary": if err := awsRestjson1_deserializeDocumentJobSummary(&sv.Summary, value); err != nil { return err } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentJobSummaries(v *[]types.JobSummary, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.([]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var cv []types.JobSummary if *v == nil { cv = []types.JobSummary{} } else { cv = *v } for _, value := range shape { var col types.JobSummary destAddr := &col if err := awsRestjson1_deserializeDocumentJobSummary(&destAddr, value); err != nil { return err } col = *destAddr cv = append(cv, col) } *v = cv return nil } func awsRestjson1_deserializeDocumentJobSummary(v **types.JobSummary, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.JobSummary if *v == nil { sv = &types.JobSummary{} } else { sv = *v } for key, value := range shape { switch key { case "commitId": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected CommitId to be of type string, got %T instead", value) } sv.CommitId = ptr.String(jtv) } case "commitMessage": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected CommitMessage to be of type string, got %T instead", value) } sv.CommitMessage = ptr.String(jtv) } case "commitTime": if value != nil { switch jtv := value.(type) { case json.Number: f64, err := jtv.Float64() if err != nil { return err } sv.CommitTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) default: return fmt.Errorf("expected CommitTime to be a JSON Number, got %T instead", value) } } case "endTime": if value != nil { switch jtv := value.(type) { case json.Number: f64, err := jtv.Float64() if err != nil { return err } sv.EndTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) default: return fmt.Errorf("expected EndTime to be a JSON Number, got %T instead", value) } } case "jobArn": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected JobArn to be of type string, got %T instead", value) } sv.JobArn = ptr.String(jtv) } case "jobId": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected JobId to be of type string, got %T instead", value) } sv.JobId = ptr.String(jtv) } case "jobType": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected JobType to be of type string, got %T instead", value) } sv.JobType = types.JobType(jtv) } case "startTime": if value != nil { switch jtv := value.(type) { case json.Number: f64, err := jtv.Float64() if err != nil { return err } sv.StartTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) default: return fmt.Errorf("expected StartTime to be a JSON Number, got %T instead", value) } } case "status": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected JobStatus to be of type string, got %T instead", value) } sv.Status = types.JobStatus(jtv) } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentLimitExceededException(v **types.LimitExceededException, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.LimitExceededException if *v == nil { sv = &types.LimitExceededException{} } else { sv = *v } for key, value := range shape { switch key { case "message": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) } sv.Message = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentNotFoundException(v **types.NotFoundException, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.NotFoundException if *v == nil { sv = &types.NotFoundException{} } else { sv = *v } for key, value := range shape { switch key { case "message": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) } sv.Message = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentProductionBranch(v **types.ProductionBranch, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.ProductionBranch if *v == nil { sv = &types.ProductionBranch{} } else { sv = *v } for key, value := range shape { switch key { case "branchName": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected BranchName to be of type string, got %T instead", value) } sv.BranchName = ptr.String(jtv) } case "lastDeployTime": if value != nil { switch jtv := value.(type) { case json.Number: f64, err := jtv.Float64() if err != nil { return err } sv.LastDeployTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) default: return fmt.Errorf("expected LastDeployTime to be a JSON Number, got %T instead", value) } } case "status": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected Status to be of type string, got %T instead", value) } sv.Status = ptr.String(jtv) } case "thumbnailUrl": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected ThumbnailUrl to be of type string, got %T instead", value) } sv.ThumbnailUrl = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentResourceNotFoundException(v **types.ResourceNotFoundException, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.ResourceNotFoundException if *v == nil { sv = &types.ResourceNotFoundException{} } else { sv = *v } for key, value := range shape { switch key { case "code": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected Code to be of type string, got %T instead", value) } sv.Code = ptr.String(jtv) } case "message": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) } sv.Message = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentScreenshots(v *map[string]string, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var mv map[string]string if *v == nil { mv = map[string]string{} } else { mv = *v } for key, value := range shape { var parsedVal string if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected ThumbnailUrl to be of type string, got %T instead", value) } parsedVal = jtv } mv[key] = parsedVal } *v = mv return nil } func awsRestjson1_deserializeDocumentStep(v **types.Step, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.Step if *v == nil { sv = &types.Step{} } else { sv = *v } for key, value := range shape { switch key { case "artifactsUrl": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected ArtifactsUrl to be of type string, got %T instead", value) } sv.ArtifactsUrl = ptr.String(jtv) } case "context": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected Context to be of type string, got %T instead", value) } sv.Context = ptr.String(jtv) } case "endTime": if value != nil { switch jtv := value.(type) { case json.Number: f64, err := jtv.Float64() if err != nil { return err } sv.EndTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) default: return fmt.Errorf("expected EndTime to be a JSON Number, got %T instead", value) } } case "logUrl": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected LogUrl to be of type string, got %T instead", value) } sv.LogUrl = ptr.String(jtv) } case "screenshots": if err := awsRestjson1_deserializeDocumentScreenshots(&sv.Screenshots, value); err != nil { return err } case "startTime": if value != nil { switch jtv := value.(type) { case json.Number: f64, err := jtv.Float64() if err != nil { return err } sv.StartTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) default: return fmt.Errorf("expected StartTime to be a JSON Number, got %T instead", value) } } case "status": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected JobStatus to be of type string, got %T instead", value) } sv.Status = types.JobStatus(jtv) } case "statusReason": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected StatusReason to be of type string, got %T instead", value) } sv.StatusReason = ptr.String(jtv) } case "stepName": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected StepName to be of type string, got %T instead", value) } sv.StepName = ptr.String(jtv) } case "testArtifactsUrl": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected TestArtifactsUrl to be of type string, got %T instead", value) } sv.TestArtifactsUrl = ptr.String(jtv) } case "testConfigUrl": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected TestConfigUrl to be of type string, got %T instead", value) } sv.TestConfigUrl = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentSteps(v *[]types.Step, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.([]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var cv []types.Step if *v == nil { cv = []types.Step{} } else { cv = *v } for _, value := range shape { var col types.Step destAddr := &col if err := awsRestjson1_deserializeDocumentStep(&destAddr, value); err != nil { return err } col = *destAddr cv = append(cv, col) } *v = cv return nil } func awsRestjson1_deserializeDocumentSubDomain(v **types.SubDomain, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.SubDomain if *v == nil { sv = &types.SubDomain{} } else { sv = *v } for key, value := range shape { switch key { case "dnsRecord": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected DNSRecord to be of type string, got %T instead", value) } sv.DnsRecord = ptr.String(jtv) } case "subDomainSetting": if err := awsRestjson1_deserializeDocumentSubDomainSetting(&sv.SubDomainSetting, value); err != nil { return err } case "verified": if value != nil { jtv, ok := value.(bool) if !ok { return fmt.Errorf("expected Verified to be of type *bool, got %T instead", value) } sv.Verified = ptr.Bool(jtv) } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentSubDomains(v *[]types.SubDomain, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.([]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var cv []types.SubDomain if *v == nil { cv = []types.SubDomain{} } else { cv = *v } for _, value := range shape { var col types.SubDomain destAddr := &col if err := awsRestjson1_deserializeDocumentSubDomain(&destAddr, value); err != nil { return err } col = *destAddr cv = append(cv, col) } *v = cv return nil } func awsRestjson1_deserializeDocumentSubDomainSetting(v **types.SubDomainSetting, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.SubDomainSetting if *v == nil { sv = &types.SubDomainSetting{} } else { sv = *v } for key, value := range shape { switch key { case "branchName": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected BranchName to be of type string, got %T instead", value) } sv.BranchName = ptr.String(jtv) } case "prefix": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected DomainPrefix to be of type string, got %T instead", value) } sv.Prefix = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentTagMap(v *map[string]string, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var mv map[string]string if *v == nil { mv = map[string]string{} } else { mv = *v } for key, value := range shape { var parsedVal string if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected TagValue to be of type string, got %T instead", value) } parsedVal = jtv } mv[key] = parsedVal } *v = mv return nil } func awsRestjson1_deserializeDocumentUnauthorizedException(v **types.UnauthorizedException, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.UnauthorizedException if *v == nil { sv = &types.UnauthorizedException{} } else { sv = *v } for key, value := range shape { switch key { case "message": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) } sv.Message = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentWebhook(v **types.Webhook, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var sv *types.Webhook if *v == nil { sv = &types.Webhook{} } else { sv = *v } for key, value := range shape { switch key { case "branchName": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected BranchName to be of type string, got %T instead", value) } sv.BranchName = ptr.String(jtv) } case "createTime": if value != nil { switch jtv := value.(type) { case json.Number: f64, err := jtv.Float64() if err != nil { return err } sv.CreateTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) default: return fmt.Errorf("expected CreateTime to be a JSON Number, got %T instead", value) } } case "description": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected Description to be of type string, got %T instead", value) } sv.Description = ptr.String(jtv) } case "updateTime": if value != nil { switch jtv := value.(type) { case json.Number: f64, err := jtv.Float64() if err != nil { return err } sv.UpdateTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) default: return fmt.Errorf("expected UpdateTime to be a JSON Number, got %T instead", value) } } case "webhookArn": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected WebhookArn to be of type string, got %T instead", value) } sv.WebhookArn = ptr.String(jtv) } case "webhookId": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected WebhookId to be of type string, got %T instead", value) } sv.WebhookId = ptr.String(jtv) } case "webhookUrl": if value != nil { jtv, ok := value.(string) if !ok { return fmt.Errorf("expected WebhookUrl to be of type string, got %T instead", value) } sv.WebhookUrl = ptr.String(jtv) } default: _, _ = key, value } } *v = sv return nil } func awsRestjson1_deserializeDocumentWebhooks(v *[]types.Webhook, value interface{}) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } if value == nil { return nil } shape, ok := value.([]interface{}) if !ok { return fmt.Errorf("unexpected JSON type %v", value) } var cv []types.Webhook if *v == nil { cv = []types.Webhook{} } else { cv = *v } for _, value := range shape { var col types.Webhook destAddr := &col if err := awsRestjson1_deserializeDocumentWebhook(&destAddr, value); err != nil { return err } col = *destAddr cv = append(cv, col) } *v = cv return nil }
}
full.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. DEPS = [ 'bot_update', 'gclient', 'gerrit', 'tryserver', 'recipe_engine/buildbucket', 'recipe_engine/json', 'recipe_engine/path', 'recipe_engine/platform', 'recipe_engine/properties', 'recipe_engine/runtime', ] from recipe_engine import types from PB.go.chromium.org.luci.buildbucket.proto.build import Build def RunSteps(api):
def GenTests(api): def try_build(**kwargs): kwargs.setdefault( 'git_repo', 'https://chromium.googlesource.com/chromium/src') return api.buildbucket.try_build('chromium/src', 'try', 'linux', **kwargs) def ci_build(**kwargs): kwargs.setdefault( 'git_repo', 'https://chromium.googlesource.com/chromium/src') return ( api.buildbucket.ci_build('chromium/src', 'ci', 'linux', **kwargs) + api.properties(patch=False) ) yield ( api.test('basic') + ci_build() ) yield ( api.test('input_commit_with_id_without_repo') + api.buildbucket.build(Build( input={ 'gitiles_commit': { 'id': 'a' * 40, }, }, )) ) yield ( api.test('unrecognized_commit_repo') + ci_build(git_repo='https://unrecognized/repo') ) yield ( api.test('basic_luci') + ci_build() + api.runtime(is_experimental=False, is_luci=True) ) yield ( api.test('with_manifest_name') + ci_build() + api.properties( manifest_name='checkout', set_output_commit=False, ) + api.step_data('bot_update (without patch)', api.json.output({ 'source_manifest': { 'directories': { 'src': { 'git_checkout': { 'repo_url': ( 'https://chromium.googlesource.com/chromium/src.git'), 'revision': 'ea17a292ecfb3dcdaa8dd226e67d6504fc13c15a' }, }, }, }, })) ) yield ( api.test('resolve_chromium_fixed_version') + ci_build() + api.properties(resolve_chromium_fixed_version=True) ) yield ( api.test('basic_with_branch_heads') + ci_build() + api.properties( with_branch_heads=True, suffix='with branch heads' ) ) yield ( api.test('with_tags') + api.properties(with_tags=True) ) yield ( api.test('deprecated_got_revision_mapping') + try_build() + api.properties( deprecated_got_revision_mapping=True, set_output_commit=False, ) ) yield ( api.test('refs') + api.properties(refs=['+refs/change/1/2/333']) ) yield ( api.test('tryjob_fail') + try_build() + api.step_data('bot_update', api.json.invalid(None), retcode=1) ) yield ( api.test('tryjob_fail_patch') + try_build() + api.properties(fail_patch='apply') + api.step_data('bot_update', retcode=88) ) yield ( api.test('tryjob_fail_patch_download') + try_build() + api.properties(fail_patch='download') + api.step_data('bot_update', retcode=87) ) yield ( api.test('clobber') + api.properties(clobber=1) ) yield ( api.test('reset_root_solution_revision') + api.properties(root_solution_revision='revision') ) yield ( api.test('gerrit_no_reset') + api.properties(gerrit_no_reset=1) ) yield ( api.test('gerrit_no_rebase_patch_ref') + api.properties(gerrit_no_rebase_patch_ref=True) ) yield ( api.test('tryjob_v8') + try_build(git_repo='https://chromium.googlesource.com/v8/v8') + api.properties(revisions={'src/v8': 'abc'}) ) yield ( api.test('tryjob_v8_head_by_default') + try_build(git_repo='https://chromium.googlesource.com/v8/v8') ) yield ( api.test('tryjob_gerrit_angle') + try_build(git_repo='https://chromium.googlesource.com/angle/angle') ) yield ( api.test('no_apply_patch_on_gclient') + try_build(git_repo='https://chromium.googlesource.com/angle/angle') ) yield ( api.test('tryjob_gerrit_v8_feature_branch') + try_build(git_repo='https://chromium.googlesource.com/v8/v8') + api.tryserver.gerrit_change_target_ref('refs/heads/experimental/feature') ) yield ( api.test('tryjob_gerrit_feature_branch') + try_build() + api.tryserver.gerrit_change_target_ref('refs/heads/experimental/feature') ) yield ( api.test('tryjob_gerrit_branch_heads') + try_build() + api.tryserver.gerrit_change_target_ref('refs/branch-heads/67') ) yield ( api.test('tryjob_gerrit_webrtc') + try_build(git_repo='https://webrtc.googlesource.com/src') ) yield ( api.test('multiple_patch_refs') + api.properties( patch_refs=[ ('https://chromium.googlesource.com/chromium/src@' 'refs/changes/12/34/5'), 'https://chromium.googlesource.com/v8/v8@refs/changes/124/45/6', ], ) ) yield ( api.test('no_cp_checkout_a_specific_commit') + ci_build(revision='a' * 40) + api.properties( revisions={'got_revision': 'src'}, bot_update_output={ 'properties': { 'got_revision': 'a' * 40, }, 'manifest': { 'src': { 'revision': 'a' * 40, 'repository': 'https://chromium.googlesource.com/chromium/src', } } } ) ) yield ( api.test('no_cp_checkout_master') + ci_build(revision='') + api.properties( revisions={'got_revision': 'src'}, bot_update_output={ 'properties': { 'got_revision': 'a' * 40, }, 'manifest': { 'src': { 'revision': 'a' * 40, 'repository': 'https://chromium.googlesource.com/chromium/src', } } } ) ) yield ( api.test('no_cp_checkout_a_branch_head') + ci_build(revision='', git_ref='refs/branch-heads/x') + api.properties( revisions={'got_revision': 'src'}, bot_update_output={ 'properties': { 'got_revision': 'a' * 40, }, 'manifest': { 'src': { 'revision': 'a' * 40, 'repository': 'https://chromium.googlesource.com/chromium/src', } } } ) ) yield ( api.test('no_cp_checkout_HEAD') + ci_build(revision='HEAD') + api.properties( revisions={'got_revision': 'src'}, bot_update_output={ 'properties': { 'got_revision': 'a' * 40, }, 'manifest': { 'src': { 'revision': 'a' * 40, 'repository': 'https://chromium.googlesource.com/chromium/src', } } } ) )
api.gclient.use_mirror = True commit = api.buildbucket.build.input.gitiles_commit src_cfg = api.gclient.make_config(CACHE_DIR='[GIT_CACHE]') soln = src_cfg.solutions.add() soln.name = 'src' soln.url = 'https://chromium.googlesource.com/chromium/src.git' soln.revision = commit.id or commit.ref or None api.gclient.c = src_cfg api.gclient.c.revisions.update(api.properties.get('revisions', {})) if api.properties.get('deprecated_got_revision_mapping'): api.gclient.c.got_revision_mapping['src'] = 'got_cr_revision' else: api.gclient.c.got_revision_reverse_mapping['got_cr_revision'] = 'src' api.gclient.c.got_revision_reverse_mapping['got_revision'] = 'src' api.gclient.c.got_revision_reverse_mapping['got_v8_revision'] = 'src/v8' api.gclient.c.got_revision_reverse_mapping['got_angle_revision'] = ( 'src/third_party/angle') api.gclient.c.repo_path_map.update({ 'https://chromium.googlesource.com/angle/angle': ( 'src/third_party/angle', 'HEAD'), 'https://chromium.googlesource.com/v8/v8': ('src/v8', 'HEAD'), 'https://webrtc.googlesource.com/src': ('src/third_party/webrtc', 'HEAD'), }) patch = api.properties.get('patch', True) clobber = True if api.properties.get('clobber') else False with_branch_heads = api.properties.get('with_branch_heads', False) with_tags = api.properties.get('with_tags', False) refs = api.properties.get('refs', []) root_solution_revision = api.properties.get('root_solution_revision') suffix = api.properties.get('suffix') gerrit_no_reset = True if api.properties.get('gerrit_no_reset') else False gerrit_no_rebase_patch_ref = bool( api.properties.get('gerrit_no_rebase_patch_ref')) manifest_name = api.properties.get('manifest_name') patch_refs = api.properties.get('patch_refs') set_output_commit = api.properties.get('set_output_commit', True) step_test_data = None bot_update_output = types.thaw(api.properties.get('bot_update_output')) if bot_update_output: step_test_data = lambda: api.json.test_api.output(bot_update_output) bot_update_step = api.bot_update.ensure_checkout( patch=patch, with_branch_heads=with_branch_heads, with_tags=with_tags, refs=refs, clobber=clobber, root_solution_revision=root_solution_revision, suffix=suffix, gerrit_no_reset=gerrit_no_reset, gerrit_no_rebase_patch_ref=gerrit_no_rebase_patch_ref, disable_syntax_validation=True, manifest_name=manifest_name, patch_refs=patch_refs, set_output_commit=set_output_commit, step_test_data=step_test_data, ) if patch: api.bot_update.deapply_patch(bot_update_step) if api.properties.get('resolve_chromium_fixed_version'): api.bot_update.resolve_fixed_revision(bot_update_step.json.output, 'src')
getHostedZoneId.ts
// *** 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! ***
/** * Use this data source to get the HostedZoneId of the AWS Elastic Load Balancing HostedZoneId * in a given region for the purpose of using in an AWS Route53 Alias. */ export function getHostedZoneId(args?: GetHostedZoneIdArgs): Promise<GetHostedZoneIdResult> { args = args || {}; return pulumi.runtime.invoke("aws:elasticloadbalancing/getHostedZoneId:getHostedZoneId", { "region": args.region, }); } /** * A collection of arguments for invoking getHostedZoneId. */ export interface GetHostedZoneIdArgs { /** * Name of the region whose AWS ELB HostedZoneId is desired. * Defaults to the region from the AWS provider configuration. */ readonly region?: pulumi.Input<string>; } /** * A collection of values returned by getHostedZoneId. */ export interface GetHostedZoneIdResult { /** * id is the provider-assigned unique ID for this managed resource. */ readonly id: string; }
import * as pulumi from "@pulumi/pulumi";
__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Backend management. Creating new backends --------------------- A new backend named 'foo-bar' corresponds to Python module 'tracetool/backend/foo_bar.py'. A backend module should provide a docstring, whose first non-empty line will be considered its short description. All backends must generate their contents through the 'tracetool.out' routine. Backend attributes ------------------ ========= ==================================================================== Attribute Description ========= ==================================================================== PUBLIC If exists and is set to 'True', the backend is considered "public". ========= ==================================================================== Backend functions ----------------- All the following functions are optional, and no output will be generated if they do not exist. =============================== ============================================== Function Description =============================== ============================================== generate_<format>_begin(events) Generate backend- and format-specific file header contents. generate_<format>_end(events) Generate backend- and format-specific file footer contents. generate_<format>(event) Generate backend- and format-specific contents for the given event. =============================== ============================================== """ __author__ = "Lluís Vilanova <[email protected]>" __copyright__ = "Copyright 2012-2014, Lluís Vilanova <[email protected]>" __license__ = "GPL version 2 or (at your option) any later version" __maintainer__ = "Stefan Hajnoczi" __email__ = "[email protected]" import os import tracetool def get_list(only_public = False): """Get a list of (name, description) pairs.""" res = [("nop", "Tracing disabled.")] modnames = [] for filename in os.listdir(tracetool.backend.__path__[0]): if filename.endswith('.py') and filename != '__init__.py': modnames.append(filename.rsplit('.', 1)[0]) for modname in sorted(modnames): module = tracetool.try_import("tracetool.backend." + modname) # just in case; should never fail unless non-module files are put there if not module[0]: continue module = module[1] public = getattr(module, "PUBLIC", False) if only_public and not public: continue doc = module.__doc__ if doc is None: doc = "" doc = doc.strip().split("\n")[0] name = modname.replace("_", "-") res.append((name, doc)) return res def exists(name): """Return whether the given backend exists.""" if len(name) == 0: return False if name == "nop": return True name = name.replace("-", "_") return tracetool.try_import("tracetool.backend." + name)[1] class Wrapper: def __init__(self, backends, format): self._backends = [backend.replace("-", "_") for backend in backends] self._format = format.replace("-", "_") for backend in self._backends: assert exists(backend) assert tracetool.format.exists(self._format) def _run_function(self, name, *args, **kwargs): for backend in self._backends: func = tracetool.try_import("tracetool.backend." + backend, name % self._format, None)[1] if func is not None: func(*args, **kwargs) def ge
elf, events, group): self._run_function("generate_%s_begin", events, group) def generate(self, event, group): self._run_function("generate_%s", event, group) def generate_end(self, events, group): self._run_function("generate_%s_end", events, group)
nerate_begin(s
TOU.py
from enum import Enum from datetime import datetime, date from dateutil.relativedelta import relativedelta, MO import argparse import holidays import pandas as pd class BGEHolidays(holidays.HolidayBase): def _populate(self, year): holidays.UnitedStates._populate(self, year) # Remove Martin Luther King Day self.pop(date(year, 1, 1) + relativedelta(weekday=MO(+3)), None) # Remove Columbus Day self.pop(date(year, 10, 1) + relativedelta(weekday=MO(+2)), None) # Remove Veterans Day self.pop(date(year, 11, 11), None) # Add good friday self[holidays.easter(year) + relativedelta(days=-2)] = 'Good Friday' class TimeOfUse(Enum): peak = 0 shoulder = 1 offpeak = 2 class Season(Enum): Winter = 0 Summer = 1 @classmethod def get(cls, dt): d = dt.date() if date(dt.year, 6, 1) <= d and date(dt.year, 9, 30) >= d: return cls.Summer return cls.Winter class Schedule(Enum): R = 'R' RL = 'RL' EV = 'EV' EVP = 'EVP' def getTOU(self, dt): d = dt.date() t = dt.time() bge_holidays = BGEHolidays(dt.year) if self == self.R: return TimeOfUse.offpeak elif self == self.RL: if Season.get(dt) == Season.Summer: if (t.hour >=10 and t.hour < 20) and \ (dt.weekday() < 5) and \ (d not in bge_holidays): return TimeOfUse.peak elif ((t.hour >= 7 and t.hour < 10) or (t.hour >= 20 and t.hour < 23)) and \ (dt.weekday() < 5) and \ (d not in bge_holidays): return TimeOfUse.shoulder else: return TimeOfUse.offpeak else: if ((t.hour >= 7 and t.hour < 11) or (t.hour >= 17 and t.hour < 21)) and \ (dt.weekday() < 5) and \
elif (t.hour >= 11 and t.hour < 17) and \ (dt.weekday() < 5) and \ (d not in bge_holidays): return TimeOfUse.shoulder else: return TimeOfUse.offpeak elif self in (self.EV, self.EVP): if Season.get(dt) == Season.Summer: if (t.hour >= 10 and t.hour < 20) and \ (dt.weekday() < 5) and \ (d not in bge_holidays): return TimeOfUse.peak else: return TimeOfUse.offpeak else: if ((t.hour >= 7 and t.hour < 11) or (t.hour >= 17 and t.hour < 21)) and \ (dt.weekday() < 5) and \ (d not in bge_holidays): return TimeOfUse.peak else: return TimeOfUse.offpeak rates = { (Schedule.R, Season.Summer, TimeOfUse.offpeak): .06722, (Schedule.R, Season.Winter, TimeOfUse.offpeak): .07805, (Schedule.RL, Season.Summer, TimeOfUse.peak): .08465, (Schedule.RL, Season.Summer, TimeOfUse.shoulder): .06069, (Schedule.RL, Season.Summer, TimeOfUse.offpeak): .05744, (Schedule.RL, Season.Winter, TimeOfUse.peak): .09053, (Schedule.RL, Season.Winter, TimeOfUse.shoulder): .07944, (Schedule.RL, Season.Winter, TimeOfUse.offpeak): .07166, (Schedule.EV, Season.Summer, TimeOfUse.peak): .1227, (Schedule.EV, Season.Summer, TimeOfUse.offpeak): .03886, (Schedule.EV, Season.Winter, TimeOfUse.peak): .18474, (Schedule.EV, Season.Winter, TimeOfUse.offpeak): .0426, (Schedule.EVP, Season.Summer, TimeOfUse.peak): .03886, (Schedule.EVP, Season.Summer, TimeOfUse.offpeak): .03886, (Schedule.EVP, Season.Winter, TimeOfUse.peak): .0426, (Schedule.EVP, Season.Winter, TimeOfUse.offpeak): .0426 } def get_rate(dt, schedule = Schedule.R): bge_holidays = BGEHolidays(dt.year) season = Season.get(dt) tou = schedule.getTOU(dt) return rates[(schedule, season, tou)] def process_row(x): dt = x['DATE_START TIME'] val = x['USAGE'] return pd.Series([dt] + [get_rate(dt, x) * (val + .0700) for x in Schedule], index=['DATE_START TIME'] + [x.value for x in Schedule]) def main(): parser = argparse.ArgumentParser() parser.add_argument('input_file', type=argparse.FileType('r')) args = parser.parse_args() df = pd.read_csv(args.input_file, parse_dates=[['DATE', 'START TIME']])[['DATE_START TIME', 'USAGE']] schedules = df.apply(process_row, axis=1) print(schedules[['R', 'RL', 'EV', 'EVP']].sum()) if __name__ == '__main__': main()
(d not in bge_holidays): return TimeOfUse.peak
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2019-01-04 08:34 from __future__ import unicode_literals import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion class
(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('courses', '0001_initial'), ] operations = [ migrations.CreateModel( name='CourseComments', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('comments', models.CharField(max_length=200, verbose_name='评论')), ('add_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')), ('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='courses.Course', verbose_name='课程')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='用户')), ], options={ 'verbose_name': '课程评论', 'verbose_name_plural': '课程评论', }, ), migrations.CreateModel( name='UserAsk', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=20, verbose_name='姓名')), ('mobile', models.CharField(max_length=11, verbose_name='手机')), ('course_name', models.CharField(max_length=50, verbose_name='课程名')), ('add_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')), ], options={ 'verbose_name': '用户咨询', 'verbose_name_plural': '用户咨询', }, ), migrations.CreateModel( name='UserCourse', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('add_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')), ('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='courses.Course', verbose_name='课程')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='用户')), ], options={ 'verbose_name': '用户课程', 'verbose_name_plural': '用户课程', }, ), migrations.CreateModel( name='UserFavorite', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('fav_id', models.IntegerField(default=0, verbose_name='数据id')), ('fav_type', models.IntegerField(choices=[(1, '课程'), (2, '课程机构'), (3, '讲师')], default=1, verbose_name='收藏类型')), ('add_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='用户')), ], options={ 'verbose_name': '用户收藏', 'verbose_name_plural': '用户收藏', }, ), migrations.CreateModel( name='UserMessage', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('user', models.IntegerField(default=0, verbose_name='接收用户')), ('message', models.CharField(max_length=500, verbose_name='消息内容')), ('has_read', models.BooleanField(default=False, verbose_name='是否已读')), ('add_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')), ], options={ 'verbose_name': '用户消息', 'verbose_name_plural': '用户消息', }, ), ]
Migration
Dropdown.d.ts
import * as React from 'react'; import { DropdownListProps, SelectAll, Selected, ChangeEvent } from "./DropdownList"; import { OptionSchema as Option } from "./option"; import { BaseProps } from "../../../utils/types"; declare type fetchOptionsFunction = (searchTerm: string) => Promise<{ searchTerm?: string; count: number; options: Option[]; }>; export declare type EventType = 'select-option' | 'deselect-option' | 'select-all' | 'deselect-all' | 'clear-all' | 'apply-selected' | 'cancel-selected'; interface ControlledProps { selected?: Option[]; onUpdate?: (type: EventType, options?: Option | Option[], recentSelected?: Option[]) => void; } interface SyncProps { options: Option[]; loading?: boolean; } interface AsyncProps { fetchOptions?: fetchOptionsFunction; } interface TriggerProps { labelLimit?: number; customLabel?: (selected: number, totalOptions?: number, selectedOptions?: Option[]) => string; customTrigger?: (label: string) => React.ReactElement; } interface SharedDropdownProps extends DropdownListProps, BaseProps { name?: string | number; totalOptions?: number; closeOnSelect: boolean; triggerOptions: TriggerProps; open?: boolean; staticLimit: number; searchDebounceDuration: number; onPopperToggle?: (open: boolean, type?: string) => void; getLabel?: (label: string) => void; onChange?: (selected: any[] | any, name?: string | number) => void; onClose?: (selected: any[], name?: string | number) => void; } declare type SyncDropdownProps = SyncProps & SharedDropdownProps; declare type AsyncDropdownProps = AsyncProps & SharedDropdownProps; export declare type UncontrolledDropdownProps = (SyncDropdownProps & AsyncDropdownProps); export declare type ControlledDropdownProps = (ControlledProps & SyncDropdownProps & AsyncDropdownProps); export declare type DropdownProps = (ControlledDropdownProps & UncontrolledDropdownProps); interface DropdownState { async: boolean; searchInit: boolean; options: Option[]; loading?: boolean; optionsApplied: boolean; open?: boolean; searchTerm: string; optionsLength: number; searchedOptionsLength: number; triggerLabel: string; selectAll: SelectAll; selected: Option[]; tempSelected: Option[]; previousSelected: Option[]; } export declare class Dropdown extends React.Component<DropdownProps, DropdownState> { staticLimit: number; static defaultProps: { triggerOptions: {}; options: never[]; closeOnSelect: boolean; staticLimit: number; searchDebounceDuration: number; }; constructor(props: DropdownProps); componentDidMount(): void; componentDidUpdate(prevProps: DropdownProps, prevState: DropdownState): void; getDisabledOptions: (options?: Option[]) => Option[]; fetchOptionsFunction: (searchTerm: string) => Promise<any>; getUnSelectedOptions: (options: Option[], init: boolean) => Option[]; getSelectedOptions: (options: Option[], init: boolean) => Option[]; updateOptions: (init: boolean, async?: boolean | undefined) => void; updateSearchTerm: (search: string) => void; updateOnPopperToggle: () => void;
onSelectAll: (event: ChangeEvent) => void; debounceSearch: import("throttle-debounce").throttle<() => void>; debounceClear: import("throttle-debounce").throttle<() => void>; onClearOptions: () => void; onTogglePopper: (type: string) => void; onCancelOptions: () => void; onApplyOptions: () => void; onToggleDropdown: (updatedOpen: boolean, type?: string | undefined) => void; render(): JSX.Element; } export default Dropdown;
updateTriggerLabel: (selectedArray?: Selected[], totalOptions?: number | undefined) => string; updateSelectedOptions: (selectedArray: Option[], isSingleSelect: boolean, isControlled?: boolean | undefined) => void; onOptionSelect: (option: Option) => void; onSelect: (option: Option, checked: boolean) => void;
two_windows.rs
use bevy::{ core_pipeline::{draw_3d_graph, node, AlphaMask3d, Opaque3d, Transparent3d}, prelude::*, render::{ camera::{ActiveCameras, ExtractedCameraNames}, render_graph::{Node, NodeRunError, RenderGraph, RenderGraphContext, SlotValue}, render_phase::RenderPhase, renderer::RenderContext, RenderApp, RenderStage, }, window::{CreateWindow, WindowId}, }; use bevy_egui::{EguiContext, EguiPlugin}; use once_cell::sync::Lazy; static SECOND_WINDOW_ID: Lazy<WindowId> = Lazy::new(WindowId::new); const BEVY_TEXTURE_ID: u64 = 0;
app.add_plugins(DefaultPlugins) .add_plugin(EguiPlugin) .init_resource::<SharedUiState>() .add_startup_system(load_assets) .add_startup_system(create_new_window) .add_system(ui_first_window) .add_system(ui_second_window); let render_app = app.sub_app_mut(RenderApp); render_app.add_system_to_stage(RenderStage::Extract, extract_secondary_camera_phases); let mut graph = render_app.world.get_resource_mut::<RenderGraph>().unwrap(); graph.add_node(SECONDARY_PASS_DRIVER, SecondaryCameraDriver); graph .add_node_edge(node::MAIN_PASS_DEPENDENCIES, SECONDARY_PASS_DRIVER) .unwrap(); bevy_egui::setup_pipeline( &mut graph, bevy_egui::RenderGraphConfig { window_id: *SECOND_WINDOW_ID, egui_pass: SECONDARY_EGUI_PASS, }, ); app.run(); } fn extract_secondary_camera_phases(mut commands: Commands, active_cameras: Res<ActiveCameras>) { if let Some(secondary) = active_cameras.get(SECONDARY_CAMERA_NAME) { if let Some(entity) = secondary.entity { commands.get_or_spawn(entity).insert_bundle(( RenderPhase::<Opaque3d>::default(), RenderPhase::<AlphaMask3d>::default(), RenderPhase::<Transparent3d>::default(), )); } } } const SECONDARY_CAMERA_NAME: &str = "Secondary"; const SECONDARY_PASS_DRIVER: &str = "secondary_pass_driver"; const SECONDARY_EGUI_PASS: &str = "secondary_egui_pass"; fn create_new_window( mut create_window_events: EventWriter<CreateWindow>, mut commands: Commands, mut active_cameras: ResMut<ActiveCameras>, ) { // sends out a "CreateWindow" event, which will be received by the windowing backend create_window_events.send(CreateWindow { id: *SECOND_WINDOW_ID, descriptor: WindowDescriptor { width: 800., height: 600., vsync: false, title: "Second window".to_string(), ..Default::default() }, }); // second window camera commands.spawn_bundle(PerspectiveCameraBundle { camera: Camera { window: *SECOND_WINDOW_ID, name: Some(SECONDARY_CAMERA_NAME.into()), ..Default::default() }, transform: Transform::from_xyz(6.0, 0.0, 0.0).looking_at(Vec3::ZERO, Vec3::Y), ..Default::default() }); active_cameras.add(SECONDARY_CAMERA_NAME); } fn load_assets(mut egui_context: ResMut<EguiContext>, assets: Res<AssetServer>) { let texture_handle = assets.load("icon.png"); egui_context.set_egui_texture(BEVY_TEXTURE_ID, texture_handle); } struct SecondaryCameraDriver; impl Node for SecondaryCameraDriver { fn run( &self, graph: &mut RenderGraphContext, _render_context: &mut RenderContext, world: &World, ) -> Result<(), NodeRunError> { let extracted_cameras = world.get_resource::<ExtractedCameraNames>().unwrap(); if let Some(camera_3d) = extracted_cameras.entities.get(SECONDARY_CAMERA_NAME) { graph.run_sub_graph( crate::draw_3d_graph::NAME, vec![SlotValue::Entity(*camera_3d)], )?; } Ok(()) } } #[derive(Default)] struct UiState { input: String, } #[derive(Default)] struct SharedUiState { shared_input: String, } fn ui_first_window( egui_context: Res<EguiContext>, mut ui_state: Local<UiState>, mut shared_ui_state: ResMut<SharedUiState>, ) { egui::Window::new("First Window") .vscroll(true) .show(egui_context.ctx(), |ui| { ui.horizontal(|ui| { ui.label("Write something: "); ui.text_edit_singleline(&mut ui_state.input); }); ui.horizontal(|ui| { ui.label("Shared input: "); ui.text_edit_singleline(&mut shared_ui_state.shared_input); }); ui.add(egui::widgets::Image::new( egui::TextureId::User(BEVY_TEXTURE_ID), [256.0, 256.0], )); }); } fn ui_second_window( egui_context: Res<EguiContext>, mut ui_state: Local<UiState>, mut shared_ui_state: ResMut<SharedUiState>, ) { let ctx = match egui_context.try_ctx_for_window(*SECOND_WINDOW_ID) { Some(ctx) => ctx, None => return, }; egui::Window::new("Second Window") .vscroll(true) .show(ctx, |ui| { ui.horizontal(|ui| { ui.label("Write something else: "); ui.text_edit_singleline(&mut ui_state.input); }); ui.horizontal(|ui| { ui.label("Shared input: "); ui.text_edit_singleline(&mut shared_ui_state.shared_input); }); ui.add(egui::widgets::Image::new( egui::TextureId::User(BEVY_TEXTURE_ID), [256.0, 256.0], )); }); }
fn main() { let mut app = App::new();
coordinates.rs
// Copyright © 2020 Delhi Durai and Rajeswari // [This program is licensed under the "MIT License"] // Please see the file LICENSE in the source // distribution of this software for license terms. /// /// Structs and Functions that are commonly used across multiple module will reside in this /// library /// extern crate ansi_term; extern crate serde; extern crate serde_derive; extern crate serde_json; use self::serde_derive::Deserialize; //use std::time::Instant; //use std::time::Duration; ///Types of Shapes handled in this programm #[derive(Debug, Copy, Clone)] pub enum Shape { Polygon, Circle, Triangle, } pub enum Colour { Red, Blue, Yellow, Purple, Black, } #[derive(Deserialize, Debug, Clone)] pub struct Coordinates { pub lat: f64, pub lon: f64, } impl Coordinates { pub fn new(lat: f64, lon: f64) -> Coordinates { Coordinates { lat, lon } } pub fn display(self) { println!( "Coordinates Latitude {} and Longitude {} ", self.lat, self.lon ); } } #[derive(Deserialize, Debug)] pub struct CircleCoordinates { pub lat: f64, pub lon: f64, pub rad: f64, } impl CircleCoordinates { pub fn new(lat: f64, lon: f64, rad: f64) -> CircleCoordinates { CircleCoordinates { lat, lon, rad } } pub fn display(self) { println!( "Circle Coordinates Latitude {} , Longitude {} and Radius {} ", self.lat, self.lon, self.rad ); } } #[derive(Deserialize, Debug)] pub struct MovingTracker { pub _comment: String, pub vehicle: String, pub shape: String, pub shape_coordinate: Vec<Coordinates>, pub moving_coordinate: Vec<Coordinates>, } #[derive(Deserialize, Debug)] pub struct MovingTrackerCircle { pub _comment: String, pub vehicle: String, pub shape: String, pub shape_coordinate: CircleCoordinates, pub moving_coordinate: Vec<Coordinates>, } pub fn display_underline(str: &str, colour: Colour) { match colour { Colour::Red => println!("{}", ansi_term::Colour::Red.bold().underline().paint(str)), Colour::Yellow => println!( "{}", ansi_term::Colour::Yellow.bold().underline().paint(str) ), Colour::Blue => println!("{}", ansi_term::Colour::Blue.bold().underline().paint(str)), Colour::Purple => println!( "{}", ansi_term::Colour::Purple.bold().underline().paint(str) ), Colour::Black => println!("{}", ansi_term::Colour::Black.bold().underline().paint(str)), } } pub fn display_bold(str: &str, colour: Colour) { match colour { Colour::Red => println!("{}", ansi_term::Colour::Red.bold().paint(str)), Colour::Yellow => println!("{}", ansi_term::Colour::Yellow.bold().paint(str)), Colour::Blue => println!("{}", ansi_term::Colour::Blue.bold().paint(str)), Colour::Purple => println!("{}", ansi_term::Colour::Purple.bold().paint(str)), Colour::Black => println!("{}", ansi_term::Colour::Black.bold().paint(str)), } } pub fn display(str: &str, colour: Colour) {
//pub fn get_current_time()->Instant{ // Instant::now() //} //pub fn calculate_run_time(instant:&Instant)->Duration{ // instant.elapsed() //}
match colour { Colour::Red => println!("{}", ansi_term::Colour::Red.paint(str)), Colour::Yellow => println!("{}", ansi_term::Colour::Yellow.paint(str)), Colour::Blue => println!("{}", ansi_term::Colour::Blue.paint(str)), Colour::Purple => println!("{}", ansi_term::Colour::Purple.paint(str)), Colour::Black => println!("{}", str), } }
application.pda.editZp.js
/** * @class application.editZp * Singleton to build the editZp window * * @singleton */ application.editZp = function() { // private variables /** * Property: map * {OpenLayers.Map} */ var map = null; /** * Property: toolbar * {mapfish.widgets.ToolBar} */ var toolbar = null; /**
* {Boolean} toolbar has already been initialized */ var toolbarInitializedOnce = false; /** * Property: vectorLayer * {OpenLayers.Layer.Vector} */ var vectorLayer = null; /** * Property: dragPanControl */ var dragPanControl = null; /** * Property: drawPolygonControl */ var drawPolygonControl = null; /** * Property: dragPolygonControl */ var dragPolygonControl = null; /** * Property: modifyFeatureControl */ var modifyFeatureControl = null; /** * Property: store * {Ext.data.Store} The zp store (should contain only one record) */ var store = null; /** * Property: protocol * {mapfish.Protocol.MapFish} */ var protocol = null /** * Property: eventProtocol * {mapfish.Protocol.TriggerEventDecorator} */ var eventProtocol = null; /** * Property: filterProtocol * {mapfish.Protocol.MergeFilterDecorator} */ var filterProtocol = null; /** * Property: format * {<OpenLayers.Format.WKT>} */ var format = new OpenLayers.Format.WKT(); /** * APIProperty: id_zp * The id of zp to update (if applies), null in case of a creating a new zp */ var indexzp = null; /** * Property: layerTreeTip * {Ext.Tip} The layerTreeTip created with the factory */ var layerTreeTip = null; /** * Property: firstGeometryLoad * {Boolean} is the geometry has been load once only */ var firstGeometryLoad = true; // private functions /** * Method: initViewport */ var initWindow = function() { return new Ext.Window({ title: "Modifier une zone de prospection" ,layout: 'border' ,modal: true ,plain: true ,plugins: [new Ext.ux.plugins.ProportionalWindows()] //,aspect: true ,width: 600 ,height: 250 ,percentage: .95 ,split: true ,closeAction: 'hide' ,defaults: { border: false } // ,bbar: new Ext.StatusBar({ // id: 'edit-zp-status' // ,defaultText: '' // }) ,items: [ getWindowCenterItem() ,getViewportEastItem() ] ,listeners: { show: initToolbarItems ,hide: resetWindow ,afterlayout: function(){ map.baseLayer.redraw(); } } }); }; /** * Method: getViewportNorthItem */ var getViewportEastItem = function() { return { region: 'east' ,width: 300 ,split: true ,autoScroll: true ,defaults: { border: false } ,items: [{ id: 'edit-zp-form' ,xtype: 'form' ,bodyStyle: 'padding: 5px' ,disabled: true ,defaults: { xtype: 'textfield' ,width: 180 } ,labelAlign: 'top' ,items: getFormItems() //pour version Extjs 3.3.1 ,buttons:[{ text: 'Annuler' ,xtype: 'button' ,handler: function() { application.editZp.window.hide(); } ,scope: this },{ text: 'Enregistrer' ,xtype: 'button' ,id: 'zpSaveButton' ,iconCls: 'action-save' ,handler: submitForm }] }] } }; /** * Method: getViewportCenterItem */ var getWindowCenterItem = function() { createMap(); toolbar = new mapfish.widgets.toolbar.Toolbar({ map: map, configurable: false }); return { region: 'center' ,id: 'edit-zp-mapcomponent' ,xtype: 'mapcomponent' ,map: map ,tbar: toolbar }; }; /** * Method: getFormItems * Creates the form items */ var getFormItems = function() { var comboObservateursZP = new Ext.ux.form.SuperBoxSelect({ id:'combo-zp-observateurs' ,xtype:'superboxselect' ,fieldLabel: 'Observateur(s) ' ,emptyText: 'Sélectionnez un ou plusieurs observateurs' ,allowBlank: false ,blankText: 'Choisir au moins un observateur est obligatoire' ,resizable: true ,name: 'lesobservateurs' ,store: application.auteursStore ,mode: 'local' ,displayField: 'auteur' ,valueField: 'id_role' ,forceSelection : true ,selectOnFocus:true ,value:'' ,anchor:'95%' ,listeners:{ afterrender :function(){ Ext.getCmp('edit-zp-form').getForm().findField('ids_observateurs').setValue(this.getValue()); } ,change:function(){ Ext.getCmp('edit-zp-form').getForm().findField('ids_observateurs').setValue(this.getValue()); // Ext.getCmp('combo-zp-taxon').focus();//ne fonctionne pas } ,render: function(c) { Ext.QuickTips.register({ target: c.getEl(), text: 'Le ou les auteurs de la prospection.' }); } } }); return [{ xtype:'label' ,html: 'Prospection du ' ,id: 'label-dateobs' },comboObservateursZP ,{ fieldLabel: 'Taxon (ne modifier que si nécessaire) ' ,id:'combo-zp-taxon' ,name: 'taxon' ,xtype:"combo" ,hiddenName:"cd_nom" ,store: application.taxonsLStore ,valueField: "cd_nom" ,displayField: "latin" ,typeAhead: true ,typeAheadDelay:750 ,forceSelection: true ,selectOnFocus: true ,triggerAction: 'all' ,mode: 'local' ,listeners:{ afterrender :function(){ Ext.getCmp('edit-zp-form').getForm().findField('taxon_saisi').setValue(this.getValue()); } ,select:function(){ Ext.getCmp('edit-zp-form').getForm().findField('taxon_saisi').setValue(this.getRawValue()); // Ext.getCmp('combo-zp-taxon').focus();//ne fonctionne pas } ,change:function(){ Ext.getCmp('edit-zp-form').getForm().findField('taxon_saisi').setValue(this.getRawValue()); } ,render: function(c) { Ext.QuickTips.register({ target: c.getEl(), text: 'Le taxon recherché lors de la prospection.' }); } } },{ id:'datefield-zp-date' ,fieldLabel: 'Date ' ,name: 'dateobs' ,xtype:'datefield' ,maxValue: new Date() ,format: 'd/m/Y' ,altFormats:'Y-m-d' ,allowBlank: false ,blankText:'La date de la prospection est obligatoire' ,listeners: { render: function(c) { Ext.QuickTips.register({ target: c.getEl(), text: 'Date de réalisation de la prospection. Elle ne peut donc être postérieure à la date de saisie.' }); } } },{ fieldLabel: 'Organisme producteur ' ,id:'combo-zp-organisme' ,name: 'organisme' ,xtype:"combo" ,hiddenName:"id_organisme" ,store: application.organismeStore ,valueField: "id_organisme" ,displayField: "nom_organisme" ,typeAhead: true ,typeAheadDelay:750 ,forceSelection: true ,selectOnFocus: true ,triggerAction: 'all' ,mode: 'local' ,listeners:{ render: function(c) { Ext.QuickTips.register({ target: c.getEl(), text: 'L\'organisme producteur de la donnée. Seuls les utilisateurs de cet organisme pourront exporter cette donnée.' }); } } },{ name: 'geometry' ,xtype: 'hidden' },{ name: 'ids_observateurs' ,xtype: 'hidden' },{ name: 'taxon_saisi' ,xtype: 'hidden' }]; }; /** * Method: createLayer * Creates the vector layer * * Return * <OpenLayers.Layer.Vector> */ var createLayer = function() { vectorLayer = new OpenLayers.Layer.Vector("editZp vector layer" ,{ protocol: eventProtocol ,strategies: [ new mapfish.Strategy.ProtocolListener() ] ,format: OpenLayers.Format.GeoJSON } ); vectorLayer.events.on({ featureadded: function(obj) { var feature = obj.feature; if (this.indexzp==null) { activateControls(false); } else { deactivateAllEditingControls(); } updateGeometryField(feature); //modifyFeatureControl.selectControl.select(feature); //modifyFeatureControl.selectControl.handlers.feature.feature = feature; Ext.getCmp('edit-zp-form').enable(); Ext.getCmp('edit-zp-form').ownerCt.ownerCt.doLayout(); } ,featuremodified: function(obj) { updateGeometryField(obj.feature); } ,featureremoved: function(obj) { updateGeometryField(null); Ext.getCmp('edit-zp-form').disable(); } }); }; /** * Method: createMap * Creates the map * * Return * <OpenLayers.Map> */ var createMap = function() { map = application.createMap(); createLayer(); map.addLayers([vectorLayer]); map.zoomToMaxExtent(); }; /** * Method: initToolbarItems * Creates the map toolbar */ var initToolbarItems = function() { if (!toolbarInitializedOnce) { toolbar.addControl( new OpenLayers.Control.ZoomToMaxExtent({ map: map, title: 'Revenir à l\'échelle maximale' }), { iconCls: 'zoomfull', toggleGroup: this.id } ); application.utils.addSeparator(toolbar); toolbar.addControl( new OpenLayers.Control.ZoomBox({ title: 'Zoomer' }), { iconCls: 'zoomin', toggleGroup: this.id } ); toolbar.addControl( new OpenLayers.Control.ZoomBox({ out: true, title: 'Dézoomer' }), { iconCls: 'zoomout', toggleGroup: this.id } ); toolbar.addControl( dragPanControl = new OpenLayers.Control.DragPan({ isDefault: true, title: 'Déplacer la carte' }), { iconCls: 'pan', toggleGroup: this.id } ); application.utils.addSeparator(toolbar); toolbar.addControl( drawPolygonControl = new OpenLayers.Control.DrawFeature(vectorLayer, OpenLayers.Handler.Polygon, { title: 'Dessiner un polygone' }), { iconCls: 'drawpolygon' ,toggleGroup: this.id ,disabled: true } ); toolbar.addControl( dragPolygonControl = new OpenLayers.Control.DragFeature(vectorLayer, { title: 'Déplacer une l\'aire de présence' ,onComplete:function(feature) { updateGeometryField(feature); } }), { iconCls: 'dragpolygon' ,toggleGroup: this.id ,disabled: true } ); toolbar.addControl( modifyFeatureControl = new OpenLayers.Control.ModifyFeature(vectorLayer, { title: 'Modifier la géométrie' }), { iconCls: 'modifyfeature' ,toggleGroup: this.id } ); application.utils.addSeparator(toolbar); toolbar.add({ text: 'Effacer la géométrie' ,id: 'edit-zp-geometry-erase' //,disabled: true ,iconCls: 'erase' ,qtip: 'Permet de supprimer la géométrie pour en créer une nouvelle' ,handler: function() { Ext.Msg.confirm('Attention' ,'Cela supprimera définitivement la géométrie dessinée avec le pda !<br />Confirmer ?' ,function(btn) { if (btn == 'yes') { activateControls(true); vectorLayer.removeFeatures(vectorLayer.features[0]); } } ) } }); application.utils.addSeparator(toolbar); toolbar.add({ text: 'GPX' ,id: 'edit-zp-gpx' //,disabled: true ,iconCls: 'gpx' ,qtip: 'Importer un fichier gpx comme aide à la numérisation de la zone de prospection' ,handler: function() { application.editZp.addGpx(); } }); layerTreeTip = application.createLayerWindow(map); layerTreeTip.render(Ext.getCmp('edit-zp-mapcomponent').body); layerTreeTip.show(); layerTreeTip.getEl().alignTo( Ext.getCmp('edit-zp-mapcomponent').body, "tl-tl", [5, 5] ); layerTreeTip.hide(); application.utils.addSeparator(toolbar); toolbar.add({ iconCls: 'legend' ,enableToggle: true ,tooltip: 'Gérer les couches affichées' ,handler: function(button) { showLayerTreeTip(button.pressed); } }); toolbar.activate(); toolbarInitializedOnce = true; // Ext.getCmp('edit-zp-status').add({ // text: 'Annuler' // ,xtype: 'button' // ,handler: function() { // application.editZp.window.hide(); // } // ,scope: this // },{ // text: 'Enregistrer' // ,xtype: 'button' // ,id: 'zpSaveButton' // ,iconCls: 'action-save' // ,handler: submitForm // }); } else{ Ext.getCmp('zpSaveButton').enable();} }; /** * Method: activateControls * Allows to activate / enable / deactivate / disable the draw and modify feature controls * * Parameters: * activateDrawControls - {Boolean} true to activate / enable the draw controls */ var activateControls = function(activateDrawControls) { Ext.getCmp('edit-zp-geometry-erase').setDisabled(false); toolbar.getButtonForControl(modifyFeatureControl).setDisabled(activateDrawControls); toolbar.getButtonForControl(dragPolygonControl).setDisabled(activateDrawControls); if (activateDrawControls) { dragPolygonControl.deactivate(); modifyFeatureControl.deactivate(); } else { dragPolygonControl.activate(); modifyFeatureControl.activate(); } Ext.each([drawPolygonControl] ,function(control) { toolbar.getButtonForControl(control).setDisabled(!activateDrawControls); if (!activateDrawControls) { control.deactivate(); } } ); }; /** * Method: deactivateAllEditingControls */ var deactivateAllEditingControls = function() { Ext.getCmp('edit-zp-geometry-erase').setDisabled(true); toolbar.getButtonForControl(modifyFeatureControl).setDisabled(true); modifyFeatureControl.deactivate(); toolbar.getButtonForControl(drawPolygonControl).setDisabled(true); drawPolygonControl.deactivate(); toolbar.getButtonForControl(dragPolygonControl).setDisabled(true); dragPolygonControl.deactivate(); }; /** * Method: updateGeometryField * Updates the geometry field (hidden) in the form * * Parameters: * geometry - {null|<OpenLayers.Geometry>} Geometry */ var updateGeometryField = function(geometry) { if (geometry == null) {wkt = '';} else {var wkt = format.write(geometry);} Ext.getCmp('edit-zp-form').getForm().findField('geometry').setValue(wkt); firstGeometryLoad = false; }; /** * Method: createProtocol * Create the search protocol. */ var createProtocol = function() { protocol = new mapfish.Protocol.MapFish({}); eventProtocol = new mapfish.Protocol.TriggerEventDecorator({ protocol: protocol ,eventListeners: { crudtriggered: function() { //zpsListGrid.loadMask.show(); } ,crudfinished: function(response) { var feature = response.features[0]; Ext.getCmp('label-dateobs').setText('<p class="bluetext">Prospection du '+feature.data.dateobs+'</p><p class="bluetext">Taxon : '+feature.data.taxon_latin+'</p><br/>',false); // Ext.getCmp('hidden-id_secteur_fp').setValue(feature.data.id_secteur_fp); Ext.getCmp('edit-zp-form').getForm().loadRecord(feature); //on limit le zoom à 9 var zoomLevel = map.getZoomForExtent(feature.geometry.getBounds()); var centerGeom = feature.geometry.getBounds().getCenterLonLat(); if (zoomLevel > 9){zoomLevel = 9;} map.setCenter(centerGeom,zoomLevel); //map.zoomToExtent(feature.geometry.getBounds()); Ext.getCmp('edit-zp-form').enable(); } } }); }; /** * Method: createStore * Create the search result store. */ var createStore = function() { store = new Ext.data.Store({ reader: new mapfish.widgets.data.FeatureReader({}, [ 'indexzp' ,'ids_observateurs' ,'observateurs' ,{name:'dateobs', type: 'date', dateFormat:'d/m/Y'} ,'taxon_latin' ,'taxon_saisi' ,'id_organisme' ,'cd_nom' ]) ,listeners: { load: function(store, records) { Ext.getCmp('edit-zp-form').getForm().loadRecord(records[0]); } } }); }; /** * Method: resetWindow * Reset the different items status (on close) for next usage */ var resetWindow = function() { indexzp = null; map.zoomToMaxExtent(); vectorLayer.removeFeatures(vectorLayer.features); Ext.getCmp('edit-zp-form').disable(); Ext.getCmp('edit-zp-form').getForm().reset(); dragPanControl.activate(); if(Ext.getCmp('zp_count').text=="les 50 dernières prospections"){ Ext.getCmp('hidden-start').setValue('yes') application.search.refreshZps(); } }; /** * Method: submitForm * Submits the form */ var submitForm = function() { Ext.getCmp('zpSaveButton').setText('Enregistrement en cours...'); Ext.getCmp('zpSaveButton').disable(); var params = {}; if (indexzp) { params.indexzp = indexzp; params.monaction = "update"; } else{ params.monaction = "add"; params.id_organisme = application.user.id_organisme; } Ext.getCmp('edit-zp-form').getForm().submit({ url: 'zp/save' ,params: params ,success: function(form, action) { application.search.refreshZps(); if (indexzp) { var index = 'zp-' + indexzp; Ext.getCmp(index).refreshZp(); Ext.getCmp('zpSaveButton').setText('Enregistrer'); Ext.getCmp('zpSaveButton').enable(); application.editZp.window.hide(); } else{ indexzp = action.result.indexzp; application.editZp.initNewAp(indexzp); } } ,failure: function(form, action) { Ext.getCmp('zpSaveButton').setText('Enregistrer'); Ext.getCmp('zpSaveButton').enable(); var msg; switch (action.failureType) { case Ext.form.Action.CLIENT_INVALID: msg = "Les informations saisies sont invalides"; break; case Ext.form.Action.CONNECT_FAILURE: msg = "Problème de connexion au serveur"; break; case Ext.form.Action.SERVER_INVALID: msg = "Erreur lors de l'enregistrement : vérifier les données saisies !"; break; } Ext.Msg.show({ title: 'Erreur' ,msg: msg ,buttons: Ext.Msg.OK ,icon: Ext.MessageBox.ERROR }); } }); }; /** * Method: showLayerTreeTip * Shows or hide the layer tree tip */ var showLayerTreeTip = function(show) { layerTreeTip.setVisible(show); }; //-----------fenêtre de questionnement pour la saisie d'une ap ------------------------------------ var initWindowNewAp = function(index) { var layer = vectorLayer; return new Ext.Window({ id:'window-new-ap' ,layout:'fit' ,height:120 ,width: 400 ,closeAction:'hide' ,autoScroll:true ,modal: true ,plain: true ,split: true ,html:'<div style="text-align:center;font-size:12px;font-weight:bold;color:blue;">Vous venez de créer une nouvelle zone de prospection. </br>Souhaitez vous ajouter une aire de présence dans de cette zone de prospection ?</div>' ,buttons: [{ text:'Nouvelle aire de présence' ,id:'bt-new-ap' ,iconCls:'add' ,handler: function(){ //récupérer l'indexzp nouveau = fait dans le submitform avec la réponse json de l'action save : on met à jour la variable global indexzp) // trouver la zp nouvelle avec le nouvel indexzp dans le store de l'onglet search var reg=new RegExp("^"+index+"$", "g"); var id = Ext.getCmp('zp_list_grid').getStore().find('indexzp',reg); var rec = Ext.getCmp('zp_list_grid').getStore().getAt(id); // ouvrir l'onglet de la zp nouvelle application.layout.loadZp(rec); // ouvrir l'editap avec mon action add + la feature contenant la géometrie pour centrer l'editAp sur les bounds de cette geometrie application.editAp.loadAp(null,rec,'add',layer.features[0].geometry.bounds); Ext.getCmp('window-new-ap').destroy(); Ext.getCmp('zpSaveButton').setText('Enregistrer'); Ext.getCmp('zpSaveButton').enable(); application.editZp.window.hide(); } },{ text: 'Aucune aire de présence' ,handler: function(){ Ext.getCmp('window-new-ap').destroy(); Ext.getCmp('zpSaveButton').setText('Enregistrer'); Ext.getCmp('zpSaveButton').enable(); application.editZp.window.hide(); Ext.ux.Toast.msg('Aucune aire de présence !', 'Il est toujours possible de saisir une aire de présence à posteriori.'); } }] ,listeners: { hide:function(){this.destroy();} } }); }; //---------------------------------- fin de fenêtre de questionnement pour la saisie d'une ap ---------------------------------- //------------------------------------formulaire de chargement des fichiers--------------------------------------------------- var getUploadFileFormPanel = function(){ var formUploadFile = new Ext.FormPanel({ id: 'form-upload-zp-gpx' ,fileUpload: true ,width: 400 ,frame: true ,autoHeight: true ,bodyStyle: 'padding: 10px 10px 0 10px;' ,labelWidth: 50 ,defaults: { anchor: '95%', allowBlank: false, msgTarget: 'side' } ,items: [{ xtype: 'hidden', name: 'username', value: application.user.nom },{ xtype: 'fileuploadfield', emptyText: 'Sélectionner un fichier (format gpx uniquement)', fieldLabel: 'Fichier', name: 'nom_fichier', buttonText: '', buttonCfg: { iconCls: 'upload-icon' } }] ,buttons: [{ text: 'Annuler', handler: function(){ formUploadFile.getForm().reset(); } },{ text: 'Enregistrer', handler: function(){ if(formUploadFile.getForm().isValid()){ formUploadFile.getForm().submit({ url: 'ap/uploadgpx', enctype:'multipart/form-data', waitMsg: 'chargement de votre fichier gpx...', success: function(form, action){ if(action.result.success==true){ application.editZp.createGpxLayer(); Ext.ux.Toast.msg('Téléchargement !', 'Fichier gpx a été télécharger, vous devez zommer sur la localisation de son contenu pour le voir sur la carte'); } else{ Ext.ux.Toast.msg('Attention !', 'Téléchargement du fichier gpx : <br>'+action.result.errors); } application.editZp.windowUploadFile.hide(); }, failure : function(form, action) { if(action.result.success==false){ Ext.ux.Toast.msg('Attention !', 'Une erreur est survenue'); } application.editZp.windowUploadFile.hide(); } }); } else{alert('biiiiiip ! Saisie non valide')} } }] }); return formUploadFile; } var initFormUploadFile = function() { return new Ext.Window({ layout:'fit' ,title: 'charger un fichier gpx sur le fond de carte' ,closeAction:'hide' ,plain: true ,modal: true ,width: 550 ,buttons: [{ text: 'Fermer' ,handler: function(){ application.editZp.windowUploadFile.hide(); } }] ,items: [ getUploadFileFormPanel() ] }); }; //---------------------------------------fin du formulaire de chargement des fichiers---------------------------------------------------- // public space return { window: null ,init: function() { createProtocol(); createStore(); this.window = initWindow(); } ,initNewAp: function(index) { this.windowNewAp = initWindowNewAp(index); this.windowNewAp.show(); } ,initWindowUploadFile: function() { this.windowUploadFile = initFormUploadFile(); } ,addGpx: function() { if (this.windowUploadFile){} if (!this.windowUploadFile) {this.initWindowUploadFile();} this.windowUploadFile.show(); } /** * Method: loadZp * Loads a record from the zps list store */ ,loadZp: function(id,monaction,bounds) { if (!this.window) { this.init(); } this.window.show(); maLayer = vectorLayer; if (monaction=='update') { this.window.setTitle('Modification d\'une zone de propection'); if (id) { indexzp = id; map.getLayersByName('overlay')[0].mergeNewParams({ indexzp: indexzp }); var options = { url: ['zp/get', id].join('/') ,params: {format: 'geoJSON'} }; eventProtocol.read(options); } } if (monaction=='add') { activateControls(true); updateGeometryField(null); this.window.setTitle('Ajout d\'une nouvelle zone de prospection'); Ext.getCmp('combo-zp-organisme').setValue(application.user.id_organisme); Ext.getCmp('label-dateobs').setText( '<p class="redtext">Nouvelle propection - Saisir puis enregistrer pour pouvoir saisir des aires de présence</p>',false); Ext.ux.Toast.msg('Attention !', 'Commencer par saisir la zone de propection sur la carte pour activer le formulaire'); var zoomLevel = map.getZoomForExtent(bounds); var centerGeom = bounds.getCenterLonLat(); if (zoomLevel > 9){zoomLevel = 9;} map.setCenter(centerGeom,zoomLevel); } } /** * Method: createGpsLayer * Creates the vector gml layer *use : createGpxLayer("../uploads/test.gpx"); * Return * <OpenLayers.Layer.Vector> */ ,createGpxLayer: function() { if(map.getLayersByName('gps')[0]){ zpSelcontrol.deactivate(); map.getLayersByName('gps')[0].events.unregister("loadend", ZpVectorGpxLayer, setExtent); map.getLayersByName('gps')[0].destroy(); } var styleMap = new OpenLayers.StyleMap({ 'default': { fillColor: "gray" ,strokeColor: "yellow" ,cursor: "pointer" ,fillOpacity: 0.5 ,strokeOpacity: 0.75 ,strokeWidth: 2 ,pointRadius: 7 } ,select : { fillColor: "blue" ,strokeColor: "blue" ,cursor: "pointer" ,fillOpacity: 0.6 ,strokeOpacity: 1 ,strokeWidth: 2 ,pointRadius: 7 } }); // This will enable us to autozoom the map to the displayed data. var dataExtent; var setExtent = function(){ if(dataExtent){dataExtent.extend(this.getDataExtent());} else{dataExtent = this.getDataExtent();} var zoomLevel = map.getZoomForExtent(dataExtent); var centerGeom = dataExtent.getCenterLonLat(); if (zoomLevel > 9){zoomLevel = 9;} map.setCenter(centerGeom,zoomLevel); // map.zoomToExtent(dataExtent); }; //identification de l'utilisateur dans le nom du gpx var reg=new RegExp("( )", "g"); var gpxFile = application.user.nom.replace(reg,"_") ZpVectorGpxLayer = new OpenLayers.Layer.Vector("gps",{ protocol: new OpenLayers.Protocol.HTTP({ url: host_uri+"/flore/uploads/gpx/gpx_"+gpxFile+".gpx" ,format: new OpenLayers.Format.GPX() }) ,strategies: [new OpenLayers.Strategy.Fixed()] ,styleMap: styleMap ,projection: new OpenLayers.Projection("EPSG:4326") }); // This will perform the autozoom as soon as the GPX file is loaded. ZpVectorGpxLayer.events.register("loadend", ZpVectorGpxLayer, setExtent); map.addLayer(ZpVectorGpxLayer); // This function creates a popup window. In this case, the popup is a cloud containing the "name" and "desc" elements from the GPX file. function createPopup(feature) { var gpxDiv = '<div> * Nom gps : <span style="font-weight:bold;">'+ feature.attributes.name+ '</span>'; if(feature.attributes.desc){gpxDiv = gpxDiv + ' - '+ feature.attributes.desc;} if(feature.attributes.ele){gpxDiv = gpxDiv + ' - '+ Math.round(feature.attributes.ele) + ' m';} gpxDiv = gpxDiv + '</span></div>'; feature.popup = new OpenLayers.Popup("gpx", feature.geometry.getBounds().getCenterLonLat(), null, gpxDiv, false ); feature.popup.backgroundColor='#ccc'; feature.popup.opacity=0.75; feature.popup.autoSize=true; map.addPopup(feature.popup); } // This function destroys the popup when the user clicks the X. function destroyPopup(feature) { feature.popup.destroy(); feature.popup = null; } // This feature connects the click events to the functions defined above, such that they are invoked when the user clicks on the map. zpSelcontrol = new OpenLayers.Control.SelectFeature(ZpVectorGpxLayer, { onSelect: createPopup, hover:true, onUnselect: destroyPopup }); map.addControl(zpSelcontrol); zpSelcontrol.activate(); } } }();
* Property: toolbarInitializedOnce
module_data.go
package models import ( "time" "github.com/astaxie/beego/orm" ) // ModuleData xml初始化数据记录 type ModuleData struct { ID int64 `orm:"column(id);pk;auto"` //主键 CreateUserID int64 `orm:"column(create_user_id);null"` //创建者 UpdateUserID int64 `orm:"column(update_user_id);null"` //最后更新者 CreateDate time.Time `orm:"auto_now_add;type(datetime)"` //创建时间 UpdateDate time.Time `orm:"auto_now;type(datetime)"` //最后更新时间 XMLID string `orm:"column(xml_id);unique;index"` //xml文件中的id Data string `orm:"null"` //数据内容 Descrition string `orm:"null"` //记录描述 InsertID int64 `orm:"column(insert_id)"` //插入记录的ID ModuleName string `orm:""` //模块(表)的名称 } func init() { orm.RegisterModel(new(ModuleData)) } // AddModuleData insert a new ModuleData into database and returns last inserted Id on success. func AddModuleData(m *ModuleData, ormObj orm.Ormer) (id int64, err error) { id, err = ormObj.Insert(m) return } // GetModuleDataByXMLID get moduledata by xmlid func GetModuleDataByXMLID(xmlid string, ormObj orm.Ormer) (*ModuleData, error) { var obj ModuleData var
mObj.QueryTable(&obj) err = qs.Filter("xml_id", xmlid).One(&obj) return &obj, err }
err error qs := or
map.py
# Copyright (c) 2017-2022 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 __all__ = ["FrozenDict", "to_hashable"] class FrozenDict(dict): """ A special subclass of `dict` that is immutable and hashable. Instances of this "dict" can be used as keys in a Python dictionary. """ def __hash__(self): return 0 def __delitem__(self, *args, **kwargs): raise RuntimeError("frozendicts are immutable") def
(self, key, value): raise RuntimeError("frozendicts are immutable") def pop(self, *args, **kwargs): raise RuntimeError("frozendicts are immutable") def popitem(self, *args, **kwargs): raise RuntimeError("frozendicts are immutable") def setdefault(self, *args, **kwargs): raise RuntimeError("frozendicts are immutable") def update(self, *args, **kwargs): raise RuntimeError("frozendicts are immutable") def clear(self, *args, **kwargs): raise RuntimeError("frozendicts are immutable") def to_hashable(obj): from collections import Collection, Mapping if isinstance(obj, Mapping): return FrozenDict(obj) elif isinstance(obj, str): return obj elif isinstance(obj, Collection): return tuple(obj) else: return obj
__setitem__
LoadingSpinner.js
import React from 'react'; import PropTypes from 'prop-types'; import {makeStyles} from '@material-ui/core/styles'; import LoadingIcon from '../LoadingIcon'; import {Grid, Typography} from '@material-ui/core'; const gridStyles = makeStyles({ root: { display: 'flex', flex: '1 1 auto', flexDirection: 'column', width: '100%', animation: '0.45s fade-in', alignItems: 'center' } }); const typographyStyles = makeStyles({ root: { paddingTop: '10px' } }); function LoadingSpinner({message}) { const gridClasses = gridStyles(); const typographyClasses = typographyStyles(); return ( <Grid classes={gridClasses}> <LoadingIcon height="10rem" /> {message && ( <Typography classes={typographyClasses} variant="subtitle1"> {message}
</Grid> ); } LoadingSpinner.propTypes = { isLoading: PropTypes.bool, message: PropTypes.string }; export default LoadingSpinner;
</Typography> )}
upyun.py
# -*- coding: utf8 -*- import httplib import md5 as imd5 import base64 import time import re METADATA_PREFIX = 'x-upyun-meta-' DL = '/' def md5(src): m1 = imd5.new() m1.update(src) dest1 = m1.hexdigest() return dest1 def md5file(fobj): m = imd5.new() while True: d = fobj.read(8096) if not d: break m.update(d) fobj.seek(0) return m.hexdigest() def merge_meta(headers, metadata): final_headers = headers.copy() for k in metadata.keys(): final_headers[METADATA_PREFIX + k] = metadata[k] return final_headers class UpYunException(Exception): '''Raised when a Yupoo method fails. More specific details will be included in the exception message when thrown. ''' #目录条目类 class FolderItem(object): def __init__(self, filename, filetype, size, number): self.filename = filename self.filetype = filetype self.size = size self.number = number class UpYun(object): def __init__(self, bucket, username, password): self.thehost = 'v0.api.upyun.com' self.username = username self.password = password self.bucket = bucket self.upAuth = False self.debug = False self._tmp_info = None self.content_md5 = '' self.file_secret = '' #版本 def version(self): return '1.0.1' #设置待上传文件的 Content-MD5 值(如又拍云服务端收到的文件MD5值与用户设置的不一致,将回报 406 Not Acceptable 错误) def setContentMD5(self, vaule): self.content_md5 = vaule #设置待上传文件的 访问密钥(注意:仅支持图片空!,设置密钥后,无法根据原文件URL直接访问,需带 URL 后面加上 (缩略图间隔标志符+密钥) 进行访问) #如缩略图间隔标志符为 ! ,密钥为 bac,上传文件路径为 /folder/test.jpg ,那么该图片的对外访问地址为: http://空间域名/folder/test.jpg!bac def setFileSecret(self, vaule): self.file_secret = vaule #设定api所调用的域名,包括电信,联通,网通,移动,铁通和自动选择 def setApiDomain(self,thehost): self.thehost = thehost #设定是否使用又拍签名 def setAuthType(self,upAuth): self.upAuth = upAuth def getList(self, path='', headers={}, metadata={}): resp = self._net_worker( 'GET', DL+self.bucket+DL+path, '', headers, metadata) return resp def delete(self, path, headers={}, metadata={}): resp = self._net_worker('DELETE',DL+self.bucket+DL+path, '',headers,metadata) return resp #获取空间占用大小 def getBucketUsage(self, path='', headers={}, metadata={}): resp = self.getList(path+'?usage', headers, metadata) try: resp = int(resp.read()) except Exception, e: resp = None return resp #获取某个目录的空间占用大小 #path目录路径 def getFolderUsage(self, path='', headers={}, metadata={}): resp = self.getBucketUsage(path, headers, metadata) return resp #新建目录 #path目录路径 #[auto] 是否自动创建父级目录(最多10级) def mkDir(self, path, auto=False, headers={}, metadata={}): headers['folder'] = 'create' if auto == True : headers['mkdir'] = 'true' resp = self._net_worker('POST', DL+self.bucket+DL+path, '', headers, metadata) if resp.status == 200 : return True else : return False #删除目录 #path目录路径 def rmDir(self, path, headers={}, metadata={}): resp = self.delete(path,headers,metadata) if resp.status == 200 : return True else : return False #读取目录,返回FolderItem #path目录路径 def readDir(self, path='', headers={}, metadata={}): resp = self.getList(path, headers, metadata) if resp.status == 200 : result = re.sub('\t', '\/', resp.read()) result = re.sub('\n', '\/', result) b = result.split('\/') i=0 fis = [] while i+1<len(b): fi = FolderItem(b[i],b[i+1],b[i+2],b[i+3]) fis.append(fi) i+=4 return fis else : retu
e #上传文件 #data 要上传的文件数据 #path 远程文件的位置 #[auto] 是否自动创建父级目录(最多10级) def writeFile(self, path, data, auto = False, headers={}, metadata={}): if auto == True : headers['mkdir'] = 'true' if type(data) != file : headers['Content-Length'] = len(data) resp = self._net_worker('PUT',DL+self.bucket+DL+path, data,headers,metadata) self._tmp_info = None if resp.status == 200 : self._tmp_info = {} self._tmp_info['x-upyun-width'] = resp.getheader('x-upyun-width') self._tmp_info['x-upyun-height'] = resp.getheader('x-upyun-height') self._tmp_info['x-upyun-frames'] = resp.getheader('x-upyun-frames') self._tmp_info['x-upyun-file-type'] = resp.getheader('x-upyun-file-type') return True else : return False #获取上传文件后的信息(仅图片空间有返回数据) #key 信息字段名(x-upyun-width、x-upyun-height、x-upyun-frames、x-upyun-file-type) #return value or NULL def getWritedFileInfo(self, key): if self._tmp_info != None and self._tmp_info['x-upyun-width'] : return self._tmp_info[key] return None #读取文件 #path 所要读取文件地远程路径 def readFile(self, path, headers={}, metadata={}): resp = self.getList(path, headers, metadata) if resp.status == 200 : return resp.read() else : return None #删除文件 #path 所要删除文件地远程路径 def deleteFile(self, path, headers={}, metadata={}): resp = self.delete(path,headers,metadata) if resp.status == 200 : return True else : return False #获取文件信息 #path 文件的远程路径 #返回格式为 {'date': unix time, 'type': file | folder, 'size': file size} 或 None def getFileInfo(self, path, headers={}, metadata={}): resp = self._net_worker( 'HEAD', DL+self.bucket+DL+path, '', headers, metadata) if resp.status == 200 : rs = {} rs['type'] = resp.getheader('x-upyun-file-type') rs['size'] = resp.getheader('x-upyun-file-size') rs['date'] = resp.getheader('x-upyun-file-date') return rs else : return None def _net_worker(self, method, path, data='', headers={}, metadata={}): connection = httplib.HTTPConnection(self.thehost) if self.content_md5 != '': headers['Content-MD5'] = self.content_md5 self.content_md5 = '' if self.file_secret != '': headers['Content-Secret'] = self.file_secret self.file_secret = '' final_headers = merge_meta(headers, metadata) if self.upAuth: self._add_upyun_auth_header(final_headers,method,path) else : self._basicAuth(final_headers,self.username,self.password) connection.request(method, path , data, final_headers) resp = connection.getresponse() if self.debug and resp.status != 200 and method != "HEAD" : raise UpYunException(u'ERROR: Code:%d,Message:%s'%(resp.status,resp.read())) return resp #又拍签名认证 def _add_upyun_auth_header(self, headers, method, uri): headers['Date'] = time.strftime("%a, %d %b %Y %X GMT", time.gmtime()) if 'Content-Length' in headers: scr = md5(method+'&'+uri+'&'+headers['Date']+'&' +str(headers['Content-Length'])+'&'+md5(self.password)) else : scr = md5(method+'&'+uri+'&'+headers['Date']+'&' +'0'+'&'+md5(self.password)) headers['Authorization'] = "UpYun %s:%s" % (self.username, scr) def _basicAuth(self,headers, username, password): encode = base64.encodestring(username+':'+password) headers['Authorization'] = "Basic %s" % encode.strip()
rn Fals
recognize_transportation_license_response.py
# coding: utf-8 import re import six from huaweicloudsdkcore.sdk_response import SdkResponse from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class
(SdkResponse): """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { 'result': 'TransportationLicenseResult' } attribute_map = { 'result': 'result' } def __init__(self, result=None): """RecognizeTransportationLicenseResponse - a model defined in huaweicloud sdk""" super(RecognizeTransportationLicenseResponse, self).__init__() self._result = None self.discriminator = None if result is not None: self.result = result @property def result(self): """Gets the result of this RecognizeTransportationLicenseResponse. :return: The result of this RecognizeTransportationLicenseResponse. :rtype: TransportationLicenseResult """ return self._result @result.setter def result(self, result): """Sets the result of this RecognizeTransportationLicenseResponse. :param result: The result of this RecognizeTransportationLicenseResponse. :type: TransportationLicenseResult """ self._result = result def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" import simplejson as json if six.PY2: import sys reload(sys) sys.setdefaultencoding("utf-8") return json.dumps(sanitize_for_serialization(self), ensure_ascii=False) def __repr__(self): """For `print`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, RecognizeTransportationLicenseResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
RecognizeTransportationLicenseResponse
create_curve_v0.rs
use crate::{error::ErrorCode, state::*}; use anchor_lang::prelude::*; #[derive(AnchorSerialize, AnchorDeserialize, Clone)] pub struct CreateCurveV0Args { pub definition: PiecewiseCurve, } pub fn primitive_curve_is_valid(curve: &PrimitiveCurve) -> bool { match *curve { PrimitiveCurve::ExponentialCurveV0 { frac, c, b, pow } => { (c == 0 || b == 0) && frac > 0 && frac <= 10 && pow <= 10 } PrimitiveCurve::TimeDecayExponentialCurveV0 { .. } => true, } } pub fn
(curve: &PiecewiseCurve) -> bool { match curve { PiecewiseCurve::TimeV0 { curves } => // All inner curves are valid { curves.iter().all(|c| primitive_curve_is_valid(&c.curve) && c.offset >= 0) && // The first curve starts at time 0 curves.get(0).map(|c| c.offset).unwrap_or(1) == 0 && // The curves list is ordered by offset curves.windows(2).all(|c| c[0].offset <= c[1].offset) } } } #[derive(Accounts)] #[instruction(args: PiecewiseCurve)] pub struct InitializeCurveV0<'info> { #[account(mut)] pub payer: Signer<'info>, #[account(zero)] pub curve: Account<'info, CurveV0>, pub system_program: Program<'info, System>, pub rent: Sysvar<'info, Rent>, } pub fn handler(ctx: Context<InitializeCurveV0>, args: CreateCurveV0Args) -> Result<()> { if !curve_is_valid(&args.definition) { return Err(error!(ErrorCode::InvalidCurve)); } let curve = &mut ctx.accounts.curve; curve.definition = args.definition; Ok(()) }
curve_is_valid
file_player.py
from pathlib import Path from random import shuffle from discord import VoiceChannel from music.abstract_music_player import AbstractMusicPlayer from music.entry import Entry class FilePlayer(AbstractMusicPlayer): """ Audio player for playing local files. """ __slots__ = ('default_path',) def __init__(self, logger, channel: VoiceChannel, default_path: Path): """ :param logger: a logger object to do logging with. :param channel: the `VoiceChannel` to play audio in. :param default_path: the path to the playlist directory. """ super().__init__(logger, channel) self.default_path = default_path
`self.entry_queue` :param ctx: the `discord.Context` object. :param query: This isn't used. """ if self.entry_queue: return files = [str(f) for f in self.default_path.iterdir()] shuffle(files) self.entry_queue.extend(Entry.from_file(ctx, file) for file in files)
async def enqueue(self, ctx, query: str = None): """ Bulk enqueue all files in the default play list directory into
find_map.rs
use core::future::Future; use core::pin::Pin; use core::task::{Context, Poll}; use crate::stream::Stream; #[doc(hidden)] #[allow(missing_debug_implementations)] pub struct FindMapFuture<'a, S, F> { stream: &'a mut S, f: F, } impl<'a, S, F> FindMapFuture<'a, S, F> { pub(super) fn new(stream: &'a mut S, f: F) -> Self { Self { stream, f } } } impl<S: Unpin, F> Unpin for FindMapFuture<'_, S, F> {} impl<'a, S, B, F> Future for FindMapFuture<'a, S, F> where S: Stream + Unpin + Sized, F: FnMut(S::Item) -> Option<B>, { type Output = Option<B>; fn
(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let item = futures_core::ready!(Pin::new(&mut *self.stream).poll_next(cx)); match item { Some(v) => match (&mut self.f)(v) { Some(v) => Poll::Ready(Some(v)), None => { cx.waker().wake_by_ref(); Poll::Pending } }, None => Poll::Ready(None), } } }
poll
register_add_hosts_cluster_parameters.go
// Code generated by go-swagger; DO NOT EDIT. package installer // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "io" "net/http" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" "github.com/go-openapi/runtime/middleware" "github.com/openshift/assisted-service/models" ) // NewRegisterAddHostsClusterParams creates a new RegisterAddHostsClusterParams object // no default values defined in spec. func NewRegisterAddHostsClusterParams() RegisterAddHostsClusterParams
// RegisterAddHostsClusterParams contains all the bound params for the register add hosts cluster operation // typically these are obtained from a http.Request // // swagger:parameters RegisterAddHostsCluster type RegisterAddHostsClusterParams struct { // HTTP Request Object HTTPRequest *http.Request `json:"-"` /*Parameters for creating a new cluster for adding nodes. Required: true In: body */ NewAddHostsClusterParams *models.AddHostsClusterCreateParams } // BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface // for simple values it will use straight method calls. // // To ensure default values, the struct must have been initialized with NewRegisterAddHostsClusterParams() beforehand. func (o *RegisterAddHostsClusterParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { var res []error o.HTTPRequest = r if runtime.HasBody(r) { defer r.Body.Close() var body models.AddHostsClusterCreateParams if err := route.Consumer.Consume(r.Body, &body); err != nil { if err == io.EOF { res = append(res, errors.Required("newAddHostsClusterParams", "body", "")) } else { res = append(res, errors.NewParseError("newAddHostsClusterParams", "body", "", err)) } } else { // validate body object if err := body.Validate(route.Formats); err != nil { res = append(res, err) } if len(res) == 0 { o.NewAddHostsClusterParams = &body } } } else { res = append(res, errors.Required("newAddHostsClusterParams", "body", "")) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
{ return RegisterAddHostsClusterParams{} }
cli.rs
use crate::io::SUPPORTED_IMAGE_EXT; use crate::scenes::Scene; use clap::{App, AppSettings, Arg, ArgMatches, SubCommand}; use std::str::FromStr; use thiserror::Error; pub struct ConfigPath(String); pub struct OutputPath(String); pub struct ImagePath(String); impl ConfigPath { pub fn path(&self) -> &str { &self.0 } } impl OutputPath { pub fn path(&self) -> &str { &self.0 } } impl ImagePath { pub fn path(&self) -> &str { &self.0 } pub fn file_name(&self) -> &str { &self.0.split('/').last().unwrap() } } pub enum CliCommand { RENDER { width: u32, output_path: OutputPath, num_of_rays: u64, num_of_threads: usize, asset_paths: Vec<ImagePath>, }, GENERATE { scene: Scene, }, } pub struct CliConfig { command: CliCommand, config_path: ConfigPath, } impl CliConfig { pub fn command(&self) -> &CliCommand { &self.command } pub fn config_path(&self) -> &ConfigPath { &self.config_path } } #[allow(clippy::enum_variant_names)] #[derive(Debug, Error)] enum CliParsingError { #[error("invalid value <{value}> for arg <{arg}>")] InvalidValue { arg: String, value: String }, #[error("Config path <{0}> must end in .yaml")] InvalidConfigPath(String), #[error("Output path <{output_path}> must end in one of {supported_extensions:?}")] InvalidOutputPath { output_path: String, supported_extensions: Vec<String>, }, } pub fn get_cli_config() -> Result<CliConfig, anyhow::Error> { let matches = App::new("Ray tracer") .setting(AppSettings::SubcommandRequiredElseHelp) .setting(AppSettings::VersionlessSubcommands) .global_setting(AppSettings::ColoredHelp) .global_setting(AppSettings::DeriveDisplayOrder) .version(crate_version!()) .arg( Arg::with_name("config") .short("c") .long("config") .takes_value(true) .required(true) .help("path to image config yaml"), ) .subcommands(vec![ SubCommand::with_name("render") .about("renders an image") .arg( Arg::with_name("width") .short("w") .long("width") .takes_value(true) .required(true)
.help("the output image width"), ) .arg( Arg::with_name("output_path") .short("o") .long("output") .takes_value(true) .required(true) .default_value("image.ppm") .help("the output image path"), ) .arg( Arg::with_name("rays") .short("r") .long("rays") .takes_value(true) .required(true) .default_value("100") .help("the number of rays to generate per pixel"), ) .arg( Arg::with_name("threads") .short("t") .long("threads") .takes_value(true) .required(true) .default_value("4") .help("the number of threads to create for the renderer"), ) .arg( Arg::with_name("asset") .short("a") .long("asset") .takes_value(true) .required(false) .multiple(true) .help( "the paths to image assets needed by the selected scene. The \ filename must be unique amongst all loaded assets", ), ), SubCommand::with_name("generate") .about("generate a random image config yaml") .arg( Arg::with_name("scene") .short("s") .long("scene") .takes_value(true) .required(true) .possible_values(&Scene::variants()) .case_insensitive(true) .help("the name of the scene to generate"), ), ]) .get_matches(); let config_path = String::from(matches.value_of("config").unwrap()); validate_config_path(&config_path)?; if let Some(subcommand) = matches.subcommand_matches("render") { let width = parse::<u32>(subcommand, "width")?; let output_path = String::from(subcommand.value_of("output_path").unwrap()); let num_of_rays = parse::<u64>(subcommand, "rays")?; let num_of_threads = parse::<usize>(subcommand, "threads")?; let asset_paths: Vec<ImagePath> = subcommand .values_of("asset") .unwrap_or_default() .map(|path| ImagePath(String::from(path))) .collect(); validate_output_path(&output_path)?; return Ok(CliConfig { command: CliCommand::RENDER { width, output_path: OutputPath(output_path), num_of_rays, num_of_threads, asset_paths, }, config_path: ConfigPath(config_path), }); } if let Some(subcommand) = matches.subcommand_matches("generate") { let scene = parse::<Scene>(subcommand, "scene")?; return Ok(CliConfig { command: CliCommand::GENERATE { scene }, config_path: ConfigPath(config_path), }); } // Clap should have errored before we get here panic!("Unable to parse CLI args") } fn validate_config_path(config_path: &str) -> Result<(), CliParsingError> { if !config_path.ends_with(".yaml") { return Err(CliParsingError::InvalidConfigPath(config_path.to_string())); } Ok(()) } fn validate_output_path(output_path: &str) -> Result<(), CliParsingError> { if !SUPPORTED_IMAGE_EXT .iter() .any(|ext| output_path.ends_with(ext)) { return Err(CliParsingError::InvalidOutputPath { output_path: output_path.to_string(), supported_extensions: SUPPORTED_IMAGE_EXT .iter() .map(|ext| (*ext).to_string()) .collect(), }); } Ok(()) } fn parse<T: FromStr>(matches: &ArgMatches, arg: &str) -> Result<T, CliParsingError> { let raw = matches.value_of(arg).unwrap(); match raw.parse::<T>() { Ok(parsed) => Ok(parsed), Err(_) => Err(CliParsingError::InvalidValue { arg: String::from(arg), value: String::from(raw), }), } }
function.rs
#[doc = "Reader of register FUNCTION"] pub type R = crate::R<u32, super::FUNCTION>; #[doc = "Writer for register FUNCTION"] pub type W = crate::W<u32, super::FUNCTION>; #[doc = "Register FUNCTION `reset()`'s with value 0"] impl crate::ResetValue for super::FUNCTION { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `Reserved1`"] pub type RESERVED1_R = crate::R<u8, u8>; #[doc = "Write proxy for field `Reserved1`"] pub struct RESERVED1_W<'a> { w: &'a mut W, } impl<'a> RESERVED1_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x7f << 25)) | (((value as u32) & 0x7f) << 25); self.w } } #[doc = "Reader of field `STALL_RESULT`"] pub type STALL_RESULT_R = crate::R<bool, bool>; #[doc = "Write proxy for field `STALL_RESULT`"] pub struct STALL_RESULT_W<'a> { w: &'a mut W, } impl<'a> STALL_RESULT_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "Reader of field `Reserved2`"] pub type RESERVED2_R = crate::R<u8, u8>; #[doc = "Write proxy for field `Reserved2`"] pub struct RESERVED2_W<'a> { w: &'a mut W, } impl<'a> RESERVED2_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 16)) | (((value as u32) & 0xff) << 16); self.w } } #[doc = "Reader of field `RUN`"] pub type RUN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RUN`"] pub struct RUN_W<'a> { w: &'a mut W, } impl<'a> RUN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `SEQUENCER_OPERATIONS`"] pub type SEQUENCER_OPERATIONS_R = crate::R<u8, u8>; #[doc = "Write proxy for field `SEQUENCER_OPERATIONS`"] pub struct SEQUENCER_OPERATIONS_W<'a> { w: &'a mut W, } impl<'a> SEQUENCER_OPERATIONS_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x07 << 12)) | (((value as u32) & 0x07) << 12); self.w } } #[doc = "Reader of field `COPY`"] pub type COPY_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COPY`"] pub struct COPY_W<'a> { w: &'a mut W, } impl<'a> COPY_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `COMPARE`"] pub type COMPARE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `COMPARE`"] pub struct COMPARE_W<'a> { w: &'a mut W, } impl<'a> COMPARE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `MODULO`"] pub type MODULO_R = crate::R<bool, bool>; #[doc = "Write proxy for field `MODULO`"] pub struct MODULO_W<'a> { w: &'a mut W, } impl<'a> MODULO_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `DIVIDE`"] pub type DIVIDE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DIVIDE`"] pub struct DIVIDE_W<'a> { w: &'a mut W, } impl<'a> DIVIDE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `LSHIFT`"] pub type LSHIFT_R = crate::R<bool, bool>; #[doc = "Write proxy for field `LSHIFT`"] pub struct LSHIFT_W<'a> { w: &'a mut W, } impl<'a> LSHIFT_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `RSHIFT`"] pub type RSHIFT_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RSHIFT`"] pub struct RSHIFT_W<'a> { w: &'a mut W, } impl<'a> RSHIFT_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Reader of field `SUBTRACT`"] pub type SUBTRACT_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SUBTRACT`"] pub struct SUBTRACT_W<'a> { w: &'a mut W, } impl<'a> SUBTRACT_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `ADD`"] pub type ADD_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ADD`"] pub struct ADD_W<'a> { w: &'a mut W, } impl<'a> ADD_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `MS_ONE`"] pub type MS_ONE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `MS_ONE`"] pub struct MS_ONE_W<'a> { w: &'a mut W, } impl<'a> MS_ONE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `Reserved3`"] pub type RESERVED3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `Reserved3`"] pub struct RESERVED3_W<'a> { w: &'a mut W, } impl<'a> RESERVED3_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `ADDSUB`"] pub type ADDSUB_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ADDSUB`"] pub struct ADDSUB_W<'a> { w: &'a mut W, } impl<'a> ADDSUB_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W {
self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `MULTIPLY`"] pub type MULTIPLY_R = crate::R<bool, bool>; #[doc = "Write proxy for field `MULTIPLY`"] pub struct MULTIPLY_W<'a> { w: &'a mut W, } impl<'a> MULTIPLY_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bits 25:31 - 31:25\\] Set to zero on write, ignore on read"] #[inline(always)] pub fn reserved1(&self) -> RESERVED1_R { RESERVED1_R::new(((self.bits >> 25) & 0x7f) as u8) } #[doc = "Bit 24 - 24:24\\] When written with a 1b, updating of the PKA_COMPARE, PKA_MSW and PKA_DIVMSW registers, as well as resetting the run bit is stalled beyond the point that a running operation is actually finished. Use this to allow software enough time to read results from a previous operation when the newly started operation is known to take only a short amount of time. If a result is waiting, the result registers is updated and the run bit is reset in the clock cycle following writing the stall result bit back to 0b. The Stall result function may only be used for basic PKCP operations."] #[inline(always)] pub fn stall_result(&self) -> STALL_RESULT_R { STALL_RESULT_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bits 16:23 - 23:16\\] Set to zero on write, ignore on read"] #[inline(always)] pub fn reserved2(&self) -> RESERVED2_R { RESERVED2_R::new(((self.bits >> 16) & 0xff) as u8) } #[doc = "Bit 15 - 15:15\\] The host sets this bit to instruct the PKA module to begin processing the basic PKCP or complex sequencer operation. This bit is reset low automatically when the operation is complete. The complement of this bit is output as interrupts\\[1\\]. After a reset, the run bit is always set to 1b. Depending on the option, program ROM or program RAM, the following applies: Program ROM - The first sequencer instruction sets the bit to 0b. This is done immediately after the hardware reset is released. Program RAM - The sequencer must set the bit to 0b. As a valid firmware may not have been loaded, the sequencer is held in software reset after the hardware reset is released (the reset bit in PKA_SEQ_CRTL is set to 1b). After the FW image is loaded and the Reset bit is cleared, the sequencer starts to execute the FW. The first instruction clears the run bit. In both cases a few clock cycles are needed before the first instruction is executed and the run bit state has been propagated."] #[inline(always)] pub fn run(&self) -> RUN_R { RUN_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bits 12:14 - 14:12\\] These bits select the complex sequencer operation to perform: 000b: None 001b: ExpMod-CRT 010b: ExpMod-ACT4 (compatible with EIP2315) 011b: ECC-ADD (if available in firmware, otherwise reserved) 100b: ExpMod-ACT2 (compatible with EIP2316) 101b: ECC-MUL (if available in firmware, otherwise reserved) 110b: ExpMod-variable 111b: ModInv (if available in firmware, otherwise reserved) The encoding of these operations is determined by sequencer firmware."] #[inline(always)] pub fn sequencer_operations(&self) -> SEQUENCER_OPERATIONS_R { SEQUENCER_OPERATIONS_R::new(((self.bits >> 12) & 0x07) as u8) } #[doc = "Bit 11 - 11:11\\] Perform copy operation"] #[inline(always)] pub fn copy(&self) -> COPY_R { COPY_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 10 - 10:10\\] Perform compare operation"] #[inline(always)] pub fn compare(&self) -> COMPARE_R { COMPARE_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 9 - 9:9\\] Perform modulo operation"] #[inline(always)] pub fn modulo(&self) -> MODULO_R { MODULO_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 8 - 8:8\\] Perform divide operation"] #[inline(always)] pub fn divide(&self) -> DIVIDE_R { DIVIDE_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 7 - 7:7\\] Perform left shift operation"] #[inline(always)] pub fn lshift(&self) -> LSHIFT_R { LSHIFT_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 6 - 6:6\\] Perform right shift operation"] #[inline(always)] pub fn rshift(&self) -> RSHIFT_R { RSHIFT_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 5 - 5:5\\] Perform subtract operation"] #[inline(always)] pub fn subtract(&self) -> SUBTRACT_R { SUBTRACT_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 4 - 4:4\\] Perform add operation"] #[inline(always)] pub fn add(&self) -> ADD_R { ADD_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 3 - 3:3\\] Loads the location of the Most Significant one bit within the result word indicated in the PKA_MSW register into bits \\[4:0\\] of the PKA_DIVMSW register - can only be used with basic PKCP operations, except for Divide, Modulo and Compare."] #[inline(always)] pub fn ms_one(&self) -> MS_ONE_R { MS_ONE_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - 2:2\\] Set to zero on write, ignore on read"] #[inline(always)] pub fn reserved3(&self) -> RESERVED3_R { RESERVED3_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - 1:1\\] Perform combined add/subtract operation"] #[inline(always)] pub fn addsub(&self) -> ADDSUB_R { ADDSUB_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - 0:0\\] Perform multiply operation"] #[inline(always)] pub fn multiply(&self) -> MULTIPLY_R { MULTIPLY_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bits 25:31 - 31:25\\] Set to zero on write, ignore on read"] #[inline(always)] pub fn reserved1(&mut self) -> RESERVED1_W { RESERVED1_W { w: self } } #[doc = "Bit 24 - 24:24\\] When written with a 1b, updating of the PKA_COMPARE, PKA_MSW and PKA_DIVMSW registers, as well as resetting the run bit is stalled beyond the point that a running operation is actually finished. Use this to allow software enough time to read results from a previous operation when the newly started operation is known to take only a short amount of time. If a result is waiting, the result registers is updated and the run bit is reset in the clock cycle following writing the stall result bit back to 0b. The Stall result function may only be used for basic PKCP operations."] #[inline(always)] pub fn stall_result(&mut self) -> STALL_RESULT_W { STALL_RESULT_W { w: self } } #[doc = "Bits 16:23 - 23:16\\] Set to zero on write, ignore on read"] #[inline(always)] pub fn reserved2(&mut self) -> RESERVED2_W { RESERVED2_W { w: self } } #[doc = "Bit 15 - 15:15\\] The host sets this bit to instruct the PKA module to begin processing the basic PKCP or complex sequencer operation. This bit is reset low automatically when the operation is complete. The complement of this bit is output as interrupts\\[1\\]. After a reset, the run bit is always set to 1b. Depending on the option, program ROM or program RAM, the following applies: Program ROM - The first sequencer instruction sets the bit to 0b. This is done immediately after the hardware reset is released. Program RAM - The sequencer must set the bit to 0b. As a valid firmware may not have been loaded, the sequencer is held in software reset after the hardware reset is released (the reset bit in PKA_SEQ_CRTL is set to 1b). After the FW image is loaded and the Reset bit is cleared, the sequencer starts to execute the FW. The first instruction clears the run bit. In both cases a few clock cycles are needed before the first instruction is executed and the run bit state has been propagated."] #[inline(always)] pub fn run(&mut self) -> RUN_W { RUN_W { w: self } } #[doc = "Bits 12:14 - 14:12\\] These bits select the complex sequencer operation to perform: 000b: None 001b: ExpMod-CRT 010b: ExpMod-ACT4 (compatible with EIP2315) 011b: ECC-ADD (if available in firmware, otherwise reserved) 100b: ExpMod-ACT2 (compatible with EIP2316) 101b: ECC-MUL (if available in firmware, otherwise reserved) 110b: ExpMod-variable 111b: ModInv (if available in firmware, otherwise reserved) The encoding of these operations is determined by sequencer firmware."] #[inline(always)] pub fn sequencer_operations(&mut self) -> SEQUENCER_OPERATIONS_W { SEQUENCER_OPERATIONS_W { w: self } } #[doc = "Bit 11 - 11:11\\] Perform copy operation"] #[inline(always)] pub fn copy(&mut self) -> COPY_W { COPY_W { w: self } } #[doc = "Bit 10 - 10:10\\] Perform compare operation"] #[inline(always)] pub fn compare(&mut self) -> COMPARE_W { COMPARE_W { w: self } } #[doc = "Bit 9 - 9:9\\] Perform modulo operation"] #[inline(always)] pub fn modulo(&mut self) -> MODULO_W { MODULO_W { w: self } } #[doc = "Bit 8 - 8:8\\] Perform divide operation"] #[inline(always)] pub fn divide(&mut self) -> DIVIDE_W { DIVIDE_W { w: self } } #[doc = "Bit 7 - 7:7\\] Perform left shift operation"] #[inline(always)] pub fn lshift(&mut self) -> LSHIFT_W { LSHIFT_W { w: self } } #[doc = "Bit 6 - 6:6\\] Perform right shift operation"] #[inline(always)] pub fn rshift(&mut self) -> RSHIFT_W { RSHIFT_W { w: self } } #[doc = "Bit 5 - 5:5\\] Perform subtract operation"] #[inline(always)] pub fn subtract(&mut self) -> SUBTRACT_W { SUBTRACT_W { w: self } } #[doc = "Bit 4 - 4:4\\] Perform add operation"] #[inline(always)] pub fn add(&mut self) -> ADD_W { ADD_W { w: self } } #[doc = "Bit 3 - 3:3\\] Loads the location of the Most Significant one bit within the result word indicated in the PKA_MSW register into bits \\[4:0\\] of the PKA_DIVMSW register - can only be used with basic PKCP operations, except for Divide, Modulo and Compare."] #[inline(always)] pub fn ms_one(&mut self) -> MS_ONE_W { MS_ONE_W { w: self } } #[doc = "Bit 2 - 2:2\\] Set to zero on write, ignore on read"] #[inline(always)] pub fn reserved3(&mut self) -> RESERVED3_W { RESERVED3_W { w: self } } #[doc = "Bit 1 - 1:1\\] Perform combined add/subtract operation"] #[inline(always)] pub fn addsub(&mut self) -> ADDSUB_W { ADDSUB_W { w: self } } #[doc = "Bit 0 - 0:0\\] Perform multiply operation"] #[inline(always)] pub fn multiply(&mut self) -> MULTIPLY_W { MULTIPLY_W { w: self } } }
ChromaLibrary.py
import mido import cv2 #Color library using dictionary from RGB to velocity value of the Launchpad MK2 from ClearLaunchpad import RemoveNotes, ClearScreen from FirstMido import FillNotes cap = cv2.imread("Velocity2RGB.png") Complete = cap.copy() while(True): Mat = cv2.inRange(cap, (0, 0, 0), (254, 254, 254)) cv2.imshow("Mat", Mat) contours, hierarchy = cv2.findContours(Mat, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) for i, c in enumerate(contours): if hierarchy[0][i][2] == -1 or hierarchy[0][i][2] > 1: if cv2.contourArea(c) < 60000 and cv2.contourArea(c) > 1000: try: cX = int(cv2.moments(c)["m10"] / cv2.moments(c)["m00"]) except ZeroDivisionError: cX = 0 try: cY = int(cv2.moments(c)["m01"] / cv2.moments(c)["m00"]) except ZeroDivisionError:
points = cv2.circle(Complete, (cX, cY), 0, (255,255,255), -1) print(cX,cY) cv2.imshow("Final", Complete) k = cv2.waitKey(32) if k == 32: break cap.release() cv2.destroyAllWindows() #Each center on the x axis is spaced out by 45 units, starting with 20 as the first center point (Left to right). min of 20 max of 335 #As for y 21 and also moves by 45 units (we can go with 20 and it will still be the same). min of 20 max of 756
cY = 0
itertools.rs
pub(crate) use decl::make_module; #[pymodule(name = "itertools")] mod decl { use crossbeam_utils::atomic::AtomicCell; use num_bigint::BigInt; use num_traits::{One, Signed, ToPrimitive, Zero}; use std::fmt; use crate::builtins::int::{self, PyInt, PyIntRef}; use crate::builtins::pybool; use crate::builtins::pytype::PyTypeRef; use crate::builtins::tuple::PyTupleRef; use crate::common::lock::{PyMutex, PyRwLock, PyRwLockWriteGuard}; use crate::common::rc::PyRc; use crate::function::{Args, FuncArgs, OptionalArg, OptionalOption}; use crate::iterator::{call_next, get_all, get_iter, get_next_object}; use crate::pyobject::{ BorrowValue, IdProtocol, IntoPyRef, PyCallable, PyObjectRc, PyObjectRef, PyObjectWeak, PyRef, PyResult, PyValue, TypeProtocol, }; use crate::vm::VirtualMachine; #[pyattr] #[pyclass(name = "chain")] #[derive(Debug)] struct PyItertoolsChain { iterables: Vec<PyObjectRef>, cur_idx: AtomicCell<usize>, cached_iter: PyRwLock<Option<PyObjectRef>>, } impl PyValue for PyItertoolsChain { fn class(vm: &VirtualMachine) -> PyTypeRef { vm.class("itertools", "chain") } } #[pyimpl] impl PyItertoolsChain { #[pyslot] fn tp_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { PyItertoolsChain { iterables: args.args, cur_idx: AtomicCell::new(0), cached_iter: PyRwLock::new(None), } .into_ref_with_type(vm, cls) } #[pymethod(name = "__next__")] fn next(&self, vm: &VirtualMachine) -> PyResult { loop { let pos = self.cur_idx.load(); if pos >= self.iterables.len() { break; } let cur_iter = if self.cached_iter.read().is_none() { // We need to call "get_iter" outside of the lock. let iter = get_iter(vm, &self.iterables[pos])?; *self.cached_iter.write() = Some(iter.clone()); iter } else if let Some(cached_iter) = (*(self.cached_iter.read())).clone() { cached_iter } else { // Someone changed cached iter to None since we checked. continue; }; // We need to call "call_next" outside of the lock. match call_next(vm, &cur_iter) { Ok(ok) => return Ok(ok), Err(err) => { if err.isinstance(&vm.ctx.exceptions.stop_iteration) { self.cur_idx.fetch_add(1); *self.cached_iter.write() = None; } else { return Err(err); } } } } Err(vm.new_stop_iteration()) } #[pymethod(name = "__iter__")] fn iter(zelf: PyRef<Self>) -> PyRef<Self> { zelf } #[pyclassmethod(name = "from_iterable")] fn from_iterable( cls: PyTypeRef, iterable: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { let it = get_iter(vm, &iterable)?; let iterables = get_all(vm, &it)?; PyItertoolsChain { iterables, cur_idx: AtomicCell::new(0), cached_iter: PyRwLock::new(None), } .into_ref_with_type(vm, cls) } } #[pyattr] #[pyclass(name = "compress")] #[derive(Debug)] struct PyItertoolsCompress { data: PyObjectRef, selector: PyObjectRef, } impl PyValue for PyItertoolsCompress { fn class(vm: &VirtualMachine) -> PyTypeRef { vm.class("itertools", "compress") } } #[pyimpl] impl PyItertoolsCompress { #[pyslot] fn tp_new( cls: PyTypeRef, data: PyObjectRef, selector: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { let data_iter = get_iter(vm, &data)?; let selector_iter = get_iter(vm, &selector)?; PyItertoolsCompress { data: data_iter, selector: selector_iter, } .into_ref_with_type(vm, cls) } #[pymethod(name = "__next__")] fn next(&self, vm: &VirtualMachine) -> PyResult { loop { let sel_obj = call_next(vm, &self.selector)?; let verdict = pybool::boolval(vm, sel_obj.clone())?; let data_obj = call_next(vm, &self.data)?; if verdict { return Ok(data_obj); } } } #[pymethod(name = "__iter__")] fn iter(zelf: PyRef<Self>) -> PyRef<Self> { zelf } } #[pyattr] #[pyclass(name = "count")] #[derive(Debug)] struct PyItertoolsCount { cur: PyRwLock<BigInt>, step: BigInt, } impl PyValue for PyItertoolsCount { fn class(vm: &VirtualMachine) -> PyTypeRef { vm.class("itertools", "count") } } #[pyimpl] impl PyItertoolsCount { #[pyslot] fn tp_new( cls: PyTypeRef, start: OptionalArg<PyIntRef>, step: OptionalArg<PyIntRef>, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { let start = match start.into_option() { Some(int) => int.borrow_value().clone(), None => BigInt::zero(), }; let step = match step.into_option() { Some(int) => int.borrow_value().clone(), None => BigInt::one(), }; PyItertoolsCount { cur: PyRwLock::new(start), step, } .into_ref_with_type(vm, cls) } #[pymethod(name = "__next__")] fn next(&self, vm: &VirtualMachine) -> PyResult<PyIntRef> { let mut cur = self.cur.write(); let result = cur.clone(); *cur += &self.step; Ok(result.into_pyref(vm)) } #[pymethod(name = "__iter__")] fn iter(zelf: PyRef<Self>) -> PyRef<Self> { zelf } } #[pyattr] #[pyclass(name = "cycle")] #[derive(Debug)] struct PyItertoolsCycle { iter: PyObjectRef, saved: PyRwLock<Vec<PyObjectRef>>, index: AtomicCell<usize>, } impl PyValue for PyItertoolsCycle { fn class(vm: &VirtualMachine) -> PyTypeRef { vm.class("itertools", "cycle") } } #[pyimpl] impl PyItertoolsCycle { #[pyslot] fn tp_new( cls: PyTypeRef, iterable: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { let iter = get_iter(vm, &iterable)?; PyItertoolsCycle { iter, saved: PyRwLock::new(Vec::new()), index: AtomicCell::new(0), } .into_ref_with_type(vm, cls) } #[pymethod(name = "__next__")] fn next(&self, vm: &VirtualMachine) -> PyResult { let item = if let Some(item) = get_next_object(vm, &self.iter)? { self.saved.write().push(item.clone()); item } else { let saved = self.saved.read(); if saved.len() == 0 { return Err(vm.new_stop_iteration()); } let last_index = self.index.fetch_add(1); if last_index >= saved.len() - 1 { self.index.store(0); } saved[last_index].clone() }; Ok(item) } #[pymethod(name = "__iter__")] fn iter(zelf: PyRef<Self>) -> PyRef<Self> { zelf } } #[pyattr] #[pyclass(name = "repeat")] #[derive(Debug)] struct PyItertoolsRepeat { object: PyObjectRef, times: Option<PyRwLock<BigInt>>, } impl PyValue for PyItertoolsRepeat { fn class(vm: &VirtualMachine) -> PyTypeRef { vm.class("itertools", "repeat") } } #[pyimpl] impl PyItertoolsRepeat { #[pyslot] fn tp_new( cls: PyTypeRef, object: PyObjectRef, times: OptionalArg<PyIntRef>, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { let times = match times.into_option() { Some(int) => Some(PyRwLock::new(int.borrow_value().clone())), None => None, }; PyItertoolsRepeat { object, times }.into_ref_with_type(vm, cls) } #[pymethod(name = "__next__")] fn next(&self, vm: &VirtualMachine) -> PyResult { if let Some(ref times) = self.times { let mut times = times.write(); if !times.is_positive() { return Err(vm.new_stop_iteration()); } *times -= 1; } Ok(self.object.clone()) } #[pymethod(name = "__iter__")] fn iter(zelf: PyRef<Self>) -> PyRef<Self> { zelf } #[pymethod(name = "__length_hint__")] fn length_hint(&self, vm: &VirtualMachine) -> PyObjectRef { match self.times { Some(ref times) => vm.ctx.new_int(times.read().clone()), None => vm.ctx.new_int(0), } } } #[pyattr] #[pyclass(name = "starmap")] #[derive(Debug)] struct PyItertoolsStarmap { function: PyObjectRef, iter: PyObjectRef, } impl PyValue for PyItertoolsStarmap { fn class(vm: &VirtualMachine) -> PyTypeRef { vm.class("itertools", "starmap") } } #[pyimpl] impl PyItertoolsStarmap { #[pyslot] fn tp_new( cls: PyTypeRef, function: PyObjectRef, iterable: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { let iter = get_iter(vm, &iterable)?; PyItertoolsStarmap { function, iter }.into_ref_with_type(vm, cls) } #[pymethod(name = "__next__")] fn next(&self, vm: &VirtualMachine) -> PyResult { let obj = call_next(vm, &self.iter)?; let function = &self.function; vm.invoke(function, vm.extract_elements(&obj)?) } #[pymethod(name = "__iter__")] fn iter(zelf: PyRef<Self>) -> PyRef<Self> { zelf } } #[pyattr] #[pyclass(name = "takewhile")] #[derive(Debug)] struct PyItertoolsTakewhile { predicate: PyObjectRef, iterable: PyObjectRef, stop_flag: AtomicCell<bool>, } impl PyValue for PyItertoolsTakewhile { fn class(vm: &VirtualMachine) -> PyTypeRef { vm.class("itertools", "takewhile") } } #[pyimpl] impl PyItertoolsTakewhile { #[pyslot] fn tp_new( cls: PyTypeRef, predicate: PyObjectRef, iterable: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { let iter = get_iter(vm, &iterable)?; PyItertoolsTakewhile { predicate, iterable: iter, stop_flag: AtomicCell::new(false), } .into_ref_with_type(vm, cls) } #[pymethod(name = "__next__")] fn next(&self, vm: &VirtualMachine) -> PyResult { if self.stop_flag.load() { return Err(vm.new_stop_iteration()); } // might be StopIteration or anything else, which is propagated upwards let obj = call_next(vm, &self.iterable)?; let predicate = &self.predicate; let verdict = vm.invoke(predicate, (obj.clone(),))?; let verdict = pybool::boolval(vm, verdict)?; if verdict { Ok(obj) } else { self.stop_flag.store(true); Err(vm.new_stop_iteration()) } } #[pymethod(name = "__iter__")] fn iter(zelf: PyRef<Self>) -> PyRef<Self> { zelf } } #[pyattr] #[pyclass(name = "dropwhile")] #[derive(Debug)] struct PyItertoolsDropwhile { predicate: PyCallable, iterable: PyObjectRef, start_flag: AtomicCell<bool>, } impl PyValue for PyItertoolsDropwhile { fn class(vm: &VirtualMachine) -> PyTypeRef { vm.class("itertools", "dropwhile") } } #[pyimpl] impl PyItertoolsDropwhile { #[pyslot] fn tp_new( cls: PyTypeRef, predicate: PyCallable, iterable: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { let iter = get_iter(vm, &iterable)?; PyItertoolsDropwhile { predicate, iterable: iter, start_flag: AtomicCell::new(false), } .into_ref_with_type(vm, cls) } #[pymethod(name = "__next__")] fn next(&self, vm: &VirtualMachine) -> PyResult { let predicate = &self.predicate; let iterable = &self.iterable; if !self.start_flag.load() { loop { let obj = call_next(vm, iterable)?; let pred = predicate.clone(); let pred_value = vm.invoke(&pred.into_object(), (obj.clone(),))?; if !pybool::boolval(vm, pred_value)? { self.start_flag.store(true); return Ok(obj); } } } call_next(vm, iterable) } #[pymethod(name = "__iter__")] fn iter(zelf: PyRef<Self>) -> PyRef<Self> { zelf } } struct GroupByState { current_value: Option<PyObjectRef>, current_key: Option<PyObjectRef>, next_group: bool, grouper: Option<PyObjectWeak<PyItertoolsGrouper>>, } impl fmt::Debug for GroupByState { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("GroupByState") .field("current_value", &self.current_value) .field("current_key", &self.current_key) .field("next_group", &self.next_group) .finish() } } impl GroupByState { fn is_current(&self, grouper: &PyItertoolsGrouperRef) -> bool { self.grouper .as_ref() .and_then(|g| g.upgrade()) .map_or(false, |ref current_grouper| grouper.is(current_grouper)) } } #[pyattr] #[pyclass(name = "groupby")] struct PyItertoolsGroupBy { iterable: PyObjectRef, key_func: Option<PyObjectRef>, state: PyMutex<GroupByState>, } impl PyValue for PyItertoolsGroupBy { fn class(vm: &VirtualMachine) -> PyTypeRef { vm.class("itertools", "groupby") } } impl fmt::Debug for PyItertoolsGroupBy { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PyItertoolsGroupBy") .field("iterable", &self.iterable) .field("key_func", &self.key_func) .field("state", &self.state.lock()) .finish() } } #[derive(FromArgs)] struct GroupByArgs { iterable: PyObjectRef, #[pyarg(any, optional)] key: OptionalOption<PyObjectRef>, } #[pyimpl] impl PyItertoolsGroupBy { #[pyslot] fn tp_new(cls: PyTypeRef, args: GroupByArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { let iter = get_iter(vm, &args.iterable)?; PyItertoolsGroupBy { iterable: iter, key_func: args.key.flatten(), state: PyMutex::new(GroupByState { current_key: None, current_value: None, next_group: false, grouper: None, }), } .into_ref_with_type(vm, cls) } #[pymethod(name = "__next__")] fn next( zelf: PyRef<Self>, vm: &VirtualMachine, ) -> PyResult<(PyObjectRef, PyItertoolsGrouperRef)> { let mut state = zelf.state.lock(); state.grouper = None; if !state.next_group { // FIXME: unnecessary clone. current_key always exist until assinging new let current_key = state.current_key.clone(); drop(state); let (value, key) = if let Some(old_key) = current_key { loop { let (value, new_key) = zelf.advance(vm)?; if !vm.bool_eq(&new_key, &old_key)? { break (value, new_key); } } } else { zelf.advance(vm)? }; state = zelf.state.lock(); state.current_value = Some(value); state.current_key = Some(key); } state.next_group = false; let grouper = PyItertoolsGrouper { groupby: zelf.clone(), } .into_ref(vm); state.grouper = Some(PyObjectRc::downgrade(&grouper.clone().into_typed_pyobj())); Ok((state.current_key.as_ref().unwrap().clone(), grouper)) } #[pymethod(name = "__iter__")] fn iter(zelf: PyRef<Self>) -> PyRef<Self> { zelf } pub(super) fn advance(&self, vm: &VirtualMachine) -> PyResult<(PyObjectRef, PyObjectRef)> { let new_value = call_next(vm, &self.iterable)?; let new_key = if let Some(ref kf) = self.key_func { vm.invoke(kf, vec![new_value.clone()])? } else { new_value.clone() }; Ok((new_value, new_key)) } } #[pyattr] #[pyclass(name = "_grouper")] #[derive(Debug)] struct PyItertoolsGrouper { groupby: PyRef<PyItertoolsGroupBy>, } type PyItertoolsGrouperRef = PyRef<PyItertoolsGrouper>; impl PyValue for PyItertoolsGrouper { fn class(vm: &VirtualMachine) -> PyTypeRef { vm.class("itertools", "_grouper") } } #[pyimpl] impl PyItertoolsGrouper { #[pymethod(name = "__next__")] fn next(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult { let old_key = { let mut state = zelf.groupby.state.lock(); if !state.is_current(&zelf) { return Err(vm.new_stop_iteration()); } // check to see if the value has already been retrieved from the iterator if let Some(val) = state.current_value.take() { return Ok(val); } state.current_key.as_ref().unwrap().clone() }; let (value, key) = zelf.groupby.advance(vm)?; if vm.bool_eq(&key, &old_key)? { Ok(value) } else { let mut state = zelf.groupby.state.lock(); state.current_value = Some(value); state.current_key = Some(key); state.next_group = true; state.grouper = None; Err(vm.new_stop_iteration()) } } #[pymethod(name = "__iter__")] fn iter(zelf: PyRef<Self>) -> PyRef<Self> { zelf } } #[pyattr] #[pyclass(name = "islice")] #[derive(Debug)] struct PyItertoolsIslice { iterable: PyObjectRef, cur: AtomicCell<usize>, next: AtomicCell<usize>, stop: Option<usize>, step: usize, } impl PyValue for PyItertoolsIslice { fn class(vm: &VirtualMachine) -> PyTypeRef { vm.class("itertools", "islice") } } fn pyobject_to_opt_usize(obj: PyObjectRef, vm: &VirtualMachine) -> Option<usize> { let is_int = obj.isinstance(&vm.ctx.types.int_type); if is_int { int::get_value(&obj).to_usize() } else { None } } #[pyimpl] impl PyItertoolsIslice { #[pyslot] fn tp_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { let (iter, start, stop, step) = match args.args.len() { 0 | 1 => { return Err(vm.new_type_error(format!( "islice expected at least 2 arguments, got {}", args.args.len() ))); } 2 => { let (iter, stop): (PyObjectRef, PyObjectRef) = args.bind(vm)?; (iter, 0usize, stop, 1usize) } _ => { let (iter, start, stop, step): ( PyObjectRef, PyObjectRef, PyObjectRef, PyObjectRef, ) = args.bind(vm)?; let start = if !vm.is_none(&start) { pyobject_to_opt_usize(start, &vm).ok_or_else(|| { vm.new_value_error( "Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize.".to_owned(), ) })? } else { 0usize }; let step = if !vm.is_none(&step) { pyobject_to_opt_usize(step, &vm).ok_or_else(|| { vm.new_value_error( "Step for islice() must be a positive integer or None.".to_owned(), ) })? } else { 1usize }; (iter, start, stop, step) } }; let stop = if !vm.is_none(&stop) { Some(pyobject_to_opt_usize(stop, &vm).ok_or_else(|| { vm.new_value_error( "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize." .to_owned(), ) })?) } else { None }; let iter = get_iter(vm, &iter)?; PyItertoolsIslice { iterable: iter, cur: AtomicCell::new(0), next: AtomicCell::new(start), stop, step, } .into_ref_with_type(vm, cls) } #[pymethod(name = "__next__")] fn next(&self, vm: &VirtualMachine) -> PyResult { while self.cur.load() < self.next.load() { call_next(vm, &self.iterable)?; self.cur.fetch_add(1); } if let Some(stop) = self.stop { if self.cur.load() >= stop { return Err(vm.new_stop_iteration()); } } let obj = call_next(vm, &self.iterable)?; self.cur.fetch_add(1); // TODO is this overflow check required? attempts to copy CPython. let (next, ovf) = self.next.load().overflowing_add(self.step); self.next.store(if ovf { self.stop.unwrap() } else { next }); Ok(obj) } #[pymethod(name = "__iter__")] fn iter(zelf: PyRef<Self>) -> PyRef<Self> { zelf } } #[pyattr] #[pyclass(name = "filterfalse")] #[derive(Debug)] struct PyItertoolsFilterFalse { predicate: PyObjectRef, iterable: PyObjectRef, } impl PyValue for PyItertoolsFilterFalse { fn class(vm: &VirtualMachine) -> PyTypeRef { vm.class("itertools", "filterfalse") } } #[pyimpl] impl PyItertoolsFilterFalse { #[pyslot] fn tp_new( cls: PyTypeRef, predicate: PyObjectRef, iterable: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { let iter = get_iter(vm, &iterable)?; PyItertoolsFilterFalse { predicate, iterable: iter, } .into_ref_with_type(vm, cls) } #[pymethod(name = "__next__")] fn next(&self, vm: &VirtualMachine) -> PyResult { let predicate = &self.predicate; let iterable = &self.iterable; loop { let obj = call_next(vm, iterable)?; let pred_value = if vm.is_none(predicate) { obj.clone() } else { vm.invoke(predicate, vec![obj.clone()])? }; if !pybool::boolval(vm, pred_value)? { return Ok(obj); } } } #[pymethod(name = "__iter__")] fn iter(zelf: PyRef<Self>) -> PyRef<Self> { zelf } } #[pyattr] #[pyclass(name = "accumulate")] #[derive(Debug)] struct PyItertoolsAccumulate { iterable: PyObjectRef, binop: PyObjectRef, acc_value: PyRwLock<Option<PyObjectRef>>, } impl PyValue for PyItertoolsAccumulate { fn class(vm: &VirtualMachine) -> PyTypeRef { vm.class("itertools", "accumulate") } } #[pyimpl] impl PyItertoolsAccumulate { #[pyslot] fn tp_new( cls: PyTypeRef, iterable: PyObjectRef, binop: OptionalArg<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>>
#[pymethod(name = "__next__")] fn next(&self, vm: &VirtualMachine) -> PyResult { let iterable = &self.iterable; let obj = call_next(vm, iterable)?; let acc_value = self.acc_value.read().clone(); let next_acc_value = match acc_value { None => obj, Some(value) => { if vm.is_none(&self.binop) { vm._add(&value, &obj)? } else { vm.invoke(&self.binop, vec![value, obj])? } } }; *self.acc_value.write() = Some(next_acc_value.clone()); Ok(next_acc_value) } #[pymethod(name = "__iter__")] fn iter(zelf: PyRef<Self>) -> PyRef<Self> { zelf } } #[derive(Debug)] struct PyItertoolsTeeData { iterable: PyObjectRef, values: PyRwLock<Vec<PyObjectRef>>, } impl PyItertoolsTeeData { fn new(iterable: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyRc<PyItertoolsTeeData>> { Ok(PyRc::new(PyItertoolsTeeData { iterable: get_iter(vm, &iterable)?, values: PyRwLock::new(vec![]), })) } fn get_item(&self, vm: &VirtualMachine, index: usize) -> PyResult { if self.values.read().len() == index { let result = call_next(vm, &self.iterable)?; self.values.write().push(result); } Ok(self.values.read()[index].clone()) } } #[pyattr] #[pyclass(name = "tee")] #[derive(Debug)] struct PyItertoolsTee { tee_data: PyRc<PyItertoolsTeeData>, index: AtomicCell<usize>, } impl PyValue for PyItertoolsTee { fn class(vm: &VirtualMachine) -> PyTypeRef { vm.class("itertools", "tee") } } #[pyimpl] impl PyItertoolsTee { fn from_iter(iterable: PyObjectRef, vm: &VirtualMachine) -> PyResult { let it = get_iter(vm, &iterable)?; if it.class().is(&PyItertoolsTee::class(vm)) { return vm.call_method(&it, "__copy__", ()); } Ok(PyItertoolsTee { tee_data: PyItertoolsTeeData::new(it, vm)?, index: AtomicCell::new(0), } .into_ref_with_type(vm, PyItertoolsTee::class(vm))? .into_object()) } // TODO: make tee() a function, rename this class to itertools._tee and make // teedata a python class #[pyslot] #[allow(clippy::new_ret_no_self)] fn tp_new( _cls: PyTypeRef, iterable: PyObjectRef, n: OptionalArg<usize>, vm: &VirtualMachine, ) -> PyResult<PyTupleRef> { let n = n.unwrap_or(2); let copyable = if iterable.class().has_attr("__copy__") { vm.call_method(&iterable, "__copy__", ())? } else { PyItertoolsTee::from_iter(iterable, vm)? }; let mut tee_vec: Vec<PyObjectRef> = Vec::with_capacity(n); for _ in 0..n { tee_vec.push(vm.call_method(&copyable, "__copy__", ())?); } Ok(PyTupleRef::with_elements(tee_vec, &vm.ctx)) } #[pymethod(name = "__copy__")] fn copy(&self, vm: &VirtualMachine) -> PyResult { Ok(PyItertoolsTee { tee_data: PyRc::clone(&self.tee_data), index: AtomicCell::new(self.index.load()), } .into_ref_with_type(vm, Self::class(vm))? .into_object()) } #[pymethod(name = "__next__")] fn next(&self, vm: &VirtualMachine) -> PyResult { let value = self.tee_data.get_item(vm, self.index.load())?; self.index.fetch_add(1); Ok(value) } #[pymethod(name = "__iter__")] fn iter(zelf: PyRef<Self>) -> PyRef<Self> { zelf } } #[pyattr] #[pyclass(name = "product")] #[derive(Debug)] struct PyItertoolsProduct { pools: Vec<Vec<PyObjectRef>>, idxs: PyRwLock<Vec<usize>>, cur: AtomicCell<usize>, stop: AtomicCell<bool>, } impl PyValue for PyItertoolsProduct { fn class(vm: &VirtualMachine) -> PyTypeRef { vm.class("itertools", "product") } } #[derive(FromArgs)] struct ProductArgs { #[pyarg(named, optional)] repeat: OptionalArg<usize>, } #[pyimpl] impl PyItertoolsProduct { #[pyslot] fn tp_new( cls: PyTypeRef, iterables: Args<PyObjectRef>, args: ProductArgs, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { let repeat = match args.repeat.into_option() { Some(i) => i, None => 1, }; let mut pools = Vec::new(); for arg in iterables.into_iter() { let it = get_iter(vm, &arg)?; let pool = get_all(vm, &it)?; pools.push(pool); } let pools = std::iter::repeat(pools) .take(repeat) .flatten() .collect::<Vec<Vec<PyObjectRef>>>(); let l = pools.len(); PyItertoolsProduct { pools, idxs: PyRwLock::new(vec![0; l]), cur: AtomicCell::new(l.wrapping_sub(1)), stop: AtomicCell::new(false), } .into_ref_with_type(vm, cls) } #[pymethod(name = "__next__")] fn next(&self, vm: &VirtualMachine) -> PyResult { // stop signal if self.stop.load() { return Err(vm.new_stop_iteration()); } let pools = &self.pools; for p in pools { if p.is_empty() { return Err(vm.new_stop_iteration()); } } let idxs = self.idxs.write(); let res = vm.ctx.new_tuple( pools .iter() .zip(idxs.iter()) .map(|(pool, idx)| pool[*idx].clone()) .collect(), ); self.update_idxs(idxs); Ok(res) } fn update_idxs(&self, mut idxs: PyRwLockWriteGuard<'_, Vec<usize>>) { if idxs.len() == 0 { self.stop.store(true); return; } let cur = self.cur.load(); let lst_idx = &self.pools[cur].len() - 1; if idxs[cur] == lst_idx { if cur == 0 { self.stop.store(true); return; } idxs[cur] = 0; self.cur.fetch_sub(1); self.update_idxs(idxs); } else { idxs[cur] += 1; self.cur.store(idxs.len() - 1); } } #[pymethod(name = "__iter__")] fn iter(zelf: PyRef<Self>) -> PyRef<Self> { zelf } } #[pyattr] #[pyclass(name = "combinations")] #[derive(Debug)] struct PyItertoolsCombinations { pool: Vec<PyObjectRef>, indices: PyRwLock<Vec<usize>>, r: AtomicCell<usize>, exhausted: AtomicCell<bool>, } impl PyValue for PyItertoolsCombinations { fn class(vm: &VirtualMachine) -> PyTypeRef { vm.class("itertools", "combinations") } } #[pyimpl] impl PyItertoolsCombinations { #[pyslot] fn tp_new( cls: PyTypeRef, iterable: PyObjectRef, r: PyIntRef, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { let iter = get_iter(vm, &iterable)?; let pool = get_all(vm, &iter)?; let r = r.borrow_value(); if r.is_negative() { return Err(vm.new_value_error("r must be non-negative".to_owned())); } let r = r.to_usize().unwrap(); let n = pool.len(); PyItertoolsCombinations { pool, indices: PyRwLock::new((0..r).collect()), r: AtomicCell::new(r), exhausted: AtomicCell::new(r > n), } .into_ref_with_type(vm, cls) } #[pymethod(name = "__iter__")] fn iter(zelf: PyRef<Self>) -> PyRef<Self> { zelf } #[pymethod(name = "__next__")] fn next(&self, vm: &VirtualMachine) -> PyResult { // stop signal if self.exhausted.load() { return Err(vm.new_stop_iteration()); } let n = self.pool.len(); let r = self.r.load(); if r == 0 { self.exhausted.store(true); return Ok(vm.ctx.new_tuple(vec![])); } let res = vm.ctx.new_tuple( self.indices .read() .iter() .map(|&i| self.pool[i].clone()) .collect(), ); let mut indices = self.indices.write(); // Scan indices right-to-left until finding one that is not at its maximum (i + n - r). let mut idx = r as isize - 1; while idx >= 0 && indices[idx as usize] == idx as usize + n - r { idx -= 1; } // If no suitable index is found, then the indices are all at // their maximum value and we're done. if idx < 0 { self.exhausted.store(true); } else { // Increment the current index which we know is not at its // maximum. Then move back to the right setting each index // to its lowest possible value (one higher than the index // to its left -- this maintains the sort order invariant). indices[idx as usize] += 1; for j in idx as usize + 1..r { indices[j] = indices[j - 1] + 1; } } Ok(res) } } #[pyattr] #[pyclass(name = "combinations_with_replacement")] #[derive(Debug)] struct PyItertoolsCombinationsWithReplacement { pool: Vec<PyObjectRef>, indices: PyRwLock<Vec<usize>>, r: AtomicCell<usize>, exhausted: AtomicCell<bool>, } impl PyValue for PyItertoolsCombinationsWithReplacement { fn class(vm: &VirtualMachine) -> PyTypeRef { vm.class("itertools", "combinations_with_replacement") } } #[pyimpl] impl PyItertoolsCombinationsWithReplacement { #[pyslot] fn tp_new( cls: PyTypeRef, iterable: PyObjectRef, r: PyIntRef, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { let iter = get_iter(vm, &iterable)?; let pool = get_all(vm, &iter)?; let r = r.borrow_value(); if r.is_negative() { return Err(vm.new_value_error("r must be non-negative".to_owned())); } let r = r.to_usize().unwrap(); let n = pool.len(); PyItertoolsCombinationsWithReplacement { pool, indices: PyRwLock::new(vec![0; r]), r: AtomicCell::new(r), exhausted: AtomicCell::new(n == 0 && r > 0), } .into_ref_with_type(vm, cls) } #[pymethod(name = "__iter__")] fn iter(zelf: PyRef<Self>) -> PyRef<Self> { zelf } #[pymethod(name = "__next__")] fn next(&self, vm: &VirtualMachine) -> PyResult { // stop signal if self.exhausted.load() { return Err(vm.new_stop_iteration()); } let n = self.pool.len(); let r = self.r.load(); if r == 0 { self.exhausted.store(true); return Ok(vm.ctx.new_tuple(vec![])); } let mut indices = self.indices.write(); let res = vm .ctx .new_tuple(indices.iter().map(|&i| self.pool[i].clone()).collect()); // Scan indices right-to-left until finding one that is not at its maximum (i + n - r). let mut idx = r as isize - 1; while idx >= 0 && indices[idx as usize] == n - 1 { idx -= 1; } // If no suitable index is found, then the indices are all at // their maximum value and we're done. if idx < 0 { self.exhausted.store(true); } else { let index = indices[idx as usize] + 1; // Increment the current index which we know is not at its // maximum. Then set all to the right to the same value. for j in idx as usize..r { indices[j as usize] = index as usize; } } Ok(res) } } #[pyattr] #[pyclass(name = "permutations")] #[derive(Debug)] struct PyItertoolsPermutations { pool: Vec<PyObjectRef>, // Collected input iterable indices: PyRwLock<Vec<usize>>, // One index per element in pool cycles: PyRwLock<Vec<usize>>, // One rollover counter per element in the result result: PyRwLock<Option<Vec<usize>>>, // Indexes of the most recently returned result r: AtomicCell<usize>, // Size of result tuple exhausted: AtomicCell<bool>, // Set when the iterator is exhausted } impl PyValue for PyItertoolsPermutations { fn class(vm: &VirtualMachine) -> PyTypeRef { vm.class("itertools", "permutations") } } #[pyimpl] impl PyItertoolsPermutations { #[pyslot] fn tp_new( cls: PyTypeRef, iterable: PyObjectRef, r: OptionalOption<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { let iter = get_iter(vm, &iterable)?; let pool = get_all(vm, &iter)?; let n = pool.len(); // If r is not provided, r == n. If provided, r must be a positive integer, or None. // If None, it behaves the same as if it was not provided. let r = match r.flatten() { Some(r) => { let val = r .payload::<PyInt>() .ok_or_else(|| vm.new_type_error("Expected int as r".to_owned()))? .borrow_value(); if val.is_negative() { return Err(vm.new_value_error("r must be non-negative".to_owned())); } val.to_usize().unwrap() } None => n, }; PyItertoolsPermutations { pool, indices: PyRwLock::new((0..n).collect()), cycles: PyRwLock::new((0..r.min(n)).map(|i| n - i).collect()), result: PyRwLock::new(None), r: AtomicCell::new(r), exhausted: AtomicCell::new(r > n), } .into_ref_with_type(vm, cls) } #[pymethod(name = "__iter__")] fn iter(zelf: PyRef<Self>) -> PyRef<Self> { zelf } #[pymethod(name = "__next__")] fn next(&self, vm: &VirtualMachine) -> PyResult { // stop signal if self.exhausted.load() { return Err(vm.new_stop_iteration()); } let n = self.pool.len(); let r = self.r.load(); if n == 0 { self.exhausted.store(true); return Ok(vm.ctx.new_tuple(vec![])); } let mut result = self.result.write(); if let Some(ref mut result) = *result { let mut indices = self.indices.write(); let mut cycles = self.cycles.write(); let mut sentinel = false; // Decrement rightmost cycle, moving leftward upon zero rollover for i in (0..r).rev() { cycles[i] -= 1; if cycles[i] == 0 { // rotation: indices[i:] = indices[i+1:] + indices[i:i+1] let index = indices[i]; for j in i..n - 1 { indices[j] = indices[j + 1]; } indices[n - 1] = index; cycles[i] = n - i; } else { let j = cycles[i]; indices.swap(i, n - j); for k in i..r { // start with i, the leftmost element that changed // yield tuple(pool[k] for k in indices[:r]) result[k] = indices[k]; } sentinel = true; break; } } if !sentinel { self.exhausted.store(true); return Err(vm.new_stop_iteration()); } } else { // On the first pass, initialize result tuple using the indices *result = Some((0..r).collect()); } Ok(vm.ctx.new_tuple( result .as_ref() .unwrap() .iter() .map(|&i| self.pool[i].clone()) .collect(), )) } } #[pyattr] #[pyclass(name = "zip_longest")] #[derive(Debug)] struct PyItertoolsZipLongest { iterators: Vec<PyObjectRef>, fillvalue: PyObjectRef, } impl PyValue for PyItertoolsZipLongest { fn class(vm: &VirtualMachine) -> PyTypeRef { vm.class("itertools", "zip_longest") } } #[derive(FromArgs)] struct ZiplongestArgs { #[pyarg(named, optional)] fillvalue: OptionalArg<PyObjectRef>, } #[pyimpl] impl PyItertoolsZipLongest { #[pyslot] fn tp_new( cls: PyTypeRef, iterables: Args, args: ZiplongestArgs, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { let fillvalue = args.fillvalue.unwrap_or_none(vm); let iterators = iterables .into_iter() .map(|iterable| get_iter(vm, &iterable)) .collect::<Result<Vec<_>, _>>()?; PyItertoolsZipLongest { iterators, fillvalue, } .into_ref_with_type(vm, cls) } #[pymethod(name = "__next__")] fn next(&self, vm: &VirtualMachine) -> PyResult { if self.iterators.is_empty() { Err(vm.new_stop_iteration()) } else { let mut result: Vec<PyObjectRef> = Vec::new(); let mut numactive = self.iterators.len(); for idx in 0..self.iterators.len() { let next_obj = match call_next(vm, &self.iterators[idx]) { Ok(obj) => obj, Err(err) => { if !err.isinstance(&vm.ctx.exceptions.stop_iteration) { return Err(err); } numactive -= 1; if numactive == 0 { return Err(vm.new_stop_iteration()); } self.fillvalue.clone() } }; result.push(next_obj); } Ok(vm.ctx.new_tuple(result)) } } #[pymethod(name = "__iter__")] fn iter(zelf: PyRef<Self>) -> PyRef<Self> { zelf } } }
{ let iter = get_iter(vm, &iterable)?; PyItertoolsAccumulate { iterable: iter, binop: binop.unwrap_or_none(vm), acc_value: PyRwLock::new(None), } .into_ref_with_type(vm, cls) }
UniversalReceivers.spec.ts
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; import { ethers } from "hardhat"; import { BasicUniversalReceiver, BasicUniversalReceiver__factory, UniversalProfile__factory, UniversalReceiverAddressStore, UniversalReceiverAddressStore__factory, UniversalReceiverTester, UniversalReceiverTester__factory, } from "../../types"; import { ERC725YKeys } from "../../constants"; import { ERC777TokensRecipient as TOKENS_RECIPIENT_INTERFACE_HASH } from "../utils/helpers"; describe("Receivers", () => { let uni: BasicUniversalReceiver; let accounts: SignerWithAddress[] = []; let signer: SignerWithAddress; beforeAll(async () => { accounts = await ethers.getSigners(); signer = accounts[1]; }); beforeEach(async () => { uni = await new BasicUniversalReceiver__factory(signer).deploy(); }); it("Can check for implementing interface", async () => { let tx = await uni.universalReceiver(TOKENS_RECIPIENT_INTERFACE_HASH, "0x"); let txReceipt = await tx.wait(); let result = await uni.callStatic.universalReceiver( TOKENS_RECIPIENT_INTERFACE_HASH, "0x" ); expect(result).toEqual(TOKENS_RECIPIENT_INTERFACE_HASH); }); it("Contract can check for implementing interface with Bytes32", async () => { let checker: UniversalReceiverTester = await new UniversalReceiverTester__factory(signer).deploy(); let tx = await checker.functions.checkImplementation( uni.address, TOKENS_RECIPIENT_INTERFACE_HASH ); let txReceipt = await tx.wait(); let res = await checker.callStatic.checkImplementation( uni.address, TOKENS_RECIPIENT_INTERFACE_HASH ); expect(res).toBeTruthy(); }); it("Contract can check for implementing interface with Low Level call", async () => { let checker = await new UniversalReceiverTester__factory(signer).deploy(); let tx = await checker.lowLevelCheckImplementation( uni.address, TOKENS_RECIPIENT_INTERFACE_HASH ); let txReceipt = await tx.wait(); let res = await checker.callStatic.lowLevelCheckImplementation( uni.address, TOKENS_RECIPIENT_INTERFACE_HASH ); expect(res).toBeTruthy(); }); it("Use delegate and test if it can store addresses", async () => { const signerAddress = accounts[1]; let account = await new UniversalProfile__factory(signer).deploy( signer.address ); let checker = await new UniversalReceiverTester__factory(signer).deploy(); let checker2 = await new UniversalReceiverTester__factory(signer).deploy(); let checker3 = await new UniversalReceiverTester__factory(signer).deploy(); let delegate: UniversalReceiverAddressStore = await new UniversalReceiverAddressStore__factory(signer).deploy( account.address ); // set uni receiver delegate await account .connect(signerAddress) .setData( [ERC725YKeys.LSP0["LSP1UniversalReceiverDelegate"]], [delegate.address] ); await checker.lowLevelCheckImplementation( account.address, TOKENS_RECIPIENT_INTERFACE_HASH ); await checker.checkImplementation( account.address, TOKENS_RECIPIENT_INTERFACE_HASH ); await checker2.checkImplementation( account.address, TOKENS_RECIPIENT_INTERFACE_HASH ); await checker3.checkImplementation( account.address, TOKENS_RECIPIENT_INTERFACE_HASH ); expect( await delegate.callStatic.containsAddress(checker.address) ).toBeTruthy(); expect( await delegate.callStatic.containsAddress(checker2.address) ).toBeTruthy(); expect( await delegate.callStatic.containsAddress(checker3.address)
expect( await (await delegate.callStatic.getIndex(checker2.address)).toNumber() ).toEqual(1); }); });
).toBeTruthy();
client.rs
use std::collections::BTreeSet; use std::sync::Arc; use futures::future::{select_all, FutureExt}; use seabird::proto::seabird::{ BackendInfoRequest, BackendInfoResponse, CommandsRequest, CommandsResponse, CoreInfoRequest, CoreInfoResponse, ListBackendsRequest, ListBackendsResponse, }; use tokio::sync::{broadcast, Mutex}; use crate::prelude::*; #[derive(Clone, Debug)] pub struct ClientConfig { pub inner: seabird::ClientConfig, pub enabled_plugins: BTreeSet<String>, pub disabled_plugins: BTreeSet<String>, pub db_url: String, pub db_pool_size: u32, } impl ClientConfig { pub fn new( url: String, token: String, db_url: String, db_pool_size: u32, enabled_plugins: BTreeSet<String>, disabled_plugins: BTreeSet<String>, ) -> Self { ClientConfig { inner: seabird::ClientConfig { url, token }, db_url, db_pool_size, enabled_plugins, disabled_plugins, } } } impl ClientConfig { /// If enabled_plugins is not specified or is empty, all plugins are allowed /// to be loaded, otherwise only specified plugins will be loaded. /// /// Any plugins in disabled_plugins which were otherwise enabled, will be /// skipped. /// /// Note that this function does not check for plugin validity, only if it /// would be enabled based on the name. pub fn plugin_enabled(&self, plugin_name: &str) -> bool { if self.disabled_plugins.contains(plugin_name) { return false; } // If enabled_plugins has no values, all are enabled. self.enabled_plugins.is_empty() || self.enabled_plugins.contains(plugin_name) } } // Client represents the running bot. #[derive(Debug)] pub struct Client { config: ClientConfig, inner: Mutex<seabird::Client>, db_pool: sqlx::PgPool, broadcast: broadcast::Sender<Arc<Context>>, } impl Client { pub async fn perform_action( &self, channel_id: impl Into<String>, text: impl Into<String>, ) -> Result<()> { self.inner .lock() .await .perform_action(channel_id, text, None) .await?; Ok(()) } pub async fn perform_private_action( &self, user_id: impl Into<String>, text: impl Into<String>, ) -> Result<()> { self.inner .lock() .await .perform_private_action(user_id, text, None) .await?; Ok(()) } pub async fn send_message( &self, channel_id: impl Into<String>, text: impl Into<String>, ) -> Result<()> { self.inner .lock() .await .send_message(channel_id, text, None) .await?; Ok(()) } pub async fn send_private_message( &self, user_id: impl Into<String>, text: impl Into<String>, ) -> Result<()> { self.inner .lock() .await .send_private_message(user_id, text, None) .await?; Ok(()) } pub async fn list_backends(&self) -> Result<ListBackendsResponse> { Ok(self .inner .lock() .await .inner_mut_ref() .list_backends(ListBackendsRequest {}) .await? .into_inner()) } pub async fn get_core_info(&self) -> Result<CoreInfoResponse> { Ok(self .inner .lock() .await .inner_mut_ref() .get_core_info(CoreInfoRequest {}) .await? .into_inner()) } pub async fn get_backend_info(&self, backend_id: String) -> Result<BackendInfoResponse> { Ok(self .inner .lock() .await .inner_mut_ref() .get_backend_info(BackendInfoRequest { backend_id }) .await? .into_inner()) } pub async fn registered_commands(&self) -> Result<CommandsResponse> { Ok(self .inner .lock() .await .inner_mut_ref() .registered_commands(CommandsRequest {}) .await? .into_inner()) } pub fn subscribe(&self) -> broadcast::Receiver<Arc<Context>> { self.broadcast.subscribe() } pub fn get_config(&self) -> &ClientConfig { &self.config } } impl Client { pub async fn new(config: ClientConfig) -> Result<Self> { let db_pool = sqlx::postgres::PgPoolOptions::new() .max_connections(config.db_pool_size) .connect(&config.db_url) .await?; crate::migrations::run(&db_pool).await?; let seabird_client = seabird::Client::new(config.inner.clone()).await?; let (sender, _) = broadcast::channel(100); Ok(Client { config, broadcast: sender, db_pool, inner: Mutex::new(seabird_client), }) } async fn reader_task( self: &Arc<Self>, commands: HashMap<String, crate::plugin::CommandMetadata>, ) -> Result<()> { let mut stream = self .inner .lock() .await .inner_mut_ref() .stream_events(proto::StreamEventsRequest { commands }) .await? .into_inner(); while let Some(event) = stream.next().await.transpose()? { info!("<-- {:?}", event); // Create an Arc out of our context to make it easier for async // plugins. if let Some(inner) = event.inner { let ctx = Arc::new(Context::new(self.clone(), inner)); self.broadcast .send(ctx) .map_err(|_| format_err!("failed to broadcast incoming event"))?; } else { warn!("Got SeabirdEvent missing an inner"); } } Err(format_err!("reader_task exited early")) } pub async fn run(self) -> Result<()> { let client = Arc::new(self); // TODO: it's unfortunately easiest to load plugins in run, even though // it would make more sense in new(). let plugin_meta = crate::plugin::load(client.clone()).await?; let mut plugin_tasks = Vec::new(); let mut plugin_commands = HashMap::new(); for meta in plugin_meta.into_iter() { plugin_tasks.push(meta.handle); for command in meta.commands.into_iter() { if plugin_commands.contains_key(&command.name) { anyhow::bail!("Duplicate commands defined with the name {}", command.name); } plugin_commands.insert(command.name.clone(), command); } } // There's not a great way to do this... if anything exits, it's // considered an error. If they returned an error, display that, // otherwise, throw a generic error. futures::select!( reader_res = client.reader_task(plugin_commands).fuse() => { reader_res?; anyhow::bail!("Reader task exited early"); }, (task, _, _) = select_all(plugin_tasks).fuse() => { task??; anyhow::bail!("A plugin task exited early"); }, ); } } #[derive(Clone, Debug)] pub struct Context { pub raw_event: SeabirdEvent, client: Arc<Client>, } impl Context { fn new(client: Arc<Client>, raw_event: SeabirdEvent) -> Self { Context { raw_event, client } } pub fn as_event(&self) -> Result<Event<'_>> { self.try_into() } pub fn is_private(&self) -> bool { if let SeabirdEvent::PrivateMessage(_) = self.raw_event { return true; } else { return false; } } pub fn sender(&self) -> Option<&str> { match &self.raw_event { SeabirdEvent::Action(message) => message .source .as_ref() .and_then(|s| s.user.as_ref().map(|u| u.display_name.as_str())), SeabirdEvent::Message(message) => message .source .as_ref() .and_then(|s| s.user.as_ref().map(|u| u.display_name.as_str())), SeabirdEvent::Command(message) => message .source .as_ref() .and_then(|s| s.user.as_ref().map(|u| u.display_name.as_str())), SeabirdEvent::Mention(message) => message .source .as_ref() .and_then(|s| s.user.as_ref().map(|u| u.display_name.as_str())), // NOTE: PrivateMessage and PrivateAction are in a different format SeabirdEvent::PrivateAction(message) => { message.source.as_ref().map(|u| u.display_name.as_str()) } SeabirdEvent::PrivateMessage(message) => { message.source.as_ref().map(|u| u.display_name.as_str()) } // Seabird-sent events SeabirdEvent::SendMessage(message) => Some(message.sender.as_str()), SeabirdEvent::SendPrivateMessage(message) => Some(message.sender.as_str()), SeabirdEvent::PerformAction(message) => Some(message.sender.as_str()), SeabirdEvent::PerformPrivateAction(message) => Some(message.sender.as_str()), } } pub async fn list_backends(&self) -> Result<ListBackendsResponse>
pub async fn get_core_info(&self) -> Result<CoreInfoResponse> { self.client.get_core_info().await } pub async fn get_backend_info(&self, backend_id: String) -> Result<BackendInfoResponse> { self.client.get_backend_info(backend_id).await } pub async fn registered_commands(&self) -> Result<CommandsResponse> { self.client.registered_commands().await } pub async fn mention_reply(&self, msg: &str) -> Result<()> { let sender = self .sender() .ok_or_else(|| format_err!("Tried to get the sender of an event without one"))?; // If it's a private message, we shouldn't send the prefix. if self.is_private() { self.reply(msg).await } else { self.reply(&format!("{}: {}", sender, msg)[..]).await } } pub async fn reply(&self, text: &str) -> Result<()> { match &self.raw_event { SeabirdEvent::Action(message) => { self.client .send_message( message .source .as_ref() .map(|s| s.channel_id.as_str()) .ok_or_else(|| format_err!("message missing channel_id"))?, text, ) .await } SeabirdEvent::Message(message) => { self.client .send_message( message .source .as_ref() .map(|s| s.channel_id.as_str()) .ok_or_else(|| format_err!("message missing channel_id"))?, text, ) .await } SeabirdEvent::Command(message) => { self.client .send_message( message .source .as_ref() .map(|s| s.channel_id.as_str()) .ok_or_else(|| format_err!("message missing channel_id"))?, text, ) .await } SeabirdEvent::Mention(message) => { self.client .send_message( message .source .as_ref() .map(|s| s.channel_id.as_str()) .ok_or_else(|| format_err!("message missing channel_id"))?, text, ) .await } SeabirdEvent::PrivateAction(message) => { self.client .send_private_message( message .source .as_ref() .map(|u| u.id.as_str()) .ok_or_else(|| format_err!("message missing user_id"))?, text, ) .await } SeabirdEvent::PrivateMessage(message) => { self.client .send_private_message( message .source .as_ref() .map(|u| u.id.as_str()) .ok_or_else(|| format_err!("message missing user_id"))?, text, ) .await } SeabirdEvent::SendMessage(_) | SeabirdEvent::SendPrivateMessage(_) | SeabirdEvent::PerformAction(_) | SeabirdEvent::PerformPrivateAction(_) => Err(format_err!("cannot reply to self")), } } pub async fn action_reply(&self, text: &str) -> Result<()> { match &self.raw_event { SeabirdEvent::Action(message) => { self.client .perform_action( message .source .as_ref() .map(|s| s.channel_id.as_str()) .ok_or_else(|| format_err!("message missing channel_id"))?, text, ) .await } SeabirdEvent::Message(message) => { self.client .perform_action( message .source .as_ref() .map(|s| s.channel_id.as_str()) .ok_or_else(|| format_err!("message missing channel_id"))?, text, ) .await } SeabirdEvent::Command(message) => { self.client .perform_action( message .source .as_ref() .map(|s| s.channel_id.as_str()) .ok_or_else(|| format_err!("message missing channel_id"))?, text, ) .await } SeabirdEvent::Mention(message) => { self.client .perform_action( message .source .as_ref() .map(|s| s.channel_id.as_str()) .ok_or_else(|| format_err!("message missing channel_id"))?, text, ) .await } SeabirdEvent::PrivateAction(message) => { self.client .perform_private_action( message .source .as_ref() .map(|u| u.id.as_str()) .ok_or_else(|| format_err!("message missing user_id"))?, text, ) .await } SeabirdEvent::PrivateMessage(message) => { self.client .perform_private_action( message .source .as_ref() .map(|u| u.id.as_str()) .ok_or_else(|| format_err!("message missing user_id"))?, text, ) .await } SeabirdEvent::SendMessage(_) | SeabirdEvent::SendPrivateMessage(_) | SeabirdEvent::PerformAction(_) | SeabirdEvent::PerformPrivateAction(_) => Err(format_err!("cannot reply to self")), } } pub fn get_db(&self) -> sqlx::PgPool { self.client.db_pool.clone() } } #[non_exhaustive] pub enum Event<'a> { // PRIVMSG target :msg Message(&'a str, &'a str), PrivateMessage(&'a str, &'a str), // PRIVMSG somewhere :!command arg Command(&'a str, Option<&'a str>), // PRIVMSG somewhere :seabird: arg Mention(&'a str), Unknown(&'a SeabirdEvent), } impl<'a> TryFrom<&'a Context> for Event<'a> { type Error = anyhow::Error; fn try_from(ctx: &'a Context) -> Result<Self> { Ok(match &ctx.raw_event { SeabirdEvent::Message(msg) => Event::Message( ctx.sender() .ok_or_else(|| format_err!("event missing sender"))?, msg.text.as_str(), ), SeabirdEvent::PrivateMessage(msg) => Event::PrivateMessage( ctx.sender() .ok_or_else(|| format_err!("event missing sender"))?, msg.text.as_str(), ), SeabirdEvent::Command(msg) => { let inner = msg.arg.trim(); Event::Command( msg.command.as_str(), if inner.is_empty() { None } else { Some(inner) }, ) } SeabirdEvent::Mention(msg) => Event::Mention(msg.text.as_str()), #[allow(unreachable_patterns)] event => Event::Unknown(event), }) } }
{ self.client.list_backends().await }
app.rs
use yew::{html, Component, ComponentLink, Html, ShouldRender}; use yew::services::console::ConsoleService; use yew::services::fetch::{FetchService, FetchTask, Response, Request}; use yew::format::Nothing; // use yew::{html, Component, ComponentLink, Html, ShouldRender}; // use http::Request; use failure::Error; pub struct App { value: i32, fetch_value: String, fetcher: FetchService, console: ConsoleService, link: ComponentLink<Self>, task: Option<FetchTask>, backend: String, } pub enum Mode { On, Off, } impl ToString for Mode { fn to_string(&self) -> String
} pub enum Msg { Light(Mode), Update(String), Error(String), } impl Component for App { // Some details omitted. Explore the examples to see more. type Message = Msg; type Properties = (); fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self { let value = 0; let fetch_value = "".to_string(); let fetcher = FetchService::new(); let console = ConsoleService::new(); let task = None; let backend = "http://192.168.0.102:3030".to_string(); App { value, fetch_value, fetcher, console, link, task, backend } } fn update(&mut self, msg: Self::Message) -> ShouldRender { match msg { Msg::Light(mode) => { let url = format!("{}/light/{}", self.backend, mode.to_string()); let request = Request::post(url) .body(Nothing) .expect("Failed to build request"); let callback = self.link.callback( |response: Response<Result<String, Error>>| { let mut console = ConsoleService::new(); console.log("Hello fetching!!"); let (meta, result) = response.into_parts(); match result { Ok(body) => { if meta.status.is_success() { Msg::Update(body) } else { console.log(&format!( "Error in status: {:?}", meta.status)); Msg::Error(meta.status.to_string()) } }, Err(e) => { console.log("Error in response!!"); Msg::Error(format!( "Error in response: {:?}", e.backtrace())) }, } } ); self.console.log("Creating fetch task."); self.task = Some(self.fetcher.fetch(request, callback)); false } Msg::Update(resp) => { self.fetch_value = format!("Fetched string: {}", resp); true } Msg::Error(resp) => { self.fetch_value = format!("Error fetching from backend: {}", resp); true } } } fn view(&self) -> Html { let turn_on = self.link.callback(|_| Msg::Light(Mode::On)); let turn_off = self.link.callback(|_| Msg::Light(Mode::Off)); html! { <div class="LightsWrapper"> <section class="lights"> <header class="header"> <h1>{ "Lights!" }</h1> </header> </section> <section class="button1"> <button onclick=turn_on >{ "Turn me on!" }</button> </section> <section class="button2"> <button onclick=turn_off >{ "Turn me off!" }</button> </section> <section class="output"> <p>{ self.view_output() }</p> </section> </div> } } } impl App { fn view_output(&self) -> Html { let mut output = "Count: ".to_string(); output.push_str(&self.value.to_string()); let fetch_output = &self.fetch_value; html! { <div> <p> {output} </p> <p> {fetch_output} </p> </div> } } } // fn main() { // yew::start_app::<App>(); // }
{ match self { Mode::On => "on", Mode::Off => "off", }.to_string() }
integration_test.go
/* Copyright 2019 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 http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* This file holds tests for the in-memory fake for comparing it against a real Cloud Spanner. By default it uses the Spanner client against the in-memory fake; set the -test_db flag to "projects/P/instances/I/databases/D" to make it use a real Cloud Spanner database instead. You may need to provide -timeout=5m too. */ package spannertest import ( "context" "flag" "fmt" "reflect" "sort" "testing" "time" "cloud.google.com/go/civil" "cloud.google.com/go/spanner" dbadmin "cloud.google.com/go/spanner/admin/database/apiv1" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" dbadminpb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" spannerpb "google.golang.org/genproto/googleapis/spanner/v1" structpb "google.golang.org/protobuf/types/known/structpb" ) var testDBFlag = flag.String("test_db", "", "Fully-qualified database name to test against; empty means use an in-memory fake.") func dbName() string { if *testDBFlag != "" { return *testDBFlag } return "projects/fake-proj/instances/fake-instance/databases/fake-db" } func makeClient(t *testing.T) (*spanner.Client, *dbadmin.DatabaseAdminClient, func()) { // Despite the docs, this context is also used for auth, // so it needs to be long-lived. ctx := context.Background() if *testDBFlag != "" { t.Logf("Using real Spanner DB %s", *testDBFlag) dialOpt := option.WithGRPCDialOption(grpc.WithTimeout(5 * time.Second)) client, err := spanner.NewClient(ctx, *testDBFlag, dialOpt) if err != nil { t.Fatalf("Connecting to %s: %v", *testDBFlag, err) } adminClient, err := dbadmin.NewDatabaseAdminClient(ctx, dialOpt) if err != nil { client.Close() t.Fatalf("Connecting DB admin client: %v", err) } return client, adminClient, func() { client.Close(); adminClient.Close() } } // Don't use SPANNER_EMULATOR_HOST because we need the raw connection for // the database admin client anyway. t.Logf("Using in-memory fake Spanner DB") srv, err := NewServer("localhost:0") if err != nil { t.Fatalf("Starting in-memory fake: %v", err) } srv.SetLogger(t.Logf) dialCtx, cancel := context.WithTimeout(ctx, 1*time.Second) defer cancel() conn, err := grpc.DialContext(dialCtx, srv.Addr, grpc.WithInsecure()) if err != nil { srv.Close() t.Fatalf("Dialing in-memory fake: %v", err) } client, err := spanner.NewClient(ctx, dbName(), option.WithGRPCConn(conn)) if err != nil { srv.Close() t.Fatalf("Connecting to in-memory fake: %v", err) } adminClient, err := dbadmin.NewDatabaseAdminClient(ctx, option.WithGRPCConn(conn)) if err != nil { srv.Close() t.Fatalf("Connecting to in-memory fake DB admin: %v", err) } return client, adminClient, func() { client.Close() adminClient.Close() conn.Close() srv.Close() } } func TestIntegration_SpannerBasics(t *testing.T) { client, adminClient, cleanup := makeClient(t) defer cleanup() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() // Do a trivial query to verify the connection works. it := client.Single().Query(ctx, spanner.NewStatement("SELECT 1")) row, err := it.Next() if err != nil { t.Fatalf("Getting first row of trivial query: %v", err) } var value int64 if err := row.Column(0, &value); err != nil { t.Fatalf("Decoding row data from trivial query: %v", err) } if value != 1 { t.Errorf("Trivial query gave %d, want 1", value) } // There shouldn't be a next row. _, err = it.Next() if err != iterator.Done { t.Errorf("Reading second row of trivial query gave %v, want iterator.Done", err) } it.Stop() // Drop any previous test table/index, and make a fresh one in a few stages. const tableName = "Characters" err = updateDDL(t, adminClient, "DROP INDEX AgeIndex") // NotFound is an acceptable failure mode here. if st, _ := status.FromError(err); st.Code() == codes.NotFound { err = nil } if err != nil { t.Fatalf("Dropping old index: %v", err) } if err := dropTable(t, adminClient, tableName); err != nil { t.Fatal(err) } err = updateDDL(t, adminClient, `CREATE TABLE `+tableName+` ( FirstName STRING(20) NOT NULL, LastName STRING(20) NOT NULL, Alias STRING(MAX), ) PRIMARY KEY (FirstName, LastName)`) if err != nil { t.Fatalf("Setting up fresh table: %v", err) } err = updateDDL(t, adminClient, `ALTER TABLE `+tableName+` ADD COLUMN Age INT64`, `CREATE INDEX AgeIndex ON `+tableName+` (Age DESC)`) if err != nil { t.Fatalf("Adding new column: %v", err) } // Insert some data. _, err = client.Apply(ctx, []*spanner.Mutation{ spanner.Insert(tableName, []string{"FirstName", "LastName", "Alias", "Age"}, []interface{}{"Steve", "Rogers", "Captain America", 101}), spanner.Insert(tableName, []string{"LastName", "FirstName", "Age", "Alias"}, []interface{}{"Romanoff", "Natasha", 35, "Black Widow"}), spanner.Insert(tableName, []string{"Age", "Alias", "FirstName", "LastName"}, []interface{}{49, "Iron Man", "Tony", "Stark"}), spanner.Insert(tableName, []string{"FirstName", "Alias", "LastName"}, // no Age []interface{}{"Clark", "Superman", "Kent"}), // Two rows with the same value in one column, // but with distinct primary keys. spanner.Insert(tableName, []string{"FirstName", "LastName", "Alias"}, []interface{}{"Peter", "Parker", "Spider-Man"}), spanner.Insert(tableName, []string{"FirstName", "LastName", "Alias"}, []interface{}{"Peter", "Quill", "Star-Lord"}), }) if err != nil { t.Fatalf("Applying mutations: %v", err) } // Delete some data. _, err = client.Apply(ctx, []*spanner.Mutation{ // Whoops. DC, not MCU. spanner.Delete(tableName, spanner.Key{"Clark", "Kent"}), }) if err != nil { t.Fatalf("Applying mutations: %v", err) } // Read a single row. row, err = client.Single().ReadRow(ctx, tableName, spanner.Key{"Tony", "Stark"}, []string{"Alias", "Age"}) if err != nil { t.Fatalf("Reading single row: %v", err) } var alias string var age int64 if err := row.Columns(&alias, &age); err != nil { t.Fatalf("Decoding single row: %v", err) } if alias != "Iron Man" || age != 49 { t.Errorf(`Single row read gave (%q, %d), want ("Iron Man", 49)`, alias, age) } // Read all rows, and do a local age sum. rows := client.Single().Read(ctx, tableName, spanner.AllKeys(), []string{"Age"}) var ageSum int64 err = rows.Do(func(row *spanner.Row) error { var age spanner.NullInt64 if err := row.Columns(&age); err != nil { return err } if age.Valid { ageSum += age.Int64 } return nil }) if err != nil { t.Fatalf("Iterating over all row read: %v", err) } if want := int64(101 + 35 + 49); ageSum != want { t.Errorf("Age sum after iterating over all rows = %d, want %d", ageSum, want) } // Do a more complex query to find the aliases of the two oldest non-centenarian characters. stmt := spanner.NewStatement(`SELECT Alias FROM ` + tableName + ` WHERE Age < @ageLimit AND Alias IS NOT NULL ORDER BY Age DESC LIMIT @limit`) stmt.Params = map[string]interface{}{ "ageLimit": 100, "limit": 2, } rows = client.Single().Query(ctx, stmt) var oldFolk []string err = rows.Do(func(row *spanner.Row) error { var alias string if err := row.Columns(&alias); err != nil { return err } oldFolk = append(oldFolk, alias) return nil }) if err != nil { t.Fatalf("Iterating over complex query: %v", err) } if want := []string{"Iron Man", "Black Widow"}; !reflect.DeepEqual(oldFolk, want) { t.Errorf("Complex query results = %v, want %v", oldFolk, want) } // Apply an update. _, err = client.Apply(ctx, []*spanner.Mutation{ spanner.Update(tableName, []string{"FirstName", "LastName", "Age"}, []interface{}{"Steve", "Rogers", 102}), }) if err != nil { t.Fatalf("Applying mutations: %v", err) } row, err = client.Single().ReadRow(ctx, tableName, spanner.Key{"Steve", "Rogers"}, []string{"Age"}) if err != nil { t.Fatalf("Reading single row: %v", err) } if err := row.Columns(&age); err != nil { t.Fatalf("Decoding single row: %v", err) } if age != 102 { t.Errorf("After updating Captain America, age = %d, want 102", age) } // Do a query where the result type isn't deducible from the first row. stmt = spanner.NewStatement(`SELECT Age FROM ` + tableName + ` WHERE FirstName = "Peter"`) rows = client.Single().Query(ctx, stmt) var nullPeters int err = rows.Do(func(row *spanner.Row) error { var age spanner.NullInt64 if err := row.Column(0, &age); err != nil { return err } if age.Valid { t.Errorf("Got non-NULL Age %d for a Peter", age.Int64) } else { nullPeters++ } return nil }) if err != nil { t.Fatalf("Counting Peters with NULL Ages: %v", err) } if nullPeters != 2 { t.Errorf("Found %d Peters with NULL Ages, want 2", nullPeters) } // Check handling of array types. err = updateDDL(t, adminClient, `ALTER TABLE `+tableName+` ADD COLUMN Allies ARRAY<STRING(20)>`) if err != nil { t.Fatalf("Adding new array-typed column: %v", err) } _, err = client.Apply(ctx, []*spanner.Mutation{ spanner.Update(tableName, []string{"FirstName", "LastName", "Allies"}, []interface{}{"Steve", "Rogers", []string{}}), spanner.Update(tableName, []string{"FirstName", "LastName", "Allies"}, []interface{}{"Tony", "Stark", []string{"Black Widow", "Spider-Man"}}), }) if err != nil { t.Fatalf("Applying mutations: %v", err) } row, err = client.Single().ReadRow(ctx, tableName, spanner.Key{"Tony", "Stark"}, []string{"Allies"}) if err != nil { t.Fatalf("Reading row with array value: %v", err) } var names []string if err := row.Column(0, &names); err != nil { t.Fatalf("Unpacking array value: %v", err) } if want := []string{"Black Widow", "Spider-Man"}; !reflect.DeepEqual(names, want) { t.Errorf("Read array value: got %q, want %q", names, want) } row, err = client.Single().ReadRow(ctx, tableName, spanner.Key{"Steve", "Rogers"}, []string{"Allies"}) if err != nil { t.Fatalf("Reading row with empty array value: %v", err) } if err := row.Column(0, &names); err != nil { t.Fatalf("Unpacking empty array value: %v", err) } if len(names) > 0 { t.Errorf("Read empty array value: got %q", names) } // Exercise commit timestamp. err = updateDDL(t, adminClient, `ALTER TABLE `+tableName+` ADD COLUMN Updated TIMESTAMP OPTIONS (allow_commit_timestamp=true)`) if err != nil { t.Fatalf("Adding new timestamp column: %v", err) } cts, err := client.Apply(ctx, []*spanner.Mutation{ // Update one row in place. spanner.Update(tableName, []string{"FirstName", "LastName", "Allies", "Updated"}, []interface{}{"Tony", "Stark", []string{"Spider-Man", "Professor Hulk"}, spanner.CommitTimestamp}), }) if err != nil { t.Fatalf("Applying mutations: %v", err) } cts = cts.In(time.UTC) if d := time.Since(cts); d < 0 || d > 10*time.Second { t.Errorf("Commit timestamp %v not in the last 10s", cts) } row, err = client.Single().ReadRow(ctx, tableName, spanner.Key{"Tony", "Stark"}, []string{"Allies", "Updated"}) if err != nil { t.Fatalf("Reading single row: %v", err) } var gotAllies []string var gotUpdated time.Time if err := row.Columns(&gotAllies, &gotUpdated); err != nil { t.Fatalf("Decoding single row: %v", err) } if want := []string{"Spider-Man", "Professor Hulk"}; !reflect.DeepEqual(gotAllies, want) { t.Errorf("After updating Iron Man, allies = %+v, want %+v", gotAllies, want) } if !gotUpdated.Equal(cts) { t.Errorf("After updating Iron Man, updated = %v, want %v", gotUpdated, cts) } // Check if IN UNNEST works. stmt = spanner.NewStatement(`SELECT Age FROM ` + tableName + ` WHERE FirstName IN UNNEST(@list)`) stmt.Params = map[string]interface{}{ "list": []string{"Peter", "Steve"}, } rows = client.Single().Query(ctx, stmt) var ages []int64 err = rows.Do(func(row *spanner.Row) error { var age spanner.NullInt64 if err := row.Column(0, &age); err != nil { return err } ages = append(ages, age.Int64) // zero for NULL return nil }) if err != nil { t.Fatalf("Getting ages using IN UNNEST: %v", err) } sort.Slice(ages, func(i, j int) bool { return ages[i] < ages[j] }) wantAges := []int64{0, 0, 102} // Peter Parker, Peter Quill, Steve Rogers (modified) if !reflect.DeepEqual(ages, wantAges) { t.Errorf("Query with IN UNNEST gave wrong ages: got %+v, want %+v", ages, wantAges) } } func TestIntegration_ReadsAndQueries(t *testing.T) { client, adminClient, cleanup := makeClient(t) defer cleanup() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() // Drop any old tables. // Do them all concurrently; this saves a lot of time. allTables := []string{ "Staff", "PlayerStats", "JoinA", "JoinB", "JoinC", "JoinD", "JoinE", "JoinF", "SomeStrings", "Updateable", } errc := make(chan error) for _, table := range allTables { go func(table string) { errc <- dropTable(t, adminClient, table) }(table) } var bad bool for range allTables { if err := <-errc; err != nil { t.Error(err) bad = true } } if bad { t.FailNow() } err := updateDDL(t, adminClient, `CREATE TABLE Staff ( Tenure INT64, ID INT64, Name STRING(MAX), Cool BOOL, Height FLOAT64, ) PRIMARY KEY (Name, ID)`) if err != nil { t.Fatal(err) } // Insert a subset of columns. _, err = client.Apply(ctx, []*spanner.Mutation{ spanner.Insert("Staff", []string{"ID", "Name", "Tenure", "Height"}, []interface{}{1, "Jack", 10, 1.85}), spanner.Insert("Staff", []string{"ID", "Name", "Tenure", "Height"}, []interface{}{2, "Daniel", 11, 1.83}), }) if err != nil { t.Fatalf("Inserting data: %v", err) } // Insert a different set of columns. _, err = client.Apply(ctx, []*spanner.Mutation{ spanner.Insert("Staff", []string{"Name", "ID", "Cool", "Tenure", "Height"}, []interface{}{"Sam", 3, false, 9, 1.75}), spanner.Insert("Staff", []string{"Name", "ID", "Cool", "Tenure", "Height"}, []interface{}{"Teal'c", 4, true, 8, 1.91}), spanner.Insert("Staff", []string{"Name", "ID", "Cool", "Tenure", "Height"}, []interface{}{"George", 5, nil, 6, 1.73}), spanner.Insert("Staff", []string{"Name", "ID", "Cool", "Tenure", "Height"}, []interface{}{"Harry", 6, true, nil, nil}), }) if err != nil { t.Fatalf("Inserting more data: %v", err) } // Delete that last one. _, err = client.Apply(ctx, []*spanner.Mutation{ spanner.Delete("Staff", spanner.Key{"Harry", 6}), }) if err != nil { t.Fatalf("Deleting a row: %v", err) } // Turns out this guy isn't cool after all. _, err = client.Apply(ctx, []*spanner.Mutation{ // Missing columns should be left alone. spanner.Update("Staff", []string{"Name", "ID", "Cool"}, []interface{}{"Daniel", 2, false}), }) if err != nil { t.Fatalf("Updating a row: %v", err) } // Read some specific keys. ri := client.Single().Read(ctx, "Staff", spanner.KeySets( spanner.Key{"George", 5}, spanner.Key{"Harry", 6}, // Missing key should be silently ignored. spanner.Key{"Sam", 3}, spanner.Key{"George", 5}, // Duplicate key should be silently ignored. ), []string{"Name", "Tenure"}) if err != nil { t.Fatalf("Reading keys: %v", err) } all := mustSlurpRows(t, ri) wantAll := [][]interface{}{ {"George", int64(6)}, {"Sam", int64(9)}, } if !reflect.DeepEqual(all, wantAll) { t.Errorf("Read data by keys wrong.\n got %v\nwant %v", all, wantAll) } // Read the same, but by key range. ri = client.Single().Read(ctx, "Staff", spanner.KeySets( spanner.KeyRange{Start: spanner.Key{"Gabriel"}, End: spanner.Key{"Harpo"}, Kind: spanner.OpenOpen}, spanner.KeyRange{Start: spanner.Key{"Sam", 3}, End: spanner.Key{"Teal'c", 4}, Kind: spanner.ClosedOpen}, ), []string{"Name", "Tenure"}) all = mustSlurpRows(t, ri) if !reflect.DeepEqual(all, wantAll) { t.Errorf("Read data by key ranges wrong.\n got %v\nwant %v", all, wantAll) } // Read a subset of all rows, with a limit. ri = client.Single().ReadWithOptions(ctx, "Staff", spanner.AllKeys(), []string{"Tenure", "Name", "Height"}, &spanner.ReadOptions{Limit: 4}) all = mustSlurpRows(t, ri) wantAll = [][]interface{}{ // Primary key is (Name, ID), so results should come back sorted by Name then ID. {int64(11), "Daniel", 1.83}, {int64(6), "George", 1.73}, {int64(10), "Jack", 1.85}, {int64(9), "Sam", 1.75}, } if !reflect.DeepEqual(all, wantAll) { t.Errorf("ReadAll data wrong.\n got %v\nwant %v", all, wantAll) } // Add DATE and TIMESTAMP columns, and populate them with some data. err = updateDDL(t, adminClient, `ALTER TABLE Staff ADD COLUMN FirstSeen DATE`, "ALTER TABLE Staff ADD COLUMN `To` TIMESTAMP", // "TO" is a keyword; needs quoting ) if err != nil { t.Fatalf("Adding columns: %v", err) } _, err = client.Apply(ctx, []*spanner.Mutation{ spanner.Update("Staff", []string{"Name", "ID", "FirstSeen", "To"}, []interface{}{"Jack", 1, "1994-10-28", nil}), spanner.Update("Staff", []string{"Name", "ID", "FirstSeen", "To"}, []interface{}{"Daniel", 2, "1994-10-28", nil}), spanner.Update("Staff", []string{"Name", "ID", "FirstSeen", "To"}, []interface{}{"George", 5, "1997-07-27", "2008-07-29T11:22:43Z"}), }) if err != nil { t.Fatalf("Updating rows: %v", err) } // Add some more data, then delete it with a KeyRange. // The queries below ensure that this was all deleted. _, err = client.Apply(ctx, []*spanner.Mutation{ spanner.Insert("Staff", []string{"Name", "ID"}, []interface{}{"01", 1}), spanner.Insert("Staff", []string{"Name", "ID"}, []interface{}{"03", 3}), spanner.Insert("Staff", []string{"Name", "ID"}, []interface{}{"06", 6}), }) if err != nil { t.Fatalf("Inserting data: %v", err) } _, err = client.Apply(ctx, []*spanner.Mutation{ spanner.Delete("Staff", spanner.KeyRange{ /* This should work: Start: spanner.Key{"01", 1}, End: spanner.Key{"9"}, However, that is unimplemented in the production Cloud Spanner, which rejects that: ""For delete ranges, start and limit keys may only differ in the final key part" */ Start: spanner.Key{"01"}, End: spanner.Key{"9"}, Kind: spanner.ClosedOpen, }), }) if err != nil { t.Fatalf("Deleting key range: %v", err) } // Re-add the data and delete with DML. _, err = client.Apply(ctx, []*spanner.Mutation{ spanner.Insert("Staff", []string{"Name", "ID"}, []interface{}{"01", 1}), spanner.Insert("Staff", []string{"Name", "ID"}, []interface{}{"03", 3}), spanner.Insert("Staff", []string{"Name", "ID"}, []interface{}{"06", 6}), }) if err != nil { t.Fatalf("Inserting data: %v", err) } var n int64 _, err = client.ReadWriteTransaction(ctx, func(ctx context.Context, tx *spanner.ReadWriteTransaction) error { stmt := spanner.NewStatement("DELETE FROM Staff WHERE Name >= @min AND Name < @max") stmt.Params["min"] = "01" stmt.Params["max"] = "07" n, err = tx.Update(ctx, stmt) return err }) if err != nil { t.Fatalf("Deleting with DML: %v", err) } if n != 3 { t.Errorf("Deleting with DML affected %d rows, want 3", n) } // Add a BYTES column, and populate it with some data. err = updateDDL(t, adminClient, `ALTER TABLE Staff ADD COLUMN RawBytes BYTES(MAX)`) if err != nil { t.Fatalf("Adding column: %v", err) } _, err = client.Apply(ctx, []*spanner.Mutation{ // bytes {0x01 0x00 0x01} encode as base-64 AQAB. spanner.Update("Staff", []string{"Name", "ID", "RawBytes"}, []interface{}{"Jack", 1, []byte{0x01, 0x00, 0x01}}), }) if err != nil { t.Fatalf("Updating rows: %v", err) } // Prepare the sample tables from the Cloud Spanner docs. // https://cloud.google.com/spanner/docs/query-syntax#appendix-a-examples-with-sample-data err = updateDDL(t, adminClient, // TODO: Roster, TeamMascot when we implement JOINs. `CREATE TABLE PlayerStats ( LastName STRING(MAX), OpponentID INT64, PointsScored INT64, ) PRIMARY KEY (LastName, OpponentID)`, // TODO: is this right? // JoinFoo are from https://cloud.google.com/spanner/docs/query-syntax#join_types. // They aren't consistently named in the docs. `CREATE TABLE JoinA ( w INT64, x STRING(MAX) ) PRIMARY KEY (w, x)`, `CREATE TABLE JoinB ( y INT64, z STRING(MAX) ) PRIMARY KEY (y, z)`, `CREATE TABLE JoinC ( x INT64, y STRING(MAX) ) PRIMARY KEY (x, y)`, `CREATE TABLE JoinD ( x INT64, z STRING(MAX) ) PRIMARY KEY (x, z)`, `CREATE TABLE JoinE ( w INT64, x STRING(MAX) ) PRIMARY KEY (w, x)`, `CREATE TABLE JoinF ( y INT64, z STRING(MAX) ) PRIMARY KEY (y, z)`, // Some other test tables. `CREATE TABLE SomeStrings ( i INT64, str STRING(MAX) ) PRIMARY KEY (i)`, `CREATE TABLE Updateable ( id INT64, first STRING(MAX), last STRING(MAX), ) PRIMARY KEY (id)`, ) if err != nil { t.Fatalf("Creating sample tables: %v", err) } _, err = client.Apply(ctx, []*spanner.Mutation{ spanner.Insert("PlayerStats", []string{"LastName", "OpponentID", "PointsScored"}, []interface{}{"Adams", 51, 3}), spanner.Insert("PlayerStats", []string{"LastName", "OpponentID", "PointsScored"}, []interface{}{"Buchanan", 77, 0}), spanner.Insert("PlayerStats", []string{"LastName", "OpponentID", "PointsScored"}, []interface{}{"Coolidge", 77, 1}), spanner.Insert("PlayerStats", []string{"LastName", "OpponentID", "PointsScored"}, []interface{}{"Adams", 52, 4}), spanner.Insert("PlayerStats", []string{"LastName", "OpponentID", "PointsScored"}, []interface{}{"Buchanan", 50, 13}), spanner.Insert("JoinA", []string{"w", "x"}, []interface{}{1, "a"}), spanner.Insert("JoinA", []string{"w", "x"}, []interface{}{2, "b"}), spanner.Insert("JoinA", []string{"w", "x"}, []interface{}{3, "c"}), spanner.Insert("JoinA", []string{"w", "x"}, []interface{}{3, "d"}), spanner.Insert("JoinB", []string{"y", "z"}, []interface{}{2, "k"}), spanner.Insert("JoinB", []string{"y", "z"}, []interface{}{3, "m"}), spanner.Insert("JoinB", []string{"y", "z"}, []interface{}{3, "n"}), spanner.Insert("JoinB", []string{"y", "z"}, []interface{}{4, "p"}), // JoinC and JoinD have the same contents as JoinA and JoinB; they have different column names. spanner.Insert("JoinC", []string{"x", "y"}, []interface{}{1, "a"}), spanner.Insert("JoinC", []string{"x", "y"}, []interface{}{2, "b"}), spanner.Insert("JoinC", []string{"x", "y"}, []interface{}{3, "c"}), spanner.Insert("JoinC", []string{"x", "y"}, []interface{}{3, "d"}), spanner.Insert("JoinD", []string{"x", "z"}, []interface{}{2, "k"}), spanner.Insert("JoinD", []string{"x", "z"}, []interface{}{3, "m"}), spanner.Insert("JoinD", []string{"x", "z"}, []interface{}{3, "n"}), spanner.Insert("JoinD", []string{"x", "z"}, []interface{}{4, "p"}), // JoinE and JoinF are used in the CROSS JOIN test. spanner.Insert("JoinE", []string{"w", "x"}, []interface{}{1, "a"}), spanner.Insert("JoinE", []string{"w", "x"}, []interface{}{2, "b"}), spanner.Insert("JoinF", []string{"y", "z"}, []interface{}{2, "c"}), spanner.Insert("JoinF", []string{"y", "z"}, []interface{}{3, "d"}), spanner.Insert("SomeStrings", []string{"i", "str"}, []interface{}{0, "afoo"}), spanner.Insert("SomeStrings", []string{"i", "str"}, []interface{}{1, "abar"}), spanner.Insert("SomeStrings", []string{"i", "str"}, []interface{}{2, nil}), spanner.Insert("SomeStrings", []string{"i", "str"}, []interface{}{3, "bbar"}), spanner.Insert("Updateable", []string{"id", "first", "last"}, []interface{}{0, "joe", nil}), spanner.Insert("Updateable", []string{"id", "first", "last"}, []interface{}{1, "doe", "joan"}), spanner.Insert("Updateable", []string{"id", "first", "last"}, []interface{}{2, "wong", "wong"}), }) if err != nil { t.Fatalf("Inserting sample data: %v", err) } // Perform UPDATE DML; the results are checked later on. n = 0 _, err = client.ReadWriteTransaction(ctx, func(ctx context.Context, tx *spanner.ReadWriteTransaction) error { for _, u := range []string{ `UPDATE Updateable SET last = "bloggs" WHERE id = 0`, `UPDATE Updateable SET first = last, last = first WHERE id = 1`, `UPDATE Updateable SET last = DEFAULT WHERE id = 2`, `UPDATE Updateable SET first = "noname" WHERE id = 3`, // no id=3 } { nr, err := tx.Update(ctx, spanner.NewStatement(u)) if err != nil { return err } n += nr } return nil }) if err != nil { t.Fatalf("Updating with DML: %v", err) } if n != 3 { t.Errorf("Updating with DML affected %d rows, want 3", n) } // Do some complex queries. tests := []struct { q string params map[string]interface{} want [][]interface{} }{ { `SELECT 17, "sweet", TRUE AND FALSE, NULL, B"hello"`, nil, [][]interface{}{{int64(17), "sweet", false, nil, []byte("hello")}}, }, // Check handling of NULL values for the IS operator. // There was a bug that returned errors for some of these cases. { `SELECT @x IS TRUE, @x IS NOT TRUE, @x IS FALSE, @x IS NOT FALSE, @x IS NULL, @x IS NOT NULL`, map[string]interface{}{"x": (*bool)(nil)}, [][]interface{}{ {false, true, false, true, true, false}, }, }, // Check handling of bools that might be NULL. // There was a bug where logical operators always returned true/false. { `SELECT @x, NOT @x, @x AND TRUE, @x AND FALSE, @x OR TRUE, @x OR FALSE`, map[string]interface{}{"x": (*bool)(nil)}, [][]interface{}{ // At the time of writing (9 Oct 2020), the docs are wrong for `NULL AND FALSE`; // the production Spanner returns FALSE, which is what we match. {nil, nil, nil, false, true, nil}, }, }, { `SELECT Name FROM Staff WHERE Cool`, nil, [][]interface{}{{"Teal'c"}}, }, { `SELECT ID FROM Staff WHERE Cool IS NOT NULL ORDER BY ID DESC`, nil, [][]interface{}{{int64(4)}, {int64(3)}, {int64(2)}}, }, { `SELECT Name, Tenure FROM Staff WHERE Cool IS NULL OR Cool ORDER BY Name LIMIT 2`, nil, [][]interface{}{ {"George", int64(6)},
`SELECT Name, ID + 100 FROM Staff WHERE @min <= Tenure AND Tenure < @lim ORDER BY Cool, Name DESC LIMIT @numResults`, map[string]interface{}{"min": 9, "lim": 11, "numResults": 100}, [][]interface{}{ {"Jack", int64(101)}, {"Sam", int64(103)}, }, }, { // Expression in SELECT list. `SELECT Name, Cool IS NOT NULL FROM Staff WHERE Tenure/2 > 4 ORDER BY NOT Cool, Name`, nil, [][]interface{}{ {"Jack", false}, // Jack has NULL Cool (NULLs always come first in orderings) {"Daniel", true}, // Daniel has Cool==true {"Sam", true}, // Sam has Cool==false }, }, { `SELECT Name, Height FROM Staff ORDER BY Height DESC LIMIT 2`, nil, [][]interface{}{ {"Teal'c", 1.91}, {"Jack", 1.85}, }, }, { `SELECT Name FROM Staff WHERE Name LIKE "J%k" OR Name LIKE "_am"`, nil, [][]interface{}{ {"Jack"}, {"Sam"}, }, }, { `SELECT Name, Height FROM Staff WHERE Height BETWEEN @min AND @max ORDER BY Height DESC`, map[string]interface{}{"min": 1.75, "max": 1.85}, [][]interface{}{ {"Jack", 1.85}, {"Daniel", 1.83}, {"Sam", 1.75}, }, }, { `SELECT COUNT(*) FROM Staff WHERE Name < "T"`, nil, [][]interface{}{ {int64(4)}, }, }, { // Check that aggregation still works for the empty set. `SELECT COUNT(*) FROM Staff WHERE Name = "Nobody"`, nil, [][]interface{}{ {int64(0)}, }, }, { `SELECT * FROM Staff WHERE Name LIKE "S%"`, nil, [][]interface{}{ // These are returned in table column order, based on the appearance in the DDL. // Our internal implementation sorts the primary key columns first, // but that should not become visible via SELECT *. {int64(9), int64(3), "Sam", false, 1.75, nil, nil, nil}, }, }, { // Exactly the same as the previous, except with a redundant ORDER BY clause. `SELECT * FROM Staff WHERE Name LIKE "S%" ORDER BY Name`, nil, [][]interface{}{ {int64(9), int64(3), "Sam", false, 1.75, nil, nil, nil}, }, }, { `SELECT Name FROM Staff WHERE FirstSeen >= @min`, map[string]interface{}{"min": civil.Date{Year: 1996, Month: 1, Day: 1}}, [][]interface{}{ {"George"}, }, }, { `SELECT RawBytes FROM Staff WHERE RawBytes IS NOT NULL`, nil, [][]interface{}{ {[]byte("\x01\x00\x01")}, }, }, { // The keyword "To" needs quoting in queries. // Check coercion of comparison operator literal args too. "SELECT COUNT(*) FROM Staff WHERE `To` > '2000-01-01T00:00:00Z'", nil, [][]interface{}{ {int64(1)}, }, }, { `SELECT DISTINCT Cool, Tenure > 8 FROM Staff ORDER BY Cool`, nil, [][]interface{}{ // The non-distinct results are // [[false true] [<nil> false] [<nil> true] [false true] [true false]] {nil, false}, {nil, true}, {false, true}, {true, false}, }, }, { `SELECT Name FROM Staff WHERE ID IN UNNEST(@ids)`, map[string]interface{}{"ids": []int64{3, 1}}, [][]interface{}{ {"Jack"}, {"Sam"}, }, }, // From https://cloud.google.com/spanner/docs/query-syntax#group-by-clause_1: { // TODO: Ordering matters? Our implementation sorts by the GROUP BY key, // but nothing documented seems to guarantee that. `SELECT LastName, SUM(PointsScored) FROM PlayerStats GROUP BY LastName`, nil, [][]interface{}{ {"Adams", int64(7)}, {"Buchanan", int64(13)}, {"Coolidge", int64(1)}, }, }, { // Another GROUP BY, but referring to an alias. // Group by ID oddness, SUM over Tenure. `SELECT ID&0x01 AS odd, SUM(Tenure) FROM Staff GROUP BY odd`, nil, [][]interface{}{ {int64(0), int64(19)}, // Daniel(ID=2, Tenure=11), Teal'c(ID=4, Tenure=8) {int64(1), int64(25)}, // Jack(ID=1, Tenure=10), Sam(ID=3, Tenure=9), George(ID=5, Tenure=6) }, }, { `SELECT MAX(Name) FROM Staff WHERE Name < @lim`, map[string]interface{}{"lim": "Teal'c"}, [][]interface{}{ {"Sam"}, }, }, { `SELECT MAX(Name) FROM Staff WHERE Cool = @p1 LIMIT 1`, map[string]interface{}{"p1": true}, [][]interface{}{ {"Teal'c"}, }, }, { `SELECT MIN(Name) FROM Staff`, nil, [][]interface{}{ {"Daniel"}, }, }, { `SELECT ARRAY_AGG(Cool) FROM Staff`, nil, [][]interface{}{ // Daniel, George (NULL), Jack (NULL), Sam, Teal'c {[]interface{}{false, nil, nil, false, true}}, }, }, // SELECT with aliases. { // Aliased table. `SELECT s.Name FROM Staff AS s WHERE s.ID = 3 ORDER BY s.Tenure`, nil, [][]interface{}{ {"Sam"}, }, }, { // Aliased expression. `SELECT Name AS nom FROM Staff WHERE ID < 4 ORDER BY nom`, nil, [][]interface{}{ {"Daniel"}, {"Jack"}, {"Sam"}, }, }, // Joins. { `SELECT * FROM JoinA INNER JOIN JoinB ON JoinA.w = JoinB.y ORDER BY w, x, y, z`, nil, [][]interface{}{ {int64(2), "b", int64(2), "k"}, {int64(3), "c", int64(3), "m"}, {int64(3), "c", int64(3), "n"}, {int64(3), "d", int64(3), "m"}, {int64(3), "d", int64(3), "n"}, }, }, { `SELECT * FROM JoinE CROSS JOIN JoinF ORDER BY w, x, y, z`, nil, [][]interface{}{ {int64(1), "a", int64(2), "c"}, {int64(1), "a", int64(3), "d"}, {int64(2), "b", int64(2), "c"}, {int64(2), "b", int64(3), "d"}, }, }, { `SELECT * FROM JoinA LEFT OUTER JOIN JoinB AS B ON JoinA.w = B.y ORDER BY w, x, y, z`, nil, [][]interface{}{ {int64(1), "a", nil, nil}, {int64(2), "b", int64(2), "k"}, {int64(3), "c", int64(3), "m"}, {int64(3), "c", int64(3), "n"}, {int64(3), "d", int64(3), "m"}, {int64(3), "d", int64(3), "n"}, }, }, { // Same as the previous, but using a USING clause instead of an ON clause. `SELECT * FROM JoinC LEFT OUTER JOIN JoinD USING (x) ORDER BY x, y, z`, nil, [][]interface{}{ {int64(1), "a", nil}, {int64(2), "b", "k"}, {int64(3), "c", "m"}, {int64(3), "c", "n"}, {int64(3), "d", "m"}, {int64(3), "d", "n"}, }, }, { // Same as in docs, but with a weird ORDER BY clause to match the row ordering. `SELECT * FROM JoinA RIGHT OUTER JOIN JoinB AS B ON JoinA.w = B.y ORDER BY w IS NULL, w, x, y, z`, nil, [][]interface{}{ {int64(2), "b", int64(2), "k"}, {int64(3), "c", int64(3), "m"}, {int64(3), "c", int64(3), "n"}, {int64(3), "d", int64(3), "m"}, {int64(3), "d", int64(3), "n"}, {nil, nil, int64(4), "p"}, }, }, { `SELECT * FROM JoinC RIGHT OUTER JOIN JoinD USING (x) ORDER BY x, y, z`, nil, [][]interface{}{ {int64(2), "b", "k"}, {int64(3), "c", "m"}, {int64(3), "c", "n"}, {int64(3), "d", "m"}, {int64(3), "d", "n"}, {int64(4), nil, "p"}, }, }, // Check the output of the UPDATE DML. { `SELECT id, first, last FROM Updateable ORDER BY id`, nil, [][]interface{}{ {int64(0), "joe", "bloggs"}, {int64(1), "joan", "doe"}, {int64(2), "wong", nil}, }, }, // Regression test for aggregating no rows; it used to return an empty row. // https://github.com/googleapis/google-cloud-go/issues/2793 { `SELECT Cool, ARRAY_AGG(Name) FROM Staff WHERE Name > "zzz" GROUP BY Cool`, nil, nil, }, // Regression test for evaluating `IN` incorrectly using ==. // https://github.com/googleapis/google-cloud-go/issues/2458 { `SELECT COUNT(*) FROM Staff WHERE RawBytes IN UNNEST(@arg)`, map[string]interface{}{ "arg": [][]byte{ {0x02}, {0x01, 0x00, 0x01}, // only one present }, }, [][]interface{}{ {int64(1)}, }, }, // Regression test for mishandling NULLs with LIKE operator. { `SELECT i, str FROM SomeStrings WHERE str LIKE "%bar"`, nil, [][]interface{}{ // Does not include [0, "afoo"] or [2, nil]. {int64(1), "abar"}, {int64(3), "bbar"}, }, }, { `SELECT i, str FROM SomeStrings WHERE str NOT LIKE "%bar"`, nil, [][]interface{}{ // Does not include [1, "abar"], [2, nil] or [3, "bbar"]. {int64(0), "afoo"}, }, }, // Regression test for ORDER BY combined with SELECT aliases. { `SELECT Name AS nom FROM Staff ORDER BY ID LIMIT 2`, nil, [][]interface{}{ {"Jack"}, {"Daniel"}, }, }, } var failures int for _, test := range tests { t.Logf("Testing query: %s", test.q) stmt := spanner.NewStatement(test.q) stmt.Params = test.params ri = client.Single().Query(ctx, stmt) all, err := slurpRows(t, ri) if err != nil { t.Errorf("Query(%q, %v): %v", test.q, test.params, err) failures++ continue } if !reflect.DeepEqual(all, test.want) { t.Errorf("Results from Query(%q, %v) are wrong.\n got %v\nwant %v", test.q, test.params, all, test.want) failures++ } } if failures > 0 { t.Logf("%d queries failed", failures) } } func dropTable(t *testing.T, adminClient *dbadmin.DatabaseAdminClient, table string) error { t.Helper() err := updateDDL(t, adminClient, "DROP TABLE "+table) // NotFound is an acceptable failure mode here. if st, _ := status.FromError(err); st.Code() == codes.NotFound { err = nil } if err != nil { return fmt.Errorf("dropping old table %q: %v", table, err) } return nil } func updateDDL(t *testing.T, adminClient *dbadmin.DatabaseAdminClient, statements ...string) error { t.Helper() ctx := context.Background() t.Logf("DDL update: %q", statements) op, err := adminClient.UpdateDatabaseDdl(ctx, &dbadminpb.UpdateDatabaseDdlRequest{ Database: dbName(), Statements: statements, }) if err != nil { t.Fatalf("Starting DDL update: %v", err) } return op.Wait(ctx) } func mustSlurpRows(t *testing.T, ri *spanner.RowIterator) [][]interface{} { t.Helper() all, err := slurpRows(t, ri) if err != nil { t.Fatalf("Reading rows: %v", err) } return all } func slurpRows(t *testing.T, ri *spanner.RowIterator) (all [][]interface{}, err error) { t.Helper() err = ri.Do(func(r *spanner.Row) error { var data []interface{} for i := 0; i < r.Size(); i++ { var gcv spanner.GenericColumnValue if err := r.Column(i, &gcv); err != nil { return err } data = append(data, genericValue(t, gcv)) } all = append(all, data) return nil }) return } func genericValue(t *testing.T, gcv spanner.GenericColumnValue) interface{} { t.Helper() if _, ok := gcv.Value.Kind.(*structpb.Value_NullValue); ok { return nil } if gcv.Type.Code == spannerpb.TypeCode_ARRAY { var arr []interface{} for _, v := range gcv.Value.GetListValue().Values { arr = append(arr, genericValue(t, spanner.GenericColumnValue{ Type: &spannerpb.Type{Code: gcv.Type.ArrayElementType.Code}, Value: v, })) } return arr } var dst interface{} switch gcv.Type.Code { case spannerpb.TypeCode_BOOL: dst = new(bool) case spannerpb.TypeCode_INT64: dst = new(int64) case spannerpb.TypeCode_FLOAT64: dst = new(float64) case spannerpb.TypeCode_TIMESTAMP: dst = new(time.Time) // TODO: do we need to force to UTC? case spannerpb.TypeCode_DATE: dst = new(civil.Date) case spannerpb.TypeCode_STRING: dst = new(string) case spannerpb.TypeCode_BYTES: dst = new([]byte) } if dst == nil { t.Fatalf("Can't decode Spanner generic column value: %v", gcv.Type) } if err := gcv.Decode(dst); err != nil { t.Fatalf("Decoding %v into %T: %v", gcv, dst, err) } return reflect.ValueOf(dst).Elem().Interface() }
{"Jack", int64(10)}, }, }, {
fabfile.py
from build import * from release import * from fabric.network import ssh from fabric.api import env, put, run, sudo, task from fabric.decorators import runs_once ssh.util.log_to_file("paramiko.log", 10) env.use_ssh_config = True WORKSPACE_DIR = os.path.join(DEPLOYMENT_WORKING_DIR, "templates/workspace/") print("WORKSPACE_DIR = {}".format(WORKSPACE_DIR)) VALID_MODES = ["full", "dryrun"] @runs_once @task def release_final(): run_release(RELEASE_TYPE_FINAL) @runs_once @task def release_snapshot(): run_release(RELEASE_TYPE_SNAPSHOT) @runs_once @task def
(): release_context = ReleaseContext( PROJECT_ROOT, RELEASE_TYPE_TEST_FINAL, "{}/Cargo.toml".format(PROJECT_ROOT), "{}/src/version.txt".format(PROJECT_ROOT), "{}/CHANGELOG.md".format(PROJECT_ROOT), True, True, True ) release(release_context) bump_version(release_context) def run_release(release_type): release_context = ReleaseContext( PROJECT_ROOT, release_type, "{}/Cargo.toml".format(PROJECT_ROOT), "{}/src/version.txt".format(PROJECT_ROOT), "{}/CHANGELOG.md".format(PROJECT_ROOT), False, False, True ) release(release_context) package() print("Publishing to crates.io.") publish() bump_version(release_context) @runs_once @task def package(): print "********** Packaging for crates.io. ********" package_cmd = 'cargo package' ret_code = subprocess.call(package_cmd, shell=True) if ret_code != 0: fabric.utils.abort("Packaging for crates.io failed with return code {}".format(ret_code)) @runs_once @task def publish(): print "********** Publishing to crates.io. ********" publish_cmd = 'cargo publish' ret_code = subprocess.call(publish_cmd, shell=True) if ret_code != 0: fabric.utils.abort("Publishing to crates.io failed with return code {}".format(ret_code))
release_test_final
ship.py
import pygame from pygame.sprite import Sprite class Ship(Sprite): def
(self, ai_settings, screen): super().__init__() '''初始化飞船并设置其初始位置''' self.screen = screen self.ai_settings = ai_settings # 加载飞船图像并获取其外接矩形 self.image = pygame.image.load('../images/ship.png') self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() # 将每艘新飞船放在屏幕底部中央 self.rect.centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom # 在飞船的属性center中存储小数值 self.center = float(self.rect.centerx) # 移动标志 self.moving_right = False self.moving_left = False def blitme(self): '''在指定位置绘制飞船''' self.screen.blit(self.image, self.rect) def update(self): '''根据移动标志调整飞船的位置''' # 更新飞船的center值,而不是rect if self.moving_right and (self.rect.right < self.screen_rect.right): self.center += self.ai_settings.ship_speed_factor if self.moving_left and (self.rect.left > 0): self.center -= self.ai_settings.ship_speed_factor # 根据self.center值跟新rect对象 self.rect.centerx = self.center def center_ship(self): '''让飞船在屏幕上居中''' self.center = self.screen_rect.centerx
__init__
transaction.rs
use crate::constants::*; use crate::convert::bytes::{self, *}; use crate::convert::number; use crate::convert::trits::{self, *}; use crate::convert::tryte_string; use crate::convert::trytes::{self, *}; use crate::crypto::curl; use crate::time; pub const MAX_TIME_TRYTE_LENGTH: usize = 9; #[derive(Clone, Debug)] pub struct Transaction { pub signature_fragments: String, pub extra_data_digest: String, pub address: String, pub value: i64, pub issuance_timestamp: i64, pub timelock_lower_bound: i64, pub timelock_upper_bound: i64, pub bundle_nonce: String, pub trunk: String, pub branch: String, pub tag: String, pub attachment_timestamp: i64, pub attachment_timestamp_lower_bound: i64, pub attachment_timestamp_upper_bound: i64, pub nonce: String, } impl Transaction { pub fn from_tx_bytes(bytes: &[u8]) -> Self { Transaction::from_tx_trytes(&trytes::from_tx_bytes_2enc9(bytes)) } pub fn from_tryte_string(tryte_string: &str) -> Self { assert!(IS_TRYTES.is_match(tryte_string)); let bytes = tryte_string.as_bytes(); assert_eq!(bytes.len(), TRANSACTION_SIZE_TRYTES); let mut trytes = [0; TRANSACTION_SIZE_TRYTES]; trytes[..].copy_from_slice(&bytes[..]); Transaction::from_tx_trytes(&trytes) } pub fn from_tx_trytes(trytes: &TxTrytes) -> Self { let signature_fragments = tryte_string::from_trytes(&trytes[SIGNATURE_FRAGMENTS.2..EXTRA_DATA_DIGEST.2]); let extra_data_digest = tryte_string::from_trytes(&trytes[EXTRA_DATA_DIGEST.2..ADDRESS.2]); let address = tryte_string::from_trytes(&trytes[ADDRESS.2..VALUE.2]); let value = number::i64_from_trytes_max11(&trytes[VALUE.2..ISSUANCE_TIMESTAMP.2]); let issuance_timestamp = number::i64_from_trytes_max11(&trytes[ISSUANCE_TIMESTAMP.2..TIMELOCK_LOWER_BOUND.2]); let timelock_lower_bound = number::i64_from_trytes_max11(&trytes[TIMELOCK_LOWER_BOUND.2..TIMELOCK_UPPER_BOUND.2]); let timelock_upper_bound = number::i64_from_trytes_max11(&trytes[TIMELOCK_UPPER_BOUND.2..BUNDLE_NONCE.2]); let bundle_nonce = tryte_string::from_trytes(&trytes[BUNDLE_NONCE.2..TRUNK_HASH.2]); let trunk = tryte_string::from_trytes(&trytes[TRUNK_HASH.2..BRANCH_HASH.2]); let branch = tryte_string::from_trytes(&trytes[BRANCH_HASH.2..TAG.2]); let tag = tryte_string::from_trytes(&trytes[TAG.2..ATTACHMENT_TIMESTAMP.2]); let attachment_timestamp = number::i64_from_trytes_max11( &trytes[ATTACHMENT_TIMESTAMP.2..ATTACHMENT_TIMESTAMP_LOWER_BOUND.2], ); let attachment_timestamp_lower_bound = number::i64_from_trytes_max11( &trytes[ATTACHMENT_TIMESTAMP_LOWER_BOUND.2..ATTACHMENT_TIMESTAMP_UPPER_BOUND.2], ); let attachment_timestamp_upper_bound = number::i64_from_trytes_max11(&trytes[ATTACHMENT_TIMESTAMP_UPPER_BOUND.2..NONCE.2]); let nonce = tryte_string::from_trytes(&trytes[NONCE.2..TRANSACTION_SIZE_TRYTES]); Transaction { signature_fragments, extra_data_digest, address, value, issuance_timestamp, timelock_lower_bound, timelock_upper_bound, bundle_nonce, trunk, branch, tag, attachment_timestamp, attachment_timestamp_lower_bound, attachment_timestamp_upper_bound, nonce, } } pub fn as_bytes(&self) -> TxBytes { bytes::from_tx_trytes_2enc9(&self.as_trytes()) } pub fn as_tryte_string(&self) -> String { tryte_string::from_trytes(&self.as_trytes()) } pub fn as_trits(&self) -> TxTrits { trits::from_tx_trytes(&self.as_trytes()) } pub fn as_trytes(&self) -> TxTrytes { let mut trytes = [0; TRANSACTION_SIZE_TRYTES]; trytes[SIGNATURE_FRAGMENTS.2..EXTRA_DATA_DIGEST.2].copy_from_slice( &trytes::from_tryte_string_to_fragment_trytes(&self.signature_fragments) [..SIGNATURE_FRAGMENTS.3], ); trytes[EXTRA_DATA_DIGEST.2..ADDRESS.2] .copy_from_slice(&self.extra_data_digest.as_bytes()[..EXTRA_DATA_DIGEST.3]); trytes[ADDRESS.2..VALUE.2].copy_from_slice(&self.address.as_bytes()[..ADDRESS.3]); trytes[VALUE.2..ISSUANCE_TIMESTAMP.2].copy_from_slice(&from_i64_fixed27(self.value)); trytes[ISSUANCE_TIMESTAMP.2..TIMELOCK_LOWER_BOUND.2] .copy_from_slice(&from_i64_fixed9(self.issuance_timestamp)); trytes[TIMELOCK_LOWER_BOUND.2..TIMELOCK_UPPER_BOUND.2] .copy_from_slice(&from_i64_fixed9(self.timelock_lower_bound)); trytes[TIMELOCK_UPPER_BOUND.2..BUNDLE_NONCE.2] .copy_from_slice(&from_i64_fixed9(self.timelock_upper_bound)); trytes[BUNDLE_NONCE.2..TRUNK_HASH.2] .copy_from_slice(&self.bundle_nonce.as_bytes()[..BUNDLE_NONCE.3]); trytes[TRUNK_HASH.2..BRANCH_HASH.2].copy_from_slice(&self.trunk.as_bytes()[..TRUNK_HASH.3]); trytes[BRANCH_HASH.2..TAG.2].copy_from_slice(&self.branch.as_bytes()[..BRANCH_HASH.3]); trytes[TAG.2..ATTACHMENT_TIMESTAMP.2].copy_from_slice(&self.tag.as_bytes()[0..TAG.3]); trytes[ATTACHMENT_TIMESTAMP.2..ATTACHMENT_TIMESTAMP_LOWER_BOUND.2] .copy_from_slice(&from_i64_fixed9(self.attachment_timestamp)); trytes[ATTACHMENT_TIMESTAMP_LOWER_BOUND.2..ATTACHMENT_TIMESTAMP_UPPER_BOUND.2] .copy_from_slice(&from_i64_fixed9(self.attachment_timestamp_lower_bound)); trytes[ATTACHMENT_TIMESTAMP_UPPER_BOUND.2..NONCE.2] .copy_from_slice(&from_i64_fixed9(self.attachment_timestamp_upper_bound)); trytes[NONCE.2..TRANSACTION_SIZE_TRYTES].copy_from_slice(&self.nonce.as_bytes()[..NONCE.3]); trytes } pub fn get_hash(&self) -> Trytes81 { trytes::from_trits_fixed81(&curl::curl_tx( self.as_trits(), CURL_ROUNDS_TRANSACTION_HASH, )) } pub fn message(mut self, message: &str) -> Self { assert!(message.len() <= SIGNATURE_FRAGMENTS.3); self.signature_fragments = tryte_string::pad_right(&tryte_string::from_ascii(message), SIGNATURE_FRAGMENTS.3); self } pub fn tag(mut self, tag: &str) -> Self { assert!(IS_TRYTES.is_match(tag)); assert!(tag.len() <= TAG.3); self.tag = tryte_string::pad_right(tag, TAG.3); self } } impl Default for Transaction { fn default() -> Self { let timestamp = time::get_unix_time_millis(); Transaction { signature_fragments: TRYTE_NULL_STR.repeat(SIGNATURE_FRAGMENTS.3), extra_data_digest: TRYTE_NULL_STR.repeat(EXTRA_DATA_DIGEST.3), address: TRYTE_NULL_STR.repeat(ADDRESS.3), value: 0, issuance_timestamp: timestamp, timelock_lower_bound: 0, timelock_upper_bound: 0, bundle_nonce: TRYTE_NULL_STR.repeat(BUNDLE_NONCE.3), trunk: TRYTE_NULL_STR.repeat(TRUNK_HASH.3), branch: TRYTE_NULL_STR.repeat(BRANCH_HASH.3), tag: TRYTE_NULL_STR.repeat(TAG.3), attachment_timestamp: timestamp, attachment_timestamp_lower_bound: 0, attachment_timestamp_upper_bound: 0, nonce: TRYTE_NULL_STR.repeat(NONCE.3), } } } pub struct TransactionBuilder { transaction: Transaction, } impl TransactionBuilder { pub fn default() -> Self { TransactionBuilder { transaction: Transaction::default(), } } pub fn value(mut self, value: i64) -> Self { assert!(value.abs() <= MAX_TOKEN_SUPPLY); self.transaction.value = value; self } pub fn trunk(mut self, trunk: &str) -> Self { assert!(IS_TRYTES.is_match(trunk)); assert!(trunk.len() <= TRUNK_HASH.3); self.transaction.trunk = trunk.to_string(); self
pub fn branch(mut self, branch: &str) -> Self { assert!(IS_TRYTES.is_match(branch)); assert!(branch.len() <= BRANCH_HASH.3); self.transaction.branch = branch.to_string(); self } pub fn message(mut self, message: &str) -> Self { assert!(message.len() <= SIGNATURE_FRAGMENTS.3); self.transaction.signature_fragments = tryte_string::pad_right(&tryte_string::from_ascii(message), SIGNATURE_FRAGMENTS.3); self } pub fn tag(mut self, tag: &str) -> Self { assert!(IS_TRYTES.is_match(tag)); assert!(tag.len() <= TAG.3); self.transaction.tag = tryte_string::pad_right(tag, TAG.3); self } pub fn build(self) -> Transaction { self.transaction } } #[cfg(test)] mod tests { use super::*; use crate::convert::{tryte_string, trytes}; use crate::crypto::curl; use rayon::prelude::*; use std::time::{Duration, Instant}; // first we need to convert mainnet trytes to ict trytes // NOTE: length is already 2754 (instead of 2673 on the mainnet) const MAINNET_TRYTES: &str = "SEGQSWYCJHRLJYEGZLRYQAZPLVRAYIWGWJUMFFX99UZUKBQNFYAOQLOFARIKNEBKDRHJJWDJARXTNPHPAODJRSGJBVVYBVJHZALJWDCJHZRSACOVCVVAVHZVTPFTAJWVGFSVLSYXHNNXEGSMJHDBZKGFQNYJJJBAPDHFFGZ9POSOMWTDPGXI9KQRLMUVWNEQDANMXROVORJVALWVGDDJAFOOBXUKVCCIVXSSHZUCZV9XVBASLWX9NXPWGMGYCRD9ILQMKIGPBGGMKAIJKNALBLABATYFVIRBKTXTWNUZAUXRASB9EEIQHWBD9ZYUDBUPBSWXVYXQXECRCHQAYH9ZBUZBASPOIGBSGWJYFKFRITUBVMCYGCMAPTXOIWEVTUXSUOUPTUQOPMMPUTHXMOP9CW9THAZXEPMOMNEOBLUBPOAIOBEBERRZCIKHSTDWUSUPUWNJOCLNZDCEKWWAAJDPJXJEHHSYFN9MH9BGUDQ9CSZBIHRC9PSQJPGKH9ILZDWUWLEKWFKUFFFIMOQKRMKOYXEJHXLCEGCGGKHGJUHOXINSWCKRNMUNAJDCVLZGEBII9ASTYFTDYDZIZSNHIWHSQ9HODQMVNDKMKHCFDXIIGDIVJSBOOE9GRIXCD9ZUTWCUDKFTETSYSRBQABXCXZFOWQMQFXHYZWD9JZXUWHILMRNWXSGUMIIXZYCTWWHCWMSSTCNSQXQXMQPTM9MOQMIVDYNNARDCVNQEDTBKWOIOSKPKPOZHJGJJGNYWQWUWAZMBZJ9XEJMRVRYFQPJ9NOIIXEGIKMMN9DXYQUILRSCSJDIDN9DCTFGQIYWROZQIEQTKMRVLGGDGA9UVZPNRGSVTZYAPMWFUWDEUULSEEGAGITPJQ9DBEYEN9NVJPUWZTOTJHEQIXAPDOICBNNCJVDNM9YRNXMMPCOYHJDUFNCYTZGRCBZKOLHHUK9VOZWHEYQND9WUHDNGFTAS99MRCAU9QOYVUZKTIBDNAAPNEZBQPIRUFUMAWVTCXSXQQIYQPRFDUXCLJNMEIKVAINVCCZROEWEX9XVRM9IHLHQCKC9VLK9ZZWFBJUZKGJCSOPQPFVVAUDLKFJIJKMLZXFBMXLMWRSNDXRMMDLE9VBPUZB9SVLTMHA9DDDANOKIPY9ULDWAKOUDFEDHZDKMU9VMHUSFG9HRGZAZULEJJTEH9SLQDOMZTLVMBCXVNQPNKXRLBOUCCSBZRJCZIUFTFBKFVLKRBPDKLRLZSMMIQNMOZYFBGQFKUJYIJULGMVNFYJWPKPTSMYUHSUEXIPPPPPJTMDQLFFSFJFEPNUBDEDDBPGAOEJGQTHIWISLRDAABO9H9CSIAXPPJYCRFRCIH9TVBZKTCK9SPQZUYMUOKMZYOMPRHRGF9UAKZTZZG9VVVTIHMSNDREUOUOSLKUHTNFXTNSJVPVWCQXUDIMJIAMBPXUGBNDTBYPKYQYJJCDJSCTTWHOJKORLHGKRJMDCMRHSXHHMQBFJWZWHNUHZLYOAFQTRZFXDBYASYKWEVHKYDTJIAUKNCCEPSW9RITZXBOFKBAQOWHKTALQSCHARLUUGXISDMBVEUKOVXTKTEVKLGYVYHPNYWKNLCVETWIHHVTBWT9UPMTQWBZPRPRSISUBIBECVDNIZQULAGLONGVFLVZPBMHJND9CEVIXSYGFZAGGN9MQYOAKMENSEOGCUNKEJTDLEDCD9LGKYANHMZFSSDDZJKTKUJSFL9GYFDICTPJEPDSBXDQTARJQEWUVWDWSQPKIHPJONKHESSQH9FNQEO9WUCFDWPPPTIQPWCVDYTTWPLCJJVYNKE9ZEJNQBEJBMDBLNJKQDOQOHVS9VY9UPSU9KZVDFOESHNRRWBK9EZCYALAUYFGPCEWJQDXFENSNQEAUWDXJGOMCLQUQWMCPHOBZZ9SZJ9KZXSHDLPHPNYMVUJQSQETTN9SG9SIANJHWUYQXZXAJLYHCZYRGITZYQLAAYDVQVNKCDIYWAYBAFBMAYEAEAGMTJGJRSNHBHCEVIQRXEFVWJWOPU9FPDOWIFL9EWGHICRBNRITJDZNYACOGTUDBZYIYZZWAOCDBQFFNTTSTGKECWTVWZSPHX9HNRUYEAEWXENEIDLVVFMZFVPUNHMQPAIOKVIBDIHQIHFGRJOHHONPLGBSJUD9HHDTQQUZN9NVJYOAUMXMMOCNUFLZ9BAJSZMDMPQHPWSFVWOJQDPHV9DYSQPIBL9LYZHQKKOVF9TFVTTXQEUWFQSLGLVTGK99VSUEDXIBIWCQHDQQSQLDHZ9999999999999999999TRINITY99999999999999999999TNXSQ9D99A99999999B99999999MXKZAGDGKVADXOVCAXEQYZGOGQKDLKIUPYXIL9PXYBQXGYDEGNXTFURSWQYLJDFKEV9VVBBQLTLHIBTFYOGBHPUUHS9CKWSAPIMDIRNSUJ9CFPGKTUFAGQYVMFKOZSVAHIFJXWCFBZLICUWF9GNDZWCOWDUIIZ9999OXNRVXLBKJXEZMVABR9UQBVSTBDFSAJVRRNFEJRL9UFTOFPJHQMQKAJHDBIQAETS9OUVTQ9DSPAOZ9999TRINITY99999999999999999999LPZYMWQME999999999MMMMMMMMMDTIZE9999999999999999999999"; const EXAMPLE_ADDR: &str = "BAJSZMDMPQHPWSFVWOJQDPHV9DYSQPIBL9LYZHQKKOVF9TFVTTXQEUWFQSLGLVTGK99VSUEDXIBIWCQHD"; #[test] fn test_transaction_decoding() { let example_trytes = get_example_trytes(); let tx = Transaction::from_tryte_string(&example_trytes); assert_eq!(EXAMPLE_ADDR, tx.address); assert_eq!(-7_297_419_313, tx.value); assert_eq!(1_544_207_541_879, tx.attachment_timestamp); } #[test] fn test_transaction_encoding_decoding() { let orig = Transaction::from_tryte_string(&get_example_trytes()); let copy = Transaction::from_tryte_string(&orig.as_tryte_string()); assert_eq!(orig.address, copy.address); assert_eq!(orig.tag, copy.tag); assert_eq!(orig.value, copy.value); assert_eq!(orig.as_tryte_string(), copy.as_tryte_string()); let trits = trits::from_tx_trytes(&orig.as_trytes()); let orig_hash = tryte_string::from_trits_243(&curl::curl_tx(orig.as_trits(), 123)); let copy_hash = tryte_string::from_trits_243(&curl::curl_tx(copy.as_trits(), 123)); assert_eq!(orig_hash, copy_hash); } fn get_example_trytes() -> String { let sig_msg_frag = MAINNET_TRYTES.get(0..2187).unwrap(); let extra_data_digest = MAINNET_TRYTES.get((2187 + 162)..(2187 + 162 + 81)).unwrap(); //copied bundle hash let addr_value_tag_timestamps = MAINNET_TRYTES.get(2187..(2187 + 162)).unwrap(); let rest = MAINNET_TRYTES.get((2187 + 162 + 81)..).unwrap(); format!( "{}{}{}{}", sig_msg_frag, extra_data_digest, addr_value_tag_timestamps, rest ) } /// This test creates 1000 different transactions and hashes them sequentially with the default /// transaction hashing algorithm (at the time of writing: Curl-27). /// /// Use `cargo test bench_create_1000_transactions_with_hash` --release -- --nocapture /// to get production results. /// /// Last results: /// ~542 ms (roughly 2000 PoW-less tps) #[test] fn bench_create_1000_transactions_with_hash() { let start = Instant::now(); for i in 0..1000 { let hash = Transaction::default().message(&i.to_string()).get_hash(); } let stop = start.elapsed(); println!( "{} ms", stop.as_secs() * 1000 + u64::from(stop.subsec_millis()) ); } /// Same as test before, but parallel using 'rayon'. /// /// Last results: /// ~203 ms (roughly 5000 PoW-less tps) #[test] fn bench_create_1000_transactions_with_hash_par() { let start = Instant::now(); (0..1000_u32).into_par_iter().for_each(|i: u32| { let hash = Transaction::default().message(&i.to_string()).get_hash(); }); let stop = start.elapsed(); println!( "{} ms", stop.as_secs() * 1000 + u64::from(stop.subsec_millis()) ); } }
}
mod.rs
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::FsGccfg { #[doc = r" Modifies the contents of the register"] #[inline(always)] 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(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline(always)] 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" Value of the field"] pub struct PwrdwnR { bits: u8, } impl PwrdwnR { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct VbusasenR { bits: u8, } impl VbusasenR { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct VbusbsenR { bits: u8, } impl VbusbsenR { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct SofoutenR { bits: u8, } impl SofoutenR { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Proxy"] pub struct _PwrdwnW<'a> { w: &'a mut W, } impl<'a> _PwrdwnW<'a> { #[doc = r" Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((bits & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _VbusasenW<'a> { w: &'a mut W, } impl<'a> _VbusasenW<'a> { #[doc = r" Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 18; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((bits & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _VbusbsenW<'a> { w: &'a mut W, } impl<'a> _VbusbsenW<'a> { #[doc = r" Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 19; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((bits & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _SofoutenW<'a> { w: &'a mut W, } impl<'a> _SofoutenW<'a> { #[doc = r" Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 20; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((bits & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 16 - Power down"] #[inline(always)] pub fn pwrdwn(&self) -> PwrdwnR { let bits = { const MASK: u8 = 1; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 }; PwrdwnR { bits } } #[doc = "Bit 18 - Enable the VBUS sensing device"] #[inline(always)] pub fn vbusasen(&self) -> VbusasenR { let bits = { const MASK: u8 = 1; const OFFSET: u8 = 18; ((self.bits >> OFFSET) & MASK as u32) as u8 }; VbusasenR { bits } } #[doc = "Bit 19 - Enable the VBUS sensing device"] #[inline(always)] pub fn vbusbsen(&self) -> VbusbsenR { let bits = { const MASK: u8 = 1; const OFFSET: u8 = 19; ((self.bits >> OFFSET) & MASK as u32) as u8 }; VbusbsenR { bits } } #[doc = "Bit 20 - SOF output enable"] #[inline(always)] pub fn sofouten(&self) -> SofoutenR { let bits = { const MASK: u8 = 1; const OFFSET: u8 = 20; ((self.bits >> OFFSET) & MASK as u32) as u8 }; SofoutenR { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline(always)] pub fn reset_value() -> W
#[doc = r" Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 16 - Power down"] #[inline(always)] pub fn pwrdwn(&mut self) -> _PwrdwnW { _PwrdwnW { w: self } } #[doc = "Bit 18 - Enable the VBUS sensing device"] #[inline(always)] pub fn vbusasen(&mut self) -> _VbusasenW { _VbusasenW { w: self } } #[doc = "Bit 19 - Enable the VBUS sensing device"] #[inline(always)] pub fn vbusbsen(&mut self) -> _VbusbsenW { _VbusbsenW { w: self } } #[doc = "Bit 20 - SOF output enable"] #[inline(always)] pub fn sofouten(&mut self) -> _SofoutenW { _SofoutenW { w: self } } }
{ W { bits: 0 } }
hardcore.rs
//! As part of the workshop you don't need to touch this contract. //! It has some hardcode stuff that is needed for you to have fun. //! But I'm glad you're looking for more. use crate::*; use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; #[allow(unused_imports)] use near_sdk::json_types::Base64VecU8; use near_sdk::serde::{Deserialize, Serialize}; use near_sdk::{env, ext_contract, Balance, Gas}; pub type AccountIndex = u32; pub const BERRYCLUB_CONTRACT_ID: &str = "berryclub.testnet"; pub const NO_DEPOSIT: Balance = 0; pub const BUY_TOKENS_GAS: Gas = 5_000_000_000_000; pub const GET_LINES_GAS: Gas = 50_000_000_000_000; pub const BASE_DRAW_GAS: Gas = 50_000_000_000_000; pub const GAS_FOR_RENDER_WITH: Gas = GET_LINES_GAS + 20_000_000_000_000; pub const GAS_PER_PIXEL: Gas = 50_000_000_000; #[derive(BorshDeserialize, BorshSerialize, Copy, Clone)] pub struct Pixel { pub color: u32, pub owner_id: AccountIndex, } impl Default for Pixel { fn default() -> Self { Self { color: 0xffffff,
owner_id: 0, } } } #[derive(BorshDeserialize, BorshSerialize)] pub struct PixelLine(pub Vec<Pixel>); impl Default for PixelLine { fn default() -> Self { Self(vec![Pixel::default(); BOARD_WIDTH as usize]) } } #[derive(Serialize, Deserialize)] #[serde(crate = "near_sdk::serde")] pub struct SetPixelRequest { pub x: u32, pub y: u32, pub color: u32, } impl SetPixelRequest { pub fn is_valid(&self) -> bool { return self.x < BOARD_WIDTH && self.y < BOARD_HEIGHT && self.color <= 0xffffff; } pub fn assert_valid(&self) { assert!(self.x < BOARD_WIDTH, "X is out of bounds"); assert!(self.y < BOARD_HEIGHT, "Y is out of bounds"); assert!(self.color <= 0xffffff, "Color is out of bounds"); } } #[ext_contract(ext_berryclub)] trait BerryclubContract { fn get_lines(&self, lines: Vec<u32>) -> Vec<Base64VecU8>; fn buy_tokens(&mut self); fn draw(&mut self, pixels: Vec<SetPixelRequest>); } pub(crate) fn draw(pixels: Vec<SetPixelRequest>) -> Promise { let mut board = [[b'.'; BOARD_WIDTH as usize]; BOARD_HEIGHT as usize]; let mut unique_pixels = vec![]; for pixel in pixels { if board[pixel.y as usize][pixel.x as usize] == b'.' { board[pixel.y as usize][pixel.x as usize] = b'X'; unique_pixels.push(pixel); } } for line in &board { env::log(line); } #[cfg(feature = "for_real")] { let gas = BASE_DRAW_GAS + (unique_pixels.len() as u64) * GAS_PER_PIXEL; ext_berryclub::draw( unique_pixels, &BERRYCLUB_CONTRACT_ID.to_string(), NO_DEPOSIT, gas, ) } #[cfg(not(feature = "for_real"))] { Promise::new(env::current_account_id()) } } pub(crate) fn decode_board(lines: Vec<Base64VecU8>) -> Vec<Vec<u32>> { lines .into_iter() .map(|bytes| { PixelLine::try_from_slice(&bytes.0) .unwrap() .0 .into_iter() .map(|p| p.color) .collect() }) .collect() } #[near_bindgen] impl Contract { #[cfg(feature = "for_real")] pub fn buy_avocado(&mut self) -> Promise { ext_berryclub::buy_tokens( &BERRYCLUB_CONTRACT_ID.to_string(), 50 * 10u128.pow(24), BUY_TOKENS_GAS, ) } pub fn render(method_name: String) -> Promise { ext_berryclub::get_lines( (0..BOARD_HEIGHT).collect(), &BERRYCLUB_CONTRACT_ID.to_string(), NO_DEPOSIT, GET_LINES_GAS, ) .then(Promise::new(env::current_account_id()).function_call( method_name.into_bytes(), env::input().unwrap(), NO_DEPOSIT, env::prepaid_gas() - GAS_FOR_RENDER_WITH, )) } } #[cfg(not(target = "wasm32"))] #[cfg(test)] pub(crate) fn debug_print_pixels(pixels: &[SetPixelRequest]) -> Vec<String> { let mut board = vec![vec![b'.'; BOARD_WIDTH as usize]; BOARD_HEIGHT as usize]; for pixel in pixels { board[pixel.y as usize][pixel.x as usize] = b'X'; } let board = board .into_iter() .map(|line| String::from_utf8(line.to_vec()).unwrap()) .collect::<Vec<_>>(); println!(); for (i, line) in board.iter().enumerate() { println!("{:02} {}", i, line); } board }
owl.carousel.min.js
/** * Owl Carousel v2.3.2 * Copyright 2013-2018 David Deutsch * Licensed under: SEE LICENSE IN https://github.com/OwlCarousel2/OwlCarousel2/blob/master/LICENSE */ !function(a,b,c,d){function e(b,c){this.settings=null,this.options=a.extend({},e.Defaults,c),this.$element=a(b),this._handlers={},this._plugins={},this._supress={},this._current=null,this._speed=null,this._coordinates=[],this._breakpoint=null,this._width=null,this._items=[],this._clones=[],this._mergers=[],this._widths=[],this._invalidated={},this._pipe=[],this._drag={time:null,target:null,pointer:null,stage:{start:null,current:null},direction:null},this._states={current:{},tags:{initializing:["busy"],animating:["busy"],dragging:["interacting"]}},a.each(["onResize","onThrottledResize"],a.proxy(function(b,c){this._handlers[c]=a.proxy(this[c],this)},this)),a.each(e.Plugins,a.proxy(function(a,b){this._plugins[a.charAt(0).toLowerCase()+a.slice(1)]=new b(this)},this)),a.each(e.Workers,a.proxy(function(b,c){this._pipe.push({filter:c.filter,run:a.proxy(c.run,this)})},this)),this.setup(),this.initialize()}e.Defaults={items:3,loop:!1,center:!1,rewind:!1,mouseDrag:!0,touchDrag:!0,pullDrag:!0,freeDrag:!1,margin:0,stagePadding:0,merge:!1,mergeFit:!0,autoWidth:!1,startPosition:0,rtl:!1,smartSpeed:250,fluidSpeed:!1,dragEndSpeed:!1,responsive:{},responsiveRefreshRate:200,responsiveBaseElement:b,fallbackEasing:"swing",info:!1,nestedItemSelector:!1,itemElement:"div",stageElement:"div",refreshClass:"owl-refresh",loadedClass:"owl-loaded",loadingClass:"owl-loading",rtlClass:"owl-rtl",responsiveClass:"owl-responsive",dragClass:"owl-drag",itemClass:"owl-item",stageClass:"owl-stage",stageOuterClass:"owl-stage-outer",grabClass:"owl-grab"},e.Width={Default:"default",Inner:"inner",Outer:"outer"},e.Type={Event:"event",State:"state"},e.Plugins={},e.Workers=[{filter:["width","settings"],run:function(){this._width=this.$element.width()}},{filter:["width","items","settings"],run:function(a){a.current=this._items&&this._items[this.relative(this._current)]}},{filter:["items","settings"],run:function(){this.$stage.children(".cloned").remove()}},{filter:["width","items","settings"],run:function(a){var b=this.settings.margin||"",c=!this.settings.autoWidth,d=this.settings.rtl,e={width:"auto","margin-left":d?b:"","margin-right":d?"":b};!c&&this.$stage.children().css(e),a.css=e}},{filter:["width","items","settings"],run:function(a){var b=(this.width()/this.settings.items).toFixed(3)-this.settings.margin,c=null,d=this._items.length,e=!this.settings.autoWidth,f=[];for(a.items={merge:!1,width:b};d--;)c=this._mergers[d],c=this.settings.mergeFit&&Math.min(c,this.settings.items)||c,a.items.merge=c>1||a.items.merge,f[d]=e?b*c:this._items[d].width();this._widths=f}},{filter:["items","settings"],run:function(){var b=[],c=this._items,d=this.settings,e=Math.max(2*d.items,4),f=2*Math.ceil(c.length/2),g=d.loop&&c.length?d.rewind?e:Math.max(e,f):0,h="",i="";for(g/=2;g>0;)b.push(this.normalize(b.length/2,!0)),h+=c[b[b.length-1]][0].outerHTML,b.push(this.normalize(c.length-1-(b.length-1)/2,!0)),i=c[b[b.length-1]][0].outerHTML+i,g-=1;this._clones=b,a(h).addClass("cloned").appendTo(this.$stage),a(i).addClass("cloned").prependTo(this.$stage)}},{filter:["width","items","settings"],run:function(){for(var a=this.settings.rtl?1:-1,b=this._clones.length+this._items.length,c=-1,d=0,e=0,f=[];++c<b;)d=f[c-1]||0,e=this._widths[this.relative(c)]+this.settings.margin,f.push(d+e*a);this._coordinates=f}},{filter:["width","items","settings"],run:function(){var a=this.settings.stagePadding,b=this._coordinates,c={width:Math.ceil(Math.abs(b[b.length-1]))+2*a,"padding-left":a||"","padding-right":a||""};this.$stage.css(c)}},{filter:["width","items","settings"],run:function(a){var b=this._coordinates.length,c=!this.settings.autoWidth,d=this.$stage.children();if(c&&a.items.merge)for(;b--;)a.css.width=this._widths[this.relative(b)],d.eq(b).css(a.css);else c&&(a.css.width=a.items.width,d.css(a.css))}},{filter:["items"],run:function(){this._coordinates.length<1&&this.$stage.removeAttr("style")}},{filter:["width","items","settings"],run:function(a){a.current=a.current?this.$stage.children().index(a.current):0,a.current=Math.max(this.minimum(),Math.min(this.maximum(),a.current)),this.reset(a.current)}},{filter:["position"],run:function(){this.animate(this.coordinates(this._current))}},{filter:["width","position","items","settings"],run:function(){var a,b,c,d,e=this.settings.rtl?1:-1,f=2*this.settings.stagePadding,g=this.coordinates(this.current())+f,h=g+this.width()*e,i=[];for(c=0,d=this._coordinates.length;c<d;c++)a=this._coordinates[c-1]||0,b=Math.abs(this._coordinates[c])+f*e,(this.op(a,"<=",g)&&this.op(a,">",h)||this.op(b,"<",g)&&this.op(b,">",h))&&i.push(c);this.$stage.children(".active").removeClass("active"),this.$stage.children(":eq("+i.join("), :eq(")+")").addClass("active"),this.$stage.children(".center").removeClass("center"),this.settings.center&&this.$stage.children().eq(this.current()).addClass("center")}}],e.prototype.initializeStage=function(){this.$stage=this.$element.find("."+this.settings.stageClass),this.$stage.length||(this.$element.addClass(this.options.loadingClass),this.$stage=a("<"+this.settings.stageElement+' class="'+this.settings.stageClass+'"/>').wrap('<div class="'+this.settings.stageOuterClass+'"/>'),this.$element.append(this.$stage.parent()))},e.prototype.initializeItems=function(){var b=this.$element.find(".owl-item");if(b.length)return this._items=b.get().map(function(b){return a(b)}),this._mergers=this._items.map(function(){return 1}),void this.refresh();this.replace(this.$element.children().not(this.$stage.parent())),this.isVisible()?this.refresh():this.invalidate("width"),this.$element.removeClass(this.options.loadingClass).addClass(this.options.loadedClass)},e.prototype.initialize=function(){if(this.enter("initializing"),this.trigger("initialize"),this.$element.toggleClass(this.settings.rtlClass,this.settings.rtl),this.settings.autoWidth&&!this.is("pre-loading")){var a,b,c;a=this.$element.find("img"),b=this.settings.nestedItemSelector?"."+this.settings.nestedItemSelector:d,c=this.$element.children(b).width(),a.length&&c<=0&&this.preloadAutoWidthImages(a)}this.initializeStage(),this.initializeItems(),this.registerEventHandlers(),this.leave("initializing"),this.trigger("initialized")},e.prototype.isVisible=function(){return!this.settings.checkVisibility||this.$element.is(":visible")},e.prototype.setup=function(){var b=this.viewport(),c=this.options.responsive,d=-1,e=null;c?(a.each(c,function(a){a<=b&&a>d&&(d=Number(a))}),e=a.extend({},this.options,c[d]),"function"==typeof e.stagePadding&&(e.stagePadding=e.stagePadding()),delete e.responsive,e.responsiveClass&&this.$element.attr("class",this.$element.attr("class").replace(new RegExp("("+this.options.responsiveClass+"-)\\S+\\s","g"),"$1"+d))):e=a.extend({},this.options),this.trigger("change",{property:{name:"settings",value:e}}),this._breakpoint=d,this.settings=e,this.invalidate("settings"),this.trigger("changed",{property:{name:"settings",value:this.settings}})},e.prototype.optionsLogic=function(){this.settings.autoWidth&&(this.settings.stagePadding=!1,this.settings.merge=!1)},e.prototype.prepare=function(b){var c=this.trigger("prepare",{content:b});return c.data||(c.data=a("<"+this.settings.itemElement+"/>").addClass(this.options.itemClass).append(b)),this.trigger("prepared",{content:c.data}),c.data},e.prototype.update=function(){for(var b=0,c=this._pipe.length,d=a.proxy(function(a){return this[a]},this._invalidated),e={};b<c;)(this._invalidated.all||a.grep(this._pipe[b].filter,d).length>0)&&this._pipe[b].run(e),b++;this._invalidated={},!this.is("valid")&&this.enter("valid")},e.prototype.width=function(a){switch(a=a||e.Width.Default){case e.Width.Inner:case e.Width.Outer:return this._width;default:return this._width-2*this.settings.stagePadding+this.settings.margin}},e.prototype.refresh=function(){this.enter("refreshing"),this.trigger("refresh"),this.setup(),this.optionsLogic(),this.$element.addClass(this.options.refreshClass),this.update(),this.$element.removeClass(this.options.refreshClass),this.leave("refreshing"),this.trigger("refreshed")},e.prototype.onThrottledResize=function(){b.clearTimeout(this.resizeTimer),this.resizeTimer=b.setTimeout(this._handlers.onResize,this.settings.responsiveRefreshRate)},e.prototype.onResize=function(){return!!this._items.length&&(this._width!==this.$element.width()&&(!!this.isVisible()&&(this.enter("resizing"),this.trigger("resize").isDefaultPrevented()?(this.leave("resizing"),!1):(this.invalidate("width"),this.refresh(),this.leave("resizing"),void this.trigger("resized")))))},e.prototype.registerEventHandlers=function(){a.support.transition&&this.$stage.on(a.support.transition.end+".owl.core",a.proxy(this.onTransitionEnd,this)),!1!==this.settings.responsive&&this.on(b,"resize",this._handlers.onThrottledResize),this.settings.mouseDrag&&(this.$element.addClass(this.options.dragClass),this.$stage.on("mousedown.owl.core",a.proxy(this.onDragStart,this)),this.$stage.on("dragstart.owl.core selectstart.owl.core",function(){return!1})),this.settings.touchDrag&&(this.$stage.on("touchstart.owl.core",a.proxy(this.onDragStart,this)),this.$stage.on("touchcancel.owl.core",a.proxy(this.onDragEnd,this)))},e.prototype.onDragStart=function(b){var d=null;3!==b.which&&(a.support.transform?(d=this.$stage.css("transform").replace(/.*\(|\)| /g,"").split(","),d={x:d[16===d.length?12:4],y:d[16===d.length?13:5]}):(d=this.$stage.position(),d={x:this.settings.rtl?d.left+this.$stage.width()-this.width()+this.settings.margin:d.left,y:d.top}),this.is("animating")&&(a.support.transform?this.animate(d.x):this.$stage.stop(),this.invalidate("position")),this.$element.toggleClass(this.options.grabClass,"mousedown"===b.type),this.speed(0),this._drag.time=(new Date).getTime(),this._drag.target=a(b.target),this._drag.stage.start=d,this._drag.stage.current=d,this._drag.pointer=this.pointer(b),a(c).on("mouseup.owl.core touchend.owl.core",a.proxy(this.onDragEnd,this)),a(c).one("mousemove.owl.core touchmove.owl.core",a.proxy(function(b){var d=this.difference(this._drag.pointer,this.pointer(b));a(c).on("mousemove.owl.core touchmove.owl.core",a.proxy(this.onDragMove,this)),Math.abs(d.x)<Math.abs(d.y)&&this.is("valid")||(b.preventDefault(),this.enter("dragging"),this.trigger("drag"))},this)))},e.prototype.onDragMove=function(a){var b=null,c=null,d=null,e=this.difference(this._drag.pointer,this.pointer(a)),f=this.difference(this._drag.stage.start,e);this.is("dragging")&&(a.preventDefault(),this.settings.loop?(b=this.coordinates(this.minimum()),c=this.coordinates(this.maximum()+1)-b,f.x=((f.x-b)%c+c)%c+b):(b=this.settings.rtl?this.coordinates(this.maximum()):this.coordinates(this.minimum()),c=this.settings.rtl?this.coordinates(this.minimum()):this.coordinates(this.maximum()),d=this.settings.pullDrag?-1*e.x/5:0,f.x=Math.max(Math.min(f.x,b+d),c+d)),this._drag.stage.current=f,this.animate(f.x))},e.prototype.onDragEnd=function(b){var d=this.difference(this._drag.pointer,this.pointer(b)),e=this._drag.stage.current,f=d.x>0^this.settings.rtl?"left":"right";a(c).off(".owl.core"),this.$element.removeClass(this.options.grabClass),(0!==d.x&&this.is("dragging")||!this.is("valid"))&&(this.speed(this.settings.dragEndSpeed||this.settings.smartSpeed),this.current(this.closest(e.x,0!==d.x?f:this._drag.direction)),this.invalidate("position"),this.update(),this._drag.direction=f,(Math.abs(d.x)>3||(new Date).getTime()-this._drag.time>300)&&this._drag.target.one("click.owl.core",function(){return!1})),this.is("dragging")&&(this.leave("dragging"),this.trigger("dragged"))},e.prototype.closest=function(b,c){var e=-1,f=30,g=this.width(),h=this.coordinates();return this.settings.freeDrag||a.each(h,a.proxy(function(a,i){return"left"===c&&b>i-f&&b<i+f?e=a:"right"===c&&b>i-g-f&&b<i-g+f?e=a+1:this.op(b,"<",i)&&this.op(b,">",h[a+1]!==d?h[a+1]:i-g)&&(e="left"===c?a+1:a),-1===e},this)),this.settings.loop||(this.op(b,">",h[this.minimum()])?e=b=this.minimum():this.op(b,"<",h[this.maximum()])&&(e=b=this.maximum())),e},e.prototype.animate=function(b){var c=this.speed()>0;this.is("animating")&&this.onTransitionEnd(),c&&(this.enter("animating"),this.trigger("translate")),a.support.transform3d&&a.support.transition?this.$stage.css({transform:"translate3d("+b+"px,0px,0px)",transition:this.speed()/1e3+"s"}):c?this.$stage.animate({left:b+"px"},this.speed(),this.settings.fallbackEasing,a.proxy(this.onTransitionEnd,this)):this.$stage.css({left:b+"px"})},e.prototype.is=function(a){return this._states.current[a]&&this._states.current[a]>0},e.prototype.current=function(a){if(a===d)return this._current;if(0===this._items.length)return d;if(a=this.normalize(a),this._current!==a){var b=this.trigger("change",{property:{name:"position",value:a}});b.data!==d&&(a=this.normalize(b.data)),this._current=a,this.invalidate("position"),this.trigger("changed",{property:{name:"position",value:this._current}})}return this._current},e.prototype.invalidate=function(b){return"string"===a.type(b)&&(this._invalidated[b]=!0,this.is("valid")&&this.leave("valid")),a.map(this._invalidated,function(a,b){return b})},e.prototype.reset=function(a){(a=this.normalize(a))!==d&&(this._speed=0,this._current=a,this.suppress(["translate","translated"]),this.animate(this.coordinates(a)),this.release(["translate","translated"]))},e.prototype.normalize=function(a,b){var c=this._items.length,e=b?0:this._clones.length;return!this.isNumeric(a)||c<1?a=d:(a<0||a>=c+e)&&(a=((a-e/2)%c+c)%c+e/2),a},e.prototype.relative=function(a){return a-=this._clones.length/2,this.normalize(a,!0)},e.prototype.maximum=function(a){var b,c,d,e=this.settings,f=this._coordinates.length;if(e.loop)f=this._clones.length/2+this._items.length-1;else if(e.autoWidth||e.merge){if(b=this._items.length)for(c=this._items[--b].width(),d=this.$element.width();b--&&!((c+=this._items[b].width()+this.settings.margin)>d););f=b+1}else f=e.center?this._items.length-1:this._items.length-e.items;return a&&(f-=this._clones.length/2),Math.max(f,0)},e.prototype.minimum=function(a){return a?0:this._clones.length/2},e.prototype.items=function(a){return a===d?this._items.slice():(a=this.normalize(a,!0),this._items[a])},e.prototype.mergers=function(a){return a===d?this._mergers.slice():(a=this.normalize(a,!0),this._mergers[a])},e.prototype.clones=function(b){var c=this._clones.length/2,e=c+this._items.length,f=function(a){return a%2==0?e+a/2:c-(a+1)/2};return b===d?a.map(this._clones,function(a,b){return f(b)}):a.map(this._clones,function(a,c){return a===b?f(c):null})},e.prototype.speed=function(a){return a!==d&&(this._speed=a),this._speed},e.prototype.coordinates=function(b){var c,e=1,f=b-1;return b===d?a.map(this._coordinates,a.proxy(function(a,b){return this.coordinates(b)},this)):(this.settings.center?(this.settings.rtl&&(e=-1,f=b+1),c=this._coordinates[b],c+=(this.width()-c+(this._coordinates[f]||0))/2*e):c=this._coordinates[f]||0,c=Math.ceil(c))},e.prototype.duration=function(a,b,c){return 0===c?0:Math.min(Math.max(Math.abs(b-a),1),6)*Math.abs(c||this.settings.smartSpeed)},e.prototype.to=function(a,b){var c=this.current(),d=null,e=a-this.relative(c),f=(e>0)-(e<0),g=this._items.length,h=this.minimum(),i=this.maximum();this.settings.loop?(!this.settings.rewind&&Math.abs(e)>g/2&&(e+=-1*f*g),a=c+e,(d=((a-h)%g+g)%g+h)!==a&&d-e<=i&&d-e>0&&(c=d-e,a=d,this.reset(c))):this.settings.rewind?(i+=1,a=(a%i+i)%i):a=Math.max(h,Math.min(i,a)),this.speed(this.duration(c,a,b)),this.current(a),this.isVisible()&&this.update()},e.prototype.next=function(a){a=a||!1,this.to(this.relative(this.current())+1,a)},e.prototype.prev=function(a){a=a||!1,this.to(this.relative(this.current())-1,a)},e.prototype.onTransitionEnd=function(a){if(a!==d&&(a.stopPropagation(),(a.target||a.srcElement||a.originalTarget)!==this.$stage.get(0)))return!1;this.leave("animating"),this.trigger("translated")},e.prototype.viewport=function(){var d;return this.options.responsiveBaseElement!==b?d=a(this.options.responsiveBaseElement).width():b.innerWidth?d=b.innerWidth:c.documentElement&&c.documentElement.clientWidth?d=c.documentElement.clientWidth:console.warn("Can not detect viewport width."),d},e.prototype.replace=function(b){this.$stage.empty(),this._items=[],b&&(b=b instanceof jQuery?b:a(b)),this.settings.nestedItemSelector&&(b=b.find("."+this.settings.nestedItemSelector)),b.filter(function(){return 1===this.nodeType}).each(a.proxy(function(a,b){b=this.prepare(b),this.$stage.append(b),this._items.push(b),this._mergers.push(1*b.find("[data-merge]").addBack("[data-merge]").attr("data-merge")||1)},this)),this.reset(this.isNumeric(this.settings.startPosition)?this.settings.startPosition:0),this.invalidate("items")},e.prototype.add=function(b,c){var e=this.relative(this._current);c=c===d?this._items.length:this.normalize(c,!0),b=b instanceof jQuery?b:a(b),this.trigger("add",{content:b,position:c}),b=this.prepare(b),0===this._items.length||c===this._items.length?(0===this._items.length&&this.$stage.append(b),0!==this._items.length&&this._items[c-1].after(b),this._items.push(b),this._mergers.push(1*b.find("[data-merge]").addBack("[data-merge]").attr("data-merge")||1)):(this._items[c].before(b),this._items.splice(c,0,b),this._mergers.splice(c,0,1*b.find("[data-merge]").addBack("[data-merge]").attr("data-merge")||1)),this._items[e]&&this.reset(this._items[e].index()),this.invalidate("items"),this.trigger("added",{content:b,position:c})},e.prototype.remove=function(a){(a=this.normalize(a,!0))!==d&&(this.trigger("remove",{content:this._items[a],position:a}),this._items[a].remove(),this._items.splice(a,1),this._mergers.splice(a,1),this.invalidate("items"),this.trigger("removed",{content:null,position:a}))},e.prototype.preloadAutoWidthImages=function(b){b.each(a.proxy(function(b,c){this.enter("pre-loading"),c=a(c),a(new Image).one("load",a.proxy(function(a){c.attr("src",a.target.src),c.css("opacity",1),this.leave("pre-loading"),!this.is("pre-loading")&&!this.is("initializing")&&this.refresh()},this)).attr("src",c.attr("src")||c.attr("data-src")||c.attr("data-src-retina"))},this))},e.prototype.destroy=function(){this.$element.off(".owl.core"),this.$stage.off(".owl.core"),a(c).off(".owl.core"),!1!==this.settings.responsive&&(b.clearTimeout(this.resizeTimer),this.off(b,"resize",this._handlers.onThrottledResize));for(var d in this._plugins)this._plugins[d].destroy();this.$stage.children(".cloned").remove(),this.$stage.unwrap(),this.$stage.children().contents().unwrap(),this.$stage.children().unwrap(),this.$stage.remove(),this.$element.removeClass(this.options.refreshClass).removeClass(this.options.loadingClass).removeClass(this.options.loadedClass).removeClass(this.options.rtlClass).removeClass(this.options.dragClass).removeClass(this.options.grabClass).attr("class",this.$element.attr("class").replace(new RegExp(this.options.responsiveClass+"-\\S+\\s","g"),"")).removeData("owl.carousel")},e.prototype.op=function(a,b,c){var d=this.settings.rtl;switch(b){case"<":return d?a>c:a<c;case">":return d?a<c:a>c;case">=":return d?a<=c:a>=c;case"<=":return d?a>=c:a<=c}},e.prototype.on=function(a,b,c,d){a.addEventListener?a.addEventListener(b,c,d):a.attachEvent&&a.attachEvent("on"+b,c)},e.prototype.off=function(a,b,c,d){a.removeEventListener?a.removeEventListener(b,c,d):a.detachEvent&&a.detachEvent("on"+b,c)},e.prototype.trigger=function(b,c,d,f,g){var h={item:{count:this._items.length,index:this.current()}},i=a.camelCase(a.grep(["on",b,d],function(a){return a}).join("-").toLowerCase()),j=a.Event([b,"owl",d||"carousel"].join(".").toLowerCase(),a.extend({relatedTarget:this},h,c));return this._supress[b]||(a.each(this._plugins,function(a,b){b.onTrigger&&b.onTrigger(j)}),this.register({type:e.Type.Event,name:b}),this.$element.trigger(j),this.settings&&"function"==typeof this.settings[i]&&this.settings[i].call(this,j)),j},e.prototype.enter=function(b){a.each([b].concat(this._states.tags[b]||[]),a.proxy(function(a,b){this._states.current[b]===d&&(this._states.current[b]=0),this._states.current[b]++},this))},e.prototype.leave=function(b){a.each([b].concat(this._states.tags[b]||[]),a.proxy(function(a,b){this._states.current[b]--},this))},e.prototype.register=function(b){if(b.type===e.Type.Event){if(a.event.special[b.name]||(a.event.special[b.name]={}),!a.event.special[b.name].owl){var c=a.event.special[b.name]._default;a.event.special[b.name]._default=function(a){return!c||!c.apply||a.namespace&&-1!==a.namespace.indexOf("owl")?a.namespace&&a.namespace.indexOf("owl")>-1:c.apply(this,arguments)},a.event.special[b.name].owl=!0}}else b.type===e.Type.State&&(this._states.tags[b.name]?this._states.tags[b.name]=this._states.tags[b.name].concat(b.tags):this._states.tags[b.name]=b.tags,this._states.tags[b.name]=a.grep(this._states.tags[b.name],a.proxy(function(c,d){return a.inArray(c,this._states.tags[b.name])===d},this)))},e.prototype.suppress=function(b){a.each(b,a.proxy(function(a,b){this._supress[b]=!0},this))},e.prototype.release=function(b){a.each(b,a.proxy(function(a,b){delete this._supress[b]},this))},e.prototype.pointer=function(a){var c={x:null,y:null};return a=a.originalEvent||a||b.event,a=a.touches&&a.touches.length?a.touches[0]:a.changedTouches&&a.changedTouches.length?a.changedTouches[0]:a,a.pageX?(c.x=a.pageX,c.y=a.pageY):(c.x=a.clientX,c.y=a.clientY),c},e.prototype.isNumeric=function(a){return!isNaN(parseFloat(a))},e.prototype.difference=function(a,b){return{x:a.x-b.x,y:a.y-b.y}},a.fn.owlCarousel=function(b){var c=Array.prototype.slice.call(arguments,1);return this.each(function(){var d=a(this),f=d.data("owl.carousel");f||(f=new e(this,"object"==typeof b&&b),d.data("owl.carousel",f),a.each(["next","prev","to","destroy","refresh","replace","add","remove"],function(b,c){f.register({type:e.Type.Event,name:c}),f.$element.on(c+".owl.carousel.core",a.proxy(function(a){a.namespace&&a.relatedTarget!==this&&(this.suppress([c]),f[c].apply(this,[].slice.call(arguments,1)),this.release([c]))},f))})),"string"==typeof b&&"_"!==b.charAt(0)&&f[b].apply(f,c)})},a.fn.owlCarousel.Constructor=e}(window.Zepto||window.jQuery,window,document),function(a,b,c,d){var e=function(b){this._core=b,this._interval=null,this._visible=null,this._handlers={"initialized.owl.carousel":a.proxy(function(a){a.namespace&&this._core.settings.autoRefresh&&this.watch()},this)},this._core.options=a.extend({},e.Defaults,this._core.options),this._core.$element.on(this._handlers)};e.Defaults={autoRefresh:!0,autoRefreshInterval:500},e.prototype.watch=function(){this._interval||(this._visible=this._core.isVisible(),this._interval=b.setInterval(a.proxy(this.refresh,this),this._core.settings.autoRefreshInterval))},e.prototype.refresh=function(){this._core.isVisible()!==this._visible&&(this._visible=!this._visible,this._core.$element.toggleClass("owl-hidden",!this._visible),this._visible&&this._core.invalidate("width")&&this._core.refresh())},e.prototype.destroy=function(){var a,c;b.clearInterval(this._interval);for(a in this._handlers)this._core.$element.off(a,this._handlers[a]);for(c in Object.getOwnPropertyNames(this))"function"!=typeof this[c]&&(this[c]=null)},a.fn.owlCarousel.Constructor.Plugins.AutoRefresh=e}(window.Zepto||window.jQuery,window,document),function(a,b,c,d){var e=function(b){this._core=b,this._loaded=[],this._handlers={"initialized.owl.carousel change.owl.carousel resized.owl.carousel":a.proxy(function(b){if(b.namespace&&this._core.settings&&this._core.settings.lazyLoad&&(b.property&&"position"==b.property.name||"initialized"==b.type))for(var c=this._core.settings,e=c.center&&Math.ceil(c.items/2)||c.items,f=c.center&&-1*e||0,g=(b.property&&b.property.value!==d?b.property.value:this._core.current())+f,h=this._core.clones().length,i=a.proxy(function(a,b){this.load(b)},this);f++<e;)this.load(h/2+this._core.relative(g)),h&&a.each(this._core.clones(this._core.relative(g)),i),g++},this)},this._core.options=a.extend({},e.Defaults,this._core.options),this._core.$element.on(this._handlers)};e.Defaults={lazyLoad:!1},e.prototype.load=function(c){var d=this._core.$stage.children().eq(c),e=d&&d.find(".owl-lazy");!e||a.inArray(d.get(0),this._loaded)>-1||(e.each(a.proxy(function(c,d){var e,f=a(d),g=b.devicePixelRatio>1&&f.attr("data-src-retina")||f.attr("data-src")||f.attr("data-srcset");this._core.trigger("load",{element:f,url:g},"lazy"),f.is("img")?f.one("load.owl.lazy",a.proxy(function(){f.css("opacity",1),this._core.trigger("loaded",{element:f,url:g},"lazy")},this)).attr("src",g):f.is("source")?f.one("load.owl.lazy",a.proxy(function(){this._core.trigger("loaded",{element:f,url:g},"lazy")},this)).attr("srcset",g):(e=new Image,e.onload=a.proxy(function(){f.css({"background-image":'url("'+g+'")',opacity:"1"}),this._core.trigger("loaded",{element:f,url:g},"lazy")},this),e.src=g)},this)),this._loaded.push(d.get(0)))},e.prototype.destroy=function(){var a,b;for(a in this.handlers)this._core.$element.off(a,this.handlers[a]);for(b in Object.getOwnPropertyNames(this))"function"!=typeof this[b]&&(this[b]=null)},a.fn.owlCarousel.Constructor.Plugins.Lazy=e}(window.Zepto||window.jQuery,window,document),function(a,b,c,d){var e=function(c){this._core=c,this._handlers={"initialized.owl.carousel refreshed.owl.carousel":a.proxy(function(a){a.namespace&&this._core.settings.autoHeight&&this.update()},this),"changed.owl.carousel":a.proxy(function(a){a.namespace&&this._core.settings.autoHeight&&"position"===a.property.name&&(console.log("update called"),this.update())},this),"loaded.owl.lazy":a.proxy(function(a){a.namespace&&this._core.settings.autoHeight&&a.element.closest("."+this._core.settings.itemClass).index()===this._core.current()&&this.update()},this)},this._core.options=a.extend({},e.Defaults,this._core.options),this._core.$element.on(this._handlers),this._intervalId=null;var d=this;a(b).on("load",function(){d._core.settings.autoHeight&&d.update()}),a(b).resize(function(){d._core.settings.autoHeight&&(null!=d._intervalId&&clearTimeout(d._intervalId),d._intervalId=setTimeout(function(){d.update()},250))})};e.Defaults={autoHeight:!1,autoHeightClass:"owl-height"},e.prototype.update=function(){var b=this._core._current,c=b+this._core.settings.items,d=this._core.$stage.children().toArray().slice(b,c),e=[],f=0;a.each(d,function(b,c){e.push(a(c).height())}),f=Math.max.apply(null,e),this._core.$stage.parent().height(f).addClass(this._core.settings.autoHeightClass)},e.prototype.destroy=function(){var a,b;for(a in this._handlers)this._core.$element.off(a,this._handlers[a]);for(b in Object.getOwnPropertyNames(this))"function"!=typeof this[b]&&(this[b]=null)},a.fn.owlCarousel.Constructor.Plugins.AutoHeight=e}(window.Zepto||window.jQuery,window,document),function(a,b,c,d){var e=function(b){this._core=b,this._videos={},this._playing=null,this._handlers={"initialized.owl.carousel":a.proxy(function(a){a.namespace&&this._core.register({type:"state",name:"playing",tags:["interacting"]})},this),"resize.owl.carousel":a.proxy(function(a){a.namespace&&this._core.settings.video&&this.isInFullScreen()&&a.preventDefault()},this),"refreshed.owl.carousel":a.proxy(function(a){a.namespace&&this._core.is("resizing")&&this._core.$stage.find(".cloned .owl-video-frame").remove()},this),"changed.owl.carousel":a.proxy(function(a){a.namespace&&"position"===a.property.name&&this._playing&&this.stop()},this),"prepared.owl.carousel":a.proxy(function(b){if(b.namespace){var c=a(b.content).find(".owl-video");c.length&&(c.css("display","none"),this.fetch(c,a(b.content)))}},this)},this._core.options=a.extend({},e.Defaults,this._core.options),this._core.$element.on(this._handlers),this._core.$element.on("click.owl.video",".owl-video-play-icon",a.proxy(function(a){this.play(a)},this))};e.Defaults={video:!1,videoHeight:!1,videoWidth:!1},e.prototype.fetch=function(a,b){var c=function(){return a.attr("data-vimeo-id")?"vimeo":a.attr("data-vzaar-id")?"vzaar":"youtube"}(),d=a.attr("data-vimeo-id")||a.attr("data-youtube-id")||a.attr("data-vzaar-id"),e=a.attr("data-width")||this._core.settings.videoWidth,f=a.attr("data-height")||this._core.settings.videoHeight,g=a.attr("href");if(!g)throw new Error("Missing video URL.");if(d=g.match(/(http:|https:|)\/\/(player.|www.|app.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com)|vzaar\.com)\/(video\/|videos\/|embed\/|channels\/.+\/|groups\/.+\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/),d[3].indexOf("youtu")>-1)c="youtube";else if(d[3].indexOf("vimeo")>-1)c="vimeo";else{if(!(d[3].indexOf("vzaar")>-1))throw new Error("Video URL not supported.");c="vzaar"}d=d[6],this._videos[g]={type:c,id:d,width:e,height:f},b.attr("data-video",g),this.thumbnail(a,this._videos[g])},e.prototype.thumbnail=function(b,c){var d,e,f,g=c.width&&c.height?'style="width:'+c.width+"px;height:"+c.height+'px;"':"",h=b.find("img"),i="src",j="",k=this._core.settings,l=function(a){e='<div class="owl-video-play-icon"></div>',d=k.lazyLoad?'<div class="owl-video-tn '+j+'" '+i+'="'+a+'"></div>':'<div class="owl-video-tn" style="opacity:1;background-image:url('+a+')"></div>',b.after(d),b.after(e)};if(b.wrap('<div class="owl-video-wrapper"'+g+"></div>"),this._core.settings.lazyLoad&&(i="data-src",j="owl-lazy"),h.length)return l(h.attr(i)),h.remove(),!1;"youtube"===c.type?(f="//img.youtube.com/vi/"+c.id+"/hqdefault.jpg",l(f)):"vimeo"===c.type?a.ajax({type:"GET",url:"//vimeo.com/api/v2/video/"+c.id+".json",jsonp:"callback",dataType:"jsonp",success:function(a){f=a[0].thumbnail_large,l(f)}}):"vzaar"===c.type&&a.ajax({type:"GET",url:"//vzaar.com/api/videos/"+c.id+".json",jsonp:"callback",dataType:"jsonp",success:function(a){f=a.framegrab_url,l(f)}})},e.prototype.stop=function(){this._core.trigger("stop",null,"video"),this._playing.find(".owl-video-frame").remove(),this._playing.removeClass("owl-video-playing"),this._playing=null,this._core.leave("playing"),this._core.trigger("stopped",null,"video")},e.prototype.play=function(b){var c,d=a(b.target),e=d.closest("."+this._core.settings.itemClass),f=this._videos[e.attr("data-video")],g=f.width||"100%",h=f.height||this._core.$stage.height();this._playing||(this._core.enter("playing"),this._core.trigger("play",null,"video"),e=this._core.items(this._core.relative(e.index())),this._core.reset(e.index()),"youtube"===f.type?c='<iframe width="'+g+'" height="'+h+'" src="//www.youtube.com/embed/'+f.id+"?autoplay=1&rel=0&v="+f.id+'" frameborder="0" allowfullscreen></iframe>':"vimeo"===f.type?c='<iframe src="//player.vimeo.com/video/'+f.id+'?autoplay=1" width="'+g+'" height="'+h+'" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>':"vzaar"===f.type&&(c='<iframe frameborder="0"height="'+h+'"width="'+g+'" allowfullscreen mozallowfullscreen webkitAllowFullScreen src="//view.vzaar.com/'+f.id+'/player?autoplay=true"></iframe>'),a('<div class="owl-video-frame">'+c+"</div>").insertAfter(e.find(".owl-video")),this._playing=e.addClass("owl-video-playing"))},e.prototype.isInFullScreen=function(){var b=c.fullscreenElement||c.mozFullScreenElement||c.webkitFullscreenElement;return b&&a(b).parent().hasClass("owl-video-frame")},e.prototype.destroy=function(){var a,b;this._core.$element.off("click.owl.video");for(a in this._handlers)this._core.$element.off(a,this._handlers[a]);for(b in Object.getOwnPropertyNames(this))"function"!=typeof this[b]&&(this[b]=null)},a.fn.owlCarousel.Constructor.Plugins.Video=e}(window.Zepto||window.jQuery,window,document),function(a,b,c,d){var e=function(b){this.core=b,this.core.options=a.extend({},e.Defaults,this.core.options),this.swapping=!0,this.previous=d,this.next=d,this.handlers={"change.owl.carousel":a.proxy(function(a){a.namespace&&"position"==a.property.name&&(this.previous=this.core.current(),this.next=a.property.value)},this),"drag.owl.carousel dragged.owl.carousel translated.owl.carousel":a.proxy(function(a){a.namespace&&(this.swapping="translated"==a.type)},this),"translate.owl.carousel":a.proxy(function(a){a.namespace&&this.swapping&&(this.core.options.animateOut||this.core.options.animateIn)&&this.swap()},this)},this.core.$element.on(this.handlers)};e.Defaults={animateOut:!1,animateIn:!1},e.prototype.swap=function(){if(1===this.core.settings.items&&a.support.animation&&a.support.transition){this.core.speed(0) ;var b,c=a.proxy(this.clear,this),d=this.core.$stage.children().eq(this.previous),e=this.core.$stage.children().eq(this.next),f=this.core.settings.animateIn,g=this.core.settings.animateOut;this.core.current()!==this.previous&&(g&&(b=this.core.coordinates(this.previous)-this.core.coordinates(this.next),d.one(a.support.animation.end,c).css({left:b+"px"}).addClass("animated owl-animated-out").addClass(g)),f&&e.one(a.support.animation.end,c).addClass("animated owl-animated-in").addClass(f))}},e.prototype.clear=function(b){a(b.target).css({left:""}).removeClass("animated owl-animated-out owl-animated-in").removeClass(this.core.settings.animateIn).removeClass(this.core.settings.animateOut),this.core.onTransitionEnd()},e.prototype.destroy=function(){var a,b;for(a in this.handlers)this.core.$element.off(a,this.handlers[a]);for(b in Object.getOwnPropertyNames(this))"function"!=typeof this[b]&&(this[b]=null)},a.fn.owlCarousel.Constructor.Plugins.Animate=e}(window.Zepto||window.jQuery,window,document),function(a,b,c,d){var e=function(b){this._core=b,this._call=null,this._time=0,this._timeout=0,this._paused=!0,this._handlers={"changed.owl.carousel":a.proxy(function(a){a.namespace&&"settings"===a.property.name?this._core.settings.autoplay?this.play():this.stop():a.namespace&&"position"===a.property.name&&this._paused&&(this._time=0)},this),"initialized.owl.carousel":a.proxy(function(a){a.namespace&&this._core.settings.autoplay&&this.play()},this),"play.owl.autoplay":a.proxy(function(a,b,c){a.namespace&&this.play(b,c)},this),"stop.owl.autoplay":a.proxy(function(a){a.namespace&&this.stop()},this),"mouseover.owl.autoplay":a.proxy(function(){this._core.settings.autoplayHoverPause&&this._core.is("rotating")&&this.pause()},this),"mouseleave.owl.autoplay":a.proxy(function(){this._core.settings.autoplayHoverPause&&this._core.is("rotating")&&this.play()},this),"touchstart.owl.core":a.proxy(function(){this._core.settings.autoplayHoverPause&&this._core.is("rotating")&&this.pause()},this),"touchend.owl.core":a.proxy(function(){this._core.settings.autoplayHoverPause&&this.play()},this)},this._core.$element.on(this._handlers),this._core.options=a.extend({},e.Defaults,this._core.options)};e.Defaults={autoplay:!1,autoplayTimeout:5e3,autoplayHoverPause:!1,autoplaySpeed:!1},e.prototype._next=function(d){this._call=b.setTimeout(a.proxy(this._next,this,d),this._timeout*(Math.round(this.read()/this._timeout)+1)-this.read()),this._core.is("busy")||this._core.is("interacting")||c.hidden||this._core.next(d||this._core.settings.autoplaySpeed)},e.prototype.read=function(){return(new Date).getTime()-this._time},e.prototype.play=function(c,d){var e;this._core.is("rotating")||this._core.enter("rotating"),c=c||this._core.settings.autoplayTimeout,e=Math.min(this._time%(this._timeout||c),c),this._paused?(this._time=this.read(),this._paused=!1):b.clearTimeout(this._call),this._time+=this.read()%c-e,this._timeout=c,this._call=b.setTimeout(a.proxy(this._next,this,d),c-e)},e.prototype.stop=function(){this._core.is("rotating")&&(this._time=0,this._paused=!0,b.clearTimeout(this._call),this._core.leave("rotating"))},e.prototype.pause=function(){this._core.is("rotating")&&!this._paused&&(this._time=this.read(),this._paused=!0,b.clearTimeout(this._call))},e.prototype.destroy=function(){var a,b;this.stop();for(a in this._handlers)this._core.$element.off(a,this._handlers[a]);for(b in Object.getOwnPropertyNames(this))"function"!=typeof this[b]&&(this[b]=null)},a.fn.owlCarousel.Constructor.Plugins.autoplay=e}(window.Zepto||window.jQuery,window,document),function(a,b,c,d){"use strict";var e=function(b){this._core=b,this._initialized=!1,this._pages=[],this._controls={},this._templates=[],this.$element=this._core.$element,this._overrides={next:this._core.next,prev:this._core.prev,to:this._core.to},this._handlers={"prepared.owl.carousel":a.proxy(function(b){b.namespace&&this._core.settings.dotsData&&this._templates.push('<div class="'+this._core.settings.dotClass+'">'+a(b.content).find("[data-dot]").addBack("[data-dot]").attr("data-dot")+"</div>")},this),"added.owl.carousel":a.proxy(function(a){a.namespace&&this._core.settings.dotsData&&this._templates.splice(a.position,0,this._templates.pop())},this),"remove.owl.carousel":a.proxy(function(a){a.namespace&&this._core.settings.dotsData&&this._templates.splice(a.position,1)},this),"changed.owl.carousel":a.proxy(function(a){a.namespace&&"position"==a.property.name&&this.draw()},this),"initialized.owl.carousel":a.proxy(function(a){a.namespace&&!this._initialized&&(this._core.trigger("initialize",null,"navigation"),this.initialize(),this.update(),this.draw(),this._initialized=!0,this._core.trigger("initialized",null,"navigation"))},this),"refreshed.owl.carousel":a.proxy(function(a){a.namespace&&this._initialized&&(this._core.trigger("refresh",null,"navigation"),this.update(),this.draw(),this._core.trigger("refreshed",null,"navigation"))},this)},this._core.options=a.extend({},e.Defaults,this._core.options),this.$element.on(this._handlers)};e.Defaults={nav:!1,navText:['<span aria-label="Previous">&#x2039;</span>','<span aria-label="Next">&#x203a;</span>'],navSpeed:!1,navElement:'button type="button" role="presentation"',navContainer:!1,navContainerClass:"owl-nav",navClass:["owl-prev","owl-next"],slideBy:1,dotClass:"owl-dot",dotsClass:"owl-dots",dots:!0,dotsEach:!1,dotsData:!1,dotsSpeed:!1,dotsContainer:!1},e.prototype.initialize=function(){var b,c=this._core.settings;this._controls.$relative=(c.navContainer?a(c.navContainer):a("<div>").addClass(c.navContainerClass).appendTo(this.$element)).addClass("disabled"),this._controls.$previous=a("<"+c.navElement+">").addClass(c.navClass[0]).html(c.navText[0]).prependTo(this._controls.$relative).on("click",a.proxy(function(a){this.prev(c.navSpeed)},this)),this._controls.$next=a("<"+c.navElement+">").addClass(c.navClass[1]).html(c.navText[1]).appendTo(this._controls.$relative).on("click",a.proxy(function(a){this.next(c.navSpeed)},this)),c.dotsData||(this._templates=[a('<button role="button">').addClass(c.dotClass).append(a("<span>")).prop("outerHTML")]),this._controls.$absolute=(c.dotsContainer?a(c.dotsContainer):a("<div>").addClass(c.dotsClass).appendTo(this.$element)).addClass("disabled"),this._controls.$absolute.on("click","button",a.proxy(function(b){var d=a(b.target).parent().is(this._controls.$absolute)?a(b.target).index():a(b.target).parent().index();b.preventDefault(),this.to(d,c.dotsSpeed)},this));for(b in this._overrides)this._core[b]=a.proxy(this[b],this)},e.prototype.destroy=function(){var a,b,c,d,e;e=this._core.settings;for(a in this._handlers)this.$element.off(a,this._handlers[a]);for(b in this._controls)"$relative"===b&&e.navContainer?this._controls[b].html(""):this._controls[b].remove();for(d in this.overides)this._core[d]=this._overrides[d];for(c in Object.getOwnPropertyNames(this))"function"!=typeof this[c]&&(this[c]=null)},e.prototype.update=function(){var a,b,c,d=this._core.clones().length/2,e=d+this._core.items().length,f=this._core.maximum(!0),g=this._core.settings,h=g.center||g.autoWidth||g.dotsData?1:g.dotsEach||g.items;if("page"!==g.slideBy&&(g.slideBy=Math.min(g.slideBy,g.items)),g.dots||"page"==g.slideBy)for(this._pages=[],a=d,b=0,c=0;a<e;a++){if(b>=h||0===b){if(this._pages.push({start:Math.min(f,a-d),end:a-d+h-1}),Math.min(f,a-d)===f)break;b=0,++c}b+=this._core.mergers(this._core.relative(a))}},e.prototype.draw=function(){var b,c=this._core.settings,d=this._core.items().length<=c.items,e=this._core.relative(this._core.current()),f=c.loop||c.rewind;this._controls.$relative.toggleClass("disabled",!c.nav||d),c.nav&&(this._controls.$previous.toggleClass("disabled",!f&&e<=this._core.minimum(!0)),this._controls.$next.toggleClass("disabled",!f&&e>=this._core.maximum(!0))),this._controls.$absolute.toggleClass("disabled",!c.dots||d),c.dots&&(b=this._pages.length-this._controls.$absolute.children().length,c.dotsData&&0!==b?this._controls.$absolute.html(this._templates.join("")):b>0?this._controls.$absolute.append(new Array(b+1).join(this._templates[0])):b<0&&this._controls.$absolute.children().slice(b).remove(),this._controls.$absolute.find(".active").removeClass("active"),this._controls.$absolute.children().eq(a.inArray(this.current(),this._pages)).addClass("active"))},e.prototype.onTrigger=function(b){var c=this._core.settings;b.page={index:a.inArray(this.current(),this._pages),count:this._pages.length,size:c&&(c.center||c.autoWidth||c.dotsData?1:c.dotsEach||c.items)}},e.prototype.current=function(){var b=this._core.relative(this._core.current());return a.grep(this._pages,a.proxy(function(a,c){return a.start<=b&&a.end>=b},this)).pop()},e.prototype.getPosition=function(b){var c,d,e=this._core.settings;return"page"==e.slideBy?(c=a.inArray(this.current(),this._pages),d=this._pages.length,b?++c:--c,c=this._pages[(c%d+d)%d].start):(c=this._core.relative(this._core.current()),d=this._core.items().length,b?c+=e.slideBy:c-=e.slideBy),c},e.prototype.next=function(b){a.proxy(this._overrides.to,this._core)(this.getPosition(!0),b)},e.prototype.prev=function(b){a.proxy(this._overrides.to,this._core)(this.getPosition(!1),b)},e.prototype.to=function(b,c,d){var e;!d&&this._pages.length?(e=this._pages.length,a.proxy(this._overrides.to,this._core)(this._pages[(b%e+e)%e].start,c)):a.proxy(this._overrides.to,this._core)(b,c)},a.fn.owlCarousel.Constructor.Plugins.Navigation=e}(window.Zepto||window.jQuery,window,document),function(a,b,c,d){"use strict";var e=function(c){this._core=c,this._hashes={},this.$element=this._core.$element,this._handlers={"initialized.owl.carousel":a.proxy(function(c){c.namespace&&"URLHash"===this._core.settings.startPosition&&a(b).trigger("hashchange.owl.navigation")},this),"prepared.owl.carousel":a.proxy(function(b){if(b.namespace){var c=a(b.content).find("[data-hash]").addBack("[data-hash]").attr("data-hash");if(!c)return;this._hashes[c]=b.content}},this),"changed.owl.carousel":a.proxy(function(c){if(c.namespace&&"position"===c.property.name){var d=this._core.items(this._core.relative(this._core.current())),e=a.map(this._hashes,function(a,b){return a===d?b:null}).join();if(!e||b.location.hash.slice(1)===e)return;b.location.hash=e}},this)},this._core.options=a.extend({},e.Defaults,this._core.options),this.$element.on(this._handlers),a(b).on("hashchange.owl.navigation",a.proxy(function(a){var c=b.location.hash.substring(1),e=this._core.$stage.children(),f=this._hashes[c]&&e.index(this._hashes[c]);f!==d&&f!==this._core.current()&&this._core.to(this._core.relative(f),!1,!0)},this))};e.Defaults={URLhashListener:!1},e.prototype.destroy=function(){var c,d;a(b).off("hashchange.owl.navigation");for(c in this._handlers)this._core.$element.off(c,this._handlers[c]);for(d in Object.getOwnPropertyNames(this))"function"!=typeof this[d]&&(this[d]=null)},a.fn.owlCarousel.Constructor.Plugins.Hash=e}(window.Zepto||window.jQuery,window,document),function(a,b,c,d){function
(b,c){var e=!1,f=b.charAt(0).toUpperCase()+b.slice(1);return a.each((b+" "+h.join(f+" ")+f).split(" "),function(a,b){if(g[b]!==d)return e=!c||b,!1}),e}function f(a){return e(a,!0)}var g=a("<support>").get(0).style,h="Webkit Moz O ms".split(" "),i={transition:{end:{WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd",transition:"transitionend"}},animation:{end:{WebkitAnimation:"webkitAnimationEnd",MozAnimation:"animationend",OAnimation:"oAnimationEnd",animation:"animationend"}}},j={csstransforms:function(){return!!e("transform")},csstransforms3d:function(){return!!e("perspective")},csstransitions:function(){return!!e("transition")},cssanimations:function(){return!!e("animation")}};j.csstransitions()&&(a.support.transition=new String(f("transition")),a.support.transition.end=i.transition.end[a.support.transition]),j.cssanimations()&&(a.support.animation=new String(f("animation")),a.support.animation.end=i.animation.end[a.support.animation]),j.csstransforms()&&(a.support.transform=new String(f("transform")),a.support.transform3d=j.csstransforms3d())}(window.Zepto||window.jQuery,window,document);
e
app.py
import os
@app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def serve(path): if(path == ""): return send_from_directory('client/build', 'index.html') else: if(os.path.exists("client/build/" + path)): return send_from_directory('client/build', path) else: return send_from_directory('client/build', 'index.html') if __name__ == '__main__': app.run(use_reloader=True, port=3000, threaded=True)
from flask import Flask, send_from_directory app = Flask(__name__, static_folder='client/build')
simplify_try.rs
fn try_identity(x: Result<u32, i32>) -> Result<u32, i32> { let y = x?; Ok(y) } fn main()
// END RUST SOURCE // START rustc.try_identity.SimplifyArmIdentity.before.mir // fn try_identity(_1: std::result::Result<u32, i32>) -> std::result::Result<u32, i32> { // let mut _0: std::result::Result<u32, i32>; // let _2: u32; // let mut _3: std::result::Result<u32, i32>; // let mut _4: std::result::Result<u32, i32>; // let mut _5: isize; // let _6: i32; // let mut _7: !; // let mut _8: i32; // let mut _9: i32; // let _10: u32; // let mut _11: u32; // scope 1 { // } // scope 2 { // scope 3 { // scope 7 { // } // scope 8 { // let mut _12: i32; // } // } // } // scope 4 { // scope 5 { // } // } // scope 6 { // } // bb0: { // _5 = discriminant(_1); // switchInt(move _5) -> [0isize: bb4, 1isize: bb2, otherwise: bb1]; // } // bb1: { // unreachable; // } // bb2: { // _6 = ((_1 as Err).0: i32); // ((_0 as Err).0: i32) = move _6; // discriminant(_0) = 1; // goto -> bb3; // } // bb3: { // return; // } // bb4: { // _10 = ((_1 as Ok).0: u32); // ((_0 as Ok).0: u32) = move _10; // discriminant(_0) = 0; // goto -> bb3; // } // } // END rustc.try_identity.SimplifyArmIdentity.before.mir // START rustc.try_identity.SimplifyArmIdentity.after.mir // fn try_identity(_1: std::result::Result<u32, i32>) -> std::result::Result<u32, i32> { // let mut _0: std::result::Result<u32, i32>; // let _2: u32; // let mut _3: std::result::Result<u32, i32>; // let mut _4: std::result::Result<u32, i32>; // let mut _5: isize; // let _6: i32; // let mut _7: !; // let mut _8: i32; // let mut _9: i32; // let _10: u32; // let mut _11: u32; // scope 1 { // } // scope 2 { // scope 3 { // scope 7 { // } // scope 8 { // let mut _12: i32; // } // } // } // scope 4 { // scope 5 { // } // } // scope 6 { // } // bb0: { // _5 = discriminant(_1); // switchInt(move _5) -> [0isize: bb4, 1isize: bb2, otherwise: bb1]; // } // bb1: { // unreachable; // } // bb2: { // _0 = move _1; // nop; // nop; // goto -> bb3; // } // bb3: { // return; // } // bb4: { // _0 = move _1; // nop; // nop; // goto -> bb3; // } // } // END rustc.try_identity.SimplifyArmIdentity.after.mir // START rustc.try_identity.SimplifyBranchSame.after.mir // fn try_identity(_1: std::result::Result<u32, i32>) -> std::result::Result<u32, i32> { // let mut _0: std::result::Result<u32, i32>; // let _2: u32; // let mut _3: std::result::Result<u32, i32>; // let mut _4: std::result::Result<u32, i32>; // let mut _5: isize; // let _6: i32; // let mut _7: !; // let mut _8: i32; // let mut _9: i32; // let _10: u32; // let mut _11: u32; // scope 1 { // } // scope 2 { // scope 3 { // scope 7 { // } // scope 8 { // let mut _12: i32; // } // } // } // scope 4 { // scope 5 { // } // } // scope 6 { // } // bb0: { // _5 = discriminant(_1); // goto -> bb2; // } // bb1: { // return; // } // bb2: { // _0 = move _1; // nop; // nop; // goto -> bb1; // } // } // END rustc.try_identity.SimplifyBranchSame.after.mir // START rustc.try_identity.SimplifyLocals.after.mir // fn try_identity(_1: std::result::Result<u32, i32>) -> std::result::Result<u32, i32> { // let mut _0: std::result::Result<u32, i32>; // let mut _2: isize; // scope 1 { // } // scope 2 { // scope 3 { // scope 7 { // } // scope 8 { // } // } // } // scope 4 { // scope 5 { // } // } // scope 6 { // } // bb0: { // _2 = discriminant(_1); // _0 = move _1; // return; // } // } // END rustc.try_identity.SimplifyLocals.after.mir
{ let _ = try_identity(Ok(0)); }
MobileMenuContainer.tsx
import * as React from "react"; import { MobileMenu } from "src/components/MobileMenu"; import { MobileMenuItem } from "src/components/MobileMenu/Item"; import { IconType } from "src/components/Icon/Type"; type ItemType = { title: string; icon: IconType; to: string; }; export type MobileMenuContainerProps = { // }; export const MobileMenuContainer: React.SFC<MobileMenuContainerProps> = ({}) => { const items: ItemType[] = [ { title: "Accounts", icon: "Wallet", to: "/accounts" }, { title: "Transfer", icon: "Transfer", to: "/transfer" }, { title: "Cards", icon: "Cards", to: "/cards" }, { title: "More", icon: "More", to: "/more" }, ];
return ( <MobileMenu> {items.map(q => { return <MobileMenuItem key={q.title} title={q.title} icon={q.icon} to={q.to} />; })} </MobileMenu> ); };
error.rs
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Error type for the `CreateContainer` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct CreateContainerError { /// Kind of error that occurred. pub kind: CreateContainerErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `CreateContainer` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum CreateContainerErrorKind { /// <p>The container that you specified in the request already exists or is being /// updated.</p> ContainerInUseException(crate::error::ContainerInUseException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// <p>A service limit has been exceeded.</p> LimitExceededException(crate::error::LimitExceededException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for CreateContainerError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { CreateContainerErrorKind::ContainerInUseException(_inner) => _inner.fmt(f), CreateContainerErrorKind::InternalServerError(_inner) => _inner.fmt(f), CreateContainerErrorKind::LimitExceededException(_inner) => _inner.fmt(f), CreateContainerErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for CreateContainerError { fn code(&self) -> Option<&str> { CreateContainerError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl CreateContainerError { /// Creates a new `CreateContainerError`. pub fn new(kind: CreateContainerErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `CreateContainerError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: CreateContainerErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `CreateContainerError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: CreateContainerErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `CreateContainerErrorKind::ContainerInUseException`. pub fn is_container_in_use_exception(&self) -> bool { matches!( &self.kind, CreateContainerErrorKind::ContainerInUseException(_) ) } /// Returns `true` if the error kind is `CreateContainerErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!(&self.kind, CreateContainerErrorKind::InternalServerError(_)) } /// Returns `true` if the error kind is `CreateContainerErrorKind::LimitExceededException`. pub fn is_limit_exceeded_exception(&self) -> bool { matches!( &self.kind, CreateContainerErrorKind::LimitExceededException(_) ) } } impl std::error::Error for CreateContainerError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { CreateContainerErrorKind::ContainerInUseException(_inner) => Some(_inner), CreateContainerErrorKind::InternalServerError(_inner) => Some(_inner), CreateContainerErrorKind::LimitExceededException(_inner) => Some(_inner), CreateContainerErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DeleteContainer` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DeleteContainerError { /// Kind of error that occurred. pub kind: DeleteContainerErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DeleteContainer` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DeleteContainerErrorKind { /// <p>The container that you specified in the request already exists or is being /// updated.</p> ContainerInUseException(crate::error::ContainerInUseException), /// <p>The container that you specified in the request does not exist.</p> ContainerNotFoundException(crate::error::ContainerNotFoundException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DeleteContainerError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DeleteContainerErrorKind::ContainerInUseException(_inner) => _inner.fmt(f), DeleteContainerErrorKind::ContainerNotFoundException(_inner) => _inner.fmt(f), DeleteContainerErrorKind::InternalServerError(_inner) => _inner.fmt(f), DeleteContainerErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DeleteContainerError { fn code(&self) -> Option<&str> { DeleteContainerError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DeleteContainerError { /// Creates a new `DeleteContainerError`. pub fn new(kind: DeleteContainerErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DeleteContainerError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DeleteContainerErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DeleteContainerError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DeleteContainerErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DeleteContainerErrorKind::ContainerInUseException`. pub fn is_container_in_use_exception(&self) -> bool { matches!( &self.kind, DeleteContainerErrorKind::ContainerInUseException(_) ) } /// Returns `true` if the error kind is `DeleteContainerErrorKind::ContainerNotFoundException`. pub fn is_container_not_found_exception(&self) -> bool { matches!( &self.kind, DeleteContainerErrorKind::ContainerNotFoundException(_) ) } /// Returns `true` if the error kind is `DeleteContainerErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!(&self.kind, DeleteContainerErrorKind::InternalServerError(_)) } } impl std::error::Error for DeleteContainerError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DeleteContainerErrorKind::ContainerInUseException(_inner) => Some(_inner), DeleteContainerErrorKind::ContainerNotFoundException(_inner) => Some(_inner), DeleteContainerErrorKind::InternalServerError(_inner) => Some(_inner), DeleteContainerErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DeleteContainerPolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DeleteContainerPolicyError { /// Kind of error that occurred. pub kind: DeleteContainerPolicyErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DeleteContainerPolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DeleteContainerPolicyErrorKind { /// <p>The container that you specified in the request already exists or is being /// updated.</p> ContainerInUseException(crate::error::ContainerInUseException), /// <p>The container that you specified in the request does not exist.</p> ContainerNotFoundException(crate::error::ContainerNotFoundException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// <p>The policy that you specified in the request does not exist.</p> PolicyNotFoundException(crate::error::PolicyNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DeleteContainerPolicyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DeleteContainerPolicyErrorKind::ContainerInUseException(_inner) => _inner.fmt(f), DeleteContainerPolicyErrorKind::ContainerNotFoundException(_inner) => _inner.fmt(f), DeleteContainerPolicyErrorKind::InternalServerError(_inner) => _inner.fmt(f), DeleteContainerPolicyErrorKind::PolicyNotFoundException(_inner) => _inner.fmt(f), DeleteContainerPolicyErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DeleteContainerPolicyError { fn code(&self) -> Option<&str> { DeleteContainerPolicyError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DeleteContainerPolicyError { /// Creates a new `DeleteContainerPolicyError`. pub fn new(kind: DeleteContainerPolicyErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DeleteContainerPolicyError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DeleteContainerPolicyErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DeleteContainerPolicyError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DeleteContainerPolicyErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DeleteContainerPolicyErrorKind::ContainerInUseException`. pub fn is_container_in_use_exception(&self) -> bool { matches!( &self.kind, DeleteContainerPolicyErrorKind::ContainerInUseException(_) ) } /// Returns `true` if the error kind is `DeleteContainerPolicyErrorKind::ContainerNotFoundException`. pub fn is_container_not_found_exception(&self) -> bool { matches!( &self.kind, DeleteContainerPolicyErrorKind::ContainerNotFoundException(_) ) } /// Returns `true` if the error kind is `DeleteContainerPolicyErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!( &self.kind, DeleteContainerPolicyErrorKind::InternalServerError(_) ) } /// Returns `true` if the error kind is `DeleteContainerPolicyErrorKind::PolicyNotFoundException`. pub fn is_policy_not_found_exception(&self) -> bool { matches!( &self.kind, DeleteContainerPolicyErrorKind::PolicyNotFoundException(_) ) } } impl std::error::Error for DeleteContainerPolicyError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DeleteContainerPolicyErrorKind::ContainerInUseException(_inner) => Some(_inner), DeleteContainerPolicyErrorKind::ContainerNotFoundException(_inner) => Some(_inner), DeleteContainerPolicyErrorKind::InternalServerError(_inner) => Some(_inner), DeleteContainerPolicyErrorKind::PolicyNotFoundException(_inner) => Some(_inner), DeleteContainerPolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DeleteCorsPolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DeleteCorsPolicyError { /// Kind of error that occurred. pub kind: DeleteCorsPolicyErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DeleteCorsPolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DeleteCorsPolicyErrorKind { /// <p>The container that you specified in the request already exists or is being /// updated.</p> ContainerInUseException(crate::error::ContainerInUseException), /// <p>The container that you specified in the request does not exist.</p> ContainerNotFoundException(crate::error::ContainerNotFoundException), /// <p>The CORS policy that you specified in the request does not exist.</p> CorsPolicyNotFoundException(crate::error::CorsPolicyNotFoundException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DeleteCorsPolicyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DeleteCorsPolicyErrorKind::ContainerInUseException(_inner) => _inner.fmt(f), DeleteCorsPolicyErrorKind::ContainerNotFoundException(_inner) => _inner.fmt(f), DeleteCorsPolicyErrorKind::CorsPolicyNotFoundException(_inner) => _inner.fmt(f), DeleteCorsPolicyErrorKind::InternalServerError(_inner) => _inner.fmt(f), DeleteCorsPolicyErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DeleteCorsPolicyError { fn code(&self) -> Option<&str> { DeleteCorsPolicyError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DeleteCorsPolicyError { /// Creates a new `DeleteCorsPolicyError`. pub fn new(kind: DeleteCorsPolicyErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DeleteCorsPolicyError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DeleteCorsPolicyErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DeleteCorsPolicyError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DeleteCorsPolicyErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DeleteCorsPolicyErrorKind::ContainerInUseException`. pub fn is_container_in_use_exception(&self) -> bool { matches!( &self.kind, DeleteCorsPolicyErrorKind::ContainerInUseException(_) ) } /// Returns `true` if the error kind is `DeleteCorsPolicyErrorKind::ContainerNotFoundException`. pub fn is_container_not_found_exception(&self) -> bool { matches!( &self.kind, DeleteCorsPolicyErrorKind::ContainerNotFoundException(_) ) } /// Returns `true` if the error kind is `DeleteCorsPolicyErrorKind::CorsPolicyNotFoundException`. pub fn is_cors_policy_not_found_exception(&self) -> bool { matches!( &self.kind, DeleteCorsPolicyErrorKind::CorsPolicyNotFoundException(_) ) } /// Returns `true` if the error kind is `DeleteCorsPolicyErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!( &self.kind, DeleteCorsPolicyErrorKind::InternalServerError(_) ) } } impl std::error::Error for DeleteCorsPolicyError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DeleteCorsPolicyErrorKind::ContainerInUseException(_inner) => Some(_inner), DeleteCorsPolicyErrorKind::ContainerNotFoundException(_inner) => Some(_inner), DeleteCorsPolicyErrorKind::CorsPolicyNotFoundException(_inner) => Some(_inner), DeleteCorsPolicyErrorKind::InternalServerError(_inner) => Some(_inner), DeleteCorsPolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DeleteLifecyclePolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DeleteLifecyclePolicyError { /// Kind of error that occurred. pub kind: DeleteLifecyclePolicyErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DeleteLifecyclePolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DeleteLifecyclePolicyErrorKind { /// <p>The container that you specified in the request already exists or is being /// updated.</p> ContainerInUseException(crate::error::ContainerInUseException), /// <p>The container that you specified in the request does not exist.</p> ContainerNotFoundException(crate::error::ContainerNotFoundException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// <p>The policy that you specified in the request does not exist.</p> PolicyNotFoundException(crate::error::PolicyNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DeleteLifecyclePolicyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DeleteLifecyclePolicyErrorKind::ContainerInUseException(_inner) => _inner.fmt(f), DeleteLifecyclePolicyErrorKind::ContainerNotFoundException(_inner) => _inner.fmt(f), DeleteLifecyclePolicyErrorKind::InternalServerError(_inner) => _inner.fmt(f), DeleteLifecyclePolicyErrorKind::PolicyNotFoundException(_inner) => _inner.fmt(f), DeleteLifecyclePolicyErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DeleteLifecyclePolicyError { fn code(&self) -> Option<&str> { DeleteLifecyclePolicyError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DeleteLifecyclePolicyError { /// Creates a new `DeleteLifecyclePolicyError`. pub fn new(kind: DeleteLifecyclePolicyErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DeleteLifecyclePolicyError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DeleteLifecyclePolicyErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DeleteLifecyclePolicyError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DeleteLifecyclePolicyErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DeleteLifecyclePolicyErrorKind::ContainerInUseException`. pub fn is_container_in_use_exception(&self) -> bool { matches!( &self.kind, DeleteLifecyclePolicyErrorKind::ContainerInUseException(_) ) } /// Returns `true` if the error kind is `DeleteLifecyclePolicyErrorKind::ContainerNotFoundException`. pub fn is_container_not_found_exception(&self) -> bool { matches!( &self.kind, DeleteLifecyclePolicyErrorKind::ContainerNotFoundException(_) ) } /// Returns `true` if the error kind is `DeleteLifecyclePolicyErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!( &self.kind, DeleteLifecyclePolicyErrorKind::InternalServerError(_) ) } /// Returns `true` if the error kind is `DeleteLifecyclePolicyErrorKind::PolicyNotFoundException`. pub fn is_policy_not_found_exception(&self) -> bool
} impl std::error::Error for DeleteLifecyclePolicyError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DeleteLifecyclePolicyErrorKind::ContainerInUseException(_inner) => Some(_inner), DeleteLifecyclePolicyErrorKind::ContainerNotFoundException(_inner) => Some(_inner), DeleteLifecyclePolicyErrorKind::InternalServerError(_inner) => Some(_inner), DeleteLifecyclePolicyErrorKind::PolicyNotFoundException(_inner) => Some(_inner), DeleteLifecyclePolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DeleteMetricPolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DeleteMetricPolicyError { /// Kind of error that occurred. pub kind: DeleteMetricPolicyErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DeleteMetricPolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DeleteMetricPolicyErrorKind { /// <p>The container that you specified in the request already exists or is being /// updated.</p> ContainerInUseException(crate::error::ContainerInUseException), /// <p>The container that you specified in the request does not exist.</p> ContainerNotFoundException(crate::error::ContainerNotFoundException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// <p>The policy that you specified in the request does not exist.</p> PolicyNotFoundException(crate::error::PolicyNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DeleteMetricPolicyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DeleteMetricPolicyErrorKind::ContainerInUseException(_inner) => _inner.fmt(f), DeleteMetricPolicyErrorKind::ContainerNotFoundException(_inner) => _inner.fmt(f), DeleteMetricPolicyErrorKind::InternalServerError(_inner) => _inner.fmt(f), DeleteMetricPolicyErrorKind::PolicyNotFoundException(_inner) => _inner.fmt(f), DeleteMetricPolicyErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DeleteMetricPolicyError { fn code(&self) -> Option<&str> { DeleteMetricPolicyError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DeleteMetricPolicyError { /// Creates a new `DeleteMetricPolicyError`. pub fn new(kind: DeleteMetricPolicyErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DeleteMetricPolicyError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DeleteMetricPolicyErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DeleteMetricPolicyError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DeleteMetricPolicyErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DeleteMetricPolicyErrorKind::ContainerInUseException`. pub fn is_container_in_use_exception(&self) -> bool { matches!( &self.kind, DeleteMetricPolicyErrorKind::ContainerInUseException(_) ) } /// Returns `true` if the error kind is `DeleteMetricPolicyErrorKind::ContainerNotFoundException`. pub fn is_container_not_found_exception(&self) -> bool { matches!( &self.kind, DeleteMetricPolicyErrorKind::ContainerNotFoundException(_) ) } /// Returns `true` if the error kind is `DeleteMetricPolicyErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!( &self.kind, DeleteMetricPolicyErrorKind::InternalServerError(_) ) } /// Returns `true` if the error kind is `DeleteMetricPolicyErrorKind::PolicyNotFoundException`. pub fn is_policy_not_found_exception(&self) -> bool { matches!( &self.kind, DeleteMetricPolicyErrorKind::PolicyNotFoundException(_) ) } } impl std::error::Error for DeleteMetricPolicyError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DeleteMetricPolicyErrorKind::ContainerInUseException(_inner) => Some(_inner), DeleteMetricPolicyErrorKind::ContainerNotFoundException(_inner) => Some(_inner), DeleteMetricPolicyErrorKind::InternalServerError(_inner) => Some(_inner), DeleteMetricPolicyErrorKind::PolicyNotFoundException(_inner) => Some(_inner), DeleteMetricPolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DescribeContainer` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeContainerError { /// Kind of error that occurred. pub kind: DescribeContainerErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeContainer` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeContainerErrorKind { /// <p>The container that you specified in the request does not exist.</p> ContainerNotFoundException(crate::error::ContainerNotFoundException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeContainerError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeContainerErrorKind::ContainerNotFoundException(_inner) => _inner.fmt(f), DescribeContainerErrorKind::InternalServerError(_inner) => _inner.fmt(f), DescribeContainerErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeContainerError { fn code(&self) -> Option<&str> { DescribeContainerError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeContainerError { /// Creates a new `DescribeContainerError`. pub fn new(kind: DescribeContainerErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DescribeContainerError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeContainerErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeContainerError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeContainerErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeContainerErrorKind::ContainerNotFoundException`. pub fn is_container_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeContainerErrorKind::ContainerNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeContainerErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!( &self.kind, DescribeContainerErrorKind::InternalServerError(_) ) } } impl std::error::Error for DescribeContainerError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeContainerErrorKind::ContainerNotFoundException(_inner) => Some(_inner), DescribeContainerErrorKind::InternalServerError(_inner) => Some(_inner), DescribeContainerErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `GetContainerPolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct GetContainerPolicyError { /// Kind of error that occurred. pub kind: GetContainerPolicyErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `GetContainerPolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum GetContainerPolicyErrorKind { /// <p>The container that you specified in the request already exists or is being /// updated.</p> ContainerInUseException(crate::error::ContainerInUseException), /// <p>The container that you specified in the request does not exist.</p> ContainerNotFoundException(crate::error::ContainerNotFoundException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// <p>The policy that you specified in the request does not exist.</p> PolicyNotFoundException(crate::error::PolicyNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for GetContainerPolicyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { GetContainerPolicyErrorKind::ContainerInUseException(_inner) => _inner.fmt(f), GetContainerPolicyErrorKind::ContainerNotFoundException(_inner) => _inner.fmt(f), GetContainerPolicyErrorKind::InternalServerError(_inner) => _inner.fmt(f), GetContainerPolicyErrorKind::PolicyNotFoundException(_inner) => _inner.fmt(f), GetContainerPolicyErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for GetContainerPolicyError { fn code(&self) -> Option<&str> { GetContainerPolicyError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl GetContainerPolicyError { /// Creates a new `GetContainerPolicyError`. pub fn new(kind: GetContainerPolicyErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `GetContainerPolicyError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: GetContainerPolicyErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `GetContainerPolicyError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: GetContainerPolicyErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `GetContainerPolicyErrorKind::ContainerInUseException`. pub fn is_container_in_use_exception(&self) -> bool { matches!( &self.kind, GetContainerPolicyErrorKind::ContainerInUseException(_) ) } /// Returns `true` if the error kind is `GetContainerPolicyErrorKind::ContainerNotFoundException`. pub fn is_container_not_found_exception(&self) -> bool { matches!( &self.kind, GetContainerPolicyErrorKind::ContainerNotFoundException(_) ) } /// Returns `true` if the error kind is `GetContainerPolicyErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!( &self.kind, GetContainerPolicyErrorKind::InternalServerError(_) ) } /// Returns `true` if the error kind is `GetContainerPolicyErrorKind::PolicyNotFoundException`. pub fn is_policy_not_found_exception(&self) -> bool { matches!( &self.kind, GetContainerPolicyErrorKind::PolicyNotFoundException(_) ) } } impl std::error::Error for GetContainerPolicyError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { GetContainerPolicyErrorKind::ContainerInUseException(_inner) => Some(_inner), GetContainerPolicyErrorKind::ContainerNotFoundException(_inner) => Some(_inner), GetContainerPolicyErrorKind::InternalServerError(_inner) => Some(_inner), GetContainerPolicyErrorKind::PolicyNotFoundException(_inner) => Some(_inner), GetContainerPolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `GetCorsPolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct GetCorsPolicyError { /// Kind of error that occurred. pub kind: GetCorsPolicyErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `GetCorsPolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum GetCorsPolicyErrorKind { /// <p>The container that you specified in the request already exists or is being /// updated.</p> ContainerInUseException(crate::error::ContainerInUseException), /// <p>The container that you specified in the request does not exist.</p> ContainerNotFoundException(crate::error::ContainerNotFoundException), /// <p>The CORS policy that you specified in the request does not exist.</p> CorsPolicyNotFoundException(crate::error::CorsPolicyNotFoundException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for GetCorsPolicyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { GetCorsPolicyErrorKind::ContainerInUseException(_inner) => _inner.fmt(f), GetCorsPolicyErrorKind::ContainerNotFoundException(_inner) => _inner.fmt(f), GetCorsPolicyErrorKind::CorsPolicyNotFoundException(_inner) => _inner.fmt(f), GetCorsPolicyErrorKind::InternalServerError(_inner) => _inner.fmt(f), GetCorsPolicyErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for GetCorsPolicyError { fn code(&self) -> Option<&str> { GetCorsPolicyError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl GetCorsPolicyError { /// Creates a new `GetCorsPolicyError`. pub fn new(kind: GetCorsPolicyErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `GetCorsPolicyError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: GetCorsPolicyErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `GetCorsPolicyError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: GetCorsPolicyErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `GetCorsPolicyErrorKind::ContainerInUseException`. pub fn is_container_in_use_exception(&self) -> bool { matches!( &self.kind, GetCorsPolicyErrorKind::ContainerInUseException(_) ) } /// Returns `true` if the error kind is `GetCorsPolicyErrorKind::ContainerNotFoundException`. pub fn is_container_not_found_exception(&self) -> bool { matches!( &self.kind, GetCorsPolicyErrorKind::ContainerNotFoundException(_) ) } /// Returns `true` if the error kind is `GetCorsPolicyErrorKind::CorsPolicyNotFoundException`. pub fn is_cors_policy_not_found_exception(&self) -> bool { matches!( &self.kind, GetCorsPolicyErrorKind::CorsPolicyNotFoundException(_) ) } /// Returns `true` if the error kind is `GetCorsPolicyErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!(&self.kind, GetCorsPolicyErrorKind::InternalServerError(_)) } } impl std::error::Error for GetCorsPolicyError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { GetCorsPolicyErrorKind::ContainerInUseException(_inner) => Some(_inner), GetCorsPolicyErrorKind::ContainerNotFoundException(_inner) => Some(_inner), GetCorsPolicyErrorKind::CorsPolicyNotFoundException(_inner) => Some(_inner), GetCorsPolicyErrorKind::InternalServerError(_inner) => Some(_inner), GetCorsPolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `GetLifecyclePolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct GetLifecyclePolicyError { /// Kind of error that occurred. pub kind: GetLifecyclePolicyErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `GetLifecyclePolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum GetLifecyclePolicyErrorKind { /// <p>The container that you specified in the request already exists or is being /// updated.</p> ContainerInUseException(crate::error::ContainerInUseException), /// <p>The container that you specified in the request does not exist.</p> ContainerNotFoundException(crate::error::ContainerNotFoundException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// <p>The policy that you specified in the request does not exist.</p> PolicyNotFoundException(crate::error::PolicyNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for GetLifecyclePolicyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { GetLifecyclePolicyErrorKind::ContainerInUseException(_inner) => _inner.fmt(f), GetLifecyclePolicyErrorKind::ContainerNotFoundException(_inner) => _inner.fmt(f), GetLifecyclePolicyErrorKind::InternalServerError(_inner) => _inner.fmt(f), GetLifecyclePolicyErrorKind::PolicyNotFoundException(_inner) => _inner.fmt(f), GetLifecyclePolicyErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for GetLifecyclePolicyError { fn code(&self) -> Option<&str> { GetLifecyclePolicyError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl GetLifecyclePolicyError { /// Creates a new `GetLifecyclePolicyError`. pub fn new(kind: GetLifecyclePolicyErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `GetLifecyclePolicyError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: GetLifecyclePolicyErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `GetLifecyclePolicyError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: GetLifecyclePolicyErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `GetLifecyclePolicyErrorKind::ContainerInUseException`. pub fn is_container_in_use_exception(&self) -> bool { matches!( &self.kind, GetLifecyclePolicyErrorKind::ContainerInUseException(_) ) } /// Returns `true` if the error kind is `GetLifecyclePolicyErrorKind::ContainerNotFoundException`. pub fn is_container_not_found_exception(&self) -> bool { matches!( &self.kind, GetLifecyclePolicyErrorKind::ContainerNotFoundException(_) ) } /// Returns `true` if the error kind is `GetLifecyclePolicyErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!( &self.kind, GetLifecyclePolicyErrorKind::InternalServerError(_) ) } /// Returns `true` if the error kind is `GetLifecyclePolicyErrorKind::PolicyNotFoundException`. pub fn is_policy_not_found_exception(&self) -> bool { matches!( &self.kind, GetLifecyclePolicyErrorKind::PolicyNotFoundException(_) ) } } impl std::error::Error for GetLifecyclePolicyError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { GetLifecyclePolicyErrorKind::ContainerInUseException(_inner) => Some(_inner), GetLifecyclePolicyErrorKind::ContainerNotFoundException(_inner) => Some(_inner), GetLifecyclePolicyErrorKind::InternalServerError(_inner) => Some(_inner), GetLifecyclePolicyErrorKind::PolicyNotFoundException(_inner) => Some(_inner), GetLifecyclePolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `GetMetricPolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct GetMetricPolicyError { /// Kind of error that occurred. pub kind: GetMetricPolicyErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `GetMetricPolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum GetMetricPolicyErrorKind { /// <p>The container that you specified in the request already exists or is being /// updated.</p> ContainerInUseException(crate::error::ContainerInUseException), /// <p>The container that you specified in the request does not exist.</p> ContainerNotFoundException(crate::error::ContainerNotFoundException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// <p>The policy that you specified in the request does not exist.</p> PolicyNotFoundException(crate::error::PolicyNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for GetMetricPolicyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { GetMetricPolicyErrorKind::ContainerInUseException(_inner) => _inner.fmt(f), GetMetricPolicyErrorKind::ContainerNotFoundException(_inner) => _inner.fmt(f), GetMetricPolicyErrorKind::InternalServerError(_inner) => _inner.fmt(f), GetMetricPolicyErrorKind::PolicyNotFoundException(_inner) => _inner.fmt(f), GetMetricPolicyErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for GetMetricPolicyError { fn code(&self) -> Option<&str> { GetMetricPolicyError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl GetMetricPolicyError { /// Creates a new `GetMetricPolicyError`. pub fn new(kind: GetMetricPolicyErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `GetMetricPolicyError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: GetMetricPolicyErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `GetMetricPolicyError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: GetMetricPolicyErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `GetMetricPolicyErrorKind::ContainerInUseException`. pub fn is_container_in_use_exception(&self) -> bool { matches!( &self.kind, GetMetricPolicyErrorKind::ContainerInUseException(_) ) } /// Returns `true` if the error kind is `GetMetricPolicyErrorKind::ContainerNotFoundException`. pub fn is_container_not_found_exception(&self) -> bool { matches!( &self.kind, GetMetricPolicyErrorKind::ContainerNotFoundException(_) ) } /// Returns `true` if the error kind is `GetMetricPolicyErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!(&self.kind, GetMetricPolicyErrorKind::InternalServerError(_)) } /// Returns `true` if the error kind is `GetMetricPolicyErrorKind::PolicyNotFoundException`. pub fn is_policy_not_found_exception(&self) -> bool { matches!( &self.kind, GetMetricPolicyErrorKind::PolicyNotFoundException(_) ) } } impl std::error::Error for GetMetricPolicyError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { GetMetricPolicyErrorKind::ContainerInUseException(_inner) => Some(_inner), GetMetricPolicyErrorKind::ContainerNotFoundException(_inner) => Some(_inner), GetMetricPolicyErrorKind::InternalServerError(_inner) => Some(_inner), GetMetricPolicyErrorKind::PolicyNotFoundException(_inner) => Some(_inner), GetMetricPolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListContainers` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListContainersError { /// Kind of error that occurred. pub kind: ListContainersErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListContainers` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListContainersErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListContainersError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListContainersErrorKind::InternalServerError(_inner) => _inner.fmt(f), ListContainersErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListContainersError { fn code(&self) -> Option<&str> { ListContainersError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListContainersError { /// Creates a new `ListContainersError`. pub fn new(kind: ListContainersErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListContainersError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListContainersErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListContainersError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListContainersErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListContainersErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!(&self.kind, ListContainersErrorKind::InternalServerError(_)) } } impl std::error::Error for ListContainersError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListContainersErrorKind::InternalServerError(_inner) => Some(_inner), ListContainersErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListTagsForResource` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListTagsForResourceError { /// Kind of error that occurred. pub kind: ListTagsForResourceErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListTagsForResource` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListTagsForResourceErrorKind { /// <p>The container that you specified in the request already exists or is being /// updated.</p> ContainerInUseException(crate::error::ContainerInUseException), /// <p>The container that you specified in the request does not exist.</p> ContainerNotFoundException(crate::error::ContainerNotFoundException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListTagsForResourceError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListTagsForResourceErrorKind::ContainerInUseException(_inner) => _inner.fmt(f), ListTagsForResourceErrorKind::ContainerNotFoundException(_inner) => _inner.fmt(f), ListTagsForResourceErrorKind::InternalServerError(_inner) => _inner.fmt(f), ListTagsForResourceErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListTagsForResourceError { fn code(&self) -> Option<&str> { ListTagsForResourceError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListTagsForResourceError { /// Creates a new `ListTagsForResourceError`. pub fn new(kind: ListTagsForResourceErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListTagsForResourceError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListTagsForResourceErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListTagsForResourceError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListTagsForResourceErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListTagsForResourceErrorKind::ContainerInUseException`. pub fn is_container_in_use_exception(&self) -> bool { matches!( &self.kind, ListTagsForResourceErrorKind::ContainerInUseException(_) ) } /// Returns `true` if the error kind is `ListTagsForResourceErrorKind::ContainerNotFoundException`. pub fn is_container_not_found_exception(&self) -> bool { matches!( &self.kind, ListTagsForResourceErrorKind::ContainerNotFoundException(_) ) } /// Returns `true` if the error kind is `ListTagsForResourceErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!( &self.kind, ListTagsForResourceErrorKind::InternalServerError(_) ) } } impl std::error::Error for ListTagsForResourceError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListTagsForResourceErrorKind::ContainerInUseException(_inner) => Some(_inner), ListTagsForResourceErrorKind::ContainerNotFoundException(_inner) => Some(_inner), ListTagsForResourceErrorKind::InternalServerError(_inner) => Some(_inner), ListTagsForResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `PutContainerPolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct PutContainerPolicyError { /// Kind of error that occurred. pub kind: PutContainerPolicyErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `PutContainerPolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum PutContainerPolicyErrorKind { /// <p>The container that you specified in the request already exists or is being /// updated.</p> ContainerInUseException(crate::error::ContainerInUseException), /// <p>The container that you specified in the request does not exist.</p> ContainerNotFoundException(crate::error::ContainerNotFoundException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for PutContainerPolicyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { PutContainerPolicyErrorKind::ContainerInUseException(_inner) => _inner.fmt(f), PutContainerPolicyErrorKind::ContainerNotFoundException(_inner) => _inner.fmt(f), PutContainerPolicyErrorKind::InternalServerError(_inner) => _inner.fmt(f), PutContainerPolicyErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for PutContainerPolicyError { fn code(&self) -> Option<&str> { PutContainerPolicyError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl PutContainerPolicyError { /// Creates a new `PutContainerPolicyError`. pub fn new(kind: PutContainerPolicyErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `PutContainerPolicyError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: PutContainerPolicyErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `PutContainerPolicyError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: PutContainerPolicyErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `PutContainerPolicyErrorKind::ContainerInUseException`. pub fn is_container_in_use_exception(&self) -> bool { matches!( &self.kind, PutContainerPolicyErrorKind::ContainerInUseException(_) ) } /// Returns `true` if the error kind is `PutContainerPolicyErrorKind::ContainerNotFoundException`. pub fn is_container_not_found_exception(&self) -> bool { matches!( &self.kind, PutContainerPolicyErrorKind::ContainerNotFoundException(_) ) } /// Returns `true` if the error kind is `PutContainerPolicyErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!( &self.kind, PutContainerPolicyErrorKind::InternalServerError(_) ) } } impl std::error::Error for PutContainerPolicyError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { PutContainerPolicyErrorKind::ContainerInUseException(_inner) => Some(_inner), PutContainerPolicyErrorKind::ContainerNotFoundException(_inner) => Some(_inner), PutContainerPolicyErrorKind::InternalServerError(_inner) => Some(_inner), PutContainerPolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `PutCorsPolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct PutCorsPolicyError { /// Kind of error that occurred. pub kind: PutCorsPolicyErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `PutCorsPolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum PutCorsPolicyErrorKind { /// <p>The container that you specified in the request already exists or is being /// updated.</p> ContainerInUseException(crate::error::ContainerInUseException), /// <p>The container that you specified in the request does not exist.</p> ContainerNotFoundException(crate::error::ContainerNotFoundException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for PutCorsPolicyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { PutCorsPolicyErrorKind::ContainerInUseException(_inner) => _inner.fmt(f), PutCorsPolicyErrorKind::ContainerNotFoundException(_inner) => _inner.fmt(f), PutCorsPolicyErrorKind::InternalServerError(_inner) => _inner.fmt(f), PutCorsPolicyErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for PutCorsPolicyError { fn code(&self) -> Option<&str> { PutCorsPolicyError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl PutCorsPolicyError { /// Creates a new `PutCorsPolicyError`. pub fn new(kind: PutCorsPolicyErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `PutCorsPolicyError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: PutCorsPolicyErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `PutCorsPolicyError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: PutCorsPolicyErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `PutCorsPolicyErrorKind::ContainerInUseException`. pub fn is_container_in_use_exception(&self) -> bool { matches!( &self.kind, PutCorsPolicyErrorKind::ContainerInUseException(_) ) } /// Returns `true` if the error kind is `PutCorsPolicyErrorKind::ContainerNotFoundException`. pub fn is_container_not_found_exception(&self) -> bool { matches!( &self.kind, PutCorsPolicyErrorKind::ContainerNotFoundException(_) ) } /// Returns `true` if the error kind is `PutCorsPolicyErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!(&self.kind, PutCorsPolicyErrorKind::InternalServerError(_)) } } impl std::error::Error for PutCorsPolicyError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { PutCorsPolicyErrorKind::ContainerInUseException(_inner) => Some(_inner), PutCorsPolicyErrorKind::ContainerNotFoundException(_inner) => Some(_inner), PutCorsPolicyErrorKind::InternalServerError(_inner) => Some(_inner), PutCorsPolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `PutLifecyclePolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct PutLifecyclePolicyError { /// Kind of error that occurred. pub kind: PutLifecyclePolicyErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `PutLifecyclePolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum PutLifecyclePolicyErrorKind { /// <p>The container that you specified in the request already exists or is being /// updated.</p> ContainerInUseException(crate::error::ContainerInUseException), /// <p>The container that you specified in the request does not exist.</p> ContainerNotFoundException(crate::error::ContainerNotFoundException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for PutLifecyclePolicyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { PutLifecyclePolicyErrorKind::ContainerInUseException(_inner) => _inner.fmt(f), PutLifecyclePolicyErrorKind::ContainerNotFoundException(_inner) => _inner.fmt(f), PutLifecyclePolicyErrorKind::InternalServerError(_inner) => _inner.fmt(f), PutLifecyclePolicyErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for PutLifecyclePolicyError { fn code(&self) -> Option<&str> { PutLifecyclePolicyError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl PutLifecyclePolicyError { /// Creates a new `PutLifecyclePolicyError`. pub fn new(kind: PutLifecyclePolicyErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `PutLifecyclePolicyError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: PutLifecyclePolicyErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `PutLifecyclePolicyError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: PutLifecyclePolicyErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `PutLifecyclePolicyErrorKind::ContainerInUseException`. pub fn is_container_in_use_exception(&self) -> bool { matches!( &self.kind, PutLifecyclePolicyErrorKind::ContainerInUseException(_) ) } /// Returns `true` if the error kind is `PutLifecyclePolicyErrorKind::ContainerNotFoundException`. pub fn is_container_not_found_exception(&self) -> bool { matches!( &self.kind, PutLifecyclePolicyErrorKind::ContainerNotFoundException(_) ) } /// Returns `true` if the error kind is `PutLifecyclePolicyErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!( &self.kind, PutLifecyclePolicyErrorKind::InternalServerError(_) ) } } impl std::error::Error for PutLifecyclePolicyError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { PutLifecyclePolicyErrorKind::ContainerInUseException(_inner) => Some(_inner), PutLifecyclePolicyErrorKind::ContainerNotFoundException(_inner) => Some(_inner), PutLifecyclePolicyErrorKind::InternalServerError(_inner) => Some(_inner), PutLifecyclePolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `PutMetricPolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct PutMetricPolicyError { /// Kind of error that occurred. pub kind: PutMetricPolicyErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `PutMetricPolicy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum PutMetricPolicyErrorKind { /// <p>The container that you specified in the request already exists or is being /// updated.</p> ContainerInUseException(crate::error::ContainerInUseException), /// <p>The container that you specified in the request does not exist.</p> ContainerNotFoundException(crate::error::ContainerNotFoundException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for PutMetricPolicyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { PutMetricPolicyErrorKind::ContainerInUseException(_inner) => _inner.fmt(f), PutMetricPolicyErrorKind::ContainerNotFoundException(_inner) => _inner.fmt(f), PutMetricPolicyErrorKind::InternalServerError(_inner) => _inner.fmt(f), PutMetricPolicyErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for PutMetricPolicyError { fn code(&self) -> Option<&str> { PutMetricPolicyError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl PutMetricPolicyError { /// Creates a new `PutMetricPolicyError`. pub fn new(kind: PutMetricPolicyErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `PutMetricPolicyError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: PutMetricPolicyErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `PutMetricPolicyError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: PutMetricPolicyErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `PutMetricPolicyErrorKind::ContainerInUseException`. pub fn is_container_in_use_exception(&self) -> bool { matches!( &self.kind, PutMetricPolicyErrorKind::ContainerInUseException(_) ) } /// Returns `true` if the error kind is `PutMetricPolicyErrorKind::ContainerNotFoundException`. pub fn is_container_not_found_exception(&self) -> bool { matches!( &self.kind, PutMetricPolicyErrorKind::ContainerNotFoundException(_) ) } /// Returns `true` if the error kind is `PutMetricPolicyErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!(&self.kind, PutMetricPolicyErrorKind::InternalServerError(_)) } } impl std::error::Error for PutMetricPolicyError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { PutMetricPolicyErrorKind::ContainerInUseException(_inner) => Some(_inner), PutMetricPolicyErrorKind::ContainerNotFoundException(_inner) => Some(_inner), PutMetricPolicyErrorKind::InternalServerError(_inner) => Some(_inner), PutMetricPolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `StartAccessLogging` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct StartAccessLoggingError { /// Kind of error that occurred. pub kind: StartAccessLoggingErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `StartAccessLogging` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum StartAccessLoggingErrorKind { /// <p>The container that you specified in the request already exists or is being /// updated.</p> ContainerInUseException(crate::error::ContainerInUseException), /// <p>The container that you specified in the request does not exist.</p> ContainerNotFoundException(crate::error::ContainerNotFoundException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for StartAccessLoggingError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { StartAccessLoggingErrorKind::ContainerInUseException(_inner) => _inner.fmt(f), StartAccessLoggingErrorKind::ContainerNotFoundException(_inner) => _inner.fmt(f), StartAccessLoggingErrorKind::InternalServerError(_inner) => _inner.fmt(f), StartAccessLoggingErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for StartAccessLoggingError { fn code(&self) -> Option<&str> { StartAccessLoggingError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl StartAccessLoggingError { /// Creates a new `StartAccessLoggingError`. pub fn new(kind: StartAccessLoggingErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `StartAccessLoggingError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: StartAccessLoggingErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `StartAccessLoggingError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: StartAccessLoggingErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `StartAccessLoggingErrorKind::ContainerInUseException`. pub fn is_container_in_use_exception(&self) -> bool { matches!( &self.kind, StartAccessLoggingErrorKind::ContainerInUseException(_) ) } /// Returns `true` if the error kind is `StartAccessLoggingErrorKind::ContainerNotFoundException`. pub fn is_container_not_found_exception(&self) -> bool { matches!( &self.kind, StartAccessLoggingErrorKind::ContainerNotFoundException(_) ) } /// Returns `true` if the error kind is `StartAccessLoggingErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!( &self.kind, StartAccessLoggingErrorKind::InternalServerError(_) ) } } impl std::error::Error for StartAccessLoggingError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { StartAccessLoggingErrorKind::ContainerInUseException(_inner) => Some(_inner), StartAccessLoggingErrorKind::ContainerNotFoundException(_inner) => Some(_inner), StartAccessLoggingErrorKind::InternalServerError(_inner) => Some(_inner), StartAccessLoggingErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `StopAccessLogging` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct StopAccessLoggingError { /// Kind of error that occurred. pub kind: StopAccessLoggingErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `StopAccessLogging` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum StopAccessLoggingErrorKind { /// <p>The container that you specified in the request already exists or is being /// updated.</p> ContainerInUseException(crate::error::ContainerInUseException), /// <p>The container that you specified in the request does not exist.</p> ContainerNotFoundException(crate::error::ContainerNotFoundException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for StopAccessLoggingError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { StopAccessLoggingErrorKind::ContainerInUseException(_inner) => _inner.fmt(f), StopAccessLoggingErrorKind::ContainerNotFoundException(_inner) => _inner.fmt(f), StopAccessLoggingErrorKind::InternalServerError(_inner) => _inner.fmt(f), StopAccessLoggingErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for StopAccessLoggingError { fn code(&self) -> Option<&str> { StopAccessLoggingError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl StopAccessLoggingError { /// Creates a new `StopAccessLoggingError`. pub fn new(kind: StopAccessLoggingErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `StopAccessLoggingError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: StopAccessLoggingErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `StopAccessLoggingError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: StopAccessLoggingErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `StopAccessLoggingErrorKind::ContainerInUseException`. pub fn is_container_in_use_exception(&self) -> bool { matches!( &self.kind, StopAccessLoggingErrorKind::ContainerInUseException(_) ) } /// Returns `true` if the error kind is `StopAccessLoggingErrorKind::ContainerNotFoundException`. pub fn is_container_not_found_exception(&self) -> bool { matches!( &self.kind, StopAccessLoggingErrorKind::ContainerNotFoundException(_) ) } /// Returns `true` if the error kind is `StopAccessLoggingErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!( &self.kind, StopAccessLoggingErrorKind::InternalServerError(_) ) } } impl std::error::Error for StopAccessLoggingError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { StopAccessLoggingErrorKind::ContainerInUseException(_inner) => Some(_inner), StopAccessLoggingErrorKind::ContainerNotFoundException(_inner) => Some(_inner), StopAccessLoggingErrorKind::InternalServerError(_inner) => Some(_inner), StopAccessLoggingErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `TagResource` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct TagResourceError { /// Kind of error that occurred. pub kind: TagResourceErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `TagResource` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum TagResourceErrorKind { /// <p>The container that you specified in the request already exists or is being /// updated.</p> ContainerInUseException(crate::error::ContainerInUseException), /// <p>The container that you specified in the request does not exist.</p> ContainerNotFoundException(crate::error::ContainerNotFoundException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for TagResourceError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { TagResourceErrorKind::ContainerInUseException(_inner) => _inner.fmt(f), TagResourceErrorKind::ContainerNotFoundException(_inner) => _inner.fmt(f), TagResourceErrorKind::InternalServerError(_inner) => _inner.fmt(f), TagResourceErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for TagResourceError { fn code(&self) -> Option<&str> { TagResourceError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl TagResourceError { /// Creates a new `TagResourceError`. pub fn new(kind: TagResourceErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `TagResourceError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: TagResourceErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `TagResourceError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: TagResourceErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `TagResourceErrorKind::ContainerInUseException`. pub fn is_container_in_use_exception(&self) -> bool { matches!(&self.kind, TagResourceErrorKind::ContainerInUseException(_)) } /// Returns `true` if the error kind is `TagResourceErrorKind::ContainerNotFoundException`. pub fn is_container_not_found_exception(&self) -> bool { matches!( &self.kind, TagResourceErrorKind::ContainerNotFoundException(_) ) } /// Returns `true` if the error kind is `TagResourceErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!(&self.kind, TagResourceErrorKind::InternalServerError(_)) } } impl std::error::Error for TagResourceError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { TagResourceErrorKind::ContainerInUseException(_inner) => Some(_inner), TagResourceErrorKind::ContainerNotFoundException(_inner) => Some(_inner), TagResourceErrorKind::InternalServerError(_inner) => Some(_inner), TagResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UntagResource` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UntagResourceError { /// Kind of error that occurred. pub kind: UntagResourceErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UntagResource` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UntagResourceErrorKind { /// <p>The container that you specified in the request already exists or is being /// updated.</p> ContainerInUseException(crate::error::ContainerInUseException), /// <p>The container that you specified in the request does not exist.</p> ContainerNotFoundException(crate::error::ContainerNotFoundException), /// <p>The service is temporarily unavailable.</p> InternalServerError(crate::error::InternalServerError), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UntagResourceError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UntagResourceErrorKind::ContainerInUseException(_inner) => _inner.fmt(f), UntagResourceErrorKind::ContainerNotFoundException(_inner) => _inner.fmt(f), UntagResourceErrorKind::InternalServerError(_inner) => _inner.fmt(f), UntagResourceErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UntagResourceError { fn code(&self) -> Option<&str> { UntagResourceError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UntagResourceError { /// Creates a new `UntagResourceError`. pub fn new(kind: UntagResourceErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UntagResourceError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UntagResourceErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UntagResourceError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UntagResourceErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UntagResourceErrorKind::ContainerInUseException`. pub fn is_container_in_use_exception(&self) -> bool { matches!( &self.kind, UntagResourceErrorKind::ContainerInUseException(_) ) } /// Returns `true` if the error kind is `UntagResourceErrorKind::ContainerNotFoundException`. pub fn is_container_not_found_exception(&self) -> bool { matches!( &self.kind, UntagResourceErrorKind::ContainerNotFoundException(_) ) } /// Returns `true` if the error kind is `UntagResourceErrorKind::InternalServerError`. pub fn is_internal_server_error(&self) -> bool { matches!(&self.kind, UntagResourceErrorKind::InternalServerError(_)) } } impl std::error::Error for UntagResourceError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UntagResourceErrorKind::ContainerInUseException(_inner) => Some(_inner), UntagResourceErrorKind::ContainerNotFoundException(_inner) => Some(_inner), UntagResourceErrorKind::InternalServerError(_inner) => Some(_inner), UntagResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// <p>The service is temporarily unavailable.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct InternalServerError { #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for InternalServerError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("InternalServerError"); formatter.field("message", &self.message); formatter.finish() } } impl InternalServerError { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for InternalServerError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "InternalServerError")?; if let Some(inner_1) = &self.message { write!(f, ": {}", inner_1)?; } Ok(()) } } impl std::error::Error for InternalServerError {} /// See [`InternalServerError`](crate::error::InternalServerError) pub mod internal_server_error { /// A builder for [`InternalServerError`](crate::error::InternalServerError) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`InternalServerError`](crate::error::InternalServerError) pub fn build(self) -> crate::error::InternalServerError { crate::error::InternalServerError { message: self.message, } } } } impl InternalServerError { /// Creates a new builder-style object to manufacture [`InternalServerError`](crate::error::InternalServerError) pub fn builder() -> crate::error::internal_server_error::Builder { crate::error::internal_server_error::Builder::default() } } /// <p>The container that you specified in the request does not exist.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ContainerNotFoundException { #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for ContainerNotFoundException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ContainerNotFoundException"); formatter.field("message", &self.message); formatter.finish() } } impl ContainerNotFoundException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for ContainerNotFoundException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ContainerNotFoundException")?; if let Some(inner_2) = &self.message { write!(f, ": {}", inner_2)?; } Ok(()) } } impl std::error::Error for ContainerNotFoundException {} /// See [`ContainerNotFoundException`](crate::error::ContainerNotFoundException) pub mod container_not_found_exception { /// A builder for [`ContainerNotFoundException`](crate::error::ContainerNotFoundException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`ContainerNotFoundException`](crate::error::ContainerNotFoundException) pub fn build(self) -> crate::error::ContainerNotFoundException { crate::error::ContainerNotFoundException { message: self.message, } } } } impl ContainerNotFoundException { /// Creates a new builder-style object to manufacture [`ContainerNotFoundException`](crate::error::ContainerNotFoundException) pub fn builder() -> crate::error::container_not_found_exception::Builder { crate::error::container_not_found_exception::Builder::default() } } /// <p>The container that you specified in the request already exists or is being /// updated.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ContainerInUseException { #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for ContainerInUseException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ContainerInUseException"); formatter.field("message", &self.message); formatter.finish() } } impl ContainerInUseException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for ContainerInUseException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ContainerInUseException")?; if let Some(inner_3) = &self.message { write!(f, ": {}", inner_3)?; } Ok(()) } } impl std::error::Error for ContainerInUseException {} /// See [`ContainerInUseException`](crate::error::ContainerInUseException) pub mod container_in_use_exception { /// A builder for [`ContainerInUseException`](crate::error::ContainerInUseException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`ContainerInUseException`](crate::error::ContainerInUseException) pub fn build(self) -> crate::error::ContainerInUseException { crate::error::ContainerInUseException { message: self.message, } } } } impl ContainerInUseException { /// Creates a new builder-style object to manufacture [`ContainerInUseException`](crate::error::ContainerInUseException) pub fn builder() -> crate::error::container_in_use_exception::Builder { crate::error::container_in_use_exception::Builder::default() } } /// <p>The policy that you specified in the request does not exist.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PolicyNotFoundException { #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for PolicyNotFoundException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PolicyNotFoundException"); formatter.field("message", &self.message); formatter.finish() } } impl PolicyNotFoundException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for PolicyNotFoundException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "PolicyNotFoundException")?; if let Some(inner_4) = &self.message { write!(f, ": {}", inner_4)?; } Ok(()) } } impl std::error::Error for PolicyNotFoundException {} /// See [`PolicyNotFoundException`](crate::error::PolicyNotFoundException) pub mod policy_not_found_exception { /// A builder for [`PolicyNotFoundException`](crate::error::PolicyNotFoundException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`PolicyNotFoundException`](crate::error::PolicyNotFoundException) pub fn build(self) -> crate::error::PolicyNotFoundException { crate::error::PolicyNotFoundException { message: self.message, } } } } impl PolicyNotFoundException { /// Creates a new builder-style object to manufacture [`PolicyNotFoundException`](crate::error::PolicyNotFoundException) pub fn builder() -> crate::error::policy_not_found_exception::Builder { crate::error::policy_not_found_exception::Builder::default() } } /// <p>The CORS policy that you specified in the request does not exist.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CorsPolicyNotFoundException { #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for CorsPolicyNotFoundException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CorsPolicyNotFoundException"); formatter.field("message", &self.message); formatter.finish() } } impl CorsPolicyNotFoundException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for CorsPolicyNotFoundException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "CorsPolicyNotFoundException")?; if let Some(inner_5) = &self.message { write!(f, ": {}", inner_5)?; } Ok(()) } } impl std::error::Error for CorsPolicyNotFoundException {} /// See [`CorsPolicyNotFoundException`](crate::error::CorsPolicyNotFoundException) pub mod cors_policy_not_found_exception { /// A builder for [`CorsPolicyNotFoundException`](crate::error::CorsPolicyNotFoundException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`CorsPolicyNotFoundException`](crate::error::CorsPolicyNotFoundException) pub fn build(self) -> crate::error::CorsPolicyNotFoundException { crate::error::CorsPolicyNotFoundException { message: self.message, } } } } impl CorsPolicyNotFoundException { /// Creates a new builder-style object to manufacture [`CorsPolicyNotFoundException`](crate::error::CorsPolicyNotFoundException) pub fn builder() -> crate::error::cors_policy_not_found_exception::Builder { crate::error::cors_policy_not_found_exception::Builder::default() } } /// <p>A service limit has been exceeded.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct LimitExceededException { #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for LimitExceededException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("LimitExceededException"); formatter.field("message", &self.message); formatter.finish() } } impl LimitExceededException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for LimitExceededException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "LimitExceededException")?; if let Some(inner_6) = &self.message { write!(f, ": {}", inner_6)?; } Ok(()) } } impl std::error::Error for LimitExceededException {} /// See [`LimitExceededException`](crate::error::LimitExceededException) pub mod limit_exceeded_exception { /// A builder for [`LimitExceededException`](crate::error::LimitExceededException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`LimitExceededException`](crate::error::LimitExceededException) pub fn build(self) -> crate::error::LimitExceededException { crate::error::LimitExceededException { message: self.message, } } } } impl LimitExceededException { /// Creates a new builder-style object to manufacture [`LimitExceededException`](crate::error::LimitExceededException) pub fn builder() -> crate::error::limit_exceeded_exception::Builder { crate::error::limit_exceeded_exception::Builder::default() } }
{ matches!( &self.kind, DeleteLifecyclePolicyErrorKind::PolicyNotFoundException(_) ) }
cors_get_issue_lsp.js
/*globals module, $, console*/ var getData = function () { 'use strict'; var apiUrl = 'http://lsp.powerathens.com/api/v1/station/now-playing/'; var ajaxObj = { url: apiUrl, data: { callback: 'cmg.radioheader.lsploop_callbacks.callback0' }, success: function() { console.log('success'); }, method: 'GET', error: function () { console.log('Error polling LSP API:', arguments); } }; try { $.ajax(ajaxObj);
}; module.exports = { getData: getData };
} catch (err) { console.log(err); }
text_field.rs
use crate::avm1::function::Executable; use crate::avm1::globals::display_object; use crate::avm1::property::Attribute::*; use crate::avm1::return_value::ReturnValue; use crate::avm1::{Avm1, Error, Object, ScriptObject, TObject, UpdateContext, Value}; use crate::display_object::{EditText, TDisplayObject}; use crate::font::TextFormat; use gc_arena::MutationContext; /// Implements `TextField` pub fn constructor<'gc>( _avm: &mut Avm1<'gc>, _context: &mut UpdateContext<'_, 'gc, '_>, _this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { Ok(Value::Undefined.into()) } pub fn get_text<'gc>( _avm: &mut Avm1<'gc>, _context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { if let Some(display_object) = this.as_display_object() { if let Some(text_field) = display_object.as_edit_text() { return Ok(text_field.text().into()); } } Ok(Value::Undefined.into()) } pub fn set_text<'gc>( avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { if let Some(display_object) = this.as_display_object() { if let Some(text_field) = display_object.as_edit_text() { if let Some(value) = args.get(0) { text_field.set_text(
.unwrap_or_else(|_| "undefined".to_string()), context.gc_context, ) } } } Ok(Value::Undefined.into()) } macro_rules! with_text_field { ( $gc_context: ident, $object:ident, $fn_proto: expr, $($name:expr => $fn:expr),* ) => {{ $( $object.force_set_function( $name, |avm, context: &mut UpdateContext<'_, 'gc, '_>, this, args| -> Result<ReturnValue<'gc>, Error> { if let Some(display_object) = this.as_display_object() { if let Some(text_field) = display_object.as_edit_text() { return $fn(text_field, avm, context, args); } } Ok(Value::Undefined.into()) } as crate::avm1::function::NativeFunction<'gc>, $gc_context, DontDelete | ReadOnly | DontEnum, $fn_proto ); )* }}; } pub fn text_width<'gc>( _avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { if let Some(etext) = this .as_display_object() .and_then(|dobj| dobj.as_edit_text()) { let metrics = etext.measure_text(context); return Ok(metrics.0.to_pixels().into()); } Ok(Value::Undefined.into()) } pub fn text_height<'gc>( _avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { if let Some(etext) = this .as_display_object() .and_then(|dobj| dobj.as_edit_text()) { let metrics = etext.measure_text(context); return Ok(metrics.1.to_pixels().into()); } Ok(Value::Undefined.into()) } pub fn multiline<'gc>( _avm: &mut Avm1<'gc>, _context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { if let Some(etext) = this .as_display_object() .and_then(|dobj| dobj.as_edit_text()) { return Ok(etext.is_multiline().into()); } Ok(Value::Undefined.into()) } pub fn set_multiline<'gc>( avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { let is_multiline = args .get(0) .cloned() .unwrap_or(Value::Undefined) .as_bool(avm.current_swf_version()); if let Some(etext) = this .as_display_object() .and_then(|dobj| dobj.as_edit_text()) { etext.set_multiline(is_multiline, context.gc_context); } Ok(Value::Undefined.into()) } pub fn word_wrap<'gc>( _avm: &mut Avm1<'gc>, _context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { if let Some(etext) = this .as_display_object() .and_then(|dobj| dobj.as_edit_text()) { return Ok(etext.is_word_wrap().into()); } Ok(Value::Undefined.into()) } pub fn set_word_wrap<'gc>( avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { let is_word_wrap = args .get(0) .cloned() .unwrap_or(Value::Undefined) .as_bool(avm.current_swf_version()); if let Some(etext) = this .as_display_object() .and_then(|dobj| dobj.as_edit_text()) { etext.set_word_wrap(is_word_wrap, context.gc_context); } Ok(Value::Undefined.into()) } pub fn create_proto<'gc>( gc_context: MutationContext<'gc, '_>, proto: Object<'gc>, fn_proto: Object<'gc>, ) -> Object<'gc> { let mut object = ScriptObject::object(gc_context, Some(proto)); display_object::define_display_object_proto(gc_context, object, fn_proto); with_text_field!( gc_context, object, Some(fn_proto), "getNewTextFormat" => |text_field: EditText<'gc>, avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, _args| { let tf = text_field.new_text_format(); Ok(tf.as_avm1_object(avm, context)?.into()) }, "setNewTextFormat" => |text_field: EditText<'gc>, avm: &mut Avm1<'gc>, context: &mut UpdateContext<'_, 'gc, '_>, args: &[Value<'gc>]| { let tf = args.get(0).cloned().unwrap_or(Value::Undefined); if let Value::Object(tf) = tf { let tf_parsed = TextFormat::from_avm1_object(tf, avm, context)?; text_field.set_new_text_format(tf_parsed, context.gc_context); } Ok(Value::Undefined.into()) } ); object.into() } pub fn attach_virtual_properties<'gc>(gc_context: MutationContext<'gc, '_>, object: Object<'gc>) { object.add_property( gc_context, "text", Executable::Native(get_text), Some(Executable::Native(set_text)), DontDelete | ReadOnly | DontEnum, ); object.add_property( gc_context, "textWidth", Executable::Native(text_width), None, ReadOnly.into(), ); object.add_property( gc_context, "textHeight", Executable::Native(text_height), None, ReadOnly.into(), ); object.add_property( gc_context, "multiline", Executable::Native(multiline), Some(Executable::Native(set_multiline)), ReadOnly.into(), ); object.add_property( gc_context, "wordWrap", Executable::Native(word_wrap), Some(Executable::Native(set_word_wrap)), ReadOnly.into(), ); }
value .to_owned() .coerce_to_string(avm, context)
error.rs
// Copyright (c) 2019 - 2021 ESRLabs // // 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 super::{Container, ExitStatus, RepositoryId}; use crate::{ api::{self}, npk, }; use std::io; use thiserror::Error; #[derive(Error, Debug)] pub enum Error { #[error("Invalid configuration: {0}")] Configuration(String), #[error("Invalid container {0}")] InvalidContainer(Container), #[error("Invalid arguments {0}")] InvalidArguments(String), #[error("Container {0} cannot be mounted because it is already mounted")] MountBusy(Container), #[error("Duplicate container {0}")] DuplicateContainer(Container), #[error("Container {0} cannot be unmounted: busy")] UmountBusy(Container), #[error("Container {0} failed to start: Already started")] StartContainerStarted(Container), #[error("Container {0} failed to start: Resources cannot be started")] StartContainerResource(Container), #[error("Container {0} failed to start: Resource {1} is missing")] StartContainerMissingResource(Container, Container), #[error("Container {0} failed to start: {1}")] StartContainerFailed(Container, String), #[error("Container {0} failed to stop: Not started")] StopContainerNotStarted(Container), #[error("Invalid repository {0}")] InvalidRepository(RepositoryId), #[error("Failed to install {0}: Already installed")] InstallDuplicate(Container), #[error("Critical container failure")] CriticalContainer(Container, ExitStatus), #[error("NPK {0:?}: {1:?}")] Npk(String, npk::npk::Error), #[error("Console: {0:?}")] Console(super::console::Error), #[error("Cgroups: {0}")] Cgroups(#[from] super::cgroups::Error), #[error("Mount: {0}")] Mount(super::mount::Error), #[error("Name: {0}")] Name(String), #[error("Key: {0}")] Key(super::key::Error), #[error("Io: {0}: {1:?}")] Io(String, io::Error), #[error("Os: {0}: {1:?}")] Os(String, nix::Error), #[error("{0}: {1:?}")] Other(String, String), }
impl Error { pub(crate) fn io<T: ToString>(m: T, e: io::Error) -> Error { Error::Io(m.to_string(), e) } pub(crate) fn os<T: ToString>(e: T, err: nix::Error) -> Error { Error::Os(e.to_string(), err) } pub(crate) fn other<T: ToString, E: std::fmt::Debug>(e: T, err: E) -> Error { Error::Other(e.to_string(), format!("{:?}", err)) } } impl From<Error> for api::model::Error { fn from(error: Error) -> api::model::Error { match error { Error::Configuration(cause) => api::model::Error::Configuration(cause), Error::DuplicateContainer(container) => { api::model::Error::DuplicateContainer(container) } Error::InvalidContainer(container) => api::model::Error::InvalidContainer(container), Error::InvalidArguments(cause) => api::model::Error::InvalidArguments(cause), Error::MountBusy(container) => api::model::Error::MountBusy(container), Error::UmountBusy(container) => api::model::Error::UmountBusy(container), Error::StartContainerStarted(container) => { api::model::Error::StartContainerStarted(container) } Error::StartContainerResource(container) => { api::model::Error::StartContainerResource(container) } Error::StartContainerMissingResource(container, resource) => { api::model::Error::StartContainerMissingResource(container, resource) } Error::StartContainerFailed(container, reason) => { api::model::Error::StartContainerFailed(container, reason) } Error::StopContainerNotStarted(container) => { api::model::Error::StopContainerNotStarted(container) } Error::InvalidRepository(repository) => { api::model::Error::InvalidRepository(repository) } Error::InstallDuplicate(container) => api::model::Error::InstallDuplicate(container), Error::CriticalContainer(container, status) => { api::model::Error::CriticalContainer(container, status.into()) } Error::Npk(cause, error) => api::model::Error::Npk(cause, error.to_string()), Error::Console(error) => api::model::Error::Console(error.to_string()), Error::Cgroups(error) => api::model::Error::Cgroups(error.to_string()), Error::Mount(error) => api::model::Error::Mount(error.to_string()), Error::Name(error) => api::model::Error::Name(error), Error::Key(error) => api::model::Error::Key(error.to_string()), Error::Io(cause, error) => api::model::Error::Io(format!("{}: {}", cause, error)), Error::Os(cause, error) => api::model::Error::Os(format!("{}: {}", cause, error)), Error::Other(cause, error) => api::model::Error::Other(cause, error), } } }
switch.rs
#![no_main] #![no_std] extern crate panic_halt; use cortex_m_rt::entry; use crate::hal::{prelude::*, stm32}; use embedded_hal::digital::v2::{InputPin, OutputPin}; use stm32f0xx_hal as hal; #[entry] fn main() -> ! { let (mut led, switch) = config(); loop { if switch.is_high().unwrap() { led.set_high().unwrap() } else { led.set_low().unwrap() } } }
cortex_m::interrupt::free(move |cs| { let mut rcc = p.RCC.configure().sysclk(8.mhz()).freeze(&mut p.FLASH); let gpiob = p.GPIOB.split(&mut rcc); let led = gpiob.pb3.into_push_pull_output(cs); let switch = gpiob.pb4.into_pull_up_input(cs); //D12 (led, switch) }) }
//Configure MCU, and return *abstract* pin trait. The real type is PB3<Output<PushPull>> fn config() -> (impl OutputPin<Error = ()>, impl InputPin<Error = ()>) { let mut p = stm32::Peripherals::take().unwrap();
chromeos_view.js
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * This view displays information on ChromeOS specific features. */ var CrosView = (function() { 'use strict'; var fileContent; var passcode = ''; /** * Clear file input div * * @private */ function clearFileInput_() { $(CrosView.IMPORT_DIV_ID).innerHTML = $(CrosView.IMPORT_DIV_ID).innerHTML; $(CrosView.IMPORT_ONC_ID).addEventListener('change', handleFileChangeEvent_, false); } /** * Send file contents and passcode to C++ cros network library. * * @private */ function importONCFile_() { clearParseStatus_(); if (fileContent) g_browser.importONCFile(fileContent, passcode); else setParseStatus_('ONC file parse failed: cannot read file'); clearFileInput_(); } /** * Set the passcode var, and trigger onc import. * * @param {string} value The passcode value. * @private */ function setPasscode_(value) { passcode = value; if (passcode) importONCFile_(); } /**
* @private */ function promptForPasscode_() { $(CrosView.PASSCODE_ID).hidden = false; $(CrosView.PASSCODE_INPUT_ID).focus(); $(CrosView.PASSCODE_INPUT_ID).select(); } /** * Set the fileContent var, and trigger onc import if the file appears to * not be encrypted, or prompt for passcode if the file is encrypted. * * @private * @param {string} text contents of selected file. */ function setFileContent_(result) { fileContent = result; // Parse the JSON to get at the top level "Type" property. var jsonObject; // Ignore any parse errors: they'll get handled in the C++ import code. try { jsonObject = JSON.parse(fileContent); } catch (error) {} // Check if file is encrypted. if (jsonObject && jsonObject.hasOwnProperty('Type') && jsonObject.Type == 'EncryptedConfiguration') { promptForPasscode_(); } else { importONCFile_(); } } /** * Clear ONC file parse status. Clears and hides the parse status div. * * @private */ function clearParseStatus_(error) { var parseStatus = $(CrosView.PARSE_STATUS_ID); parseStatus.hidden = true; parseStatus.textContent = ''; } /** * Set ONC file parse status. * * @private */ function setParseStatus_(error) { var parseStatus = $(CrosView.PARSE_STATUS_ID); parseStatus.hidden = false; parseStatus.textContent = error ? 'ONC file parse failed: ' + error : 'ONC file successfully parsed'; reset_(); } /** * Set storing debug logs status. * * @private */ function setStoreDebugLogsStatus_(status) { $(CrosView.STORE_DEBUG_LOGS_STATUS_ID).innerText = status; } /** * Set status for current debug mode. * * @private */ function setNetworkDebugModeStatus_(status) { $(CrosView.DEBUG_STATUS_ID).innerText = status; } /** * An event listener for the file selection field. * * @private */ function handleFileChangeEvent_(event) { clearParseStatus_(); var file = event.target.files[0]; var reader = new FileReader(); reader.onloadend = function(e) { setFileContent_(reader.result); }; reader.readAsText(file); } /** * Add event listeners for the file selection, passcode input * fields, for the button for debug logs storing and for buttons * for debug mode selection. * * @private */ function addEventListeners_() { $(CrosView.IMPORT_ONC_ID).addEventListener('change', handleFileChangeEvent_, false); $(CrosView.PASSCODE_INPUT_ID).addEventListener('change', function(event) { setPasscode_(this.value); }, false); $(CrosView.STORE_DEBUG_LOGS_ID).addEventListener('click', function(event) { $(CrosView.STORE_DEBUG_LOGS_STATUS_ID).innerText = ''; g_browser.storeDebugLogs(); }, false); $(CrosView.DEBUG_WIFI_ID).addEventListener('click', function(event) { setNetworkDebugMode_('wifi'); }, false); $(CrosView.DEBUG_ETHERNET_ID).addEventListener('click', function(event) { setNetworkDebugMode_('ethernet'); }, false); $(CrosView.DEBUG_CELLULAR_ID).addEventListener('click', function(event) { setNetworkDebugMode_('cellular'); }, false); $(CrosView.DEBUG_WIMAX_ID).addEventListener('click', function(event) { setNetworkDebugMode_('wimax'); }, false); $(CrosView.DEBUG_NONE_ID).addEventListener('click', function(event) { setNetworkDebugMode_('none'); }, false); } /** * Reset fileContent and passcode vars. * * @private */ function reset_() { fileContent = undefined; passcode = ''; $(CrosView.PASSCODE_ID).hidden = true; } /** * Enables or disables debug mode for a specified subsystem. * * @private */ function setNetworkDebugMode_(subsystem) { $(CrosView.DEBUG_STATUS_ID).innerText = ''; g_browser.setNetworkDebugMode(subsystem); } /** * @constructor * @extends {DivView} */ function CrosView() { assertFirstConstructorCall(CrosView); // Call superclass's constructor. DivView.call(this, CrosView.MAIN_BOX_ID); g_browser.addCrosONCFileParseObserver(this); g_browser.addStoreDebugLogsObserver(this); g_browser.addSetNetworkDebugModeObserver(this); addEventListeners_(); } CrosView.TAB_ID = 'tab-handle-chromeos'; CrosView.TAB_NAME = 'ChromeOS'; CrosView.TAB_HASH = '#chromeos'; CrosView.MAIN_BOX_ID = 'chromeos-view-tab-content'; CrosView.IMPORT_DIV_ID = 'chromeos-view-import-div'; CrosView.IMPORT_ONC_ID = 'chromeos-view-import-onc'; CrosView.PASSCODE_ID = 'chromeos-view-password-div'; CrosView.PASSCODE_INPUT_ID = 'chromeos-view-onc-password'; CrosView.PARSE_STATUS_ID = 'chromeos-view-parse-status'; CrosView.STORE_DEBUG_LOGS_ID = 'chromeos-view-store-debug-logs'; CrosView.STORE_DEBUG_LOGS_STATUS_ID = 'chromeos-view-store-debug-logs-status'; CrosView.DEBUG_WIFI_ID = 'chromeos-view-network-debugging-wifi'; CrosView.DEBUG_ETHERNET_ID = 'chromeos-view-network-debugging-ethernet'; CrosView.DEBUG_CELLULAR_ID = 'chromeos-view-network-debugging-cellular'; CrosView.DEBUG_WIMAX_ID = 'chromeos-view-network-debugging-wimax'; CrosView.DEBUG_NONE_ID = 'chromeos-view-network-debugging-none'; CrosView.DEBUG_STATUS_ID = 'chromeos-view-network-debugging-status'; cr.addSingletonGetter(CrosView); CrosView.prototype = { // Inherit from DivView. __proto__: DivView.prototype, onONCFileParse: setParseStatus_, onStoreDebugLogs: setStoreDebugLogsStatus_, onSetNetworkDebugMode: setNetworkDebugModeStatus_, }; return CrosView; })();
* Unhide the passcode prompt input field and give it focus. *
apiDiagnostic.ts
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "../../types"; import * as utilities from "../../utilities"; /** * Diagnostic details. */ export class ApiDiagnostic extends pulumi.CustomResource { /** * Get an existing ApiDiagnostic resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, opts?: pulumi.CustomResourceOptions): ApiDiagnostic { return new ApiDiagnostic(name, undefined as any, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure-native:apimanagement/v20191201preview:ApiDiagnostic'; /** * Returns true if the given object is an instance of ApiDiagnostic. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is ApiDiagnostic { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === ApiDiagnostic.__pulumiType; } /** * Specifies for what type of messages sampling settings should not apply. */ public readonly alwaysLog!: pulumi.Output<string | undefined>; /** * Diagnostic settings for incoming/outgoing HTTP messages to the Backend */ public readonly backend!: pulumi.Output<outputs.apimanagement.v20191201preview.PipelineDiagnosticSettingsResponse | undefined>; /** * Diagnostic settings for incoming/outgoing HTTP messages to the Gateway. */ public readonly frontend!: pulumi.Output<outputs.apimanagement.v20191201preview.PipelineDiagnosticSettingsResponse | undefined>; /** * Sets correlation protocol to use for Application Insights diagnostics. */ public readonly httpCorrelationProtocol!: pulumi.Output<string | undefined>; /** * Log the ClientIP. Default is false. */ public readonly logClientIp!: pulumi.Output<boolean | undefined>; /** * Resource Id of a target logger. */ public readonly loggerId!: pulumi.Output<string>; /** * Resource name. */ public /*out*/ readonly name!: pulumi.Output<string>; /** * Sampling settings for Diagnostic. */ public readonly sampling!: pulumi.Output<outputs.apimanagement.v20191201preview.SamplingSettingsResponse | undefined>; /** * Resource type for API Management resource. */ public /*out*/ readonly type!: pulumi.Output<string>; /** * The verbosity level applied to traces emitted by trace policies. */ public readonly verbosity!: pulumi.Output<string | undefined>; /** * Create a ApiDiagnostic resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: ApiDiagnosticArgs, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (!opts.id) { if ((!args || args.apiId === undefined) && !opts.urn) { throw new Error("Missing required property 'apiId'"); } if ((!args || args.loggerId === undefined) && !opts.urn) { throw new Error("Missing required property 'loggerId'"); } if ((!args || args.resourceGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupName'"); } if ((!args || args.serviceName === undefined) && !opts.urn) { throw new Error("Missing required property 'serviceName'"); } inputs["alwaysLog"] = args ? args.alwaysLog : undefined; inputs["apiId"] = args ? args.apiId : undefined; inputs["backend"] = args ? args.backend : undefined; inputs["diagnosticId"] = args ? args.diagnosticId : undefined; inputs["frontend"] = args ? args.frontend : undefined; inputs["httpCorrelationProtocol"] = args ? args.httpCorrelationProtocol : undefined; inputs["logClientIp"] = args ? args.logClientIp : undefined; inputs["loggerId"] = args ? args.loggerId : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined;
inputs["name"] = undefined /*out*/; inputs["type"] = undefined /*out*/; } else { inputs["alwaysLog"] = undefined /*out*/; inputs["backend"] = undefined /*out*/; inputs["frontend"] = undefined /*out*/; inputs["httpCorrelationProtocol"] = undefined /*out*/; inputs["logClientIp"] = undefined /*out*/; inputs["loggerId"] = undefined /*out*/; inputs["name"] = undefined /*out*/; inputs["sampling"] = undefined /*out*/; inputs["type"] = undefined /*out*/; inputs["verbosity"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } const aliasOpts = { aliases: [{ type: "azure-nextgen:apimanagement/v20191201preview:ApiDiagnostic" }, { type: "azure-native:apimanagement:ApiDiagnostic" }, { type: "azure-nextgen:apimanagement:ApiDiagnostic" }, { type: "azure-native:apimanagement/latest:ApiDiagnostic" }, { type: "azure-nextgen:apimanagement/latest:ApiDiagnostic" }, { type: "azure-native:apimanagement/v20170301:ApiDiagnostic" }, { type: "azure-nextgen:apimanagement/v20170301:ApiDiagnostic" }, { type: "azure-native:apimanagement/v20180101:ApiDiagnostic" }, { type: "azure-nextgen:apimanagement/v20180101:ApiDiagnostic" }, { type: "azure-native:apimanagement/v20180601preview:ApiDiagnostic" }, { type: "azure-nextgen:apimanagement/v20180601preview:ApiDiagnostic" }, { type: "azure-native:apimanagement/v20190101:ApiDiagnostic" }, { type: "azure-nextgen:apimanagement/v20190101:ApiDiagnostic" }, { type: "azure-native:apimanagement/v20191201:ApiDiagnostic" }, { type: "azure-nextgen:apimanagement/v20191201:ApiDiagnostic" }, { type: "azure-native:apimanagement/v20200601preview:ApiDiagnostic" }, { type: "azure-nextgen:apimanagement/v20200601preview:ApiDiagnostic" }, { type: "azure-native:apimanagement/v20201201:ApiDiagnostic" }, { type: "azure-nextgen:apimanagement/v20201201:ApiDiagnostic" }] }; opts = pulumi.mergeOptions(opts, aliasOpts); super(ApiDiagnostic.__pulumiType, name, inputs, opts); } } /** * The set of arguments for constructing a ApiDiagnostic resource. */ export interface ApiDiagnosticArgs { /** * Specifies for what type of messages sampling settings should not apply. */ readonly alwaysLog?: pulumi.Input<string | enums.apimanagement.v20191201preview.AlwaysLog>; /** * API identifier. Must be unique in the current API Management service instance. */ readonly apiId: pulumi.Input<string>; /** * Diagnostic settings for incoming/outgoing HTTP messages to the Backend */ readonly backend?: pulumi.Input<inputs.apimanagement.v20191201preview.PipelineDiagnosticSettings>; /** * Diagnostic identifier. Must be unique in the current API Management service instance. */ readonly diagnosticId?: pulumi.Input<string>; /** * Diagnostic settings for incoming/outgoing HTTP messages to the Gateway. */ readonly frontend?: pulumi.Input<inputs.apimanagement.v20191201preview.PipelineDiagnosticSettings>; /** * Sets correlation protocol to use for Application Insights diagnostics. */ readonly httpCorrelationProtocol?: pulumi.Input<string | enums.apimanagement.v20191201preview.HttpCorrelationProtocol>; /** * Log the ClientIP. Default is false. */ readonly logClientIp?: pulumi.Input<boolean>; /** * Resource Id of a target logger. */ readonly loggerId: pulumi.Input<string>; /** * The name of the resource group. */ readonly resourceGroupName: pulumi.Input<string>; /** * Sampling settings for Diagnostic. */ readonly sampling?: pulumi.Input<inputs.apimanagement.v20191201preview.SamplingSettings>; /** * The name of the API Management service. */ readonly serviceName: pulumi.Input<string>; /** * The verbosity level applied to traces emitted by trace policies. */ readonly verbosity?: pulumi.Input<string | enums.apimanagement.v20191201preview.Verbosity>; }
inputs["sampling"] = args ? args.sampling : undefined; inputs["serviceName"] = args ? args.serviceName : undefined; inputs["verbosity"] = args ? args.verbosity : undefined;
input.rs
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. use std::fmt::Write; /// See [`AssociateExternalConnectionInput`](crate::input::AssociateExternalConnectionInput) pub mod associate_external_connection_input { /// A builder for [`AssociateExternalConnectionInput`](crate::input::AssociateExternalConnectionInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, pub(crate) external_connection: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the domain that contains the repository.</p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p>The name of the domain that contains the repository.</p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> /// The name of the repository to which the external connection is added. /// </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p> /// The name of the repository to which the external connection is added. /// </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// <p> /// The name of the external connection to add to the repository. The following values are supported: /// </p> /// <ul> /// <li> /// <p> /// <code>public:npmjs</code> - for the npm public repository. /// </p> /// </li> /// <li> /// <p> /// <code>public:pypi</code> - for the Python Package Index. /// </p> /// </li> /// <li> /// <p> /// <code>public:maven-central</code> - for Maven Central. /// </p> /// </li> /// <li> /// <p> /// <code>public:maven-googleandroid</code> - for the Google Android repository. /// </p> /// </li> /// <li> /// <p> /// <code>public:maven-gradleplugins</code> - for the Gradle plugins repository. /// </p> /// </li> /// <li> /// <p> /// <code>public:maven-commonsware</code> - for the CommonsWare Android repository. /// </p> /// </li> /// </ul> pub fn external_connection(mut self, input: impl Into<std::string::String>) -> Self { self.external_connection = Some(input.into()); self } /// <p> /// The name of the external connection to add to the repository. The following values are supported: /// </p> /// <ul> /// <li> /// <p> /// <code>public:npmjs</code> - for the npm public repository. /// </p> /// </li> /// <li> /// <p> /// <code>public:pypi</code> - for the Python Package Index. /// </p> /// </li> /// <li> /// <p> /// <code>public:maven-central</code> - for Maven Central. /// </p> /// </li> /// <li> /// <p> /// <code>public:maven-googleandroid</code> - for the Google Android repository. /// </p> /// </li> /// <li> /// <p> /// <code>public:maven-gradleplugins</code> - for the Gradle plugins repository. /// </p> /// </li> /// <li> /// <p> /// <code>public:maven-commonsware</code> - for the CommonsWare Android repository. /// </p> /// </li> /// </ul> pub fn set_external_connection( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.external_connection = input; self } /// Consumes the builder and constructs a [`AssociateExternalConnectionInput`](crate::input::AssociateExternalConnectionInput) pub fn build( self, ) -> std::result::Result< crate::input::AssociateExternalConnectionInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::AssociateExternalConnectionInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, external_connection: self.external_connection, }) } } } #[doc(hidden)] pub type AssociateExternalConnectionInputOperationOutputAlias = crate::operation::AssociateExternalConnection; #[doc(hidden)] pub type AssociateExternalConnectionInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl AssociateExternalConnectionInput { /// Consumes the builder and constructs an Operation<[`AssociateExternalConnection`](crate::operation::AssociateExternalConnection)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::AssociateExternalConnection, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::AssociateExternalConnectionInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/repository/external-connection") .expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::AssociateExternalConnectionInput, mut output: &mut String, ) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_1) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_1)); } if let Some(inner_2) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_2), ); } if let Some(inner_3) = &_input.repository { query.push_kv("repository", &aws_smithy_http::query::fmt_string(&inner_3)); } if let Some(inner_4) = &_input.external_connection { query.push_kv( "external-connection", &aws_smithy_http::query::fmt_string(&inner_4), ); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::AssociateExternalConnectionInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::AssociateExternalConnectionInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::AssociateExternalConnection::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "AssociateExternalConnection", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`AssociateExternalConnectionInput`](crate::input::AssociateExternalConnectionInput) pub fn builder() -> crate::input::associate_external_connection_input::Builder { crate::input::associate_external_connection_input::Builder::default() } } /// See [`CopyPackageVersionsInput`](crate::input::CopyPackageVersionsInput) pub mod copy_package_versions_input { /// A builder for [`CopyPackageVersionsInput`](crate::input::CopyPackageVersionsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) source_repository: std::option::Option<std::string::String>, pub(crate) destination_repository: std::option::Option<std::string::String>, pub(crate) format: std::option::Option<crate::model::PackageFormat>, pub(crate) namespace: std::option::Option<std::string::String>, pub(crate) package: std::option::Option<std::string::String>, pub(crate) versions: std::option::Option<std::vec::Vec<std::string::String>>, pub(crate) version_revisions: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, pub(crate) allow_overwrite: std::option::Option<bool>, pub(crate) include_from_upstream: std::option::Option<bool>, } impl Builder { /// <p> /// The name of the domain that contains the source and destination repositories. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain that contains the source and destination repositories. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> /// The name of the repository that contains the package versions to copy. /// </p> pub fn source_repository(mut self, input: impl Into<std::string::String>) -> Self { self.source_repository = Some(input.into()); self } /// <p> /// The name of the repository that contains the package versions to copy. /// </p> pub fn set_source_repository( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.source_repository = input; self } /// <p> /// The name of the repository into which package versions are copied. /// </p> pub fn destination_repository(mut self, input: impl Into<std::string::String>) -> Self { self.destination_repository = Some(input.into()); self } /// <p> /// The name of the repository into which package versions are copied. /// </p> pub fn set_destination_repository( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.destination_repository = input; self } /// <p> /// The format of the package that is copied. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub fn format(mut self, input: crate::model::PackageFormat) -> Self { self.format = Some(input); self } /// <p> /// The format of the package that is copied. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub fn set_format( mut self, input: std::option::Option<crate::model::PackageFormat>, ) -> Self { self.format = input; self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(mut self, input: impl Into<std::string::String>) -> Self { self.namespace = Some(input.into()); self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn set_namespace(mut self, input: std::option::Option<std::string::String>) -> Self { self.namespace = input; self } /// <p> /// The name of the package that is copied. /// </p> pub fn package(mut self, input: impl Into<std::string::String>) -> Self { self.package = Some(input.into()); self } /// <p> /// The name of the package that is copied. /// </p> pub fn set_package(mut self, input: std::option::Option<std::string::String>) -> Self { self.package = input; self } /// Appends an item to `versions`. /// /// To override the contents of this collection use [`set_versions`](Self::set_versions). /// /// <p> /// The versions of the package to copy. /// </p> /// <note> /// <p> /// You must specify <code>versions</code> or <code>versionRevisions</code>. You cannot specify both. /// </p> /// </note> pub fn versions(mut self, input: impl Into<std::string::String>) -> Self { let mut v = self.versions.unwrap_or_default(); v.push(input.into()); self.versions = Some(v); self } /// <p> /// The versions of the package to copy. /// </p> /// <note> /// <p> /// You must specify <code>versions</code> or <code>versionRevisions</code>. You cannot specify both. /// </p> /// </note> pub fn set_versions( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.versions = input; self } /// Adds a key-value pair to `version_revisions`. /// /// To override the contents of this collection use [`set_version_revisions`](Self::set_version_revisions). /// /// <p> /// A list of key-value pairs. The keys are package versions and the values are package version revisions. A <code>CopyPackageVersion</code> operation /// succeeds if the specified versions in the source repository match the specified package version revision. /// </p> /// <note> /// <p> /// You must specify <code>versions</code> or <code>versionRevisions</code>. You cannot specify both. /// </p> /// </note> pub fn version_revisions( mut self, k: impl Into<std::string::String>, v: impl Into<std::string::String>, ) -> Self { let mut hash_map = self.version_revisions.unwrap_or_default(); hash_map.insert(k.into(), v.into()); self.version_revisions = Some(hash_map); self } /// <p> /// A list of key-value pairs. The keys are package versions and the values are package version revisions. A <code>CopyPackageVersion</code> operation /// succeeds if the specified versions in the source repository match the specified package version revision. /// </p> /// <note> /// <p> /// You must specify <code>versions</code> or <code>versionRevisions</code>. You cannot specify both. /// </p> /// </note> pub fn set_version_revisions( mut self, input: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, ) -> Self { self.version_revisions = input; self } /// <p> /// Set to true to overwrite a package version that already exists in the destination repository. /// If set to false and the package version already exists in the destination repository, /// the package version is returned in the <code>failedVersions</code> field of the response with /// an <code>ALREADY_EXISTS</code> error code. /// </p> pub fn allow_overwrite(mut self, input: bool) -> Self { self.allow_overwrite = Some(input); self } /// <p> /// Set to true to overwrite a package version that already exists in the destination repository. /// If set to false and the package version already exists in the destination repository, /// the package version is returned in the <code>failedVersions</code> field of the response with /// an <code>ALREADY_EXISTS</code> error code. /// </p> pub fn set_allow_overwrite(mut self, input: std::option::Option<bool>) -> Self { self.allow_overwrite = input; self } /// <p> Set to true to copy packages from repositories that are upstream from the source /// repository to the destination repository. The default setting is false. For more information, /// see <a href="https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html">Working with /// upstream repositories</a>. </p> pub fn include_from_upstream(mut self, input: bool) -> Self { self.include_from_upstream = Some(input); self } /// <p> Set to true to copy packages from repositories that are upstream from the source /// repository to the destination repository. The default setting is false. For more information, /// see <a href="https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html">Working with /// upstream repositories</a>. </p> pub fn set_include_from_upstream(mut self, input: std::option::Option<bool>) -> Self { self.include_from_upstream = input; self } /// Consumes the builder and constructs a [`CopyPackageVersionsInput`](crate::input::CopyPackageVersionsInput) pub fn build( self, ) -> std::result::Result< crate::input::CopyPackageVersionsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::CopyPackageVersionsInput { domain: self.domain, domain_owner: self.domain_owner, source_repository: self.source_repository, destination_repository: self.destination_repository, format: self.format, namespace: self.namespace, package: self.package, versions: self.versions, version_revisions: self.version_revisions, allow_overwrite: self.allow_overwrite, include_from_upstream: self.include_from_upstream, }) } } } #[doc(hidden)] pub type CopyPackageVersionsInputOperationOutputAlias = crate::operation::CopyPackageVersions; #[doc(hidden)] pub type CopyPackageVersionsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl CopyPackageVersionsInput { /// Consumes the builder and constructs an Operation<[`CopyPackageVersions`](crate::operation::CopyPackageVersions)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::CopyPackageVersions, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::CopyPackageVersionsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/package/versions/copy").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::CopyPackageVersionsInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_5) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_5)); } if let Some(inner_6) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_6), ); } if let Some(inner_7) = &_input.source_repository { query.push_kv( "source-repository", &aws_smithy_http::query::fmt_string(&inner_7), ); } if let Some(inner_8) = &_input.destination_repository { query.push_kv( "destination-repository", &aws_smithy_http::query::fmt_string(&inner_8), ); } if let Some(inner_9) = &_input.format { query.push_kv("format", &aws_smithy_http::query::fmt_string(&inner_9)); } if let Some(inner_10) = &_input.namespace { query.push_kv("namespace", &aws_smithy_http::query::fmt_string(&inner_10)); } if let Some(inner_11) = &_input.package { query.push_kv("package", &aws_smithy_http::query::fmt_string(&inner_11)); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::CopyPackageVersionsInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::CopyPackageVersionsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_copy_package_versions(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::CopyPackageVersions::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "CopyPackageVersions", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`CopyPackageVersionsInput`](crate::input::CopyPackageVersionsInput) pub fn builder() -> crate::input::copy_package_versions_input::Builder { crate::input::copy_package_versions_input::Builder::default() } } /// See [`CreateDomainInput`](crate::input::CreateDomainInput) pub mod create_domain_input { /// A builder for [`CreateDomainInput`](crate::input::CreateDomainInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) encryption_key: std::option::Option<std::string::String>, pub(crate) tags: std::option::Option<std::vec::Vec<crate::model::Tag>>, } impl Builder { /// <p> The name of the domain to create. All domain names in an AWS Region that are in the /// same AWS account must be unique. The domain name is used as the prefix in DNS hostnames. Do /// not use sensitive information in a domain name because it is publicly discoverable. </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> The name of the domain to create. All domain names in an AWS Region that are in the /// same AWS account must be unique. The domain name is used as the prefix in DNS hostnames. Do /// not use sensitive information in a domain name because it is publicly discoverable. </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> The encryption key for the domain. This is used to encrypt content stored in a domain. /// An encryption key can be a key ID, a key Amazon Resource Name (ARN), a key alias, or a key /// alias ARN. To specify an <code>encryptionKey</code>, your IAM role must have /// <code>kms:DescribeKey</code> and <code>kms:CreateGrant</code> permissions on the encryption /// key that is used. For more information, see <a href="https://docs.aws.amazon.com/kms/latest/APIReference/API_DescribeKey.html#API_DescribeKey_RequestSyntax">DescribeKey</a> in the <i>AWS Key Management Service API Reference</i> /// and <a href="https://docs.aws.amazon.com/kms/latest/developerguide/kms-api-permissions-reference.html">AWS KMS API Permissions /// Reference</a> in the <i>AWS Key Management Service Developer Guide</i>. </p> /// <important> /// <p> CodeArtifact supports only symmetric CMKs. Do not associate an asymmetric CMK with your /// domain. For more information, see <a href="https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html">Using symmetric and asymmetric /// keys</a> in the <i>AWS Key Management Service Developer Guide</i>. </p> /// </important> pub fn encryption_key(mut self, input: impl Into<std::string::String>) -> Self { self.encryption_key = Some(input.into()); self } /// <p> The encryption key for the domain. This is used to encrypt content stored in a domain. /// An encryption key can be a key ID, a key Amazon Resource Name (ARN), a key alias, or a key /// alias ARN. To specify an <code>encryptionKey</code>, your IAM role must have /// <code>kms:DescribeKey</code> and <code>kms:CreateGrant</code> permissions on the encryption /// key that is used. For more information, see <a href="https://docs.aws.amazon.com/kms/latest/APIReference/API_DescribeKey.html#API_DescribeKey_RequestSyntax">DescribeKey</a> in the <i>AWS Key Management Service API Reference</i> /// and <a href="https://docs.aws.amazon.com/kms/latest/developerguide/kms-api-permissions-reference.html">AWS KMS API Permissions /// Reference</a> in the <i>AWS Key Management Service Developer Guide</i>. </p> /// <important> /// <p> CodeArtifact supports only symmetric CMKs. Do not associate an asymmetric CMK with your /// domain. For more information, see <a href="https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html">Using symmetric and asymmetric /// keys</a> in the <i>AWS Key Management Service Developer Guide</i>. </p> /// </important> pub fn set_encryption_key( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.encryption_key = input; self } /// Appends an item to `tags`. /// /// To override the contents of this collection use [`set_tags`](Self::set_tags). /// /// <p>One or more tag key-value pairs for the domain.</p> pub fn tags(mut self, input: impl Into<crate::model::Tag>) -> Self { let mut v = self.tags.unwrap_or_default(); v.push(input.into()); self.tags = Some(v); self } /// <p>One or more tag key-value pairs for the domain.</p> pub fn set_tags( mut self, input: std::option::Option<std::vec::Vec<crate::model::Tag>>, ) -> Self { self.tags = input; self } /// Consumes the builder and constructs a [`CreateDomainInput`](crate::input::CreateDomainInput) pub fn build( self, ) -> std::result::Result< crate::input::CreateDomainInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::CreateDomainInput { domain: self.domain, encryption_key: self.encryption_key, tags: self.tags, }) } } } #[doc(hidden)] pub type CreateDomainInputOperationOutputAlias = crate::operation::CreateDomain; #[doc(hidden)] pub type CreateDomainInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl CreateDomainInput { /// Consumes the builder and constructs an Operation<[`CreateDomain`](crate::operation::CreateDomain)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::CreateDomain, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::CreateDomainInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/domain").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::CreateDomainInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_12) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_12)); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::CreateDomainInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::CreateDomainInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_create_domain(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::CreateDomain::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "CreateDomain", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`CreateDomainInput`](crate::input::CreateDomainInput) pub fn builder() -> crate::input::create_domain_input::Builder { crate::input::create_domain_input::Builder::default() } } /// See [`CreateRepositoryInput`](crate::input::CreateRepositoryInput) pub mod create_repository_input { /// A builder for [`CreateRepositoryInput`](crate::input::CreateRepositoryInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, pub(crate) description: std::option::Option<std::string::String>, pub(crate) upstreams: std::option::Option<std::vec::Vec<crate::model::UpstreamRepository>>, pub(crate) tags: std::option::Option<std::vec::Vec<crate::model::Tag>>, } impl Builder { /// <p> /// The name of the domain that contains the created repository. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain that contains the created repository. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> The name of the repository to create. </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p> The name of the repository to create. </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// <p> /// A description of the created repository. /// </p> pub fn description(mut self, input: impl Into<std::string::String>) -> Self { self.description = Some(input.into()); self } /// <p> /// A description of the created repository. /// </p> pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self { self.description = input; self } /// Appends an item to `upstreams`. /// /// To override the contents of this collection use [`set_upstreams`](Self::set_upstreams). /// /// <p> A list of upstream repositories to associate with the repository. The order of the upstream repositories /// in the list determines their priority order when AWS CodeArtifact looks for a requested package version. For more /// information, see <a href="https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html">Working with upstream repositories</a>. </p> pub fn upstreams(mut self, input: impl Into<crate::model::UpstreamRepository>) -> Self { let mut v = self.upstreams.unwrap_or_default(); v.push(input.into()); self.upstreams = Some(v); self } /// <p> A list of upstream repositories to associate with the repository. The order of the upstream repositories /// in the list determines their priority order when AWS CodeArtifact looks for a requested package version. For more /// information, see <a href="https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html">Working with upstream repositories</a>. </p> pub fn set_upstreams( mut self, input: std::option::Option<std::vec::Vec<crate::model::UpstreamRepository>>, ) -> Self { self.upstreams = input; self } /// Appends an item to `tags`. /// /// To override the contents of this collection use [`set_tags`](Self::set_tags). /// /// <p>One or more tag key-value pairs for the repository.</p> pub fn tags(mut self, input: impl Into<crate::model::Tag>) -> Self { let mut v = self.tags.unwrap_or_default(); v.push(input.into()); self.tags = Some(v); self } /// <p>One or more tag key-value pairs for the repository.</p> pub fn set_tags( mut self, input: std::option::Option<std::vec::Vec<crate::model::Tag>>, ) -> Self { self.tags = input; self } /// Consumes the builder and constructs a [`CreateRepositoryInput`](crate::input::CreateRepositoryInput) pub fn build( self, ) -> std::result::Result< crate::input::CreateRepositoryInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::CreateRepositoryInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, description: self.description, upstreams: self.upstreams, tags: self.tags, }) } } } #[doc(hidden)] pub type CreateRepositoryInputOperationOutputAlias = crate::operation::CreateRepository; #[doc(hidden)] pub type CreateRepositoryInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl CreateRepositoryInput { /// Consumes the builder and constructs an Operation<[`CreateRepository`](crate::operation::CreateRepository)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::CreateRepository, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::CreateRepositoryInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/repository").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::CreateRepositoryInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_13) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_13)); } if let Some(inner_14) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_14), ); } if let Some(inner_15) = &_input.repository { query.push_kv("repository", &aws_smithy_http::query::fmt_string(&inner_15)); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::CreateRepositoryInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::CreateRepositoryInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_create_repository(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::CreateRepository::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "CreateRepository", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`CreateRepositoryInput`](crate::input::CreateRepositoryInput) pub fn builder() -> crate::input::create_repository_input::Builder { crate::input::create_repository_input::Builder::default() } } /// See [`DeleteDomainInput`](crate::input::DeleteDomainInput) pub mod delete_domain_input { /// A builder for [`DeleteDomainInput`](crate::input::DeleteDomainInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, } impl Builder { /// <p> /// The name of the domain to delete. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain to delete. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// Consumes the builder and constructs a [`DeleteDomainInput`](crate::input::DeleteDomainInput) pub fn build( self, ) -> std::result::Result< crate::input::DeleteDomainInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DeleteDomainInput { domain: self.domain, domain_owner: self.domain_owner, }) } } } #[doc(hidden)] pub type DeleteDomainInputOperationOutputAlias = crate::operation::DeleteDomain; #[doc(hidden)] pub type DeleteDomainInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DeleteDomainInput { /// Consumes the builder and constructs an Operation<[`DeleteDomain`](crate::operation::DeleteDomain)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::DeleteDomain, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DeleteDomainInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/domain").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::DeleteDomainInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_16) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_16)); } if let Some(inner_17) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_17), ); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DeleteDomainInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DeleteDomainInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::DeleteDomain::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DeleteDomain", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DeleteDomainInput`](crate::input::DeleteDomainInput) pub fn builder() -> crate::input::delete_domain_input::Builder { crate::input::delete_domain_input::Builder::default() } } /// See [`DeleteDomainPermissionsPolicyInput`](crate::input::DeleteDomainPermissionsPolicyInput) pub mod delete_domain_permissions_policy_input { /// A builder for [`DeleteDomainPermissionsPolicyInput`](crate::input::DeleteDomainPermissionsPolicyInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) policy_revision: std::option::Option<std::string::String>, } impl Builder { /// <p> /// The name of the domain associated with the resource policy to be deleted. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain associated with the resource policy to be deleted. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> /// The current revision of the resource policy to be deleted. This revision is used for optimistic locking, which /// prevents others from overwriting your changes to the domain's resource policy. /// </p> pub fn policy_revision(mut self, input: impl Into<std::string::String>) -> Self { self.policy_revision = Some(input.into()); self } /// <p> /// The current revision of the resource policy to be deleted. This revision is used for optimistic locking, which /// prevents others from overwriting your changes to the domain's resource policy. /// </p> pub fn set_policy_revision( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.policy_revision = input; self } /// Consumes the builder and constructs a [`DeleteDomainPermissionsPolicyInput`](crate::input::DeleteDomainPermissionsPolicyInput) pub fn build( self, ) -> std::result::Result< crate::input::DeleteDomainPermissionsPolicyInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DeleteDomainPermissionsPolicyInput { domain: self.domain, domain_owner: self.domain_owner, policy_revision: self.policy_revision, }) } } } #[doc(hidden)] pub type DeleteDomainPermissionsPolicyInputOperationOutputAlias = crate::operation::DeleteDomainPermissionsPolicy; #[doc(hidden)] pub type DeleteDomainPermissionsPolicyInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DeleteDomainPermissionsPolicyInput { /// Consumes the builder and constructs an Operation<[`DeleteDomainPermissionsPolicy`](crate::operation::DeleteDomainPermissionsPolicy)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::DeleteDomainPermissionsPolicy, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DeleteDomainPermissionsPolicyInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/domain/permissions/policy").expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::DeleteDomainPermissionsPolicyInput, mut output: &mut String, ) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_18) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_18)); } if let Some(inner_19) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_19), ); } if let Some(inner_20) = &_input.policy_revision { query.push_kv( "policy-revision", &aws_smithy_http::query::fmt_string(&inner_20), ); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DeleteDomainPermissionsPolicyInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DeleteDomainPermissionsPolicyInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::DeleteDomainPermissionsPolicy::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DeleteDomainPermissionsPolicy", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DeleteDomainPermissionsPolicyInput`](crate::input::DeleteDomainPermissionsPolicyInput) pub fn builder() -> crate::input::delete_domain_permissions_policy_input::Builder { crate::input::delete_domain_permissions_policy_input::Builder::default() } } /// See [`DeletePackageVersionsInput`](crate::input::DeletePackageVersionsInput) pub mod delete_package_versions_input { /// A builder for [`DeletePackageVersionsInput`](crate::input::DeletePackageVersionsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, pub(crate) format: std::option::Option<crate::model::PackageFormat>, pub(crate) namespace: std::option::Option<std::string::String>, pub(crate) package: std::option::Option<std::string::String>, pub(crate) versions: std::option::Option<std::vec::Vec<std::string::String>>, pub(crate) expected_status: std::option::Option<crate::model::PackageVersionStatus>, } impl Builder { /// <p> /// The name of the domain that contains the package to delete. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain that contains the package to delete. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> /// The name of the repository that contains the package versions to delete. /// </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p> /// The name of the repository that contains the package versions to delete. /// </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// <p> /// The format of the package versions to delete. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn format(mut self, input: crate::model::PackageFormat) -> Self { self.format = Some(input); self } /// <p> /// The format of the package versions to delete. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn set_format( mut self, input: std::option::Option<crate::model::PackageFormat>, ) -> Self { self.format = input; self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(mut self, input: impl Into<std::string::String>) -> Self { self.namespace = Some(input.into()); self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn set_namespace(mut self, input: std::option::Option<std::string::String>) -> Self { self.namespace = input; self } /// <p> /// The name of the package with the versions to delete. /// </p> pub fn package(mut self, input: impl Into<std::string::String>) -> Self { self.package = Some(input.into()); self } /// <p> /// The name of the package with the versions to delete. /// </p> pub fn set_package(mut self, input: std::option::Option<std::string::String>) -> Self { self.package = input; self } /// Appends an item to `versions`. /// /// To override the contents of this collection use [`set_versions`](Self::set_versions). /// /// <p> /// An array of strings that specify the versions of the package to delete. /// </p> pub fn versions(mut self, input: impl Into<std::string::String>) -> Self { let mut v = self.versions.unwrap_or_default(); v.push(input.into()); self.versions = Some(v); self } /// <p> /// An array of strings that specify the versions of the package to delete. /// </p> pub fn set_versions( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.versions = input; self } /// <p> /// The expected status of the package version to delete. Valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>Published</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unfinished</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unlisted</code> /// </p> /// </li> /// <li> /// <p> /// <code>Archived</code> /// </p> /// </li> /// <li> /// <p> /// <code>Disposed</code> /// </p> /// </li> /// </ul> pub fn expected_status(mut self, input: crate::model::PackageVersionStatus) -> Self { self.expected_status = Some(input); self } /// <p> /// The expected status of the package version to delete. Valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>Published</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unfinished</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unlisted</code> /// </p> /// </li> /// <li> /// <p> /// <code>Archived</code> /// </p> /// </li> /// <li> /// <p> /// <code>Disposed</code> /// </p> /// </li> /// </ul> pub fn set_expected_status( mut self, input: std::option::Option<crate::model::PackageVersionStatus>, ) -> Self { self.expected_status = input; self } /// Consumes the builder and constructs a [`DeletePackageVersionsInput`](crate::input::DeletePackageVersionsInput) pub fn build( self, ) -> std::result::Result< crate::input::DeletePackageVersionsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DeletePackageVersionsInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, format: self.format, namespace: self.namespace, package: self.package, versions: self.versions, expected_status: self.expected_status, }) } } } #[doc(hidden)] pub type DeletePackageVersionsInputOperationOutputAlias = crate::operation::DeletePackageVersions; #[doc(hidden)] pub type DeletePackageVersionsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DeletePackageVersionsInput { /// Consumes the builder and constructs an Operation<[`DeletePackageVersions`](crate::operation::DeletePackageVersions)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::DeletePackageVersions, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DeletePackageVersionsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/package/versions/delete").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::DeletePackageVersionsInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_21) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_21)); } if let Some(inner_22) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_22), ); } if let Some(inner_23) = &_input.repository { query.push_kv("repository", &aws_smithy_http::query::fmt_string(&inner_23)); } if let Some(inner_24) = &_input.format { query.push_kv("format", &aws_smithy_http::query::fmt_string(&inner_24)); } if let Some(inner_25) = &_input.namespace { query.push_kv("namespace", &aws_smithy_http::query::fmt_string(&inner_25)); } if let Some(inner_26) = &_input.package { query.push_kv("package", &aws_smithy_http::query::fmt_string(&inner_26)); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DeletePackageVersionsInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DeletePackageVersionsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_delete_package_versions( &self, )?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::DeletePackageVersions::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DeletePackageVersions", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DeletePackageVersionsInput`](crate::input::DeletePackageVersionsInput) pub fn builder() -> crate::input::delete_package_versions_input::Builder { crate::input::delete_package_versions_input::Builder::default() } } /// See [`DeleteRepositoryInput`](crate::input::DeleteRepositoryInput) pub mod delete_repository_input { /// A builder for [`DeleteRepositoryInput`](crate::input::DeleteRepositoryInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, } impl Builder { /// <p> /// The name of the domain that contains the repository to delete. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain that contains the repository to delete. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> The name of the repository to delete. </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p> The name of the repository to delete. </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// Consumes the builder and constructs a [`DeleteRepositoryInput`](crate::input::DeleteRepositoryInput) pub fn build( self, ) -> std::result::Result< crate::input::DeleteRepositoryInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DeleteRepositoryInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, }) } } } #[doc(hidden)] pub type DeleteRepositoryInputOperationOutputAlias = crate::operation::DeleteRepository; #[doc(hidden)] pub type DeleteRepositoryInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DeleteRepositoryInput { /// Consumes the builder and constructs an Operation<[`DeleteRepository`](crate::operation::DeleteRepository)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::DeleteRepository, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DeleteRepositoryInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/repository").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::DeleteRepositoryInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_27) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_27)); } if let Some(inner_28) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_28), ); } if let Some(inner_29) = &_input.repository { query.push_kv("repository", &aws_smithy_http::query::fmt_string(&inner_29)); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DeleteRepositoryInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DeleteRepositoryInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::DeleteRepository::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DeleteRepository", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DeleteRepositoryInput`](crate::input::DeleteRepositoryInput) pub fn builder() -> crate::input::delete_repository_input::Builder { crate::input::delete_repository_input::Builder::default() } } /// See [`DeleteRepositoryPermissionsPolicyInput`](crate::input::DeleteRepositoryPermissionsPolicyInput) pub mod delete_repository_permissions_policy_input { /// A builder for [`DeleteRepositoryPermissionsPolicyInput`](crate::input::DeleteRepositoryPermissionsPolicyInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, pub(crate) policy_revision: std::option::Option<std::string::String>, } impl Builder { /// <p> /// The name of the domain that contains the repository associated with the resource policy to be deleted. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain that contains the repository associated with the resource policy to be deleted. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> /// The name of the repository that is associated with the resource policy to be deleted /// </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p> /// The name of the repository that is associated with the resource policy to be deleted /// </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// <p> /// The revision of the repository's resource policy to be deleted. This revision is used for optimistic locking, which /// prevents others from accidentally overwriting your changes to the repository's resource policy. /// </p> pub fn policy_revision(mut self, input: impl Into<std::string::String>) -> Self { self.policy_revision = Some(input.into()); self } /// <p> /// The revision of the repository's resource policy to be deleted. This revision is used for optimistic locking, which /// prevents others from accidentally overwriting your changes to the repository's resource policy. /// </p> pub fn set_policy_revision( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.policy_revision = input; self } /// Consumes the builder and constructs a [`DeleteRepositoryPermissionsPolicyInput`](crate::input::DeleteRepositoryPermissionsPolicyInput) pub fn build( self, ) -> std::result::Result< crate::input::DeleteRepositoryPermissionsPolicyInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DeleteRepositoryPermissionsPolicyInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, policy_revision: self.policy_revision, }) } } } #[doc(hidden)] pub type DeleteRepositoryPermissionsPolicyInputOperationOutputAlias = crate::operation::DeleteRepositoryPermissionsPolicy; #[doc(hidden)] pub type DeleteRepositoryPermissionsPolicyInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DeleteRepositoryPermissionsPolicyInput { /// Consumes the builder and constructs an Operation<[`DeleteRepositoryPermissionsPolicy`](crate::operation::DeleteRepositoryPermissionsPolicy)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::DeleteRepositoryPermissionsPolicy, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DeleteRepositoryPermissionsPolicyInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/repository/permissions/policies") .expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::DeleteRepositoryPermissionsPolicyInput, mut output: &mut String, ) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_30) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_30)); } if let Some(inner_31) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_31), ); } if let Some(inner_32) = &_input.repository { query.push_kv("repository", &aws_smithy_http::query::fmt_string(&inner_32)); } if let Some(inner_33) = &_input.policy_revision { query.push_kv( "policy-revision", &aws_smithy_http::query::fmt_string(&inner_33), ); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DeleteRepositoryPermissionsPolicyInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DeleteRepositoryPermissionsPolicyInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::DeleteRepositoryPermissionsPolicy::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DeleteRepositoryPermissionsPolicy", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DeleteRepositoryPermissionsPolicyInput`](crate::input::DeleteRepositoryPermissionsPolicyInput) pub fn builder() -> crate::input::delete_repository_permissions_policy_input::Builder { crate::input::delete_repository_permissions_policy_input::Builder::default() } } /// See [`DescribeDomainInput`](crate::input::DescribeDomainInput) pub mod describe_domain_input { /// A builder for [`DescribeDomainInput`](crate::input::DescribeDomainInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, } impl Builder { /// <p> /// A string that specifies the name of the requested domain. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// A string that specifies the name of the requested domain. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// Consumes the builder and constructs a [`DescribeDomainInput`](crate::input::DescribeDomainInput) pub fn build( self, ) -> std::result::Result< crate::input::DescribeDomainInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DescribeDomainInput { domain: self.domain, domain_owner: self.domain_owner, }) } } } #[doc(hidden)] pub type DescribeDomainInputOperationOutputAlias = crate::operation::DescribeDomain; #[doc(hidden)] pub type DescribeDomainInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DescribeDomainInput { /// Consumes the builder and constructs an Operation<[`DescribeDomain`](crate::operation::DescribeDomain)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::DescribeDomain, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DescribeDomainInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/domain").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::DescribeDomainInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_34) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_34)); } if let Some(inner_35) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_35), ); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DescribeDomainInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DescribeDomainInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::DescribeDomain::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DescribeDomain", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DescribeDomainInput`](crate::input::DescribeDomainInput) pub fn builder() -> crate::input::describe_domain_input::Builder { crate::input::describe_domain_input::Builder::default() } } /// See [`DescribePackageVersionInput`](crate::input::DescribePackageVersionInput) pub mod describe_package_version_input { /// A builder for [`DescribePackageVersionInput`](crate::input::DescribePackageVersionInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, pub(crate) format: std::option::Option<crate::model::PackageFormat>, pub(crate) namespace: std::option::Option<std::string::String>, pub(crate) package: std::option::Option<std::string::String>, pub(crate) package_version: std::option::Option<std::string::String>, } impl Builder { /// <p> /// The name of the domain that contains the repository that contains the package version. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain that contains the repository that contains the package version. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> The name of the repository that contains the package version. </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p> The name of the repository that contains the package version. </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// <p> /// A format that specifies the type of the requested package version. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn format(mut self, input: crate::model::PackageFormat) -> Self { self.format = Some(input); self } /// <p> /// A format that specifies the type of the requested package version. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn set_format( mut self, input: std::option::Option<crate::model::PackageFormat>, ) -> Self { self.format = input; self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(mut self, input: impl Into<std::string::String>) -> Self { self.namespace = Some(input.into()); self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn set_namespace(mut self, input: std::option::Option<std::string::String>) -> Self { self.namespace = input; self } /// <p> The name of the requested package version. </p> pub fn package(mut self, input: impl Into<std::string::String>) -> Self { self.package = Some(input.into()); self } /// <p> The name of the requested package version. </p> pub fn set_package(mut self, input: std::option::Option<std::string::String>) -> Self { self.package = input; self } /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub fn package_version(mut self, input: impl Into<std::string::String>) -> Self { self.package_version = Some(input.into()); self } /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub fn set_package_version( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.package_version = input; self } /// Consumes the builder and constructs a [`DescribePackageVersionInput`](crate::input::DescribePackageVersionInput) pub fn build( self, ) -> std::result::Result< crate::input::DescribePackageVersionInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DescribePackageVersionInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, format: self.format, namespace: self.namespace, package: self.package, package_version: self.package_version, }) } } } #[doc(hidden)] pub type DescribePackageVersionInputOperationOutputAlias = crate::operation::DescribePackageVersion; #[doc(hidden)] pub type DescribePackageVersionInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DescribePackageVersionInput { /// Consumes the builder and constructs an Operation<[`DescribePackageVersion`](crate::operation::DescribePackageVersion)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::DescribePackageVersion, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DescribePackageVersionInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/package/version").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::DescribePackageVersionInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_36) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_36)); } if let Some(inner_37) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_37), ); } if let Some(inner_38) = &_input.repository { query.push_kv("repository", &aws_smithy_http::query::fmt_string(&inner_38)); } if let Some(inner_39) = &_input.format { query.push_kv("format", &aws_smithy_http::query::fmt_string(&inner_39)); } if let Some(inner_40) = &_input.namespace { query.push_kv("namespace", &aws_smithy_http::query::fmt_string(&inner_40)); } if let Some(inner_41) = &_input.package { query.push_kv("package", &aws_smithy_http::query::fmt_string(&inner_41)); } if let Some(inner_42) = &_input.package_version { query.push_kv("version", &aws_smithy_http::query::fmt_string(&inner_42)); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DescribePackageVersionInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DescribePackageVersionInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::DescribePackageVersion::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DescribePackageVersion", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DescribePackageVersionInput`](crate::input::DescribePackageVersionInput) pub fn builder() -> crate::input::describe_package_version_input::Builder { crate::input::describe_package_version_input::Builder::default() } } /// See [`DescribeRepositoryInput`](crate::input::DescribeRepositoryInput) pub mod describe_repository_input { /// A builder for [`DescribeRepositoryInput`](crate::input::DescribeRepositoryInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, } impl Builder { /// <p> /// The name of the domain that contains the repository to describe. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain that contains the repository to describe. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> /// A string that specifies the name of the requested repository. /// </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p> /// A string that specifies the name of the requested repository. /// </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// Consumes the builder and constructs a [`DescribeRepositoryInput`](crate::input::DescribeRepositoryInput) pub fn build( self, ) -> std::result::Result< crate::input::DescribeRepositoryInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DescribeRepositoryInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, }) } } } #[doc(hidden)] pub type DescribeRepositoryInputOperationOutputAlias = crate::operation::DescribeRepository; #[doc(hidden)] pub type DescribeRepositoryInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DescribeRepositoryInput { /// Consumes the builder and constructs an Operation<[`DescribeRepository`](crate::operation::DescribeRepository)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::DescribeRepository, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DescribeRepositoryInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/repository").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::DescribeRepositoryInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_43) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_43)); } if let Some(inner_44) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_44), ); } if let Some(inner_45) = &_input.repository { query.push_kv("repository", &aws_smithy_http::query::fmt_string(&inner_45)); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DescribeRepositoryInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DescribeRepositoryInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::DescribeRepository::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DescribeRepository", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DescribeRepositoryInput`](crate::input::DescribeRepositoryInput) pub fn builder() -> crate::input::describe_repository_input::Builder { crate::input::describe_repository_input::Builder::default() } } /// See [`DisassociateExternalConnectionInput`](crate::input::DisassociateExternalConnectionInput) pub mod disassociate_external_connection_input { /// A builder for [`DisassociateExternalConnectionInput`](crate::input::DisassociateExternalConnectionInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, pub(crate) external_connection: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the domain that contains the repository from which to remove the external /// repository. </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p>The name of the domain that contains the repository from which to remove the external /// repository. </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p>The name of the repository from which the external connection will be removed. </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p>The name of the repository from which the external connection will be removed. </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// <p>The name of the external connection to be removed from the repository. </p> pub fn external_connection(mut self, input: impl Into<std::string::String>) -> Self { self.external_connection = Some(input.into()); self } /// <p>The name of the external connection to be removed from the repository. </p> pub fn set_external_connection( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.external_connection = input; self } /// Consumes the builder and constructs a [`DisassociateExternalConnectionInput`](crate::input::DisassociateExternalConnectionInput) pub fn build( self, ) -> std::result::Result< crate::input::DisassociateExternalConnectionInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DisassociateExternalConnectionInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, external_connection: self.external_connection, }) } } } #[doc(hidden)] pub type DisassociateExternalConnectionInputOperationOutputAlias = crate::operation::DisassociateExternalConnection; #[doc(hidden)] pub type DisassociateExternalConnectionInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DisassociateExternalConnectionInput { /// Consumes the builder and constructs an Operation<[`DisassociateExternalConnection`](crate::operation::DisassociateExternalConnection)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::DisassociateExternalConnection, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DisassociateExternalConnectionInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/repository/external-connection") .expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::DisassociateExternalConnectionInput, mut output: &mut String, ) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_46) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_46)); } if let Some(inner_47) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_47), ); } if let Some(inner_48) = &_input.repository { query.push_kv("repository", &aws_smithy_http::query::fmt_string(&inner_48)); } if let Some(inner_49) = &_input.external_connection { query.push_kv( "external-connection", &aws_smithy_http::query::fmt_string(&inner_49), ); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DisassociateExternalConnectionInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DisassociateExternalConnectionInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::DisassociateExternalConnection::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DisassociateExternalConnection", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DisassociateExternalConnectionInput`](crate::input::DisassociateExternalConnectionInput) pub fn builder() -> crate::input::disassociate_external_connection_input::Builder { crate::input::disassociate_external_connection_input::Builder::default() } } /// See [`DisposePackageVersionsInput`](crate::input::DisposePackageVersionsInput) pub mod dispose_package_versions_input { /// A builder for [`DisposePackageVersionsInput`](crate::input::DisposePackageVersionsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, pub(crate) format: std::option::Option<crate::model::PackageFormat>, pub(crate) namespace: std::option::Option<std::string::String>, pub(crate) package: std::option::Option<std::string::String>, pub(crate) versions: std::option::Option<std::vec::Vec<std::string::String>>, pub(crate) version_revisions: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, pub(crate) expected_status: std::option::Option<crate::model::PackageVersionStatus>, } impl Builder { /// <p> /// The name of the domain that contains the repository you want to dispose. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain that contains the repository you want to dispose. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> /// The name of the repository that contains the package versions you want to dispose. /// </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p> /// The name of the repository that contains the package versions you want to dispose. /// </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// <p> /// A format that specifies the type of package versions you want to dispose. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn format(mut self, input: crate::model::PackageFormat) -> Self { self.format = Some(input); self } /// <p> /// A format that specifies the type of package versions you want to dispose. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn set_format( mut self, input: std::option::Option<crate::model::PackageFormat>, ) -> Self { self.format = input; self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(mut self, input: impl Into<std::string::String>) -> Self { self.namespace = Some(input.into()); self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn set_namespace(mut self, input: std::option::Option<std::string::String>) -> Self { self.namespace = input; self } /// <p> /// The name of the package with the versions you want to dispose. /// </p> pub fn package(mut self, input: impl Into<std::string::String>) -> Self { self.package = Some(input.into()); self } /// <p> /// The name of the package with the versions you want to dispose. /// </p> pub fn set_package(mut self, input: std::option::Option<std::string::String>) -> Self { self.package = input; self } /// Appends an item to `versions`. /// /// To override the contents of this collection use [`set_versions`](Self::set_versions). /// /// <p> /// The versions of the package you want to dispose. /// </p> pub fn versions(mut self, input: impl Into<std::string::String>) -> Self { let mut v = self.versions.unwrap_or_default(); v.push(input.into()); self.versions = Some(v); self } /// <p> /// The versions of the package you want to dispose. /// </p> pub fn set_versions( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.versions = input; self } /// Adds a key-value pair to `version_revisions`. /// /// To override the contents of this collection use [`set_version_revisions`](Self::set_version_revisions). /// /// <p> /// The revisions of the package versions you want to dispose. /// </p> pub fn version_revisions( mut self, k: impl Into<std::string::String>, v: impl Into<std::string::String>, ) -> Self { let mut hash_map = self.version_revisions.unwrap_or_default(); hash_map.insert(k.into(), v.into()); self.version_revisions = Some(hash_map); self } /// <p> /// The revisions of the package versions you want to dispose. /// </p> pub fn set_version_revisions( mut self, input: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, ) -> Self { self.version_revisions = input; self } /// <p> /// The expected status of the package version to dispose. Valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>Published</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unfinished</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unlisted</code> /// </p> /// </li> /// <li> /// <p> /// <code>Archived</code> /// </p> /// </li> /// <li> /// <p> /// <code>Disposed</code> /// </p> /// </li> /// </ul> pub fn expected_status(mut self, input: crate::model::PackageVersionStatus) -> Self { self.expected_status = Some(input); self } /// <p> /// The expected status of the package version to dispose. Valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>Published</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unfinished</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unlisted</code> /// </p> /// </li> /// <li> /// <p> /// <code>Archived</code> /// </p> /// </li> /// <li> /// <p> /// <code>Disposed</code> /// </p> /// </li> /// </ul> pub fn set_expected_status( mut self, input: std::option::Option<crate::model::PackageVersionStatus>, ) -> Self { self.expected_status = input; self } /// Consumes the builder and constructs a [`DisposePackageVersionsInput`](crate::input::DisposePackageVersionsInput) pub fn build( self, ) -> std::result::Result< crate::input::DisposePackageVersionsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DisposePackageVersionsInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, format: self.format, namespace: self.namespace, package: self.package, versions: self.versions, version_revisions: self.version_revisions, expected_status: self.expected_status, }) } } } #[doc(hidden)] pub type DisposePackageVersionsInputOperationOutputAlias = crate::operation::DisposePackageVersions; #[doc(hidden)] pub type DisposePackageVersionsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DisposePackageVersionsInput { /// Consumes the builder and constructs an Operation<[`DisposePackageVersions`](crate::operation::DisposePackageVersions)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::DisposePackageVersions, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DisposePackageVersionsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/package/versions/dispose").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::DisposePackageVersionsInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_50) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_50)); } if let Some(inner_51) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_51), ); } if let Some(inner_52) = &_input.repository { query.push_kv("repository", &aws_smithy_http::query::fmt_string(&inner_52)); } if let Some(inner_53) = &_input.format { query.push_kv("format", &aws_smithy_http::query::fmt_string(&inner_53)); } if let Some(inner_54) = &_input.namespace { query.push_kv("namespace", &aws_smithy_http::query::fmt_string(&inner_54)); } if let Some(inner_55) = &_input.package { query.push_kv("package", &aws_smithy_http::query::fmt_string(&inner_55)); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DisposePackageVersionsInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DisposePackageVersionsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_dispose_package_versions( &self, )?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::DisposePackageVersions::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DisposePackageVersions", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DisposePackageVersionsInput`](crate::input::DisposePackageVersionsInput) pub fn builder() -> crate::input::dispose_package_versions_input::Builder { crate::input::dispose_package_versions_input::Builder::default() } } /// See [`GetAuthorizationTokenInput`](crate::input::GetAuthorizationTokenInput) pub mod get_authorization_token_input { /// A builder for [`GetAuthorizationTokenInput`](crate::input::GetAuthorizationTokenInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) duration_seconds: std::option::Option<i64>, } impl Builder { /// <p> /// The name of the domain that is in scope for the generated authorization token. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain that is in scope for the generated authorization token. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p>The time, in seconds, that the generated authorization token is valid. Valid values are /// <code>0</code> and any number between <code>900</code> (15 minutes) and <code>43200</code> (12 hours). /// A value of <code>0</code> will set the expiration of the authorization token to the same expiration of /// the user's role's temporary credentials.</p> pub fn duration_seconds(mut self, input: i64) -> Self { self.duration_seconds = Some(input); self } /// <p>The time, in seconds, that the generated authorization token is valid. Valid values are /// <code>0</code> and any number between <code>900</code> (15 minutes) and <code>43200</code> (12 hours). /// A value of <code>0</code> will set the expiration of the authorization token to the same expiration of /// the user's role's temporary credentials.</p> pub fn set_duration_seconds(mut self, input: std::option::Option<i64>) -> Self { self.duration_seconds = input; self } /// Consumes the builder and constructs a [`GetAuthorizationTokenInput`](crate::input::GetAuthorizationTokenInput) pub fn build( self, ) -> std::result::Result< crate::input::GetAuthorizationTokenInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetAuthorizationTokenInput { domain: self.domain, domain_owner: self.domain_owner, duration_seconds: self.duration_seconds, }) } } } #[doc(hidden)] pub type GetAuthorizationTokenInputOperationOutputAlias = crate::operation::GetAuthorizationToken; #[doc(hidden)] pub type GetAuthorizationTokenInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetAuthorizationTokenInput { /// Consumes the builder and constructs an Operation<[`GetAuthorizationToken`](crate::operation::GetAuthorizationToken)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::GetAuthorizationToken, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetAuthorizationTokenInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/authorization-token").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::GetAuthorizationTokenInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_56) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_56)); } if let Some(inner_57) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_57), ); } if let Some(inner_58) = &_input.duration_seconds { query.push_kv( "duration", &aws_smithy_types::primitive::Encoder::from(*inner_58).encode(), ); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetAuthorizationTokenInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetAuthorizationTokenInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::GetAuthorizationToken::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetAuthorizationToken", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetAuthorizationTokenInput`](crate::input::GetAuthorizationTokenInput) pub fn builder() -> crate::input::get_authorization_token_input::Builder { crate::input::get_authorization_token_input::Builder::default() } } /// See [`GetDomainPermissionsPolicyInput`](crate::input::GetDomainPermissionsPolicyInput) pub mod get_domain_permissions_policy_input { /// A builder for [`GetDomainPermissionsPolicyInput`](crate::input::GetDomainPermissionsPolicyInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, } impl Builder { /// <p> /// The name of the domain to which the resource policy is attached. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain to which the resource policy is attached. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// Consumes the builder and constructs a [`GetDomainPermissionsPolicyInput`](crate::input::GetDomainPermissionsPolicyInput) pub fn build( self, ) -> std::result::Result< crate::input::GetDomainPermissionsPolicyInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetDomainPermissionsPolicyInput { domain: self.domain, domain_owner: self.domain_owner, }) } } } #[doc(hidden)] pub type GetDomainPermissionsPolicyInputOperationOutputAlias = crate::operation::GetDomainPermissionsPolicy; #[doc(hidden)] pub type GetDomainPermissionsPolicyInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetDomainPermissionsPolicyInput { /// Consumes the builder and constructs an Operation<[`GetDomainPermissionsPolicy`](crate::operation::GetDomainPermissionsPolicy)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::GetDomainPermissionsPolicy, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetDomainPermissionsPolicyInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/domain/permissions/policy").expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::GetDomainPermissionsPolicyInput, mut output: &mut String, ) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_59) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_59)); } if let Some(inner_60) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_60), ); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetDomainPermissionsPolicyInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetDomainPermissionsPolicyInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::GetDomainPermissionsPolicy::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetDomainPermissionsPolicy", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetDomainPermissionsPolicyInput`](crate::input::GetDomainPermissionsPolicyInput) pub fn builder() -> crate::input::get_domain_permissions_policy_input::Builder { crate::input::get_domain_permissions_policy_input::Builder::default() } } /// See [`GetPackageVersionAssetInput`](crate::input::GetPackageVersionAssetInput) pub mod get_package_version_asset_input { /// A builder for [`GetPackageVersionAssetInput`](crate::input::GetPackageVersionAssetInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, pub(crate) format: std::option::Option<crate::model::PackageFormat>, pub(crate) namespace: std::option::Option<std::string::String>, pub(crate) package: std::option::Option<std::string::String>, pub(crate) package_version: std::option::Option<std::string::String>, pub(crate) asset: std::option::Option<std::string::String>, pub(crate) package_version_revision: std::option::Option<std::string::String>, } impl Builder { /// <p> /// The name of the domain that contains the repository that contains the package version with the requested asset. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain that contains the repository that contains the package version with the requested asset. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> /// The repository that contains the package version with the requested asset. /// </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p> /// The repository that contains the package version with the requested asset. /// </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// <p> /// A format that specifies the type of the package version with the requested asset file. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn format(mut self, input: crate::model::PackageFormat) -> Self { self.format = Some(input); self } /// <p> /// A format that specifies the type of the package version with the requested asset file. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn set_format( mut self, input: std::option::Option<crate::model::PackageFormat>, ) -> Self { self.format = input; self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(mut self, input: impl Into<std::string::String>) -> Self { self.namespace = Some(input.into()); self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn set_namespace(mut self, input: std::option::Option<std::string::String>) -> Self { self.namespace = input; self } /// <p> /// The name of the package that contains the requested asset. /// </p> pub fn package(mut self, input: impl Into<std::string::String>) -> Self { self.package = Some(input.into()); self } /// <p> /// The name of the package that contains the requested asset. /// </p> pub fn set_package(mut self, input: std::option::Option<std::string::String>) -> Self { self.package = input; self } /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub fn package_version(mut self, input: impl Into<std::string::String>) -> Self { self.package_version = Some(input.into()); self } /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub fn set_package_version( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.package_version = input; self } /// <p> /// The name of the requested asset. /// </p> pub fn asset(mut self, input: impl Into<std::string::String>) -> Self { self.asset = Some(input.into()); self } /// <p> /// The name of the requested asset. /// </p> pub fn set_asset(mut self, input: std::option::Option<std::string::String>) -> Self { self.asset = input; self } /// <p> /// The name of the package version revision that contains the requested asset. /// </p> pub fn package_version_revision(mut self, input: impl Into<std::string::String>) -> Self { self.package_version_revision = Some(input.into()); self } /// <p> /// The name of the package version revision that contains the requested asset. /// </p> pub fn set_package_version_revision( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.package_version_revision = input; self } /// Consumes the builder and constructs a [`GetPackageVersionAssetInput`](crate::input::GetPackageVersionAssetInput) pub fn build( self, ) -> std::result::Result< crate::input::GetPackageVersionAssetInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetPackageVersionAssetInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, format: self.format, namespace: self.namespace, package: self.package, package_version: self.package_version, asset: self.asset, package_version_revision: self.package_version_revision, }) } } } #[doc(hidden)] pub type GetPackageVersionAssetInputOperationOutputAlias = crate::operation::GetPackageVersionAsset; #[doc(hidden)] pub type GetPackageVersionAssetInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetPackageVersionAssetInput { /// Consumes the builder and constructs an Operation<[`GetPackageVersionAsset`](crate::operation::GetPackageVersionAsset)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::GetPackageVersionAsset, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetPackageVersionAssetInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/package/version/asset").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::GetPackageVersionAssetInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_61) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_61)); } if let Some(inner_62) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_62), ); } if let Some(inner_63) = &_input.repository { query.push_kv("repository", &aws_smithy_http::query::fmt_string(&inner_63)); } if let Some(inner_64) = &_input.format { query.push_kv("format", &aws_smithy_http::query::fmt_string(&inner_64)); } if let Some(inner_65) = &_input.namespace { query.push_kv("namespace", &aws_smithy_http::query::fmt_string(&inner_65)); } if let Some(inner_66) = &_input.package { query.push_kv("package", &aws_smithy_http::query::fmt_string(&inner_66)); } if let Some(inner_67) = &_input.package_version { query.push_kv("version", &aws_smithy_http::query::fmt_string(&inner_67)); } if let Some(inner_68) = &_input.asset { query.push_kv("asset", &aws_smithy_http::query::fmt_string(&inner_68)); } if let Some(inner_69) = &_input.package_version_revision { query.push_kv("revision", &aws_smithy_http::query::fmt_string(&inner_69)); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetPackageVersionAssetInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetPackageVersionAssetInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::GetPackageVersionAsset::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetPackageVersionAsset", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetPackageVersionAssetInput`](crate::input::GetPackageVersionAssetInput) pub fn builder() -> crate::input::get_package_version_asset_input::Builder { crate::input::get_package_version_asset_input::Builder::default() } } /// See [`GetPackageVersionReadmeInput`](crate::input::GetPackageVersionReadmeInput) pub mod get_package_version_readme_input { /// A builder for [`GetPackageVersionReadmeInput`](crate::input::GetPackageVersionReadmeInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, pub(crate) format: std::option::Option<crate::model::PackageFormat>, pub(crate) namespace: std::option::Option<std::string::String>, pub(crate) package: std::option::Option<std::string::String>, pub(crate) package_version: std::option::Option<std::string::String>, } impl Builder { /// <p> /// The name of the domain that contains the repository that contains the package version with the requested readme file. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain that contains the repository that contains the package version with the requested readme file. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> /// The repository that contains the package with the requested readme file. /// </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p> /// The repository that contains the package with the requested readme file. /// </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// <p> /// A format that specifies the type of the package version with the requested readme file. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn format(mut self, input: crate::model::PackageFormat) -> Self { self.format = Some(input); self } /// <p> /// A format that specifies the type of the package version with the requested readme file. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn set_format( mut self, input: std::option::Option<crate::model::PackageFormat>, ) -> Self { self.format = input; self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(mut self, input: impl Into<std::string::String>) -> Self { self.namespace = Some(input.into()); self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn set_namespace(mut self, input: std::option::Option<std::string::String>) -> Self { self.namespace = input; self } /// <p> /// The name of the package version that contains the requested readme file. /// </p> pub fn package(mut self, input: impl Into<std::string::String>) -> Self { self.package = Some(input.into()); self } /// <p> /// The name of the package version that contains the requested readme file. /// </p> pub fn set_package(mut self, input: std::option::Option<std::string::String>) -> Self { self.package = input; self } /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub fn package_version(mut self, input: impl Into<std::string::String>) -> Self { self.package_version = Some(input.into()); self } /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub fn set_package_version( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.package_version = input; self } /// Consumes the builder and constructs a [`GetPackageVersionReadmeInput`](crate::input::GetPackageVersionReadmeInput) pub fn build( self, ) -> std::result::Result< crate::input::GetPackageVersionReadmeInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetPackageVersionReadmeInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, format: self.format, namespace: self.namespace, package: self.package, package_version: self.package_version, }) } } } #[doc(hidden)] pub type GetPackageVersionReadmeInputOperationOutputAlias = crate::operation::GetPackageVersionReadme; #[doc(hidden)] pub type GetPackageVersionReadmeInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetPackageVersionReadmeInput { /// Consumes the builder and constructs an Operation<[`GetPackageVersionReadme`](crate::operation::GetPackageVersionReadme)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::GetPackageVersionReadme, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetPackageVersionReadmeInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/package/version/readme").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::GetPackageVersionReadmeInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_70) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_70)); } if let Some(inner_71) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_71), ); } if let Some(inner_72) = &_input.repository { query.push_kv("repository", &aws_smithy_http::query::fmt_string(&inner_72)); } if let Some(inner_73) = &_input.format { query.push_kv("format", &aws_smithy_http::query::fmt_string(&inner_73)); } if let Some(inner_74) = &_input.namespace { query.push_kv("namespace", &aws_smithy_http::query::fmt_string(&inner_74)); } if let Some(inner_75) = &_input.package { query.push_kv("package", &aws_smithy_http::query::fmt_string(&inner_75)); } if let Some(inner_76) = &_input.package_version { query.push_kv("version", &aws_smithy_http::query::fmt_string(&inner_76)); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetPackageVersionReadmeInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetPackageVersionReadmeInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::GetPackageVersionReadme::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetPackageVersionReadme", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetPackageVersionReadmeInput`](crate::input::GetPackageVersionReadmeInput) pub fn builder() -> crate::input::get_package_version_readme_input::Builder { crate::input::get_package_version_readme_input::Builder::default() } } /// See [`GetRepositoryEndpointInput`](crate::input::GetRepositoryEndpointInput) pub mod get_repository_endpoint_input { /// A builder for [`GetRepositoryEndpointInput`](crate::input::GetRepositoryEndpointInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, pub(crate) format: std::option::Option<crate::model::PackageFormat>, } impl Builder { /// <p> /// The name of the domain that contains the repository. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain that contains the repository. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain that contains the repository. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain that contains the repository. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> /// The name of the repository. /// </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p> /// The name of the repository. /// </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// <p> /// Returns which endpoint of a repository to return. A repository has one endpoint for each /// package format: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn format(mut self, input: crate::model::PackageFormat) -> Self { self.format = Some(input); self } /// <p> /// Returns which endpoint of a repository to return. A repository has one endpoint for each /// package format: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn set_format( mut self, input: std::option::Option<crate::model::PackageFormat>, ) -> Self { self.format = input; self } /// Consumes the builder and constructs a [`GetRepositoryEndpointInput`](crate::input::GetRepositoryEndpointInput) pub fn build( self, ) -> std::result::Result< crate::input::GetRepositoryEndpointInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetRepositoryEndpointInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, format: self.format, }) } } } #[doc(hidden)] pub type GetRepositoryEndpointInputOperationOutputAlias = crate::operation::GetRepositoryEndpoint; #[doc(hidden)] pub type GetRepositoryEndpointInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetRepositoryEndpointInput { /// Consumes the builder and constructs an Operation<[`GetRepositoryEndpoint`](crate::operation::GetRepositoryEndpoint)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::GetRepositoryEndpoint, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetRepositoryEndpointInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/repository/endpoint").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::GetRepositoryEndpointInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_77) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_77)); } if let Some(inner_78) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_78), ); } if let Some(inner_79) = &_input.repository { query.push_kv("repository", &aws_smithy_http::query::fmt_string(&inner_79)); } if let Some(inner_80) = &_input.format { query.push_kv("format", &aws_smithy_http::query::fmt_string(&inner_80)); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetRepositoryEndpointInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetRepositoryEndpointInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::GetRepositoryEndpoint::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetRepositoryEndpoint", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetRepositoryEndpointInput`](crate::input::GetRepositoryEndpointInput) pub fn builder() -> crate::input::get_repository_endpoint_input::Builder { crate::input::get_repository_endpoint_input::Builder::default() } } /// See [`GetRepositoryPermissionsPolicyInput`](crate::input::GetRepositoryPermissionsPolicyInput) pub mod get_repository_permissions_policy_input { /// A builder for [`GetRepositoryPermissionsPolicyInput`](crate::input::GetRepositoryPermissionsPolicyInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, } impl Builder { /// <p> /// The name of the domain containing the repository whose associated resource policy is to be retrieved. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain containing the repository whose associated resource policy is to be retrieved. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> /// The name of the repository whose associated resource policy is to be retrieved. /// </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p> /// The name of the repository whose associated resource policy is to be retrieved. /// </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// Consumes the builder and constructs a [`GetRepositoryPermissionsPolicyInput`](crate::input::GetRepositoryPermissionsPolicyInput) pub fn build( self, ) -> std::result::Result< crate::input::GetRepositoryPermissionsPolicyInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetRepositoryPermissionsPolicyInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, }) } } } #[doc(hidden)] pub type GetRepositoryPermissionsPolicyInputOperationOutputAlias = crate::operation::GetRepositoryPermissionsPolicy; #[doc(hidden)] pub type GetRepositoryPermissionsPolicyInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetRepositoryPermissionsPolicyInput { /// Consumes the builder and constructs an Operation<[`GetRepositoryPermissionsPolicy`](crate::operation::GetRepositoryPermissionsPolicy)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::GetRepositoryPermissionsPolicy, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetRepositoryPermissionsPolicyInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/repository/permissions/policy").expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::GetRepositoryPermissionsPolicyInput, mut output: &mut String, ) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_81) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_81)); } if let Some(inner_82) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_82), ); } if let Some(inner_83) = &_input.repository { query.push_kv("repository", &aws_smithy_http::query::fmt_string(&inner_83)); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetRepositoryPermissionsPolicyInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetRepositoryPermissionsPolicyInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::GetRepositoryPermissionsPolicy::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetRepositoryPermissionsPolicy", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetRepositoryPermissionsPolicyInput`](crate::input::GetRepositoryPermissionsPolicyInput) pub fn builder() -> crate::input::get_repository_permissions_policy_input::Builder { crate::input::get_repository_permissions_policy_input::Builder::default() } } /// See [`ListDomainsInput`](crate::input::ListDomainsInput) pub mod list_domains_input { /// A builder for [`ListDomainsInput`](crate::input::ListDomainsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) max_results: std::option::Option<i32>, pub(crate) next_token: std::option::Option<std::string::String>, } impl Builder { /// <p> /// The maximum number of results to return per page. /// </p> pub fn max_results(mut self, input: i32) -> Self { self.max_results = Some(input); self } /// <p> /// The maximum number of results to return per page. /// </p> pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self { self.max_results = input; self } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.next_token = input; self } /// Consumes the builder and constructs a [`ListDomainsInput`](crate::input::ListDomainsInput) pub fn build( self, ) -> std::result::Result< crate::input::ListDomainsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::ListDomainsInput { max_results: self.max_results, next_token: self.next_token, }) } } } #[doc(hidden)] pub type ListDomainsInputOperationOutputAlias = crate::operation::ListDomains; #[doc(hidden)] pub type ListDomainsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListDomainsInput { /// Consumes the builder and constructs an Operation<[`ListDomains`](crate::operation::ListDomains)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::ListDomains, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListDomainsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/domains").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::ListDomainsInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListDomainsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_list_domains(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::ListDomains::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "ListDomains", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListDomainsInput`](crate::input::ListDomainsInput) pub fn builder() -> crate::input::list_domains_input::Builder { crate::input::list_domains_input::Builder::default() } } /// See [`ListPackagesInput`](crate::input::ListPackagesInput) pub mod list_packages_input { /// A builder for [`ListPackagesInput`](crate::input::ListPackagesInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, pub(crate) format: std::option::Option<crate::model::PackageFormat>, pub(crate) namespace: std::option::Option<std::string::String>, pub(crate) package_prefix: std::option::Option<std::string::String>, pub(crate) max_results: std::option::Option<i32>, pub(crate) next_token: std::option::Option<std::string::String>, } impl Builder { /// <p> /// The name of the domain that contains the repository that contains the requested list of packages. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain that contains the repository that contains the requested list of packages. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> /// The name of the repository from which packages are to be listed. /// </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p> /// The name of the repository from which packages are to be listed. /// </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// <p> /// The format of the packages. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub fn format(mut self, input: crate::model::PackageFormat) -> Self { self.format = Some(input); self } /// <p> /// The format of the packages. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub fn set_format( mut self, input: std::option::Option<crate::model::PackageFormat>, ) -> Self { self.format = input; self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(mut self, input: impl Into<std::string::String>) -> Self { self.namespace = Some(input.into()); self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn set_namespace(mut self, input: std::option::Option<std::string::String>) -> Self { self.namespace = input; self } /// <p> /// A prefix used to filter returned packages. Only packages with names that start with /// <code>packagePrefix</code> are returned. /// </p> pub fn package_prefix(mut self, input: impl Into<std::string::String>) -> Self { self.package_prefix = Some(input.into()); self } /// <p> /// A prefix used to filter returned packages. Only packages with names that start with /// <code>packagePrefix</code> are returned. /// </p> pub fn set_package_prefix( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.package_prefix = input; self } /// <p> /// The maximum number of results to return per page. /// </p> pub fn max_results(mut self, input: i32) -> Self { self.max_results = Some(input); self } /// <p> /// The maximum number of results to return per page. /// </p> pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self { self.max_results = input; self } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.next_token = input; self } /// Consumes the builder and constructs a [`ListPackagesInput`](crate::input::ListPackagesInput) pub fn build( self, ) -> std::result::Result< crate::input::ListPackagesInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::ListPackagesInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, format: self.format, namespace: self.namespace, package_prefix: self.package_prefix, max_results: self.max_results, next_token: self.next_token, }) } } } #[doc(hidden)] pub type ListPackagesInputOperationOutputAlias = crate::operation::ListPackages; #[doc(hidden)] pub type ListPackagesInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListPackagesInput { /// Consumes the builder and constructs an Operation<[`ListPackages`](crate::operation::ListPackages)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::ListPackages, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListPackagesInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/packages").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::ListPackagesInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_84) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_84)); } if let Some(inner_85) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_85), ); } if let Some(inner_86) = &_input.repository { query.push_kv("repository", &aws_smithy_http::query::fmt_string(&inner_86)); } if let Some(inner_87) = &_input.format { query.push_kv("format", &aws_smithy_http::query::fmt_string(&inner_87)); } if let Some(inner_88) = &_input.namespace { query.push_kv("namespace", &aws_smithy_http::query::fmt_string(&inner_88)); } if let Some(inner_89) = &_input.package_prefix { query.push_kv( "package-prefix", &aws_smithy_http::query::fmt_string(&inner_89), ); } if let Some(inner_90) = &_input.max_results { query.push_kv( "max-results", &aws_smithy_types::primitive::Encoder::from(*inner_90).encode(), ); } if let Some(inner_91) = &_input.next_token { query.push_kv("next-token", &aws_smithy_http::query::fmt_string(&inner_91)); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::ListPackagesInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListPackagesInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::ListPackages::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "ListPackages", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListPackagesInput`](crate::input::ListPackagesInput) pub fn builder() -> crate::input::list_packages_input::Builder { crate::input::list_packages_input::Builder::default() } } /// See [`ListPackageVersionAssetsInput`](crate::input::ListPackageVersionAssetsInput) pub mod list_package_version_assets_input { /// A builder for [`ListPackageVersionAssetsInput`](crate::input::ListPackageVersionAssetsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, pub(crate) format: std::option::Option<crate::model::PackageFormat>, pub(crate) namespace: std::option::Option<std::string::String>, pub(crate) package: std::option::Option<std::string::String>, pub(crate) package_version: std::option::Option<std::string::String>, pub(crate) max_results: std::option::Option<i32>, pub(crate) next_token: std::option::Option<std::string::String>, } impl Builder { /// <p> /// The name of the domain that contains the repository associated with the package version assets. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain that contains the repository associated with the package version assets. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> /// The name of the repository that contains the package that contains the returned package version assets. /// </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p> /// The name of the repository that contains the package that contains the returned package version assets. /// </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// <p> /// The format of the package that contains the returned package version assets. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub fn format(mut self, input: crate::model::PackageFormat) -> Self { self.format = Some(input); self } /// <p> /// The format of the package that contains the returned package version assets. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub fn set_format( mut self, input: std::option::Option<crate::model::PackageFormat>, ) -> Self { self.format = input; self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(mut self, input: impl Into<std::string::String>) -> Self { self.namespace = Some(input.into()); self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn set_namespace(mut self, input: std::option::Option<std::string::String>) -> Self { self.namespace = input; self } /// <p> /// The name of the package that contains the returned package version assets. /// </p> pub fn package(mut self, input: impl Into<std::string::String>) -> Self { self.package = Some(input.into()); self } /// <p> /// The name of the package that contains the returned package version assets. /// </p> pub fn set_package(mut self, input: std::option::Option<std::string::String>) -> Self { self.package = input; self } /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub fn package_version(mut self, input: impl Into<std::string::String>) -> Self { self.package_version = Some(input.into()); self } /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub fn set_package_version( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.package_version = input; self } /// <p> /// The maximum number of results to return per page. /// </p> pub fn max_results(mut self, input: i32) -> Self { self.max_results = Some(input); self } /// <p> /// The maximum number of results to return per page. /// </p> pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self { self.max_results = input; self } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.next_token = input; self } /// Consumes the builder and constructs a [`ListPackageVersionAssetsInput`](crate::input::ListPackageVersionAssetsInput) pub fn build( self, ) -> std::result::Result< crate::input::ListPackageVersionAssetsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::ListPackageVersionAssetsInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, format: self.format, namespace: self.namespace, package: self.package, package_version: self.package_version, max_results: self.max_results, next_token: self.next_token, }) } } } #[doc(hidden)] pub type ListPackageVersionAssetsInputOperationOutputAlias = crate::operation::ListPackageVersionAssets; #[doc(hidden)] pub type ListPackageVersionAssetsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListPackageVersionAssetsInput { /// Consumes the builder and constructs an Operation<[`ListPackageVersionAssets`](crate::operation::ListPackageVersionAssets)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::ListPackageVersionAssets, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListPackageVersionAssetsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/package/version/assets").expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::ListPackageVersionAssetsInput, mut output: &mut String, ) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_92) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_92)); } if let Some(inner_93) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_93), ); } if let Some(inner_94) = &_input.repository { query.push_kv("repository", &aws_smithy_http::query::fmt_string(&inner_94)); } if let Some(inner_95) = &_input.format { query.push_kv("format", &aws_smithy_http::query::fmt_string(&inner_95)); } if let Some(inner_96) = &_input.namespace { query.push_kv("namespace", &aws_smithy_http::query::fmt_string(&inner_96)); } if let Some(inner_97) = &_input.package { query.push_kv("package", &aws_smithy_http::query::fmt_string(&inner_97)); } if let Some(inner_98) = &_input.package_version { query.push_kv("version", &aws_smithy_http::query::fmt_string(&inner_98)); } if let Some(inner_99) = &_input.max_results { query.push_kv( "max-results", &aws_smithy_types::primitive::Encoder::from(*inner_99).encode(), ); } if let Some(inner_100) = &_input.next_token { query.push_kv( "next-token", &aws_smithy_http::query::fmt_string(&inner_100), ); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::ListPackageVersionAssetsInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListPackageVersionAssetsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::ListPackageVersionAssets::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "ListPackageVersionAssets", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListPackageVersionAssetsInput`](crate::input::ListPackageVersionAssetsInput) pub fn builder() -> crate::input::list_package_version_assets_input::Builder { crate::input::list_package_version_assets_input::Builder::default() } } /// See [`ListPackageVersionDependenciesInput`](crate::input::ListPackageVersionDependenciesInput) pub mod list_package_version_dependencies_input { /// A builder for [`ListPackageVersionDependenciesInput`](crate::input::ListPackageVersionDependenciesInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, pub(crate) format: std::option::Option<crate::model::PackageFormat>, pub(crate) namespace: std::option::Option<std::string::String>, pub(crate) package: std::option::Option<std::string::String>, pub(crate) package_version: std::option::Option<std::string::String>, pub(crate) next_token: std::option::Option<std::string::String>, } impl Builder { /// <p> /// The name of the domain that contains the repository that contains the requested package version dependencies. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain that contains the repository that contains the requested package version dependencies. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> /// The name of the repository that contains the requested package version. /// </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p> /// The name of the repository that contains the requested package version. /// </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// <p> /// The format of the package with the requested dependencies. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub fn format(mut self, input: crate::model::PackageFormat) -> Self { self.format = Some(input); self } /// <p> /// The format of the package with the requested dependencies. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub fn set_format( mut self, input: std::option::Option<crate::model::PackageFormat>, ) -> Self { self.format = input; self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(mut self, input: impl Into<std::string::String>) -> Self { self.namespace = Some(input.into()); self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn set_namespace(mut self, input: std::option::Option<std::string::String>) -> Self { self.namespace = input; self } /// <p> /// The name of the package versions' package. /// </p> pub fn package(mut self, input: impl Into<std::string::String>) -> Self { self.package = Some(input.into()); self } /// <p> /// The name of the package versions' package. /// </p> pub fn set_package(mut self, input: std::option::Option<std::string::String>) -> Self { self.package = input; self } /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub fn package_version(mut self, input: impl Into<std::string::String>) -> Self { self.package_version = Some(input.into()); self } /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub fn set_package_version( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.package_version = input; self } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.next_token = input; self } /// Consumes the builder and constructs a [`ListPackageVersionDependenciesInput`](crate::input::ListPackageVersionDependenciesInput) pub fn build( self, ) -> std::result::Result< crate::input::ListPackageVersionDependenciesInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::ListPackageVersionDependenciesInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, format: self.format, namespace: self.namespace, package: self.package, package_version: self.package_version, next_token: self.next_token, }) } } } #[doc(hidden)] pub type ListPackageVersionDependenciesInputOperationOutputAlias = crate::operation::ListPackageVersionDependencies; #[doc(hidden)] pub type ListPackageVersionDependenciesInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListPackageVersionDependenciesInput { /// Consumes the builder and constructs an Operation<[`ListPackageVersionDependencies`](crate::operation::ListPackageVersionDependencies)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::ListPackageVersionDependencies, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListPackageVersionDependenciesInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/package/version/dependencies").expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::ListPackageVersionDependenciesInput, mut output: &mut String, ) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_101) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_101)); } if let Some(inner_102) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_102), ); } if let Some(inner_103) = &_input.repository { query.push_kv( "repository", &aws_smithy_http::query::fmt_string(&inner_103), ); } if let Some(inner_104) = &_input.format { query.push_kv("format", &aws_smithy_http::query::fmt_string(&inner_104)); } if let Some(inner_105) = &_input.namespace { query.push_kv("namespace", &aws_smithy_http::query::fmt_string(&inner_105)); } if let Some(inner_106) = &_input.package { query.push_kv("package", &aws_smithy_http::query::fmt_string(&inner_106)); } if let Some(inner_107) = &_input.package_version { query.push_kv("version", &aws_smithy_http::query::fmt_string(&inner_107)); } if let Some(inner_108) = &_input.next_token { query.push_kv( "next-token", &aws_smithy_http::query::fmt_string(&inner_108), ); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::ListPackageVersionDependenciesInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListPackageVersionDependenciesInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::ListPackageVersionDependencies::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "ListPackageVersionDependencies", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListPackageVersionDependenciesInput`](crate::input::ListPackageVersionDependenciesInput) pub fn builder() -> crate::input::list_package_version_dependencies_input::Builder { crate::input::list_package_version_dependencies_input::Builder::default() } } /// See [`ListPackageVersionsInput`](crate::input::ListPackageVersionsInput) pub mod list_package_versions_input { /// A builder for [`ListPackageVersionsInput`](crate::input::ListPackageVersionsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, pub(crate) format: std::option::Option<crate::model::PackageFormat>, pub(crate) namespace: std::option::Option<std::string::String>, pub(crate) package: std::option::Option<std::string::String>, pub(crate) status: std::option::Option<crate::model::PackageVersionStatus>, pub(crate) sort_by: std::option::Option<crate::model::PackageVersionSortType>, pub(crate) max_results: std::option::Option<i32>, pub(crate) next_token: std::option::Option<std::string::String>, } impl Builder { /// <p> /// The name of the domain that contains the repository that contains the returned package versions. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain that contains the repository that contains the returned package versions. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> /// The name of the repository that contains the package. /// </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p> /// The name of the repository that contains the package. /// </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// <p> /// The format of the returned packages. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub fn format(mut self, input: crate::model::PackageFormat) -> Self { self.format = Some(input); self } /// <p> /// The format of the returned packages. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub fn set_format( mut self, input: std::option::Option<crate::model::PackageFormat>, ) -> Self { self.format = input; self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(mut self, input: impl Into<std::string::String>) -> Self { self.namespace = Some(input.into()); self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn set_namespace(mut self, input: std::option::Option<std::string::String>) -> Self { self.namespace = input; self } /// <p> /// The name of the package for which you want to return a list of package versions. /// </p> pub fn package(mut self, input: impl Into<std::string::String>) -> Self { self.package = Some(input.into()); self } /// <p> /// The name of the package for which you want to return a list of package versions. /// </p> pub fn set_package(mut self, input: std::option::Option<std::string::String>) -> Self { self.package = input; self } /// <p> /// A string that specifies the status of the package versions to include in the returned list. It can be one of the following: /// </p> /// <ul> /// <li> /// <p> /// <code>Published</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unfinished</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unlisted</code> /// </p> /// </li> /// <li> /// <p> /// <code>Archived</code> /// </p> /// </li> /// <li> /// <p> /// <code>Disposed</code> /// </p> /// </li> /// </ul> pub fn status(mut self, input: crate::model::PackageVersionStatus) -> Self { self.status = Some(input); self } /// <p> /// A string that specifies the status of the package versions to include in the returned list. It can be one of the following: /// </p> /// <ul> /// <li> /// <p> /// <code>Published</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unfinished</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unlisted</code> /// </p> /// </li> /// <li> /// <p> /// <code>Archived</code> /// </p> /// </li> /// <li> /// <p> /// <code>Disposed</code> /// </p> /// </li> /// </ul> pub fn set_status( mut self, input: std::option::Option<crate::model::PackageVersionStatus>, ) -> Self { self.status = input; self } /// <p> /// How to sort the returned list of package versions. /// </p> pub fn sort_by(mut self, input: crate::model::PackageVersionSortType) -> Self { self.sort_by = Some(input); self } /// <p> /// How to sort the returned list of package versions. /// </p> pub fn set_sort_by( mut self, input: std::option::Option<crate::model::PackageVersionSortType>, ) -> Self { self.sort_by = input; self } /// <p> /// The maximum number of results to return per page. /// </p> pub fn max_results(mut self, input: i32) -> Self { self.max_results = Some(input); self } /// <p> /// The maximum number of results to return per page. /// </p> pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self { self.max_results = input; self } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.next_token = input; self } /// Consumes the builder and constructs a [`ListPackageVersionsInput`](crate::input::ListPackageVersionsInput) pub fn build( self, ) -> std::result::Result< crate::input::ListPackageVersionsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::ListPackageVersionsInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, format: self.format, namespace: self.namespace, package: self.package, status: self.status, sort_by: self.sort_by, max_results: self.max_results, next_token: self.next_token, }) } } } #[doc(hidden)] pub type ListPackageVersionsInputOperationOutputAlias = crate::operation::ListPackageVersions; #[doc(hidden)] pub type ListPackageVersionsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListPackageVersionsInput { /// Consumes the builder and constructs an Operation<[`ListPackageVersions`](crate::operation::ListPackageVersions)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::ListPackageVersions, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListPackageVersionsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/package/versions").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::ListPackageVersionsInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_109) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_109)); } if let Some(inner_110) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_110), ); } if let Some(inner_111) = &_input.repository { query.push_kv( "repository", &aws_smithy_http::query::fmt_string(&inner_111), ); } if let Some(inner_112) = &_input.format { query.push_kv("format", &aws_smithy_http::query::fmt_string(&inner_112)); } if let Some(inner_113) = &_input.namespace { query.push_kv("namespace", &aws_smithy_http::query::fmt_string(&inner_113)); } if let Some(inner_114) = &_input.package { query.push_kv("package", &aws_smithy_http::query::fmt_string(&inner_114)); } if let Some(inner_115) = &_input.status { query.push_kv("status", &aws_smithy_http::query::fmt_string(&inner_115)); } if let Some(inner_116) = &_input.sort_by { query.push_kv("sortBy", &aws_smithy_http::query::fmt_string(&inner_116)); } if let Some(inner_117) = &_input.max_results { query.push_kv( "max-results", &aws_smithy_types::primitive::Encoder::from(*inner_117).encode(), ); } if let Some(inner_118) = &_input.next_token { query.push_kv( "next-token", &aws_smithy_http::query::fmt_string(&inner_118), ); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::ListPackageVersionsInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListPackageVersionsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::ListPackageVersions::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "ListPackageVersions", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListPackageVersionsInput`](crate::input::ListPackageVersionsInput) pub fn builder() -> crate::input::list_package_versions_input::Builder { crate::input::list_package_versions_input::Builder::default() } } /// See [`ListRepositoriesInput`](crate::input::ListRepositoriesInput) pub mod list_repositories_input { /// A builder for [`ListRepositoriesInput`](crate::input::ListRepositoriesInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) repository_prefix: std::option::Option<std::string::String>, pub(crate) max_results: std::option::Option<i32>, pub(crate) next_token: std::option::Option<std::string::String>, } impl Builder { /// <p> A prefix used to filter returned repositories. Only repositories with names that start /// with <code>repositoryPrefix</code> are returned.</p> pub fn repository_prefix(mut self, input: impl Into<std::string::String>) -> Self { self.repository_prefix = Some(input.into()); self } /// <p> A prefix used to filter returned repositories. Only repositories with names that start /// with <code>repositoryPrefix</code> are returned.</p> pub fn set_repository_prefix( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.repository_prefix = input; self } /// <p> /// The maximum number of results to return per page. /// </p> pub fn max_results(mut self, input: i32) -> Self { self.max_results = Some(input); self } /// <p> /// The maximum number of results to return per page. /// </p> pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self { self.max_results = input; self } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.next_token = input; self } /// Consumes the builder and constructs a [`ListRepositoriesInput`](crate::input::ListRepositoriesInput) pub fn build( self, ) -> std::result::Result< crate::input::ListRepositoriesInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::ListRepositoriesInput { repository_prefix: self.repository_prefix, max_results: self.max_results, next_token: self.next_token, }) } } } #[doc(hidden)] pub type ListRepositoriesInputOperationOutputAlias = crate::operation::ListRepositories; #[doc(hidden)] pub type ListRepositoriesInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListRepositoriesInput { /// Consumes the builder and constructs an Operation<[`ListRepositories`](crate::operation::ListRepositories)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::ListRepositories, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListRepositoriesInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/repositories").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::ListRepositoriesInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_119) = &_input.repository_prefix { query.push_kv( "repository-prefix", &aws_smithy_http::query::fmt_string(&inner_119), ); } if let Some(inner_120) = &_input.max_results { query.push_kv( "max-results", &aws_smithy_types::primitive::Encoder::from(*inner_120).encode(), ); } if let Some(inner_121) = &_input.next_token { query.push_kv( "next-token", &aws_smithy_http::query::fmt_string(&inner_121), ); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::ListRepositoriesInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListRepositoriesInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::ListRepositories::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "ListRepositories", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListRepositoriesInput`](crate::input::ListRepositoriesInput) pub fn builder() -> crate::input::list_repositories_input::Builder { crate::input::list_repositories_input::Builder::default() } } /// See [`ListRepositoriesInDomainInput`](crate::input::ListRepositoriesInDomainInput) pub mod list_repositories_in_domain_input { /// A builder for [`ListRepositoriesInDomainInput`](crate::input::ListRepositoriesInDomainInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) administrator_account: std::option::Option<std::string::String>, pub(crate) repository_prefix: std::option::Option<std::string::String>, pub(crate) max_results: std::option::Option<i32>, pub(crate) next_token: std::option::Option<std::string::String>, } impl Builder { /// <p> /// The name of the domain that contains the returned list of repositories. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain that contains the returned list of repositories. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> /// Filter the list of repositories to only include those that are managed by the AWS account ID. /// </p> pub fn administrator_account(mut self, input: impl Into<std::string::String>) -> Self { self.administrator_account = Some(input.into()); self } /// <p> /// Filter the list of repositories to only include those that are managed by the AWS account ID. /// </p> pub fn set_administrator_account( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.administrator_account = input; self } /// <p> /// A prefix used to filter returned repositories. Only repositories with names that start with /// <code>repositoryPrefix</code> are returned. /// </p> pub fn repository_prefix(mut self, input: impl Into<std::string::String>) -> Self { self.repository_prefix = Some(input.into()); self } /// <p> /// A prefix used to filter returned repositories. Only repositories with names that start with /// <code>repositoryPrefix</code> are returned. /// </p> pub fn set_repository_prefix( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.repository_prefix = input; self } /// <p> /// The maximum number of results to return per page. /// </p> pub fn max_results(mut self, input: i32) -> Self { self.max_results = Some(input); self } /// <p> /// The maximum number of results to return per page. /// </p> pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self { self.max_results = input; self } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.next_token = input; self } /// Consumes the builder and constructs a [`ListRepositoriesInDomainInput`](crate::input::ListRepositoriesInDomainInput) pub fn build( self, ) -> std::result::Result< crate::input::ListRepositoriesInDomainInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::ListRepositoriesInDomainInput { domain: self.domain, domain_owner: self.domain_owner, administrator_account: self.administrator_account, repository_prefix: self.repository_prefix, max_results: self.max_results, next_token: self.next_token, }) } } } #[doc(hidden)] pub type ListRepositoriesInDomainInputOperationOutputAlias = crate::operation::ListRepositoriesInDomain; #[doc(hidden)] pub type ListRepositoriesInDomainInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListRepositoriesInDomainInput { /// Consumes the builder and constructs an Operation<[`ListRepositoriesInDomain`](crate::operation::ListRepositoriesInDomain)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::ListRepositoriesInDomain, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListRepositoriesInDomainInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/domain/repositories").expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::ListRepositoriesInDomainInput, mut output: &mut String, ) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_122) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_122)); } if let Some(inner_123) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_123), ); } if let Some(inner_124) = &_input.administrator_account { query.push_kv( "administrator-account", &aws_smithy_http::query::fmt_string(&inner_124), ); } if let Some(inner_125) = &_input.repository_prefix { query.push_kv( "repository-prefix", &aws_smithy_http::query::fmt_string(&inner_125), ); } if let Some(inner_126) = &_input.max_results { query.push_kv( "max-results", &aws_smithy_types::primitive::Encoder::from(*inner_126).encode(), ); } if let Some(inner_127) = &_input.next_token { query.push_kv( "next-token", &aws_smithy_http::query::fmt_string(&inner_127), ); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::ListRepositoriesInDomainInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListRepositoriesInDomainInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::ListRepositoriesInDomain::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "ListRepositoriesInDomain", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListRepositoriesInDomainInput`](crate::input::ListRepositoriesInDomainInput) pub fn builder() -> crate::input::list_repositories_in_domain_input::Builder { crate::input::list_repositories_in_domain_input::Builder::default() } } /// See [`ListTagsForResourceInput`](crate::input::ListTagsForResourceInput) pub mod list_tags_for_resource_input { /// A builder for [`ListTagsForResourceInput`](crate::input::ListTagsForResourceInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) resource_arn: std::option::Option<std::string::String>, } impl Builder { /// <p>The Amazon Resource Name (ARN) of the resource to get tags for.</p> pub fn resource_arn(mut self, input: impl Into<std::string::String>) -> Self { self.resource_arn = Some(input.into()); self } /// <p>The Amazon Resource Name (ARN) of the resource to get tags for.</p> pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.resource_arn = input; self } /// Consumes the builder and constructs a [`ListTagsForResourceInput`](crate::input::ListTagsForResourceInput) pub fn build( self, ) -> std::result::Result< crate::input::ListTagsForResourceInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::ListTagsForResourceInput { resource_arn: self.resource_arn, }) } } } #[doc(hidden)] pub type ListTagsForResourceInputOperationOutputAlias = crate::operation::ListTagsForResource; #[doc(hidden)] pub type ListTagsForResourceInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListTagsForResourceInput { /// Consumes the builder and constructs an Operation<[`ListTagsForResource`](crate::operation::ListTagsForResource)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::ListTagsForResource, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListTagsForResourceInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/tags").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::ListTagsForResourceInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_128) = &_input.resource_arn { query.push_kv( "resourceArn", &aws_smithy_http::query::fmt_string(&inner_128), ); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::ListTagsForResourceInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListTagsForResourceInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::ListTagsForResource::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "ListTagsForResource", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListTagsForResourceInput`](crate::input::ListTagsForResourceInput) pub fn builder() -> crate::input::list_tags_for_resource_input::Builder { crate::input::list_tags_for_resource_input::Builder::default() } } /// See [`PutDomainPermissionsPolicyInput`](crate::input::PutDomainPermissionsPolicyInput) pub mod put_domain_permissions_policy_input { /// A builder for [`PutDomainPermissionsPolicyInput`](crate::input::PutDomainPermissionsPolicyInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) policy_revision: std::option::Option<std::string::String>, pub(crate) policy_document: std::option::Option<std::string::String>, } impl Builder { /// <p> /// The name of the domain on which to set the resource policy. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain on which to set the resource policy. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> /// The current revision of the resource policy to be set. This revision is used for optimistic locking, which /// prevents others from overwriting your changes to the domain's resource policy. /// </p> pub fn policy_revision(mut self, input: impl Into<std::string::String>) -> Self { self.policy_revision = Some(input.into()); self } /// <p> /// The current revision of the resource policy to be set. This revision is used for optimistic locking, which /// prevents others from overwriting your changes to the domain's resource policy. /// </p> pub fn set_policy_revision( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.policy_revision = input; self } /// <p> A valid displayable JSON Aspen policy string to be set as the access control resource /// policy on the provided domain. </p> pub fn policy_document(mut self, input: impl Into<std::string::String>) -> Self { self.policy_document = Some(input.into()); self } /// <p> A valid displayable JSON Aspen policy string to be set as the access control resource /// policy on the provided domain. </p> pub fn set_policy_document( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.policy_document = input; self } /// Consumes the builder and constructs a [`PutDomainPermissionsPolicyInput`](crate::input::PutDomainPermissionsPolicyInput) pub fn build( self, ) -> std::result::Result< crate::input::PutDomainPermissionsPolicyInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::PutDomainPermissionsPolicyInput { domain: self.domain, domain_owner: self.domain_owner, policy_revision: self.policy_revision, policy_document: self.policy_document, }) } } } #[doc(hidden)] pub type PutDomainPermissionsPolicyInputOperationOutputAlias = crate::operation::PutDomainPermissionsPolicy; #[doc(hidden)] pub type PutDomainPermissionsPolicyInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutDomainPermissionsPolicyInput { /// Consumes the builder and constructs an Operation<[`PutDomainPermissionsPolicy`](crate::operation::PutDomainPermissionsPolicy)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::PutDomainPermissionsPolicy, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutDomainPermissionsPolicyInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/domain/permissions/policy").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutDomainPermissionsPolicyInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; Ok(builder.method("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutDomainPermissionsPolicyInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_domain_permissions_policy(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::PutDomainPermissionsPolicy::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutDomainPermissionsPolicy", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutDomainPermissionsPolicyInput`](crate::input::PutDomainPermissionsPolicyInput) pub fn builder() -> crate::input::put_domain_permissions_policy_input::Builder { crate::input::put_domain_permissions_policy_input::Builder::default() } } /// See [`PutRepositoryPermissionsPolicyInput`](crate::input::PutRepositoryPermissionsPolicyInput) pub mod put_repository_permissions_policy_input { /// A builder for [`PutRepositoryPermissionsPolicyInput`](crate::input::PutRepositoryPermissionsPolicyInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, pub(crate) policy_revision: std::option::Option<std::string::String>, pub(crate) policy_document: std::option::Option<std::string::String>, } impl Builder { /// <p> /// The name of the domain containing the repository to set the resource policy on. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain containing the repository to set the resource policy on. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> The name of the repository to set the resource policy on. </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p> The name of the repository to set the resource policy on. </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// <p> /// Sets the revision of the resource policy that specifies permissions to access the repository. /// This revision is used for optimistic locking, which prevents others from overwriting your /// changes to the repository's resource policy. /// </p> pub fn policy_revision(mut self, input: impl Into<std::string::String>) -> Self { self.policy_revision = Some(input.into()); self } /// <p> /// Sets the revision of the resource policy that specifies permissions to access the repository. /// This revision is used for optimistic locking, which prevents others from overwriting your /// changes to the repository's resource policy. /// </p> pub fn set_policy_revision( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.policy_revision = input; self } /// <p> A valid displayable JSON Aspen policy string to be set as the access control resource /// policy on the provided repository. </p> pub fn policy_document(mut self, input: impl Into<std::string::String>) -> Self { self.policy_document = Some(input.into()); self } /// <p> A valid displayable JSON Aspen policy string to be set as the access control resource /// policy on the provided repository. </p> pub fn set_policy_document( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.policy_document = input; self } /// Consumes the builder and constructs a [`PutRepositoryPermissionsPolicyInput`](crate::input::PutRepositoryPermissionsPolicyInput) pub fn build( self, ) -> std::result::Result< crate::input::PutRepositoryPermissionsPolicyInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::PutRepositoryPermissionsPolicyInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, policy_revision: self.policy_revision, policy_document: self.policy_document, }) } } } #[doc(hidden)] pub type PutRepositoryPermissionsPolicyInputOperationOutputAlias = crate::operation::PutRepositoryPermissionsPolicy; #[doc(hidden)] pub type PutRepositoryPermissionsPolicyInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutRepositoryPermissionsPolicyInput { /// Consumes the builder and constructs an Operation<[`PutRepositoryPermissionsPolicy`](crate::operation::PutRepositoryPermissionsPolicy)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::PutRepositoryPermissionsPolicy, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutRepositoryPermissionsPolicyInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/repository/permissions/policy").expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::PutRepositoryPermissionsPolicyInput, mut output: &mut String, ) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_129) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_129)); } if let Some(inner_130) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_130), ); } if let Some(inner_131) = &_input.repository { query.push_kv( "repository", &aws_smithy_http::query::fmt_string(&inner_131), ); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutRepositoryPermissionsPolicyInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutRepositoryPermissionsPolicyInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_repository_permissions_policy(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::PutRepositoryPermissionsPolicy::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutRepositoryPermissionsPolicy", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutRepositoryPermissionsPolicyInput`](crate::input::PutRepositoryPermissionsPolicyInput) pub fn builder() -> crate::input::put_repository_permissions_policy_input::Builder { crate::input::put_repository_permissions_policy_input::Builder::default() } } /// See [`TagResourceInput`](crate::input::TagResourceInput) pub mod tag_resource_input { /// A builder for [`TagResourceInput`](crate::input::TagResourceInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) resource_arn: std::option::Option<std::string::String>, pub(crate) tags: std::option::Option<std::vec::Vec<crate::model::Tag>>, } impl Builder { /// <p>The Amazon Resource Name (ARN) of the resource that you want to add or update tags for.</p> pub fn resource_arn(mut self, input: impl Into<std::string::String>) -> Self { self.resource_arn = Some(input.into()); self } /// <p>The Amazon Resource Name (ARN) of the resource that you want to add or update tags for.</p> pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.resource_arn = input; self } /// Appends an item to `tags`. /// /// To override the contents of this collection use [`set_tags`](Self::set_tags). /// /// <p>The tags you want to modify or add to the resource.</p> pub fn tags(mut self, input: impl Into<crate::model::Tag>) -> Self { let mut v = self.tags.unwrap_or_default(); v.push(input.into()); self.tags = Some(v); self } /// <p>The tags you want to modify or add to the resource.</p> pub fn set_tags( mut self, input: std::option::Option<std::vec::Vec<crate::model::Tag>>, ) -> Self { self.tags = input; self } /// Consumes the builder and constructs a [`TagResourceInput`](crate::input::TagResourceInput) pub fn build( self, ) -> std::result::Result< crate::input::TagResourceInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::TagResourceInput { resource_arn: self.resource_arn, tags: self.tags, }) } } } #[doc(hidden)] pub type TagResourceInputOperationOutputAlias = crate::operation::TagResource; #[doc(hidden)] pub type TagResourceInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl TagResourceInput { /// Consumes the builder and constructs an Operation<[`TagResource`](crate::operation::TagResource)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::TagResource, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::TagResourceInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/tag").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::TagResourceInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_132) = &_input.resource_arn { query.push_kv( "resourceArn", &aws_smithy_http::query::fmt_string(&inner_132), ); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::TagResourceInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::TagResourceInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_tag_resource(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::TagResource::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "TagResource", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`TagResourceInput`](crate::input::TagResourceInput) pub fn builder() -> crate::input::tag_resource_input::Builder { crate::input::tag_resource_input::Builder::default() } } /// See [`UntagResourceInput`](crate::input::UntagResourceInput) pub mod untag_resource_input { /// A builder for [`UntagResourceInput`](crate::input::UntagResourceInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) resource_arn: std::option::Option<std::string::String>, pub(crate) tag_keys: std::option::Option<std::vec::Vec<std::string::String>>, } impl Builder { /// <p>The Amazon Resource Name (ARN) of the resource that you want to remove tags from.</p> pub fn resource_arn(mut self, input: impl Into<std::string::String>) -> Self { self.resource_arn = Some(input.into()); self } /// <p>The Amazon Resource Name (ARN) of the resource that you want to remove tags from.</p> pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.resource_arn = input; self } /// Appends an item to `tag_keys`. /// /// To override the contents of this collection use [`set_tag_keys`](Self::set_tag_keys). /// /// <p>The tag key for each tag that you want to remove from the resource.</p> pub fn tag_keys(mut self, input: impl Into<std::string::String>) -> Self { let mut v = self.tag_keys.unwrap_or_default(); v.push(input.into()); self.tag_keys = Some(v); self } /// <p>The tag key for each tag that you want to remove from the resource.</p> pub fn set_tag_keys( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.tag_keys = input; self } /// Consumes the builder and constructs a [`UntagResourceInput`](crate::input::UntagResourceInput) pub fn build( self, ) -> std::result::Result< crate::input::UntagResourceInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::UntagResourceInput { resource_arn: self.resource_arn, tag_keys: self.tag_keys, }) } } } #[doc(hidden)] pub type UntagResourceInputOperationOutputAlias = crate::operation::UntagResource; #[doc(hidden)] pub type UntagResourceInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl UntagResourceInput { /// Consumes the builder and constructs an Operation<[`UntagResource`](crate::operation::UntagResource)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::UntagResource, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::UntagResourceInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/untag").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::UntagResourceInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_133) = &_input.resource_arn { query.push_kv( "resourceArn", &aws_smithy_http::query::fmt_string(&inner_133), ); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::UntagResourceInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::UntagResourceInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_untag_resource(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::UntagResource::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "UntagResource", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`UntagResourceInput`](crate::input::UntagResourceInput) pub fn builder() -> crate::input::untag_resource_input::Builder { crate::input::untag_resource_input::Builder::default() } } /// See [`UpdatePackageVersionsStatusInput`](crate::input::UpdatePackageVersionsStatusInput) pub mod update_package_versions_status_input { /// A builder for [`UpdatePackageVersionsStatusInput`](crate::input::UpdatePackageVersionsStatusInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, pub(crate) format: std::option::Option<crate::model::PackageFormat>, pub(crate) namespace: std::option::Option<std::string::String>, pub(crate) package: std::option::Option<std::string::String>, pub(crate) versions: std::option::Option<std::vec::Vec<std::string::String>>, pub(crate) version_revisions: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, pub(crate) expected_status: std::option::Option<crate::model::PackageVersionStatus>, pub(crate) target_status: std::option::Option<crate::model::PackageVersionStatus>, } impl Builder { /// <p> /// The name of the domain that contains the repository that contains the package versions with a status to be updated. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain that contains the repository that contains the package versions with a status to be updated. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> /// The repository that contains the package versions with the status you want to update. /// </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p> /// The repository that contains the package versions with the status you want to update. /// </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// <p> /// A format that specifies the type of the package with the statuses to update. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn format(mut self, input: crate::model::PackageFormat) -> Self { self.format = Some(input); self } /// <p> /// A format that specifies the type of the package with the statuses to update. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn set_format( mut self, input: std::option::Option<crate::model::PackageFormat>, ) -> Self { self.format = input; self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(mut self, input: impl Into<std::string::String>) -> Self { self.namespace = Some(input.into()); self } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn set_namespace(mut self, input: std::option::Option<std::string::String>) -> Self { self.namespace = input; self } /// <p> /// The name of the package with the version statuses to update. /// </p> pub fn package(mut self, input: impl Into<std::string::String>) -> Self { self.package = Some(input.into()); self } /// <p> /// The name of the package with the version statuses to update. /// </p> pub fn set_package(mut self, input: std::option::Option<std::string::String>) -> Self { self.package = input; self } /// Appends an item to `versions`. /// /// To override the contents of this collection use [`set_versions`](Self::set_versions). /// /// <p> /// An array of strings that specify the versions of the package with the statuses to update. /// </p> pub fn versions(mut self, input: impl Into<std::string::String>) -> Self { let mut v = self.versions.unwrap_or_default(); v.push(input.into()); self.versions = Some(v); self } /// <p> /// An array of strings that specify the versions of the package with the statuses to update. /// </p> pub fn set_versions( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.versions = input; self } /// Adds a key-value pair to `version_revisions`. /// /// To override the contents of this collection use [`set_version_revisions`](Self::set_version_revisions). /// /// <p> A map of package versions and package version revisions. The map <code>key</code> is the /// package version (for example, <code>3.5.2</code>), and the map <code>value</code> is the /// package version revision. </p> pub fn version_revisions( mut self, k: impl Into<std::string::String>, v: impl Into<std::string::String>, ) -> Self { let mut hash_map = self.version_revisions.unwrap_or_default(); hash_map.insert(k.into(), v.into()); self.version_revisions = Some(hash_map); self } /// <p> A map of package versions and package version revisions. The map <code>key</code> is the /// package version (for example, <code>3.5.2</code>), and the map <code>value</code> is the /// package version revision. </p> pub fn set_version_revisions( mut self, input: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, ) -> Self { self.version_revisions = input; self } /// <p> The package version’s expected status before it is updated. If /// <code>expectedStatus</code> is provided, the package version's status is updated only if its /// status at the time <code>UpdatePackageVersionsStatus</code> is called matches /// <code>expectedStatus</code>. </p> pub fn expected_status(mut self, input: crate::model::PackageVersionStatus) -> Self { self.expected_status = Some(input); self } /// <p> The package version’s expected status before it is updated. If /// <code>expectedStatus</code> is provided, the package version's status is updated only if its /// status at the time <code>UpdatePackageVersionsStatus</code> is called matches /// <code>expectedStatus</code>. </p> pub fn set_expected_status( mut self, input: std::option::Option<crate::model::PackageVersionStatus>, ) -> Self { self.expected_status = input; self } /// <p> /// The status you want to change the package version status to. /// </p> pub fn target_status(mut self, input: crate::model::PackageVersionStatus) -> Self { self.target_status = Some(input); self } /// <p> /// The status you want to change the package version status to. /// </p> pub fn set_target_status( mut self, input: std::option::Option<crate::model::PackageVersionStatus>, ) -> Self { self.target_status = input; self } /// Consumes the builder and constructs a [`UpdatePackageVersionsStatusInput`](crate::input::UpdatePackageVersionsStatusInput) pub fn build( self, ) -> std::result::Result< crate::input::UpdatePackageVersionsStatusInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::UpdatePackageVersionsStatusInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, format: self.format, namespace: self.namespace, package: self.package, versions: self.versions, version_revisions: self.version_revisions, expected_status: self.expected_status, target_status: self.target_status, }) } } } #[doc(hidden)] pub type UpdatePackageVersionsStatusInputOperationOutputAlias = crate::operation::UpdatePackageVersionsStatus; #[doc(hidden)] pub type UpdatePackageVersionsStatusInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl UpdatePackageVersionsStatusInput { /// Consumes the builder and constructs an Operation<[`UpdatePackageVersionsStatus`](crate::operation::UpdatePackageVersionsStatus)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::UpdatePackageVersionsStatus, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::UpdatePackageVersionsStatusInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/package/versions/update_status") .expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::UpdatePackageVersionsStatusInput, mut output: &mut String, ) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_134) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_134)); } if let Some(inner_135) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_135), ); } if let Some(inner_136) = &_input.repository { query.push_kv( "repository", &aws_smithy_http::query::fmt_string(&inner_136), ); } if let Some(inner_137) = &_input.format { query.push_kv("format", &aws_smithy_http::query::fmt_string(&inner_137)); } if let Some(inner_138) = &_input.namespace { query.push_kv("namespace", &aws_smithy_http::query::fmt_string(&inner_138)); } if let Some(inner_139) = &_input.package { query.push_kv("package", &aws_smithy_http::query::fmt_string(&inner_139)); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::UpdatePackageVersionsStatusInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::UpdatePackageVersionsStatusInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_update_package_versions_status(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::UpdatePackageVersionsStatus::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "UpdatePackageVersionsStatus", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`UpdatePackageVersionsStatusInput`](crate::input::UpdatePackageVersionsStatusInput) pub fn builder() -> crate::input::update_package_versions_status_input::Builder { crate::input::update_package_versions_status_input::Builder::default() } } /// See [`UpdateRepositoryInput`](crate::input::UpdateRepositoryInput) pub mod update_repository_input { /// A builder for [`UpdateRepositoryInput`](crate::input::UpdateRepositoryInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) domain_owner: std::option::Option<std::string::String>, pub(crate) repository: std::option::Option<std::string::String>, pub(crate) description: std::option::Option<std::string::String>, pub(crate) upstreams: std::option::Option<std::vec::Vec<crate::model::UpstreamRepository>>, } impl Builder { /// <p> /// The name of the domain associated with the repository to update. /// </p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p> /// The name of the domain associated with the repository to update. /// </p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self { self.domain_owner = Some(input.into()); self } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_owner = input; self } /// <p> /// The name of the repository to update. /// </p> pub fn repository(mut self, input: impl Into<std::string::String>) -> Self { self.repository = Some(input.into()); self } /// <p> /// The name of the repository to update. /// </p> pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self { self.repository = input; self } /// <p> /// An updated repository description. /// </p> pub fn description(mut self, input: impl Into<std::string::String>) -> Self { self.description = Some(input.into()); self } /// <p> /// An updated repository description. /// </p> pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self { self.description = input; self } /// Appends an item to `upstreams`. /// /// To override the contents of this collection use [`set_upstreams`](Self::set_upstreams). /// /// <p> A list of upstream repositories to associate with the repository. The order of the upstream repositories /// in the list determines their priority order when AWS CodeArtifact looks for a requested package version. For more /// information, see <a href="https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html">Working with upstream repositories</a>. </p> pub fn upstreams(mut self, input: impl Into<crate::model::UpstreamRepository>) -> Self { let mut v = self.upstreams.unwrap_or_default(); v.push(input.into()); self.upstreams = Some(v); self } /// <p> A list of upstream repositories to associate with the repository. The order of the upstream repositories /// in the list determines their priority order when AWS CodeArtifact looks for a requested package version. For more /// information, see <a href="https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html">Working with upstream repositories</a>. </p> pub fn set_upstreams( mut self, input: std::option::Option<std::vec::Vec<crate::model::UpstreamRepository>>, ) -> Self { self.upstreams = input; self } /// Consumes the builder and constructs a [`UpdateRepositoryInput`](crate::input::UpdateRepositoryInput) pub fn build( self, ) -> std::result::Result< crate::input::UpdateRepositoryInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::UpdateRepositoryInput { domain: self.domain, domain_owner: self.domain_owner, repository: self.repository, description: self.description, upstreams: self.upstreams, }) } } } #[doc(hidden)] pub type UpdateRepositoryInputOperationOutputAlias = crate::operation::UpdateRepository; #[doc(hidden)] pub type UpdateRepositoryInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl UpdateRepositoryInput { /// Consumes the builder and constructs an Operation<[`UpdateRepository`](crate::operation::UpdateRepository)> #[allow(clippy::let_and_return)] pub async fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< aws_smithy_http::operation::Operation< crate::operation::UpdateRepository, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::UpdateRepositoryInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v1/repository").expect("formatting should succeed"); Ok(()) } fn uri_query(_input: &crate::input::UpdateRepositoryInput, mut output: &mut String) { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_140) = &_input.domain { query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_140)); } if let Some(inner_141) = &_input.domain_owner { query.push_kv( "domain-owner", &aws_smithy_http::query::fmt_string(&inner_141), ); } if let Some(inner_142) = &_input.repository { query.push_kv( "repository", &aws_smithy_http::query::fmt_string(&inner_142), ); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::UpdateRepositoryInput, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { let mut uri = String::new(); uri_base(input, &mut uri)?; uri_query(input, &mut uri); Ok(builder.method("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::UpdateRepositoryInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_update_repository(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), properties, ); request .properties_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_http::auth::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = aws_smithy_http::operation::Operation::new( request, crate::operation::UpdateRepository::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "UpdateRepository", "codeartifact", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`UpdateRepositoryInput`](crate::input::UpdateRepositoryInput) pub fn builder() -> crate::input::update_repository_input::Builder { crate::input::update_repository_input::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UpdateRepositoryInput { /// <p> /// The name of the domain associated with the repository to update. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> /// The name of the repository to update. /// </p> pub repository: std::option::Option<std::string::String>, /// <p> /// An updated repository description. /// </p> pub description: std::option::Option<std::string::String>, /// <p> A list of upstream repositories to associate with the repository. The order of the upstream repositories /// in the list determines their priority order when AWS CodeArtifact looks for a requested package version. For more /// information, see <a href="https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html">Working with upstream repositories</a>. </p> pub upstreams: std::option::Option<std::vec::Vec<crate::model::UpstreamRepository>>, } impl UpdateRepositoryInput { /// <p> /// The name of the domain associated with the repository to update. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> /// The name of the repository to update. /// </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } /// <p> /// An updated repository description. /// </p> pub fn description(&self) -> std::option::Option<&str> { self.description.as_deref() } /// <p> A list of upstream repositories to associate with the repository. The order of the upstream repositories /// in the list determines their priority order when AWS CodeArtifact looks for a requested package version. For more /// information, see <a href="https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html">Working with upstream repositories</a>. </p> pub fn upstreams(&self) -> std::option::Option<&[crate::model::UpstreamRepository]> { self.upstreams.as_deref() } } impl std::fmt::Debug for UpdateRepositoryInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UpdateRepositoryInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.field("description", &self.description); formatter.field("upstreams", &self.upstreams); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UpdatePackageVersionsStatusInput { /// <p> /// The name of the domain that contains the repository that contains the package versions with a status to be updated. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> /// The repository that contains the package versions with the status you want to update. /// </p> pub repository: std::option::Option<std::string::String>, /// <p> /// A format that specifies the type of the package with the statuses to update. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub format: std::option::Option<crate::model::PackageFormat>, /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub namespace: std::option::Option<std::string::String>, /// <p> /// The name of the package with the version statuses to update. /// </p> pub package: std::option::Option<std::string::String>, /// <p> /// An array of strings that specify the versions of the package with the statuses to update. /// </p> pub versions: std::option::Option<std::vec::Vec<std::string::String>>, /// <p> A map of package versions and package version revisions. The map <code>key</code> is the /// package version (for example, <code>3.5.2</code>), and the map <code>value</code> is the /// package version revision. </p> pub version_revisions: std::option::Option<std::collections::HashMap<std::string::String, std::string::String>>, /// <p> The package version’s expected status before it is updated. If /// <code>expectedStatus</code> is provided, the package version's status is updated only if its /// status at the time <code>UpdatePackageVersionsStatus</code> is called matches /// <code>expectedStatus</code>. </p> pub expected_status: std::option::Option<crate::model::PackageVersionStatus>, /// <p> /// The status you want to change the package version status to. /// </p> pub target_status: std::option::Option<crate::model::PackageVersionStatus>, } impl UpdatePackageVersionsStatusInput { /// <p> /// The name of the domain that contains the repository that contains the package versions with a status to be updated. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> /// The repository that contains the package versions with the status you want to update. /// </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } /// <p> /// A format that specifies the type of the package with the statuses to update. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn format(&self) -> std::option::Option<&crate::model::PackageFormat> { self.format.as_ref() } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(&self) -> std::option::Option<&str> { self.namespace.as_deref() } /// <p> /// The name of the package with the version statuses to update. /// </p> pub fn package(&self) -> std::option::Option<&str> { self.package.as_deref() } /// <p> /// An array of strings that specify the versions of the package with the statuses to update. /// </p> pub fn versions(&self) -> std::option::Option<&[std::string::String]> { self.versions.as_deref() } /// <p> A map of package versions and package version revisions. The map <code>key</code> is the /// package version (for example, <code>3.5.2</code>), and the map <code>value</code> is the /// package version revision. </p> pub fn version_revisions( &self, ) -> std::option::Option<&std::collections::HashMap<std::string::String, std::string::String>> { self.version_revisions.as_ref() } /// <p> The package version’s expected status before it is updated. If /// <code>expectedStatus</code> is provided, the package version's status is updated only if its /// status at the time <code>UpdatePackageVersionsStatus</code> is called matches /// <code>expectedStatus</code>. </p> pub fn expected_status(&self) -> std::option::Option<&crate::model::PackageVersionStatus> { self.expected_status.as_ref() } /// <p> /// The status you want to change the package version status to. /// </p> pub fn target_status(&self) -> std::option::Option<&crate::model::PackageVersionStatus> { self.target_status.as_ref() } } impl std::fmt::Debug for UpdatePackageVersionsStatusInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UpdatePackageVersionsStatusInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.field("format", &self.format); formatter.field("namespace", &self.namespace); formatter.field("package", &self.package); formatter.field("versions", &self.versions); formatter.field("version_revisions", &self.version_revisions); formatter.field("expected_status", &self.expected_status); formatter.field("target_status", &self.target_status); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UntagResourceInput { /// <p>The Amazon Resource Name (ARN) of the resource that you want to remove tags from.</p> pub resource_arn: std::option::Option<std::string::String>, /// <p>The tag key for each tag that you want to remove from the resource.</p> pub tag_keys: std::option::Option<std::vec::Vec<std::string::String>>, } impl UntagResourceInput { /// <p>The Amazon Resource Name (ARN) of the resource that you want to remove tags from.</p> pub fn resource_arn(&self) -> std::option::Option<&str> { self.resource_arn.as_deref() } /// <p>The tag key for each tag that you want to remove from the resource.</p> pub fn tag_keys(&self) -> std::option::Option<&[std::string::String]> { self.tag_keys.as_deref() } } impl std::fmt::Debug for UntagResourceInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UntagResourceInput"); formatter.field("resource_arn", &self.resource_arn); formatter.field("tag_keys", &self.tag_keys); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct TagResourceInput { /// <p>The Amazon Resource Name (ARN) of the resource that you want to add or update tags for.</p> pub resource_arn: std::option::Option<std::string::String>, /// <p>The tags you want to modify or add to the resource.</p> pub tags: std::option::Option<std::vec::Vec<crate::model::Tag>>, } impl TagResourceInput { /// <p>The Amazon Resource Name (ARN) of the resource that you want to add or update tags for.</p> pub fn resource_arn(&self) -> std::option::Option<&str> { self.resource_arn.as_deref() } /// <p>The tags you want to modify or add to the resource.</p> pub fn tags(&self) -> std::option::Option<&[crate::model::Tag]> { self.tags.as_deref() } } impl std::fmt::Debug for TagResourceInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("TagResourceInput"); formatter.field("resource_arn", &self.resource_arn); formatter.field("tags", &self.tags); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutRepositoryPermissionsPolicyInput { /// <p> /// The name of the domain containing the repository to set the resource policy on. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> The name of the repository to set the resource policy on. </p> pub repository: std::option::Option<std::string::String>, /// <p> /// Sets the revision of the resource policy that specifies permissions to access the repository. /// This revision is used for optimistic locking, which prevents others from overwriting your /// changes to the repository's resource policy. /// </p> pub policy_revision: std::option::Option<std::string::String>, /// <p> A valid displayable JSON Aspen policy string to be set as the access control resource /// policy on the provided repository. </p> pub policy_document: std::option::Option<std::string::String>, } impl PutRepositoryPermissionsPolicyInput { /// <p> /// The name of the domain containing the repository to set the resource policy on. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> The name of the repository to set the resource policy on. </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } /// <p> /// Sets the revision of the resource policy that specifies permissions to access the repository. /// This revision is used for optimistic locking, which prevents others from overwriting your /// changes to the repository's resource policy. /// </p> pub fn policy_revision(&self) -> std::option::Option<&str> { self.policy_revision.as_deref() } /// <p> A valid displayable JSON Aspen policy string to be set as the access control resource /// policy on the provided repository. </p> pub fn policy_document(&self) -> std::option::Option<&str> { self.policy_document.as_deref() } } impl std::fmt::Debug for PutRepositoryPermissionsPolicyInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutRepositoryPermissionsPolicyInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.field("policy_revision", &self.policy_revision); formatter.field("policy_document", &self.policy_document); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutDomainPermissionsPolicyInput { /// <p> /// The name of the domain on which to set the resource policy. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> /// The current revision of the resource policy to be set. This revision is used for optimistic locking, which /// prevents others from overwriting your changes to the domain's resource policy. /// </p> pub policy_revision: std::option::Option<std::string::String>, /// <p> A valid displayable JSON Aspen policy string to be set as the access control resource /// policy on the provided domain. </p> pub policy_document: std::option::Option<std::string::String>, } impl PutDomainPermissionsPolicyInput { /// <p> /// The name of the domain on which to set the resource policy. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> /// The current revision of the resource policy to be set. This revision is used for optimistic locking, which /// prevents others from overwriting your changes to the domain's resource policy. /// </p> pub fn policy_revision(&self) -> std::option::Option<&str> { self.policy_revision.as_deref() } /// <p> A valid displayable JSON Aspen policy string to be set as the access control resource /// policy on the provided domain. </p> pub fn policy_document(&self) -> std::option::Option<&str> { self.policy_document.as_deref() } } impl std::fmt::Debug for PutDomainPermissionsPolicyInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutDomainPermissionsPolicyInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("policy_revision", &self.policy_revision); formatter.field("policy_document", &self.policy_document); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListTagsForResourceInput { /// <p>The Amazon Resource Name (ARN) of the resource to get tags for.</p> pub resource_arn: std::option::Option<std::string::String>, } impl ListTagsForResourceInput { /// <p>The Amazon Resource Name (ARN) of the resource to get tags for.</p> pub fn resource_arn(&self) -> std::option::Option<&str> { self.resource_arn.as_deref() } } impl std::fmt::Debug for ListTagsForResourceInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListTagsForResourceInput"); formatter.field("resource_arn", &self.resource_arn); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListRepositoriesInDomainInput { /// <p> /// The name of the domain that contains the returned list of repositories. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> /// Filter the list of repositories to only include those that are managed by the AWS account ID. /// </p> pub administrator_account: std::option::Option<std::string::String>, /// <p> /// A prefix used to filter returned repositories. Only repositories with names that start with /// <code>repositoryPrefix</code> are returned. /// </p> pub repository_prefix: std::option::Option<std::string::String>, /// <p> /// The maximum number of results to return per page. /// </p> pub max_results: std::option::Option<i32>, /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub next_token: std::option::Option<std::string::String>, } impl ListRepositoriesInDomainInput { /// <p> /// The name of the domain that contains the returned list of repositories. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> /// Filter the list of repositories to only include those that are managed by the AWS account ID. /// </p> pub fn administrator_account(&self) -> std::option::Option<&str> { self.administrator_account.as_deref() } /// <p> /// A prefix used to filter returned repositories. Only repositories with names that start with /// <code>repositoryPrefix</code> are returned. /// </p> pub fn repository_prefix(&self) -> std::option::Option<&str> { self.repository_prefix.as_deref() } /// <p> /// The maximum number of results to return per page. /// </p> pub fn max_results(&self) -> std::option::Option<i32> { self.max_results } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } } impl std::fmt::Debug for ListRepositoriesInDomainInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListRepositoriesInDomainInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("administrator_account", &self.administrator_account); formatter.field("repository_prefix", &self.repository_prefix); formatter.field("max_results", &self.max_results); formatter.field("next_token", &self.next_token); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListRepositoriesInput { /// <p> A prefix used to filter returned repositories. Only repositories with names that start /// with <code>repositoryPrefix</code> are returned.</p> pub repository_prefix: std::option::Option<std::string::String>, /// <p> /// The maximum number of results to return per page. /// </p> pub max_results: std::option::Option<i32>, /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub next_token: std::option::Option<std::string::String>, } impl ListRepositoriesInput { /// <p> A prefix used to filter returned repositories. Only repositories with names that start /// with <code>repositoryPrefix</code> are returned.</p> pub fn repository_prefix(&self) -> std::option::Option<&str> { self.repository_prefix.as_deref() } /// <p> /// The maximum number of results to return per page. /// </p> pub fn max_results(&self) -> std::option::Option<i32> { self.max_results } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } } impl std::fmt::Debug for ListRepositoriesInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListRepositoriesInput"); formatter.field("repository_prefix", &self.repository_prefix); formatter.field("max_results", &self.max_results); formatter.field("next_token", &self.next_token); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListPackageVersionsInput { /// <p> /// The name of the domain that contains the repository that contains the returned package versions. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> /// The name of the repository that contains the package. /// </p> pub repository: std::option::Option<std::string::String>, /// <p> /// The format of the returned packages. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub format: std::option::Option<crate::model::PackageFormat>, /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub namespace: std::option::Option<std::string::String>, /// <p> /// The name of the package for which you want to return a list of package versions. /// </p> pub package: std::option::Option<std::string::String>, /// <p> /// A string that specifies the status of the package versions to include in the returned list. It can be one of the following: /// </p> /// <ul> /// <li> /// <p> /// <code>Published</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unfinished</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unlisted</code> /// </p> /// </li> /// <li> /// <p> /// <code>Archived</code> /// </p> /// </li> /// <li> /// <p> /// <code>Disposed</code> /// </p> /// </li> /// </ul> pub status: std::option::Option<crate::model::PackageVersionStatus>, /// <p> /// How to sort the returned list of package versions. /// </p> pub sort_by: std::option::Option<crate::model::PackageVersionSortType>, /// <p> /// The maximum number of results to return per page. /// </p> pub max_results: std::option::Option<i32>, /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub next_token: std::option::Option<std::string::String>, } impl ListPackageVersionsInput { /// <p> /// The name of the domain that contains the repository that contains the returned package versions. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> /// The name of the repository that contains the package. /// </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } /// <p> /// The format of the returned packages. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub fn format(&self) -> std::option::Option<&crate::model::PackageFormat> { self.format.as_ref() } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(&self) -> std::option::Option<&str> { self.namespace.as_deref() } /// <p> /// The name of the package for which you want to return a list of package versions. /// </p> pub fn package(&self) -> std::option::Option<&str> { self.package.as_deref() } /// <p> /// A string that specifies the status of the package versions to include in the returned list. It can be one of the following: /// </p> /// <ul> /// <li> /// <p> /// <code>Published</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unfinished</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unlisted</code> /// </p> /// </li> /// <li> /// <p> /// <code>Archived</code> /// </p> /// </li> /// <li> /// <p> /// <code>Disposed</code> /// </p> /// </li> /// </ul> pub fn status(&self) -> std::option::Option<&crate::model::PackageVersionStatus> { self.status.as_ref() } /// <p> /// How to sort the returned list of package versions. /// </p> pub fn sort_by(&self) -> std::option::Option<&crate::model::PackageVersionSortType> { self.sort_by.as_ref() } /// <p> /// The maximum number of results to return per page. /// </p> pub fn max_results(&self) -> std::option::Option<i32> { self.max_results } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } } impl std::fmt::Debug for ListPackageVersionsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListPackageVersionsInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.field("format", &self.format); formatter.field("namespace", &self.namespace); formatter.field("package", &self.package); formatter.field("status", &self.status); formatter.field("sort_by", &self.sort_by); formatter.field("max_results", &self.max_results); formatter.field("next_token", &self.next_token); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListPackageVersionDependenciesInput { /// <p> /// The name of the domain that contains the repository that contains the requested package version dependencies. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> /// The name of the repository that contains the requested package version. /// </p> pub repository: std::option::Option<std::string::String>, /// <p> /// The format of the package with the requested dependencies. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub format: std::option::Option<crate::model::PackageFormat>, /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub namespace: std::option::Option<std::string::String>, /// <p> /// The name of the package versions' package. /// </p> pub package: std::option::Option<std::string::String>, /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub package_version: std::option::Option<std::string::String>, /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub next_token: std::option::Option<std::string::String>, } impl ListPackageVersionDependenciesInput { /// <p> /// The name of the domain that contains the repository that contains the requested package version dependencies. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> /// The name of the repository that contains the requested package version. /// </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } /// <p> /// The format of the package with the requested dependencies. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub fn format(&self) -> std::option::Option<&crate::model::PackageFormat> { self.format.as_ref() } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(&self) -> std::option::Option<&str> { self.namespace.as_deref() } /// <p> /// The name of the package versions' package. /// </p> pub fn package(&self) -> std::option::Option<&str> { self.package.as_deref() } /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub fn package_version(&self) -> std::option::Option<&str> { self.package_version.as_deref() } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } } impl std::fmt::Debug for ListPackageVersionDependenciesInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListPackageVersionDependenciesInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.field("format", &self.format); formatter.field("namespace", &self.namespace); formatter.field("package", &self.package); formatter.field("package_version", &self.package_version); formatter.field("next_token", &self.next_token); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListPackageVersionAssetsInput { /// <p> /// The name of the domain that contains the repository associated with the package version assets. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> /// The name of the repository that contains the package that contains the returned package version assets. /// </p> pub repository: std::option::Option<std::string::String>, /// <p> /// The format of the package that contains the returned package version assets. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub format: std::option::Option<crate::model::PackageFormat>, /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub namespace: std::option::Option<std::string::String>, /// <p> /// The name of the package that contains the returned package version assets. /// </p> pub package: std::option::Option<std::string::String>, /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub package_version: std::option::Option<std::string::String>, /// <p> /// The maximum number of results to return per page. /// </p> pub max_results: std::option::Option<i32>, /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub next_token: std::option::Option<std::string::String>, } impl ListPackageVersionAssetsInput { /// <p> /// The name of the domain that contains the repository associated with the package version assets. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> /// The name of the repository that contains the package that contains the returned package version assets. /// </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } /// <p> /// The format of the package that contains the returned package version assets. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub fn format(&self) -> std::option::Option<&crate::model::PackageFormat> { self.format.as_ref() } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(&self) -> std::option::Option<&str> { self.namespace.as_deref() } /// <p> /// The name of the package that contains the returned package version assets. /// </p> pub fn package(&self) -> std::option::Option<&str> { self.package.as_deref() } /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub fn package_version(&self) -> std::option::Option<&str> { self.package_version.as_deref() } /// <p> /// The maximum number of results to return per page. /// </p> pub fn max_results(&self) -> std::option::Option<i32> { self.max_results } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } } impl std::fmt::Debug for ListPackageVersionAssetsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListPackageVersionAssetsInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.field("format", &self.format); formatter.field("namespace", &self.namespace); formatter.field("package", &self.package); formatter.field("package_version", &self.package_version); formatter.field("max_results", &self.max_results); formatter.field("next_token", &self.next_token); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListPackagesInput { /// <p> /// The name of the domain that contains the repository that contains the requested list of packages. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> /// The name of the repository from which packages are to be listed. /// </p> pub repository: std::option::Option<std::string::String>, /// <p> /// The format of the packages. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub format: std::option::Option<crate::model::PackageFormat>, /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub namespace: std::option::Option<std::string::String>, /// <p> /// A prefix used to filter returned packages. Only packages with names that start with /// <code>packagePrefix</code> are returned. /// </p> pub package_prefix: std::option::Option<std::string::String>, /// <p> /// The maximum number of results to return per page. /// </p> pub max_results: std::option::Option<i32>, /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub next_token: std::option::Option<std::string::String>, } impl ListPackagesInput { /// <p> /// The name of the domain that contains the repository that contains the requested list of packages. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> /// The name of the repository from which packages are to be listed. /// </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } /// <p> /// The format of the packages. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub fn format(&self) -> std::option::Option<&crate::model::PackageFormat> { self.format.as_ref() } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(&self) -> std::option::Option<&str> { self.namespace.as_deref() } /// <p> /// A prefix used to filter returned packages. Only packages with names that start with /// <code>packagePrefix</code> are returned. /// </p> pub fn package_prefix(&self) -> std::option::Option<&str> { self.package_prefix.as_deref() } /// <p> /// The maximum number of results to return per page. /// </p> pub fn max_results(&self) -> std::option::Option<i32> { self.max_results } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } } impl std::fmt::Debug for ListPackagesInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListPackagesInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.field("format", &self.format); formatter.field("namespace", &self.namespace); formatter.field("package_prefix", &self.package_prefix); formatter.field("max_results", &self.max_results); formatter.field("next_token", &self.next_token); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListDomainsInput { /// <p> /// The maximum number of results to return per page. /// </p> pub max_results: std::option::Option<i32>, /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub next_token: std::option::Option<std::string::String>, } impl ListDomainsInput { /// <p> /// The maximum number of results to return per page. /// </p> pub fn max_results(&self) -> std::option::Option<i32> { self.max_results } /// <p> /// The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results. /// </p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } } impl std::fmt::Debug for ListDomainsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListDomainsInput"); formatter.field("max_results", &self.max_results); formatter.field("next_token", &self.next_token); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetRepositoryPermissionsPolicyInput { /// <p> /// The name of the domain containing the repository whose associated resource policy is to be retrieved. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> /// The name of the repository whose associated resource policy is to be retrieved. /// </p> pub repository: std::option::Option<std::string::String>, } impl GetRepositoryPermissionsPolicyInput { /// <p> /// The name of the domain containing the repository whose associated resource policy is to be retrieved. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> /// The name of the repository whose associated resource policy is to be retrieved. /// </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } } impl std::fmt::Debug for GetRepositoryPermissionsPolicyInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetRepositoryPermissionsPolicyInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetRepositoryEndpointInput { /// <p> /// The name of the domain that contains the repository. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain that contains the repository. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> /// The name of the repository. /// </p> pub repository: std::option::Option<std::string::String>, /// <p> /// Returns which endpoint of a repository to return. A repository has one endpoint for each /// package format: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub format: std::option::Option<crate::model::PackageFormat>, } impl GetRepositoryEndpointInput { /// <p> /// The name of the domain that contains the repository. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain that contains the repository. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> /// The name of the repository. /// </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } /// <p> /// Returns which endpoint of a repository to return. A repository has one endpoint for each /// package format: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn format(&self) -> std::option::Option<&crate::model::PackageFormat> { self.format.as_ref() } } impl std::fmt::Debug for GetRepositoryEndpointInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetRepositoryEndpointInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.field("format", &self.format); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetPackageVersionReadmeInput { /// <p> /// The name of the domain that contains the repository that contains the package version with the requested readme file. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> /// The repository that contains the package with the requested readme file. /// </p> pub repository: std::option::Option<std::string::String>, /// <p> /// A format that specifies the type of the package version with the requested readme file. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub format: std::option::Option<crate::model::PackageFormat>, /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub namespace: std::option::Option<std::string::String>, /// <p> /// The name of the package version that contains the requested readme file. /// </p> pub package: std::option::Option<std::string::String>, /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub package_version: std::option::Option<std::string::String>, } impl GetPackageVersionReadmeInput { /// <p> /// The name of the domain that contains the repository that contains the package version with the requested readme file. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> /// The repository that contains the package with the requested readme file. /// </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } /// <p> /// A format that specifies the type of the package version with the requested readme file. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn format(&self) -> std::option::Option<&crate::model::PackageFormat> { self.format.as_ref() } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(&self) -> std::option::Option<&str> { self.namespace.as_deref() } /// <p> /// The name of the package version that contains the requested readme file. /// </p> pub fn package(&self) -> std::option::Option<&str> { self.package.as_deref() } /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub fn package_version(&self) -> std::option::Option<&str> { self.package_version.as_deref() } } impl std::fmt::Debug for GetPackageVersionReadmeInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetPackageVersionReadmeInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.field("format", &self.format); formatter.field("namespace", &self.namespace); formatter.field("package", &self.package); formatter.field("package_version", &self.package_version); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetPackageVersionAssetInput { /// <p> /// The name of the domain that contains the repository that contains the package version with the requested asset. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> /// The repository that contains the package version with the requested asset. /// </p> pub repository: std::option::Option<std::string::String>, /// <p> /// A format that specifies the type of the package version with the requested asset file. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub format: std::option::Option<crate::model::PackageFormat>, /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub namespace: std::option::Option<std::string::String>, /// <p> /// The name of the package that contains the requested asset. /// </p> pub package: std::option::Option<std::string::String>, /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub package_version: std::option::Option<std::string::String>, /// <p> /// The name of the requested asset. /// </p> pub asset: std::option::Option<std::string::String>, /// <p> /// The name of the package version revision that contains the requested asset. /// </p> pub package_version_revision: std::option::Option<std::string::String>, } impl GetPackageVersionAssetInput { /// <p> /// The name of the domain that contains the repository that contains the package version with the requested asset. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> /// The repository that contains the package version with the requested asset. /// </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } /// <p> /// A format that specifies the type of the package version with the requested asset file. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn format(&self) -> std::option::Option<&crate::model::PackageFormat> { self.format.as_ref() } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(&self) -> std::option::Option<&str> { self.namespace.as_deref() } /// <p> /// The name of the package that contains the requested asset. /// </p> pub fn package(&self) -> std::option::Option<&str> { self.package.as_deref() } /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub fn package_version(&self) -> std::option::Option<&str> { self.package_version.as_deref() } /// <p> /// The name of the requested asset. /// </p> pub fn asset(&self) -> std::option::Option<&str> { self.asset.as_deref() } /// <p> /// The name of the package version revision that contains the requested asset. /// </p> pub fn package_version_revision(&self) -> std::option::Option<&str> { self.package_version_revision.as_deref() } } impl std::fmt::Debug for GetPackageVersionAssetInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetPackageVersionAssetInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.field("format", &self.format); formatter.field("namespace", &self.namespace); formatter.field("package", &self.package); formatter.field("package_version", &self.package_version); formatter.field("asset", &self.asset); formatter.field("package_version_revision", &self.package_version_revision); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetDomainPermissionsPolicyInput { /// <p> /// The name of the domain to which the resource policy is attached. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, } impl GetDomainPermissionsPolicyInput { /// <p> /// The name of the domain to which the resource policy is attached. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } } impl std::fmt::Debug for GetDomainPermissionsPolicyInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetDomainPermissionsPolicyInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetAuthorizationTokenInput { /// <p> /// The name of the domain that is in scope for the generated authorization token. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p>The time, in seconds, that the generated authorization token is valid. Valid values are /// <code>0</code> and any number between <code>900</code> (15 minutes) and <code>43200</code> (12 hours). /// A value of <code>0</code> will set the expiration of the authorization token to the same expiration of /// the user's role's temporary credentials.</p> pub duration_seconds: std::option::Option<i64>, } impl GetAuthorizationTokenInput { /// <p> /// The name of the domain that is in scope for the generated authorization token. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p>The time, in seconds, that the generated authorization token is valid. Valid values are /// <code>0</code> and any number between <code>900</code> (15 minutes) and <code>43200</code> (12 hours). /// A value of <code>0</code> will set the expiration of the authorization token to the same expiration of /// the user's role's temporary credentials.</p> pub fn duration_seconds(&self) -> std::option::Option<i64> { self.duration_seconds } } impl std::fmt::Debug for GetAuthorizationTokenInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetAuthorizationTokenInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("duration_seconds", &self.duration_seconds); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DisposePackageVersionsInput { /// <p> /// The name of the domain that contains the repository you want to dispose. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> /// The name of the repository that contains the package versions you want to dispose. /// </p> pub repository: std::option::Option<std::string::String>, /// <p> /// A format that specifies the type of package versions you want to dispose. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub format: std::option::Option<crate::model::PackageFormat>, /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub namespace: std::option::Option<std::string::String>, /// <p> /// The name of the package with the versions you want to dispose. /// </p> pub package: std::option::Option<std::string::String>, /// <p> /// The versions of the package you want to dispose. /// </p> pub versions: std::option::Option<std::vec::Vec<std::string::String>>, /// <p> /// The revisions of the package versions you want to dispose. /// </p> pub version_revisions: std::option::Option<std::collections::HashMap<std::string::String, std::string::String>>, /// <p> /// The expected status of the package version to dispose. Valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>Published</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unfinished</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unlisted</code> /// </p> /// </li> /// <li> /// <p> /// <code>Archived</code> /// </p> /// </li> /// <li> /// <p> /// <code>Disposed</code> /// </p> /// </li> /// </ul> pub expected_status: std::option::Option<crate::model::PackageVersionStatus>, } impl DisposePackageVersionsInput { /// <p> /// The name of the domain that contains the repository you want to dispose. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> /// The name of the repository that contains the package versions you want to dispose. /// </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } /// <p> /// A format that specifies the type of package versions you want to dispose. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn format(&self) -> std::option::Option<&crate::model::PackageFormat> { self.format.as_ref() } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(&self) -> std::option::Option<&str> { self.namespace.as_deref() } /// <p> /// The name of the package with the versions you want to dispose. /// </p> pub fn package(&self) -> std::option::Option<&str> { self.package.as_deref() } /// <p> /// The versions of the package you want to dispose. /// </p> pub fn versions(&self) -> std::option::Option<&[std::string::String]> { self.versions.as_deref() } /// <p> /// The revisions of the package versions you want to dispose. /// </p> pub fn version_revisions( &self, ) -> std::option::Option<&std::collections::HashMap<std::string::String, std::string::String>> { self.version_revisions.as_ref() } /// <p> /// The expected status of the package version to dispose. Valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>Published</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unfinished</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unlisted</code> /// </p> /// </li> /// <li> /// <p> /// <code>Archived</code> /// </p> /// </li> /// <li> /// <p> /// <code>Disposed</code> /// </p> /// </li> /// </ul> pub fn expected_status(&self) -> std::option::Option<&crate::model::PackageVersionStatus> { self.expected_status.as_ref() } } impl std::fmt::Debug for DisposePackageVersionsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DisposePackageVersionsInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.field("format", &self.format); formatter.field("namespace", &self.namespace); formatter.field("package", &self.package); formatter.field("versions", &self.versions); formatter.field("version_revisions", &self.version_revisions); formatter.field("expected_status", &self.expected_status); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DisassociateExternalConnectionInput { /// <p>The name of the domain that contains the repository from which to remove the external /// repository. </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p>The name of the repository from which the external connection will be removed. </p> pub repository: std::option::Option<std::string::String>, /// <p>The name of the external connection to be removed from the repository. </p> pub external_connection: std::option::Option<std::string::String>, } impl DisassociateExternalConnectionInput { /// <p>The name of the domain that contains the repository from which to remove the external /// repository. </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p>The name of the repository from which the external connection will be removed. </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } /// <p>The name of the external connection to be removed from the repository. </p> pub fn external_connection(&self) -> std::option::Option<&str> { self.external_connection.as_deref() } } impl std::fmt::Debug for DisassociateExternalConnectionInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DisassociateExternalConnectionInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.field("external_connection", &self.external_connection); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DescribeRepositoryInput { /// <p> /// The name of the domain that contains the repository to describe. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> /// A string that specifies the name of the requested repository. /// </p> pub repository: std::option::Option<std::string::String>, } impl DescribeRepositoryInput { /// <p> /// The name of the domain that contains the repository to describe. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> /// A string that specifies the name of the requested repository. /// </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } } impl std::fmt::Debug for DescribeRepositoryInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DescribeRepositoryInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DescribePackageVersionInput { /// <p> /// The name of the domain that contains the repository that contains the package version. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> The name of the repository that contains the package version. </p> pub repository: std::option::Option<std::string::String>, /// <p> /// A format that specifies the type of the requested package version. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub format: std::option::Option<crate::model::PackageFormat>, /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub namespace: std::option::Option<std::string::String>, /// <p> The name of the requested package version. </p> pub package: std::option::Option<std::string::String>, /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub package_version: std::option::Option<std::string::String>, } impl DescribePackageVersionInput { /// <p> /// The name of the domain that contains the repository that contains the package version. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> The name of the repository that contains the package version. </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } /// <p> /// A format that specifies the type of the requested package version. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn format(&self) -> std::option::Option<&crate::model::PackageFormat> { self.format.as_ref() } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(&self) -> std::option::Option<&str> { self.namespace.as_deref() } /// <p> The name of the requested package version. </p> pub fn package(&self) -> std::option::Option<&str> { self.package.as_deref() } /// <p> /// A string that contains the package version (for example, <code>3.5.2</code>). /// </p> pub fn package_version(&self) -> std::option::Option<&str> { self.package_version.as_deref() } } impl std::fmt::Debug for DescribePackageVersionInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DescribePackageVersionInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.field("format", &self.format); formatter.field("namespace", &self.namespace); formatter.field("package", &self.package); formatter.field("package_version", &self.package_version); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DescribeDomainInput { /// <p> /// A string that specifies the name of the requested domain. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, } impl DescribeDomainInput { /// <p> /// A string that specifies the name of the requested domain. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } } impl std::fmt::Debug for DescribeDomainInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DescribeDomainInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeleteRepositoryPermissionsPolicyInput { /// <p> /// The name of the domain that contains the repository associated with the resource policy to be deleted. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> /// The name of the repository that is associated with the resource policy to be deleted /// </p> pub repository: std::option::Option<std::string::String>, /// <p> /// The revision of the repository's resource policy to be deleted. This revision is used for optimistic locking, which /// prevents others from accidentally overwriting your changes to the repository's resource policy. /// </p> pub policy_revision: std::option::Option<std::string::String>, } impl DeleteRepositoryPermissionsPolicyInput { /// <p> /// The name of the domain that contains the repository associated with the resource policy to be deleted. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> /// The name of the repository that is associated with the resource policy to be deleted /// </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } /// <p> /// The revision of the repository's resource policy to be deleted. This revision is used for optimistic locking, which /// prevents others from accidentally overwriting your changes to the repository's resource policy. /// </p> pub fn policy_revision(&self) -> std::option::Option<&str> { self.policy_revision.as_deref() } } impl std::fmt::Debug for DeleteRepositoryPermissionsPolicyInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeleteRepositoryPermissionsPolicyInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.field("policy_revision", &self.policy_revision); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeleteRepositoryInput { /// <p> /// The name of the domain that contains the repository to delete. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> The name of the repository to delete. </p> pub repository: std::option::Option<std::string::String>, } impl DeleteRepositoryInput { /// <p> /// The name of the domain that contains the repository to delete. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> The name of the repository to delete. </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } } impl std::fmt::Debug for DeleteRepositoryInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeleteRepositoryInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeletePackageVersionsInput { /// <p> /// The name of the domain that contains the package to delete. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> /// The name of the repository that contains the package versions to delete. /// </p> pub repository: std::option::Option<std::string::String>, /// <p> /// The format of the package versions to delete. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub format: std::option::Option<crate::model::PackageFormat>, /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p>
/// </p> /// </li> /// </ul> pub namespace: std::option::Option<std::string::String>, /// <p> /// The name of the package with the versions to delete. /// </p> pub package: std::option::Option<std::string::String>, /// <p> /// An array of strings that specify the versions of the package to delete. /// </p> pub versions: std::option::Option<std::vec::Vec<std::string::String>>, /// <p> /// The expected status of the package version to delete. Valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>Published</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unfinished</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unlisted</code> /// </p> /// </li> /// <li> /// <p> /// <code>Archived</code> /// </p> /// </li> /// <li> /// <p> /// <code>Disposed</code> /// </p> /// </li> /// </ul> pub expected_status: std::option::Option<crate::model::PackageVersionStatus>, } impl DeletePackageVersionsInput { /// <p> /// The name of the domain that contains the package to delete. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> /// The name of the repository that contains the package versions to delete. /// </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } /// <p> /// The format of the package versions to delete. The valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code> /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code> /// </p> /// </li> /// <li> /// <p> /// <code>maven</code> /// </p> /// </li> /// </ul> pub fn format(&self) -> std::option::Option<&crate::model::PackageFormat> { self.format.as_ref() } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(&self) -> std::option::Option<&str> { self.namespace.as_deref() } /// <p> /// The name of the package with the versions to delete. /// </p> pub fn package(&self) -> std::option::Option<&str> { self.package.as_deref() } /// <p> /// An array of strings that specify the versions of the package to delete. /// </p> pub fn versions(&self) -> std::option::Option<&[std::string::String]> { self.versions.as_deref() } /// <p> /// The expected status of the package version to delete. Valid values are: /// </p> /// <ul> /// <li> /// <p> /// <code>Published</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unfinished</code> /// </p> /// </li> /// <li> /// <p> /// <code>Unlisted</code> /// </p> /// </li> /// <li> /// <p> /// <code>Archived</code> /// </p> /// </li> /// <li> /// <p> /// <code>Disposed</code> /// </p> /// </li> /// </ul> pub fn expected_status(&self) -> std::option::Option<&crate::model::PackageVersionStatus> { self.expected_status.as_ref() } } impl std::fmt::Debug for DeletePackageVersionsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeletePackageVersionsInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.field("format", &self.format); formatter.field("namespace", &self.namespace); formatter.field("package", &self.package); formatter.field("versions", &self.versions); formatter.field("expected_status", &self.expected_status); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeleteDomainPermissionsPolicyInput { /// <p> /// The name of the domain associated with the resource policy to be deleted. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> /// The current revision of the resource policy to be deleted. This revision is used for optimistic locking, which /// prevents others from overwriting your changes to the domain's resource policy. /// </p> pub policy_revision: std::option::Option<std::string::String>, } impl DeleteDomainPermissionsPolicyInput { /// <p> /// The name of the domain associated with the resource policy to be deleted. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> /// The current revision of the resource policy to be deleted. This revision is used for optimistic locking, which /// prevents others from overwriting your changes to the domain's resource policy. /// </p> pub fn policy_revision(&self) -> std::option::Option<&str> { self.policy_revision.as_deref() } } impl std::fmt::Debug for DeleteDomainPermissionsPolicyInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeleteDomainPermissionsPolicyInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("policy_revision", &self.policy_revision); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeleteDomainInput { /// <p> /// The name of the domain to delete. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, } impl DeleteDomainInput { /// <p> /// The name of the domain to delete. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } } impl std::fmt::Debug for DeleteDomainInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeleteDomainInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CreateRepositoryInput { /// <p> /// The name of the domain that contains the created repository. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> The name of the repository to create. </p> pub repository: std::option::Option<std::string::String>, /// <p> /// A description of the created repository. /// </p> pub description: std::option::Option<std::string::String>, /// <p> A list of upstream repositories to associate with the repository. The order of the upstream repositories /// in the list determines their priority order when AWS CodeArtifact looks for a requested package version. For more /// information, see <a href="https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html">Working with upstream repositories</a>. </p> pub upstreams: std::option::Option<std::vec::Vec<crate::model::UpstreamRepository>>, /// <p>One or more tag key-value pairs for the repository.</p> pub tags: std::option::Option<std::vec::Vec<crate::model::Tag>>, } impl CreateRepositoryInput { /// <p> /// The name of the domain that contains the created repository. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> The name of the repository to create. </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } /// <p> /// A description of the created repository. /// </p> pub fn description(&self) -> std::option::Option<&str> { self.description.as_deref() } /// <p> A list of upstream repositories to associate with the repository. The order of the upstream repositories /// in the list determines their priority order when AWS CodeArtifact looks for a requested package version. For more /// information, see <a href="https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html">Working with upstream repositories</a>. </p> pub fn upstreams(&self) -> std::option::Option<&[crate::model::UpstreamRepository]> { self.upstreams.as_deref() } /// <p>One or more tag key-value pairs for the repository.</p> pub fn tags(&self) -> std::option::Option<&[crate::model::Tag]> { self.tags.as_deref() } } impl std::fmt::Debug for CreateRepositoryInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CreateRepositoryInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.field("description", &self.description); formatter.field("upstreams", &self.upstreams); formatter.field("tags", &self.tags); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CreateDomainInput { /// <p> The name of the domain to create. All domain names in an AWS Region that are in the /// same AWS account must be unique. The domain name is used as the prefix in DNS hostnames. Do /// not use sensitive information in a domain name because it is publicly discoverable. </p> pub domain: std::option::Option<std::string::String>, /// <p> The encryption key for the domain. This is used to encrypt content stored in a domain. /// An encryption key can be a key ID, a key Amazon Resource Name (ARN), a key alias, or a key /// alias ARN. To specify an <code>encryptionKey</code>, your IAM role must have /// <code>kms:DescribeKey</code> and <code>kms:CreateGrant</code> permissions on the encryption /// key that is used. For more information, see <a href="https://docs.aws.amazon.com/kms/latest/APIReference/API_DescribeKey.html#API_DescribeKey_RequestSyntax">DescribeKey</a> in the <i>AWS Key Management Service API Reference</i> /// and <a href="https://docs.aws.amazon.com/kms/latest/developerguide/kms-api-permissions-reference.html">AWS KMS API Permissions /// Reference</a> in the <i>AWS Key Management Service Developer Guide</i>. </p> /// <important> /// <p> CodeArtifact supports only symmetric CMKs. Do not associate an asymmetric CMK with your /// domain. For more information, see <a href="https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html">Using symmetric and asymmetric /// keys</a> in the <i>AWS Key Management Service Developer Guide</i>. </p> /// </important> pub encryption_key: std::option::Option<std::string::String>, /// <p>One or more tag key-value pairs for the domain.</p> pub tags: std::option::Option<std::vec::Vec<crate::model::Tag>>, } impl CreateDomainInput { /// <p> The name of the domain to create. All domain names in an AWS Region that are in the /// same AWS account must be unique. The domain name is used as the prefix in DNS hostnames. Do /// not use sensitive information in a domain name because it is publicly discoverable. </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> The encryption key for the domain. This is used to encrypt content stored in a domain. /// An encryption key can be a key ID, a key Amazon Resource Name (ARN), a key alias, or a key /// alias ARN. To specify an <code>encryptionKey</code>, your IAM role must have /// <code>kms:DescribeKey</code> and <code>kms:CreateGrant</code> permissions on the encryption /// key that is used. For more information, see <a href="https://docs.aws.amazon.com/kms/latest/APIReference/API_DescribeKey.html#API_DescribeKey_RequestSyntax">DescribeKey</a> in the <i>AWS Key Management Service API Reference</i> /// and <a href="https://docs.aws.amazon.com/kms/latest/developerguide/kms-api-permissions-reference.html">AWS KMS API Permissions /// Reference</a> in the <i>AWS Key Management Service Developer Guide</i>. </p> /// <important> /// <p> CodeArtifact supports only symmetric CMKs. Do not associate an asymmetric CMK with your /// domain. For more information, see <a href="https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html">Using symmetric and asymmetric /// keys</a> in the <i>AWS Key Management Service Developer Guide</i>. </p> /// </important> pub fn encryption_key(&self) -> std::option::Option<&str> { self.encryption_key.as_deref() } /// <p>One or more tag key-value pairs for the domain.</p> pub fn tags(&self) -> std::option::Option<&[crate::model::Tag]> { self.tags.as_deref() } } impl std::fmt::Debug for CreateDomainInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CreateDomainInput"); formatter.field("domain", &self.domain); formatter.field("encryption_key", &self.encryption_key); formatter.field("tags", &self.tags); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CopyPackageVersionsInput { /// <p> /// The name of the domain that contains the source and destination repositories. /// </p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> /// The name of the repository that contains the package versions to copy. /// </p> pub source_repository: std::option::Option<std::string::String>, /// <p> /// The name of the repository into which package versions are copied. /// </p> pub destination_repository: std::option::Option<std::string::String>, /// <p> /// The format of the package that is copied. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub format: std::option::Option<crate::model::PackageFormat>, /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub namespace: std::option::Option<std::string::String>, /// <p> /// The name of the package that is copied. /// </p> pub package: std::option::Option<std::string::String>, /// <p> /// The versions of the package to copy. /// </p> /// <note> /// <p> /// You must specify <code>versions</code> or <code>versionRevisions</code>. You cannot specify both. /// </p> /// </note> pub versions: std::option::Option<std::vec::Vec<std::string::String>>, /// <p> /// A list of key-value pairs. The keys are package versions and the values are package version revisions. A <code>CopyPackageVersion</code> operation /// succeeds if the specified versions in the source repository match the specified package version revision. /// </p> /// <note> /// <p> /// You must specify <code>versions</code> or <code>versionRevisions</code>. You cannot specify both. /// </p> /// </note> pub version_revisions: std::option::Option<std::collections::HashMap<std::string::String, std::string::String>>, /// <p> /// Set to true to overwrite a package version that already exists in the destination repository. /// If set to false and the package version already exists in the destination repository, /// the package version is returned in the <code>failedVersions</code> field of the response with /// an <code>ALREADY_EXISTS</code> error code. /// </p> pub allow_overwrite: std::option::Option<bool>, /// <p> Set to true to copy packages from repositories that are upstream from the source /// repository to the destination repository. The default setting is false. For more information, /// see <a href="https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html">Working with /// upstream repositories</a>. </p> pub include_from_upstream: std::option::Option<bool>, } impl CopyPackageVersionsInput { /// <p> /// The name of the domain that contains the source and destination repositories. /// </p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> /// The name of the repository that contains the package versions to copy. /// </p> pub fn source_repository(&self) -> std::option::Option<&str> { self.source_repository.as_deref() } /// <p> /// The name of the repository into which package versions are copied. /// </p> pub fn destination_repository(&self) -> std::option::Option<&str> { self.destination_repository.as_deref() } /// <p> /// The format of the package that is copied. The valid package types are: /// </p> /// <ul> /// <li> /// <p> /// <code>npm</code>: A Node Package Manager (npm) package. /// </p> /// </li> /// <li> /// <p> /// <code>pypi</code>: A Python Package Index (PyPI) package. /// </p> /// </li> /// <li> /// <p> /// <code>maven</code>: A Maven package that contains compiled code in a distributable format, such as a JAR file. /// </p> /// </li> /// </ul> pub fn format(&self) -> std::option::Option<&crate::model::PackageFormat> { self.format.as_ref() } /// <p> /// The namespace of the package. The package component that specifies its /// namespace depends on its type. For example: /// </p> /// <ul> /// <li> /// <p> /// The namespace of a Maven package is its <code>groupId</code>. /// </p> /// </li> /// <li> /// <p> /// The namespace of an npm package is its <code>scope</code>. /// </p> /// </li> /// <li> /// <p> /// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace. /// </p> /// </li> /// </ul> pub fn namespace(&self) -> std::option::Option<&str> { self.namespace.as_deref() } /// <p> /// The name of the package that is copied. /// </p> pub fn package(&self) -> std::option::Option<&str> { self.package.as_deref() } /// <p> /// The versions of the package to copy. /// </p> /// <note> /// <p> /// You must specify <code>versions</code> or <code>versionRevisions</code>. You cannot specify both. /// </p> /// </note> pub fn versions(&self) -> std::option::Option<&[std::string::String]> { self.versions.as_deref() } /// <p> /// A list of key-value pairs. The keys are package versions and the values are package version revisions. A <code>CopyPackageVersion</code> operation /// succeeds if the specified versions in the source repository match the specified package version revision. /// </p> /// <note> /// <p> /// You must specify <code>versions</code> or <code>versionRevisions</code>. You cannot specify both. /// </p> /// </note> pub fn version_revisions( &self, ) -> std::option::Option<&std::collections::HashMap<std::string::String, std::string::String>> { self.version_revisions.as_ref() } /// <p> /// Set to true to overwrite a package version that already exists in the destination repository. /// If set to false and the package version already exists in the destination repository, /// the package version is returned in the <code>failedVersions</code> field of the response with /// an <code>ALREADY_EXISTS</code> error code. /// </p> pub fn allow_overwrite(&self) -> std::option::Option<bool> { self.allow_overwrite } /// <p> Set to true to copy packages from repositories that are upstream from the source /// repository to the destination repository. The default setting is false. For more information, /// see <a href="https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html">Working with /// upstream repositories</a>. </p> pub fn include_from_upstream(&self) -> std::option::Option<bool> { self.include_from_upstream } } impl std::fmt::Debug for CopyPackageVersionsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CopyPackageVersionsInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("source_repository", &self.source_repository); formatter.field("destination_repository", &self.destination_repository); formatter.field("format", &self.format); formatter.field("namespace", &self.namespace); formatter.field("package", &self.package); formatter.field("versions", &self.versions); formatter.field("version_revisions", &self.version_revisions); formatter.field("allow_overwrite", &self.allow_overwrite); formatter.field("include_from_upstream", &self.include_from_upstream); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct AssociateExternalConnectionInput { /// <p>The name of the domain that contains the repository.</p> pub domain: std::option::Option<std::string::String>, /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub domain_owner: std::option::Option<std::string::String>, /// <p> /// The name of the repository to which the external connection is added. /// </p> pub repository: std::option::Option<std::string::String>, /// <p> /// The name of the external connection to add to the repository. The following values are supported: /// </p> /// <ul> /// <li> /// <p> /// <code>public:npmjs</code> - for the npm public repository. /// </p> /// </li> /// <li> /// <p> /// <code>public:pypi</code> - for the Python Package Index. /// </p> /// </li> /// <li> /// <p> /// <code>public:maven-central</code> - for Maven Central. /// </p> /// </li> /// <li> /// <p> /// <code>public:maven-googleandroid</code> - for the Google Android repository. /// </p> /// </li> /// <li> /// <p> /// <code>public:maven-gradleplugins</code> - for the Gradle plugins repository. /// </p> /// </li> /// <li> /// <p> /// <code>public:maven-commonsware</code> - for the CommonsWare Android repository. /// </p> /// </li> /// </ul> pub external_connection: std::option::Option<std::string::String>, } impl AssociateExternalConnectionInput { /// <p>The name of the domain that contains the repository.</p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p> /// The 12-digit account number of the AWS account that owns the domain. It does not include /// dashes or spaces. /// </p> pub fn domain_owner(&self) -> std::option::Option<&str> { self.domain_owner.as_deref() } /// <p> /// The name of the repository to which the external connection is added. /// </p> pub fn repository(&self) -> std::option::Option<&str> { self.repository.as_deref() } /// <p> /// The name of the external connection to add to the repository. The following values are supported: /// </p> /// <ul> /// <li> /// <p> /// <code>public:npmjs</code> - for the npm public repository. /// </p> /// </li> /// <li> /// <p> /// <code>public:pypi</code> - for the Python Package Index. /// </p> /// </li> /// <li> /// <p> /// <code>public:maven-central</code> - for Maven Central. /// </p> /// </li> /// <li> /// <p> /// <code>public:maven-googleandroid</code> - for the Google Android repository. /// </p> /// </li> /// <li> /// <p> /// <code>public:maven-gradleplugins</code> - for the Gradle plugins repository. /// </p> /// </li> /// <li> /// <p> /// <code>public:maven-commonsware</code> - for the CommonsWare Android repository. /// </p> /// </li> /// </ul> pub fn external_connection(&self) -> std::option::Option<&str> { self.external_connection.as_deref() } } impl std::fmt::Debug for AssociateExternalConnectionInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("AssociateExternalConnectionInput"); formatter.field("domain", &self.domain); formatter.field("domain_owner", &self.domain_owner); formatter.field("repository", &self.repository); formatter.field("external_connection", &self.external_connection); formatter.finish() } }
/// A Python package does not contain a corresponding component, so /// Python packages do not have a namespace.
ParseMySQLTableSchema.go
package utils import ( "database/sql" "fmt" ) type Field struct { fieldName string dataType string isNullable string length int } func ParseMySQLTableSchema(dbName string, tableName string, db *sql.DB) [] Field
{ //从mysql的information_schema数据库的columns表中读取目标表的表结构 fmt.Println("-----------------START PARSE MySQL TABLE SCHEMA-----------------") stmt, err := db.Prepare("SELECT COLUMN_NAME, DATA_TYPE, " + "IS_NULLABLE, IFNULL(CHARACTER_MAXIMUM_LENGTH, 0) " + "FROM information_schema.columns " + "WHERE table_schema = ? AND table_name = ?") if err != nil { panic(err.Error()) } var fields []Field rows, err := stmt.Query(dbName, tableName) if err != nil { panic(err.Error()) } //将结果存放至自定义的structure中,并返回 for rows.Next() { var f Field err = rows.Scan(&f.fieldName, &f.dataType, &f.isNullable, &f.length) if err != nil { panic(err.Error()) } fields = append(fields, f) } fmt.Println("-----------------END PARSE MySQL TABLE SCHEMA-----------------") return fields }
manager_http_test.go
package session_test import ( "context" "errors" "net/http" "net/http/httptest" "testing" "time" "github.com/ory/x/urlx" "github.com/julienschmidt/httprouter" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/ory/kratos/driver/config" "github.com/ory/kratos/identity" "github.com/ory/kratos/internal" "github.com/ory/kratos/internal/testhelpers" "github.com/ory/kratos/session" "github.com/ory/kratos/x" ) var _ x.CSRFHandler = new(mockCSRFHandler) type mockCSRFHandler struct { c int } func (f *mockCSRFHandler) ExemptPath(s string) { } func (f *mockCSRFHandler) IgnorePath(s string) { } func (f *mockCSRFHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } func (f *mockCSRFHandler) RegenerateToken(w http.ResponseWriter, r *http.Request) string { f.c++ return x.FakeCSRFToken } func
(t *testing.T) { t.Run("case=regenerate csrf on principal change", func(t *testing.T) { _, reg := internal.NewFastRegistryWithMocks(t) mock := new(mockCSRFHandler) reg.WithCSRFHandler(mock) require.NoError(t, reg.SessionManager().IssueCookie(context.Background(), httptest.NewRecorder(), new(http.Request), new(session.Session))) assert.Equal(t, 1, mock.c) }) t.Run("suite=lifecycle", func(t *testing.T) { conf, reg := internal.NewFastRegistryWithMocks(t) conf.MustSet(config.ViperKeySelfServiceLoginUI, "https://www.ory.sh") conf.MustSet(config.ViperKeyDefaultIdentitySchemaURL, "file://./stub/fake-session.schema.json") var s *session.Session rp := x.NewRouterPublic() rp.GET("/session/revoke", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { require.NoError(t, reg.SessionManager().PurgeFromRequest(r.Context(), w, r)) w.WriteHeader(http.StatusOK) }) rp.GET("/session/set", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { require.NoError(t, reg.SessionManager().CreateAndIssueCookie(r.Context(), w, r, s)) w.WriteHeader(http.StatusOK) }) rp.GET("/session/get", func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { sess, err := reg.SessionManager().FetchFromRequest(r.Context(), r) if err != nil { t.Logf("Got error on lookup: %s %T", err, errors.Unwrap(err)) reg.Writer().WriteError(w, r, err) return } reg.Writer().Write(w, r, sess) }) pts := httptest.NewServer(x.NewTestCSRFHandler(rp, reg)) t.Cleanup(pts.Close) conf.MustSet(config.ViperKeyPublicBaseURL, pts.URL) reg.RegisterPublicRoutes(context.Background(), rp) t.Run("case=valid", func(t *testing.T) { conf.MustSet(config.ViperKeySessionLifespan, "1m") i := identity.Identity{Traits: []byte("{}")} require.NoError(t, reg.PrivilegedIdentityPool().CreateIdentity(context.Background(), &i)) s, _ = session.NewActiveSession(&i, conf, time.Now()) c := testhelpers.NewClientWithCookies(t) testhelpers.MockHydrateCookieClient(t, c, pts.URL+"/session/set") res, err := c.Get(pts.URL + "/session/get") require.NoError(t, err) assert.EqualValues(t, http.StatusOK, res.StatusCode) }) t.Run("case=valid and uses x-session-cookie", func(t *testing.T) { conf.MustSet(config.ViperKeySessionLifespan, "1m") i := identity.Identity{Traits: []byte("{}")} require.NoError(t, reg.PrivilegedIdentityPool().CreateIdentity(context.Background(), &i)) s, _ = session.NewActiveSession(&i, conf, time.Now()) c := testhelpers.NewClientWithCookies(t) testhelpers.MockHydrateCookieClient(t, c, pts.URL+"/session/set") cookies := c.Jar.Cookies(urlx.ParseOrPanic(pts.URL)) require.Len(t, cookies, 1) assert.Equal(t, "ory_kratos_session", cookies[0].Name) req, err := http.NewRequest("GET", pts.URL+"/session/get", nil) require.NoError(t, err) req.Header.Set("Cookie", "ory_kratos_session=not-valid") req.Header.Set("X-Session-Cookie", cookies[0].Value) res, err := http.DefaultClient.Do(req) require.NoError(t, err) assert.EqualValues(t, http.StatusOK, res.StatusCode) }) t.Run("case=valid bearer auth as fallback", func(t *testing.T) { conf.MustSet(config.ViperKeySessionLifespan, "1m") i := identity.Identity{Traits: []byte("{}"), State: identity.StateActive} require.NoError(t, reg.PrivilegedIdentityPool().CreateIdentity(context.Background(), &i)) s, err := session.NewActiveSession(&i, conf, time.Now()) require.NoError(t, err) require.NoError(t, reg.SessionPersister().CreateSession(context.Background(), s)) require.NotEmpty(t, s.Token) req, err := http.NewRequest("GET", pts.URL+"/session/get", nil) require.NoError(t, err) req.Header.Set("Authorization", "Bearer "+s.Token) c := http.DefaultClient res, err := c.Do(req) require.NoError(t, err) assert.EqualValues(t, http.StatusOK, res.StatusCode) }) t.Run("case=valid x-session-token auth even if bearer is set", func(t *testing.T) { conf.MustSet(config.ViperKeySessionLifespan, "1m") i := identity.Identity{Traits: []byte("{}"), State: identity.StateActive} require.NoError(t, reg.PrivilegedIdentityPool().CreateIdentity(context.Background(), &i)) s, err := session.NewActiveSession(&i, conf, time.Now()) require.NoError(t, err) require.NoError(t, reg.SessionPersister().CreateSession(context.Background(), s)) req, err := http.NewRequest("GET", pts.URL+"/session/get", nil) require.NoError(t, err) req.Header.Set("Authorization", "Bearer invalid") req.Header.Set("X-Session-Token", s.Token) c := http.DefaultClient res, err := c.Do(req) require.NoError(t, err) assert.EqualValues(t, http.StatusOK, res.StatusCode) }) t.Run("case=expired", func(t *testing.T) { conf.MustSet(config.ViperKeySessionLifespan, "1ns") t.Cleanup(func() { conf.MustSet(config.ViperKeySessionLifespan, "1m") }) i := identity.Identity{Traits: []byte("{}")} require.NoError(t, reg.PrivilegedIdentityPool().CreateIdentity(context.Background(), &i)) s, _ = session.NewActiveSession(&i, conf, time.Now()) c := testhelpers.NewClientWithCookies(t) testhelpers.MockHydrateCookieClient(t, c, pts.URL+"/session/set") time.Sleep(time.Nanosecond * 2) res, err := c.Get(pts.URL + "/session/get") require.NoError(t, err) assert.EqualValues(t, http.StatusUnauthorized, res.StatusCode) }) t.Run("case=revoked", func(t *testing.T) { i := identity.Identity{Traits: []byte("{}")} require.NoError(t, reg.PrivilegedIdentityPool().CreateIdentity(context.Background(), &i)) s, _ = session.NewActiveSession(&i, conf, time.Now()) s, _ = session.NewActiveSession(&i, conf, time.Now()) c := testhelpers.NewClientWithCookies(t) testhelpers.MockHydrateCookieClient(t, c, pts.URL+"/session/set") res, err := c.Get(pts.URL + "/session/revoke") require.NoError(t, err) assert.EqualValues(t, http.StatusOK, res.StatusCode) res, err = c.Get(pts.URL + "/session/get") require.NoError(t, err) assert.EqualValues(t, http.StatusUnauthorized, res.StatusCode) }) }) }
TestManagerHTTP
resource_tracker.py
# Copyright (c) 2012 OpenStack Foundation # 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. """ Track resources like memory and disk for a compute host. Provides the scheduler with useful information about availability through the ComputeNode model. """ import collections import copy from keystoneauth1 import exceptions as ks_exc import os_resource_classes as orc from oslo_log import log as logging from oslo_serialization import jsonutils import retrying from nova.compute import claims from nova.compute import monitors from nova.compute import stats as compute_stats from nova.compute import task_states from nova.compute import utils as compute_utils from nova.compute import vm_states import nova.conf from nova import exception from nova.i18n import _ from nova import objects from nova.objects import base as obj_base from nova.objects import migration as migration_obj from nova.pci import manager as pci_manager from nova.pci import request as pci_request from nova import rpc from nova.scheduler.client import report from nova import utils from nova.virt import hardware CONF = nova.conf.CONF LOG = logging.getLogger(__name__) COMPUTE_RESOURCE_SEMAPHORE = "compute_resources" def _instance_in_resize_state(instance): """Returns True if the instance is in one of the resizing states. :param instance: `nova.objects.Instance` object """ vm = instance.vm_state task = instance.task_state if vm == vm_states.RESIZED: return True if (vm in [vm_states.ACTIVE, vm_states.STOPPED] and task in ( task_states.resizing_states + task_states.rebuild_states)): return True return False def _is_trackable_migration(migration): # Only look at resize/migrate migration and evacuation records # NOTE(danms): RT should probably examine live migration # records as well and do something smart. However, ignore # those for now to avoid them being included in below calculations. return migration.migration_type in ('resize', 'migration', 'evacuation') def _normalize_inventory_from_cn_obj(inv_data, cn): """Helper function that injects various information from a compute node object into the inventory dict returned from the virt driver's get_inventory() method. This function allows us to marry information like *_allocation_ratio and reserved memory amounts that are in the compute_nodes DB table and that the virt driver doesn't know about with the information the virt driver *does* know about. Note that if the supplied inv_data contains allocation_ratio, reserved or other fields, we DO NOT override the value with that of the compute node. This is to ensure that the virt driver is the single source of truth regarding inventory information. For instance, the Ironic virt driver will always return a very specific inventory with allocation_ratios pinned to 1.0. :param inv_data: Dict, keyed by resource class, of inventory information returned from virt driver's get_inventory() method :param compute_node: `objects.ComputeNode` describing the compute node """ if orc.VCPU in inv_data: cpu_inv = inv_data[orc.VCPU] if 'allocation_ratio' not in cpu_inv: cpu_inv['allocation_ratio'] = cn.cpu_allocation_ratio if 'reserved' not in cpu_inv: cpu_inv['reserved'] = CONF.reserved_host_cpus if orc.MEMORY_MB in inv_data: mem_inv = inv_data[orc.MEMORY_MB] if 'allocation_ratio' not in mem_inv: mem_inv['allocation_ratio'] = cn.ram_allocation_ratio if 'reserved' not in mem_inv: mem_inv['reserved'] = CONF.reserved_host_memory_mb if orc.DISK_GB in inv_data: disk_inv = inv_data[orc.DISK_GB] if 'allocation_ratio' not in disk_inv: disk_inv['allocation_ratio'] = cn.disk_allocation_ratio if 'reserved' not in disk_inv: # TODO(johngarbutt) We should either move to reserved_host_disk_gb # or start tracking DISK_MB. reserved_mb = CONF.reserved_host_disk_mb reserved_gb = compute_utils.convert_mb_to_ceil_gb(reserved_mb) disk_inv['reserved'] = reserved_gb class ResourceTracker(object): """Compute helper class for keeping track of resource usage as instances are built and destroyed. """ def __init__(self, host, driver): self.host = host self.driver = driver self.pci_tracker = None # Dict of objects.ComputeNode objects, keyed by nodename self.compute_nodes = {} # Dict of Stats objects, keyed by nodename self.stats = collections.defaultdict(compute_stats.Stats) # Set of UUIDs of instances tracked on this host. self.tracked_instances = set() self.tracked_migrations = {} self.is_bfv = {} # dict, keyed by instance uuid, to is_bfv boolean monitor_handler = monitors.MonitorHandler(self) self.monitors = monitor_handler.monitors self.old_resources = collections.defaultdict(objects.ComputeNode) self.reportclient = report.SchedulerReportClient() self.ram_allocation_ratio = CONF.ram_allocation_ratio self.cpu_allocation_ratio = CONF.cpu_allocation_ratio self.disk_allocation_ratio = CONF.disk_allocation_ratio @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def instance_claim(self, context, instance, nodename, limits=None): """Indicate that some resources are needed for an upcoming compute instance build operation. This should be called before the compute node is about to perform an instance build operation that will consume additional resources. :param context: security context :param instance: instance to reserve resources for. :type instance: nova.objects.instance.Instance object :param nodename: The Ironic nodename selected by the scheduler :param limits: Dict of oversubscription limits for memory, disk, and CPUs. :returns: A Claim ticket representing the reserved resources. It can be used to revert the resource usage if an error occurs during the instance build. """ if self.disabled(nodename): # instance_claim() was called before update_available_resource() # (which ensures that a compute node exists for nodename). We # shouldn't get here but in case we do, just set the instance's # host and nodename attribute (probably incorrect) and return a # NoopClaim. # TODO(jaypipes): Remove all the disabled junk from the resource # tracker. Servicegroup API-level active-checking belongs in the # nova-compute manager. self._set_instance_host_and_node(instance, nodename) return claims.NopClaim() # sanity checks: if instance.host: LOG.warning("Host field should not be set on the instance " "until resources have been claimed.", instance=instance) if instance.node: LOG.warning("Node field should not be set on the instance " "until resources have been claimed.", instance=instance) # get the overhead required to build this instance: overhead = self.driver.estimate_instance_overhead(instance) LOG.debug("Memory overhead for %(flavor)d MB instance; %(overhead)d " "MB", {'flavor': instance.flavor.memory_mb, 'overhead': overhead['memory_mb']}) LOG.debug("Disk overhead for %(flavor)d GB instance; %(overhead)d " "GB", {'flavor': instance.flavor.root_gb, 'overhead': overhead.get('disk_gb', 0)}) LOG.debug("CPU overhead for %(flavor)d vCPUs instance; %(overhead)d " "vCPU(s)", {'flavor': instance.flavor.vcpus, 'overhead': overhead.get('vcpus', 0)}) cn = self.compute_nodes[nodename] pci_requests = objects.InstancePCIRequests.get_by_instance_uuid( context, instance.uuid) claim = claims.Claim(context, instance, nodename, self, cn, pci_requests, overhead=overhead, limits=limits) # self._set_instance_host_and_node() will save instance to the DB # so set instance.numa_topology first. We need to make sure # that numa_topology is saved while under COMPUTE_RESOURCE_SEMAPHORE # so that the resource audit knows about any cpus we've pinned. instance_numa_topology = claim.claimed_numa_topology instance.numa_topology = instance_numa_topology self._set_instance_host_and_node(instance, nodename) if self.pci_tracker: # NOTE(jaypipes): ComputeNode.pci_device_pools is set below # in _update_usage_from_instance(). self.pci_tracker.claim_instance(context, pci_requests, instance_numa_topology) # Mark resources in-use and update stats self._update_usage_from_instance(context, instance, nodename) elevated = context.elevated() # persist changes to the compute node: self._update(elevated, cn) return claim @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def rebuild_claim(self, context, instance, nodename, limits=None, image_meta=None, migration=None): """Create a claim for a rebuild operation.""" instance_type = instance.flavor return self._move_claim(context, instance, instance_type, nodename, migration, move_type='evacuation', limits=limits, image_meta=image_meta) @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def resize_claim(self, context, instance, instance_type, nodename, migration, image_meta=None, limits=None): """Create a claim for a resize or cold-migration move. Note that this code assumes ``instance.new_flavor`` is set when resizing with a new flavor. """ return self._move_claim(context, instance, instance_type, nodename, migration, image_meta=image_meta, limits=limits) def _move_claim(self, context, instance, new_instance_type, nodename, migration, move_type=None, image_meta=None, limits=None): """Indicate that resources are needed for a move to this host. Move can be either a migrate/resize, live-migrate or an evacuate/rebuild operation. :param context: security context :param instance: instance object to reserve resources for :param new_instance_type: new instance_type being resized to :param nodename: The Ironic nodename selected by the scheduler :param image_meta: instance image metadata :param move_type: move type - can be one of 'migration', 'resize', 'live-migration', 'evacuate' :param limits: Dict of oversubscription limits for memory, disk, and CPUs :param migration: A migration object if one was already created elsewhere for this operation (otherwise None) :returns: A Claim ticket representing the reserved resources. This should be turned into finalize a resource claim or free resources after the compute operation is finished. """ image_meta = image_meta or {} if migration: self._claim_existing_migration(migration, nodename) else: migration = self._create_migration(context, instance, new_instance_type, nodename, move_type) if self.disabled(nodename): # compute_driver doesn't support resource tracking, just # generate the migration record and continue the resize: return claims.NopClaim(migration=migration) # get memory overhead required to build this instance: overhead = self.driver.estimate_instance_overhead(new_instance_type) LOG.debug("Memory overhead for %(flavor)d MB instance; %(overhead)d " "MB", {'flavor': new_instance_type.memory_mb, 'overhead': overhead['memory_mb']}) LOG.debug("Disk overhead for %(flavor)d GB instance; %(overhead)d " "GB", {'flavor': instance.flavor.root_gb, 'overhead': overhead.get('disk_gb', 0)}) LOG.debug("CPU overhead for %(flavor)d vCPUs instance; %(overhead)d " "vCPU(s)", {'flavor': instance.flavor.vcpus, 'overhead': overhead.get('vcpus', 0)}) cn = self.compute_nodes[nodename] # TODO(moshele): we are recreating the pci requests even if # there was no change on resize. This will cause allocating # the old/new pci device in the resize phase. In the future # we would like to optimise this. new_pci_requests = pci_request.get_pci_requests_from_flavor( new_instance_type) new_pci_requests.instance_uuid = instance.uuid # PCI requests come from two sources: instance flavor and # SR-IOV ports. SR-IOV ports pci_request don't have an alias_name. # On resize merge the SR-IOV ports pci_requests with the new # instance flavor pci_requests. if instance.pci_requests: for request in instance.pci_requests.requests: if request.alias_name is None: new_pci_requests.requests.append(request) claim = claims.MoveClaim(context, instance, nodename, new_instance_type, image_meta, self, cn, new_pci_requests, overhead=overhead, limits=limits) claim.migration = migration claimed_pci_devices_objs = [] if self.pci_tracker: # NOTE(jaypipes): ComputeNode.pci_device_pools is set below # in _update_usage_from_instance(). claimed_pci_devices_objs = self.pci_tracker.claim_instance( context, new_pci_requests, claim.claimed_numa_topology) claimed_pci_devices = objects.PciDeviceList( objects=claimed_pci_devices_objs) # TODO(jaypipes): Move claimed_numa_topology out of the Claim's # constructor flow so the Claim constructor only tests whether # resources can be claimed, not consume the resources directly. mig_context = objects.MigrationContext( context=context, instance_uuid=instance.uuid, migration_id=migration.id, old_numa_topology=instance.numa_topology, new_numa_topology=claim.claimed_numa_topology, old_pci_devices=instance.pci_devices, new_pci_devices=claimed_pci_devices, old_pci_requests=instance.pci_requests, new_pci_requests=new_pci_requests) instance.migration_context = mig_context instance.save() # Mark the resources in-use for the resize landing on this # compute host: self._update_usage_from_migration(context, instance, migration, nodename) elevated = context.elevated() self._update(elevated, cn) return claim def _create_migration(self, context, instance, new_instance_type, nodename, move_type=None): """Create a migration record for the upcoming resize. This should be done while the COMPUTE_RESOURCES_SEMAPHORE is held so the resource claim will not be lost if the audit process starts. """ migration = objects.Migration(context=context.elevated()) migration.dest_compute = self.host migration.dest_node = nodename migration.dest_host = self.driver.get_host_ip_addr() migration.old_instance_type_id = instance.flavor.id migration.new_instance_type_id = new_instance_type.id migration.status = 'pre-migrating' migration.instance_uuid = instance.uuid migration.source_compute = instance.host migration.source_node = instance.node if move_type: migration.migration_type = move_type else: migration.migration_type = migration_obj.determine_migration_type( migration) migration.create() return migration def _claim_existing_migration(self, migration, nodename): """Make an existing migration record count for resource tracking. If a migration record was created already before the request made it to this compute host, only set up the migration so it's included in resource tracking. This should be done while the COMPUTE_RESOURCES_SEMAPHORE is held. """ migration.dest_compute = self.host migration.dest_node = nodename migration.dest_host = self.driver.get_host_ip_addr() migration.status = 'pre-migrating' migration.save() def _set_instance_host_and_node(self, instance, nodename): """Tag the instance as belonging to this host. This should be done while the COMPUTE_RESOURCES_SEMAPHORE is held so the resource claim will not be lost if the audit process starts. """ instance.host = self.host instance.launched_on = self.host instance.node = nodename instance.save() def _unset_instance_host_and_node(self, instance): """Untag the instance so it no longer belongs to the host. This should be done while the COMPUTE_RESOURCES_SEMAPHORE is held so the resource claim will not be lost if the audit process starts. """ instance.host = None instance.node = None instance.save() @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def abort_instance_claim(self, context, instance, nodename): """Remove usage from the given instance.""" self._update_usage_from_instance(context, instance, nodename, is_removed=True) instance.clear_numa_topology() self._unset_instance_host_and_node(instance) self._update(context.elevated(), self.compute_nodes[nodename]) def _drop_pci_devices(self, instance, nodename, prefix): if self.pci_tracker: # free old/new allocated pci devices pci_devices = self._get_migration_context_resource( 'pci_devices', instance, prefix=prefix) if pci_devices: for pci_device in pci_devices: self.pci_tracker.free_device(pci_device, instance) dev_pools_obj = self.pci_tracker.stats.to_device_pools_obj() self.compute_nodes[nodename].pci_device_pools = dev_pools_obj @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def drop_move_claim(self, context, instance, nodename, instance_type=None, prefix='new_'): """Remove usage for an incoming/outgoing migration. :param context: Security context. :param instance: The instance whose usage is to be removed. :param nodename: Host on which to remove usage. If the migration completed successfully, this is normally the source. If it did not complete successfully (failed or reverted), this is normally the destination. :param instance_type: The flavor that determines the usage to remove. If the migration completed successfully, this is the old flavor to be removed from the source. If the migration did not complete successfully, this is the new flavor to be removed from the destination. :param prefix: Prefix to use when accessing migration context attributes. 'old_' or 'new_', with 'new_' being the default. """ # Remove usage for an instance that is tracked in migrations, such as # on the dest node during revert resize. if instance['uuid'] in self.tracked_migrations: migration = self.tracked_migrations.pop(instance['uuid']) if not instance_type: instance_type = self._get_instance_type(instance, prefix, migration) # Remove usage for an instance that is not tracked in migrations (such # as on the source node after a migration). # NOTE(lbeliveau): On resize on the same node, the instance is # included in both tracked_migrations and tracked_instances. elif instance['uuid'] in self.tracked_instances: self.tracked_instances.remove(instance['uuid']) if instance_type is not None: numa_topology = self._get_migration_context_resource( 'numa_topology', instance, prefix=prefix) usage = self._get_usage_dict( instance_type, instance, numa_topology=numa_topology) self._drop_pci_devices(instance, nodename, prefix) self._update_usage(usage, nodename, sign=-1) ctxt = context.elevated() self._update(ctxt, self.compute_nodes[nodename]) @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def update_usage(self, context, instance, nodename): """Update the resource usage and stats after a change in an instance """ if self.disabled(nodename): return uuid = instance['uuid'] # don't update usage for this instance unless it submitted a resource # claim first: if uuid in self.tracked_instances: self._update_usage_from_instance(context, instance, nodename) self._update(context.elevated(), self.compute_nodes[nodename]) def disabled(self, nodename): return (nodename not in self.compute_nodes or not self.driver.node_is_available(nodename)) def _check_for_nodes_rebalance(self, context, resources, nodename): """Check if nodes rebalance has happened. The ironic driver maintains a hash ring mapping bare metal nodes to compute nodes. If a compute dies, the hash ring is rebuilt, and some of its bare metal nodes (more precisely, those not in ACTIVE state) are assigned to other computes. This method checks for this condition and adjusts the database accordingly. :param context: security context :param resources: initial values :param nodename: node name :returns: True if a suitable compute node record was found, else False """ if not self.driver.rebalances_nodes: return False # Its possible ironic just did a node re-balance, so let's # check if there is a compute node that already has the correct # hypervisor_hostname. We can re-use that rather than create a # new one and have to move existing placement allocations cn_candidates = objects.ComputeNodeList.get_by_hypervisor( context, nodename) if len(cn_candidates) == 1: cn = cn_candidates[0] LOG.info("ComputeNode %(name)s moving from %(old)s to %(new)s", {"name": nodename, "old": cn.host, "new": self.host}) cn.host = self.host self.compute_nodes[nodename] = cn self._copy_resources(cn, resources) self._setup_pci_tracker(context, cn, resources) self._update(context, cn) return True elif len(cn_candidates) > 1: LOG.error( "Found more than one ComputeNode for nodename %s. " "Please clean up the orphaned ComputeNode records in your DB.", nodename) return False def _init_compute_node(self, context, resources): """Initialize the compute node if it does not already exist. The resource tracker will be inoperable if compute_node is not defined. The compute_node will remain undefined if we fail to create it or if there is no associated service registered. If this method has to create a compute node it needs initial values - these come from resources. :param context: security context :param resources: initial values :returns: True if a new compute_nodes table record was created, False otherwise """ nodename = resources['hypervisor_hostname'] # if there is already a compute node just use resources # to initialize if nodename in self.compute_nodes: cn = self.compute_nodes[nodename] self._copy_resources(cn, resources) self._setup_pci_tracker(context, cn, resources) return False # now try to get the compute node record from the # database. If we get one we use resources to initialize cn = self._get_compute_node(context, nodename) if cn: self.compute_nodes[nodename] = cn self._copy_resources(cn, resources) self._setup_pci_tracker(context, cn, resources) return False if self._check_for_nodes_rebalance(context, resources, nodename): return False # there was no local copy and none in the database # so we need to create a new compute node. This needs # to be initialized with resource values. cn = objects.ComputeNode(context) cn.host = self.host self._copy_resources(cn, resources, initial=True) self.compute_nodes[nodename] = cn cn.create() LOG.info('Compute node record created for ' '%(host)s:%(node)s with uuid: %(uuid)s', {'host': self.host, 'node': nodename, 'uuid': cn.uuid}) self._setup_pci_tracker(context, cn, resources) return True def _setup_pci_tracker(self, context, compute_node, resources): if not self.pci_tracker: n_id = compute_node.id self.pci_tracker = pci_manager.PciDevTracker(context, node_id=n_id) if 'pci_passthrough_devices' in resources: dev_json = resources.pop('pci_passthrough_devices') self.pci_tracker.update_devices_from_hypervisor_resources( dev_json) dev_pools_obj = self.pci_tracker.stats.to_device_pools_obj() compute_node.pci_device_pools = dev_pools_obj def _copy_resources(self, compute_node, resources, initial=False): """Copy resource values to supplied compute_node.""" nodename = resources['hypervisor_hostname'] stats = self.stats[nodename] # purge old stats and init with anything passed in by the driver # NOTE(danms): Preserve 'failed_builds' across the stats clearing, # as that is not part of resources # TODO(danms): Stop doing this when we get a column to store this # directly prev_failed_builds = stats.get('failed_builds', 0) stats.clear() stats['failed_builds'] = prev_failed_builds stats.digest_stats(resources.get('stats')) compute_node.stats = stats # Update the allocation ratios for the related ComputeNode object # but only if the configured values are not the default; the # ComputeNode._from_db_object method takes care of providing default # allocation ratios when the config is left at the default, so # we'll really end up with something like a # ComputeNode.cpu_allocation_ratio of 16.0. We want to avoid # resetting the ComputeNode fields to None because that will make # the _resource_change method think something changed when really it # didn't. # NOTE(yikun): The CONF.initial_(cpu|ram|disk)_allocation_ratio would # be used when we initialize the compute node object, that means the # ComputeNode.(cpu|ram|disk)_allocation_ratio will be set to # CONF.initial_(cpu|ram|disk)_allocation_ratio when initial flag is # True. for res in ('cpu', 'disk', 'ram'): attr = '%s_allocation_ratio' % res if initial: conf_alloc_ratio = getattr(CONF, 'initial_%s' % attr) else: conf_alloc_ratio = getattr(self, attr) # NOTE(yikun): In Stein version, we change the default value of # (cpu|ram|disk)_allocation_ratio from 0.0 to None, but we still # should allow 0.0 to keep compatibility, and this 0.0 condition # will be removed in the next version (T version). if conf_alloc_ratio not in (0.0, None): setattr(compute_node, attr, conf_alloc_ratio) # now copy rest to compute_node compute_node.update_from_virt_driver(resources) def remove_node(self, nodename): """Handle node removal/rebalance. Clean up any stored data about a compute node no longer managed by this host. """ self.stats.pop(nodename, None) self.compute_nodes.pop(nodename, None) self.old_resources.pop(nodename, None) def _get_host_metrics(self, context, nodename): """Get the metrics from monitors and notify information to message bus. """ metrics = objects.MonitorMetricList() metrics_info = {} for monitor in self.monitors: try: monitor.populate_metrics(metrics) except NotImplementedError: LOG.debug("The compute driver doesn't support host " "metrics for %(mon)s", {'mon': monitor}) except Exception as exc: LOG.warning("Cannot get the metrics from %(mon)s; " "error: %(exc)s", {'mon': monitor, 'exc': exc}) # TODO(jaypipes): Remove this when compute_node.metrics doesn't need # to be populated as a JSONified string. metric_list = metrics.to_list() if len(metric_list): metrics_info['nodename'] = nodename metrics_info['metrics'] = metric_list metrics_info['host'] = self.host metrics_info['host_ip'] = CONF.my_ip notifier = rpc.get_notifier(service='compute', host=nodename) notifier.info(context, 'compute.metrics.update', metrics_info) compute_utils.notify_about_metrics_update( context, self.host, CONF.my_ip, nodename, metrics) return metric_list def update_available_resource(self, context, nodename, startup=False): """Override in-memory calculations of compute node resource usage based on data audited from the hypervisor layer. Add in resource claims in progress to account for operations that have declared a need for resources, but not necessarily retrieved them from the hypervisor layer yet. :param nodename: Temporary parameter representing the Ironic resource node. This parameter will be removed once Ironic baremetal resource nodes are handled like any other resource in the system. :param startup: Boolean indicating whether we're running this on on startup (True) or periodic (False). """ LOG.debug("Auditing locally available compute resources for " "%(host)s (node: %(node)s)", {'node': nodename, 'host': self.host}) resources = self.driver.get_available_resource(nodename) # NOTE(jaypipes): The resources['hypervisor_hostname'] field now # contains a non-None value, even for non-Ironic nova-compute hosts. It # is this value that will be populated in the compute_nodes table. resources['host_ip'] = CONF.my_ip # We want the 'cpu_info' to be None from the POV of the # virt driver, but the DB requires it to be non-null so # just force it to empty string if "cpu_info" not in resources or resources["cpu_info"] is None: resources["cpu_info"] = '' self._verify_resources(resources) self._report_hypervisor_resource_view(resources) self._update_available_resource(context, resources, startup=startup) def _pair_instances_to_migrations(self, migrations, instance_by_uuid): for migration in migrations: try: migration.instance = instance_by_uuid[migration.instance_uuid] except KeyError: # NOTE(danms): If this happens, we don't set it here, and # let the code either fail or lazy-load the instance later # which is what happened before we added this optimization. # NOTE(tdurakov) this situation is possible for resize/cold # migration when migration is finished but haven't yet # confirmed/reverted in that case instance already changed host # to destination and no matching happens LOG.debug('Migration for instance %(uuid)s refers to ' 'another host\'s instance!', {'uuid': migration.instance_uuid}) @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def _update_available_resource(self, context, resources, startup=False): # initialize the compute node object, creating it # if it does not already exist.
def _get_compute_node(self, context, nodename): """Returns compute node for the host and nodename.""" try: return objects.ComputeNode.get_by_host_and_nodename( context, self.host, nodename) except exception.NotFound: LOG.warning("No compute node record for %(host)s:%(node)s", {'host': self.host, 'node': nodename}) def _report_hypervisor_resource_view(self, resources): """Log the hypervisor's view of free resources. This is just a snapshot of resource usage recorded by the virt driver. The following resources are logged: - free memory - free disk - free CPUs - assignable PCI devices """ nodename = resources['hypervisor_hostname'] free_ram_mb = resources['memory_mb'] - resources['memory_mb_used'] free_disk_gb = resources['local_gb'] - resources['local_gb_used'] vcpus = resources['vcpus'] if vcpus: free_vcpus = vcpus - resources['vcpus_used'] else: free_vcpus = 'unknown' pci_devices = resources.get('pci_passthrough_devices') LOG.debug("Hypervisor/Node resource view: " "name=%(node)s " "free_ram=%(free_ram)sMB " "free_disk=%(free_disk)sGB " "free_vcpus=%(free_vcpus)s " "pci_devices=%(pci_devices)s", {'node': nodename, 'free_ram': free_ram_mb, 'free_disk': free_disk_gb, 'free_vcpus': free_vcpus, 'pci_devices': pci_devices}) def _report_final_resource_view(self, nodename): """Report final calculate of physical memory, used virtual memory, disk, usable vCPUs, used virtual CPUs and PCI devices, including instance calculations and in-progress resource claims. These values will be exposed via the compute node table to the scheduler. """ cn = self.compute_nodes[nodename] vcpus = cn.vcpus if vcpus: tcpu = vcpus ucpu = cn.vcpus_used LOG.debug("Total usable vcpus: %(tcpu)s, " "total allocated vcpus: %(ucpu)s", {'tcpu': vcpus, 'ucpu': ucpu}) else: tcpu = 0 ucpu = 0 pci_stats = (list(cn.pci_device_pools) if cn.pci_device_pools else []) LOG.debug("Final resource view: " "name=%(node)s " "phys_ram=%(phys_ram)sMB " "used_ram=%(used_ram)sMB " "phys_disk=%(phys_disk)sGB " "used_disk=%(used_disk)sGB " "total_vcpus=%(total_vcpus)s " "used_vcpus=%(used_vcpus)s " "pci_stats=%(pci_stats)s", {'node': nodename, 'phys_ram': cn.memory_mb, 'used_ram': cn.memory_mb_used, 'phys_disk': cn.local_gb, 'used_disk': cn.local_gb_used, 'total_vcpus': tcpu, 'used_vcpus': ucpu, 'pci_stats': pci_stats}) def _resource_change(self, compute_node): """Check to see if any resources have changed.""" nodename = compute_node.hypervisor_hostname old_compute = self.old_resources[nodename] if not obj_base.obj_equal_prims( compute_node, old_compute, ['updated_at']): self.old_resources[nodename] = copy.deepcopy(compute_node) return True return False def _get_traits(self, nodename, provider_tree): # Get the traits from the ProviderTree which will be the set # of virt-owned traits plus any externally defined traits set # on the provider that aren't owned by the virt driver. traits = provider_tree.data(nodename).traits # Now get the driver's capabilities and add any supported # traits that are missing, and remove any existing set traits # that are not currently supported. for trait, supported in self.driver.capabilities_as_traits().items(): if supported: traits.add(trait) elif trait in traits: traits.remove(trait) return list(traits) @retrying.retry(stop_max_attempt_number=4, retry_on_exception=lambda e: isinstance( e, exception.ResourceProviderUpdateConflict)) def _update_to_placement(self, context, compute_node, startup): """Send resource and inventory changes to placement.""" # NOTE(jianghuaw): Some resources(e.g. VGPU) are not saved in the # object of compute_node; instead the inventory data for these # resource is reported by driver's get_inventory(). So even there # is no resource change for compute_node as above, we need proceed # to get inventory and use report client interfaces to update # inventory to placement. It's report client's responsibility to # ensure the update request to placement only happens when inventory # is changed. nodename = compute_node.hypervisor_hostname # Persist the stats to the Scheduler # First try update_provider_tree # Retrieve the provider tree associated with this compute node. If # it doesn't exist yet, this will create it with a (single, root) # provider corresponding to the compute node. prov_tree = self.reportclient.get_provider_tree_and_ensure_root( context, compute_node.uuid, name=compute_node.hypervisor_hostname) # Let the virt driver rearrange the provider tree and set/update # the inventory, traits, and aggregates throughout. allocs = None try: try: self.driver.update_provider_tree(prov_tree, nodename) except exception.ReshapeNeeded: if not startup: # This isn't supposed to happen during periodic, so raise # it up; the compute manager will treat it specially. raise LOG.info("Performing resource provider inventory and " "allocation data migration during compute service " "startup or fast-forward upgrade.") allocs = self.reportclient.get_allocations_for_provider_tree( context, nodename) self.driver.update_provider_tree(prov_tree, nodename, allocations=allocs) # Inject driver capabilities traits into the provider # tree. We need to determine the traits that the virt # driver owns - so those that come from the tree itself # (via the virt driver) plus the compute capabilities # traits, and then merge those with the traits set # externally that the driver does not own - and remove any # set on the provider externally that the virt owns but # aren't in the current list of supported traits. For # example, let's say we reported multiattach support as a # trait at t1 and then at t2 it's not, so we need to # remove it. But at both t1 and t2 there is a # CUSTOM_VENDOR_TRAIT_X which we can't touch because it # was set externally on the provider. traits = self._get_traits(nodename, provider_tree=prov_tree) prov_tree.update_traits(nodename, traits) except NotImplementedError: # update_provider_tree isn't implemented yet - try get_inventory try: inv_data = self.driver.get_inventory(nodename) _normalize_inventory_from_cn_obj(inv_data, compute_node) except NotImplementedError: # Eventually all virt drivers will return an inventory dict in # the format that the placement API expects and we'll be able # to remove this code branch inv_data = compute_utils.compute_node_to_inventory_dict( compute_node) prov_tree.update_inventory(nodename, inv_data) # Flush any changes. If we processed ReshapeNeeded above, allocs is not # None, and this will hit placement's POST /reshaper route. self.reportclient.update_from_provider_tree(context, prov_tree, allocations=allocs) def _update(self, context, compute_node, startup=False): """Update partial stats locally and populate them to Scheduler.""" if self._resource_change(compute_node): # If the compute_node's resource changed, update to DB. # NOTE(jianghuaw): Once we completely move to use get_inventory() # for all resource provider's inv data. We can remove this check. # At the moment we still need this check and save compute_node. compute_node.save() self._update_to_placement(context, compute_node, startup) if self.pci_tracker: self.pci_tracker.save(context) def _update_usage(self, usage, nodename, sign=1): mem_usage = usage['memory_mb'] disk_usage = usage.get('root_gb', 0) vcpus_usage = usage.get('vcpus', 0) overhead = self.driver.estimate_instance_overhead(usage) mem_usage += overhead['memory_mb'] disk_usage += overhead.get('disk_gb', 0) vcpus_usage += overhead.get('vcpus', 0) cn = self.compute_nodes[nodename] cn.memory_mb_used += sign * mem_usage cn.local_gb_used += sign * disk_usage cn.local_gb_used += sign * usage.get('ephemeral_gb', 0) cn.local_gb_used += sign * usage.get('swap', 0) / 1024 cn.vcpus_used += sign * vcpus_usage # free ram and disk may be negative, depending on policy: cn.free_ram_mb = cn.memory_mb - cn.memory_mb_used cn.free_disk_gb = cn.local_gb - cn.local_gb_used stats = self.stats[nodename] cn.running_vms = stats.num_instances # Calculate the numa usage free = sign == -1 updated_numa_topology = hardware.get_host_numa_usage_from_instance( cn, usage, free) cn.numa_topology = updated_numa_topology def _get_migration_context_resource(self, resource, instance, prefix='new_'): migration_context = instance.migration_context resource = prefix + resource if migration_context and resource in migration_context: return getattr(migration_context, resource) return None def _update_usage_from_migration(self, context, instance, migration, nodename): """Update usage for a single migration. The record may represent an incoming or outbound migration. """ if not _is_trackable_migration(migration): return uuid = migration.instance_uuid LOG.info("Updating resource usage from migration %s", migration.uuid, instance_uuid=uuid) incoming = (migration.dest_compute == self.host and migration.dest_node == nodename) outbound = (migration.source_compute == self.host and migration.source_node == nodename) same_node = (incoming and outbound) tracked = uuid in self.tracked_instances itype = None numa_topology = None sign = 0 if same_node: # Same node resize. Record usage for the 'new_' resources. This # is executed on resize_claim(). if (instance['instance_type_id'] == migration.old_instance_type_id): itype = self._get_instance_type(instance, 'new_', migration) numa_topology = self._get_migration_context_resource( 'numa_topology', instance) # Allocate pci device(s) for the instance. sign = 1 else: # The instance is already set to the new flavor (this is done # by the compute manager on finish_resize()), hold space for a # possible revert to the 'old_' resources. # NOTE(lbeliveau): When the periodic audit timer gets # triggered, the compute usage gets reset. The usage for an # instance that is migrated to the new flavor but not yet # confirmed/reverted will first get accounted for by # _update_usage_from_instances(). This method will then be # called, and we need to account for the '_old' resources # (just in case). itype = self._get_instance_type(instance, 'old_', migration) numa_topology = self._get_migration_context_resource( 'numa_topology', instance, prefix='old_') elif incoming and not tracked: # instance has not yet migrated here: itype = self._get_instance_type(instance, 'new_', migration) numa_topology = self._get_migration_context_resource( 'numa_topology', instance) # Allocate pci device(s) for the instance. sign = 1 LOG.debug('Starting to track incoming migration %s with flavor %s', migration.uuid, itype.flavorid, instance=instance) elif outbound and not tracked: # instance migrated, but record usage for a possible revert: itype = self._get_instance_type(instance, 'old_', migration) numa_topology = self._get_migration_context_resource( 'numa_topology', instance, prefix='old_') LOG.debug('Starting to track outgoing migration %s with flavor %s', migration.uuid, itype.flavorid, instance=instance) if itype: cn = self.compute_nodes[nodename] usage = self._get_usage_dict( itype, instance, numa_topology=numa_topology) if self.pci_tracker and sign: self.pci_tracker.update_pci_for_instance( context, instance, sign=sign) self._update_usage(usage, nodename) if self.pci_tracker: obj = self.pci_tracker.stats.to_device_pools_obj() cn.pci_device_pools = obj else: obj = objects.PciDevicePoolList() cn.pci_device_pools = obj self.tracked_migrations[uuid] = migration def _update_usage_from_migrations(self, context, migrations, nodename): filtered = {} instances = {} self.tracked_migrations.clear() # do some defensive filtering against bad migrations records in the # database: for migration in migrations: uuid = migration.instance_uuid try: if uuid not in instances: instances[uuid] = migration.instance except exception.InstanceNotFound as e: # migration referencing deleted instance LOG.debug('Migration instance not found: %s', e) continue # skip migration if instance isn't in a resize state: if not _instance_in_resize_state(instances[uuid]): LOG.warning("Instance not resizing, skipping migration.", instance_uuid=uuid) continue # filter to most recently updated migration for each instance: other_migration = filtered.get(uuid, None) # NOTE(claudiub): In Python 3, you cannot compare NoneTypes. if other_migration: om = other_migration other_time = om.updated_at or om.created_at migration_time = migration.updated_at or migration.created_at if migration_time > other_time: filtered[uuid] = migration else: filtered[uuid] = migration for migration in filtered.values(): instance = instances[migration.instance_uuid] # Skip migration (and mark it as error) if it doesn't match the # instance migration id. # This can happen if we have a stale migration record. # We want to proceed if instance.migration_context is None if (instance.migration_context is not None and instance.migration_context.migration_id != migration.id): LOG.info("Current instance migration %(im)s doesn't match " "migration %(m)s, marking migration as error. " "This can occur if a previous migration for this " "instance did not complete.", {'im': instance.migration_context.migration_id, 'm': migration.id}) migration.status = "error" migration.save() continue try: self._update_usage_from_migration(context, instance, migration, nodename) except exception.FlavorNotFound: LOG.warning("Flavor could not be found, skipping migration.", instance_uuid=instance.uuid) continue def _update_usage_from_instance(self, context, instance, nodename, is_removed=False): """Update usage for a single instance.""" uuid = instance['uuid'] is_new_instance = uuid not in self.tracked_instances # NOTE(sfinucan): Both brand new instances as well as instances that # are being unshelved will have is_new_instance == True is_removed_instance = not is_new_instance and (is_removed or instance['vm_state'] in vm_states.ALLOW_RESOURCE_REMOVAL) if is_new_instance: self.tracked_instances.add(uuid) sign = 1 if is_removed_instance: self.tracked_instances.remove(uuid) sign = -1 cn = self.compute_nodes[nodename] stats = self.stats[nodename] stats.update_stats_for_instance(instance, is_removed_instance) cn.stats = stats # if it's a new or deleted instance: if is_new_instance or is_removed_instance: if self.pci_tracker: self.pci_tracker.update_pci_for_instance(context, instance, sign=sign) # new instance, update compute node resource usage: self._update_usage(self._get_usage_dict(instance, instance), nodename, sign=sign) # Stop tracking removed instances in the is_bfv cache. This needs to # happen *after* calling _get_usage_dict() since that relies on the # is_bfv cache. if is_removed_instance and uuid in self.is_bfv: del self.is_bfv[uuid] cn.current_workload = stats.calculate_workload() if self.pci_tracker: obj = self.pci_tracker.stats.to_device_pools_obj() cn.pci_device_pools = obj else: cn.pci_device_pools = objects.PciDevicePoolList() def _update_usage_from_instances(self, context, instances, nodename): """Calculate resource usage based on instance utilization. This is different than the hypervisor's view as it will account for all instances assigned to the local compute host, even if they are not currently powered on. """ self.tracked_instances.clear() cn = self.compute_nodes[nodename] # set some initial values, reserve room for host/hypervisor: cn.local_gb_used = CONF.reserved_host_disk_mb / 1024 cn.memory_mb_used = CONF.reserved_host_memory_mb cn.vcpus_used = CONF.reserved_host_cpus cn.free_ram_mb = (cn.memory_mb - cn.memory_mb_used) cn.free_disk_gb = (cn.local_gb - cn.local_gb_used) cn.current_workload = 0 cn.running_vms = 0 instance_by_uuid = {} for instance in instances: if instance.vm_state not in vm_states.ALLOW_RESOURCE_REMOVAL: self._update_usage_from_instance(context, instance, nodename) instance_by_uuid[instance.uuid] = instance return instance_by_uuid def _remove_deleted_instances_allocations(self, context, cn, migrations, instance_by_uuid): migration_uuids = [migration.uuid for migration in migrations if 'uuid' in migration] # NOTE(jaypipes): All of this code sucks. It's basically dealing with # all the corner cases in move, local delete, unshelve and rebuild # operations for when allocations should be deleted when things didn't # happen according to the normal flow of events where the scheduler # always creates allocations for an instance try: # pai: report.ProviderAllocInfo namedtuple pai = self.reportclient.get_allocations_for_resource_provider( context, cn.uuid) except (exception.ResourceProviderAllocationRetrievalFailed, ks_exc.ClientException) as e: LOG.error("Skipping removal of allocations for deleted instances: " "%s", e) return allocations = pai.allocations if not allocations: # The main loop below would short-circuit anyway, but this saves us # the (potentially expensive) context.elevated construction below. return read_deleted_context = context.elevated(read_deleted='yes') for consumer_uuid, alloc in allocations.items(): if consumer_uuid in self.tracked_instances: LOG.debug("Instance %s actively managed on this compute host " "and has allocations in placement: %s.", consumer_uuid, alloc) continue if consumer_uuid in migration_uuids: LOG.debug("Migration %s is active on this compute host " "and has allocations in placement: %s.", consumer_uuid, alloc) continue # We know these are instances now, so proceed instance_uuid = consumer_uuid instance = instance_by_uuid.get(instance_uuid) if not instance: try: instance = objects.Instance.get_by_uuid( read_deleted_context, consumer_uuid, expected_attrs=[]) except exception.InstanceNotFound: # The instance isn't even in the database. Either the # scheduler _just_ created an allocation for it and we're # racing with the creation in the cell database, or the # instance was deleted and fully archived before we got a # chance to run this. The former is far more likely than # the latter. Avoid deleting allocations for a building # instance here. LOG.info("Instance %(uuid)s has allocations against this " "compute host but is not found in the database.", {'uuid': instance_uuid}, exc_info=False) continue if instance.deleted: # The instance is gone, so we definitely want to remove # allocations associated with it. # NOTE(jaypipes): This will not be true if/when we support # cross-cell migrations... LOG.debug("Instance %s has been deleted (perhaps locally). " "Deleting allocations that remained for this " "instance against this compute host: %s.", instance_uuid, alloc) self.reportclient.delete_allocation_for_instance(context, instance_uuid) continue if not instance.host: # Allocations related to instances being scheduled should not # be deleted if we already wrote the allocation previously. LOG.debug("Instance %s has been scheduled to this compute " "host, the scheduler has made an allocation " "against this compute node but the instance has " "yet to start. Skipping heal of allocation: %s.", instance_uuid, alloc) continue if (instance.host == cn.host and instance.node == cn.hypervisor_hostname): # The instance is supposed to be on this compute host but is # not in the list of actively managed instances. LOG.warning("Instance %s is not being actively managed by " "this compute host but has allocations " "referencing this compute host: %s. Skipping " "heal of allocation because we do not know " "what to do.", instance_uuid, alloc) continue if instance.host != cn.host: # The instance has been moved to another host either via a # migration, evacuation or unshelve in between the time when we # ran InstanceList.get_by_host_and_node(), added those # instances to RT.tracked_instances and the above # Instance.get_by_uuid() call. We SHOULD attempt to remove any # allocations that reference this compute host if the VM is in # a stable terminal state (i.e. it isn't in a state of waiting # for resize to confirm/revert), however if the destination # host is an Ocata compute host, it will delete the allocation # that contains this source compute host information anyway and # recreate an allocation that only refers to itself. So we # don't need to do anything in that case. Just log the # situation here for information but don't attempt to delete or # change the allocation. LOG.warning("Instance %s has been moved to another host " "%s(%s). There are allocations remaining against " "the source host that might need to be removed: " "%s.", instance_uuid, instance.host, instance.node, alloc) def delete_allocation_for_evacuated_instance(self, context, instance, node, node_type='source'): # Clean up the instance allocation from this node in placement cn_uuid = self.compute_nodes[node].uuid if not self.reportclient.remove_provider_tree_from_instance_allocation( context, instance.uuid, cn_uuid): LOG.error("Failed to clean allocation of evacuated " "instance on the %s node %s", node_type, cn_uuid, instance=instance) def _find_orphaned_instances(self): """Given the set of instances and migrations already account for by resource tracker, sanity check the hypervisor to determine if there are any "orphaned" instances left hanging around. Orphans could be consuming memory and should be accounted for in usage calculations to guard against potential out of memory errors. """ uuids1 = frozenset(self.tracked_instances) uuids2 = frozenset(self.tracked_migrations.keys()) uuids = uuids1 | uuids2 usage = self.driver.get_per_instance_usage() vuuids = frozenset(usage.keys()) orphan_uuids = vuuids - uuids orphans = [usage[uuid] for uuid in orphan_uuids] return orphans def _update_usage_from_orphans(self, orphans, nodename): """Include orphaned instances in usage.""" for orphan in orphans: memory_mb = orphan['memory_mb'] LOG.warning("Detected running orphan instance: %(uuid)s " "(consuming %(memory_mb)s MB memory)", {'uuid': orphan['uuid'], 'memory_mb': memory_mb}) # just record memory usage for the orphan usage = {'memory_mb': memory_mb} self._update_usage(usage, nodename) def delete_allocation_for_shelve_offloaded_instance(self, context, instance): self.reportclient.delete_allocation_for_instance(context, instance.uuid) def _verify_resources(self, resources): resource_keys = ["vcpus", "memory_mb", "local_gb", "cpu_info", "vcpus_used", "memory_mb_used", "local_gb_used", "numa_topology"] missing_keys = [k for k in resource_keys if k not in resources] if missing_keys: reason = _("Missing keys: %s") % missing_keys raise exception.InvalidInput(reason=reason) def _get_instance_type(self, instance, prefix, migration): """Get the instance type from instance.""" stashed_flavors = migration.migration_type in ('resize',) if stashed_flavors: return getattr(instance, '%sflavor' % prefix) else: # NOTE(ndipanov): Certain migration types (all but resize) # do not change flavors so there is no need to stash # them. In that case - just get the instance flavor. return instance.flavor def _get_usage_dict(self, object_or_dict, instance, **updates): """Make a usage dict _update methods expect. Accepts a dict or an Instance or Flavor object, and a set of updates. Converts the object to a dict and applies the updates. :param object_or_dict: instance or flavor as an object or just a dict :param instance: nova.objects.Instance for the related operation; this is needed to determine if the instance is volume-backed :param updates: key-value pairs to update the passed object. Currently only considers 'numa_topology', all other keys are ignored. :returns: a dict with all the information from object_or_dict updated with updates """ def _is_bfv(): # Check to see if we have the is_bfv value cached. if instance.uuid in self.is_bfv: is_bfv = self.is_bfv[instance.uuid] else: is_bfv = compute_utils.is_volume_backed_instance( instance._context, instance) self.is_bfv[instance.uuid] = is_bfv return is_bfv usage = {} if isinstance(object_or_dict, objects.Instance): is_bfv = _is_bfv() usage = {'memory_mb': object_or_dict.flavor.memory_mb, 'swap': object_or_dict.flavor.swap, 'vcpus': object_or_dict.flavor.vcpus, 'root_gb': (0 if is_bfv else object_or_dict.flavor.root_gb), 'ephemeral_gb': object_or_dict.flavor.ephemeral_gb, 'numa_topology': object_or_dict.numa_topology} elif isinstance(object_or_dict, objects.Flavor): usage = obj_base.obj_to_primitive(object_or_dict) if _is_bfv(): usage['root_gb'] = 0 else: usage.update(object_or_dict) for key in ('numa_topology',): if key in updates: usage[key] = updates[key] return usage def build_failed(self, nodename): """Increments the failed_builds stats for the given node.""" self.stats[nodename].build_failed() def build_succeeded(self, nodename): """Resets the failed_builds stats for the given node.""" self.stats[nodename].build_succeeded() @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def claim_pci_devices(self, context, pci_requests): """Claim instance PCI resources :param context: security context :param pci_requests: a list of nova.objects.InstancePCIRequests :returns: a list of nova.objects.PciDevice objects """ result = self.pci_tracker.claim_instance( context, pci_requests, None) self.pci_tracker.save(context) return result @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def allocate_pci_devices_for_instance(self, context, instance): """Allocate instance claimed PCI resources :param context: security context :param instance: instance object """ self.pci_tracker.allocate_instance(instance) self.pci_tracker.save(context) @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def free_pci_device_allocations_for_instance(self, context, instance): """Free instance allocated PCI resources :param context: security context :param instance: instance object """ self.pci_tracker.free_instance_allocations(context, instance) self.pci_tracker.save(context) @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def free_pci_device_claims_for_instance(self, context, instance): """Free instance claimed PCI resources :param context: security context :param instance: instance object """ self.pci_tracker.free_instance_claims(context, instance) self.pci_tracker.save(context)
is_new_compute_node = self._init_compute_node(context, resources) nodename = resources['hypervisor_hostname'] # if we could not init the compute node the tracker will be # disabled and we should quit now if self.disabled(nodename): return # Grab all instances assigned to this node: instances = objects.InstanceList.get_by_host_and_node( context, self.host, nodename, expected_attrs=['system_metadata', 'numa_topology', 'flavor', 'migration_context']) # Now calculate usage based on instance utilization: instance_by_uuid = self._update_usage_from_instances( context, instances, nodename) # Grab all in-progress migrations: migrations = objects.MigrationList.get_in_progress_by_host_and_node( context, self.host, nodename) self._pair_instances_to_migrations(migrations, instance_by_uuid) self._update_usage_from_migrations(context, migrations, nodename) # A new compute node means there won't be a resource provider yet since # that would be created via the _update() call below, and if there is # no resource provider then there are no allocations against it. if not is_new_compute_node: self._remove_deleted_instances_allocations( context, self.compute_nodes[nodename], migrations, instance_by_uuid) # Detect and account for orphaned instances that may exist on the # hypervisor, but are not in the DB: orphans = self._find_orphaned_instances() self._update_usage_from_orphans(orphans, nodename) cn = self.compute_nodes[nodename] # NOTE(yjiang5): Because pci device tracker status is not cleared in # this periodic task, and also because the resource tracker is not # notified when instances are deleted, we need remove all usages # from deleted instances. self.pci_tracker.clean_usage(instances, migrations, orphans) dev_pools_obj = self.pci_tracker.stats.to_device_pools_obj() cn.pci_device_pools = dev_pools_obj self._report_final_resource_view(nodename) metrics = self._get_host_metrics(context, nodename) # TODO(pmurray): metrics should not be a json string in ComputeNode, # but it is. This should be changed in ComputeNode cn.metrics = jsonutils.dumps(metrics) # update the compute_node self._update(context, cn, startup=startup) LOG.debug('Compute_service record updated for %(host)s:%(node)s', {'host': self.host, 'node': nodename})
lib.rs
//! //! morse_code/src/lib.rs //! //! Michael G. Cummings //! 2019-08-26 //! // MIT License // // Copyright (c) 2019 Michael Cummings // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #[macro_use] extern crate structopt; use std::{fs, io}; use std::collections::HashMap; use std::error::Error; use std::path::PathBuf; /// Main library function that does the actual work.
/// pub fn run(config: &mut Config) -> Result<(), Box<dyn Error>> { let mut contents = String::new(); config.read.read_to_string(&mut contents)?; let morse_map = init_code_map(); let mut result = String::new(); for char in contents.trim().to_uppercase().chars() { match morse_map.get(&char) { Some(hash) => { result = result + *hash; } None => { result = result + "#" } } result = result + " "; } config.write.write(result.as_ref())?; Ok(()) } /// Configuration structure for the input and output streams. #[derive(Debug)] pub struct Config { read: Box<dyn io::Read>, write: Box<dyn io::Write>, } impl Config { pub fn new(opts: Opt) -> Result<Config, &'static str> { let input: Box<dyn io::Read> = match opts.input { Some(p) => Box::new(fs::File::open(p).unwrap()), None => Box::new(io::stdin()), }; let output: Box<dyn io::Write> = match opts.output { Some(p) => Box::new(fs::File::create(p).unwrap()), None => Box::new(io::stdout()), }; Ok(Config { read: input, write: output }) } } /// Structure used to hold command line opts(parameters) of binary. /// /// Using StructOpt crate to parse command-line parameters/options. /// #[derive(Debug, StructOpt)] #[structopt(rename_all = "kebab-case", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] pub struct Opt { /// Input file, stdin if not present #[structopt(short, long, parse(from_os_str))] input: Option<PathBuf>, /// Output file, stdout if not present #[structopt(short, long, parse(from_os_str))] output: Option<PathBuf>, } /// Initialize hash map of characters to morse code as string. pub fn init_code_map() -> HashMap<char, &'static str> { let mut morse_map: HashMap<char, &str> = HashMap::with_capacity(37); morse_map.insert(' ', " "); morse_map.insert('A', "._"); morse_map.insert('B', "_..."); morse_map.insert('C', "_._."); morse_map.insert('D', "_.."); morse_map.insert('E', "."); morse_map.insert('F', ".._."); morse_map.insert('G', "__."); morse_map.insert('H', "...."); morse_map.insert('I', ".."); morse_map.insert('J', ".___"); morse_map.insert('K', "_._"); morse_map.insert('L', "._.."); morse_map.insert('M', "__"); morse_map.insert('N', "_."); morse_map.insert('O', "___"); morse_map.insert('P', ".__."); morse_map.insert('Q', "__._"); morse_map.insert('R', "._."); morse_map.insert('S', "..."); morse_map.insert('T', "_"); morse_map.insert('U', ".._"); morse_map.insert('V', "..._"); morse_map.insert('W', ".__"); morse_map.insert('X', "_.._"); morse_map.insert('Y', "_.__"); morse_map.insert('Z', "__.."); morse_map.insert('1', ".____"); morse_map.insert('2', "..___"); morse_map.insert('3', "...__"); morse_map.insert('4', "...._"); morse_map.insert('5', "....."); morse_map.insert('6', "_...."); morse_map.insert('7', "__..."); morse_map.insert('8', "___.."); morse_map.insert('9', "____."); morse_map.insert('0', "_____"); morse_map }
/// /// Each character has one space between them and there are two spaces between words. /// Unknown characters in the input are replaced with a '#' in the output.
builder.go
package generate import ( "strings" jen "github.com/dave/jennifer/jen" "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" ) const ( builder = "Builder" ) func
() jen.Code { return jen. Type().Id("Clock").Interface( jen.Id("Now").Params().Qual("time", "Time"), ). Line().Line(). Type().Id("realClock").Struct().Line().Line(). Func().Params(jen.Id("realClock")).Id("Now").Params().Qual("time", "Time").Block( jen.Return(jen.Qual("time", "Now").Call()), ).Line().Line(). Type().Id("BuilderOption").Func().Params(jen.Op("*").Id(builder)).Line().Line(). Func().Id("WithClock").Params(jen.Id("c").Id("Clock")).Id("BuilderOption").Block( jen.Return( jen.Func().Params(jen.Id("b").Op("*").Id(builder)).Block( jen.Id("b").Dot("clock").Op("=").Id("c"), ), ), ).Line().Line(). Type().Id(builder).Struct( jen.Id("ID").String(), jen.Id("Events").Index().Qual("github.com/vectorhacker/eventing", "Event"), jen.Id("Version").Int(), jen.Id("clock").Id("Clock"), ).Line().Line(). Func().Params(jen.Id("b").Op("*").Id(builder)).Id("nextVersion").Params().Int32().Block( jen.Id("b").Dot("Version").Op("++"), jen.Return(jen.Int32().Parens(jen.Id("b").Dot("Version"))), ).Line().Line(). Func().Id("NewBuilder").Params(jen.Id("id").String(), jen.Id("version").Int(), jen.Id("opts").Op("...").Id("BuilderOption")).Op("*").Id(builder).Block( jen.Id("b").Op(":=").Op("&").Id(builder).Values(jen.Dict{ jen.Id("Version"): jen.Id("version"), jen.Id("ID"): jen.Id("id"), jen.Id("clock"): jen.Id("realClock").Values(jen.Dict{}), }), jen.For(jen.Id("_").Op(",").Id("opt").Op(":=").Range().Id("opts")).Block( jen.Id("opt").Call(jen.Id("b")), ), jen.Return( jen.Id("b"), ), ) } func generateEventBuilder(message *descriptor.DescriptorProto, packageName string) jen.Code { params := []jen.Code{} values := jen.Dict{} for _, field := range message.Field { switch strings.ToLower(name(field)) { case AtField: values[jen.Id(name(field))] = jen.Id("b").Dot("clock").Dot("Now").Call().Dot("Unix").Call() case VersionField: values[jen.Id(name(field))] = jen.Id("b").Dot("nextVersion").Call() case IDField: values[jen.Id(name(field))] = jen.Id("b").Dot("ID") default: values[jen.Id(name(field))] = jen.Id(paramCaseName(field)) param := jen.Id(paramCaseName(field)) if field.IsRepeated() { param = param.Index() } typeName := strings.ReplaceAll(strings.ReplaceAll(field.GetTypeName(), "."+packageName+".", ""), ".", "_") switch field.GetType() { case descriptor.FieldDescriptorProto_TYPE_BOOL: param = param.Bool() case descriptor.FieldDescriptorProto_TYPE_BYTES: param = param.Index().Byte() case descriptor.FieldDescriptorProto_TYPE_DOUBLE: param = param.Float64() case descriptor.FieldDescriptorProto_TYPE_SFIXED32, descriptor.FieldDescriptorProto_TYPE_INT32, descriptor.FieldDescriptorProto_TYPE_SINT32: param = param.Int32() case descriptor.FieldDescriptorProto_TYPE_SFIXED64, descriptor.FieldDescriptorProto_TYPE_INT64, descriptor.FieldDescriptorProto_TYPE_SINT64: param = param.Int64() case descriptor.FieldDescriptorProto_TYPE_FLOAT: param = param.Float32() case descriptor.FieldDescriptorProto_TYPE_MESSAGE: param = param.Op("*").Id(typeName) case descriptor.FieldDescriptorProto_TYPE_STRING: param = param.String() case descriptor.FieldDescriptorProto_TYPE_UINT32: param = param.Uint32() case descriptor.FieldDescriptorProto_TYPE_UINT64: param = param.Uint64() case descriptor.FieldDescriptorProto_TYPE_ENUM: param = param.Id(typeName) } params = append(params, param) } } return jen.Func().Params(jen.Id("b").Op("*").Id(builder)).Id(message.GetName()).Params(params...). Block( jen.Id("e").Op(":=").Op("&").Id(message.GetName()).Values(values), jen.Id("b").Dot("Events").Op("=").Append(jen.Id("b").Dot("Events"), jen.Id("e")), ) }
generateBuilder
admin-layout.module.ts
import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { DataTablesModule } from 'angular-datatables'; import { ReactiveFormsModule } from '@angular/forms'; import { NgSelectModule } from '@ng-select/ng-select'; import { NgxSmartModalModule } from 'ngx-smart-modal'; import { NgxMaskModule } from 'ngx-mask' import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'; import { AdminLayoutRoutes } from './admin-layout.routing'; import { InicioComponent } from '../../pages/inicio/inicio.component'; import { PacienteComponent } from '../../pages/paciente/paciente.component'; import { HistoricoMedicoComponent } from '../../pages/historico-medico/historico-medico.component'; import { ExameFisicoComponent } from '../../pages/exame-fisico/exame-fisico.component'; import { ProntuarioComponent } from '../../pages/prontuario/prontuario.component'; import { InventarioComponent } from '../../pages/inventario/inventario.component'; import { EvolucaoComponent } from '../../pages/evolucao/evolucao.component'; import { UsuarioComponent } from '../../pages/usuario/usuario.component'; import { AuditoriaComponent } from '../../pages/auditoria/auditoria.component'; import { RelatorioComponent } from '../../pages/relatorios/relatorios.component'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { FilterPipe } from '../../pipe/filter/filter.pipe'; @NgModule({ imports: [ CommonModule, RouterModule.forChild(AdminLayoutRoutes), FormsModule, NgbModule, DataTablesModule, ReactiveFormsModule, NgSelectModule, NgxSmartModalModule, NgxMaskModule, FontAwesomeModule, ], declarations: [ InicioComponent, PacienteComponent, HistoricoMedicoComponent, ExameFisicoComponent, ProntuarioComponent, InventarioComponent, EvolucaoComponent, UsuarioComponent, AuditoriaComponent, RelatorioComponent, FilterPipe, ] }) export class
{ }
AdminLayoutModule
redirect.js
module.exports = { "redirect": [ /**************************************************** * GENERAL REDIRECTS ****************************************************/ { from: "/docs/Overview", to: "/" }, { from: "/docs/", to: "/" }, /**************************************************** * API & SDK ****************************************************/ { from: "/apidocs/Home", to: "/apidocs-mxsdk/apidocs/" }, { from: "/apidocs/Authentication", to: "/apidocs-mxsdk/apidocs/authentication" }, { from: "/apidocs/Build+API", to: "/apidocs-mxsdk/apidocs/build-api" }, { from: "/apidocs/Deploy+API", to: "/apidocs-mxsdk/apidocs/deploy-api" }, { from: "/apidocs/Example+implementation", to: "/apidocs-mxsdk/apidocs/example-implementation" }, { from: "/apidocs/Feedback+API", to: "/apidocs-mxsdk/apidocs/feedback-api" }, { from: "/apidocs/API+documentation", to: "/apidocs-mxsdk/apidocs/" }, { from: "/apidocs/Invite+API", to: "/apidocs-mxsdk/apidocs/invite-api" }, { from: "/apidocs/Moving+From+6+to+7", to: "/refguide/moving-from-6-to-7" }, { from: "/apidocs/Permissions+API", to: "/apidocs-mxsdk/apidocs/permissions-api" }, { from: "/apidocs/Profile+API", to: "/apidocs-mxsdk/apidocs/profile-api" }, { from: "/apidocs/Projects+API", to: "/apidocs-mxsdk/apidocs/projects-api" }, { from: "/apidocs/Runtime+API+changes", to: "/refguide/moving-from-6-to-7" }, { from: "/apidocs/Single+Sign-On+API", to: "/apidocs-mxsdk/apidocs/single-sign-on-api" }, { from: "/apidocs/Stories+API", to: "/apidocs-mxsdk/apidocs/stories-api" }, { from: "/apidocs/Team+Server+API", to: "/apidocs-mxsdk/apidocs/team-server-api" }, { from: "/apidocs/User+Management+API", to: "/apidocs-mxsdk/apidocs/user-management-api" }, { from: "/MXSDK/Changing+things+in+the+model", to: "/apidocs-mxsdk/mxsdk/changing-things-in-the-model" }, { from: "/MXSDK/Closing+the+server+connection", to: "/apidocs-mxsdk/mxsdk/closing-the-server-connection" }, { from: "/MXSDK/Creating+the+domain+model", to: "/apidocs-mxsdk/mxsdk/creating-the-domain-model" }, { from: "/MXSDK/Creating+your+first+script", to: "/apidocs-mxsdk/mxsdk/creating-your-first-script" }, { from: "/MXSDK/Domain+Model+Metamodel", to: "/apidocs-mxsdk/mxsdk/domain-model-metamodel" }, { from: "/MXSDK/FAQ", to: "/apidocs-mxsdk/mxsdk/faq" }, { from: "/MXSDK/Finding+things+in+the+model", to: "/apidocs-mxsdk/mxsdk/finding-things-in-the-model" }, { from: "/MXSDK/Generating+code+from+the+model", to: "/apidocs-mxsdk/mxsdk/generating-code-from-the-model" }, { from: "/MXSDK/Mendix+SDK+Home", to: "/apidocs-mxsdk/mxsdk/" }, { from: "/MXSDK/JavaScript+TypeScript+Resources", to: "/apidocs-mxsdk/mxsdk/javascript-typescript-resources" }, { from: "/MXSDK/Loading+units+and+elements", to: "/apidocs-mxsdk/mxsdk/loading-units-and-elements" }, { from: "/MXSDK/Manipulating+existing+models", to: "/apidocs-mxsdk/mxsdk/manipulating-existing-models" }, { from: "/MXSDK/Microflows+Metamodel", to: "/apidocs-mxsdk/mxsdk/microflows-metamodel" }, { from: "/MXSDK/Pages+Metamodel", to: "/apidocs-mxsdk/mxsdk/pages-metamodel" }, { from: "/MXSDK/Projects+Metamodel", to: "/apidocs-mxsdk/mxsdk/projects-metamodel" }, { from: "/MXSDK/Reference+Documentation", to: "/apidocs-mxsdk/mxsdk/reference-documentation" }, { from: "/MXSDK/Setting+up+your+development+environment", to: "/apidocs-mxsdk/mxsdk/setting-up-your-development-environment" }, { from: "/MXSDK/Understanding+the+metamodel", to: "/apidocs-mxsdk/mxsdk/understanding-the-metamodel" }, { from: "/MXSDK/Use+case+examples", to: "/apidocs-mxsdk/mxsdk/use-case-examples" }, { from: "/MXSDK/Working+with+when.js+and+promises+in+TypeScript", to: "/apidocs-mxsdk/mxsdk/working-with-when.js-and-promises-in-typescript" }, { from: "/MXSDK/Your+learning+path+for+the+Mendix+SDK", to: "/apidocs-mxsdk/mxsdk/tutorial-for-the-mendix-sdk" }, /**************************************************** * APPSTORE ****************************************************/ { from: "/appstore/Adding+App+Store+content+to+your+app", to: "/community/app-store/use-app-store-content-in-the-modeler" }, { from: "/appstore/App+Store+Approval+Guidelines", to: "/community/app-store/share-app-store-content" }, { from: "/appstore/App+Store+Content+Support", to: "/community/app-store/app-store-content-support" }, { from: "/community/app-store-content-support", to: "/community/app-store/app-store-content-support" }, { from: "/appstore/App+Store", to: "/community/app-store/" }, { from: "/appstore/App+Store+Home", to: "/community/app-store/" }, { from: "/appstore/Install+an+App+from+the+App+Store", to: "/community/app-store/use-app-store-content-in-the-modeler" }, /**************************************************** * Best Practices ****************************************************/ { from: "/bestpractices/Best+Practices+for+Component+Based+Development", to: "/howtogeneral/bestpractices/best-practices-for-component-based-development" }, { from: "/bestpractices/Best+Practices", to: "/howtogeneral/bestpractices/" }, { from: "/bestpractices/Naming+conventions", to: "/howtogeneral/bestpractices/dev-best-practices" }, { from: "/bestpractices/Naming+conventions+in+Mendix+5", to: "/howtogeneral/bestpractices/dev-best-practices" }, { from: "/howtogeneral/bestpractices/naming-conventions", to: "/howtogeneral/bestpractices/dev-best-practices" }, /**************************************************** * Community ****************************************************/ { from: "/community/Community+Documentation", to: "/community/documentation/" }, { from: "/community/Community+Projects", to: "/community/tools/" }, { from: "/community/Content+Writing+and+Formatting+Guidelines", to: "/community/documentation/content-writing-and-formatting-guidelines" }, { from: "/community/Contribute+to+the+Mendix+Documentation", to: "/community/documentation/contribute-to-the-mendix-documentation" }, { from: "/community/How+to+set+up+your+partner+profile", to: "/community/tools/how-to-set-up-your-partner-profile" }, { from: "/community/How+to+set+up+your+profile", to: "/community/tools/how-to-set-up-your-profile" }, { from: "/community/The+How+to+Template+Page", to: "/community/documentation/the-how-to-template-page" }, { from: "/community/The+Mendix+Job+Board", to: "/community/tools/the-mendix-job-board" }, { from: "/community/The+Mendix+MVP+program", to: "/community/tools/the-mendix-mvp-program" }, { from: "/community/The+Reference+Guide+Page+Template+Page", to: "/community/documentation/the-reference-guide-page-template-page" }, /**************************************************** * HOWTO MENDIX 4 ****************************************************/ { from: "/howto40/Access+Rules", to: "/howto40/access-rules" }, { from: "/howto40/Action+Call+Activities", to: "/howto40/action-call-activities" }, { from: "/howto40/Activate+your+Mendix+license", to: "/howto40/activate-your-mendix-license" }, { from: "/howto40/Activities", to: "/howto40/activities" }, { from: "/howto40/Add+a+new+language+to+your+project", to: "/howto40/add-a-new-language-to-your-project" }, { from: "/howto40/Add+a+reference+set", to: "/howto40/add-a-reference-set" }, { from: "/howto40/Add+a+validation+rule", to: "/howto40/add-a-validation-rule" }, { from: "/howto25/Add+a+widget+to+a+form", to: "/howto40/add-a-widget-to-a-form" }, { from: "/howto40/Add+a+widget+to+a+form", to: "/howto40/add-a-widget-to-a-form" }, { from: "/howto40/Add+an+activity+to+a+microflow", to: "/howto40/add-an-activity-to-a-microflow" }, { from: "/howto25/Add+an+attribute", to: "/howto40/add-an-attribute" }, { from: "/howto40/Add+an+attribute", to: "/howto40/add-an-attribute" }, { from: "/howto40/Add+an+event+handler", to: "/howto40/add-an-event-handler" }, { from: "/howto40/Add+and+configure+a+file+manager", to: "/howto40/add-and-configure-a-file-manager" }, { from: "/howto40/Add+and+configure+a+Java+action", to: "/howto40/add-and-configure-a-java-action" }, { from: "/howto40/Add+and+configure+an+image+uploader", to: "/howto40/add-and-configure-an-image-uploader" }, { from: "/howto40/Add+and+configure+an+image+viewer", to: "/howto40/add-and-configure-an-image-viewer" }, { from: "/howto40/Add+and+configure+an+XML+schema", to: "/howto40/add-and-configure-an-xml-schema" }, { from: "/howto40/Add+and+configure+tab+pages", to: "/howto40/add-and-configure-tab-pages" }, { from: "/howto40/Add+custom+images", to: "/howto40/add-custom-images" }, { from: "/howto40/Add+documents+to+a+module", to: "/howto40/add-documents-to-a-module" }, { from: "/howto40/Add+validation+feedback+to+forms", to: "/howto40/add-validation-feedback-to-forms" }, { from: "/howto40/Add+web+service+users", to: "/howto40/add-web-service-users" }, { from: "/howto40/Apply+XPath+within+the+form+builder", to: "/howto40/apply-xpath-within-the-form-builder" }, { from: "/howto40/Associations", to: "/howto40/associations" }, { from: "/howto40/Attributes", to: "/howto40/attributes" }, { from: "/howto40/Basic+Reports", to: "/howto40/basic-reports" }, { from: "/howto40/Build+a+template+grid", to: "/howto40/build-a-template-grid" }, { from: "/howto40/Call+a+microflow", to: "/howto40/call-a-microflow" }, { from: "/howto40/Call+a+microflow+inside+another+microflow", to: "/howto40/call-a-microflow-inside-another-microflow" }, { from: "/howto40/Call+SAP+BAPI+from+Mx", to: "/howto40/call-sap-bapi-from-mx" }, { from: "/howto40/Cast+an+object", to: "/howto40/cast-an-object" }, { from: "/howto40/Change+a+list", to: "/howto40/change-a-list" }, { from: "/howto40/Client+Activities", to: "/howto40/client-activities" }, { from: "/howto40/Columns", to: "/howto40/columns" }, { from: "/howto40/Commit+an+object", to: "/howto40/commit-an-object" }, { from: "/howto40/Conditions", to: "/howto40/conditions" }, { from: "/howto40/Configuration+form", to: "/howto40/configuration-form" }, { from: "/howto40/Configure+a+Domain+to+XML+mapping", to: "/howto40/configure-a-domain-to-xml-mapping" }, { from: "/howto40/Configure+a+Java+action+call", to: "/howto40/configure-a-java-action-call" }, { from: "/howto40/Configure+a+list+operation", to: "/howto40/configure-a-list-operation" }, { from: "/howto40/Configure+a+loop", to: "/howto40/configure-a-loop" }, { from: "/howto40/Configure+a+microflow+button", to: "/howto40/configure-a-microflow-button" }, { from: "/howto40/Configure+a+microflow+trigger", to: "/howto40/configure-a-microflow-trigger" }, { from: "/howto40/Configure+a+scheduled+event", to: "/howto40/configure-a-scheduled-event" }, { from: "/howto40/Configure+an+Aggregate+list+activity", to: "/howto40/configure-an-aggregate-list-activity" }, { from: "/howto40/Configure+an+exclusive+split", to: "/howto40/configure-an-exclusive-split" }, { from: "/howto40/Configure+an+XML+to+Domain+mapping", to: "/howto40/configure-an-xml-to-domain-mapping" }, { from: "/howto40/Configure+delete+behavior", to: "/howto40/configure-delete-behavior" }, { from: "/howto40/Configure+Java+actions+using+Eclipse", to: "/howto40/configure-java-actions-using-eclipse" }, { from: "/howto40/Configure+the+date+range+selector", to: "/howto40/configure-the-date-range-selector" }, { from: "/howto40/Configure+the+default+button+of+a+data+grid", to: "/howto40/configure-the-default-button-of-a-data-grid" }, { from: "/howto40/Configure+the+go+to+form+of+a+reference+selector", to: "/howto40/configure-the-go-to-form-of-a-reference-selector" }, { from: "/howto40/Configure+the+pop+up+form+of+a+reference+selector", to: "/howto40/configure-the-pop-up-form-of-a-reference-selector" }, { from: "/howto40/Configure+the+tooltip+form+of++a+data+grid", to: "/howto40/configure-the-tooltip-form-of--a-data-grid" }, { from: "/howto40/Configure+the+tooltip+form+of+a+reference+set+selector", to: "/howto40/configure-the-tooltip-form-of-a-reference-set-selector" }, { from: "/howto40/Configure+zooming+for+a+basic+report", to: "/howto40/configure-zooming-for-a-basic-report" }, { from: "/howto40/Connect+a+basic+report+to+a+data+set", to: "/howto40/connect-a-basic-report-to-a-data-set" }, { from: "/howto40/Connect+a+microflow+to+a+widget+event", to: "/howto40/connect-a-microflow-to-a-widget-event" }, { from: "/howto40/Connect+a+report+chart+to+a+data+set", to: "/howto40/connect-a-report-chart-to-a-data-set" }, { from: "/howto40/Connect+an+attribute+to+a+column", to: "/howto40/connect-an-attribute-to-a-column" }, { from: "/howto40/Connect+an+attribute+to+a+search+field", to: "/howto40/connect-an-attribute-to-a-search-field" }, { from: "/howto40/Connect+an+entity+to+a+data+grid", to: "/howto40/connect-an-entity-to-a-data-grid" }, { from: "/howto25/Connect+an+entity+to+a+data+view", to: "/howto40/connect-an-entity-to-a-data-view" }, { from: "/howto40/Connect+an+entity+to+a+data+view", to: "/howto40/connect-an-entity-to-a-data-view" }, { from: "/howto40/Connect+forms+using+buttons", to: "/howto40/connect-forms-using-buttons" }, { from: "/howto40/Connect+parameter+widgets+to+a+data+set", to: "/howto40/connect-parameter-widgets-to-a-data-set" }, { from: "/howto40/Constants", to: "/howto40/constants" }, { from: "/howto40/Constrained+by+functionality+for+a+reference+selector", to: "/howto40/constrained-by-functionality-for-a-reference-selector" }, { from: "/howto40/Constrained+by+functionality+for+a+reference+set+selector", to: "/howto40/constrained-by-functionality-for-a-reference-set-selector" }, { from: "/howto40/Consume+a+web+service", to: "/howto40/consume-a-web-service" }, { from: "/howto40/Context+Mechanism", to: "/howto40/context-mechanism" }, { from: "/howto40/Create+a+data+set+and+add+parameters+to+it", to: "/howto40/create-a-data-set-and-add-parameters-to-it" }, { from: "/howto40/Create+a+list", to: "/howto40/create-a-list" }, { from: "/howto40/Create+a+module+role", to: "/howto40/create-a-module-role" }, { from: "/howto40/Create+a+multi+language+enumeration", to: "/howto40/create-a-multi-language-enumeration" }, { from: "/howto40/Create+a+new+navigation+menu+item", to: "/howto40/create-a-new-navigation-menu-item" }, { from: "/howto40/Create+a+new+object+with+associated+image+object", to: "/howto40/create-a-new-object-with-associated-image-object" }, { from: "/howto40/Create+a+report+and+add+widgets+to+it", to: "/howto40/create-a-report-and-add-widgets-to-it" }, { from: "/howto40/Create+a+specialized+entity", to: "/howto40/create-a-specialized-entity" }, { from: "/howto40/Create+an+association", to: "/howto40/create-an-association" }, { from: "/howto40/Create+and+build+a+document+template", to: "/howto40/create-and-build-a-document-template" }, { from: "/howto40/Create+and+build+a+form", to: "/howto40/create-and-build-a-form" }, { from: "/howto40/Create+and+change+an+object", to: "/howto40/create-and-change-an-object" }, { from: "/howto40/Create+and+configure+a+constant", to: "/howto40/create-and-configure-a-constant" }, { from: "/howto40/Custom+Widgets", to: "/howto40/custom-widgets" }, { from: "/howto40/Data+Grid", to: "/howto40/data-grid" }, { from: "/howto40/Data+Sets", to: "/howto40/data-sets" }, { from: "/howto40/Data+View", to: "/howto40/data-view" }, { from: "/howto40/Database+form", to: "/howto40/database-form" }, { from: "/howto40/Date+Range+Selector", to: "/howto40/date-range-selector" }, { from: "/howto40/Debugging", to: "/howto40/debugging" }, { from: "/howto40/Debugging+4.2+and+before", to: "/howto40/debugging-4.2-and-before" }, { from: "/howto40/Determine+contents+of+a+nested+data+view+by+microflow", to: "/howto40/determine-contents-of-a-nested-data-view-by-microflow" }, { from: "/howto40/Display+a+message+with+a+microflow", to: "/howto40/display-a-message-with-a-microflow" }, { from: "/howto40/Display+icons+for+enumeration+values", to: "/howto40/display-icons-for-enumeration-values" }, { from: "/howto40/Display+the+sum+of+a+data+grid+column", to: "/howto40/display-the-sum-of-a-data-grid-column" }, { from: "/howto40/Document+Templates", to: "/howto40/document-templates" }, { from: "/howto40/Domain+Model", to: "/howto40/domain-model" }, { from: "/howto40/Edit+system+texts", to: "/howto40/edit-system-texts" }, { from: "/howto40/Encode+an+icon+with+Base64", to: "/howto40/encode-an-icon-with-base64" }, { from: "/howto40/Entities", to: "/howto40/entities" }, { from: "/howto40/Enumerations", to: "/howto40/enumerations" }, { from: "/howto40/Event+Handlers", to: "/howto40/event-handlers" }, { from: "/howto40/Exclusive+Split", to: "/howto40/exclusive-split" }, { from: "/howto40/Expose+a+web+service", to: "/howto40/expose-a-web-service" }, { from: "/howto40/File+Manager", to: "/howto40/file-manager" }, { from: "/howto40/Forms", to: "/howto40/forms" }, { from: "/howto40/Generate+documents+using+document+templates", to: "/howto40/generate-documents-using-document-templates" }, { from: "/howto40/How+to+4+Home", to: "/howto40/" }, { from: "/howto40/How+to+update+a+Mendix+Version", to: "/howto40/how-to-update-a-mendix-version" }, { from: "/howto40/Image+Uploader", to: "/howto40/image-uploader" }, { from: "/howto40/Image+Viewer", to: "/howto40/image-viewer" }, { from: "/howto40/Images", to: "/howto40/images" }, { from: "/howto40/Import+XML+documents", to: "/howto40/import-xml-documents" }, { from: "/howto40/Improve+performance+with+indexes", to: "/howto40/improve-performance-with-indexes" }, { from: "/howto40/Indexes", to: "/howto40/indexes" }, { from: "/howto40/Inheritance+Split", to: "/howto40/inheritance-split" }, { from: "/howto40/Install+an+App+from+the+AppStore", to: "/howto40/install-an-app-from-the-appstore" }, { from: "/howto40/Installing+Mendix+2.5+on+Debian+5", to: "/howto40/installing-mendix-2.5-on-debian-5" }, { from: "/howto40/Installing+Mendix+on+GNU", to: "/howto40/installing-mendix-on-gnu" }, { from: "/howto40/Installing+the+SAP+GUI", to: "/howto40/installing-the-sap-gui" }, { from: "/howto40/Integration", to: "/howto40/integration" }, { from: "/howto40/Integration+Activities", to: "/howto40/integration-activities" }, { from: "/howto40/Java+Actions", to: "/howto40/java-actions" }, { from: "/howto40/Java+API+Tutorial", to: "/howto40/java-api-tutorial" }, { from: "/howto40/Java+Programming", to: "/howto40/java-programming" }, { from: "/howto40/List+Activities", to: "/howto40/list-activities" }, { from: "/howto40/Loop", to: "/howto40/loop" }, { from: "/howto40/Mendix+on+the+Mendix+Cloud", to: "/howto40/mendix-on-the-mendix-cloud" }, { from: "/howto40/Mendix+on+Windows+-+Service+Console+3", to: "/howto40/mendix-on-windows---service-console-3" }, { from: "/howto40/Mendix+on+Windows+-+Service+Console+4", to: "/howto40/mendix-on-windows---service-console-4" }, { from: "/howto40/Merge", to: "/howto40/merge" }, { from: "/howto40/Merge+multiple+sequence+flows", to: "/howto40/merge-multiple-sequence-flows" }, { from: "/howto40/Microflow+Trigger", to: "/howto40/microflow-trigger" }, { from: "/howto40/Microflows", to: "/howto40/microflows" }, { from: "/howto40/Migrating+your+data", to: "/howto40/migrating-your-data" }, { from: "/howto40/Modeler", to: "/howto40/modeler" }, { from: "/howto40/Module+Security", to: "/howto40/module-security" }, { from: "/howto40/Modules", to: "/howto40/modules" }, { from: "/howto40/Navigation", to: "/howto40/navigation" }, { from: "/howto40/Object+Activities", to: "/howto40/object-activities" }, { from: "/howto40/Object+Query+Language", to: "/refguide4/oql" }, { from: "/howto40/Opening+forms", to: "/howto40/opening-forms" }, { from: "/howto40/Preparation+of+the+environment", to: "/howto40/preparation-of-the-environment" }, { from: "/howto40/Project", to: "/howto40/project" }, { from: "/howto40/Project+Security", to: "/howto40/project-security" }, { from: "/howto40/Project+Settings", to: "/howto40/project-settings" }, { from: "/howto40/Publish+an+App+in+the+AppStore", to: "/howto40/publish-an-app-in-the-appstore" }, { from: "/howto40/Receive+IDoc+from+SAP+in+Mx", to: "/howto40/receive-idoc-from-sap-in-mx" }, { from: "/howto40/Reference+Selector", to: "/howto40/reference-selector" }, { from: "/howto40/Reference+Set+Selector", to: "/howto40/reference-set-selector" }, { from: "/howto40/Report+Chart", to: "/howto40/report-chart" }, { from: "/howto40/Reporting", to: "/howto40/reporting" }, { from: "/howto40/Retrieve+a+list+of+objects", to: "/howto40/retrieve-a-list-of-objects" }, { from: "/howto40/Retrieve+and+manipulate+batches+of+objects", to: "/howto40/retrieve-and-manipulate-batches-of-objects" }, { from: "/howto40/Rules", to: "/howto40/rules" }, { from: "/howto40/Run+two+applications+locally+at+once", to: "/howto40/run-two-applications-locally-at-once" }, { from: "/howto40/SAP+Integration", to: "/howto40/sap-integration" }, { from: "/howto40/Scheduled+Events", to: "/howto40/scheduled-events" }, { from: "/howto40/Search+Bar", to: "/howto40/search-bar" }, { from: "/howto40/Security+checklist+for+your+on+premise+installation", to: "/howto40/security-checklist-for-your-on-premise-installation" }, { from: "/howto40/Security+checklist+for+your+on+premise-installation", to: "/howto40/security-checklist-for-your-on-premise-installation" }, { from: "/howto40/Send+IDoc+from+Mx+to+SAP", to: "/howto40/send-idoc-from-mx-to-sap" }, { from: "/howto40/Sending+Email", to: "/howto40/sending-email" }, { from: "/howto40/Service+form", to: "/howto40/service-form" }, { from: "/howto40/Set+the+association+owner+to+both", to: "/howto40/set-the-association-owner-to-both" }, { from: "/howto40/Set+up+a+listen+target+for+a+data+view", to: "/howto40/set-up-a-listen-target-for-a-data-view" }, { from: "/howto40/Set+up+a+Mendix+app", to: "/howto40/set-up-a-mendix-app" }, { from: "/howto40/Set+up+a+rule", to: "/howto40/set-up-a-rule" }, { from: "/howto40/Set+up+access+rules", to: "/howto40/set-up-access-rules" }, { from: "/howto40/Set+up+alternative+home+pages+based+on+user+role", to: "/howto40/set-up-alternative-home-pages-based-on-user-role" }, { from: "/howto40/Set+up+an+attribute+with+microflow+source", to: "/howto40/set-up-an-attribute-with-microflow-source" }, { from: "/howto40/Set+up+Internet+Information+Services", to: "/howto40/set-up-internet-information-services" }, { from: "/howto40/Set+up+module+roles+for+a+project+user+role", to: "/howto40/set-up-module-roles-for-a-project-user-role" }, { from: "/howto40/Set+up+multiple+sorting+priorities", to: "/howto40/set-up-multiple-sorting-priorities" }, { from: "/howto40/Set+up+visibility+and+editability+based+on+an+enumeration", to: "/howto40/set-up-visibility-and-editability-based-on-an-enumeration" }, { from: "/howto40/Set+up+visibility+based+on+an+module+role", to: "/howto40/set-up-visibility-based-on-an-module-role" }, { from: "/howto40/Show+a+form+using+a+microflow", to: "/howto40/show-a-form-using-a-microflow" }, { from: "/howto40/Sort+Bar", to: "/howto40/sort-bar" }, { from: "/howto40/Starting+Microflows", to: "/howto40/starting-microflows" }, { from: "/howto40/System+Texts", to: "/howto40/system-texts" }, { from: "/howto40/Tab+Control", to: "/howto40/tab-control" }, { from: "/howto40/Template+Grid", to: "/howto40/template-grid" }, { from: "/howto40/Translatable+Texts", to: "/howto40/translatable-texts" }, { from: "/howto40/Translate+texts+with+the+batch+translate+function", to: "/howto40/translate-texts-with-the-batch-translate-function" }, { from: "/howto40/Update+app+form", to: "/howto40/update-app-form" }, { from: "/howto40/Upgrading+the+Mendix+Service+Console", to: "/howto40/upgrading-the-mendix-service-console" }, { from: "/howto40/Uploading+your+Project", to: "/howto40/uploading-your-project" }, { from: "/howto40/Use+a+microflow+to+determine+selectable+objects", to: "/howto40/use-a-microflow-to-determine-selectable-objects" }, { from: "/howto40/Use+a+specialization+of+an+entity", to: "/howto40/use-a-specialization-of-an-entity" }, { from: "/howto40/Use+the+Apply+context+property", to: "/howto40/use-the-apply-context-property" }, { from: "/howto40/Use+the+batch+replace+function", to: "/howto40/use-the-batch-replace-function" }, { from: "/howto40/Use+the+Data+View+context+object", to: "/howto40/use-the-data-view-context-object" }, { from: "/howto40/Validation+Rules", to: "/howto40/validation-rules" }, { from: "/howto40/Widget+Events", to: "/howto40/widget-events" }, /**************************************************** * HOWTO MENDIX 5 ****************************************************/ { from: "/howto50/Mendix+5+How-to's", to: "/howto50/" }, { from: "/howto50/How+to+50", to: "/howto50/" }, { from: "/howto50/TreeNavigation", to: "/howto50/" }, { from: "/howto50/Access+a+Samba+share+from+the+MxCloud", to: "/howto50/access-a-samba-share-from-the-mxcloud" }, { from: "/howto50/Adding+App+Store+content+to+your+app", to: "/community/app-store/use-app-store-content-in-the-modeler" }, { from: "/howto50/Anonymous+User+Security", to: "/howto50/anonymous-user-security" }, { from: "/howto50/Architecture+Options", to: "/deployment/on-premises/design-the-architecture" }, { from: "/howto50/Build+a+simple+HRM+app+1+Create+manage+and+deploy+the+app", to: "/howto50/build-a-simple-hrm-app-1-create-manage-and-deploy-the-app" }, { from: "/howto50/Build+a+simple+HRM+app+2+First+steps+in+building+a+rich+GUI", to: "/howto50/build-a-simple-hrm-app-2-first-steps-in-building-a-rich-gui" }, { from: "/howto50/Build+a+simple+HRM+app+3+Show+related+data+in+the+GUI", to: "/howto50/build-a-simple-hrm-app-3-show-related-data-in-the-gui" }, { from: "/howto50/Build+a+simple+HRM+app+4+Enrich+the+GUI+with+Filter+Options", to: "/howto50/build-a-simple-hrm-app-4-enrich-the-gui-with-filter-options" }, { from: "/howto50/Build+a+simple+HRM+app+5+Smarten+up+your+app+with+business+logic", to: "/howto50/build-a-simple-hrm-app-5-smarten-up-your-app-with-business-logic" }, { from: "/howto50/call+a+microflow", to: "/refguide5/microflow-call" }, { from: "/howto50/Clearing+Warning+Messages+in+Mendix", to: "/howto50/clearing-warning-messages-in-mendix" }, { from: "/howto50/Collaboration+and+Project+Management", to: "/howto50/collaboration-and-project-management" }, { from: "/howto50/Common+Mendix+SSO+Errors", to: "/howto50/common-mendix-sso-errors" }, { from: "/howto50/Consuming+a+complex+web+service", to: "/howto50/consuming-a-complex-web-service" }, { from: "/howto50/Consuming+a+REST+Service", to: "/howto50/consuming-a-rest-service" }, { from: "/howto50/Consuming+a+simple+Web+Service", to: "/howto50/consuming-a-simple-web-service" }, { from: "/howto50/Contributing+to+a+GitHub+repository", to: "/howto50/contributing-to-a-github-repository" }, { from: "/howto50/Create+a+custom+theme+with+the+Mendix+UI+Framework", to: "/howto50/create-a-custom-theme-with-the-mendix-ui-framework" }, { from: "/howto50/Create+and+Deploy+Your+First+App", to: "/howto50/create-and-deploy-your-first-app" }, { from: "/howto50/Create+your+first+Microflow+Hello+World", to: "/howto50/create-your-first-microflow-hello-world" }, { from: "/howto50/Creating+a+basic+data+layer", to: "/howto50/creating-a-basic-data-layer" }, { from: "/howto50/Creating+a+Basic+Hello+World+Custom+Widget", to: "/howto50/creating-a-basic-hello-world-custom-widget" }, { from: "/howto50/Creating+a+chainable+Custom+Widget", to: "/howto50/creating-a-chainable-custom-widget" }, { from: "/howto50/Creating+a+Custom+Save+Button", to: "/howto50/creating-a-custom-save-button" }, { from: "/howto50/Creating+a+secure+app", to: "/howto50/creating-a-secure-app" }, { from: "/howto50/Creating+your+first+two+Overview+and+Detail+pages", to: "/howto50/creating-your-first-two-overview-and-detail-pages" }, { from: "/howto50/Custom+Widget+Development", to: "/howto50/custom-widget-development" }, { from: "/howto50/Data+Models", to: "/howto50/data-models" }, { from: "/howto50/Debug+a+Hybrid+Mobile+Application", to: "/howto50/debug-a-hybrid-mobile-application" }, { from: "/howto50/Debugging+Java+Actions", to: "/howto50/debugging-java-actions" }, { from: "/howto50/Debugging+Java+actions+remotely", to: "/howto50/debugging-java-actions-remotely" }, { from: "/howto50/Debugging+Microflows", to: "/howto50/debugging-microflows" }, { from: "/howto50/Debugging+Microflows+Remotely", to: "/howto50/debugging-microflows-remotely" }, { from: "/howto50/Defining+access+rules+using+XPath", to: "/howto50/defining-access-rules-using-xpath" }, { from: "/howto50/Denormalize+Data+to+Improve+Performance", to: "/howto50/denormalize-data-to-improve-performance" }, { from: "/howto50/Deploying+a+Mendix+App+to+Cloud+Foundry", to: "/deployment/cloud-foundry/index" }, { from: "/howto50/Deploying+a+Mendix+App+to+Pivotal", to: "/deployment/cloud-foundry/index" }, { from: "/howto50/Deploying+Mendix+on+Microsoft+Windows", to: "/deployment/on-premises/deploy-mendix-on-microsoft-windows" }, { from: "/howto50/Drag+Microflows+and+Pages+into+a+Microflow", to: "/howto50/drag-microflows-and-pages-into-a-microflow" }, { from: "/howto50/Error+Handling", to: "/howto50/error-handling" }, { from: "/howto50/Explore+our+connectors+and+adapters", to: "/howto50/explore-our-connectors-and-adapters" }, { from: "/howto50/Exporting+XML+documents", to: "/howto50/exporting-xml-documents" }, { from: "/howto50/Exposing+a+web+service", to: "/howto50/exposing-a-web-service" }, { from: "/howto50/Extendability", to: "/howto50/extendability" }, { from: "/howto50/Extending+Your+Application+with+Custom+Java", to: "/howto50/extending-your-application-with-custom-java" }, { from: "/howto50/Extract+and+use+sub+microflows", to: "/howto50/extract-and-use-sub-microflows" }, { from: "/howto50/Filtering+Data+on+an+Overview+Page", to: "/howto50/filtering-data-on-an-overview-page" }, { from: "/howto50/Finding+Object+Activities", to: "/howto/tips/finding-object-activities" }, { from: "/howto50/Finding+the+Root+Cause+of+Runtime+Errors", to: "/howto50/finding-the-root-cause-of-runtime-errors" }, { from: "/howto50/Finding+Unused+Items", to: "/howto/tips/finding-unused-items" }, { from: "/howto50/Finding+your+way+through+a+project", to: "/howto/tips/finding-your-way-through-a-project" }, { from: "/howto50/Gathering+user+feedback", to: "/developerportal/howto/gathering-user-feedback" }, { from: "/howto50/Getting+Started", to: "/howto50/getting-started" }, { from: "/howto50/Kick-Start", to: "/howto50/getting-started" }, { from: "/howto50/Getting+started+with+the+Widget+Development+Plugin+for+Adobe+Brackets", to: "/howto50/getting-started-with-the-widget-development-plugin-for-adobe-brackets" }, { from: "/howto50/GUI's", to: "/howto50/guis" }, { from: "/howto50/High+Availability", to: "/deployment/on-premises/high-availability" }, { from: "/howto50/How+to+build+a+simple+HRM+app", to: "/howto50/how-to-build-a-simple-hrm-app" }, { from: "/howto50/Importing+and+Exporting+Objects", to: "/howto50/importing-and-exporting-objects" }, { from: "/howto50/Importing+Excel+Documents", to: "/howto50/importing-excel-documents" }, { from: "/howto50/Importing+XML+documents", to: "/howto50/importing-xml-documents" }, { from: "/howto50/Installing+Mendix+on+Debian+GNU+Linux", to: "/deployment/on-premises/installing-mendix-on-debian-gnu-linux" }, { from: "/howto50/Installing+Mendix+on+RedHat+and+CentOS", to: "/deployment/on-premises/installing-mendix-on-redhat-and-centos" }, { from: "/howto50/Integrating+a+Legacy+System+into+a+Mendix+App", to: "/howto50/integrating-a-legacy-system-into-a-mendix-app" }, { from: "/howto50/Integration", to: "/howto50/integration" }, { from: "/howto50/Java+API+Tutorial", to: "/howto50/java-api-tutorial" }, { from: "/howto50/Layouts+and+Snippets", to: "/howto50/layouts-and-snippets" }, { from: "/howto50/Log+Levels", to: "/howto50/log-levels" }, { from: "/howto50/Logic+and+Business+Rules", to: "/howto50/logic-and-business-rules" }, { from: "/howto50/Manage+scheduled+events", to: "/howto50/manage-scheduled-events" }, { from: "/howto50/Managing+your+Application+Requirements+with+Mendix", to: "/developerportal/howto/managing-your-application-requirements-with-mendix" }, { from: "/howto50/Mendix+on+Windows+-+Microsoft+SQL+Server", to: "/deployment/on-premises/mendix-on-windows-microsoft-sql-server" }, { from: "/howto50/Mendix+SQL+Maintenance+Plans", to: "/deployment/on-premises/mendix-sql-maintenance-plans" }, { from: "/howto50/Mobile", to: "/howto50/mobile" }, { from: "/howto50/Monitoring+and+Troubleshooting", to: "/howto50/monitoring-and-troubleshooting" }, { from: "/howto50/Monitoring+application+health", to: "/developerportal/operate/monitoring-application-health" }, { from: "/howto50/Monitoring+Mendix+using+JMX", to: "/howto50/monitoring-mendix-using-jmx" }, { from: "/howto50/Optimizing+Microflow+Aggregates", to: "/howto50/optimizing-microflow-aggregates" }, { from: "/howto50/Optimizing+Retrieve+Activities", to: "/howto50/optimizing-retrieve-activities" }, { from: "/howto50/Publishing+a+Mendix+Hybrid+Mobile+App+in+Mobile+App+Stores", to: "/howto50/publishing-a-mendix-hybrid-mobile-app-in-mobile-app-stores" }, { from: "/howto50/Querying+over+self+references", to: "/howto/tips/querying-over-self-references" }, { from: "/howto50/Restoring+a+SQL+Server+database", to: "/deployment/on-premises/restoring-a-sql-server-database" }, { from: "/howto50/Scout+and+Windows+10+Workaround", to: "/howto50/scout-and-windows-10-workaround" }, { from: "/howto50/Security", to: "/howto50/security" }, { from: "/howto50/Security+checklist+for+your+on+premises+installation", to: "/deployment/on-premises/security-checklist-for-your-on-premises-installation" }, { from: "/howto50/Selenium+Support", to: "/howto50/selenium-support" }, { from: "/howto50/Setting+up+a+new+SQL+Server+database", to: "/deployment/on-premises/setting-up-a-new-sql-server-database" }, { from: "/howto50/Setting+up+a+SQL+Server+user", to: "/deployment/on-premises/setting-up-a-sql-server-user" }, { from: "/howto50/Setting+up+data+validation", to: "/howto50/setting-up-data-validation" }, { from: "/howto50/Setting+up+monitoring+with+New+Relic", to: "/deployment/on-premises/setting-up-monitoring-with-new-relic" }, { from: "/howto50/Setting+up+the+database+user", to: "/deployment/on-premises/setting-up-the-database-user" }, { from: "/howto50/Setting+Up+the+Navigation+Structure", to: "/howto50/setting-up-the-navigation-structure" }, { from: "/howto50/Setup+Mendix+UI+Framework", to: "/howto50/setup-mendix-ui-framework" }, { from: "/howto50/Setup+Mendix+UI+Framework+with+just+CSS", to: "/howto50/setup-mendix-ui-framework-with-just-css" }, { from: "/howto50/Setup+Mendix+UI+Framework+with+Koala", to: "/howto50/setup-mendix-ui-framework-with-koala" }, { from: "/howto50/Sharing+the+Development+Database", to: "/howto50/sharing-the-development-database" }, { from: "/howto50/Showing+a+Project+in+the+Directory+in+Explorer", to: "/howto/tips/showing-a-project-in-the-directory-in-explorer" }, { from: "/howto50/Solving+Load+and+Import+Errors", to: "/howto50/solving-load-and-import-errors" }, { from: "/howto50/Starting+your+own+repository", to: "/howto50/starting-your-own-repository" }, { from: "/howto50/String+Concatenation", to: "/howto50/string-concatenation" }, { from: "/howto50/Synchronizing+user+accounts+using+the+LDAP+module", to: "/howto50/synchronizing-user-accounts-using-the-ldap-module" }, { from: "/howto50/Testing", to: "/howto50/testing" }, { from: "/howto50/Testing+microflows+using+the+UnitTesting+module", to: "/howto50/testing-microflows-using-the-unittesting-module" }, { from: "/howto50/Testing+web+services+using+SoapUI", to: "/howto50/testing-web-services-using-soapui" }, { from: "/howto50/The+Mobile+Slider+Custom+Widget", to: "/howto50/the-mobile-slider-custom-widget" }, { from: "/howto50/Tips+Tricks", to: "/howto/tips/" }, { from: "/howto50/Translatable+Validation+Messages", to: "/howto/tips/translatable-validation-messages" }, { from: "/howto50/Trends", to: "/developerportal/operate/trends" }, { from: "/howto50/Triggering+Logic+using+Microflows", to: "/howto50/triggering-logic-using-microflows" }, { from: "/howto50/Troubleshooting", to: "/deployment/on-premises/troubleshooting" }, { from: "/howto50/Troubleshooting+SQL+Server", to: "/deployment/on-premises/troubleshooting-sql-server" }, { from: "/howto50/Updating+a+Mendix+Application", to: "/deployment/on-premises/updating-a-mendix-application" }, { from: "/howto50/Using+Team+Server+-+Version+Control", to: "/howto50/using-team-server-version-control" }, { from: "/howto50/Using+the+Excel+Exporter", to: "/howto50/using-the-excel-exporter" }, { from: "/howto50/View+logging+-+Advanced", to: "/howto50/view-logging-advanced" }, { from: "/howto50/Working+with+images+and+files", to: "/howto50/working-with-images-and-files" }, { from: "/howto50/Working+With+Lists+in+a+Microflow", to: "/howto50/working-with-lists-in-a-microflow" }, { from: "/howto50/Working+With+Object+Events", to: "/howto50/working-with-object-events" }, /**************************************************** * HOWTO MENDIX 6 ****************************************************/ { from: "/howto6/Mendix+6+How-to's", to: "/howto6/" }, { from: "/howto6/Access+a+Samba+share+from+the+MxCloud", to: "/howto6/access-a-samba-share-from-the-mxcloud" }, { from: "/howto6/Activate+a+Mendix+License+on+Microsoft+Windows", to: "/deployment/on-premises/activate-a-mendix-license-on-microsoft-windows" }, { from: "/howto6/APIs", to: "/howto6/apis" }, { from: "/howto6/Build+a+Simple+HRM+App", to: "/howto6/build-a-simple-hrm-app" }, { from: "/howto6/Build+a+simple+HRM+app+1+Create+manage+and+deploy+the+app", to: "/howto6/build-a-simple-hrm-app-1-create-manage-and-deploy-the-app" }, { from: "/howto6/Build+a+simple+HRM+app+2+First+steps+in+building+a+rich+GUI", to: "/howto6/build-a-simple-hrm-app-2-first-steps-in-building-a-rich-gui" }, { from: "/howto6/Build+a+simple+HRM+app+3+Show+related+data+in+the+GUI", to: "/howto6/build-a-simple-hrm-app-3-show-related-data-in-the-gui" }, { from: "/howto6/Build+a+simple+HRM+app+4+Enrich+the+GUI+with+Filter+Options", to: "/howto6/build-a-simple-hrm-app-4-enrich-the-gui-with-filter-options" }, { from: "/howto6/Build+a+simple+HRM+app+5+Smarten+up+your+app+with+business+logic", to: "/howto6/build-a-simple-hrm-app-5-smarten-up-your-app-with-business-logic" }, { from: "/howto6/Building+a+Mendix+Hybrid+Mobile+App+for+Windows+Phone", to: "/howto6/building-a-mendix-hybrid-mobile-app-for-windows-phone" }, { from: "/howto6/Clear+Warning+Messages", to: "/howto6/clear-warning-messages" }, { from: "/howto6/Consuming+a+complex+web+service", to: "/howto6/consume-a-complex-web-service" }, { from: "/howto6/Consume+a+Complex+Web+Service", to: "/howto6/consume-a-complex-web-service" }, { from: "/howto6/Consume+a+REST+Service", to: "/howto6/consume-a-rest-service" }, { from: "/howto6/consuming+a+rest+service", to: "/howto6/consume-a-rest-service" }, { from: "/howto6/Consuming+a+simple+Web+Service", to: "/howto6/consume-a-simple-web-service" }, { from: "/howto6/Consume+a+Simple+Web+Service", to: "/howto6/consume-a-simple-web-service" }, { from: "/howto6/Contribute+to+a+GitHub+Repository", to: "/howto6/contribute-to-a-github-repository" }, { from: "/howto6/Create+a+Basic+Data+Layer", to: "/howto6/create-a-basic-data-layer" }, { from: "/howto6/Creating+a+Basic+Data+Layer", to: "/howto6/create-a-basic-data-layer" }, { from: "/howto6/Create+a+Basic+Hello+World+Custom+Widget", to: "/howto6/create-a-basic-hello-world-custom-widget" }, { from: "/howto6/Create+a+Chainable+Custom+Widget", to: "/howto6/create-a-chainable-custom-widget" }, { from: "/howto6/Create+a+Custom+Save+Button", to: "/howto6/create-a-custom-save-button" }, { from: "/howto6/Create+a+custom+theme+with+the+Mendix+UI+Framework", to: "/howto6/create-a-custom-theme-with-the-mendix-ui-framework" }, { from: "/howto6/Create+a+Secure+App", to: "/howto6/create-a-secure-app" }, { from: "/howto6/Creating+a+Secure+App", to: "/howto6/create-a-secure-app" }, { from: "/howto6/Create+and+Deploy+Your+First+App", to: "/howto6/create-and-deploy-your-first-app" }, { from: "/howto6/Create+your+first+Microflow+Hello+World", to: "/howto6/create-your-first-microflow-hello-world" }, { from: "/howto6/Create+Your+First+Two+Overview+and+Detail+Pages", to: "/howto6/create-your-first-two-overview-and-detail-pages" }, { from: "/howto6/Debug+a+Hybrid+Mobile+Application", to: "/howto6/debug-a-hybrid-mobile-application" }, { from: "/howto6/Debug+Java+Actions", to: "/howto6/debug-java-actions" }, { from: "/howto6/Debug+Java+Actions+Remotely", to: "/howto6/debug-java-actions-remotely" }, { from: "/howto6/Debug+Microflows", to: "/howto6/debug-microflows" }, { from: "/howto6/Debugging+Microflows", to: "/howto6/debug-microflows" }, { from: "/howto6/Debug+Microflows+Remotely", to: "/howto6/debug-microflows-remotely" }, { from: "/howto6/Define+Access+Rules+Using+XPath", to: "/howto6/define-access-rules-using-xpath" }, { from: "/howto6/Denormalize+Data+to+Improve+Performance", to: "/howto6/denormalize-data-to-improve-performance" }, { from: "/howto6/Deploy+a+Mendix+App+to+IBM+Bluemix", to: "/deployment/cloud-foundry/index" }, { from: "/howto6/deploying+a+mendix+app+to+ibm+bluemix", to: "/deployment/cloud-foundry/index" }, { from: "/howto6/Deploy+a+Mendix+App+to+Pivotal", to: "/deployment/cloud-foundry/index" }, { from: "/howto6/Deploy+Mendix+on+Microsoft+Windows", to: "/deployment/on-premises/deploy-mendix-on-microsoft-windows" }, { from: "/howto6/Deploying+a+Mendix+App+to+Cloud+Foundry", to: "/deployment/cloud-foundry/index" }, { from: "/howto6/deploying+to+the+cloud", to: "/developerportal/howto/deploying-to-the-cloud" }, { from: "/howto6/Design+the+Architecture", to: "/deployment/on-premises/design-the-architecture" }, { from: "/howto6/Architecture+Options", to: "/deployment/on-premises/design-the-architecture" }, { from: "/howto6/Detect+and+Resolve+Performance+Issues", to: "/howto6/detect-and-resolve-performance-issues" }, { from: "/howto6/Drag+Microflows+and+Pages+into+a+Microflow", to: "/howto6/drag-microflows-and-pages-into-a-microflow" }, { from: "/howto6/Explore+the+Connectors+and+Adapters", to: "/howto6/explore-the-connectors-and-adapters" }, { from: "/howto6/Exporting+XML+Documents", to: "/howto6/export-xml-documents" }, { from: "/howto6/Export+XML+Documents", to: "/howto6/export-xml-documents" }, { from: "/howto6/Expose+a+web+service", to: "/howto6/expose-a-web-service" }, { from: "/howto6/Exposing+a+web+service", to: "/howto6/expose-a-web-service" }, { from: "/howto6/Extendability", to: "/howto6/extendability" }, { from: "/howto6/Extending+Your+Application+with+Custom+Java", to: "/howto6/extending-your-application-with-custom-java" }, { from: "/howto6/Extract+and+use+sub+microflows", to: "/howto6/extract-and-use-sub-microflows" }, { from: "/howto6/Filtering+Data+on+an+Overview+Page", to: "/howto6/filtering-data-on-an-overview-page" }, { from: "/howto6/Finding+the+Root+Cause+of+Runtime+Errors", to: "/howto6/finding-the-root-cause-of-runtime-errors" }, { from: "/howto6/Gathering+user+feedback", to: "/developerportal/howto/gathering-user-feedback" }, { from: "/howto6/Getting+Started", to: "/howto6/getting-started" }, { from: "/howto6/Getting+started+with+the+Widget+Development+Plugin+for+Adobe+Brackets", to: "/howto6/getting-started-with-the-widget-development-plugin-for-adobe-brackets" }, { from: "/howto6/GUI's", to: "/howto6/guis" }, { from: "/howto6/Handle+Common+Mendix+SSO+Errors", to: "/howto6/handle-common-mendix-sso-errors" }, { from: "/howto6/High+Availability", to: "/deployment/on-premises/high-availability" }, { from: "/howto6/How+To+Enable+WKWebView+for+Hybrid+App+for+iOS", to: "/howto6/how-to-enable-wkwebview-for-hybrid-app-for-ios" }, { from: "/howto6/How+to+incorporate+Mendix+application+with+Amazon+Machine+Learning", to: "/howto6/how-to-incorporate-mendix-application-with-amazon-machine-learning" }, { from: "/howto6/Implementation+Guide", to: "/howto6/implementation-guide" }, { from: "/howto6/Importing+and+Exporting+Objects", to: "/howto6/importing-and-exporting-objects" }, { from: "/howto6/Importing+Excel+Documents", to: "/howto6/importing-excel-documents" }, { from: "/howto6/Importing+XML+documents", to: "/howto6/importing-xml-documents" }, { from: "/howto6/Install+and+Configure+the+SMTP+Module", to: "/howto6/install-and-configure-the-smtp-module" }, { from: "/howto6/Installing+Mendix+on+Debian+GNU+Linux", to: "/deployment/on-premises/installing-mendix-on-debian-gnu-linux" }, { from: "/howto6/Installing+Mendix+on+RedHat+and+CentOS", to: "/deployment/on-premises/installing-mendix-on-redhat-and-centos" }, { from: "/howto6/Integrating+a+Legacy+System+into+a+Mendix+App", to: "/howto6/integrating-a-legacy-system-into-a-mendix-app" }, { from: "/howto6/Integration", to: "/howto6/integration" }, { from: "/howto6/Java+API+Tutorial", to: "/howto6/java-api-tutorial" }, { from: "/howto6/Layouts+and+Snippets", to: "/howto6/layouts-and-snippets" }, { from: "/howto6/Log+Levels", to: "/howto6/log-levels" }, { from: "/howto6/Logic+and+Business+Rules", to: "/howto6/logic-and-business-rules" }, { from: "/howto6/Manage+Application+Performance+with+AppDynamics", to: "/howto6/manage-application-performance-with-appdynamics" }, { from: "/howto6/Manage+Application+Performance+with+New+Relic", to: "/howto6/manage-application-performance-with-new-relic" }, { from: "/howto6/Managing+your+Application+Requirements+with+Mendix", to: "/developerportal/howto/managing-your-application-requirements-with-mendix" }, { from: "/howto6/Mendix+on+Windows+-+Microsoft+SQL+Server", to: "/deployment/on-premises/mendix-on-windows-microsoft-sql-server" }, { from: "/howto6/Mendix+SQL+Maintenance+Plans", to: "/deployment/on-premises/mendix-sql-maintenance-plans" }, { from: "/howto6/Mobile", to: "/howto6/mobile" }, { from: "/howto6/Monitoring+and+Troubleshooting", to: "/howto6/monitoring-and-troubleshooting" }, { from: "/howto6/Monitoring+Mendix+using+JMX", to: "/howto6/monitoring-mendix-using-jmx" }, { from: "/howto6/monitoring+application+health", to: "/developerportal/operate/monitoring-application-health" }, { from: "/howto6/Optimizing+Microflow+Aggregates", to: "/howto6/optimizing-microflow-aggregates" }, { from: "/howto6/Optimizing+Retrieve+Activities", to: "/howto6/optimizing-retrieve-activities" }, { from: "/howto6/Push+Notifications", to: "/howto6/push-notifications" }, { from: "/howto6/Restoring+a+SQL+Server+database", to: "/deployment/on-premises/restoring-a-sql-server-database" }, { from: "/howto6/Scaffold+a+widget+with+the+Yeoman+Widget+generator", to: "/howto6/scaffold-a-widget-with-the-yeoman-widget-generator" }, { from: "/howto6/Scout+and+Windows+10+Workaround", to: "/howto6/scout-and-windows-10-workaround" }, { from: "/howto6/Security", to: "/howto6/security" }, { from: "/howto6/Security+checklist+for+your+on+premises+installation", to: "/deployment/on-premises/security-checklist-for-your-on-premises-installation" }, { from: "/howto6/Selenium+Support", to: "/howto6/selenium-support" }, { from: "/howto6/Set+Up+Anonymous+User+Security", to: "/howto6/set-up-anonymous-user-security" }, { from: "/howto6/Set+Up+Error+Handling", to: "/howto6/set-up-error-handling" }, { from: "/howto6/Setting+up+a+new+SQL+Server+database", to: "/deployment/on-premises/setting-up-a-new-sql-server-database" }, { from: "/howto6/Setting+up+a+SQL+Server+user", to: "/deployment/on-premises/setting-up-a-sql-server-user" }, { from: "/howto6/Setting+up+Apple+Push+Notification+Server", to: "/howto6/setting-up-apple-push-notification-server" }, { from: "/howto6/Setting+up+data+validation", to: "/howto6/setting-up-data-validation" }, { from: "/howto6/Setting+up+Google+Firebase+Cloud+Messaging+Server", to: "/howto6/setting-up-google-firebase-cloud-messaging-server" }, { from: "/howto6/Setting+up+monitoring+with+New+Relic", to: "/deployment/on-premises/setting-up-monitoring-with-new-relic" }, { from: "/howto6/Setting+up+the+database+user", to: "/deployment/on-premises/setting-up-the-database-user" }, { from: "/howto6/Setting+Up+the+Navigation+Structure", to: "/howto6/setting-up-the-navigation-structure" }, { from: "/howto6/Setup+Mendix+UI+Framework", to: "/howto6/setup-mendix-ui-framework" }, { from: "/howto6/Setup+Mendix+UI+Framework+with+just+CSS", to: "/howto6/setup-mendix-ui-framework-with-just-css" }, { from: "/howto6/Setup+Mendix+UI+Framework+with+Koala", to: "/howto6/setup-mendix-ui-framework-with-koala" }, { from: "/howto6/Sharing+the+Development+Database", to: "/howto6/sharing-the-development-database" }, { from: "/howto6/Solving+Load+and+Import+Errors", to: "/howto6/solving-load-and-import-errors" }, { from: "/howto6/Starting+your+own+repository", to: "/howto6/starting-your-own-repository" }, { from: "/howto6/String+Concatenation", to: "/howto6/string-concatenation" }, { from: "/howto6/Style+Google+Maps", to: "/howto6/style-google-maps" }, { from: "/howto6/Synchronizing+user+accounts+using+the+LDAP+module", to: "/howto6/synchronizing-user-accounts-using-the-ldap-module" }, { from: "/howto6/Testing", to: "/howto6/testing" }, { from: "/howto6/Testing+microflows+using+the+UnitTesting+module", to: "/howto6/testing-microflows-using-the-unittesting-module" }, { from: "/howto6/Testing+the+Implementation", to: "/howto6/testing-the-implementation" }, { from: "/howto6/Testing+web+services+using+SoapUI", to: "/howto6/testing-web-services-using-soapui" }, { from: "/howto6/The+Mobile+Slider+Custom+Widget", to: "/howto6/the-mobile-slider-custom-widget" }, { from: "/howto6/Translate+Your+App+Content", to: "/howto6/translate-your-app-content" }, { from: "/howto6/Triggering+Logic+using+Microflows", to: "/howto6/triggering-logic-using-microflows" }, { from: "/howto6/Troubleshooting", to: "/deployment/on-premises/troubleshooting" }, { from: "/howto6/Troubleshooting+SQL+Server", to: "/deployment/on-premises/troubleshooting-sql-server" }, { from: "/howto6/Updating+a+Mendix+Application", to: "/deployment/on-premises/updating-a-mendix-application" }, { from: "/howto6/Use+Connectors+and+Adapters", to: "/howto6/use-connectors-and-adapters" }, { from: "/howto6/Using+Team+Server+-+Version+Control", to: "/howto6/using-team-server-version-control" }, { from: "/howto6/Using+the+Excel+Exporter", to: "/howto6/using-the-excel-exporter" }, { from: "/howto6/Visualize+Data+using+the+ChartsJS+Module", to: "/howto6/visualize-data-using-the-chartsjs-module" }, { from: "/howto6/Working+with+images+and+files", to: "/howto6/working-with-images-and-files" }, { from: "/howto6/Working+With+Lists+in+a+Microflow", to: "/howto6/working-with-lists-in-a-microflow" }, { from: "/howto6/Working+With+Object+Events", to: "/howto6/working-with-object-events" }, /**************************************************** * HOWTO MENDIX 7 ****************************************************/ { from: "/howto/getting-started/build-an-iot-app", to: "/howto/tutorials/build-an-iot-app" }, { from: "/howto/getting-started/build-a-simple-hrm-app", to: "/howto/tutorials/build-a-simple-hrm-app" }, { from: "/howto/getting-started/create-a-to-do-app", to: "/howto/tutorials/create-a-to-do-app" }, { from: "/howto/deploying-a-mendix-app-to-cloud-foundry", to: "/deployment/cloud-foundry/index" }, { from: "/howto7/deploying-a-mendix-app-to-cloud-foundry", to: "/deployment/cloud-foundry/index" }, { from: "/deploy-a-mendix-app-to-cloud-foundry", to: "/deployment/cloud-foundry/index" }, { from: "/bestpractices/How+to+execute+an+SQL+statement+on+an+external+database", to: "/howto/integration/how-to-execute-an-sql-statement-on-an-external-database" }, { from: "/howto7/solving-load-and-import-errors", to: "/howto/monitoring-troubleshooting/solving-load-and-import-errors" }, /**************************************************** * Mendix Cloud ****************************************************/ { from: "/mendixcloud/Custom+Domains", to: "/developerportal/howto/custom-domains" }, { from: "/mendixcloud/custom-domains", to: "/developerportal/howto/custom-domains" }, { from: "/mendixcloud/Deploying+to+the+cloud", to: "/developerportal/howto/deploying-to-the-cloud" }, { from: "/mendixcloud/deploying-to-the-cloud", to: "/developerportal/howto/deploying-to-the-cloud" }, { from: "/mendixcloud/Different+user+logins+when+integrated+with+Mendix+SSO", to: "/deployment/mendixcloud/different-user-logins-when-integrated-with-mendix-sso" }, { from: "/mendixcloud/How+to+deploy+a+Mendix+app+on+Azure", to: "/deployment/azure/how-to-deploy-a-mendix-app-on-azure" }, { from: "/mendixcloud/how-to-link-app-to-node", to: "/developerportal/howto/how-to-link-app-to-node" }, { from: "/mendixcloud/Mendix+Cloud", to: "/deployment/mendixcloud/" }, { from: "/mendixcloud/Mendix+Cloud+Home", to: "/deployment/mendixcloud/" }, { from: "/mendixcloud/Integrate+your+app+with+Mendix+SSO", to: "/deployment/mendixcloud/integrate-your-app-with-mendix-sso" }, { from: "/mendixcloud/Java+in+the+Cloud", to: "/deployment/mendixcloud/java-in-the-cloud" }, { from: "/mendixcloud/Maintenance+Windows", to: "/developerportal/howto/maintenance-windows" }, { from: "/mendixcloud/maintenance-windows", to: "/developerportal/howto/maintenance-windows" }, { from: "/mendixcloud/migrating+to+v4", to: "/deployment/mendixcloud/migrating-to-v4" }, { from: "/developerportal/howto/migrating-to-v4", to: "/deployment/mendixcloud/migrating-to-v4" }, { from: "/mendixcloud/Monitoring+application+health", to: "/developerportal/operate/monitoring-application-health" }, { from: "/mendixcloud/monitoring-application-health", to: "/developerportal/operate/monitoring-application-health" }, { from: "/mendixcloud/Securing+Outgoing+Connections+from+your+Application", to: "/deployment/mendixcloud/securing-outgoing-connections-from-your-application" }, { from: "/mendixcloud/Sending+Email", to: "/deployment/mendixcloud/sending-email" }, { from: "/deployment/mendixcloud/how-to-deploy-a-mendix-app-on-azure", to: "/deployment/azure/how-to-deploy-a-mendix-app-on-azure" }, { from: "/mendixcloud/Trends", to: "/developerportal/operate/trends" }, /**************************************************** * SUPPORT ****************************************************/ { from: "/mxsupport/Google+Authenticator+and+SMS+Installation", to: "/howtogeneral/support/how-to-set-up-two-factor-authentication-with-google-authenticator" }, { from: "/mxsupport/Mendix+Support+Home", to: "/howtogeneral/support/" }, { from: "/mxsupport/TreeNavigation", to: "/howtogeneral/support/" }, { from: "/mxsupport/License+key+activation+on+Linux+server", to: "/howtogeneral/support/license-key-activation-on-linux" }, { from: "/mxsupport/Preparing+Your+Project+for+New+Customer+Support+Tool", to: "/howtogeneral/support/prepare-your-project-for-new-customer-support-portal" }, { from: "/mxsupport/Required+Network+Access+for+connecting+to+the+Mendix+Platform", to: "/howtogeneral/support/troubleshoot-network-issues-for-team-server" }, { from: "/mxsupport/Technical+Contact+Definition", to: "/developerportal/general/technical-contact" }, { from: "/mxsupport/technical-contact", to: "/developerportal/general/technical-contact" }, { from: "/howtogeneral/support/how-to-activate-or-deactivate-your-mendix-account", to: "/developerportal/howto/deactivate-users" }, { from: "/howtogeneral/support/technical-contact", to: "/developerportal/general/technical-contact" }, /**************************************************** * DEVELOPER PORTAL ****************************************************/ { from: "/developerportal/settings/technical-contact", to: "/developerportal/general/technical-contact" }, { from: "/developerportal/operate/mendix-cloud-status", to: "/developerportal/general/mendix-cloud-status" }, /**************************************************** * REFERENCE GUIDE MENDIX 4 ****************************************************/ { from: "/refguide4/Access+Rules", to: "/refguide4/access-rules" }, { from: "/refguide4/Action+Call+Activities", to: "/refguide4/action-call-activities" }, { from: "/refguide4/Activities", to: "/refguide4/activities" }, { from: "/refguide4/Add+Button", to: "/refguide4/add-button" }, { from: "/refguide4/Add+date+function+calls", to: "/refguide4/add-date-function-calls" }, { from: "/refguide4/Aggregate+List", to: "/refguide4/aggregate-list" }, { from: "/refguide4/And+Or+expressions", to: "/refguide4/and-or-expressions" }, { from: "/refguide4/Annotation", to: "/refguide4/annotation" }, { from: "/refguide4/Annotation+flow", to: "/refguide4/annotation-flow" }, { from: "/refguide4/App+Platform", to: "/refguide4/app-platform" }, { from: "/refguide4/Arithmetic+expressions", to: "/refguide4/arithmetic-expressions" }, { from: "/refguide4/Associations", to: "/refguide4/associations" }, { from: "/refguide4/Attributes", to: "/refguide4/attributes" }, { from: "/refguide4/Back+Button", to: "/refguide4/back-button" }, { from: "/refguide4/Basic+Reports", to: "/refguide4/basic-reports" }, { from: "/refguide4/Between+date+function+calls", to: "/refguide4/between-date-function-calls" }, { from: "/refguide4/Branch+Manager+Dialog", to: "/refguide4/branch-manager-dialog" }, { from: "/refguide4/Break+Event", to: "/refguide4/break-event" }, { from: "/refguide4/Button+Properties", to: "/refguide4/button-properties" }, { from: "/refguide4/Call+Web+Service", to: "/refguide4/call-web-service" }, { from: "/refguide4/Cancel+Button", to: "/refguide4/cancel-button" }, { from: "/refguide4/Cast+Object", to: "/refguide4/cast-object" }, { from: "/refguide4/certificates", to: "/deployment/mendixcloud/certificates" }, { from: "/refguide4/Change+List", to: "/refguide4/change-list" }, { from: "/refguide4/Change+Object", to: "/refguide4/change-object" }, { from: "/refguide4/Change+Variable", to: "/refguide4/change-variable" }, { from: "/refguide4/Check+Box", to: "/refguide4/check-box" }, { from: "/refguide4/Client", to: "/refguide4/client" }, { from: "/refguide4/Client+Activities", to: "/refguide4/client-activities" }, { from: "/refguide4/Close+Form", to: "/refguide4/close-form" }, { from: "/refguide4/Columns", to: "/refguide4/columns" }, { from: "/refguide4/Commit+Dialog", to: "/refguide4/commit-dialog" }, { from: "/refguide4/Common+Widgets", to: "/refguide4/common-widgets" }, { from: "/refguide4/Comparison+Search+Field", to: "/refguide4/comparison-search-field" }, { from: "/refguide4/Conditions", to: "/refguide4/conditions" }, { from: "/refguide4/Configuration", to: "/refguide4/configuration" }, { from: "/refguide4/Constants", to: "/refguide4/constants" }, { from: "/refguide4/Context+Mechanism", to: "/refguide4/context-mechanism" }, { from: "/refguide4/Continue+Event", to: "/refguide4/continue-event" }, { from: "/refguide4/Control+Bar", to: "/refguide4/control-bar" }, { from: "/refguide4/Create+Branch+Line+Dialog", to: "/refguide4/create-branch-line-dialog" }, { from: "/refguide4/Create+Deployment+Archive+Dialog", to: "/refguide4/create-deployment-archive-dialog" }, { from: "/refguide4/Create+List", to: "/refguide4/create-list" }, { from: "/refguide4/Create+Object", to: "/refguide4/create-object" }, { from: "/refguide4/Create+Variable", to: "/refguide4/create-variable" }, { from: "/refguide4/Custom+Settings", to: "/refguide4/custom-settings" }, { from: "/refguide4/Data+Grid", to: "/refguide4/data-grid" }, { from: "/refguide4/Data+Sets", to: "/refguide4/data-sets" }, { from: "/refguide4/Data+Sources", to: "/refguide4/data-sources" }, { from: "/refguide4/Data+View", to: "/refguide4/data-view" }, { from: "/refguide4/Data+View+Cancel+Button", to: "/refguide4/data-view-cancel-button" }, { from: "/refguide4/Data+View+Close+Button", to: "/refguide4/data-view-close-button" }, { from: "/refguide4/Data+View+Control+Bar", to: "/refguide4/data-view-control-bar" }, { from: "/refguide4/Data+View+Microflow+Button", to: "/refguide4/data-view-microflow-button" }, { from: "/refguide4/Data+View+Save+Button", to: "/refguide4/data-view-save-button" }, { from: "/refguide4/Database+Source", to: "/refguide4/database-source" }, { from: "/refguide4/Date+and+Time+Handling+in+3.0", to: "/refguide5/date-and-time-handling-in-3.0" }, { from: "/refguide4/Date+creation", to: "/refguide4/date-creation" }, { from: "/refguide4/Date+Picker", to: "/refguide4/date-picker" }, { from: "/refguide4/Date+Range+Field", to: "/refguide4/date-range-field" }, { from: "/refguide4/Date+Range+Selector", to: "/refguide4/date-range-selector" }, { from: "/refguide4/Date+Search+Field", to: "/refguide4/date-search-field" }, { from: "/refguide4/DateTime+handling+FAQ", to: "/refguide4/datetime-handling-faq" }, { from: "/refguide4/Delete+Button", to: "/refguide4/delete-button" }, { from: "/refguide4/Deploy+To+The+Cloud+Dialog", to: "/refguide4/deploy-to-the-cloud-dialog" }, { from: "/refguide4/Deselect+All+Button", to: "/refguide4/deselect-all-button" }, { from: "/refguide4/Dialogs", to: "/refguide4/dialogs" }, { from: "/refguide4/Document+Template", to: "/refguide4/document-template" }, { from: "/refguide4/Document+Templates", to: "/refguide4/document-templates" }, { from: "/refguide4/Domain+Model", to: "/refguide4/domain-model" }, { from: "/refguide4/Domain+to+XML+Mappings", to: "/refguide4/domain-to-xml-mappings" }, { from: "/refguide4/Download+File", to: "/refguide4/download-file" }, { from: "/refguide4/Download+From+Team+Server+Dialog", to: "/refguide4/download-from-team-server-dialog" }, { from: "/refguide4/Drop+Down", to: "/refguide4/drop-down" }, { from: "/refguide4/Drop+Down+Button", to: "/refguide4/drop-down-button" }, { from: "/refguide4/Drop+Down+Search+Field", to: "/refguide4/drop-down-search-field" }, { from: "/refguide4/Drop+Down+Widget", to: "/refguide4/drop-down-widget" }, { from: "/refguide4/Drop-Down+Widget", to: "/refguide4/drop-down-widget" }, { from: "/refguide4/Edit+Button", to: "/refguide4/edit-button" }, { from: "/refguide4/End+Event", to: "/refguide4/end-event" }, { from: "/refguide4/Entities", to: "/refguide4/entities" }, { from: "/refguide4/Enumeration+Values", to: "/refguide4/enumeration-values" }, { from: "/refguide4/Enumerations", to: "/refguide4/enumerations" }, { from: "/refguide4/Enumerations+in+microflow+expressions", to: "/refguide4/enumerations-in-microflow-expressions" }, { from: "/refguide4/Error+Event", to: "/refguide4/error-event"
{ from: "/refguide4/Event+Handlers", to: "/refguide4/event-handlers" }, { from: "/refguide4/Exclusive+Split", to: "/refguide4/exclusive-split" }, { from: "/refguide4/Export+To+CSV+Button", to: "/refguide4/export-to-csv-button" }, { from: "/refguide4/Export+To+Excel+Button", to: "/refguide4/export-to-excel-button" }, { from: "/refguide4/Export+XML", to: "/refguide4/export-xml" }, { from: "/refguide4/External+Link", to: "/refguide4/external-link" }, { from: "/refguide4/File+Manager", to: "/refguide4/file-manager" }, { from: "/refguide4/Form+Concepts", to: "/refguide4/form-concepts" }, { from: "/refguide4/Forms", to: "/refguide4/forms" }, { from: "/refguide4/Garbage+collection", to: "/refguide4/garbage-collection" }, { from: "/refguide4/Generate+Document", to: "/refguide4/generate-document" }, { from: "/refguide4/Goal", to: "/refguide4/" }, { from: "/refguide4/History+Dialog", to: "/refguide4/history-dialog" }, { from: "/refguide4/Horizontal+Split+Pane", to: "/refguide4/horizontal-split-pane" }, { from: "/refguide4/If+expressions", to: "/refguide4/if-expressions" }, { from: "/refguide4/Image+Uploader", to: "/refguide4/image-uploader" }, { from: "/refguide4/Image+Viewer", to: "/refguide4/image-viewer" }, { from: "/refguide4/Images", to: "/refguide4/images" }, { from: "/refguide4/Import+XML", to: "/refguide4/import-xml" }, { from: "/refguide4/Imported+web+service", to: "/refguide4/imported-web-service" }, { from: "/refguide4/Imported+Web+Services", to: "/refguide4/imported-web-services" }, { from: "/refguide4/Indexes", to: "/refguide4/indexes" }, { from: "/refguide4/Inheritance+Split", to: "/refguide4/inheritance-split" }, { from: "/refguide4/Input+Reference+Set+Selector", to: "/refguide4/input-reference-set-selector" }, { from: "/refguide4/Integration", to: "/refguide4/integration" }, { from: "/refguide4/Integration+Activities", to: "/refguide4/integration-activities" }, { from: "/refguide4/Java+Action+Call", to: "/refguide4/java-action-call" }, { from: "/refguide4/Java+Actions", to: "/refguide4/java-actions" }, { from: "/refguide4/Java+API+Tutorial", to: "/howto40/java-api-tutorial" }, { from: "/refguide4/Java+in+the+Cloud", to: "/refguide4/java-in-the-cloud" }, { from: "/refguide4/Java+Programming", to: "/refguide4/java-programming" }, { from: "/refguide4/Label", to: "/refguide4/label" }, { from: "/refguide4/Languages", to: "/refguide4/languages" }, { from: "/refguide4/Link+Button", to: "/refguide4/link-button" }, { from: "/refguide4/List+Activities", to: "/refguide4/list-activities" }, { from: "/refguide4/List+Operation", to: "/refguide4/list-operation" }, { from: "/refguide4/List+View", to: "/refguide4/list-view" }, { from: "/refguide4/Log+Message", to: "/refguide4/log-message" }, { from: "/refguide4/Logging", to: "/refguide4/logging" }, { from: "/refguide4/Logging+Activities", to: "/refguide4/logging-activities" }, { from: "/refguide4/Loop", to: "/refguide4/loop" }, { from: "/refguide4/Map+element+to+entity", to: "/refguide4/map-element-to-entity" }, { from: "/refguide4/Map+entity+to+element", to: "/refguide4/map-entity-to-element" }, { from: "/refguide4/Mathematical+function+calls", to: "/refguide4/mathematical-function-calls" }, { from: "/refguide4/Merge", to: "/refguide4/merge" }, { from: "/refguide4/Merge+Dialog", to: "/refguide4/merge-dialog" }, { from: "/refguide4/Microflow", to: "/refguide4/microflow" }, { from: "/refguide4/Microflow+Button", to: "/refguide4/microflow-button" }, { from: "/refguide4/Microflow+Call", to: "/refguide4/microflow-call" }, { from: "/refguide4/Microflow+Element+Common+Properties", to: "/refguide4/microflow-element-common-properties" }, { from: "/refguide4/Microflow+Expressions", to: "/refguide4/microflow-expressions" }, { from: "/refguide4/Microflow+Trigger", to: "/refguide4/microflow-trigger" }, { from: "/refguide4/Microflows", to: "/refguide4/microflows" }, { from: "/refguide4/Mobile+Form", to: "/refguide4/mobile-form" }, { from: "/refguide4/Mobile+Form+Buttons", to: "/refguide4/mobile-form-buttons" }, { from: "/refguide4/Mobile+Forms", to: "/refguide4/mobile-forms" }, { from: "/refguide4/Mobile+Microflow+Button", to: "/refguide4/mobile-microflow-button" }, { from: "/refguide4/Mobile+New+Button", to: "/refguide4/mobile-new-button" }, { from: "/refguide4/Modeler", to: "/refguide4/modeler" }, { from: "/refguide4/Module+Role", to: "/refguide4/module-role" }, { from: "/refguide4/Module+Security", to: "/refguide4/module-security" }, { from: "/refguide4/Modules", to: "/refguide4/modules" }, { from: "/refguide4/Monitoring", to: "/refguide4/monitoring" }, { from: "/refguide4/Moving+from+3+to+4", to: "/refguide4/moving-from-3-to-4" }, { from: "/refguide4/Navigation", to: "/refguide4/navigation" }, { from: "/refguide4/Navigation+Item", to: "/refguide4/navigation-item" }, { from: "/refguide4/Navigation+List", to: "/refguide4/navigation-list" }, { from: "/refguide4/New+Button", to: "/refguide4/new-button" }, { from: "/refguide4/New+Project+Dialog", to: "/refguide4/new-project-dialog" }, { from: "/refguide4/Object+Activities", to: "/refguide4/object-activities" }, { from: "/refguide4/Open+Project+Dialog", to: "/refguide4/open-project-dialog" }, { from: "/refguide4/Opening+Forms", to: "/refguide4/opening-forms" }, { from: "/refguide4/Operations", to: "/refguide4/operations" }, { from: "/refguide4/OQL", to: "/refguide4/oql" }, { from: "/refguide4/OQL+Aggregation", to: "/refguide4/oql-aggregation" }, { from: "/refguide4/OQL+Case+Expression", to: "/refguide4/oql-case-expression" }, { from: "/refguide4/OQL+CAST", to: "/refguide4/oql-cast" }, { from: "/refguide4/OQL+COALESCE", to: "/refguide4/oql-coalesce" }, { from: "/refguide4/OQL+DATEDIFF", to: "/refguide4/oql-datediff" }, { from: "/refguide4/OQL+DATEPART", to: "/refguide4/oql-datepart" }, { from: "/refguide4/OQL+Expressions", to: "/refguide4/oql-expressions" }, { from: "/refguide4/OQL+From+Clause", to: "/refguide4/oql-from-clause" }, { from: "/refguide4/OQL+FULL+OUTER+JOIN", to: "/refguide4/oql-full-outer-join" }, { from: "/refguide4/OQL+Functions", to: "/refguide4/oql-functions" }, { from: "/refguide4/OQL+Group+by+Clause", to: "/refguide4/oql-group-by-clause" }, { from: "/refguide4/OQL+INNER+JOIN", to: "/refguide4/oql-inner-join" }, { from: "/refguide4/OQL+LEFT+OUTER+JOIN", to: "/refguide4/oql-left-outer-join" }, { from: "/refguide4/OQL+LENGTH", to: "/refguide4/oql-length" }, { from: "/refguide4/OQL+Limit+Clause", to: "/refguide4/oql-limit-clause" }, { from: "/refguide4/OQL+Operators", to: "/refguide4/oql-operators" }, { from: "/refguide4/OQL+Order+by+Clause", to: "/refguide4/oql-order-by-clause" }, { from: "/refguide4/OQL+Parameters", to: "/refguide4/oql-parameters" }, { from: "/refguide4/OQL+RANGEBEGIN", to: "/refguide4/oql-rangebegin" }, { from: "/refguide4/OQL+RANGEEND", to: "/refguide4/oql-rangeend" }, { from: "/refguide4/OQL+RIGHT+OUTER+JOIN", to: "/refguide4/oql-right-outer-join" }, { from: "/refguide4/OQL+ROUND", to: "/refguide4/oql-round" }, { from: "/refguide4/OQL+Select+Clause", to: "/refguide4/oql-select-clause" }, { from: "/refguide4/OQL+Where+Clause", to: "/refguide4/oql-where-clause" }, { from: "/refguide4/Oracle", to: "/refguide4/oracle" }, { from: "/refguide4/Parameter", to: "/refguide4/parameter" }, { from: "/refguide4/Parse+and+format+date+function+calls", to: "/refguide4/parse-and-format-date-function-calls" }, { from: "/refguide4/Parse+and+format+float+function+calls", to: "/refguide4/parse-and-format-float-function-calls" }, { from: "/refguide4/Parse+integer", to: "/refguide4/parse-integer" }, { from: "/refguide4/Persistability", to: "/refguide4/persistability" }, { from: "/refguide4/Persistent+Create+Object", to: "/refguide4/persistent-create-object" }, { from: "/refguide4/Preferences+Dialog", to: "/refguide4/preferences-dialog" }, { from: "/refguide4/Project", to: "/refguide4/project" }, { from: "/refguide4/Project+Security", to: "/refguide4/project-security" }, { from: "/refguide4/Project+Settings", to: "/refguide4/project-settings" }, { from: "/refguide4/Published+web+service", to: "/refguide4/published-web-service" }, { from: "/refguide4/Published+Web+Services", to: "/refguide4/published-web-services" }, { from: "/refguide4/Range+Search+Field", to: "/refguide4/range-search-field" }, { from: "/refguide4/Reference+Guide+4+Introduction", to: "/refguide4/" }, { from: "/refguide4/Reference+Selector", to: "/refguide4/reference-selector" }, { from: "/refguide4/Reference+Set+Selector", to: "/refguide4/reference-set-selector" }, { from: "/refguide4/Regular+Expressions", to: "/refguide4/regular-expressions" }, { from: "/refguide4/Relational+expressions", to: "/refguide4/relational-expressions" }, { from: "/refguide4/Release+Notes", to: "/refguide4/release-notes" }, { from: "/refguide4/Remove+Button", to: "/refguide4/remove-button" }, { from: "/refguide4/Report+Button", to: "/refguide4/report-button" }, { from: "/refguide4/Report+Chart", to: "/refguide4/report-chart" }, { from: "/refguide4/Report+Pane", to: "/refguide4/report-pane" }, { from: "/refguide4/Reporting", to: "/refguide4/reporting" }, { from: "/refguide4/Retrieve", to: "/refguide4/retrieve" }, { from: "/refguide4/Rollback+Object", to: "/refguide4/rollback-object" }, { from: "/refguide4/Rules", to: "/refguide4/rules" }, { from: "/refguide4/Runtime", to: "/refguide4/runtime" }, { from: "/refguide4/Save+Button", to: "/refguide4/save-button" }, { from: "/refguide4/Scheduled+Events", to: "/refguide4/scheduled-events" }, { from: "/refguide4/Search+Bar", to: "/refguide4/search-bar" }, { from: "/refguide4/Search+Button", to: "/refguide4/search-button" }, { from: "/refguide4/Search+Field+Properties", to: "/refguide4/search-field-properties" }, { from: "/refguide4/Section", to: "/refguide4/section" }, { from: "/refguide4/Security", to: "/refguide4/security" }, { from: "/refguide4/Select+All+Button", to: "/refguide4/select-all-button" }, { from: "/refguide4/Select+Button", to: "/refguide4/select-button" }, { from: "/refguide4/Select+elements", to: "/refguide4/select-elements" }, { from: "/refguide4/Sequence+Flow", to: "/refguide4/sequence-flow" }, { from: "/refguide4/Show+Form", to: "/refguide4/show-form" }, { from: "/refguide4/Show+Message", to: "/refguide4/show-message" }, { from: "/refguide4/Sign+In+Dialog", to: "/refguide4/sign-in-dialog" }, { from: "/refguide4/Sign+Out+Button", to: "/refguide4/sign-out-button" }, { from: "/refguide4/Sort+Bar", to: "/refguide4/sort-bar" }, { from: "/refguide4/Special+checks", to: "/refguide4/special-checks" }, { from: "/refguide4/Start+Event", to: "/refguide4/start-event" }, { from: "/refguide4/Starting+Microflows", to: "/refguide4/starting-microflows" }, { from: "/refguide4/String+function+calls", to: "/refguide4/string-function-calls" }, { from: "/refguide4/Style", to: "/refguide4/style" }, { from: "/refguide4/System+Requirements", to: "/refguide4/system-requirements" }, { from: "/refguide4/System+Texts", to: "/refguide4/system-texts" }, { from: "/refguide4/Tab+Control", to: "/refguide4/tab-control" }, { from: "/refguide4/Tab+Page", to: "/refguide4/tab-page" }, { from: "/refguide4/Table", to: "/refguide4/table" }, { from: "/refguide4/Table+Cell", to: "/refguide4/table-cell" }, { from: "/refguide4/Table+Row", to: "/refguide4/table-row" }, { from: "/refguide4/Team+Server", to: "/refguide4/team-server" }, { from: "/refguide4/Team+Server+FAQ", to: "/refguide4/team-server-faq" }, { from: "/refguide4/Template+Grid", to: "/refguide4/template-grid" }, { from: "/refguide4/Text+Area", to: "/refguide4/text-area" }, { from: "/refguide4/Text+Box", to: "/refguide4/text-box" }, { from: "/refguide4/Text+Search+Field", to: "/refguide4/text-search-field" }, { from: "/refguide4/To+string", to: "/refguide4/to-string" }, { from: "/refguide4/Translatable+Texts", to: "/refguide4/translatable-texts" }, { from: "/refguide4/TreeNavigation", to: "/refguide4/" }, { from: "/refguide4/Trim+to+date", to: "/refguide4/trim-to-date" }, { from: "/refguide4/Unary+expressions", to: "/refguide4/unary-expressions" }, { from: "/refguide4/Upload+To+Team+Server+Dialog", to: "/refguide4/upload-to-team-server-dialog" }, { from: "/refguide4/User+Role", to: "/refguide4/user-role" }, { from: "/refguide4/User+Roles", to: "/refguide4/project-security" }, { from: "/refguide4/Using+a+proxy+to+call+a+webservice", to: "/refguide4/using-a-proxy-to-call-a-webservice" }, { from: "/refguide4/Using+Eclipse", to: "/refguide4/using-eclipse" }, { from: "/refguide4/Validation+Feedback", to: "/refguide4/validation-feedback" }, { from: "/refguide4/Validation+Rules", to: "/refguide4/validation-rules" }, { from: "/refguide4/Variable+Activities", to: "/refguide4/variable-activities" }, { from: "/refguide4/Version+Control", to: "/refguide4/version-control" }, { from: "/refguide4/Version+Control+Concepts", to: "/refguide4/version-control-concepts" }, { from: "/refguide4/Version+Control+Scenarios", to: "/refguide4/version-control-scenarios" }, { from: "/refguide4/Vertical+Split+Pane", to: "/refguide4/vertical-split-pane" }, { from: "/refguide4/Web+Form", to: "/refguide4/web-form" }, { from: "/refguide4/Web+Forms", to: "/refguide4/web-forms" }, { from: "/refguide4/Widget+Events", to: "/refguide4/widget-events" }, { from: "/refguide4/Widget+Properties", to: "/refguide4/widget-properties" }, { from: "/refguide4/XML+Schema+Support", to: "/refguide4/xml-schema-support" }, { from: "/refguide4/XML+Schemas", to: "/refguide4/xml-schemas" }, { from: "/refguide4/XML+to+Domain+Mappings", to: "/refguide4/xml-to-domain-mappings" }, { from: "/refguide4/XPath", to: "/refguide4/xpath" }, { from: "/refguide4/XPath+avg", to: "/refguide4/xpath-avg" }, { from: "/refguide4/XPath+Constraint+Functions", to: "/refguide4/xpath-constraint-functions" }, { from: "/refguide4/XPath+Constraints", to: "/refguide4/xpath-constraints" }, { from: "/refguide4/XPath+contains", to: "/refguide4/xpath-contains" }, { from: "/refguide4/XPath+count", to: "/refguide4/xpath-count" }, { from: "/refguide4/XPath+day+from+dateTime", to: "/refguide4/xpath-day-from-datetime" }, { from: "/refguide4/XPath+day+of+year+from+dateTime", to: "/refguide4/xpath-day-of-year-from-datetime" }, { from: "/refguide4/XPath+ends+with", to: "/refguide4/xpath-ends-with" }, { from: "/refguide4/XPath+Expressions", to: "/refguide4/xpath-expressions" }, { from: "/refguide4/XPath+false", to: "/refguide4/xpath-false" }, { from: "/refguide4/XPath+hours+from+dateTime", to: "/refguide4/xpath-hours-from-datetime" }, { from: "/refguide4/XPath+id", to: "/refguide4/xpath-id" }, { from: "/refguide4/XPath+Keywords+and+System+Variables", to: "/refguide4/xpath-keywords-and-system-variables" }, { from: "/refguide4/XPath+length", to: "/refguide4/xpath-length" }, { from: "/refguide4/XPath+max", to: "/refguide4/xpath-max" }, { from: "/refguide4/XPath+min", to: "/refguide4/xpath-min" }, { from: "/refguide4/XPath+minutes+from+dateTime", to: "/refguide4/xpath-minutes-from-datetime" }, { from: "/refguide4/XPath+month+from+dateTime", to: "/refguide4/xpath-month-from-datetime" }, { from: "/refguide4/XPath+not", to: "/refguide4/xpath-not" }, { from: "/refguide4/XPath+Operators", to: "/refguide4/xpath-operators" }, { from: "/refguide4/XPath+quarter+from+dateTime", to: "/refguide4/xpath-quarter-from-datetime" }, { from: "/refguide4/XPath+Query+Functions", to: "/refguide4/xpath-query-functions" }, { from: "/refguide4/XPath+seconds+from+dateTime", to: "/refguide4/xpath-seconds-from-datetime" }, { from: "/refguide4/XPath+starts+with", to: "/refguide4/xpath-starts-with" }, { from: "/refguide4/XPath+string+length", to: "/refguide4/xpath-string-length" }, { from: "/refguide4/XPath+sum", to: "/refguide4/xpath-sum" }, { from: "/refguide4/XPath+Tokens", to: "/refguide4/xpath-tokens" }, { from: "/refguide4/XPath+true", to: "/refguide4/xpath-true" }, { from: "/refguide4/XPath+week+from+dateTime", to: "/refguide4/xpath-week-from-datetime" }, { from: "/refguide4/XPath+weekday+from+dateTime", to: "/refguide4/xpath-weekday-from-datetime" }, { from: "/refguide4/XPath+year+from+dateTime", to: "/refguide4/xpath-year-from-datetime" }, /**************************************************** * REFERENCE GUIDE MENDIX 5 ****************************************************/ { from: "/refguide5/TreeNavigation", to: "/refguide5/" }, { from: "/refguide5/Access+Rules", to: "/refguide5/access-rules" }, { from: "/refguide5/Action+Button", to: "/refguide5/action-button" }, { from: "/refguide5/Action+Call+Activities", to: "/refguide5/action-call-activities" }, { from: "/refguide5/Actions", to: "/refguide5/actions" }, { from: "/refguide5/Activities", to: "/refguide5/activities" }, { from: "/refguide5/Add+button", to: "/refguide5/add-button" }, { from: "/refguide5/Add+date+function+calls", to: "/refguide5/add-date-function-calls" }, { from: "/refguide5/Administrator", to: "/refguide5/administrator" }, { from: "/refguide5/Aggregate+List", to: "/refguide5/aggregate-list" }, { from: "/refguide5/Annotation", to: "/refguide5/annotation" }, { from: "/refguide5/Annotation+flow", to: "/refguide5/annotation-flow" }, { from: "/refguide5/Annotations", to: "/refguide5/annotations" }, { from: "/refguide5/Anonymous+Users", to: "/refguide5/anonymous-users" }, { from: "/refguide5/App+Platform", to: "/refguide5/app-platform" }, { from: "/refguide5/App+Settings+Dialog", to: "/refguide5/app-settings-dialog" }, { from: "/refguide5/New+Project+Dialog", to: "/refguide5/app-settings-dialog" }, { from: "/refguide5/Arithmetic+expressions", to: "/refguide5/arithmetic-expressions" }, { from: "/refguide5/Association+Source", to: "/refguide5/association-source" }, { from: "/refguide5/Associations", to: "/refguide5/associations" }, { from: "/refguide5/Attributes", to: "/refguide5/attributes" }, { from: "/refguide5/Back+button", to: "/refguide5/back-button" }, { from: "/refguide5/Basic+Reports", to: "/refguide5/basic-reports" }, { from: "/refguide5/Between+date+function+calls", to: "/refguide5/between-date-function-calls" }, { from: "/refguide5/Boolean+expressions", to: "/refguide5/boolean-expressions" }, { from: "/refguide5/Branch+Manager+Dialog", to: "/refguide5/branch-manager-dialog" }, { from: "/refguide5/Break+Event", to: "/refguide5/break-event" }, { from: "/refguide5/Button+Widgets", to: "/refguide5/button-widgets" }, { from: "/refguide5/Page+Buttons", to: "/refguide5/button-widgets" }, { from: "/refguide5/Call+Web+Service", to: "/refguide5/call-web-service" }, { from: "/refguide5/Cancel+button", to: "/refguide5/cancel-button" }, { from: "/refguide5/Cast+Object", to: "/refguide5/cast-object" }, { from: "/refguide5/Cell+Document+Template", to: "/refguide5/cell-document-template" }, { from: "/refguide5/certificates", to: "/deployment/mendixcloud/certificates" }, { from: "/refguide5/Change+List", to: "/refguide5/change-list" }, { from: "/refguide5/Change+Object", to: "/refguide5/change-object" }, { from: "/refguide5/Change+Variable", to: "/refguide5/change-variable" }, { from: "/refguide5/Check+box", to: "/refguide5/check-box" }, { from: "/refguide5/Client+Activities", to: "/refguide5/client-activities" }, { from: "/refguide5/Close+Form", to: "/refguide5/close-form" }, { from: "/refguide5/Clustered+Mendix+Runtime", to: "/refguide5/clustered-mendix-runtime" }, { from: "/refguide5/Clustered+Mendix+Business+Server", to: "/refguide5/clustered-mendix-runtime" }, { from: "/refguide5/Columns", to: "/refguide5/columns" }, { from: "/refguide5/Columns+Document+Template", to: "/refguide5/columns-document-template" }, { from: "/refguide5/Commit+Dialog", to: "/refguide5/commit-dialog" }, { from: "/refguide5/Committing+Objects", to: "/refguide5/committing-objects" }, { from: "/refguide5/Common+Widget+Properties", to: "/refguide5/common-widget-properties" }, { from: "/refguide5/Common+Widgets", to: "/refguide5/common-widgets" }, { from: "/refguide5/Comparison+Search+Field", to: "/refguide5/comparison-search-field" }, { from: "/refguide5/Conditions", to: "/refguide5/conditions" }, { from: "/refguide5/Configuration", to: "/refguide5/configuration" }, { from: "/refguide5/Constants", to: "/refguide5/constants" }, { from: "/refguide5/Consumed+App+Services", to: "/refguide5/consumed-app-services" }, { from: "/refguide5/Consumed+web+service", to: "/refguide5/consumed-web-service" }, { from: "/refguide5/Consumed+Web+Services", to: "/refguide5/consumed-web-services" }, { from: "/refguide5/Container", to: "/refguide5/container" }, { from: "/refguide5/Container+Widgets", to: "/refguide5/container-widgets" }, { from: "/refguide5/Context+Mechanism", to: "/refguide5/context-mechanism" }, { from: "/refguide5/Continue+Event", to: "/refguide5/continue-event" }, { from: "/refguide5/Control+Bar", to: "/refguide5/control-bar" }, { from: "/refguide5/Create+Branch+Line+Dialog", to: "/refguide5/create-branch-line-dialog" }, { from: "/refguide5/Create+Deployment+Archive+Dialog", to: "/refguide5/create-deployment-archive-dialog" }, { from: "/refguide5/Create+List", to: "/refguide5/create-list" }, { from: "/refguide5/Create+Object", to: "/refguide5/create-object" }, { from: "/refguide5/Create+Variable", to: "/refguide5/create-variable" }, { from: "/refguide5/Custom+Settings", to: "/refguide5/custom-settings" }, { from: "/refguide5/Customizing+Hybrid+Mobile+Apps", to: "/refguide5/customizing-hybrid-mobile-apps" }, { from: "/refguide5/Customizing+PhoneGap+Build+packages", to: "/refguide5/customizing-phonegap-build-packages" }, { from: "/refguide5/Data+grid", to: "/refguide5/data-grid" }, { from: "/refguide5/Data+Grid+Document+Template", to: "/refguide5/data-grid-document-template" }, { from: "/refguide5/Data+Sets", to: "/refguide5/data-sets" }, { from: "/refguide5/Data+Sources", to: "/refguide5/data-sources" }, { from: "/refguide5/Data+Types", to: "/refguide5/data-types" }, { from: "/refguide5/Data+view", to: "/refguide5/data-view" }, { from: "/refguide5/Data+view+action+button", to: "/refguide5/data-view-action-button" }, { from: "/refguide5/Data+view+cancel+button", to: "/refguide5/data-view-cancel-button" }, { from: "/refguide5/Data+view+close+button", to: "/refguide5/data-view-close-button" }, { from: "/refguide5/Data+view+control+bar", to: "/refguide5/data-view-control-bar" }, { from: "/refguide5/Data+View+Document+Template", to: "/refguide5/data-view-document-template" }, { from: "/refguide5/Data+view+microflow+button", to: "/refguide5/data-view-microflow-button" }, { from: "/refguide5/Data+view+save+button", to: "/refguide5/data-view-save-button" }, { from: "/refguide5/Data+Widgets", to: "/refguide5/data-widgets" }, { from: "/refguide5/Database+Source", to: "/refguide5/database-source" }, { from: "/refguide5/Date+and+Time+Handling+in+3.0", to: "/refguide5/date-and-time-handling-in-3.0" }, { from: "/refguide5/Date+creation", to: "/refguide5/date-creation" }, { from: "/refguide5/Date+picker", to: "/refguide5/date-picker" }, { from: "/refguide5/Date+Range+Field", to: "/refguide5/date-range-field" }, { from: "/refguide5/Date+Range+Selector", to: "/refguide5/date-range-selector" }, { from: "/refguide5/DateTime+handling+FAQ", to: "/refguide5/datetime-handling-faq" }, { from: "/refguide5/Delete+button", to: "/refguide5/delete-button" }, { from: "/refguide5/Delete+Object(s)", to: "/refguide5/deleting-objects" }, { from: "/refguide5/Deleting+Objects", to: "/refguide5/deleting-objects" }, { from: "/refguide5/Demo+Users", to: "/refguide5/demo-users" }, { from: "/refguide5/Deploy+To+The+Cloud+Dialog", to: "/refguide5/deploy-to-the-cloud-dialog" }, { from: "/refguide5/Deselect+all+button", to: "/refguide5/deselect-all-button" }, { from: "/refguide5/Developing+Hybrid+Mobile+Apps", to: "/refguide5/developing-hybrid-mobile-apps" }, { from: "/refguide5/Device+Type", to: "/refguide5/device-type" }, { from: "/refguide5/Dialogs", to: "/refguide5/dialogs" }, { from: "/refguide5/Document+Template", to: "/refguide5/document-template" }, { from: "/refguide5/Document+Templates", to: "/refguide5/document-templates" }, { from: "/refguide5/Domain+Model", to: "/refguide5/domain-model" }, { from: "/refguide5/Domain+to+XML+Mappings", to: "/refguide5/domain-to-xml-mappings" }, { from: "/refguide5/Download+File", to: "/refguide5/download-file" }, { from: "/refguide5/Download+From+Team+Server+Dialog", to: "/refguide5/download-from-team-server-dialog" }, { from: "/refguide5/Drop-down", to: "/refguide5/drop_down" }, { from: "/refguide5/Drop-Down+Widget", to: "/refguide5/drop_down" }, { from: "/refguide5/Drop-Down Widget", to: "/refguide5/drop_down" }, { from: "/refguide5/Drop+Down", to: "/refguide5/drop-down" }, { from: "/refguide5/Drop+down+button", to: "/refguide5/drop-down-button" }, { from: "/refguide5/Drop+Down+Search+Field", to: "/refguide5/drop-down-search-field" }, { from: "/refguide5/Dynamic+Image+Document+Template", to: "/refguide5/dynamic-image-document-template" }, { from: "/refguide5/Dynamic+Label+Document+Template", to: "/refguide5/dynamic-label-document-template" }, { from: "/refguide5/Dynamic+Label+(Document+Template)", to: "/refguide5/dynamic-label-document-template" }, { from: "/refguide5/Edit+button", to: "/refguide5/edit-button" }, { from: "/refguide5/End+Event", to: "/refguide5/end-event" }, { from: "/refguide5/Entities", to: "/refguide5/entities" }, { from: "/refguide5/Enumeration+Values", to: "/refguide5/enumeration-values" }, { from: "/refguide5/Enumerations", to: "/refguide5/enumerations" }, { from: "/refguide5/Enumerations+in+microflow+expressions", to: "/refguide5/enumerations-in-microflow-expressions" }, { from: "/refguide5/Error+Event", to: "/refguide5/error-event" }, { from: "/refguide5/Event+Handlers", to: "/refguide5/event-handlers" }, { from: "/refguide5/Exclusive+Split", to: "/refguide5/exclusive-split" }, { from: "/refguide5/Export+to+CSV+button", to: "/refguide5/export-to-csv-button" }, { from: "/refguide5/Export+to+excel+button", to: "/refguide5/export-to-excel-button" }, { from: "/refguide5/Export+XML", to: "/refguide5/export-xml" }, { from: "/refguide5/File+manager", to: "/refguide5/file-manager" }, { from: "/refguide5/File+Widgets", to: "/refguide5/file-widgets" }, { from: "/refguide5/Footer+Document+Template", to: "/refguide5/footer-document-template" }, { from: "/refguide5/Garbage+collection", to: "/refguide5/garbage-collection" }, { from: "/refguide5/General", to: "/refguide5/general" }, { from: "/refguide5/Generate+Document", to: "/refguide5/generate-document" }, { from: "/refguide5/Getting+the+Mendix+Developer+App", to: "/refguide5/getting-the-mendix-developer-app" }, { from: "/refguide5/Goal", to: "/refguide5/" }, { from: "/refguide5/Grid+action+button", to: "/refguide5/grid-action-button" }, { from: "/refguide5/Grid+microflow+button", to: "/refguide5/grid-microflow-button" }, { from: "/refguide5/Grid+New+Button", to: "/refguide5/grid-new-button" }, { from: "/refguide5/Group+box", to: "/refguide5/group-box" }, { from: "/refguide5/Section", to: "/refguide5/group-box" }, { from: "/refguide5/Header", to: "/refguide5/header" }, { from: "/refguide5/Header+Document+Template", to: "/refguide5/header-document-template" }, { from: "/refguide5/History+Dialog", to: "/refguide5/history-dialog" }, { from: "/refguide5/Horizontal+Split+Pane", to: "/refguide5/horizontal-split-pane" }, { from: "/refguide5/If+expressions", to: "/refguide5/if-expressions" }, { from: "/refguide5/Image", to: "/refguide5/image" }, { from: "/refguide5/Image+uploader", to: "/refguide5/image-uploader" }, { from: "/refguide5/Image+viewer", to: "/refguide5/image-viewer" }, { from: "/refguide5/Images", to: "/refguide5/images" }, { from: "/refguide5/Import+XML", to: "/refguide5/import-xml" }, { from: "/refguide5/Inheritance+Split", to: "/refguide5/inheritance-split" }, { from: "/refguide5/Indexes", to: "/refguide5/indexes" }, { from: "/refguide5/Input+reference+set+selector", to: "/refguide5/input-reference-set-selector" }, { from: "/refguide5/Input+Widgets", to: "/refguide5/input-widgets" }, { from: "/refguide5/Integration", to: "/refguide5/integration" }, { from: "/refguide5/Integration+Activities", to: "/refguide5/integration-activities" }, { from: "/refguide5/ISession+API+Usage", to: "/refguide5/isession-api-usage" }, { from: "/refguide5/Java+Action+Call", to: "/refguide5/java-action-call" }, { from: "/refguide5/Java+Actions", to: "/refguide5/java-actions" }, { from: "/refguide5/Java+in+the+Cloud", to: "/refguide5/java-in-the-cloud" }, { from: "/refguide5/Java+Memory+Usage+With+Mendix", to: "/refguide5/java-memory-usage-with-mendix" }, { from: "/refguide5/Java+Programming", to: "/refguide5/java-programming" }, { from: "/refguide5/Keep+alive+mechanism+for+Persistent+Sessions", to: "/refguide5/keep-alive-mechanism-for-persistent-sessions" }, { from: "/refguide5/Label", to: "/refguide5/label" }, { from: "/refguide5/Layout", to: "/refguide5/layout" }, { from: "/refguide5/Layouts", to: "/refguide5/layout" }, { from: "/refguide5/Layout+Container", to: "/refguide5/layout-container" }, { from: "/refguide5/Layout+Container+Region", to: "/refguide5/layout-container-region" }, { from: "/refguide5/Layout+grid", to: "/refguide5/layout-grid" }, { from: "/refguide5/Layout+Widgets", to: "/refguide5/layout-widgets" }, { from: "/refguide5/Line+Break+Document+Template", to: "/refguide5/line-break-document-template" }, { from: "/refguide5/Link+button", to: "/refguide5/link-button" }, { from: "/refguide5/List+Activities", to: "/refguide5/list-activities" }, { from: "/refguide5/List+Operation", to: "/refguide5/list-operation" }, { from: "/refguide5/List+Parameters", to: "/refguide5/list-parameters" }, { from: "/refguide5/List+view", to: "/refguide5/list-view" }, { from: "/refguide5/Listen+To+Grid+Source", to: "/refguide5/listen-to-grid-source" }, { from: "/refguide5/Log+Message", to: "/refguide5/log-message" }, { from: "/refguide5/Logging", to: "/refguide5/logging" }, { from: "/refguide5/Logging+Activities", to: "/refguide5/logging-activities" }, { from: "/refguide5/Loop", to: "/refguide5/loop" }, { from: "/refguide5/Managing+App+Signing+Keys", to: "/refguide5/managing-app-signing-keys" }, { from: "/refguide5/Map+element+to+entity", to: "/refguide5/map-element-to-entity" }, { from: "/refguide5/Map+entity+to+element", to: "/refguide5/map-entity-to-element" }, { from: "/refguide5/Mathematical+function+calls", to: "/refguide5/mathematical-function-calls" }, { from: "/refguide5/Menu", to: "/refguide5/menu" }, { from: "/refguide5/Menu+Bar", to: "/refguide5/menu-bar" }, { from: "/refguide5/Menu+Item", to: "/refguide5/menu-item" }, { from: "/refguide5/Menu+Widgets", to: "/refguide5/menu-widgets" }, { from: "/refguide5/Merge", to: "/refguide5/merge" }, { from: "/refguide5/Merge+Dialog", to: "/refguide5/merge-dialog" }, { from: "/refguide5/Microflow", to: "/refguide5/microflow" }, { from: "/refguide5/Microflow+button", to: "/refguide5/microflow-button" }, { from: "/refguide5/Microflow+Call", to: "/refguide5/microflow-call" }, { from: "/refguide5/Microflow+Element+Common+Properties", to: "/refguide5/microflow-element-common-properties" }, { from: "/refguide5/Microflow+Expressions", to: "/refguide5/microflow-expressions" }, { from: "/refguide5/Microflow+Source", to: "/refguide5/microflow-source" }, { from: "/refguide5/Microflows", to: "/refguide5/microflows" }, { from: "/refguide5/Mobile", to: "/refguide5/mobile" }, { from: "/refguide5/Model+Share", to: "/refguide5/model-share" }, { from: "/refguide5/Modeler", to: "/refguide5/modeler" }, { from: "/refguide5/Module+Role", to: "/refguide5/module-role" }, { from: "/refguide5/Module+Security", to: "/refguide5/module-security" }, { from: "/refguide5/Module+Status", to: "/refguide5/module-status" }, { from: "/refguide5/Modules", to: "/refguide5/modules" }, { from: "/refguide5/Monitoring+-+Mendix+Runtime", to: "/refguide5/monitoring-mendix-runtime" }, { from: "/refguide5/Monitoring+-+What+to+monitor", to: "/refguide5/monitoring-what-to-monitor" }, { from: "/refguide5/Moving+from+4+to+5", to: "/refguide5/moving-from-4-to-5" }, { from: "/refguide5/MySQL", to: "/refguide5/mysql" }, { from: "/refguide5/Navigation", to: "/refguide5/navigation" }, { from: "/refguide5/Navigation+list", to: "/refguide5/navigation-list" }, { from: "/refguide5/Navigation+Tree", to: "/refguide5/navigation-tree" }, { from: "/refguide5/New+button", to: "/refguide5/new-button" }, { from: "/refguide5/Numeric+formatting", to: "/refguide5/numeric-formatting" }, { from: "/refguide5/Object+Activities", to: "/refguide5/object-activities" }, { from: "/refguide5/OData+Query+Options", to: "/refguide5/odata-query-options" }, { from: "/refguide5/OData+Representation", to: "/refguide5/odata-representation" }, { from: "/refguide5/On+Click+Event", to: "/refguide5/on-click-event" }, { from: "/refguide5/Open+Project+Dialog", to: "/refguide5/open-project-dialog" }, { from: "/refguide5/Opening+Pages", to: "/refguide5/opening-pages" }, { from: "/refguide5/Operations", to: "/refguide5/operations" }, { from: "/refguide5/OQL", to: "/refguide5/oql" }, { from: "/refguide5/OQL+Aggregation", to: "/refguide5/oql-aggregation" }, { from: "/refguide5/OQL+Case+Expression", to: "/refguide5/oql-case-expression" }, { from: "/refguide5/OQL+CAST", to: "/refguide5/oql-cast" }, { from: "/refguide5/OQL+COALESCE", to: "/refguide5/oql-coalesce" }, { from: "/refguide5/OQL+DATEDIFF", to: "/refguide5/oql-datediff" }, { from: "/refguide5/OQL+DATEPART", to: "/refguide5/oql-datepart" }, { from: "/refguide5/OQL+Expressions", to: "/refguide5/oql-expressions" }, { from: "/refguide5/OQL+From+Clause", to: "/refguide5/oql-from-clause" }, { from: "/refguide5/OQL+FULL+OUTER+JOIN", to: "/refguide5/oql-full-outer-join" }, { from: "/refguide5/OQL+Functions", to: "/refguide5/oql-functions" }, { from: "/refguide5/OQL+Group+by+Clause", to: "/refguide5/oql-group-by-clause" }, { from: "/refguide5/OQL+INNER+JOIN", to: "/refguide5/oql-inner-join" }, { from: "/refguide5/OQL+LEFT+OUTER+JOIN", to: "/refguide5/oql-left-outer-join" }, { from: "/refguide5/OQL+LENGTH", to: "/refguide5/oql-length" }, { from: "/refguide5/OQL+Limit+Clause", to: "/refguide5/oql-limit-clause" }, { from: "/refguide5/OQL+Operators", to: "/refguide5/oql-operators" }, { from: "/refguide5/OQL+Order+by+Clause", to: "/refguide5/oql-order-by-clause" }, { from: "/refguide5/OQL+Parameters", to: "/refguide5/oql-parameters" }, { from: "/refguide5/OQL+RANGEBEGIN", to: "/refguide5/oql-rangebegin" }, { from: "/refguide5/OQL+RANGEEND", to: "/refguide5/oql-rangeend" }, { from: "/refguide5/OQL+RIGHT+OUTER+JOIN", to: "/refguide5/oql-right-outer-join" }, { from: "/refguide5/OQL+ROUND", to: "/refguide5/oql-round" }, { from: "/refguide5/OQL+Select+Clause", to: "/refguide5/oql-select-clause" }, { from: "/refguide5/OQL+Where+Clause", to: "/refguide5/oql-where-clause" }, { from: "/refguide5/Oracle", to: "/refguide5/oracle" }, { from: "/refguide5/Packaging+Hybrid+Mobile+Apps", to: "/refguide5/packaging-hybrid-mobile-apps" }, { from: "/refguide5/Page", to: "/refguide5/page" }, { from: "/refguide5/Page+Break+Document+Template", to: "/refguide5/page-break-document-template" }, { from: "/refguide5/Page+Concepts", to: "/refguide5/page-concepts" }, { from: "/refguide5/Page+Templates", to: "/refguide5/page-templates" }, { from: "/refguide5/Page+title", to: "/refguide5/page-title" }, { from: "/refguide5/Pages", to: "/refguide5/pages" }, { from: "/refguide5/Parameter", to: "/refguide5/parameter" }, { from: "/refguide5/Parse+and+format+date+function+calls", to: "/refguide5/parse-and-format-date-function-calls" }, { from: "/refguide5/Parse+and+format+decimal+function+calls", to: "/refguide5/parse-and-format-decimal-function-calls" }, { from: "/refguide5/Parse+and+format+float+function+calls", to: "/refguide5/parse-and-format-float-function-calls" }, { from: "/refguide5/Parse+integer", to: "/refguide5/parse-integer" }, { from: "/refguide5/Password+Policy", to: "/refguide5/password-policy" }, { from: "/refguide5/Persistability", to: "/refguide5/persistability" }, { from: "/refguide5/Persistent+Create+Object", to: "/refguide5/persistent-create-object" }, { from: "/refguide5/Placeholder", to: "/refguide5/placeholder" }, { from: "/refguide5/Preferences+Dialog", to: "/refguide5/preferences-dialog" }, { from: "/refguide5/Proactive+Maintenance", to: "/refguide5/proactive-maintenance" }, { from: "/refguide5/Project", to: "/refguide5/project" }, { from: "/refguide5/Project+Security", to: "/refguide5/project-security" }, { from: "/refguide5/Project+Settings", to: "/refguide5/project-settings" }, { from: "/refguide5/Publish+Packages+To+Mobile+Stores", to: "/refguide5/publish-packages-to-mobile-stores" }, { from: "/refguide5/Published+App+Service", to: "/refguide5/published-app-service" }, { from: "/refguide5/Published+App+Services", to: "/refguide5/published-app-services" }, { from: "/refguide5/Published+OData+resource", to: "/refguide5/published-odata-resource" }, { from: "/refguide5/Published+OData+Services", to: "/refguide5/published-odata-services" }, { from: "/refguide5/Published+web+service", to: "/refguide5/published-web-service" }, { from: "/refguide5/Published+Web+Services", to: "/refguide5/published-web-services" }, { from: "/refguide5/Radio+buttons", to: "/refguide5/radio-buttons" }, { from: "/refguide5/Range+Search+Field", to: "/refguide5/range-search-field" }, { from: "/refguide5/Reference+Guide+5", to: "/refguide5/" }, { from: "/refguide5/Reference+selector", to: "/refguide5/reference-selector" }, { from: "/refguide5/Reference+set+selector", to: "/refguide5/reference-set-selector" }, { from: "/refguide5/Regular+Expressions", to: "/refguide5/regular-expressions" }, { from: "/refguide5/Relational+expressions", to: "/refguide5/relational-expressions" }, { from: "/refguide5/Release+Notes", to: "/refguide5/release-notes" }, { from: "/refguide5/Remove+button", to: "/refguide5/remove-button" }, { from: "/refguide5/Report+Button", to: "/refguide5/report-button" }, { from: "/refguide5/Report+Chart", to: "/refguide5/report-chart" }, { from: "/refguide5/Report+Pane", to: "/refguide5/report-pane" }, { from: "/refguide5/Report+Widgets", to: "/refguide5/report-widgets" }, { from: "/refguide5/Reporting+Widgets", to: "/refguide5/report-widgets" }, { from: "/refguide5/Reporting", to: "/refguide5/report-widgets" }, { from: "/refguide5/Retrieve", to: "/refguide5/retrieve" }, { from: "/refguide5/Review+log+files+-+MS+IIS+Server", to: "/refguide5/review-log-files-ms-iis-server" }, { from: "/refguide5/Review+log+files+-+MS+SQL+Server", to: "/refguide5/review-log-files-ms-sql-server" }, { from: "/refguide5/Rollback+Object", to: "/refguide5/rollback-object" }, { from: "/refguide5/Row+Document+Template", to: "/refguide5/row-document-template" }, { from: "/refguide5/Rules", to: "/refguide5/rules" }, { from: "/refguide5/Runtime", to: "/refguide5/runtime" }, { from: "/refguide5/Save+button", to: "/refguide5/save-button" }, { from: "/refguide5/Scheduled+Events", to: "/refguide5/scheduled-events" }, { from: "/refguide5/Scroll+Container", to: "/refguide5/scroll-container" }, { from: "/refguide5/Scroll+Container+Region", to: "/refguide5/scroll-container-region" }, { from: "/refguide5/Search+Bar", to: "/refguide5/search-bar" }, { from: "/refguide5/Search+button", to: "/refguide5/search-button" }, { from: "/refguide5/Security", to: "/refguide5/security" }, { from: "/refguide5/Select+all+button", to: "/refguide5/select-all-button" }, { from: "/refguide5/Select+app+service", to: "/refguide5/select-app-service" }, { from: "/refguide5/Select+button", to: "/refguide5/select-button" }, { from: "/refguide5/Select+elements", to: "/refguide5/select-elements" }, { from: "/refguide5/Sequence+Flow", to: "/refguide5/sequence-flow" }, { from: "/refguide5/Settings", to: "/refguide5/settings" }, { from: "/refguide5/Show+Home+Page", to: "/refguide5/show-home-page" }, { from: "/refguide5/Show+Message", to: "/refguide5/show-message" }, { from: "/refguide5/Show+Page", to: "/refguide5/show-page" }, { from: "/refguide5/Show+Form", to: "/refguide5/show-page" }, { from: "/refguide5/Sidebar+toggle+button", to: "/refguide5/sidebar-toggle-button" }, { from: "/refguide5/Sign+In+Dialog", to: "/refguide5/sign-in-dialog" }, { from: "/refguide5/Sign+out+button", to: "/refguide5/sign-out-button" }, { from: "/refguide5/Simple+Menu+Bar", to: "/refguide5/simple-menu-bar" }, { from: "/refguide5/Snippet", to: "/refguide5/snippet" }, { from: "/refguide5/Snippets", to: "/refguide5/snippet" }, { from: "/refguide5/Snippet+Call", to: "/refguide5/snippet-call" }, { from: "/refguide5/Sort+Bar", to: "/refguide5/sort-bar" }, { from: "/refguide5/Special+checks", to: "/refguide5/special-checks" }, { from: "/refguide5/Start+Event", to: "/refguide5/start-event" }, { from: "/refguide5/Starting+Microflows", to: "/refguide5/starting-microflows" }, { from: "/refguide5/Static+Image+Document+Template", to: "/refguide5/static-image-document-template" }, { from: "/refguide5/Static+Label+Document+Template", to: "/refguide5/static-label-document-template" }, { from: "/refguide5/String+function+calls", to: "/refguide5/string-function-calls" }, { from: "/refguide5/Style", to: "/refguide5/style" }, { from: "/refguide5/System+Requirements", to: "/refguide5/system-requirements" }, { from: "/refguide5/System+Texts", to: "/refguide5/system-texts" }, { from: "/refguide5/Tab+container", to: "/refguide5/tab-container" }, { from: "/refguide5/Tab+Control", to: "/refguide5/tab-container" }, { from: "/refguide5/Tab+page", to: "/refguide5/tab-page" }, { from: "/refguide5/Table", to: "/refguide5/table" }, { from: "/refguide5/Table+cell", to: "/refguide5/table-cell" }, { from: "/refguide5/Table+Document+Template", to: "/refguide5/table-document-template" }, { from: "/refguide5/Table+row", to: "/refguide5/table-row" }, { from: "/refguide5/Team+Server", to: "/refguide5/team-server" }, { from: "/refguide5/Team+Server+FAQ", to: "/refguide5/team-server-faq" }, { from: "/refguide5/Template+grid", to: "/refguide5/template-grid" }, { from: "/refguide5/Template+Grid+Document+Template", to: "/refguide5/template-grid-document-template" }, { from: "/refguide5/Text", to: "/refguide5/text" }, { from: "/refguide5/Text+area", to: "/refguide5/text-area" }, { from: "/refguide5/Text+box", to: "/refguide5/text-box" }, { from: "/refguide5/Third+Party+Licenses", to: "/refguide5/third-party-licenses" }, { from: "/refguide5/Title+Document+Template", to: "/refguide5/title-document-template" }, { from: "/refguide5/To+float", to: "/refguide5/to-float" }, { from: "/refguide5/To+string", to: "/refguide5/to-string" }, { from: "/refguide5/Transient+Objects+Garbage+Collecting", to: "/refguide5/transient-objects-garbage-collecting" }, { from: "/refguide5/Translatable+Texts", to: "/refguide5/translatable-texts" }, { from: "/refguide5/Trim+to+date", to: "/refguide5/trim-to-date" }, { from: "/refguide5/Troubleshooting", to: "/refguide5/troubleshooting" }, { from: "/refguide5/Unary+expressions", to: "/refguide5/unary-expressions" }, { from: "/refguide5/Upload+To+Team+Server+Dialog", to: "/refguide5/upload-to-team-server-dialog" }, { from: "/refguide5/User+Roles", to: "/refguide5/user-roles" }, { from: "/refguide5/User+Role", to: "/refguide5/user-roles" }, { from: "/refguide5/Using+a+proxy+to+call+a+webservice", to: "/refguide5/using-a-proxy-to-call-a-webservice" }, { from: "/refguide5/Using+Eclipse", to: "/refguide5/using-eclipse" }, { from: "/refguide5/Validation+Feedback", to: "/refguide5/validation-feedback" }, { from: "/refguide5/Validation+Rules", to: "/refguide5/validation-rules" }, { from: "/refguide5/Variable+Activities", to: "/refguide5/variable-activities" }, { from: "/refguide5/Version+Control", to: "/refguide5/version-control" }, { from: "/refguide5/Version+Control+Concepts", to: "/refguide5/version-control-concepts" }, { from: "/refguide5/Version+Control+Scenarios", to: "/refguide5/version-control-scenarios" }, { from: "/refguide5/Vertical+Split+Pane", to: "/refguide5/vertical-split-pane" }, { from: "/refguide5/XML+Reference+Guide", to: "/refguide5/xml-reference-guide" }, { from: "/refguide5/XML+Schema+Support", to: "/refguide5/xml-schema-support" }, { from: "/refguide5/XML+Schemas", to: "/refguide5/xml-schemas" }, { from: "/refguide5/XML+to+Domain+Mappings", to: "/refguide5/xml-to-domain-mappings" }, { from: "/refguide5/XPath", to: "/refguide5/xpath" }, { from: "/refguide5/XPath+avg", to: "/refguide5/xpath-avg" }, { from: "/refguide5/XPath+Constraint+Functions", to: "/refguide5/xpath-constraint-functions" }, { from: "/refguide5/XPath+Constraints", to: "/refguide5/xpath-constraints" }, { from: "/refguide5/XPath+contains", to: "/refguide5/xpath-contains" }, { from: "/refguide5/XPath+count", to: "/refguide5/xpath-count" }, { from: "/refguide5/XPath+day+from+dateTime", to: "/refguide5/xpath-day-from-datetime" }, { from: "/refguide5/XPath+day+of+year+from+dateTime", to: "/refguide5/xpath-day-of-year-from-datetime" }, { from: "/refguide5/XPath+ends+with", to: "/refguide5/xpath-ends-with" }, { from: "/refguide5/XPath+Expressions", to: "/refguide5/xpath-expressions" }, { from: "/refguide5/XPath+false", to: "/refguide5/xpath-false" }, { from: "/refguide5/XPath+hours+from+dateTime", to: "/refguide5/xpath-hours-from-datetime" }, { from: "/refguide5/XPath+id", to: "/refguide5/xpath-id" }, { from: "/refguide5/XPath+Keywords+and+System+Variables", to: "/refguide5/xpath-keywords-and-system-variables" }, { from: "/refguide5/XPath+length", to: "/refguide5/xpath-length" }, { from: "/refguide5/XPath+max", to: "/refguide5/xpath-max" }, { from: "/refguide5/XPath+min", to: "/refguide5/xpath-min" }, { from: "/refguide5/XPath+minutes+from+dateTime", to: "/refguide5/xpath-minutes-from-datetime" }, { from: "/refguide5/XPath+month+from+dateTime", to: "/refguide5/xpath-month-from-datetime" }, { from: "/refguide5/XPath+not", to: "/refguide5/xpath-not" }, { from: "/refguide5/XPath+Operators", to: "/refguide5/xpath-operators" }, { from: "/refguide5/XPath+quarter+from+dateTime", to: "/refguide5/xpath-quarter-from-datetime" }, { from: "/refguide5/XPath+Query+Functions", to: "/refguide5/xpath-query-functions" }, { from: "/refguide5/XPath+seconds+from+dateTime", to: "/refguide5/xpath-seconds-from-datetime" }, { from: "/refguide5/XPath+starts+with", to: "/refguide5/xpath-starts-with" }, { from: "/refguide5/XPath+string+length", to: "/refguide5/xpath-string-length" }, { from: "/refguide5/XPath+sum", to: "/refguide5/xpath-sum" }, { from: "/refguide5/XPath+Tokens", to: "/refguide5/xpath-tokens" }, { from: "/refguide5/XPath+true", to: "/refguide5/xpath-true" }, { from: "/refguide5/XPath+week+from+dateTime", to: "/refguide5/xpath-week-from-datetime" }, { from: "/refguide5/XPath+weekday+from+dateTime", to: "/refguide5/xpath-weekday-from-datetime" }, { from: "/refguide5/XPath+year+from+dateTime", to: "/refguide5/xpath-year-from-datetime" }, /**************************************************** * REFERENCE GUIDE MENDIX 6 ****************************************************/ { from: "/refguide6/Reference+Guide+6", to: "/refguide6/" }, { from: "/refguide6/TreeNavigation", to: "/refguide6/" }, { from: "/refguide6/Access+Rules", to: "/refguide6/access-rules" }, { from: "/refguide6/Action+Button", to: "/refguide6/action-button" }, { from: "/refguide6/Action+Call+Activities", to: "/refguide6/action-call-activities" }, { from: "/refguide6/Actions", to: "/refguide6/actions" }, { from: "/refguide6/Activities", to: "/refguide6/activities" }, { from: "/refguide6/Add+button", to: "/refguide6/add-button" }, { from: "/refguide6/Add+date+function+calls", to: "/refguide6/add-date-function-calls" }, { from: "/refguide6/Administrator", to: "/refguide6/administrator" }, { from: "/refguide6/Aggregate+List", to: "/refguide6/aggregate-list" }, { from: "/refguide6/Annotation", to: "/refguide6/annotation" }, { from: "/refguide6/Annotation+flow", to: "/refguide6/annotation-flow" }, { from: "/refguide6/Annotations", to: "/refguide6/annotations" }, { from: "/refguide6/Anonymous+Users", to: "/refguide6/anonymous-users" }, { from: "/refguide6/App+Platform", to: "/refguide6/app-platform" }, { from: "/refguide6/App+Settings+Dialog", to: "/refguide6/app-settings-dialog" }, { from: "/refguide6/Arithmetic+expressions", to: "/refguide6/arithmetic-expressions" }, { from: "/refguide6/Association+Source", to: "/refguide6/association-source" }, { from: "/refguide6/Associations", to: "/refguide6/associations" }, { from: "/refguide6/Attributes", to: "/refguide6/attributes" }, { from: "/refguide6/Back+button", to: "/refguide6/back-button" }, { from: "/refguide6/Basic+Reports", to: "/refguide6/basic-reports" }, { from: "/refguide6/Between+date+function+calls", to: "/refguide6/between-date-function-calls" }, { from: "/refguide6/Boolean+expressions", to: "/refguide6/boolean-expressions" }, { from: "/refguide6/Branch+Line+Manager+Dialog", to: "/refguide6/branch-line-manager-dialog" }, { from: "/refguide6/Break+Event", to: "/refguide6/break-event" }, { from: "/refguide6/Button+Widgets", to: "/refguide6/button-widgets" }, { from: "/refguide6/Call+Rest+Action", to: "/refguide6/call-rest-action" }, { from: "/refguide6/Call+Web+Service", to: "/refguide6/call-web-service" }, { from: "/refguide6/Call+Web+Service+Action", to: "/refguide6/call-web-service-action" }, { from: "/refguide6/Cancel+button", to: "/refguide6/cancel-button" }, { from: "/refguide6/Cast+Object", to: "/refguide6/cast-object" }, { from: "/refguide6/Cell+Document+Template", to: "/refguide6/cell-document-template" }, { from: "/refguide6/certificates", to: "/deployment/mendixcloud/certificates" }, { from: "/refguide6/Change+List", to: "/refguide6/change-list" }, { from: "/refguide6/Change+Object", to: "/refguide6/change-object" }, { from: "/refguide6/Change+Variable", to: "/refguide6/change-variable" }, { from: "/refguide6/Check+box", to: "/refguide6/check-box" }, { from: "/refguide6/Client+Activities", to: "/refguide6/client-activities" }, { from: "/refguide6/Close+Form", to: "/refguide6/close-form" }, { from: "/refguide6/Close+page+button", to: "/refguide6/close-page-button" }, { from: "/refguide6/Clustered+Mendix+Runtime", to: "/refguide6/clustered-mendix-runtime" }, { from: "/refguide6/Clustered+Mendix+Business+Server", to: "/refguide6/clustered-mendix-runtime" }, { from: "/refguide6/Columns", to: "/refguide6/columns" }, { from: "/refguide6/Columns+Document+Template", to: "/refguide6/columns-document-template" }, { from: "/refguide6/Commit+Dialog", to: "/refguide6/commit-dialog" }, { from: "/refguide6/Commit+Object(s)", to: "/refguide6/committing-objects" }, { from: "/refguide6/Committing+Objects", to: "/refguide6/committing-objects" }, { from: "/refguide6/Common+Widget+Properties", to: "/refguide6/common-widget-properties" }, { from: "/refguide6/Common+Widgets", to: "/refguide6/common-widgets" }, { from: "/refguide6/Comparison+Search+Field", to: "/refguide6/comparison-search-field" }, { from: "/refguide6/Conditions", to: "/refguide6/conditions" }, { from: "/refguide6/Configuration", to: "/refguide6/configuration" }, { from: "/refguide6/Configuring+Hybrid+Mobile+Apps+To+Run+Offline", to: "/refguide6/configuring-hybrid-mobile-apps-to-run-offline" }, { from: "/refguide6/Constants", to: "/refguide6/constants" }, { from: "/refguide6/Consumed+App+Services", to: "/refguide6/consumed-app-services" }, { from: "/refguide6/Consumed+REST+Services", to: "/refguide6/consumed-rest-services" }, { from: "/refguide6/Consumed+web+service", to: "/refguide6/consumed-web-service" }, { from: "/refguide6/Consumed+Web+Services", to: "/refguide6/consumed-web-services" }, { from: "/refguide6/Container", to: "/refguide6/container" }, { from: "/refguide6/Container+Widgets", to: "/refguide6/container-widgets" }, { from: "/refguide6/Context+Mechanism", to: "/refguide6/context-mechanism" }, { from: "/refguide6/Continue+Event", to: "/refguide6/continue-event" }, { from: "/refguide6/Control+Bar", to: "/refguide6/control-bar" }, { from: "/refguide6/Create+Branch+Line+Dialog", to: "/refguide6/create-branch-line-dialog" }, { from: "/refguide6/Create+Deployment+Package+Dialog", to: "/refguide6/create-deployment-package-dialog" }, { from: "/refguide6/Create+List", to: "/refguide6/create-list" }, { from: "/refguide6/Create+Object", to: "/refguide6/create-object" }, { from: "/refguide6/Create+Variable", to: "/refguide6/create-variable" }, { from: "/refguide6/Custom+Settings", to: "/refguide6/custom-settings" }, { from: "/refguide6/Customizing+Hybrid+Mobile+Apps", to: "/refguide6/customizing-hybrid-mobile-apps" }, { from: "/refguide6/Customizing+PhoneGap+Build+packages", to: "/refguide6/customizing-phonegap-build-packages" }, { from: "/refguide6/Data+grid", to: "/refguide6/data-grid" }, { from: "/refguide6/Data+Grid+Document+Template", to: "/refguide6/data-grid-document-template" }, { from: "/refguide6/Data+Sets", to: "/refguide6/data-sets" }, { from: "/refguide6/Data+Sources", to: "/refguide6/data-sources" }, { from: "/refguide6/Data+Storage", to: "/refguide6/data-storage" }, { from: "/refguide6/Data+Types", to: "/refguide6/data-types" }, { from: "/refguide6/Data+view", to: "/refguide6/data-view" }, { from: "/refguide6/Data+view+action+button", to: "/refguide6/data-view-action-button" }, { from: "/refguide6/Data+view+cancel+button", to: "/refguide6/data-view-cancel-button" }, { from: "/refguide6/Data+view+close+button", to: "/refguide6/data-view-close-button" }, { from: "/refguide6/Data+view+control+bar", to: "/refguide6/data-view-control-bar" }, { from: "/refguide6/Data+View+Document+Template", to: "/refguide6/data-view-document-template" }, { from: "/refguide6/Data+view+save+button", to: "/refguide6/data-view-save-button" }, { from: "/refguide6/Data+Widgets", to: "/refguide6/data-widgets" }, { from: "/refguide6/Database+Source", to: "/refguide6/database-source" }, { from: "/refguide6/Date+and+Time+Handling+in+3.0", to: "/refguide6/date-and-time-handling-in-3.0" }, { from: "/refguide6/Date+creation", to: "/refguide6/date-creation" }, { from: "/refguide6/Date+picker", to: "/refguide6/date-picker" }, { from: "/refguide6/Date+Range+Field", to: "/refguide6/date-range-field" }, { from: "/refguide6/Date+Range+Selector", to: "/refguide6/date-range-selector" }, { from: "/refguide6/DateTime+handling+FAQ", to: "/refguide6/datetime-handling-faq" }, { from: "/refguide6/DB2", to: "/refguide6/db2" }, { from: "/refguide6/Delete+button", to: "/refguide6/delete-button" }, { from: "/refguide6/Delete+Object(s)", to: "/refguide6/deleting-objects" }, { from: "/refguide6/Deleting+Objects", to: "/refguide6/deleting-objects" }, { from: "/refguide6/Demo+Users", to: "/refguide6/demo-users" }, { from: "/refguide6/Deploy+To+The+Cloud+Dialog", to: "/refguide6/deploy-to-the-cloud-dialog" }, { from: "/refguide6/Deselect+all+button", to: "/refguide6/deselect-all-button" }, { from: "/refguide6/Desktop+profile", to: "/refguide6/desktop-profile" }, { from: "/refguide6/Developing+Hybrid+Mobile+Apps", to: "/refguide6/developing-hybrid-mobile-apps" }, { from: "/refguide6/Dialogs", to: "/refguide6/dialogs" }, { from: "/refguide6/Document+Generation+Activities", to: "/refguide6/document-generation-activities" }, { from: "/refguide6/Document+Template", to: "/refguide6/document-template" }, { from: "/refguide6/Document+Templates", to: "/refguide6/document-templates" }, { from: "/refguide6/Domain+Model", to: "/refguide6/domain-model" }, { from: "/refguide6/Download+File", to: "/refguide6/download-file" }, { from: "/refguide6/Download+From+Team+Server+Dialog", to: "/refguide6/download-from-team-server-dialog" }, { from: "~\/refguide6\/Drop-down", to: "/refguide6/drop_down", "exact": true }, { from: "/refguide6/Drop+Down+Widget", to: "/refguide6/drop_down" }, { from: "/refguide6/Drop+Down Widget", to: "/refguide6/drop_down" }, { from: "/refguide6/Drop+Down", to: "/refguide6/drop-down" }, { from: "/refguide6/Drop+down+button", to: "/refguide6/drop-down-button" }, { from: "/refguide6/Drop+Down+Search+Field", to: "/refguide6/drop-down-search-field" }, { from: "/refguide6/Dynamic+Image+Document+Template", to: "/refguide6/dynamic-image-document-template" }, { from: "/refguide6/Dynamic+Label+Document+Template", to: "/refguide6/dynamic-label-document-template" }, { from: "/refguide6/Edit+button", to: "/refguide6/edit-button" }, { from: "/refguide6/Edit+Cloud+Foundry+Settings+Dialog", to: "/refguide6/edit-cloud-foundry-settings-dialog" }, { from: "/refguide6/End+Event", to: "/refguide6/end-event" }, { from: "/refguide6/Entities", to: "/refguide6/entities" }, { from: "/refguide6/Entity+Path+Source", to: "/refguide6/entity-path-source" }, { from: "/refguide6/Enumeration+Values", to: "/refguide6/enumeration-values" }, { from: "/refguide6/Enumerations", to: "/refguide6/enumerations" }, { from: "/refguide6/Enumerations+in+microflow+expressions", to: "/refguide6/enumerations-in-microflow-expressions" }, { from: "/refguide6/Error+Event", to: "/refguide6/error-event" }, { from: "/refguide6/Event+Handlers", to: "/refguide6/event-handlers" }, { from: "/refguide6/Exclusive+Split", to: "/refguide6/exclusive-split" }, { from: "/refguide6/Export+Mapping+Action", to: "/refguide6/export-mapping-action" }, { from: "/refguide6/Export+Mappings", to: "/refguide6/export-mappings" }, { from: "/refguide6/Export+to+CSV+button", to: "/refguide6/export-to-csv-button" }, { from: "/refguide6/Export+to+excel+button", to: "/refguide6/export-to-excel-button" }, { from: "/refguide6/Export+XML", to: "/refguide6/export-xml" }, { from: "/refguide6/File+manager", to: "/refguide6/file-manager" }, { from: "/refguide6/File+Widgets", to: "/refguide6/file-widgets" }, { from: "/refguide6/Footer+Document+Template", to: "/refguide6/footer-document-template" }, { from: "/refguide6/Garbage+collection", to: "/refguide6/garbage-collection" }, { from: "/refguide6/General", to: "/refguide6/general" }, { from: "/refguide6/Generate+Document", to: "/refguide6/generate-document" }, { from: "/refguide6/Getting+the+Mendix+Developer+App", to: "/refguide6/getting-the-mendix-developer-app" }, { from: "/refguide6/Grid+action+button", to: "/refguide6/grid-action-button" }, { from: "/refguide6/Grid+microflow+button", to: "/refguide6/grid-microflow-button" }, { from: "/refguide6/Grid+New+Button", to: "/refguide6/grid-new-button" }, { from: "/refguide6/Group+box", to: "/refguide6/group-box" }, { from: "/refguide6/Section", to: "/refguide6/group-box" }, { from: "/refguide6/Header", to: "/refguide6/header" }, { from: "/refguide6/Header+Document+Template", to: "/refguide6/header-document-template" }, { from: "/refguide6/History+Dialog", to: "/refguide6/history-dialog" }, { from: "/refguide6/Horizontal+Split+Pane", to: "/refguide6/horizontal-split-pane" }, { from: "/refguide6/If+expressions", to: "/refguide6/if-expressions" }, { from: "/refguide6/Image", to: "/refguide6/image" }, { from: "/refguide6/Image+uploader", to: "/refguide6/image-uploader" }, { from: "/refguide6/Image+viewer", to: "/refguide6/image-viewer" }, { from: "/refguide6/Images+refguide", to: "/refguide6/images" }, { from: "/refguide6/Images", to: "/refguide6/images" }, { from: "/refguide6/Image+Property", to: "/refguide6/image-property" }, { from: "/refguide6/Import+Mapping+Action", to: "/refguide6/import-mapping-action" }, { from: "/refguide6/Import+Mappings", to: "/refguide6/import-mappings" }, { from: "/refguide6/Import+XML", to: "/refguide6/import-xml" }, { from: "/refguide6/Inheritance+Split", to: "/refguide6/inheritance-split" }, { from: "/refguide6/Indexes", to: "/refguide6/indexes" }, { from: "/refguide6/Input+reference+set+selector", to: "/refguide6/input-reference-set-selector" }, { from: "/refguide6/Input+Widgets", to: "/refguide6/input-widgets" }, { from: "/refguide6/Integration", to: "/refguide6/integration" }, { from: "/refguide6/Integration+Activities", to: "/refguide6/integration-activities" }, { from: "/refguide6/ISession+API+Usage", to: "/refguide6/isession-api-usage" }, { from: "/refguide6/Java+Action+Call", to: "/refguide6/java-action-call" }, { from: "/refguide6/Java+Actions", to: "/refguide6/java-actions" }, { from: "/refguide6/Java+Memory+Usage+With+Mendix", to: "/refguide6/java-memory-usage-with-mendix" }, { from: "/refguide6/Java+Programming", to: "/refguide6/java-programming" }, { from: "/refguide6/JSON+Structures", to: "/refguide6/json-structures" }, { from: "/refguide6/Keep+alive+mechanism+for+Persistent+Sessions", to: "/refguide6/keep-alive-mechanism-for-persistent-sessions" }, { from: "/refguide6/Label", to: "/refguide6/label" }, { from: "/refguide6/Layout", to: "/refguide6/layout" }, { from: "/refguide6/Layouts", to: "/refguide6/layout" }, { from: "/refguide6/Layout+grid", to: "/refguide6/layout-grid" }, { from: "/refguide6/Layout+Widgets", to: "/refguide6/layout-widgets" }, { from: "/refguide6/Line+Break+Document+Template", to: "/refguide6/line-break-document-template" }, { from: "/refguide6/Link+button", to: "/refguide6/link-button" }, { from: "/refguide6/List+Activities", to: "/refguide6/list-activities" }, { from: "/refguide6/List+Operation", to: "/refguide6/list-operation" }, { from: "/refguide6/List+view", to: "/refguide6/list-view" }, { from: "/refguide6/Listen+To+Grid+Source", to: "/refguide6/listen-to-grid-source" }, { from: "/refguide6/Log+Message", to: "/refguide6/log-message" }, { from: "/refguide6/Logging", to: "/refguide6/logging" }, { from: "/refguide6/Logging+Activities", to: "/refguide6/logging-activities" }, { from: "/refguide6/Loop", to: "/refguide6/loop" }, { from: "/refguide6/Managing+App+Signing+Keys", to: "/refguide6/managing-app-signing-keys" }, { from: "/refguide6/Map+Automatically", to: "/refguide6/map-automatically" }, { from: "/refguide6/Mapping+Documents", to: "/refguide6/mapping-documents" }, { from: "/refguide6/Mathematical+function+calls", to: "/refguide6/mathematical-function-calls" }, { from: "/refguide6/Menu", to: "/refguide6/menu" }, { from: "/refguide6/Menu+Bar", to: "/refguide6/menu-bar" }, { from: "/refguide6/Menu+Item", to: "/refguide6/menu-item" }, { from: "/refguide6/Menu+Widgets", to: "/refguide6/menu-widgets" }, { from: "/refguide6/Merge", to: "/refguide6/merge" }, { from: "/refguide6/Merge+Dialog", to: "/refguide6/merge-dialog" }, { from: "/refguide6/Microflow", to: "/refguide6/microflow" }, { from: "/refguide6/Microflow+Activities", to: "/refguide6/microflow-activities" }, { from: "/refguide6/Microflow+Call", to: "/refguide6/microflow-call" }, { from: "/refguide6/Microflow+Element+Common+Properties", to: "/refguide6/microflow-element-common-properties" }, { from: "/refguide6/Microflow+Expressions", to: "/refguide6/microflow-expressions" }, { from: "/refguide6/Microflow+Source", to: "/refguide6/microflow-source" }, { from: "/refguide6/Microflows", to: "/refguide6/microflows" }, { from: "/refguide6/Mobile", to: "/refguide6/mobile" }, { from: "/refguide6/Model+Share", to: "/refguide6/model-share" }, { from: "/refguide6/Modeler", to: "/refguide6/modeler" }, { from: "/refguide6/Module+Role", to: "/refguide6/module-role" }, { from: "/refguide6/Module+Security", to: "/refguide6/module-security" }, { from: "/refguide6/Module+Status", to: "/refguide6/module-status" }, { from: "/refguide6/Modules", to: "/refguide6/modules" }, { from: "/refguide6/Monitoring+-+Mendix+Runtime", to: "/refguide6/monitoring-mendix-runtime" }, { from: "/refguide6/Monitoring+-+Mendix+Business+Server", to: "/refguide6/monitoring-mendix-runtime" }, { from: "/refguide6/Monitoring+-+What+to+monitor", to: "/refguide6/monitoring-what-to-monitor" }, { from: "/refguide6/Moving+from+5+to+6", to: "/refguide6/moving-from-5-to-6" }, { from: "/refguide6/MySQL", to: "/refguide6/mysql" }, { from: "/refguide6/Navigation", to: "/refguide6/navigation" }, { from: "/refguide6/Navigation+list", to: "/refguide6/navigation-list" }, { from: "/refguide6/Navigation+Tree", to: "/refguide6/navigation-tree" }, { from: "/refguide6/New+button", to: "/refguide6/new-button" }, { from: "/refguide6/NULL+Ordering+Behavior", to: "/refguide6/null-ordering-behavior" }, { from: "/refguide6/Numeric+formatting", to: "/refguide6/numeric-formatting" }, { from: "/refguide6/Object+Activities", to: "/refguide6/object-activities" }, { from: "/refguide6/OData+Query+Options", to: "/refguide6/odata-query-options" }, { from: "/refguide6/OData+Representation", to: "/refguide6/odata-representation" }, { from: "/refguide6/Offline", to: "/refguide6/offline" }, { from: "/refguide6/Offline+device+profile", to: "/refguide6/offline-device-profile" }, { from: "/refguide6/On+Click+Event", to: "/refguide6/on-click-event" }, { from: "/refguide6/Open+Project+Dialog", to: "/refguide6/open-project-dialog" }, { from: "/refguide6/Opening+Pages", to: "/refguide6/opening-pages" }, { from: "/refguide6/Operations", to: "/refguide6/operations" }, { from: "/refguide6/OQL", to: "/refguide6/oql" }, { from: "/refguide6/OQL+Aggregation", to: "/refguide6/oql-aggregation" }, { from: "/refguide6/OQL+Case+Expression", to: "/refguide6/oql-case-expression" }, { from: "/refguide6/OQL+CAST", to: "/refguide6/oql-cast" }, { from: "/refguide6/OQL+COALESCE", to: "/refguide6/oql-coalesce" }, { from: "/refguide6/OQL+DATEDIFF", to: "/refguide6/oql-datediff" }, { from: "/refguide6/OQL+DATEPART", to: "/refguide6/oql-datepart" }, { from: "/refguide6/OQL+Expressions", to: "/refguide6/oql-expressions" }, { from: "/refguide6/OQL+From+Clause", to: "/refguide6/oql-from-clause" }, { from: "/refguide6/OQL+FULL+OUTER+JOIN", to: "/refguide6/oql-full-outer-join" }, { from: "/refguide6/OQL+Functions", to: "/refguide6/oql-functions" }, { from: "/refguide6/OQL+Group+by+Clause", to: "/refguide6/oql-group-by-clause" }, { from: "/refguide6/OQL+INNER+JOIN", to: "/refguide6/oql-inner-join" }, { from: "/refguide6/OQL+LEFT+OUTER+JOIN", to: "/refguide6/oql-left-outer-join" }, { from: "/refguide6/OQL+LENGTH", to: "/refguide6/oql-length" }, { from: "/refguide6/OQL+Limit+Clause", to: "/refguide6/oql-limit-clause" }, { from: "/refguide6/OQL+Operators", to: "/refguide6/oql-operators" }, { from: "/refguide6/OQL+Order+by+Clause", to: "/refguide6/oql-order-by-clause" }, { from: "/refguide6/OQL+Parameters", to: "/refguide6/oql-parameters" }, { from: "/refguide6/OQL+RANGEBEGIN", to: "/refguide6/oql-rangebegin" }, { from: "/refguide6/OQL+RANGEEND", to: "/refguide6/oql-rangeend" }, { from: "/refguide6/OQL+RIGHT+OUTER+JOIN", to: "/refguide6/oql-right-outer-join" }, { from: "/refguide6/OQL+ROUND", to: "/refguide6/oql-round" }, { from: "/refguide6/OQL+Select+Clause", to: "/refguide6/oql-select-clause" }, { from: "/refguide6/OQL+Where+Clause", to: "/refguide6/oql-where-clause" }, { from: "/refguide6/Oracle", to: "/refguide6/oracle" }, { from: "/refguide6/Packaging+Hybrid+Mobile+Apps", to: "/refguide6/packaging-hybrid-mobile-apps" }, { from: "/refguide6/Page", to: "/refguide6/page" }, { from: "/refguide6/Page+Break+Document+Template", to: "/refguide6/page-break-document-template" }, { from: "/refguide6/Page+Concepts", to: "/refguide6/page-concepts" }, { from: "/refguide6/Page+Templates", to: "/refguide6/page-templates" }, { from: "/refguide6/Page+title", to: "/refguide6/page-title" }, { from: "/refguide6/Pages", to: "/refguide6/pages" }, { from: "/refguide6/Parameter", to: "/refguide6/parameter" }, { from: "/refguide6/Parse+and+format+date+function+calls", to: "/refguide6/parse-and-format-date-function-calls" }, { from: "/refguide6/Parse+and+format+decimal+function+calls", to: "/refguide6/parse-and-format-decimal-function-calls" }, { from: "/refguide6/Parse+and+format+float+function+calls", to: "/refguide6/parse-and-format-float-function-calls" }, { from: "/refguide6/Parse+integer", to: "/refguide6/parse-integer" }, { from: "/refguide6/Password+Policy", to: "/refguide6/password-policy" }, { from: "/refguide6/Persistability", to: "/refguide6/persistability" }, { from: "/refguide6/Phone+profile", to: "/refguide6/phone-profile" }, { from: "/refguide6/Placeholder", to: "/refguide6/placeholder" }, { from: "/refguide6/Preferences+Dialog", to: "/refguide6/preferences-dialog" }, { from: "/refguide6/Proactive+Maintenance", to: "/refguide6/proactive-maintenance" }, { from: "/refguide6/Project", to: "/refguide6/project" }, { from: "/refguide6/Project+Security", to: "/refguide6/project-security" }, { from: "/refguide6/Project+Settings", to: "/refguide6/project-settings" }, { from: "/refguide6/Publish+Packages+To+Mobile+Stores", to: "/refguide6/publish-packages-to-mobile-stores" }, { from: "/refguide6/Published+App+Service", to: "/refguide6/published-app-service" }, { from: "/refguide6/Published+App+Services", to: "/refguide6/published-app-services" }, { from: "/refguide6/Published+OData+resource", to: "/refguide6/published-odata-resource" }, { from: "/refguide6/Published+OData+Services", to: "/refguide6/published-odata-services" }, { from: "/refguide6/Published+web+service", to: "/refguide6/published-web-service" }, { from: "/refguide6/Published+Web+Services", to: "/refguide6/published-web-services" }, { from: "/refguide6/Radio+buttons", to: "/refguide6/radio-buttons" }, { from: "/refguide6/Range+Search+Field", to: "/refguide6/range-search-field" }, { from: "/refguide6/Reference+selector", to: "/refguide6/reference-selector" }, { from: "/refguide6/Reference+set+selector", to: "/refguide6/reference-set-selector" }, { from: "/refguide6/Regular+Expressions", to: "/refguide6/regular-expressions" }, { from: "/refguide6/Relational+expressions", to: "/refguide6/relational-expressions" }, { from: "/refguide6/Remove+button", to: "/refguide6/remove-button" }, { from: "/refguide6/Removed+APIs", to: "/refguide6/removed-apis" }, { from: "/refguide6/Report+Button", to: "/refguide6/report-button" }, { from: "/refguide6/Report+Chart", to: "/refguide6/report-chart" }, { from: "/refguide6/Report+Date+Parameter", to: "/refguide6/report-date-parameter" }, { from: "/refguide6/Report+Grid", to: "/refguide6/report-grid" }, { from: "/refguide6/Report+Pane", to: "/refguide6/report-pane" }, { from: "/refguide6/Report+Parameter", to: "/refguide6/report-parameter" }, { from: "/refguide6/Report+Widgets", to: "/refguide6/report-widgets" }, { from: "/refguide6/Reporting", to: "/refguide6/report-widgets" }, { from: "/refguide6/Retrieve", to: "/refguide6/retrieve" }, { from: "/refguide6/Review+log+files+-+MS+IIS+Server", to: "/refguide6/review-log-files-ms-iis-server" }, { from: "/refguide6/Review+log+files+-+MS+SQL+Server", to: "/refguide6/review-log-files-ms-sql-server" }, { from: "/refguide6/Rollback+Object", to: "/refguide6/rollback-object" }, { from: "/refguide6/Row+Document+Template", to: "/refguide6/row-document-template" }, { from: "/refguide6/Rules", to: "/refguide6/rules" }, { from: "/refguide6/Runtime", to: "/refguide6/runtime" }, { from: "/refguide6/Save+button", to: "/refguide6/save-button" }, { from: "/refguide6/Scheduled+Events", to: "/refguide6/scheduled-events" }, { from: "/refguide6/Scroll+Container", to: "/refguide6/scroll-container" }, { from: "/refguide6/Scroll+Container+Region", to: "/refguide6/scroll-container-region" }, { from: "/refguide6/Search+Bar", to: "/refguide6/search-bar" }, { from: "/refguide6/Search+button", to: "/refguide6/search-button" }, { from: "/refguide6/Security", to: "/refguide6/security" }, { from: "/refguide6/Select++Elements", to: "/refguide6/select--elements" }, { from: "/refguide6/Select+all+button", to: "/refguide6/select-all-button" }, { from: "/refguide6/Select+app+service", to: "/refguide6/select-app-service" }, { from: "/refguide6/Select+button", to: "/refguide6/select-button" }, { from: "/refguide6/Sequence+Flow", to: "/refguide6/sequence-flow" }, { from: "/refguide6/Settings", to: "/refguide6/settings" }, { from: "/refguide6/Show+Home+Page", to: "/refguide6/show-home-page" }, { from: "/refguide6/Show+Message", to: "/refguide6/show-message" }, { from: "/refguide6/Show+Page", to: "/refguide6/show-page" }, { from: "/refguide6/Sidebar+toggle+button", to: "/refguide6/sidebar-toggle-button" }, { from: "/refguide6/Sign+In+Dialog", to: "/refguide6/sign-in-dialog" }, { from: "/refguide6/Sign+out+button", to: "/refguide6/sign-out-button" }, { from: "/refguide6/Simple+Menu+Bar", to: "/refguide6/simple-menu-bar" }, { from: "/refguide6/Snippet", to: "/refguide6/snippet" }, { from: "/refguide6/Snippet+Call", to: "/refguide6/snippet-call" }, { from: "/refguide6/Sort+Bar", to: "/refguide6/sort-bar" }, { from: "/refguide6/Special+checks", to: "/refguide6/special-checks" }, { from: "/refguide6/Start+Event", to: "/refguide6/start-event" }, { from: "/refguide6/Starting+Microflows", to: "/refguide6/starting-microflows" }, { from: "/refguide6/Static+Image+Document+Template", to: "/refguide6/static-image-document-template" }, { from: "/refguide6/Static+Label+Document+Template", to: "/refguide6/static-label-document-template" }, { from: "/refguide6/String+function+calls", to: "/refguide6/string-function-calls" }, { from: "/refguide6/Style", to: "/refguide6/style" }, { from: "/refguide6/Sync+button", to: "/refguide6/sync-button" }, { from: "/refguide6/System+Requirements", to: "/refguide6/system-requirements" }, { from: "/refguide6/System+Texts", to: "/refguide6/system-texts" }, { from: "/refguide6/Tab+container", to: "/refguide6/tab-container" }, { from: "/refguide6/Tab+page", to: "/refguide6/tab-page" }, { from: "/refguide6/Table", to: "/refguide6/table" }, { from: "/refguide6/Table+cell", to: "/refguide6/table-cell" }, { from: "/refguide6/Table+Document+Template", to: "/refguide6/table-document-template" }, { from: "/refguide6/Table+row", to: "/refguide6/table-row" }, { from: "/refguide6/Tablet+profile", to: "/refguide6/tablet-profile" }, { from: "/refguide6/Team+Server", to: "/refguide6/team-server" }, { from: "/refguide6/Team+Server+FAQ", to: "/refguide6/team-server-faq" }, { from: "/refguide6/Template+grid", to: "/refguide6/template-grid" }, { from: "/refguide6/Template+Grid+Document+Template", to: "/refguide6/template-grid-document-template" }, { from: "/refguide6/Text", to: "/refguide6/text" }, { from: "/refguide6/Text+area", to: "/refguide6/text-area" }, { from: "/refguide6/Text+box", to: "/refguide6/text-box" }, { from: "/refguide6/Third+Party+Licenses", to: "/refguide6/third-party-licenses" }, { from: "/refguide6/Title+Document+Template", to: "/refguide6/title-document-template" }, { from: "/refguide6/To+float", to: "/refguide6/to-float" }, { from: "/refguide6/To+string", to: "/refguide6/to-string" }, { from: "/refguide6/Transient+Objects+Garbage+Collecting", to: "/refguide6/transient-objects-garbage-collecting" }, { from: "/refguide6/Translatable+Texts", to: "/refguide6/translatable-texts" }, { from: "/refguide6/Trim+to+date", to: "/refguide6/trim-to-date" }, { from: "/refguide6/Troubleshooting", to: "/refguide6/troubleshooting" }, { from: "/refguide6/Unary+expressions", to: "/refguide6/unary-expressions" }, { from: "/refguide6/Upload+To+Team+Server+Dialog", to: "/refguide6/upload-to-team-server-dialog" }, { from: "/refguide6/User+Roles", to: "/refguide6/user-roles" }, { from: "/refguide6/User+Role", to: "/refguide6/user-roles" }, { from: "/refguide6/Using+a+proxy+to+call+a+webservice", to: "/refguide6/using-a-proxy-to-call-a-webservice" }, { from: "/refguide6/Using+Eclipse", to: "/refguide6/using-eclipse" }, { from: "/refguide6/Validation+Feedback", to: "/refguide6/validation-feedback" }, { from: "/refguide6/Validation+Rules", to: "/refguide6/validation-rules" }, { from: "/refguide6/Variable+Activities", to: "/refguide6/variable-activities" }, { from: "/refguide6/Version+Control", to: "/refguide6/version-control" }, { from: "/refguide6/Version+Control+Concepts", to: "/refguide6/version-control-concepts" }, { from: "/refguide6/Version+Control+Scenarios", to: "/refguide6/version-control-scenarios" }, { from: "/refguide6/version-downgrade-prevention", to: "/deployment/mendixcloud/version-downgrade-prevention" }, { from: "/refguide6/Vertical+Split+Pane", to: "/refguide6/vertical-split-pane" }, { from: "/refguide6/XML+Inheritance+and+Choice", to: "/refguide6/xml-inheritance-and-choice" }, { from: "/refguide6/XML+Reference+Guide", to: "/refguide6/xml-reference-guide" }, { from: "/refguide6/XML+Schema+Support", to: "/refguide6/xml-schema-support" }, { from: "/refguide6/XML+Schemas", to: "/refguide6/xml-schemas" }, { from: "/refguide6/XPath", to: "/refguide6/xpath" }, { from: "/refguide6/XPath+avg", to: "/refguide6/xpath-avg" }, { from: "/refguide6/XPath+Constraint+Functions", to: "/refguide6/xpath-constraint-functions" }, { from: "/refguide6/XPath+Constraints", to: "/refguide6/xpath-constraints" }, { from: "/refguide6/XPath+contains", to: "/refguide6/xpath-contains" }, { from: "/refguide6/XPath+count", to: "/refguide6/xpath-count" }, { from: "/refguide6/XPath+day+from+dateTime", to: "/refguide6/xpath-day-from-datetime" }, { from: "/refguide6/XPath+day+of+year+from+dateTime", to: "/refguide6/xpath-day-of-year-from-datetime" }, { from: "/refguide6/XPath+ends+with", to: "/refguide6/xpath-ends-with" }, { from: "/refguide6/XPath+Expressions", to: "/refguide6/xpath-expressions" }, { from: "/refguide6/XPath+false", to: "/refguide6/xpath-false" }, { from: "/refguide6/XPath+hours+from+dateTime", to: "/refguide6/xpath-hours-from-datetime" }, { from: "/refguide6/XPath+id", to: "/refguide6/xpath-id" }, { from: "/refguide6/XPath+Keywords+and+System+Variables", to: "/refguide6/xpath-keywords-and-system-variables" }, { from: "/refguide6/XPath+length", to: "/refguide6/xpath-length" }, { from: "/refguide6/XPath+max", to: "/refguide6/xpath-max" }, { from: "/refguide6/XPath+min", to: "/refguide6/xpath-min" }, { from: "/refguide6/XPath+minutes+from+dateTime", to: "/refguide6/xpath-minutes-from-datetime" }, { from: "/refguide6/XPath+month+from+dateTime", to: "/refguide6/xpath-month-from-datetime" }, { from: "/refguide6/XPath+not", to: "/refguide6/xpath-not" }, { from: "/refguide6/XPath+Operators", to: "/refguide6/xpath-operators" }, { from: "/refguide6/XPath+quarter+from+dateTime", to: "/refguide6/xpath-quarter-from-datetime" }, { from: "/refguide6/XPath+Query+Functions", to: "/refguide6/xpath-query-functions" }, { from: "/refguide6/XPath+seconds+from+dateTime", to: "/refguide6/xpath-seconds-from-datetime" }, { from: "/refguide6/XPath+Source", to: "/refguide6/xpath-source" }, { from: "/refguide6/XPath+starts+with", to: "/refguide6/xpath-starts-with" }, { from: "/refguide6/XPath+string+length", to: "/refguide6/xpath-string-length" }, { from: "/refguide6/XPath+sum", to: "/refguide6/xpath-sum" }, { from: "/refguide6/XPath+Tokens", to: "/refguide6/xpath-tokens" }, { from: "/refguide6/XPath+true", to: "/refguide6/xpath-true" }, { from: "/refguide6/XPath+week+from+dateTime", to: "/refguide6/xpath-week-from-datetime" }, { from: "/refguide6/XPath+weekday+from+dateTime", to: "/refguide6/xpath-weekday-from-datetime" }, { from: "/refguide6/XPath+year+from+dateTime", to: "/refguide6/xpath-year-from-datetime" }, /**************************************************** * REFERENCE GUIDE MENDIX 7 ****************************************************/ { "from": "/refguide7/Reference+Guide+7", "to": "/refguide/" }, { "from": "/refguide7/TreeNavigation", "to": "/refguide/" }, { "from": "/refguide7/Access+Rules", "to": "/refguide/access-rules" }, { "from": "/refguide7/Action+Button", "to": "/refguide/action-button" }, { "from": "/refguide7/Action+Call+Activities", "to": "/refguide/action-call-activities" }, { "from": "/refguide7/Actions", "to": "/refguide/actions" }, { "from": "/refguide7/Activities", "to": "/refguide/activities" }, { "from": "/refguide7/Add+button", "to": "/refguide/add-button" }, { "from": "/refguide7/Add+date+function+calls", "to": "/refguide/add-date-function-calls" }, { "from": "/refguide7/Administrator", "to": "/refguide/administrator" }, { "from": "/refguide7/Aggregate+List", "to": "/refguide/aggregate-list" }, { "from": "/refguide7/Annotation", "to": "/refguide/annotation" }, { "from": "/refguide7/Annotation+flow", "to": "/refguide/annotation-flow" }, { "from": "/refguide7/Annotations", "to": "/refguide/annotations" }, { "from": "/refguide7/Anonymous+Users", "to": "/refguide/anonymous-users" }, { "from": "/refguide7/App+Platform", "to": "/refguide/app-platform" }, { "from": "/refguide7/App+Settings+Dialog", "to": "/refguide/app-settings-dialog" }, { "from": "/refguide7/Arithmetic+expressions", "to": "/refguide/arithmetic-expressions" }, { "from": "/refguide7/Association+Source", "to": "/refguide/association-source" }, { "from": "/refguide7/Associations", "to": "/refguide/associations" }, { "from": "/refguide7/Attributes", "to": "/refguide/attributes" }, { "from": "/refguide7/Between+date+function+calls", "to": "/refguide/between-date-function-calls" }, { "from": "/refguide7/Boolean+expressions", "to": "/refguide/boolean-expressions" }, { "from": "/refguide7/Branch+Line+Manager+Dialog", "to": "/refguide/branch-line-manager-dialog" }, { "from": "/refguide7/Break+Event", "to": "/refguide/break-event" }, { "from": "/refguide7/Button+Widgets", "to": "/refguide/button-widgets" }, { "from": "/refguide7/Call+Rest+Action", "to": "/refguide/call-rest-action" }, { "from": "/refguide7/Call+Web+Service", "to": "/refguide/call-web-service" }, { "from": "/refguide7/Call+Web+Service+Action", "to": "/refguide/call-web-service-action" }, { "from": "/refguide7/Cast+Object", "to": "/refguide/cast-object" }, { "from": "/refguide7/Cell+Document+Template", "to": "/refguide/cell-document-template" }, { "from": "/refguide7/Change+List", "to": "/refguide/change-list" }, { "from": "/refguide7/Change+Object", "to": "/refguide/change-object" }, { "from": "/refguide7/Change+Variable", "to": "/refguide/change-variable" }, { "from": "/refguide7/Check+box", "to": "/refguide/check-box" }, { "from": "/refguide7/Client+Activities", "to": "/refguide/client-activities" }, { "from": "/refguide7/Close+Form", "to": "/refguide/close-page" }, { "from": "/refguide7/Clustered+Mendix+Runtime", "to": "/refguide/clustered-mendix-runtime" }, { "from": "/refguide7/Clustered+Mendix+Business+Server", "to": "/refguide/clustered-mendix-runtime" }, { "from": "/refguide7/Columns", "to": "/refguide/columns" }, { "from": "/refguide7/Columns+Document+Template", "to": "/refguide/columns-document-template" }, { "from": "/refguide7/Commit+Dialog", "to": "/refguide/commit-dialog" }, { "from": "/refguide7/Commit+Object(s)", "to": "/refguide/committing-objects" }, { "from": "/refguide7/Committing+Objects", "to": "/refguide/committing-objects" }, { "from": "/refguide7/Common+Widget+Properties", "to": "/refguide/common-widget-properties" }, { "from": "/refguide7/Common+Widgets", "to": "/refguide/common-widgets" }, { "from": "/refguide7/Comparison+Search+Field", "to": "/refguide/comparison-search-field" }, { "from": "/refguide7/Conditions", "to": "/refguide/conditions" }, { "from": "/refguide7/Configuration", "to": "/refguide/configuration" }, { "from": "/refguide7/Configuring+Hybrid+Mobile+Apps+To+Run+Offline", "to": "/refguide/configuring-hybrid-mobile-apps-to-run-offline" }, { "from": "/refguide7/Constants", "to": "/refguide/constants" }, { "from": "/refguide7/Consumed+App+Services", "to": "/refguide/consumed-app-services" }, { "from": "/refguide7/Consumed+REST+Services", "to": "/refguide/consumed-rest-services" }, { "from": "/refguide7/Consumed+web+service", "to": "/refguide/consumed-web-service" }, { "from": "/refguide7/Consumed+Web+Services", "to": "/refguide/consumed-web-services" }, { "from": "/refguide7/Container", "to": "/refguide/container" }, { "from": "/refguide7/Container+Widgets", "to": "/refguide/container-widgets" }, { "from": "/refguide7/Continue+Event", "to": "/refguide/continue-event" }, { "from": "/refguide7/Control+Bar", "to": "/refguide/control-bar" }, { "from": "/refguide7/Create+Branch+Line+Dialog", "to": "/refguide/create-branch-line-dialog" }, { "from": "/refguide7/Create+Deployment+Package+Dialog", "to": "/refguide/create-deployment-package-dialog" }, { "from": "/refguide7/Create+List", "to": "/refguide/create-list" }, { "from": "/refguide7/Create+Object", "to": "/refguide/create-object" }, { "from": "/refguide7/Create+Variable", "to": "/refguide/create-variable" }, { "from": "/refguide7/Custom+Settings", "to": "/refguide/custom-settings" }, { "from": "/refguide7/Customizing+Hybrid+Mobile+Apps", "to": "/refguide/customizing-hybrid-mobile-apps" }, { "from": "/refguide7/Customizing+PhoneGap+Build+packages", "to": "/refguide/customizing-phonegap-build-packages" }, { "from": "/refguide7/Data+grid", "to": "/refguide/data-grid" }, { "from": "/refguide7/Data+Grid+Document+Template", "to": "/refguide/data-grid-document-template" }, { "from": "/refguide7/Data+Sets", "to": "/refguide/data-sets" }, { "from": "/refguide7/Data+Sources", "to": "/refguide/data-sources" }, { "from": "/refguide7/Data+Storage", "to": "/refguide/data-storage" }, { "from": "/refguide7/Data+Types", "to": "/refguide/data-types" }, { "from": "/refguide7/Data+view", "to": "/refguide/data-view" }, { "from": "/refguide7/Data+View+Document+Template", "to": "/refguide/data-view-document-template" }, { "from": "/refguide7/Data+Widgets", "to": "/refguide/data-widgets" }, { "from": "/refguide7/Database+Source", "to": "/refguide/database-source" }, { "from": "/refguide7/Date+and+Time+Handling+in+3.0", "to": "/refguide/date-and-time-handling" }, { "from": "/refguide7/Date+creation", "to": "/refguide/date-creation" }, { "from": "/refguide7/Date+picker", "to": "/refguide/date-picker" }, { "from": "/refguide7/Date+Range+Field", "to": "/refguide/date-range-field" }, { "from": "/refguide7/DateTime+handling+FAQ", "to": "/refguide/datetime-handling-faq" }, { "from": "/refguide7/DB2", "to": "/refguide/db2" }, { "from": "/refguide7/Delete+button", "to": "/refguide/delete-button" }, { "from": "/refguide7/Delete+Object(s)", "to": "/refguide/deleting-objects" }, { "from": "/refguide7/Deleting+Objects", "to": "/refguide/deleting-objects" }, { "from": "/refguide7/Demo+Users", "to": "/refguide/demo-users" }, { "from": "/refguide7/Deploy+To+The+Cloud+Dialog", "to": "/refguide/deploy-to-the-cloud-dialog" }, { "from": "/refguide7/Deselect+all+button", "to": "/refguide/deselect-all-button" }, { "from": "/refguide7/Desktop+profile", "to": "/refguide/desktop-profile" }, { "from": "/refguide7/desktop-webmodeler", "to": "/howto/web-modeler/syncing-webmodeler-desktop" }, { "from": "/refguide7/Developing+Hybrid+Mobile+Apps", "to": "/refguide/developing-hybrid-mobile-apps" }, { "from": "/refguide7/Dialogs", "to": "/refguide/dialogs" }, { "from": "/refguide7/Document+Generation+Activities", "to": "/refguide/document-generation-activities" }, { "from": "/refguide7/Document+Template", "to": "/refguide/document-template" }, { "from": "/refguide7/Document+Templates", "to": "/refguide/document-templates" }, { "from": "/refguide7/Domain+Model", "to": "/refguide/domain-model" }, { "from": "/refguide7/Download+File", "to": "/refguide/download-file" }, { "from": "/refguide7/Download+From+Team+Server+Dialog", "to": "/refguide/download-from-version-control-dialog" }, { "from": "/refguide7/drop-down-widget", "to": "/refguide/drop_down" }, { "from": "/refguide7/Drop-down", "to": "/refguide/drop_down" }, { "from": "/refguide7/Drop+Down+Widget", "to": "/refguide/drop_down" }, { "from": "/refguide7/Drop+Down Widget", "to": "/refguide/drop_down" }, { "from": "/refguide7/Drop+down+button", "to": "/refguide/drop-down-button" }, { "from": "/refguide7/Drop+Down+Search+Field", "to": "/refguide/drop-down-search-field" }, { "from": "/refguide7/Dynamic+Image+Document+Template", "to": "/refguide/dynamic-image-document-template" }, { "from": "/refguide7/Dynamic+Label+Document+Template", "to": "/refguide/dynamic-label-document-template" }, { "from": "/refguide7/Edit+button", "to": "/refguide/edit-button" }, { "from": "/refguide7/Edit+Cloud+Foundry+Settings+Dialog", "to": "/refguide/edit-cloud-foundry-settings-dialog" }, { "from": "/refguide7/End+Event", "to": "/refguide/end-event" }, { "from": "/refguide7/Entities", "to": "/refguide/entities" }, { "from": "/refguide7/Entity+Path+Source", "to": "/refguide/entity-path-source" }, { "from": "/refguide7/Enumeration+Values", "to": "/refguide/enumeration-values" }, { "from": "/refguide7/Enumerations", "to": "/refguide/enumerations" }, { "from": "/refguide7/Enumerations+in+microflow+expressions", "to": "/refguide/enumerations-in-expressions" }, { "from": "/refguide7/Error+Event", "to": "/refguide/error-event" }, { "from": "/refguide7/Event+Handlers", "to": "/refguide/event-handlers" }, { "from": "/refguide7/Exclusive+Split", "to": "/refguide/exclusive-split" }, { "from": "/refguide7/Export+Mapping+Action", "to": "/refguide/export-mapping-action" }, { "from": "/refguide7/Export+Mappings", "to": "/refguide/export-mappings" }, { "from": "/refguide7/Export+to+CSV+button", "to": "/refguide/export-to-csv-button" }, { "from": "/refguide7/Export+to+excel+button", "to": "/refguide/export-to-excel-button" }, { "from": "/refguide7/Export+XML", "to": "/refguide/export-xml" }, { "from": "/refguide7/File+manager", "to": "/refguide/file-manager" }, { "from": "/refguide7/File+Widgets", "to": "/refguide/file-widgets" }, { "from": "/refguide7/Footer+Document+Template", "to": "/refguide/footer-document-template" }, { "from": "/refguide7/General", "to": "/refguide/general" }, { "from": "/refguide7/Generate+Document", "to": "/refguide/generate-document" }, { "from": "/refguide7/Getting+the+Mendix+Developer+App", "to": "/refguide/getting-the-mendix-app" }, { "from": "/refguide7/Grid+action+button", "to": "/refguide/grid-action-button" }, { "from": "/refguide7/Grid+New+Button", "to": "/refguide/grid-new-button" }, { "from": "/refguide7/Group+box", "to": "/refguide/group-box" }, { "from": "/refguide7/Section", "to": "/refguide/group-box" }, { "from": "/refguide7/Header", "to": "/refguide/header" }, { "from": "/refguide7/Header+Document+Template", "to": "/refguide/header-document-template" }, { "from": "/refguide7/History+Dialog", "to": "/refguide/history-dialog" }, { "from": "/refguide7/horizontal-split-pane", "to": "/refguide/scroll-container" }, { "from": "/refguide7/If+expressions", "to": "/refguide/if-expressions" }, { "from": "/refguide7/Image", "to": "/refguide/image" }, { "from": "/refguide7/Image+uploader", "to": "/refguide/image-uploader" }, { "from": "/refguide7/Image+viewer", "to": "/refguide/image-viewer" }, { "from": "/refguide7/Images+refguide", "to": "/refguide/images" }, { "from": "/refguide7/Images", "to": "/refguide/images" }, { "from": "/refguide7/Image+Property", "to": "/refguide/image-property" }, { "from": "/refguide7/Import+Mapping+Action", "to": "/refguide/import-mapping-action" }, { "from": "/refguide7/Import+Mappings", "to": "/refguide/import-mappings" }, { "from": "/refguide7/Import+XML", "to": "/refguide/import-xml" }, { "from": "/refguide7/Inheritance+Split", "to": "/refguide/inheritance-split" }, { "from": "/refguide7/Indexes", "to": "/refguide/indexes" }, { "from": "/refguide7/Input+reference+set+selector", "to": "/refguide/input-reference-set-selector" }, { "from": "/refguide7/Input+Widgets", "to": "/refguide/input-widgets" }, { "from": "/refguide7/Integration", "to": "/refguide/integration" }, { "from": "/refguide7/Integration+Activities", "to": "/refguide/integration-activities" }, { "from": "/refguide7/Java+Action+Call", "to": "/refguide/java-action-call" }, { "from": "/refguide7/Java+Actions", "to": "/refguide/java-actions" }, { "from": "/refguide7/Java+Memory+Usage+With+Mendix", "to": "/refguide/java-memory-usage-with-mendix" }, { "from": "/refguide7/Java+Programming", "to": "/refguide/java-programming" }, { "from": "/refguide7/JSON+Structures", "to": "/refguide/json-structures" }, { "from": "/refguide7/Label", "to": "/refguide/label" }, { "from": "/refguide7/Layout", "to": "/refguide/layout" }, { "from": "/refguide7/Layouts", "to": "/refguide/layout" }, { "from": "/refguide7/Layout+grid", "to": "/refguide/layout-grid" }, { "from": "/refguide7/Layout+Widgets", "to": "/refguide/layout-widgets" }, { "from": "/refguide7/Line+Break+Document+Template", "to": "/refguide/line-break-document-template" }, { "from": "/refguide7/Link+button", "to": "/refguide/action-button" }, { "from": "/refguide7/List+Activities", "to": "/refguide/list-activities" }, { "from": "/refguide7/List+Operation", "to": "/refguide/list-operation" }, { "from": "/refguide7/List+view", "to": "/refguide/list-view" }, { "from": "/refguide7/Listen+To+Grid+Source", "to": "/refguide/listen-to-grid-source" }, { "from": "/refguide7/Log+Message", "to": "/refguide/log-message" }, { "from": "/refguide7/Logging", "to": "/refguide/logging" }, { "from": "/refguide7/Logging+Activities", "to": "/refguide/logging-activities" }, { "from": "/refguide7/Loop", "to": "/refguide/loop" }, { "from": "/refguide7/Managing+App+Signing+Keys", "to": "/refguide/managing-app-signing-keys" }, { "from": "/refguide7/Map+Automatically", "to": "/refguide/map-automatically" }, { "from": "/refguide7/Mapping+Documents", "to": "/refguide/mapping-documents" }, { "from": "/refguide7/Mathematical+function+calls", "to": "/refguide/mathematical-function-calls" }, { "from": "/refguide7/Menu", "to": "/refguide/menu" }, { "from": "/refguide7/Menu+Bar", "to": "/refguide/menu-bar" }, { "from": "/refguide7/Menu+Item", "to": "/refguide/menu-item" }, { "from": "/refguide7/Menu+Widgets", "to": "/refguide/menu-widgets" }, { "from": "/refguide7/Merge", "to": "/refguide/merge" }, { "from": "/refguide7/Merge+Dialog", "to": "/refguide/merge-dialog" }, { "from": "/refguide7/Microflow", "to": "/refguide/microflow" }, { "from": "/refguide7/Microflow+Activities", "to": "/refguide/microflow-activities" }, { "from": "/refguide7/Microflow+Call", "to": "/refguide/microflow-call" }, { "from": "/refguide7/Microflow+Element+Common+Properties", "to": "/refguide/microflow-element-common-properties" }, { "from": "/refguide7/Microflow+Expressions", "to": "/refguide/expressions" }, { "from": "/refguide7/microflow-expressions", "to": "/refguide/expressions" }, { "from": "/refguide7/Microflow+Source", "to": "/refguide/microflow-source" }, { "from": "/refguide7/Microflows", "to": "/refguide/microflows" }, { "from": "/refguide7/Mobile", "to": "/refguide/mobile" }, { "from": "/refguide7/Model+Share", "to": "/refguide/model-share" }, { "from": "/refguide7/Modeler", "to": "/refguide/desktop-modeler" }, { "from": "/refguide7/Module+Role", "to": "/refguide/module-role" }, { "from": "/refguide7/Module+Security", "to": "/refguide/module-security" }, { "from": "/refguide7/Module+Status", "to": "/refguide/module-status" }, { "from": "/refguide7/Modules", "to": "/refguide/modules" }, { "from": "/refguide7/Monitoring+-+Mendix+Runtime", "to": "/refguide/monitoring-mendix-runtime" }, { "from": "/refguide7/Monitoring+-+Mendix+Business+Server", "to": "/refguide/monitoring-mendix-runtime" }, { "from": "/refguide7/Moving+from+6+to+7", "to": "/refguide/moving-from-6-to-7" }, { "from": "/refguide7/MySQL", "to": "/refguide/mysql" }, { "from": "/refguide7/Navigation", "to": "/refguide/navigation" }, { "from": "/refguide7/Navigation+list", "to": "/refguide/navigation-list" }, { "from": "/refguide7/Navigation+Tree", "to": "/refguide/navigation-tree" }, { "from": "/refguide7/New+button", "to": "/refguide/new-button" }, { "from": "/refguide7/NULL+Ordering+Behavior", "to": "/refguide/null-ordering-behavior" }, { "from": "/refguide7/Numeric+formatting", "to": "/refguide/numeric-formatting" }, { "from": "/refguide7/Object+Activities", "to": "/refguide/object-activities" }, { "from": "/refguide7/OData+Query+Options", "to": "/refguide/odata-query-options" }, { "from": "/refguide7/OData+Representation", "to": "/refguide/odata-representation" }, { "from": "/refguide7/Offline", "to": "/refguide/offline" }, { "from": "/refguide7/Offline+device+profile", "to": "/refguide/offline-device-profile" }, { "from": "/refguide7/On+Click+Event", "to": "/refguide/on-click-event" }, { "from": "/refguide7/Open+Project+Dialog", "to": "/refguide/open-app-dialog" }, { "from": "/refguide7/Opening+Pages", "to": "/refguide/opening-pages" }, { "from": "/refguide7/Operations", "to": "/refguide/operations" }, { "from": "/refguide7/OQL", "to": "/refguide/oql" }, { "from": "/refguide7/OQL+Aggregation", "to": "/refguide/oql-aggregation" }, { "from": "/refguide7/OQL+Case+Expression", "to": "/refguide/oql-case-expression" }, { "from": "/refguide7/OQL+CAST", "to": "/refguide/oql-cast" }, { "from": "/refguide7/OQL+COALESCE", "to": "/refguide/oql-coalesce" }, { "from": "/refguide7/OQL+DATEDIFF", "to": "/refguide/oql-datediff" }, { "from": "/refguide7/OQL+DATEPART", "to": "/refguide/oql-datepart" }, { "from": "/refguide7/OQL+Expressions", "to": "/refguide/oql-expressions" }, { "from": "/refguide7/OQL+From+Clause", "to": "/refguide/oql-from-clause" }, { "from": "/refguide7/OQL+FULL+OUTER+JOIN", "to": "/refguide/oql-full-outer-join" }, { "from": "/refguide7/OQL+Functions", "to": "/refguide/oql-functions" }, { "from": "/refguide7/OQL+Group+by+Clause", "to": "/refguide/oql-group-by-clause" }, { "from": "/refguide7/OQL+INNER+JOIN", "to": "/refguide/oql-inner-join" }, { "from": "/refguide7/OQL+LEFT+OUTER+JOIN", "to": "/refguide/oql-left-outer-join" }, { "from": "/refguide7/OQL+LENGTH", "to": "/refguide/oql-length" }, { "from": "/refguide7/OQL+Limit+Clause", "to": "/refguide/oql-limit-clause" }, { "from": "/refguide7/OQL+Operators", "to": "/refguide/oql-operators" }, { "from": "/refguide7/OQL+Order+by+Clause", "to": "/refguide/oql-order-by-clause" }, { "from": "/refguide7/OQL+Parameters", "to": "/refguide/oql-parameters" }, { "from": "/refguide7/OQL+RANGEBEGIN", "to": "/refguide/oql-rangebegin" }, { "from": "/refguide7/OQL+RANGEEND", "to": "/refguide/oql-rangeend" }, { "from": "/refguide7/OQL+RIGHT+OUTER+JOIN", "to": "/refguide/oql-right-outer-join" }, { "from": "/refguide7/OQL+ROUND", "to": "/refguide/oql-round" }, { "from": "/refguide7/OQL+Select+Clause", "to": "/refguide/oql-select-clause" }, { "from": "/refguide7/OQL+Where+Clause", "to": "/refguide/oql-where-clause" }, { "from": "/refguide7/Oracle", "to": "/refguide/oracle" }, { "from": "/refguide7/Packaging+Hybrid+Mobile+Apps", "to": "/refguide/packaging-hybrid-mobile-apps" }, { "from": "/refguide7/Page", "to": "/refguide/page" }, { "from": "/refguide7/Page+Break+Document+Template", "to": "/refguide/page-break-document-template" }, { "from": "/refguide7/Page+Concepts", "to": "/refguide/page-concepts" }, { "from": "/refguide7/Page+Templates", "to": "/refguide/page-templates" }, { "from": "/refguide7/Page+title", "to": "/refguide/page-title" }, { "from": "/refguide7/Pages", "to": "/refguide/pages" }, { "from": "/refguide7/Parameter", "to": "/refguide/parameter" }, { "from": "/refguide7/Parse+and+format+date+function+calls", "to": "/refguide/parse-and-format-date-function-calls" }, { "from": "/refguide7/Parse+and+format+decimal+function+calls", "to": "/refguide/parse-and-format-decimal-function-calls" }, { "from": "/refguide7/Parse+and+format+float+function+calls", "to": "/refguide/parse-and-format-float-function-calls" }, { "from": "/refguide7/Parse+integer", "to": "/refguide/parse-integer" }, { "from": "/refguide7/Password+Policy", "to": "/refguide/password-policy" }, { "from": "/refguide7/Persistability", "to": "/refguide/persistability" }, { "from": "/refguide7/Phone+profile", "to": "/refguide/phone-profile" }, { "from": "/refguide7/Placeholder", "to": "/refguide/placeholder" }, { "from": "/refguide7/Preferences+Dialog", "to": "/refguide/preferences-dialog" }, { "from": "/refguide7/Project", "to": "/refguide/project" }, { "from": "/refguide7/Project+Security", "to": "/refguide/project-security" }, { "from": "/refguide7/Project+Settings", "to": "/refguide/project-settings" }, { "from": "/refguide7/Publish+Packages+To+Mobile+Stores", "to": "/refguide/publish-packages-to-mobile-stores" }, { "from": "/refguide7/Published+App+Service", "to": "/refguide/published-app-service" }, { "from": "/refguide7/Published+App+Services", "to": "/refguide/published-app-services" }, { "from": "/refguide7/Published+OData+resource", "to": "/refguide/published-odata-resource" }, { "from": "/refguide7/Published+OData+Services", "to": "/refguide/published-odata-services" }, { "from": "/refguide7/Published+web+service", "to": "/refguide/published-web-service" }, { "from": "/refguide7/Published+Web+Services", "to": "/refguide/published-web-services" }, { "from": "/refguide7/Radio+buttons", "to": "/refguide/radio-buttons" }, { "from": "/refguide7/Range+Search+Field", "to": "/refguide/range-search-field" }, { "from": "/refguide7/Reference+selector", "to": "/refguide/reference-selector" }, { "from": "/refguide7/Reference+set+selector", "to": "/refguide/reference-set-selector" }, { "from": "/refguide7/Regular+Expressions", "to": "/refguide/regular-expressions" }, { "from": "/refguide7/Relational+expressions", "to": "/refguide/relational-expressions" }, { "from": "/refguide7/Remove+button", "to": "/refguide/remove-button" }, { "from": "/refguide7/Report+Button", "to": "/refguide/report-button" }, { "from": "/refguide7/Report+Chart", "to": "/refguide/report-chart" }, { "from": "/refguide7/Report+Date+Parameter", "to": "/refguide/report-date-parameter" }, { "from": "/refguide7/Report+Grid", "to": "/refguide/report-grid" }, { "from": "/refguide7/Report+Parameter", "to": "/refguide/report-parameter" }, { "from": "/refguide7/Report+Widgets", "to": "/refguide/report-widgets" }, { "from": "/refguide7/Reporting", "to": "/refguide/report-widgets" }, { "from": "/refguide7/Retrieve", "to": "/refguide/retrieve" }, { "from": "/refguide7/Rollback+Object", "to": "/refguide/rollback-object" }, { "from": "/refguide7/Row+Document+Template", "to": "/refguide/row-document-template" }, { "from": "/refguide7/Rules", "to": "/refguide/rules" }, { "from": "/refguide7/Runtime", "to": "/refguide/runtime" }, { "from": "/refguide7/Scheduled+Events", "to": "/refguide/scheduled-events" }, { "from": "/refguide7/Scroll+Container", "to": "/refguide/scroll-container" }, { "from": "/refguide7/Scroll+Container+Region", "to": "/refguide/scroll-container-region" }, { "from": "/refguide7/Search+Bar", "to": "/refguide/search-bar" }, { "from": "/refguide7/Search+button", "to": "/refguide/search-button" }, { "from": "/refguide7/Security", "to": "/refguide/security" }, { "from": "/refguide7/Select++Elements", "to": "/refguide/select--elements" }, { "from": "/refguide7/Select+all+button", "to": "/refguide/select-all-button" }, { "from": "/refguide7/Select+app+service", "to": "/refguide/select-app-service" }, { "from": "/refguide7/Select+button", "to": "/refguide/select-button" }, { "from": "/refguide7/Sequence+Flow", "to": "/refguide/sequence-flow" }, { "from": "/refguide7/Settings", "to": "/refguide/settings" }, { "from": "/refguide7/Show+Home+Page", "to": "/refguide/show-home-page" }, { "from": "/refguide7/Show+Message", "to": "/refguide/show-message" }, { "from": "/refguide7/Show+Page", "to": "/refguide/show-page" }, { "from": "/refguide7/Sidebar+toggle+button", "to": "/refguide/sidebar-toggle-button" }, { "from": "/refguide7/Sign+In+Dialog", "to": "/refguide/sign-in-dialog" }, { "from": "/refguide7/Sign+out+button", "to": "/refguide/action-button" }, { "from": "/refguide7/Simple+Menu+Bar", "to": "/refguide/simple-menu-bar" }, { "from": "/refguide7/Snippet", "to": "/refguide/snippet" }, { "from": "/refguide7/Snippet+Call", "to": "/refguide/snippet-call" }, { "from": "/refguide7/Sort+Bar", "to": "/refguide/sort-bar" }, { "from": "/refguide7/Special+checks", "to": "/refguide/special-checks" }, { "from": "/refguide7/Start+Event", "to": "/refguide/start-event" }, { "from": "/refguide7/Starting+Microflows", "to": "/refguide/starting-microflows" }, { "from": "/refguide7/Static+Image+Document+Template", "to": "/refguide/static-image-document-template" }, { "from": "/refguide7/Static+Label+Document+Template", "to": "/refguide/static-label-document-template" }, { "from": "/refguide7/String+function+calls", "to": "/refguide/string-function-calls" }, { "from": "/refguide7/Style", "to": "/refguide/style" }, { "from": "/refguide7/System+Requirements", "to": "/refguide/system-requirements" }, { "from": "/refguide7/System+Texts", "to": "/refguide/system-texts" }, { "from": "/refguide7/Tab+container", "to": "/refguide/tab-container" }, { "from": "/refguide7/Tab+page", "to": "/refguide/tab-page" }, { "from": "/refguide7/Table", "to": "/refguide/table" }, { "from": "/refguide7/Table+cell", "to": "/refguide/table-cell" }, { "from": "/refguide7/Table+Document+Template", "to": "/refguide/table-document-template" }, { "from": "/refguide7/Table+row", "to": "/refguide/table-row" }, { "from": "/refguide7/Tablet+profile", "to": "/refguide/tablet-profile" }, { "from": "/refguide7/Team+Server", "to": "/refguide/team-server" }, { "from": "/refguide7/Team+Server+FAQ", "to": "/refguide/team-server-faq" }, { "from": "/refguide7/Template+grid", "to": "/refguide/template-grid" }, { "from": "/refguide7/Template+Grid+Document+Template", "to": "/refguide/template-grid-document-template" }, { "from": "/refguide7/Text", "to": "/refguide/text", "case": true }, { "from": "/refguide7/Text+area", "to": "/refguide/text-area", "case": true }, { "from": "/refguide7/Text+box", "to": "/refguide/text-box", "case": true }, { "from": "/refguide7/Third+Party+Licenses", "to": "/refguide/third-party-licenses" }, { "from": "/refguide7/Title+Document+Template", "to": "/refguide/title-document-template" }, { "from": "/refguide7/To+float", "to": "/refguide/to-float" }, { "from": "/refguide7/To+string", "to": "/refguide/to-string" }, { "from": "/refguide7/Transient+Objects+Garbage+Collecting", "to": "/refguide/transient-objects-garbage-collecting" }, { "from": "/refguide7/Translatable+Texts", "to": "/refguide/translatable-texts" }, { "from": "/refguide7/Trim+to+date", "to": "/refguide/trim-to-date" }, { "from": "/refguide7/Troubleshooting", "to": "/refguide/troubleshooting" }, { "from": "/refguide7/Unary+expressions", "to": "/refguide/unary-expressions" }, { "from": "/refguide7/Upload+To+Team+Server+Dialog", "to": "/refguide/upload-to-version-control-dialog" }, { "from": "/refguide7/User+Roles", "to": "/refguide/user-roles" }, { "from": "/refguide7/User+Role", "to": "/refguide/user-roles" }, { "from": "/refguide7/Using+a+proxy+to+call+a+webservice", "to": "/refguide/using-a-proxy-to-call-a-webservice" }, { "from": "/refguide7/Using+Eclipse", "to": "/refguide/using-eclipse" }, { "from": "/refguide7/Validation+Feedback", "to": "/refguide/validation-feedback" }, { "from": "/refguide7/Validation+Rules", "to": "/refguide/validation-rules" }, { "from": "/refguide7/Variable+Activities", "to": "/refguide/variable-activities" }, { "from": "/refguide7/Version+Control", "to": "/refguide/version-control" }, { "from": "/refguide7/Version+Control+Concepts", "to": "/refguide/version-control-concepts" }, { "from": "/refguide7/Version+Control+Scenarios", "to": "/refguide/version-control-scenarios" }, { "from": "/refguide7/vertical-split-pane", "to": "/refguide/scroll-container" }, { "from": "/refguide7/XML+Inheritance+and+Choice", "to": "/refguide/xml-inheritance-and-choice" }, { "from": "/refguide7/XML+Reference+Guide", "to": "/refguide/xml-reference-guide" }, { "from": "/refguide7/XML+Schema+Support", "to": "/refguide/xml-schema-support" }, { "from": "/refguide7/XML+Schemas", "to": "/refguide/xml-schemas" }, { "from": "/refguide7/XPath", "to": "/refguide/xpath" }, { "from": "/refguide7/XPath+avg", "to": "/refguide/xpath-avg" }, { "from": "/refguide7/XPath+Constraint+Functions", "to": "/refguide/xpath-constraint-functions" }, { "from": "/refguide7/XPath+Constraints", "to": "/refguide/xpath-constraints" }, { "from": "/refguide7/XPath+contains", "to": "/refguide/xpath-contains" }, { "from": "/refguide7/XPath+count", "to": "/refguide/xpath-count" }, { "from": "/refguide7/XPath+day+from+dateTime", "to": "/refguide/xpath-day-from-datetime" }, { "from": "/refguide7/XPath+day+of+year+from+dateTime", "to": "/refguide/xpath-day-of-year-from-datetime" }, { "from": "/refguide7/XPath+ends+with", "to": "/refguide/xpath-ends-with" }, { "from": "/refguide7/XPath+Expressions", "to": "/refguide/xpath-expressions" }, { "from": "/refguide7/XPath+false", "to": "/refguide/xpath-false" }, { "from": "/refguide7/XPath+hours+from+dateTime", "to": "/refguide/xpath-hours-from-datetime" }, { "from": "/refguide7/XPath+id", "to": "/refguide/xpath-id" }, { "from": "/refguide7/XPath+Keywords+and+System+Variables", "to": "/refguide/xpath-keywords-and-system-variables" }, { "from": "/refguide7/XPath+length", "to": "/refguide/xpath-length" }, { "from": "/refguide7/XPath+max", "to": "/refguide/xpath-max" }, { "from": "/refguide7/XPath+min", "to": "/refguide/xpath-min" }, { "from": "/refguide7/XPath+minutes+from+dateTime", "to": "/refguide/xpath-minutes-from-datetime" }, { "from": "/refguide7/XPath+month+from+dateTime", "to": "/refguide/xpath-month-from-datetime" }, { "from": "/refguide7/XPath+not", "to": "/refguide/xpath-not" }, { "from": "/refguide7/XPath+Operators", "to": "/refguide/xpath-operators" }, { "from": "/refguide7/XPath+quarter+from+dateTime", "to": "/refguide/xpath-quarter-from-datetime" }, { "from": "/refguide7/XPath+Query+Functions", "to": "/refguide/xpath-query-functions" }, { "from": "/refguide7/XPath+seconds+from+dateTime", "to": "/refguide/xpath-seconds-from-datetime" }, { "from": "/refguide7/XPath+Source", "to": "/refguide/xpath-source" }, { "from": "/refguide7/XPath+starts+with", "to": "/refguide/xpath-starts-with" }, { "from": "/refguide7/XPath+string+length", "to": "/refguide/xpath-string-length" }, { "from": "/refguide7/XPath+sum", "to": "/refguide/xpath-sum" }, { "from": "/refguide7/XPath+Tokens", "to": "/refguide/xpath-tokens" }, { "from": "/refguide7/XPath+true", "to": "/refguide/xpath-true" }, { "from": "/refguide7/XPath+week+from+dateTime", "to": "/refguide/xpath-week-from-datetime" }, { "from": "/refguide7/XPath+weekday+from+dateTime", "to": "/refguide/xpath-weekday-from-datetime" }, { "from": "/refguide7/XPath+year+from+dateTime", "to": "/refguide/xpath-year-from-datetime" }, { "from": "/bestpractices/SIG+-+Mendix+performance+subjects+explanation", "to": "/refguide/sig-mendix-performance-subjects-explanation" }, { "from": "/bestpractices/Inheritance+vs.+1+1+association", "to": "/refguide/inheritance-vs.-1-1-association" }, { "from": "/refguide7/certificates", "to": "/deployment/mendixcloud/certificates" }, /**************************************************** * REFERENCE GUIDE RENAMES ****************************************************/ { "from": "/refguide/download-from-team-server-dialog", "to": "/refguide/download-from-version-control-dialog" }, { "from": "/refguide/open-project-dialog", "to": "/refguide/open-app-dialog" }, { "from": "/refguide/upload-to-team-server-dialog", "to": "/refguide/upload-to-version-control-dialog" }, /**************************************************** * TIPS & TRICKS ****************************************************/ { from: "/tips/Finding+Object+Activities", to: "/howto/tips/finding-object-activities" }, { from: "/tips/Finding+Unused+Items", to: "/howto/tips/finding-unused-items" }, { from: "/tips/Finding+your+way+through+a+project", to: "/howto/tips/finding-your-way-through-a-project" }, { from: "/tips/Import+a+large+Excel+file", to: "/howto/tips/import-a-large-excel-file" }, { from: "/tips/Tips+and+Tricks", to: "/howto/tips/" }, { from: "/tips/Migrating+your+Mendix+database", to: "/howto/tips/migrating-your-mendix-database" }, { from: "/tips/Querying+over+self-references", to: "/howto/tips/querying-over-self-references" }, { from: "/tips/Showing+a+Project+in+the+Directory+in+Explorer", to: "/howto/tips/showing-a-project-in-the-directory-in-explorer" }, { from: "/tips/Translatable+Validation+Messages", to: "/howto/tips/translatable-validation-messages" }, /**************************************************** * APM ****************************************************/ // { // from: "~*\\\/apm\\\/use-cases\\\/uc", // to: "/apm/use-cases/", // exact: true // }, // { // from: "~*\\\/apm\\\/installation-guide\\\/ig", // to: "/apm/installation-guide/", // exact: true // }, // { // from: "~*\\\/apm\\\/reference-guide\\\/rg", // to: "/apm/reference-guide/", // exact: true // }, /**************************************************** * RELEASE NOTES ****************************************************/ { from: "/ReleaseNotes/", to: "/releasenotes/" }, { from: "/ReleaseNotes/Release+Notes+Home", to: "/releasenotes/" }, { from: "/ReleaseNotes/Modeler/", to: "/releasenotes/desktop-modeler/" }, { from: "/ReleaseNotes/6.10.3", to: "/releasenotes/desktop-modeler/6.10" }, { from: "/ReleaseNotes/6.10.2", to: "/releasenotes/desktop-modeler/6.10" }, { from: "/ReleaseNotes/6.10.1", to: "/releasenotes/desktop-modeler/6.10" }, { from: "/ReleaseNotes/6.10.0", to: "/releasenotes/desktop-modeler/6.10" }, { from: "/ReleaseNotes/6.9.1", to: "/releasenotes/desktop-modeler/6.9" }, { from: "/ReleaseNotes/6.9.0", to: "/releasenotes/desktop-modeler/6.9" }, { from: "/ReleaseNotes/6.8.1", to: "/releasenotes/desktop-modeler/6.8" }, { from: "/ReleaseNotes/6.8.0", to: "/releasenotes/desktop-modeler/6.8" }, { from: "/ReleaseNotes/6.7.1", to: "/releasenotes/desktop-modeler/6.7" }, { from: "/ReleaseNotes/6.7.0", to: "/releasenotes/desktop-modeler/6.7" }, { from: "/ReleaseNotes/5.21.5", to: "/releasenotes/desktop-modeler/5.21" }, { from: "/ReleaseNotes/6.6.0", to: "/releasenotes/desktop-modeler/6.6" }, { from: "/ReleaseNotes/6.5.1", to: "/releasenotes/desktop-modeler/6.5" }, { from: "/ReleaseNotes/6.5.0", to: "/releasenotes/desktop-modeler/6.5" }, { from: "/ReleaseNotes/5.21.4", to: "/releasenotes/desktop-modeler/5.21" }, { from: "/ReleaseNotes/6.4.1", to: "/releasenotes/desktop-modeler/6.4" }, { from: "/ReleaseNotes/6.4.0", to: "/releasenotes/desktop-modeler/6.4" }, { from: "/ReleaseNotes/5.21.3", to: "/releasenotes/desktop-modeler/5.21" }, { from: "/ReleaseNotes/6.3.1", to: "/releasenotes/desktop-modeler/6.3" }, { from: "/ReleaseNotes/6.3.0", to: "/releasenotes/desktop-modeler/6.3" }, { from: "/ReleaseNotes/5.21.2", to: "/releasenotes/desktop-modeler/5.21" }, { from: "/ReleaseNotes/6.2.1", to: "/releasenotes/desktop-modeler/6.2" }, { from: "/ReleaseNotes/6.2.0", to: "/releasenotes/desktop-modeler/6.2" }, { from: "/ReleaseNotes/6.1.0", to: "/releasenotes/desktop-modeler/6.1" }, { from: "/ReleaseNotes/6.0.1", to: "/releasenotes/desktop-modeler/6.0" }, { from: "/ReleaseNotes/5.21.1", to: "/releasenotes/desktop-modeler/5.21" }, { from: "/ReleaseNotes/6.0.0", to: "/releasenotes/desktop-modeler/6.0" }, { from: "/ReleaseNotes/5.21.0", to: "/releasenotes/desktop-modeler/5.21" }, { from: "/ReleaseNotes/5.20.0", to: "/releasenotes/desktop-modeler/5.20" }, { from: "/ReleaseNotes/5.19.0", to: "/releasenotes/desktop-modeler/5.19" }, { from: "/ReleaseNotes/5.18.0", to: "/releasenotes/desktop-modeler/5.18" }, { from: "/ReleaseNotes/5.17.0", to: "/releasenotes/desktop-modeler/5.17" }, { from: "/ReleaseNotes/5.16.1", to: "/releasenotes/desktop-modeler/5.16" }, { from: "/ReleaseNotes/5.16.0", to: "/releasenotes/desktop-modeler/5.16" }, { from: "/ReleaseNotes/5.15.1", to: "/releasenotes/desktop-modeler/5.15" }, { from: "/ReleaseNotes/5.14.2", to: "/releasenotes/desktop-modeler/5.14" }, { from: "/ReleaseNotes/4.08.10", to: "/releasenotes/desktop-modeler/unsupported-versions/4.8" }, { from: "/ReleaseNotes/5.15.0", to: "/releasenotes/desktop-modeler/5.15" }, { from: "/ReleaseNotes/5.14.1", to: "/releasenotes/desktop-modeler/5.14" }, { from: "/ReleaseNotes/5.14.0", to: "/releasenotes/desktop-modeler/5.14" }, { from: "/ReleaseNotes/5.13.1", to: "/releasenotes/desktop-modeler/5.13" }, { from: "/ReleaseNotes/5.13.0", to: "/releasenotes/desktop-modeler/5.13" }, { from: "/ReleaseNotes/5.12.0", to: "/releasenotes/desktop-modeler/5.12" }, { from: "/ReleaseNotes/5.11.1", to: "/releasenotes/desktop-modeler/5.11" }, { from: "/ReleaseNotes/5.11.0", to: "/releasenotes/desktop-modeler/5.11" }, { from: "/ReleaseNotes/5.10.0", to: "/releasenotes/desktop-modeler/5.10" }, { from: "/ReleaseNotes/5.09.0", to: "/releasenotes/desktop-modeler/5.9" }, { from: "/ReleaseNotes/Platform+Portal", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+Notes+2016-10-05", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2016-05-12", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2016-03-24", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2016-02-18", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2016-01-13", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-12-01", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-11-30", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-10-16", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-09-17", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-09-03", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-08-06", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-07-31", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-07-24", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-07-16", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-07-03", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-06-16", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-06-02", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-05-29", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-04-21", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-04-16", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-03-31", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-02-26", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-02-19", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-02-05", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2015-01-22", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2014-12-30", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Release+notes+2014-12-23", to: "/releasenotes/developer-portal/" }, { from: "/ReleaseNotes/Model+SDK+3.0.1", to: "/releasenotes/model-sdk/3" }, { from: "/ReleaseNotes/Model+SDK+3.0.0", to: "/releasenotes/model-sdk/3" }, { from: "/ReleaseNotes/Model+SDK+2.9.1", to: "/releasenotes/model-sdk/2" }, { from: "/ReleaseNotes/Model+SDK+2.9.0", to: "/releasenotes/model-sdk/2" }, { from: "/ReleaseNotes/Model+SDK+2.8.1", to: "/releasenotes/model-sdk/2" }, { from: "/ReleaseNotes/Model+SDK+2.8.0", to: "/releasenotes/model-sdk/2" }, { from: "/ReleaseNotes/Model+SDK+2.7.0", to: "/releasenotes/model-sdk/2" }, { from: "/ReleaseNotes/Model+SDK+2.6.3", to: "/releasenotes/model-sdk/2" }, { from: "/ReleaseNotes/Model+SDK+2.6.0", to: "/releasenotes/model-sdk/2" }, { from: "/ReleaseNotes/Model+SDK+2.5.0", to: "/releasenotes/model-sdk/2" }, { from: "/ReleaseNotes/Model+SDK+2.4.0", to: "/releasenotes/model-sdk/2" }, { from: "/ReleaseNotes/Model+SDK+2.3.0", to: "/releasenotes/model-sdk/2" }, { from: "/ReleaseNotes/Model+SDK+2.2.2", to: "/releasenotes/model-sdk/2" }, { from: "/ReleaseNotes/Model+SDK+2.1.0", to: "/releasenotes/model-sdk/2" }, { from: "/ReleaseNotes/Platform+SDK+2.0.0", to: "/releasenotes/platform-sdk/2.0" }, { from: "/ReleaseNotes/Model+SDK+2.0.0", to: "/releasenotes/model-sdk/2" }, { from: "/ReleaseNotes/Model+SDK+1.2.0", to: "/releasenotes/model-sdk/1" }, { from: "/ReleaseNotes/Model+SDK+1.1.1", to: "/releasenotes/model-sdk/1" }, { from: "/ReleaseNotes/Model+SDK+1.1.0", to: "/releasenotes/model-sdk/1" }, { from: "/ReleaseNotes/Model+SDK+1.0.2", to: "/releasenotes/model-sdk/1" }, { from: "/ReleaseNotes/Platform+SDK+1.0.2", to: "/releasenotes/platform-sdk/1.0" }, { from: "/ReleaseNotes/Model+SDK+1.0.0", to: "/releasenotes/model-sdk/1" }, { from: "/ReleaseNotes/Application+Quality+Monitor", to: "/releasenotes/aqm/" }, { from: "/ReleaseNotes/Mendix+AQM+2.0+Release+Notes", to: "/releasenotes/aqm/2.0" }, { from: "/ReleaseNotes/Application+Performance+Monitor", to: "/releasenotes/apm/" }, { from: "/ReleaseNotes/Beta+features", to: "/releasenotes/beta-features/" }, { from: "/ReleaseNotes/Application+Test+Suite", to: "/releasenotes/ats/" }, { from: "/releasenotes/APM/1", to: "/releasenotes/apm/1" }, { from: "/releasenotes/ATS/1", to: "/releasenotes/ats/1" }, { from: "/releasenotes/APM/1.10", to: "/releasenotes/apm/1.10" }, { from: "/releasenotes/APM/1.11", to: "/releasenotes/apm/1.11" }, { from: "/releasenotes/APM/1.12", to: "/releasenotes/apm/1.12" }, { from: "/releasenotes/ATS/1.5", to: "/releasenotes/ats/1.5" }, { from: "/releasenotes/APM/1.6", to: "/releasenotes/apm/1.6" }, { from: "/releasenotes/ATS/1.6", to: "/releasenotes/ats/1.6" }, { from: "/releasenotes/APM/1.7", to: "/releasenotes/apm/1.7" }, { from: "/releasenotes/APM/1.8", to: "/releasenotes/apm/1.8" }, { from: "/releasenotes/ATS/1.8", to: "/releasenotes/ats/1.8" }, { from: "/releasenotes/APM/1.9", to: "/releasenotes/apm/1.9" }, { from: "/releasenotes/AQM/2", to: "/releasenotes/aqm/2" }, { from: "/releasenotes/AQM/2.0", to: "/releasenotes/aqm/2.0" }, { from: "/releasenotes/APM/", to: "/releasenotes/apm/" }, { from: "/releasenotes/AQM/", to: "/releasenotes/aqm/" }, { from: "/releasenotes/ATS/", to: "/releasenotes/ats/" } ] }
},
YieldValue.test.ts
import YieldValue from '../YieldValue'; import { expect } from 'chai';
const testYieldValue: YieldValue = new YieldValue(0); expect(testYieldValue.provider()).to.eql(''); }); it('should inherit values when instantiated using another `YieldValue`', (): void => { const testYieldValue: YieldValue = new YieldValue( new YieldValue(1, 'test-1') ); expect(testYieldValue.value()).to.equal(1); expect(testYieldValue.provider()).to.equal('test-1'); }); });
describe('YieldValue', (): void => { it('should default to a value of `0` and an empty provider', (): void => {
WinnerInfo.test.tsx
import React from "react";
import WinnerInfo from "./WinnerInfo.react"; import { create, ReactTestRenderer } from "react-test-renderer"; import Participant from "../../../store/round/match/participant/Participant"; import { createDummyParticipant, createDummyTranslationProps, } from "../../../util/test"; describe("WinnerInfo Component.", () => { it("Matches snapshot.", () => { const participant: Participant = createDummyParticipant(0); const component: ReactTestRenderer = create( <WinnerInfo className="foobar" winner={participant} {...createDummyTranslationProps()} />, ); expect(component.toJSON()).toMatchSnapshot(); }); });
puzzle1.py
def read_input():
mod = lambda i,j: ((i-1) % j) + 1 def main(): pos = read_input() s = [0,0] for i in range(1,1000,3): pos[(i-1)%2] += sum([mod(j,100) for j in range(i,i+3)]) pos[(i-1)%2] = mod(pos[(i-1)%2],10) s[(i-1)%2] += pos[(i-1)%2] if s[(i-1)%2] >= 1000: break print(f"Part 1 {min(s)*(i+2)}") if __name__ == "__main__": main()
with open("input.txt", "r") as file: return [int(p[28:]) for p in file.read().splitlines()]
components_breadcrumb_index.md.649dcfc0.lean.js
var x=Object.defineProperty;var _=Object.getOwnPropertySymbols;var y=Object.prototype.hasOwnProperty,I=Object.prototype.propertyIsEnumerable;var A=(s,e,a)=>e in s?x(s,e,{enumerable:!0,configurable:!0,writable:!0,value:a}):s[e]=a,h=(s,e)=>{for(var a in e||(e={}))y.call(e,a)&&A(s,a,e[a]);if(_)for(var a of _(e))I.call(e,a)&&A(s,a,e[a]);return s};import{_ as N,V as F,r as E,c as V,a as k,w as m,b as f,d as n,e as t,o as w}from"./app.e2d85a78.js";const L={name:"component-doc",components:{"render-demo-0":function(){const{createTextVNode:s,resolveComponent:e,withCtx:a,createVNode:u,createElementVNode:p,openBlock:r,createElementBlock:l}=F,o=s("Homepage"),c=p("a",{href:"/"},"DevUI",-1),i=p("span",null,"Breadcrumb",-1);function
(v,D){const b=e("d-breadcrumb-item"),d=e("d-breadcrumb");return r(),l("div",null,[u(d,null,{default:a(()=>[u(b,{to:"{ path: '/' }"},{default:a(()=>[o]),_:1}),u(b,null,{default:a(()=>[c]),_:1}),u(b,null,{default:a(()=>[i]),_:1})]),_:1})])}return h({render:g},{})}(),"render-demo-1":function(){const{resolveComponent:s,createVNode:e,openBlock:a,createElementBlock:u}=F;function p(c,i){const g=s("d-breadcrumb");return a(),u("div",null,[e(g,{source:c.source},null,8,["source"])])}const{defineComponent:r,reactive:l}=F,o=r({name:"DBreadcrumbDemoSourceConfig",setup(){return{source:l([{title:"DevUI",link:"/",linkType:"routerLink",replace:!0},{title:"Breadcrumb",link:"components/breadcrumb/",noNavigation:!0}])}}});return h({render:p},o)}(),"render-demo-2":function(){const{createElementVNode:s,resolveComponent:e,withCtx:a,createVNode:u,openBlock:p,createElementBlock:r}=F,l=s("a",{routerLink:"/components/zh-cn/get-start"},"DevUI",-1),o=s("span",null,"Breadcrumb",-1),c=s("span",{style:{color:"red"}},">",-1),i=s("a",{routerLink:"/components/zh-cn/get-start"},"DevUI",-1),g=s("span",null,"Breadcrumb",-1);function C(D,b){const d=e("d-breadcrumb-item"),B=e("d-breadcrumb");return p(),r("div",null,[s("div",null,[u(B,{separatorIcon:">"},{default:a(()=>[u(d,null,{default:a(()=>[l]),_:1}),u(d,null,{default:a(()=>[o]),_:1})]),_:1})]),s("div",null,[u(B,null,{separatorIcon:a(()=>[c]),default:a(()=>[u(d,null,{default:a(()=>[i]),_:1}),u(d,null,{default:a(()=>[g]),_:1})]),_:1})])])}return h({render:C},{})}()}},J='{"title":"Breadcrumb \u9762\u5305\u5C51","description":"","frontmatter":{},"headers":[{"level":3,"title":"\u4F55\u65F6\u4F7F\u7528","slug":"\u4F55\u65F6\u4F7F\u7528"},{"level":3,"title":"\u57FA\u7840\u9762\u5305\u5C51","slug":"\u57FA\u7840\u9762\u5305\u5C51"},{"level":3,"title":"\u4F20\u5165source","slug":"\u4F20\u5165source"},{"level":3,"title":"\u53EF\u4E0B\u62C9\u7684\u9762\u5305\u5C51\u3010TODO\u3011","slug":"\u53EF\u4E0B\u62C9\u7684\u9762\u5305\u5C51\u3010todo\u3011"},{"level":3,"title":"\u81EA\u5B9A\u4E49\u5206\u9694\u7B26\u7684\u9762\u5305\u5C51","slug":"\u81EA\u5B9A\u4E49\u5206\u9694\u7B26\u7684\u9762\u5305\u5C51"},{"level":3,"title":"API","slug":"api"},{"level":3,"title":"d-breadcrumb \u53C2\u6570","slug":"d-breadcrumb-\u53C2\u6570"},{"level":3,"title":"d-breadcrumb-item \u53C2\u6570","slug":"d-breadcrumb-item-\u53C2\u6570"},{"level":3,"title":"\u63A5\u53E3 & \u7C7B\u578B\u5B9A\u4E49","slug":"\u63A5\u53E3-\u7C7B\u578B\u5B9A\u4E49"},{"level":3,"title":"SourceConfig","slug":"sourceconfig"}],"relativePath":"components/breadcrumb/index.md","lastUpdated":1639287489613}',U=f('<h1 id="breadcrumb-\u9762\u5305\u5C51" tabindex="-1">Breadcrumb \u9762\u5305\u5C51 <a class="header-anchor" href="#breadcrumb-\u9762\u5305\u5C51" aria-hidden="true">#</a></h1><p>\u663E\u793A\u5F53\u524D\u9875\u9762\u5C42\u7EA7\u7684\u7EC4\u4EF6\u3002</p><h3 id="\u4F55\u65F6\u4F7F\u7528" tabindex="-1">\u4F55\u65F6\u4F7F\u7528 <a class="header-anchor" href="#\u4F55\u65F6\u4F7F\u7528" aria-hidden="true">#</a></h3><ol><li>\u7528\u6237\u9700\u8981\u4E86\u89E3\u5F53\u524D\u51FA\u4E8E\u4EC0\u4E48\u5C42\u7EA7\u65F6\uFF1B</li><li>\u7528\u6237\u9700\u8981\u5FEB\u901F\u8FD4\u56DE\u4E4B\u524D\u7684\u5C42\u7EA7\u65F6\uFF1B</li><li>\u7528\u6237\u9700\u8981\u5BFC\u822A\u81F3\u4E0E\u6307\u5B9A\u5C42\u7EA7\u76F8\u540C\u7684\u4EFB\u610F\u9875\u9762\u65F6\u3002</li></ol><h3 id="\u57FA\u7840\u9762\u5305\u5C51" tabindex="-1">\u57FA\u7840\u9762\u5305\u5C51 <a class="header-anchor" href="#\u57FA\u7840\u9762\u5305\u5C51" aria-hidden="true">#</a></h3>',5),S=n("div",{class:"language-vue"},[n("pre",null,[n("code",null,[n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("template")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("d-breadcrumb")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("d-breadcrumb-item")]),t(),n("span",{class:"token attr-name"},"to"),n("span",{class:"token attr-value"},[n("span",{class:"token punctuation attr-equals"},"="),n("span",{class:"token punctuation"},'"'),t("{ path: "),n("span",{class:"token punctuation"},"'"),t("/"),n("span",{class:"token punctuation"},"'"),t(" }"),n("span",{class:"token punctuation"},'"')]),n("span",{class:"token punctuation"},">")]),t("Homepage"),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("d-breadcrumb-item")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("d-breadcrumb-item")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("a")]),t(),n("span",{class:"token attr-name"},"href"),n("span",{class:"token attr-value"},[n("span",{class:"token punctuation attr-equals"},"="),n("span",{class:"token punctuation"},'"'),t("/"),n("span",{class:"token punctuation"},'"')]),n("span",{class:"token punctuation"},">")]),t("DevUI"),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("a")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("d-breadcrumb-item")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("d-breadcrumb-item")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("span")]),n("span",{class:"token punctuation"},">")]),t("Breadcrumb"),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("span")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("d-breadcrumb-item")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("d-breadcrumb")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("template")]),n("span",{class:"token punctuation"},">")]),t(` `)])])],-1),T=n("h3",{id:"\u4F20\u5165source",tabindex:"-1"},[t("\u4F20\u5165source "),n("a",{class:"header-anchor",href:"#\u4F20\u5165source","aria-hidden":"true"},"#")],-1),q=n("div",{class:"language-vue"},[n("pre",null,[n("code",null,[n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("template")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("d-breadcrumb")]),t(),n("span",{class:"token attr-name"},":source"),n("span",{class:"token attr-value"},[n("span",{class:"token punctuation attr-equals"},"="),n("span",{class:"token punctuation"},'"'),t("source"),n("span",{class:"token punctuation"},'"')]),n("span",{class:"token punctuation"},">")]),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("d-breadcrumb")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("template")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("script")]),n("span",{class:"token punctuation"},">")]),n("span",{class:"token script"},[n("span",{class:"token language-javascript"},[t(` `),n("span",{class:"token keyword"},"import"),t(),n("span",{class:"token punctuation"},"{"),t(" defineComponent"),n("span",{class:"token punctuation"},","),t(" reactive "),n("span",{class:"token punctuation"},"}"),t(),n("span",{class:"token keyword"},"from"),t(),n("span",{class:"token string"},"'vue'"),t(` `),n("span",{class:"token keyword"},"export"),t(),n("span",{class:"token keyword"},"default"),t(),n("span",{class:"token function"},"defineComponent"),n("span",{class:"token punctuation"},"("),n("span",{class:"token punctuation"},"{"),t(` name`),n("span",{class:"token operator"},":"),t(),n("span",{class:"token string"},'"DBreadcrumbDemoSourceConfig"'),n("span",{class:"token punctuation"},","),t(` `),n("span",{class:"token function"},"setup"),n("span",{class:"token punctuation"},"("),n("span",{class:"token punctuation"},")"),t(),n("span",{class:"token punctuation"},"{"),t(` `),n("span",{class:"token keyword"},"const"),t(" source "),n("span",{class:"token operator"},"="),t(),n("span",{class:"token function"},"reactive"),n("span",{class:"token punctuation"},"("),n("span",{class:"token punctuation"},"["),t(` `),n("span",{class:"token punctuation"},"{"),t(" title"),n("span",{class:"token operator"},":"),t(),n("span",{class:"token string"},"'DevUI'"),n("span",{class:"token punctuation"},","),t(" link"),n("span",{class:"token operator"},":"),t(),n("span",{class:"token string"},"'/'"),n("span",{class:"token punctuation"},","),t(" linkType"),n("span",{class:"token operator"},":"),t(),n("span",{class:"token string"},"'routerLink'"),n("span",{class:"token punctuation"},","),t(" replace"),n("span",{class:"token operator"},":"),t(),n("span",{class:"token boolean"},"true"),t(),n("span",{class:"token punctuation"},"}"),n("span",{class:"token punctuation"},","),t(` `),n("span",{class:"token punctuation"},"{"),t(" title"),n("span",{class:"token operator"},":"),t(),n("span",{class:"token string"},"'Breadcrumb'"),n("span",{class:"token punctuation"},","),t(" link"),n("span",{class:"token operator"},":"),t(),n("span",{class:"token string"},"'components/breadcrumb/'"),n("span",{class:"token punctuation"},","),t(" noNavigation"),n("span",{class:"token operator"},":"),t(),n("span",{class:"token boolean"},"true"),t(),n("span",{class:"token punctuation"},"}"),t(` `),n("span",{class:"token punctuation"},"]"),n("span",{class:"token punctuation"},")"),t(` `),n("span",{class:"token keyword"},"return"),t(),n("span",{class:"token punctuation"},"{"),t(` source`),n("span",{class:"token punctuation"},","),t(` `),n("span",{class:"token punctuation"},"}"),t(` `),n("span",{class:"token punctuation"},"}"),n("span",{class:"token punctuation"},","),t(` `),n("span",{class:"token punctuation"},"}"),n("span",{class:"token punctuation"},")"),t(` `)])]),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("script")]),n("span",{class:"token punctuation"},">")]),t(` `)])])],-1),z=n("h3",{id:"\u53EF\u4E0B\u62C9\u7684\u9762\u5305\u5C51\u3010todo\u3011",tabindex:"-1"},[t("\u53EF\u4E0B\u62C9\u7684\u9762\u5305\u5C51\u3010TODO\u3011 "),n("a",{class:"header-anchor",href:"#\u53EF\u4E0B\u62C9\u7684\u9762\u5305\u5C51\u3010todo\u3011","aria-hidden":"true"},"#")],-1),O=n("h3",{id:"\u81EA\u5B9A\u4E49\u5206\u9694\u7B26\u7684\u9762\u5305\u5C51",tabindex:"-1"},[t("\u81EA\u5B9A\u4E49\u5206\u9694\u7B26\u7684\u9762\u5305\u5C51 "),n("a",{class:"header-anchor",href:"#\u81EA\u5B9A\u4E49\u5206\u9694\u7B26\u7684\u9762\u5305\u5C51","aria-hidden":"true"},"#")],-1),$=n("div",{class:"language-vue"},[n("pre",null,[n("code",null,[n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("template")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("div")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("d-breadcrumb")]),t(),n("span",{class:"token attr-name"},"separatorIcon"),n("span",{class:"token attr-value"},[n("span",{class:"token punctuation attr-equals"},"="),n("span",{class:"token punctuation"},'"'),t(">"),n("span",{class:"token punctuation"},'"')]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("d-breadcrumb-item")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("a")]),t(),n("span",{class:"token attr-name"},"routerLink"),n("span",{class:"token attr-value"},[n("span",{class:"token punctuation attr-equals"},"="),n("span",{class:"token punctuation"},'"'),t("/components/zh-cn/get-start"),n("span",{class:"token punctuation"},'"')]),n("span",{class:"token punctuation"},">")]),t("DevUI"),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("a")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("d-breadcrumb-item")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("d-breadcrumb-item")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("span")]),n("span",{class:"token punctuation"},">")]),t("Breadcrumb"),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("span")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("d-breadcrumb-item")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("d-breadcrumb")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("div")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("div")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("d-breadcrumb")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("template")]),t(),n("span",{class:"token attr-name"},[n("span",{class:"token namespace"},"v-slot:"),t("separatorIcon")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("span")]),t(),n("span",{class:"token special-attr"},[n("span",{class:"token attr-name"},"style"),n("span",{class:"token attr-value"},[n("span",{class:"token punctuation attr-equals"},"="),n("span",{class:"token punctuation"},'"'),n("span",{class:"token value css language-css"},[n("span",{class:"token property"},"color"),n("span",{class:"token punctuation"},":"),t(" red")]),n("span",{class:"token punctuation"},'"')])]),n("span",{class:"token punctuation"},">")]),t(">"),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("span")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("template")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("d-breadcrumb-item")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("a")]),t(),n("span",{class:"token attr-name"},"routerLink"),n("span",{class:"token attr-value"},[n("span",{class:"token punctuation attr-equals"},"="),n("span",{class:"token punctuation"},'"'),t("/components/zh-cn/get-start"),n("span",{class:"token punctuation"},'"')]),n("span",{class:"token punctuation"},">")]),t("DevUI"),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("a")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("d-breadcrumb-item")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("d-breadcrumb-item")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"<"),t("span")]),n("span",{class:"token punctuation"},">")]),t("Breadcrumb"),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("span")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("d-breadcrumb-item")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("d-breadcrumb")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("div")]),n("span",{class:"token punctuation"},">")]),t(` `),n("span",{class:"token tag"},[n("span",{class:"token tag"},[n("span",{class:"token punctuation"},"</"),t("template")]),n("span",{class:"token punctuation"},">")]),t(` `)])])],-1),j=f(`<h3 id="api" tabindex="-1">API <a class="header-anchor" href="#api" aria-hidden="true">#</a></h3><h3 id="d-breadcrumb-\u53C2\u6570" tabindex="-1">d-breadcrumb \u53C2\u6570 <a class="header-anchor" href="#d-breadcrumb-\u53C2\u6570" aria-hidden="true">#</a></h3><table><thead><tr><th style="text-align:center;">\u53C2\u6570</th><th style="text-align:center;">\u7C7B\u578B</th><th style="text-align:center;">\u9ED8\u8BA4</th><th style="text-align:left;">\u8BF4\u660E</th><th>\u8DF3\u8F6C Demo</th></tr></thead><tbody><tr><td style="text-align:center;">separatorIcon</td><td style="text-align:center;"><a href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%88%86%E9%9A%94%E7%AC%A6%E7%9A%84%E9%9D%A2%E5%8C%85%E5%B1%91"><code>string</code></a></td><td style="text-align:center;">&#39;/&#39;</td><td style="text-align:left;">\u53EF\u9009\uFF0C\u81EA\u5B9A\u4E49\u5206\u9694\u7B26\u6837\u5F0F</td><td><a href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%88%86%E9%9A%94%E7%AC%A6%E7%9A%84%E9%9D%A2%E5%8C%85%E5%B1%91">\u81EA\u5B9A\u4E49\u5206\u9694\u7B26\u7684\u9762\u5305\u5C51</a></td></tr><tr><td style="text-align:center;">source</td><td style="text-align:center;"><a href="#SourceConfig"><code>Array&lt;SourceConfig&gt;</code></a></td><td style="text-align:center;">[]</td><td style="text-align:left;">\u53EF\u9009\uFF0C\u9762\u5305\u5C51\u6839\u636E\u914D\u7F6E\u7684 source \u6309\u7167\u9ED8\u8BA4\u6E32\u67D3\u65B9\u5F0F\u663E\u793A</td><td><a href="#%E4%BC%A0%E5%85%A5source">\u4F20\u5165source</a></td></tr></tbody></table><h3 id="d-breadcrumb-item-\u53C2\u6570" tabindex="-1">d-breadcrumb-item \u53C2\u6570 <a class="header-anchor" href="#d-breadcrumb-item-\u53C2\u6570" aria-hidden="true">#</a></h3><table><thead><tr><th style="text-align:center;">\u53C2\u6570</th><th style="text-align:center;">\u7C7B\u578B</th><th style="text-align:center;">\u9ED8\u8BA4</th><th style="text-align:center;">\u8BF4\u660E</th><th style="text-align:left;">\u8DF3\u8F6C Demo</th></tr></thead><tbody><tr><td style="text-align:center;">to</td><td style="text-align:center;"><code>string/object</code></td><td style="text-align:center;">\u2014</td><td style="text-align:center;">\u8DEF\u7531\u8DF3\u8F6C\u5BF9\u8C61\uFF0C\u540C vue-router \u7684 to</td><td style="text-align:left;"><a href="#%E5%9F%BA%E7%A1%80%E9%9D%A2%E5%8C%85%E5%B1%91">\u57FA\u7840\u9762\u5305\u5C51</a></td></tr><tr><td style="text-align:center;">replace</td><td style="text-align:center;"><code>boolean</code></td><td style="text-align:center;">false</td><td style="text-align:center;">\u5728\u4F7F\u7528 to \u8FDB\u884C\u8DEF\u7531\u8DF3\u8F6C\u65F6\uFF0C\u542F\u7528 replace \u5C06\u4E0D\u4F1A\u5411 history \u6DFB\u52A0\u65B0\u8BB0\u5F55</td><td style="text-align:left;"><a href="#%E5%9F%BA%E7%A1%80%E9%9D%A2%E5%8C%85%E5%B1%91">\u57FA\u7840\u9762\u5305\u5C51</a></td></tr></tbody></table><h3 id="\u63A5\u53E3-\u7C7B\u578B\u5B9A\u4E49" tabindex="-1">\u63A5\u53E3 &amp; \u7C7B\u578B\u5B9A\u4E49 <a class="header-anchor" href="#\u63A5\u53E3-\u7C7B\u578B\u5B9A\u4E49" aria-hidden="true">#</a></h3><h3 id="sourceconfig" tabindex="-1">SourceConfig <a class="header-anchor" href="#sourceconfig" aria-hidden="true">#</a></h3><div class="language-ts"><pre><code><span class="token keyword">export</span> <span class="token keyword">interface</span> <span class="token class-name">SourceConfig</span> <span class="token punctuation">{</span> title<span class="token operator">:</span> <span class="token builtin">string</span><span class="token punctuation">;</span> <span class="token comment">// \u663E\u793A\u7684\u540D\u79F0</span> link<span class="token operator">?</span><span class="token operator">:</span> <span class="token builtin">string</span><span class="token punctuation">;</span> <span class="token comment">// \u8DF3\u8F6C\u7684\u8DEF\u5F84</span> target<span class="token operator">?</span><span class="token operator">:</span> <span class="token builtin">string</span> <span class="token comment">// \u89C4\u5B9A\u5728\u4F55\u5904\u6253\u5F00\u94FE\u63A5\u6587\u6863</span> noNavigation<span class="token operator">?</span><span class="token operator">:</span> <span class="token builtin">boolean</span><span class="token punctuation">;</span> <span class="token comment">// \u94FE\u63A5\u662F\u5426\u4E0D\u53EF\u8DF3\u8F6C\uFF0C\u4E00\u822C\u7528\u4E8E\u5F53\u524D\u6240\u5904\u4F4D\u7F6E\u4E0D\u53EF\u8DF3\u8F6C\u7684\u914D\u7F6E</span> linkType<span class="token operator">?</span><span class="token operator">:</span> <span class="token string">&#39;hrefLink&#39;</span> <span class="token operator">|</span> <span class="token string">&#39;routerLink&#39;</span><span class="token punctuation">;</span> <span class="token comment">// \u94FE\u63A5\u7C7B\u578B\uFF0C\u9ED8\u8BA4\u4E3A&#39;hrefLink&#39;\u65B9\u5F0F\uFF0C\u53EF\u9009&#39;hrefLink&#39; \u6216 &#39;routerLink&#39;</span> replace<span class="token operator">:</span> Boolean <span class="token comment">// \u5728\u4F7F\u7528 to \u8FDB\u884C\u8DEF\u7531\u8DF3\u8F6C\u65F6\uFF0C\u542F\u7528 replace \u5C06\u4E0D\u4F1A\u5411 history \u6DFB\u52A0\u65B0\u8BB0\u5F55</span> <span class="token punctuation">}</span> </code></pre></div>`,8);function H(s,e,a,u,p,r){const l=E("render-demo-0"),o=E("demo"),c=E("render-demo-1"),i=E("render-demo-2");return w(),V("div",null,[U,k(o,{sourceCode:`<template> <d-breadcrumb> <d-breadcrumb-item to="{ path: '/' }">Homepage</d-breadcrumb-item> <d-breadcrumb-item> <a href="/">DevUI</a> </d-breadcrumb-item> <d-breadcrumb-item> <span>Breadcrumb</span> </d-breadcrumb-item> </d-breadcrumb> </template> `},{highlight:m(()=>[S]),default:m(()=>[k(l)]),_:1}),T,k(o,{sourceCode:`<template> <d-breadcrumb :source="source"></d-breadcrumb> </template> <script> import { defineComponent, reactive } from 'vue' export default defineComponent({ name: "DBreadcrumbDemoSourceConfig", setup() { const source = reactive([ { title: 'DevUI', link: '/', linkType: 'routerLink', replace: true }, { title: 'Breadcrumb', link: 'components/breadcrumb/', noNavigation: true } ]) return { source, } }, }) <\/script> `},{highlight:m(()=>[q]),default:m(()=>[k(c)]),_:1}),z,O,k(o,{sourceCode:`<template> <div> <d-breadcrumb separatorIcon=">"> <d-breadcrumb-item> <a routerLink="/components/zh-cn/get-start">DevUI</a> </d-breadcrumb-item> <d-breadcrumb-item> <span>Breadcrumb</span> </d-breadcrumb-item> </d-breadcrumb> </div> <div> <d-breadcrumb> <template v-slot:separatorIcon> <span style="color: red">></span> </template> <d-breadcrumb-item> <a routerLink="/components/zh-cn/get-start">DevUI</a> </d-breadcrumb-item> <d-breadcrumb-item> <span>Breadcrumb</span> </d-breadcrumb-item> </d-breadcrumb> </div> </template> `},{highlight:m(()=>[$]),default:m(()=>[k(i)]),_:1}),j])}var K=N(L,[["render",H]]);export{J as __pageData,K as default};
g
trainer_lib_test.py
# coding=utf-8 # Copyright 2021 The Trax 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. """Tests for trax.supervised.trainer_lib.""" import functools import os from absl.testing import absltest from absl.testing import parameterized from jax import test_util # pylint: disable=unused-import from jax.config import config from jax.lib import xla_bridge import tensorflow.compat.v2 as tf from trax import fastmath from trax import layers as tl from trax import models from trax import optimizers as trax_opt from trax import shapes as trax_shapes from trax import test_utils from trax.data import inputs as inputs_lib from trax.fastmath import numpy as jnp from trax.supervised import lr_schedules as lr from trax.supervised import trainer_lib from trax.tf_numpy import extensions as npe from trax.tf_numpy import numpy as tf_np def _test_inputs(n_classes, with_weights=False, input_shape=(6, 6, 3)): """Make trainer_lib.inputs.Inputs.""" batch_size = 2 * xla_bridge.device_count() def input_stream(n_devices): del n_devices key = fastmath.random.get_prng(0) while True: keys = fastmath.random.split(key, 4) key = keys[0] inputs = fastmath.random.uniform( keys[1], [batch_size] + list(input_shape)) targets = fastmath.random.randint( keys[2], [batch_size], dtype=jnp.int32, minval=0, maxval=n_classes) weights = fastmath.random.uniform(keys[3], [batch_size]) if with_weights: yield inputs, targets, weights else: yield inputs, targets def input_stream_masked(n_devices): return inputs_lib.add_loss_weights(input_stream(n_devices)) return inputs_lib.Inputs(input_stream_masked) def _test_inputs_lm(vocab_size, seq_len, per_device_batch_size=2): """Make trainer_lib.inputs.Inputs for language model.""" batch_size = per_device_batch_size * xla_bridge.device_count() def input_stream(_): def make_batch(key): return fastmath.random.randint( key, [batch_size, seq_len], dtype=jnp.int32, minval=0, maxval=vocab_size) key = fastmath.random.get_prng(0) while True: keys = fastmath.random.split(key, 3) key = keys[0] inputs = make_batch(keys[1]) targets = make_batch(keys[2]) yield inputs, targets def input_stream_masked(n_devices): return inputs_lib.add_loss_weights(input_stream(n_devices)) return inputs_lib.Inputs(input_stream_masked) BACKENDS = [fastmath.Backend.JAX, fastmath.Backend.TFNP] def short_name(b): if b == fastmath.Backend.JAX: return 'jax' else: return 'tf' def opt_name(opt): if opt is None: return 'None' return opt.__name__ def _pure_lsh_self_attention_fn(n_chunks_after=0): return functools.partial( tl.PureLSHSelfAttentionWrapper, attention_dropout=0.1, chunk_len=16, n_buckets=[32, 32], n_chunks_after=n_chunks_after, n_chunks_before=1, n_hashes=2, n_parallel_heads=1, max_length_for_buckets=1024, predict_drop_len=128, predict_mem_len=1024, num_weights=2, bias=False, pure_lsh_implementation=tl.PureLSHSelfAttention, ) def _mixed_lsh_self_attention_fn(n_chunks_after=0): return functools.partial( tl.PureLSHSelfAttentionWrapper, attention_dropout=0.1, chunk_len=16, n_buckets=[32, 32], n_chunks_after=n_chunks_after, n_chunks_before=1, n_hashes=2, n_parallel_heads=1, max_length_for_buckets=1024, predict_drop_len=128, predict_mem_len=1024, num_weights=2, bias=False, pure_lsh_implementation=tl.MixedLSHSelfAttention, ) class TraxTest(parameterized.TestCase): def __init__(self, methodName='runTest'): # pylint: disable=invalid-name super().__init__(methodName) if npe.tpu_devices(): # Initialize TPU for TF resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='local') tf.tpu.experimental.initialize_tpu_system(resolver) def setUp(self): super().setUp() test_utils.ensure_flag('test_tmpdir') self._old_is_allow_float64 = tf_np.is_allow_float64() tf_np.set_allow_float64(False) def tearDown(self): tf_np.set_allow_float64(self._old_is_allow_float64) super().tearDown() def _test_train_eval_predict(self, backend, model_name='Simple', optimizer=None): with fastmath.use_backend(backend): # Prepare model and inputs steps = 2 eval_steps = 2 if model_name == 'Simple': n_classes = 4 # Adds Dropout and BatchNorm to test state handling. def model_fn(mode='train'): return tl.Serial( tl.Dropout(mode=mode, rate=0.1), tl.BatchNorm(mode=mode), models.MLP(layer_widths=(16, 16, n_classes), mode=mode)) inputs = _test_inputs(n_classes) n_in = 1 elif model_name == 'Resnet50': n_classes = 4 model_fn = models.Resnet50 inputs = _test_inputs(n_classes, input_shape=(224, 224, 3)) n_in = 1 elif model_name == 'Transformer': vocab_size = 32 seq_len = 16 inputs = _test_inputs_lm(vocab_size, seq_len) model_fn = functools.partial( models.Transformer, input_vocab_size=vocab_size) n_in = 2 else: raise ValueError('Unrecognized model name: ' + model_name) kwargs = {} if optimizer is not None: kwargs['optimizer'] = optimizer # Train and evaluate output_dir = self.create_tempdir().full_path loop = trainer_lib.train( output_dir, model=model_fn, inputs=inputs, steps=steps, eval_steps=eval_steps, eval_frequency=1, # eval at every step. **kwargs) # Assert total train steps self.assertEqual(steps, loop.step) inputs = inputs.train_stream(1) # Predict with final weights model = model_fn() weights = loop.model.weights state = loop.model.state model(next(inputs)[:n_in], weights=weights, state=state) # Predict with weights loaded from file. model = model_fn() model.init_from_file(os.path.join(output_dir, 'model.pkl.gz')) model(next(inputs)[:n_in]) @parameterized.named_parameters( ('_%s_%s_%s' % (short_name(backend), model_name, opt_name(opt)), # pylint: disable=g-complex-comprehension backend, model_name, opt) for backend, configs in [ (fastmath.Backend.JAX, [('Simple', None)]), (fastmath.Backend.TFNP, [('Simple', None), ('Resnet50', trax_opt.Momentum), ('Transformer', trax_opt.Adam)])] for model_name, opt in configs) def test_train_eval_predict(self, backend, model_name, opt): self._test_train_eval_predict(backend, model_name, opt) @parameterized.parameters(BACKENDS) def test_train_eval_predict_sm3(self, backend): self._test_train_eval_predict(backend, 'Simple', trax_opt.SM3) @parameterized.parameters(BACKENDS) def test_train_restart(self, backend): with fastmath.use_backend(backend): # Prepare model and inputs n_classes = 4 steps = 2 eval_steps = 2 model_fn = functools.partial(models.MLP, layer_widths=(16, 16, n_classes)) inputs = _test_inputs(n_classes) # Train and evaluate output_dir = self.create_tempdir().full_path trainer_lib.train( output_dir, model=model_fn, inputs=inputs, steps=steps, eval_steps=eval_steps, eval_frequency=1) # Restart training loop = trainer_lib.train( output_dir, model=model_fn, inputs=inputs, steps=(2 * steps), eval_steps=eval_steps, eval_frequency=1) # Assert total train steps self.assertEqual(loop.step, 2 * steps) @parameterized.parameters(BACKENDS) def test_train_permanent_checkpoints(self, backend): with fastmath.use_backend(backend): # Prepare model and inputs n_classes = 4 steps = 5 eval_steps = 2 model_fn = functools.partial(models.MLP, layer_widths=(16, 16, n_classes)) inputs = _test_inputs(n_classes) # Train and evaluate output_dir = self.create_tempdir().full_path # Steps 1 -> 5 loop = trainer_lib.train( output_dir, model=model_fn, inputs=inputs, steps=steps, eval_steps=eval_steps, eval_frequency=1, permanent_checkpoint_frequency=2) # Steps 6 -> 10 loop = trainer_lib.train( output_dir, model=model_fn, inputs=inputs, steps=(2 * steps), eval_steps=eval_steps, eval_frequency=1, permanent_checkpoints_at=[7, 8, 10]) path = os.path.join(output_dir, 'model.pkl.gz') self.assertTrue(tf.io.gfile.exists(path)) for step in range(11): filename = 'model_{}.pkl.gz'.format(step) path = os.path.join(output_dir, filename) if step in [1, 2, 4, 7, 8, 10]: self.assertTrue(tf.io.gfile.exists(path), msg='No model for step: {} in dir {}.'.format( step, tf.io.gfile.listdir(output_dir))) else: self.assertFalse(tf.io.gfile.exists(path), msg='Model for step: {} in dir {}.'.format( step, tf.io.gfile.listdir(output_dir))) # Assert total train steps self.assertEqual(loop.step, 10) @parameterized.parameters(BACKENDS) def test_train_restart_with_same_steps(self, backend): with fastmath.use_backend(backend): # Prepare model and inputs n_classes = 4 steps = 2 eval_steps = 2 model_fn = functools.partial(models.MLP, layer_widths=(16, 16, n_classes)) inputs = _test_inputs(n_classes) # Train and evaluate output_dir = self.create_tempdir().full_path trainer_lib.train( output_dir, model=model_fn, inputs=inputs, steps=steps, eval_steps=eval_steps, eval_frequency=1) # Restart training loop = trainer_lib.train( output_dir, model=model_fn, inputs=inputs, steps=steps, eval_steps=eval_steps, eval_frequency=1) # Assert total train steps self.assertEqual(loop.step, steps) def test_train_with_pure_lsh_attention(self, backend=fastmath.Backend.JAX):
def test_train_with_mixed_lsh_attention(self, backend=fastmath.Backend.JAX): with fastmath.use_backend(backend): # Prepare model and inputs def model(mode='train'): return models.Reformer2( mode=mode, d_model=16, d_ff=16, n_heads=2, dropout=0.05, n_decoder_layers=1, n_encoder_layers=1, input_vocab_size=256, encoder_attention_type=_mixed_lsh_self_attention_fn(), encoder_decoder_attention_type=_mixed_lsh_self_attention_fn(), ) max_len = 128 inputs = _test_inputs_lm(vocab_size=256, seq_len=max_len) steps = 1 eval_steps = 1 # Train and evaluate output_dir = self.create_tempdir().full_path trainer_lib.train( output_dir, model=model, inputs=inputs, steps=steps, eval_steps=eval_steps, eval_frequency=1) # Read checkpoint model_file = os.path.join(output_dir, 'model.pkl.gz') shape11 = trax_shapes.ShapeDtype((1, 1), dtype=jnp.int32) shape1l = trax_shapes.ShapeDtype((1, max_len), dtype=jnp.int32) model_predict = model(mode='predict') model_predict.init_from_file(model_file, weights_only=True, input_signature=(shape1l, shape11)) @parameterized.parameters(BACKENDS) def test_train_fills_in_missing_eval_metrics(self, backend): with fastmath.use_backend(backend): # Prepare model and inputs n_classes = 4 steps = 2 eval_steps = 2 model_fn = functools.partial(models.MLP, layer_widths=(16, 16, n_classes)) inputs = _test_inputs(n_classes) additional_eval_stream = trainer_lib.NamedStream( # deliberately duplicating eval data stream=inputs.eval_stream(1), name='additional_eval_task') # Train and evaluate output_dir = self.create_tempdir().full_path loop = trainer_lib.train( output_dir, model=model_fn, inputs=inputs, steps=steps, eval_steps=eval_steps, eval_frequency=1, additional_eval_streams=[additional_eval_stream]) self.assertLen(loop.eval_tasks, 2) eval_task_1, eval_task_2 = loop.eval_tasks self.assertCountEqual(eval_task_1.metrics, eval_task_2.metrics) self.assertCountEqual(eval_task_1.metric_names, eval_task_2.metric_names) @parameterized.named_parameters( ('_%s' % short_name(backend), backend) for backend in BACKENDS) def test_train_with_weights(self, backend): with fastmath.use_backend(backend): # Prepare model and inputs n_classes = 4 steps = 2 eval_steps = 2 model_fn = functools.partial(models.MLP, layer_widths=(16, 16, n_classes)) inputs = _test_inputs(n_classes, with_weights=True) # Train and evaluate output_dir = self.create_tempdir().full_path state = trainer_lib.train( output_dir, model=model_fn, inputs=inputs, steps=steps, eval_steps=eval_steps) # Assert total train steps self.assertEqual(state.step, steps) @parameterized.parameters(BACKENDS) def test_reset_twice(self, backend): with fastmath.use_backend(backend): n_classes = 4 model_fn = functools.partial(models.MLP, layer_widths=(16, 16, n_classes)) inputs = _test_inputs(n_classes) trainer = trainer_lib.Trainer( model=model_fn, loss_fn=tl.WeightedCategoryCrossEntropy(), optimizer=trax_opt.SM3, lr_schedule=lr.multifactor(), inputs=inputs, ) output_dir1 = self.create_tempdir(name='output_dir1').full_path trainer.reset(output_dir1) trainer.evaluate(1) output_dir2 = self.create_tempdir(name='output_dir2').full_path trainer.reset(output_dir2) trainer.evaluate(1) def test_tf_xla_forced_compile(self): # TODO(wangpeng): re-enable this test self.skipTest('Needs --config=cuda to pass this test') old_flag = fastmath.tf.tf_xla_forced_compile_enabled() fastmath.tf.set_tf_xla_forced_compile(True) self._test_train_eval_predict('tf') fastmath.tf.set_tf_xla_forced_compile(old_flag) def test_no_int32_or_uint32_returned(self): """Tests that Trainer._jit_update_fn doesn't return int32 or uint32. TF pins int32/uint32 tensors to CPU, which will cause XLA-forced-compiled computation to copy int32/uint32 outputs to CPU. This test makes sure that won't happen. """ with fastmath.use_backend(fastmath.Backend.TFNP): n_classes = 1001 model_fn = functools.partial(models.Resnet50, n_output_classes=n_classes) inputs = _test_inputs(n_classes, input_shape=(224, 224, 3)) trainer = trainer_lib.Trainer( model=model_fn, loss_fn=tl.WeightedCategoryCrossEntropy(), optimizer=trax_opt.SM3, lr_schedule=lr.multifactor(), inputs=inputs, ) output_dir = self.create_tempdir().full_path trainer.reset(output_dir) trainer.train_epoch(1, 0) # Those are the things returned by Trainer._jit_update_fn arrays = (trainer._opt_state.weights, trainer._opt_state.slots, trainer._model_state, trainer._rngs) arrays = tf.nest.flatten(arrays) for x in arrays: if isinstance(x, jnp.ndarray) and (x.dtype == jnp.int32 or x.dtype == jnp.uint32): raise ValueError('Found an array of int32 or uint32: %s' % x) class EpochsTest(absltest.TestCase): def test_cuts_epoch_when_total_steps_reached(self): epoch_steps = trainer_lib.epochs( total_steps=5, steps_to_skip=0, epoch_steps=[1, 2, 3]) self.assertEqual(list(epoch_steps), [1, 2, 2]) def test_skips_full_epoch(self): epoch_steps = trainer_lib.epochs( total_steps=4, steps_to_skip=2, epoch_steps=[2, 2]) self.assertEqual(list(epoch_steps), [2]) def test_skips_part_of_epoch(self): epoch_steps = trainer_lib.epochs( total_steps=4, steps_to_skip=1, epoch_steps=[2, 2]) self.assertEqual(list(epoch_steps), [1, 2]) if __name__ == '__main__': config.config_with_absl() tf.compat.v1.enable_eager_execution() absltest.main()
with fastmath.use_backend(backend): # Prepare model and inputs def model(mode='train'): return models.Reformer2( mode=mode, d_model=16, d_ff=16, n_heads=2, dropout=0.05, n_decoder_layers=1, n_encoder_layers=1, input_vocab_size=256, encoder_attention_type=_pure_lsh_self_attention_fn(), encoder_decoder_attention_type=_pure_lsh_self_attention_fn(), ) max_len = 128 inputs = _test_inputs_lm(vocab_size=256, seq_len=max_len) steps = 1 eval_steps = 1 # Train and evaluate output_dir = self.create_tempdir().full_path trainer_lib.train( output_dir, model=model, inputs=inputs, steps=steps, eval_steps=eval_steps, eval_frequency=1) # Read checkpoint model_file = os.path.join(output_dir, 'model.pkl.gz') shape11 = trax_shapes.ShapeDtype((1, 1), dtype=jnp.int32) shape1l = trax_shapes.ShapeDtype((1, max_len), dtype=jnp.int32) model_predict = model(mode='predict') model_predict.init_from_file( model_file, weights_only=True, input_signature=(shape1l, shape11))
E0195.rs
trait Trait { fn bar<'a,'b:'a>(x: &'a str, y: &'b str); //~^ NOTE lifetimes in impl do not match this method in trait }
//~^ NOTE lifetimes do not match method in trait } } fn main() { }
struct Foo; impl Trait for Foo { fn bar<'a,'b>(x: &'a str, y: &'b str) { //~ ERROR E0195
mpi_inf_3dhp.py
import os import sys import cv2 import glob import h5py import json import numpy as np import scipy.io as sio import scipy.misc from .read_openpose import read_openpose def read_calibration(calib_file, vid_list): Ks, Rs, Ts = [], [], [] file = open(calib_file, 'r') content = file.readlines() for vid_i in vid_list: K = np.array([float(s) for s in content[vid_i*7+5][11:-2].split()]) K = np.reshape(K, (4, 4)) RT = np.array([float(s) for s in content[vid_i*7+6][11:-2].split()]) RT = np.reshape(RT, (4, 4)) R = RT[:3,:3] T = RT[:3,3]/1000 Ks.append(K) Rs.append(R) Ts.append(T) return Ks, Rs, Ts def
(dataset_path, openpose_path, out_path, joints_idx, scaleFactor, extract_img=False, fits_3d=None): joints17_idx = [4, 18, 19, 20, 23, 24, 25, 3, 5, 6, 7, 9, 10, 11, 14, 15, 16] h, w = 2048, 2048 imgnames_, scales_, centers_ = [], [], [] parts_, Ss_, openposes_ = [], [], [] # training data user_list = range(1,9) seq_list = range(1,3) vid_list = list(range(3)) + list(range(4,9)) counter = 0 for user_i in user_list: for seq_i in seq_list: seq_path = os.path.join(dataset_path, 'S' + str(user_i), 'Seq' + str(seq_i)) # mat file with annotations annot_file = os.path.join(seq_path, 'annot.mat') annot2 = sio.loadmat(annot_file)['annot2'] annot3 = sio.loadmat(annot_file)['annot3'] # calibration file and camera parameters calib_file = os.path.join(seq_path, 'camera.calibration') Ks, Rs, Ts = read_calibration(calib_file, vid_list) for j, vid_i in enumerate(vid_list): # image folder imgs_path = os.path.join(seq_path, 'imageFrames', 'video_' + str(vid_i)) # extract frames from video file if extract_img: # if doesn't exist if not os.path.isdir(imgs_path): os.makedirs(imgs_path) # video file vid_file = os.path.join(seq_path, 'imageSequence', 'video_' + str(vid_i) + '.avi') vidcap = cv2.VideoCapture(vid_file) # process video frame = 0 while 1: # extract all frames success, image = vidcap.read() if not success: break frame += 1 # image name imgname = os.path.join(imgs_path, 'frame_%06d.jpg' % frame) # save image cv2.imwrite(imgname, image) # per frame cam_aa = cv2.Rodrigues(Rs[j])[0].T[0] pattern = os.path.join(imgs_path, '*.jpg') img_list = glob.glob(pattern) for i, img_i in enumerate(img_list): # for each image we store the relevant annotations img_name = img_i.split('/')[-1] img_view = os.path.join('S' + str(user_i), 'Seq' + str(seq_i), 'imageFrames', 'video_' + str(vid_i), img_name) joints = np.reshape(annot2[vid_i][0][i], (28, 2))[joints17_idx] S17 = np.reshape(annot3[vid_i][0][i], (28, 3))/1000 S17 = S17[joints17_idx] - S17[4] # 4 is the root bbox = [min(joints[:,0]), min(joints[:,1]), max(joints[:,0]), max(joints[:,1])] center = [(bbox[2]+bbox[0])/2, (bbox[3]+bbox[1])/2] scale = scaleFactor*max(bbox[2]-bbox[0], bbox[3]-bbox[1])/200 # check that all joints are visible x_in = np.logical_and(joints[:, 0] < w, joints[:, 0] >= 0) y_in = np.logical_and(joints[:, 1] < h, joints[:, 1] >= 0) ok_pts = np.logical_and(x_in, y_in) if np.sum(ok_pts) < len(joints_idx): continue part = np.zeros([24,3]) part[joints_idx] = np.hstack([joints, np.ones([17,1])]) json_file = os.path.join(openpose_path, 'mpi_inf_3dhp', img_view.replace('.jpg', '_keypoints.json')) openpose = read_openpose(json_file, part, 'mpi_inf_3dhp') S = np.zeros([24,4]) S[joints_idx] = np.hstack([S17, np.ones([17,1])]) # because of the dataset size, we only keep every 10th frame counter += 1 if counter % 10 != 1: continue # store the data imgnames_.append(img_view) centers_.append(center) scales_.append(scale) parts_.append(part) Ss_.append(S) openposes_.append(openpose) # store the data struct if not os.path.isdir(out_path): os.makedirs(out_path) out_file = os.path.join(out_path, 'mpi_inf_3dhp_train.npz') if fits_3d is not None: fits_3d = np.load(fits_3d) np.savez(out_file, imgname=imgnames_, center=centers_, scale=scales_, part=parts_, pose=fits_3d['pose'], shape=fits_3d['shape'], has_smpl=fits_3d['has_smpl'], S=Ss_, openpose=openposes_) else: np.savez(out_file, imgname=imgnames_, center=centers_, scale=scales_, part=parts_, S=Ss_, openpose=openposes_) def test_data(dataset_path, out_path, joints_idx, scaleFactor): joints17_idx = [14, 11, 12, 13, 8, 9, 10, 15, 1, 16, 0, 5, 6, 7, 2, 3, 4] imgnames_, scales_, centers_, parts_, Ss_ = [], [], [], [], [] # training data user_list = range(1,7) for user_i in user_list: seq_path = os.path.join(dataset_path, 'mpi_inf_3dhp_test_set', 'TS' + str(user_i)) # mat file with annotations annot_file = os.path.join(seq_path, 'annot_data.mat') mat_as_h5 = h5py.File(annot_file, 'r') annot2 = np.array(mat_as_h5['annot2']) annot3 = np.array(mat_as_h5['univ_annot3']) valid = np.array(mat_as_h5['valid_frame']) for frame_i, valid_i in enumerate(valid): if valid_i == 0: continue img_name = os.path.join('mpi_inf_3dhp_test_set', 'TS' + str(user_i), 'imageSequence', 'img_' + str(frame_i+1).zfill(6) + '.jpg') joints = annot2[frame_i,0,joints17_idx,:] S17 = annot3[frame_i,0,joints17_idx,:]/1000 S17 = S17 - S17[0] bbox = [min(joints[:,0]), min(joints[:,1]), max(joints[:,0]), max(joints[:,1])] center = [(bbox[2]+bbox[0])/2, (bbox[3]+bbox[1])/2] scale = scaleFactor*max(bbox[2]-bbox[0], bbox[3]-bbox[1])/200 # check that all joints are visible img_file = os.path.join(dataset_path, img_name) I = scipy.misc.imread(img_file) h, w, _ = I.shape x_in = np.logical_and(joints[:, 0] < w, joints[:, 0] >= 0) y_in = np.logical_and(joints[:, 1] < h, joints[:, 1] >= 0) ok_pts = np.logical_and(x_in, y_in) if np.sum(ok_pts) < len(joints_idx): continue part = np.zeros([24,3]) part[joints_idx] = np.hstack([joints, np.ones([17,1])]) S = np.zeros([24,4]) S[joints_idx] = np.hstack([S17, np.ones([17,1])]) # store the data imgnames_.append(img_name) centers_.append(center) scales_.append(scale) parts_.append(part) Ss_.append(S) # store the data struct if not os.path.isdir(out_path): os.makedirs(out_path) out_file = os.path.join(out_path, 'mpi_inf_3dhp_test.npz') np.savez(out_file, imgname=imgnames_, center=centers_, scale=scales_, part=parts_, S=Ss_) def mpi_inf_3dhp_extract(dataset_path, openpose_path, out_path, mode, extract_img=False, static_fits=None): scaleFactor = 1.2 joints_idx = [14, 3, 4, 5, 2, 1, 0, 16, 12, 17, 18, 9, 10, 11, 8, 7, 6] if static_fits is not None: fits_3d = os.path.join(static_fits, 'mpi-inf-3dhp_mview_fits.npz') else: fits_3d = None if mode == 'train': train_data(dataset_path, openpose_path, out_path, joints_idx, scaleFactor, extract_img=extract_img, fits_3d=fits_3d) elif mode == 'test': test_data(dataset_path, out_path, joints_idx, scaleFactor)
train_data
button.test.tsx
import React from 'react' import { render, screen, fireEvent } from '@testing-library/react' import { Plus } from 'react-feather' import { Button } from '../src' test('renders children(text) correctly', () => { render(<Button type="button">Button</Button>) expect(screen.getByRole('button')).toHaveTextContent('Button') }) test('calls onClick prop when clicked', () => { const handleClick = jest.fn() render(<Button onClick={handleClick} />) fireEvent.click(screen.getByRole('button')) expect(handleClick).toHaveBeenCalledTimes(1) }) test('not calls onClick prop when clicked if is disabled', () => { const handleClick = jest.fn() render(<Button onClick={handleClick} isDisabled />) fireEvent.click(screen.getByRole('button')) expect(handleClick).toHaveBeenCalledTimes(0) })
const button = screen.getByRole('button') const svg = screen.getByTestId('svg') expect(button).toContainElement(svg) })
test('renders an icon correctly', () => { render(<Button icon={<Plus data-testid="svg" />} />)
txhashset.rs
// Copyright 2020 The Grin 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. //! Utility structs to handle the 3 MMRs (output, rangeproof, //! kernel) along the overall header MMR conveniently and transactionally. use crate::core::core::committed::Committed; use crate::core::core::hash::{Hash, Hashed}; use crate::core::core::merkle_proof::MerkleProof; use crate::core::core::pmmr::{self, Backend, ReadonlyPMMR, RewindablePMMR, PMMR}; use crate::core::core::{Block, BlockHeader, Input, Output, OutputIdentifier, TxKernel}; use crate::core::ser::{PMMRIndexHashable, PMMRable, ProtocolVersion}; use crate::error::{Error, ErrorKind}; use crate::store::{Batch, ChainStore}; use crate::txhashset::bitmap_accumulator::BitmapAccumulator; use crate::txhashset::{RewindableKernelView, UTXOView}; use crate::types::{CommitPos, OutputRoots, Tip, TxHashSetRoots, TxHashsetWriteStatus}; use crate::util::secp::pedersen::{Commitment, RangeProof}; use crate::util::{file, secp_static, zip}; use croaring::Bitmap; use grin_store; use grin_store::pmmr::{clean_files_by_prefix, PMMRBackend}; use std::fs::{self, File}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::Instant; const TXHASHSET_SUBDIR: &str = "txhashset"; const OUTPUT_SUBDIR: &str = "output"; const RANGE_PROOF_SUBDIR: &str = "rangeproof"; const KERNEL_SUBDIR: &str = "kernel"; const TXHASHSET_ZIP: &str = "txhashset_snapshot"; /// Convenience wrapper around a single prunable MMR backend. pub struct PMMRHandle<T: PMMRable> { /// The backend storage for the MMR. pub backend: PMMRBackend<T>, /// The last position accessible via this MMR handle (backend may continue out beyond this). pub last_pos: u64, } impl<T: PMMRable> PMMRHandle<T> { /// Constructor to create a PMMR handle from an existing directory structure on disk. /// Creates the backend files as necessary if they do not already exist. pub fn new( root_dir: &str, sub_dir: &str, file_name: &str, prunable: bool, version: ProtocolVersion, header: Option<&BlockHeader>, ) -> Result<PMMRHandle<T>, Error> { let path = Path::new(root_dir).join(sub_dir).join(file_name); fs::create_dir_all(path.clone())?; let path_str = path .to_str() .ok_or_else(|| ErrorKind::Other("invalid file path".to_owned()))?; let backend = PMMRBackend::new(path_str.to_string(), prunable, version, header)?; let last_pos = backend.unpruned_size(); Ok(PMMRHandle { backend, last_pos }) } } impl PMMRHandle<BlockHeader> { /// Get the header hash at the specified height based on the current header MMR state. pub fn get_header_hash_by_height(&self, height: u64) -> Result<Hash, Error> { let pos = pmmr::insertion_to_pmmr_index(height + 1); let header_pmmr = ReadonlyPMMR::at(&self.backend, self.last_pos); if let Some(entry) = header_pmmr.get_data(pos) { Ok(entry.hash()) } else { Err(ErrorKind::Other(format!("not found header hash for height {}", height)).into()) } } /// Get the header hash for the head of the header chain based on current MMR state. /// Find the last leaf pos based on MMR size and return its header hash. pub fn head_hash(&self) -> Result<Hash, Error> { if self.last_pos == 0 { return Err(ErrorKind::Other("MMR empty, no head".to_string()).into()); } let header_pmmr = ReadonlyPMMR::at(&self.backend, self.last_pos); let leaf_pos = pmmr::bintree_rightmost(self.last_pos); if let Some(entry) = header_pmmr.get_data(leaf_pos) { Ok(entry.hash()) } else { Err(ErrorKind::Other("failed to find head hash".to_string()).into()) } } } /// An easy to manipulate structure holding the 3 MMRs necessary to /// validate blocks and capturing the output set, associated rangeproofs and the /// kernels. Also handles the index of Commitments to positions in the /// output and rangeproof MMRs. /// /// Note that the index is never authoritative, only the trees are /// guaranteed to indicate whether an output is spent or not. The index /// may have commitments that have already been spent, even with /// pruning enabled. pub struct TxHashSet { output_pmmr_h: PMMRHandle<Output>, rproof_pmmr_h: PMMRHandle<RangeProof>, kernel_pmmr_h: PMMRHandle<TxKernel>, bitmap_accumulator: BitmapAccumulator, // chain store used as index of commitments to MMR positions commit_index: Arc<ChainStore>, } impl TxHashSet { /// Open an existing or new set of backends for the TxHashSet pub fn open( root_dir: String, commit_index: Arc<ChainStore>, header: Option<&BlockHeader>, ) -> Result<TxHashSet, Error> { let output_pmmr_h = PMMRHandle::new( &root_dir, TXHASHSET_SUBDIR, OUTPUT_SUBDIR, true, ProtocolVersion(1), header, )?; let rproof_pmmr_h = PMMRHandle::new( &root_dir, TXHASHSET_SUBDIR, RANGE_PROOF_SUBDIR, true, ProtocolVersion(1), header, )?; // Initialize the bitmap accumulator from the current output PMMR. let bitmap_accumulator = TxHashSet::bitmap_accumulator(&output_pmmr_h)?; let mut maybe_kernel_handle: Option<PMMRHandle<TxKernel>> = None; let versions = vec![ProtocolVersion(2), ProtocolVersion(1)]; for version in versions { let handle = PMMRHandle::new( &root_dir, TXHASHSET_SUBDIR, KERNEL_SUBDIR, false, // not prunable version, None, )?; if handle.last_pos == 0 { debug!( "attempting to open (empty) kernel PMMR using {:?} - SUCCESS", version ); maybe_kernel_handle = Some(handle); break; } let kernel: Option<TxKernel> = ReadonlyPMMR::at(&handle.backend, 1).get_data(1); if let Some(kernel) = kernel { if kernel.verify().is_ok() { debug!( "attempting to open kernel PMMR using {:?} - SUCCESS", version ); maybe_kernel_handle = Some(handle); break; } else { debug!( "attempting to open kernel PMMR using {:?} - FAIL (verify failed)", version ); } } else { debug!( "attempting to open kernel PMMR using {:?} - FAIL (read failed)", version ); } } if let Some(kernel_pmmr_h) = maybe_kernel_handle { Ok(TxHashSet { output_pmmr_h, rproof_pmmr_h, kernel_pmmr_h, bitmap_accumulator, commit_index, }) } else { Err(ErrorKind::TxHashSetErr("failed to open kernel PMMR".to_string()).into()) } } // Build a new bitmap accumulator for the provided output PMMR. fn bitmap_accumulator(pmmr_h: &PMMRHandle<Output>) -> Result<BitmapAccumulator, Error> { let pmmr = ReadonlyPMMR::at(&pmmr_h.backend, pmmr_h.last_pos); let size = pmmr::n_leaves(pmmr_h.last_pos); let mut bitmap_accumulator = BitmapAccumulator::new(); bitmap_accumulator.init(&mut pmmr.leaf_idx_iter(0), size)?; Ok(bitmap_accumulator) } /// Close all backend file handles pub fn release_backend_files(&mut self) { self.output_pmmr_h.backend.release_files(); self.rproof_pmmr_h.backend.release_files(); self.kernel_pmmr_h.backend.release_files(); } /// Check if an output is unspent. /// We look in the index to find the output MMR pos. /// Then we check the entry in the output MMR and confirm the hash matches. pub fn is_unspent(&self, output_id: &OutputIdentifier) -> Result<CommitPos, Error> { let commit = output_id.commit; match self.commit_index.get_output_pos_height(&commit) { Ok((pos, height)) => { let output_pmmr: ReadonlyPMMR<'_, Output, _> = ReadonlyPMMR::at(&self.output_pmmr_h.backend, self.output_pmmr_h.last_pos); if let Some(hash) = output_pmmr.get_hash(pos) { if hash == output_id.hash_with_index(pos - 1) { Ok(CommitPos { pos, height }) } else { Err(ErrorKind::TxHashSetErr("txhashset hash mismatch".to_string()).into()) } } else { Err(ErrorKind::OutputNotFound(format!( "output pmmr not found for pos {} and height {}", pos, height )) .into()) } } Err(grin_store::Error::NotFoundErr(msg)) => { Err(ErrorKind::OutputNotFound(format!("Commit not found in imdb, {}", msg)).into()) } Err(e) => Err(ErrorKind::StoreErr(e, "txhashset unspent check".to_string()).into()), } } /// returns the last N nodes inserted into the tree (i.e. the 'bottom' /// nodes at level 0 /// TODO: These need to return the actual data from the flat-files instead /// of hashes now pub fn last_n_output(&self, distance: u64) -> Vec<(Hash, OutputIdentifier)> { ReadonlyPMMR::at(&self.output_pmmr_h.backend, self.output_pmmr_h.last_pos) .get_last_n_insertions(distance) } /// as above, for range proofs pub fn last_n_rangeproof(&self, distance: u64) -> Vec<(Hash, RangeProof)> { ReadonlyPMMR::at(&self.rproof_pmmr_h.backend, self.rproof_pmmr_h.last_pos) .get_last_n_insertions(distance) } /// as above, for kernels pub fn last_n_kernel(&self, distance: u64) -> Vec<(Hash, TxKernel)> { ReadonlyPMMR::at(&self.kernel_pmmr_h.backend, self.kernel_pmmr_h.last_pos) .get_last_n_insertions(distance) } /// Convenience function to query the db for a header by its hash. pub fn get_block_header(&self, hash: &Hash) -> Result<BlockHeader, Error> { Ok(self.commit_index.get_block_header(&hash)?) } /// returns outputs from the given pmmr index up to the /// specified limit. Also returns the last index actually populated /// max index is the last PMMR index to consider, not leaf index pub fn outputs_by_pmmr_index( &self, start_index: u64, max_count: u64, max_index: Option<u64>, ) -> (u64, Vec<OutputIdentifier>) { ReadonlyPMMR::at(&self.output_pmmr_h.backend, self.output_pmmr_h.last_pos) .elements_from_pmmr_index(start_index, max_count, max_index) } /// highest output insertion index available pub fn highest_output_insertion_index(&self) -> u64 { self.output_pmmr_h.last_pos } /// As above, for rangeproofs pub fn rangeproofs_by_pmmr_index( &self, start_index: u64, max_count: u64, max_index: Option<u64>, ) -> (u64, Vec<RangeProof>) { ReadonlyPMMR::at(&self.rproof_pmmr_h.backend, self.rproof_pmmr_h.last_pos) .elements_from_pmmr_index(start_index, max_count, max_index) } /// Find a kernel with a given excess. Work backwards from `max_index` to `min_index` pub fn find_kernel( &self, excess: &Commitment, min_index: Option<u64>, max_index: Option<u64>, ) -> Option<(TxKernel, u64)> { let min_index = min_index.unwrap_or(1); let max_index = max_index.unwrap_or(self.kernel_pmmr_h.last_pos); let pmmr = ReadonlyPMMR::at(&self.kernel_pmmr_h.backend, self.kernel_pmmr_h.last_pos); let mut index = max_index + 1; while index > min_index { index -= 1; if let Some(kernel) = pmmr.get_data(index) { if &kernel.excess == excess { return Some((kernel, index)); } } } None } /// Get MMR roots. pub fn roots(&self) -> TxHashSetRoots { let output_pmmr = ReadonlyPMMR::at(&self.output_pmmr_h.backend, self.output_pmmr_h.last_pos); let rproof_pmmr = ReadonlyPMMR::at(&self.rproof_pmmr_h.backend, self.rproof_pmmr_h.last_pos); let kernel_pmmr = ReadonlyPMMR::at(&self.kernel_pmmr_h.backend, self.kernel_pmmr_h.last_pos); TxHashSetRoots { output_roots: OutputRoots { pmmr_root: output_pmmr.root(), bitmap_root: self.bitmap_accumulator.root(), }, rproof_root: rproof_pmmr.root(), kernel_root: kernel_pmmr.root(), } } /// Return Commit's MMR position pub fn get_output_pos(&self, commit: &Commitment) -> Result<u64, Error> { Ok(self.commit_index.get_output_pos(&commit)?) } /// build a new merkle proof for the given position. pub fn merkle_proof(&mut self, commit: Commitment) -> Result<MerkleProof, Error> { let pos = self.commit_index.get_output_pos(&commit)?; PMMR::at(&mut self.output_pmmr_h.backend, self.output_pmmr_h.last_pos) .merkle_proof(pos) .map_err(|e| { ErrorKind::MerkleProof(format!("Commit {:?}, pos {}, {}", commit, pos, e)).into() }) } /// Compact the MMR data files and flush the rm logs pub fn compact( &mut self, horizon_header: &BlockHeader, batch: &Batch<'_>, ) -> Result<(), Error> { debug!("txhashset: starting compaction..."); let head_header = batch.head_header()?; let rewind_rm_pos = input_pos_to_rewind(&horizon_header, &head_header, batch)?; debug!("txhashset: check_compact output mmr backend..."); self.output_pmmr_h .backend .check_compact(horizon_header.output_mmr_size, &rewind_rm_pos)?; debug!("txhashset: check_compact rangeproof mmr backend..."); self.rproof_pmmr_h .backend .check_compact(horizon_header.output_mmr_size, &rewind_rm_pos)?; debug!("txhashset: ... compaction finished"); Ok(()) } /// (Re)build the output_pos index to be consistent with the current UTXO set. /// Remove any "stale" index entries that do not correspond to outputs in the UTXO set. /// Add any missing index entries based on UTXO set. pub fn init_output_pos_index( &self, header_pmmr: &PMMRHandle<BlockHeader>, batch: &Batch<'_>, ) -> Result<(), Error> { let now = Instant::now(); let output_pmmr = ReadonlyPMMR::at(&self.output_pmmr_h.backend, self.output_pmmr_h.last_pos); // Iterate over the current output_pos index, removing any entries that // do not point to to the expected output. let mut removed_count = 0; for (key, (pos, _)) in batch.output_pos_iter()? { if let Some(out) = output_pmmr.get_data(pos) { if let Ok(pos_via_mmr) = batch.get_output_pos(&out.commitment()) { // If the pos matches and the index key matches the commitment // then keep the entry, other we want to clean it up. if pos == pos_via_mmr && batch.is_match_output_pos_key(&key, &out.commitment()) { continue; } } } batch.delete(&key)?; removed_count += 1; } debug!( "init_output_pos_index: removed {} stale index entries", removed_count ); let mut outputs_pos: Vec<(Commitment, u64)> = vec![]; for pos in output_pmmr.leaf_pos_iter() { if let Some(out) = output_pmmr.get_data(pos) { outputs_pos.push((out.commit, pos)); } } debug!("init_output_pos_index: {} utxos", outputs_pos.len()); outputs_pos.retain(|x| batch.get_output_pos_height(&x.0).is_err()); debug!( "init_output_pos_index: {} utxos with missing index entries", outputs_pos.len() ); if outputs_pos.is_empty() { return Ok(()); } let total_outputs = outputs_pos.len(); let max_height = batch.head()?.height; let mut i = 0; for search_height in 0..max_height { let hash = header_pmmr.get_header_hash_by_height(search_height + 1)?; let h = batch.get_block_header(&hash)?; while i < total_outputs { let (commit, pos) = outputs_pos[i]; if pos > h.output_mmr_size { // Note: MMR position is 1-based and not 0-based, so here must be '>' instead of '>=' break; } batch.save_output_pos_height(&commit, pos, h.height)?; i += 1; } } debug!( "init_height_pos_index: added entries for {} utxos, took {}s", total_outputs, now.elapsed().as_secs(), ); Ok(()) } } /// Starts a new unit of work to extend (or rewind) the chain with additional /// blocks. Accepts a closure that will operate within that unit of work. /// The closure has access to an Extension object that allows the addition /// of blocks to the txhashset and the checking of the current tree roots. /// /// The unit of work is always discarded (always rollback) as this is read-only. pub fn extending_readonly<F, T>( handle: &mut PMMRHandle<BlockHeader>, trees: &mut TxHashSet, inner: F, ) -> Result<T, Error> where F: FnOnce(&mut ExtensionPair<'_>, &Batch<'_>) -> Result<T, Error>, { let commit_index = trees.commit_index.clone(); let batch = commit_index.batch()?; trace!("Starting new txhashset (readonly) extension."); let head = batch.head()?; // Find header head based on current header MMR (the rightmost leaf node in the MMR). let header_head = { let hash = handle.head_hash()?; let header = batch.get_block_header(&hash)?; Tip::from_header(&header) }; let res = { let header_pmmr = PMMR::at(&mut handle.backend, handle.last_pos); let mut header_extension = HeaderExtension::new(header_pmmr, header_head); let mut extension = Extension::new(trees, head); let mut extension_pair = ExtensionPair { header_extension: &mut header_extension, extension: &mut extension, }; inner(&mut extension_pair, &batch) }; trace!("Rollbacking txhashset (readonly) extension."); handle.backend.discard(); trees.output_pmmr_h.backend.discard(); trees.rproof_pmmr_h.backend.discard(); trees.kernel_pmmr_h.backend.discard(); trace!("TxHashSet (readonly) extension done."); res } /// Readonly view on the UTXO set. /// Based on the current txhashset output_pmmr. pub fn utxo_view<F, T>( handle: &PMMRHandle<BlockHeader>, trees: &TxHashSet, inner: F, ) -> Result<T, Error> where F: FnOnce(&UTXOView<'_>, &Batch<'_>) -> Result<T, Error>, { let res: Result<T, Error>; { let output_pmmr = ReadonlyPMMR::at(&trees.output_pmmr_h.backend, trees.output_pmmr_h.last_pos); let header_pmmr = ReadonlyPMMR::at(&handle.backend, handle.last_pos); let rproof_pmmr = ReadonlyPMMR::at(&trees.rproof_pmmr_h.backend, trees.rproof_pmmr_h.last_pos); // Create a new batch here to pass into the utxo_view. // Discard it (rollback) after we finish with the utxo_view. let batch = trees.commit_index.batch()?; let utxo = UTXOView::new(output_pmmr, header_pmmr, rproof_pmmr); res = inner(&utxo, &batch); } res } /// Rewindable (but still readonly) view on the kernel MMR. /// The underlying backend is readonly. But we permit the PMMR to be "rewound" /// via last_pos. /// We create a new db batch for this view and discard it (rollback) /// when we are done with the view. pub fn rewindable_kernel_view<F, T>(trees: &TxHashSet, inner: F) -> Result<T, Error> where F: FnOnce(&mut RewindableKernelView<'_>, &Batch<'_>) -> Result<T, Error>, { let res: Result<T, Error>; { let kernel_pmmr = RewindablePMMR::at(&trees.kernel_pmmr_h.backend, trees.kernel_pmmr_h.last_pos); // Create a new batch here to pass into the kernel_view. // Discard it (rollback) after we finish with the kernel_view. let batch = trees.commit_index.batch()?; let header = batch.head_header()?; let mut view = RewindableKernelView::new(kernel_pmmr, header); res = inner(&mut view, &batch); } res } /// Starts a new unit of work to extend the chain with additional blocks, /// accepting a closure that will work within that unit of work. The closure /// has access to an Extension object that allows the addition of blocks to /// the txhashset and the checking of the current tree roots. /// /// If the closure returns an error, modifications are canceled and the unit /// of work is abandoned. Otherwise, the unit of work is permanently applied. pub fn extending<'a, F, T>( header_pmmr: &'a mut PMMRHandle<BlockHeader>, trees: &'a mut TxHashSet, batch: &'a mut Batch<'_>, inner: F, ) -> Result<T, Error> where F: FnOnce(&mut ExtensionPair<'_>, &Batch<'_>) -> Result<T, Error>, { let sizes: (u64, u64, u64); let res: Result<T, Error>; let rollback: bool; let bitmap_accumulator: BitmapAccumulator; let head = batch.head()?; // Find header head based on current header MMR (the rightmost leaf node in the MMR). let header_head = { let hash = header_pmmr.head_hash()?; let header = batch.get_block_header(&hash)?; Tip::from_header(&header) }; // create a child transaction so if the state is rolled back by itself, all // index saving can be undone let child_batch = batch.child()?; { trace!("Starting new txhashset extension."); let header_pmmr = PMMR::at(&mut header_pmmr.backend, header_pmmr.last_pos); let mut header_extension = HeaderExtension::new(header_pmmr, header_head); let mut extension = Extension::new(trees, head); let mut extension_pair = ExtensionPair { header_extension: &mut header_extension, extension: &mut extension, }; res = inner(&mut extension_pair, &child_batch); rollback = extension_pair.extension.rollback; sizes = extension_pair.extension.sizes(); bitmap_accumulator = extension_pair.extension.bitmap_accumulator.clone(); } // During an extension we do not want to modify the header_extension (and only read from it). // So make sure we discard any changes to the header MMR backed. header_pmmr.backend.discard(); match res { Err(e) => { debug!("Error returned, discarding txhashset extension: {}", e); trees.output_pmmr_h.backend.discard(); trees.rproof_pmmr_h.backend.discard(); trees.kernel_pmmr_h.backend.discard(); Err(e) } Ok(r) => { if rollback { trace!("Rollbacking txhashset extension. sizes {:?}", sizes); trees.output_pmmr_h.backend.discard(); trees.rproof_pmmr_h.backend.discard(); trees.kernel_pmmr_h.backend.discard(); } else { trace!("Committing txhashset extension. sizes {:?}", sizes); child_batch.commit()?; trees.output_pmmr_h.backend.sync()?; trees.rproof_pmmr_h.backend.sync()?; trees.kernel_pmmr_h.backend.sync()?; trees.output_pmmr_h.last_pos = sizes.0; trees.rproof_pmmr_h.last_pos = sizes.1; trees.kernel_pmmr_h.last_pos = sizes.2;
trace!("TxHashSet extension done."); Ok(r) } } } /// Start a new header MMR unit of work. /// This MMR can be extended individually beyond the other (output, rangeproof and kernel) MMRs /// to allow headers to be validated before we receive the full block data. pub fn header_extending<'a, F, T>( handle: &'a mut PMMRHandle<BlockHeader>, batch: &'a mut Batch<'_>, inner: F, ) -> Result<T, Error> where F: FnOnce(&mut HeaderExtension<'_>, &Batch<'_>) -> Result<T, Error>, { let size: u64; let res: Result<T, Error>; let rollback: bool; // create a child transaction so if the state is rolled back by itself, all // index saving can be undone let child_batch = batch.child()?; // Find chain head based on current MMR (the rightmost leaf node in the MMR). let head = match handle.head_hash() { Ok(hash) => { let header = child_batch.get_block_header(&hash)?; Tip::from_header(&header) } Err(_) => Tip::default(), }; { let pmmr = PMMR::at(&mut handle.backend, handle.last_pos); let mut extension = HeaderExtension::new(pmmr, head); res = inner(&mut extension, &child_batch); rollback = extension.rollback; size = extension.size(); } match res { Err(e) => { handle.backend.discard(); Err(e) } Ok(r) => { if rollback { handle.backend.discard(); } else { child_batch.commit()?; handle.backend.sync()?; handle.last_pos = size; } Ok(r) } } } /// A header extension to allow the header MMR to extend beyond the other MMRs individually. /// This is to allow headers to be validated against the MMR before we have the full block data. pub struct HeaderExtension<'a> { head: Tip, pmmr: PMMR<'a, BlockHeader, PMMRBackend<BlockHeader>>, /// Rollback flag. rollback: bool, } impl<'a> HeaderExtension<'a> { fn new( pmmr: PMMR<'a, BlockHeader, PMMRBackend<BlockHeader>>, head: Tip, ) -> HeaderExtension<'a> { HeaderExtension { head, pmmr, rollback: false, } } /// Get the header hash for the specified pos from the underlying MMR backend. fn get_header_hash(&self, pos: u64) -> Option<Hash> { self.pmmr.get_data(pos).map(|x| x.hash()) } /// The head representing the furthest extent of the current extension. pub fn head(&self) -> Tip { self.head.clone() } /// Get the header at the specified height based on the current state of the header extension. /// Derives the MMR pos from the height (insertion index) and retrieves the header hash. /// Looks the header up in the db by hash. pub fn get_header_by_height( &self, height: u64, batch: &Batch<'_>, ) -> Result<BlockHeader, Error> { let pos = pmmr::insertion_to_pmmr_index(height + 1); if let Some(hash) = self.get_header_hash(pos) { Ok(batch.get_block_header(&hash)?) } else { Err(ErrorKind::Other(format!("not found header for height {}", height)).into()) } } /// Compares the provided header to the header in the header MMR at that height. /// If these match we know the header is on the current chain. pub fn is_on_current_chain( &self, header: &BlockHeader, batch: &Batch<'_>, ) -> Result<(), Error> { if header.height > self.head.height { return Err( ErrorKind::Other(format!("header is not on current chain, out beyond")).into(), ); } let chain_header = self.get_header_by_height(header.height, batch)?; if chain_header.hash() == header.hash() { Ok(()) } else { Err(ErrorKind::Other("header is not on current chain".to_string()).into()) } } /// Force the rollback of this extension, no matter the result. pub fn force_rollback(&mut self) { self.rollback = true; } /// Apply a new header to the header MMR extension. /// This may be either the header MMR or the sync MMR depending on the /// extension. pub fn apply_header(&mut self, header: &BlockHeader) -> Result<(), Error> { self.pmmr.push(header).map_err(|e| { ErrorKind::TxHashSetErr(format!( "Unable to apply header with height {}, {}", header.height, e )) })?; self.head = Tip::from_header(header); Ok(()) } /// Rewind the header extension to the specified header. /// Note the close relationship between header height and insertion index. pub fn rewind(&mut self, header: &BlockHeader) -> Result<(), Error> { debug!( "Rewind header extension to {} at {} from {} at {}", header.hash(), header.height, self.head.hash(), self.head.height, ); let header_pos = pmmr::insertion_to_pmmr_index(header.height + 1); self.pmmr .rewind(header_pos, &Bitmap::create()) .map_err(|e| { ErrorKind::TxHashSetErr(format!("pmmr rewind for pos {}, {}", header_pos, e)) })?; // Update our head to reflect the header we rewound to. self.head = Tip::from_header(header); Ok(()) } /// The size of the header MMR. pub fn size(&self) -> u64 { self.pmmr.unpruned_size() } /// The root of the header MMR for convenience. pub fn root(&self) -> Result<Hash, Error> { Ok(self.pmmr.root().map_err(|e| ErrorKind::InvalidRoot(e))?) } /// Validate the prev_root of the header against the root of the current header MMR. pub fn validate_root(&self, header: &BlockHeader) -> Result<(), Error> { // If we are validating the genesis block then we have no prev_root. // So we are done here. if header.height == 0 { return Ok(()); } let root = self.root()?; if root != header.prev_root { Err(ErrorKind::InvalidRoot(format!( "Unable to validate root, Expected header.prev_root {}, get {}", header.prev_root, root )) .into()) } else { Ok(()) } } } /// An extension "pair" consisting of a txhashet extension (outputs, rangeproofs, kernels) /// and the associated header extension. pub struct ExtensionPair<'a> { /// The header extension. pub header_extension: &'a mut HeaderExtension<'a>, /// The txhashset extension. pub extension: &'a mut Extension<'a>, } /// Allows the application of new blocks on top of the txhashset in a /// reversible manner within a unit of work provided by the `extending` /// function. pub struct Extension<'a> { head: Tip, output_pmmr: PMMR<'a, Output, PMMRBackend<Output>>, rproof_pmmr: PMMR<'a, RangeProof, PMMRBackend<RangeProof>>, kernel_pmmr: PMMR<'a, TxKernel, PMMRBackend<TxKernel>>, bitmap_accumulator: BitmapAccumulator, /// Rollback flag. rollback: bool, } impl<'a> Committed for Extension<'a> { fn inputs_committed(&self) -> Vec<Commitment> { vec![] } fn outputs_committed(&self) -> Vec<Commitment> { let mut commitments = vec![]; for pos in self.output_pmmr.leaf_pos_iter() { if let Some(out) = self.output_pmmr.get_data(pos) { commitments.push(out.commit); } } commitments } fn kernels_committed(&self) -> Vec<Commitment> { let mut commitments = vec![]; for n in 1..self.kernel_pmmr.unpruned_size() + 1 { if pmmr::is_leaf(n) { if let Some(kernel) = self.kernel_pmmr.get_data(n) { commitments.push(kernel.excess()); } } } commitments } } impl<'a> Extension<'a> { fn new(trees: &'a mut TxHashSet, head: Tip) -> Extension<'a> { Extension { head, output_pmmr: PMMR::at( &mut trees.output_pmmr_h.backend, trees.output_pmmr_h.last_pos, ), rproof_pmmr: PMMR::at( &mut trees.rproof_pmmr_h.backend, trees.rproof_pmmr_h.last_pos, ), kernel_pmmr: PMMR::at( &mut trees.kernel_pmmr_h.backend, trees.kernel_pmmr_h.last_pos, ), bitmap_accumulator: trees.bitmap_accumulator.clone(), rollback: false, } } /// The head representing the furthest extent of the current extension. pub fn head(&self) -> Tip { self.head.clone() } /// Build a view of the current UTXO set based on the output PMMR /// and the provided header extension. pub fn utxo_view(&'a self, header_ext: &'a HeaderExtension<'a>) -> UTXOView<'a> { UTXOView::new( self.output_pmmr.readonly_pmmr(), header_ext.pmmr.readonly_pmmr(), self.rproof_pmmr.readonly_pmmr(), ) } /// Apply a new block to the current txhashet extension (output, rangeproof, kernel MMRs). /// Returns a vec of commit_pos representing the pos and height of the outputs spent /// by this block. pub fn apply_block(&mut self, b: &Block, batch: &Batch<'_>) -> Result<Vec<CommitPos>, Error> { let mut affected_pos = vec![]; let mut spent = vec![]; // Apply the output to the output and rangeproof MMRs. // Add pos to affected_pos to update the accumulator later on. // Add the new output to the output_pos index. for out in b.outputs() { let pos = self.apply_output(out, batch)?; affected_pos.push(pos); batch.save_output_pos_height(&out.commitment(), pos, b.header.height)?; } // Remove the output from the output and rangeproof MMRs. // Add spent_pos to affected_pos to update the accumulator later on. // Remove the spent output from the output_pos index. for input in b.inputs() { let spent_pos = self.apply_input(input, batch)?; affected_pos.push(spent_pos.pos); batch.delete_output_pos_height(&input.commitment())?; spent.push(spent_pos); } for kernel in b.kernels() { self.apply_kernel(kernel)?; } // Update our BitmapAccumulator based on affected outputs (both spent and created). self.apply_to_bitmap_accumulator(&affected_pos)?; // Update the head of the extension to reflect the block we just applied. self.head = Tip::from_header(&b.header); Ok(spent) } fn apply_to_bitmap_accumulator(&mut self, output_pos: &[u64]) -> Result<(), Error> { let mut output_idx: Vec<_> = output_pos .iter() .map(|x| pmmr::n_leaves(*x).saturating_sub(1)) .collect(); output_idx.sort_unstable(); let min_idx = output_idx.first().cloned().unwrap_or(0); let size = pmmr::n_leaves(self.output_pmmr.last_pos); self.bitmap_accumulator.apply( output_idx, self.output_pmmr .leaf_idx_iter(BitmapAccumulator::chunk_start_idx(min_idx)), size, ) } fn apply_input(&mut self, input: &Input, batch: &Batch<'_>) -> Result<CommitPos, Error> { let commit = input.commitment(); if let Ok((pos, height)) = batch.get_output_pos_height(&commit) { // First check this input corresponds to an existing entry in the output MMR. if let Some(hash) = self.output_pmmr.get_hash(pos) { if hash != input.hash_with_index(pos - 1) { return Err( ErrorKind::TxHashSetErr("output pmmr hash mismatch".to_string()).into(), ); } } // Now prune the output_pmmr, rproof_pmmr and their storage. // Input is not valid if we cannot prune successfully (to spend an unspent // output). match self.output_pmmr.prune(pos) { Ok(true) => { self.rproof_pmmr .prune(pos) .map_err(|e| ErrorKind::TxHashSetErr(format!("pmmr prune error, {}", e)))?; Ok(CommitPos { pos, height }) } Ok(false) => Err(ErrorKind::AlreadySpent(commit).into()), Err(e) => Err(ErrorKind::TxHashSetErr(format!("commit prune error, {}", e)).into()), } } else { Err(ErrorKind::AlreadySpent(commit).into()) } } fn apply_output(&mut self, out: &Output, batch: &Batch<'_>) -> Result<u64, Error> { let commit = out.commitment(); if let Ok(pos) = batch.get_output_pos(&commit) { if let Some(out_mmr) = self.output_pmmr.get_data(pos) { if out_mmr.commitment() == commit { return Err(ErrorKind::DuplicateCommitment(commit).into()); } } } // push the new output to the MMR. let output_pos = self .output_pmmr .push(out) .map_err(|e| ErrorKind::TxHashSetErr(format!("pmmr output push error, {}", e)))?; // push the rangeproof to the MMR. let rproof_pos = self .rproof_pmmr .push(&out.proof) .map_err(|e| ErrorKind::TxHashSetErr(format!("pmmr proof push error, {}", e)))?; // The output and rproof MMRs should be exactly the same size // and we should have inserted to both in exactly the same pos. { if self.output_pmmr.unpruned_size() != self.rproof_pmmr.unpruned_size() { return Err( ErrorKind::Other("output vs rproof MMRs different sizes".to_string()).into(), ); } if output_pos != rproof_pos { return Err( ErrorKind::Other("output vs rproof MMRs different pos".to_string()).into(), ); } } Ok(output_pos) } /// Push kernel onto MMR (hash and data files). fn apply_kernel(&mut self, kernel: &TxKernel) -> Result<(), Error> { self.kernel_pmmr .push(kernel) .map_err(|e| ErrorKind::TxHashSetErr(format!("pmmr push kernel error, {}", e)))?; Ok(()) } /// Build a Merkle proof for the given output and the block /// this extension is currently referencing. /// Note: this relies on the MMR being stable even after pruning/compaction. /// We need the hash of each sibling pos from the pos up to the peak /// including the sibling leaf node which may have been removed. pub fn merkle_proof( &self, output: &OutputIdentifier, batch: &Batch<'_>, ) -> Result<MerkleProof, Error> { debug!("txhashset: merkle_proof: output: {:?}", output.commit,); // then calculate the Merkle Proof based on the known pos let pos = batch.get_output_pos(&output.commit)?; let merkle_proof = self.output_pmmr.merkle_proof(pos).map_err(|e| { ErrorKind::TxHashSetErr(format!("pmmr get merkle proof at pos {}, {}", pos, e)) })?; Ok(merkle_proof) } /// Saves a snapshot of the output and rangeproof MMRs to disk. /// Specifically - saves a snapshot of the utxo file, tagged with /// the block hash as filename suffix. /// Needed for fast-sync (utxo file needs to be rewound before sending /// across). pub fn snapshot(&mut self, batch: &Batch<'_>) -> Result<(), Error> { let header = batch.get_block_header(&self.head.last_block_h)?; self.output_pmmr .snapshot(&header) .map_err(|e| ErrorKind::Other(format!("pmmr snapshot error, {}", e)))?; self.rproof_pmmr .snapshot(&header) .map_err(|e| ErrorKind::Other(format!("pmmr snapshot error, {}", e)))?; Ok(()) } /// Rewinds the MMRs to the provided block, rewinding to the last output pos /// and last kernel pos of that block. pub fn rewind(&mut self, header: &BlockHeader, batch: &Batch<'_>) -> Result<(), Error> { debug!( "Rewind extension to {} at {} from {} at {}", header.hash(), header.height, self.head.hash(), self.head.height ); // We need to build bitmaps of added and removed output positions // so we can correctly rewind all operations applied to the output MMR // after the position we are rewinding to (these operations will be // undone during rewind). // Rewound output pos will be removed from the MMR. // Rewound input (spent) pos will be added back to the MMR. let head_header = batch.get_block_header(&self.head.hash())?; if head_header.height <= header.height { // Nothing to rewind but we do want to truncate the MMRs at header for consistency. self.rewind_mmrs_to_pos(header.output_mmr_size, header.kernel_mmr_size, &vec![])?; self.apply_to_bitmap_accumulator(&[header.output_mmr_size])?; } else { let mut affected_pos = vec![]; let mut current = head_header; while header.height < current.height { let mut affected_pos_single_block = self.rewind_single_block(&current, batch)?; affected_pos.append(&mut affected_pos_single_block); current = batch.get_previous_header(&current)?; } // Now apply a single aggregate "affected_pos" to our bitmap accumulator. self.apply_to_bitmap_accumulator(&affected_pos)?; } // Update our head to reflect the header we rewound to. self.head = Tip::from_header(header); Ok(()) } // Rewind the MMRs and the output_pos index. // Returns a vec of "affected_pos" so we can apply the necessary updates to the bitmap // accumulator in a single pass for all rewound blocks. fn rewind_single_block( &mut self, header: &BlockHeader, batch: &Batch<'_>, ) -> Result<Vec<u64>, Error> { // The spent index allows us to conveniently "unspend" everything in a block. let spent = batch.get_spent_index(&header.hash()); let spent_pos: Vec<_> = if let Ok(ref spent) = spent { spent.iter().map(|x| x.pos).collect() } else { warn!( "rewind_single_block: fallback to legacy input bitmap for block {} at {}", header.hash(), header.height ); let bitmap = batch.get_block_input_bitmap(&header.hash())?; bitmap.iter().map(|x| x.into()).collect() }; if header.height == 0 { self.rewind_mmrs_to_pos(0, 0, &spent_pos)?; } else { let prev = batch.get_previous_header(&header)?; self.rewind_mmrs_to_pos(prev.output_mmr_size, prev.kernel_mmr_size, &spent_pos)?; } // Update our BitmapAccumulator based on affected outputs. // We want to "unspend" every rewound spent output. // Treat last_pos as an affected output to ensure we rebuild far enough back. let mut affected_pos = spent_pos.clone(); affected_pos.push(self.output_pmmr.last_pos); // Remove any entries from the output_pos created by the block being rewound. let block = batch.get_block(&header.hash())?; let mut missing_count = 0; for out in block.outputs() { if batch.delete_output_pos_height(&out.commitment()).is_err() { missing_count += 1; } } if missing_count > 0 { warn!( "rewind_single_block: {} output_pos entries missing for: {} at {}", missing_count, header.hash(), header.height, ); } // Update output_pos based on "unspending" all spent pos from this block. // This is necessary to ensure the output_pos index correclty reflects a // reused output commitment. For example an output at pos 1, spent, reused at pos 2. // The output_pos index should be updated to reflect the old pos 1 when unspent. if let Ok(spent) = spent { for (x, y) in block.inputs().into_iter().zip(spent) { batch.save_output_pos_height(&x.commitment(), y.pos, y.height)?; } } Ok(affected_pos) } /// Rewinds the MMRs to the provided positions, given the output and /// kernel pos we want to rewind to. fn rewind_mmrs_to_pos( &mut self, output_pos: u64, kernel_pos: u64, spent_pos: &[u64], ) -> Result<(), Error> { let bitmap: Bitmap = spent_pos.into_iter().map(|x| *x as u32).collect(); self.output_pmmr .rewind(output_pos, &bitmap) .map_err(|e| ErrorKind::TxHashSetErr(format!("output_pmmr rewind error, {}", e)))?; self.rproof_pmmr .rewind(output_pos, &bitmap) .map_err(|e| ErrorKind::TxHashSetErr(format!("rproof_pmmr rewind error, {}", e)))?; self.kernel_pmmr .rewind(kernel_pos, &Bitmap::create()) .map_err(|e| ErrorKind::TxHashSetErr(format!("kernel_pmmr rewind error, {}", e)))?; Ok(()) } /// Current root hashes and sums (if applicable) for the Output, range proof /// and kernel MMRs. pub fn roots(&self) -> Result<TxHashSetRoots, Error> { Ok(TxHashSetRoots { output_roots: OutputRoots { pmmr_root: self .output_pmmr .root() .map_err(|e| ErrorKind::InvalidRoot(e))?, bitmap_root: self.bitmap_accumulator.root(), }, rproof_root: self .rproof_pmmr .root() .map_err(|e| ErrorKind::InvalidRoot(e))?, kernel_root: self .kernel_pmmr .root() .map_err(|e| ErrorKind::InvalidRoot(e))?, }) } /// Validate the MMR (output, rangeproof, kernel) roots against the latest header. pub fn validate_roots(&self, header: &BlockHeader) -> Result<(), Error> { if header.height == 0 { return Ok(()); } self.roots()?.validate(header) } /// Validate the header, output and kernel MMR sizes against the block header. pub fn validate_sizes(&self, header: &BlockHeader) -> Result<(), Error> { if header.height == 0 { return Ok(()); } if ( header.output_mmr_size, header.output_mmr_size, header.kernel_mmr_size, ) != self.sizes() { Err(ErrorKind::InvalidMMRSize.into()) } else { Ok(()) } } fn validate_mmrs(&self) -> Result<(), Error> { let now = Instant::now(); // validate all hashes and sums within the trees if let Err(e) = self.output_pmmr.validate() { return Err(ErrorKind::InvalidTxHashSet(e).into()); } if let Err(e) = self.rproof_pmmr.validate() { return Err(ErrorKind::InvalidTxHashSet(e).into()); } if let Err(e) = self.kernel_pmmr.validate() { return Err(ErrorKind::InvalidTxHashSet(e).into()); } debug!( "txhashset: validated the output {}, rproof {}, kernel {} mmrs, took {}s", self.output_pmmr.unpruned_size(), self.rproof_pmmr.unpruned_size(), self.kernel_pmmr.unpruned_size(), now.elapsed().as_secs(), ); Ok(()) } /// Validate full kernel sums against the provided header (for overage and kernel_offset). /// This is an expensive operation as we need to retrieve all the UTXOs and kernels /// from the respective MMRs. /// For a significantly faster way of validating full kernel sums see BlockSums. pub fn validate_kernel_sums( &self, genesis: &BlockHeader, header: &BlockHeader, ) -> Result<(Commitment, Commitment), Error> { let now = Instant::now(); let (utxo_sum, kernel_sum) = self.verify_kernel_sums( header.total_overage(genesis.kernel_mmr_size > 0), header.total_kernel_offset(), )?; debug!( "txhashset: validated total kernel sums, took {}s", now.elapsed().as_secs(), ); Ok((utxo_sum, kernel_sum)) } /// Validate the txhashset state against the provided block header. /// A "fast validation" will skip rangeproof verification and kernel signature verification. pub fn validate( &self, genesis: &BlockHeader, fast_validation: bool, status: &dyn TxHashsetWriteStatus, header: &BlockHeader, ) -> Result<(Commitment, Commitment), Error> { self.validate_mmrs()?; self.validate_roots(header)?; self.validate_sizes(header)?; if self.head.height == 0 { let zero_commit = secp_static::commit_to_zero_value(); return Ok((zero_commit, zero_commit)); } // The real magicking happens here. Sum of kernel excesses should equal // sum of unspent outputs minus total supply. let (output_sum, kernel_sum) = self.validate_kernel_sums(genesis, header)?; // These are expensive verification step (skipped for "fast validation"). if !fast_validation { // Verify the rangeproof associated with each unspent output. self.verify_rangeproofs(status)?; // Verify all the kernel signatures. self.verify_kernel_signatures(status)?; } Ok((output_sum, kernel_sum)) } /// Force the rollback of this extension, no matter the result pub fn force_rollback(&mut self) { self.rollback = true; } /// Dumps the output MMR. /// We use this after compacting for visual confirmation that it worked. pub fn dump_output_pmmr(&self) { debug!("-- outputs --"); self.output_pmmr.dump_from_file(false); debug!("--"); self.output_pmmr.dump_stats(); debug!("-- end of outputs --"); } /// Dumps the state of the 3 MMRs to stdout for debugging. Short /// version only prints the Output tree. pub fn dump(&self, short: bool) { debug!("-- outputs --"); self.output_pmmr.dump(short); if !short { debug!("-- range proofs --"); self.rproof_pmmr.dump(short); debug!("-- kernels --"); self.kernel_pmmr.dump(short); } } /// Sizes of each of the MMRs pub fn sizes(&self) -> (u64, u64, u64) { ( self.output_pmmr.unpruned_size(), self.rproof_pmmr.unpruned_size(), self.kernel_pmmr.unpruned_size(), ) } fn verify_kernel_signatures(&self, status: &dyn TxHashsetWriteStatus) -> Result<(), Error> { let now = Instant::now(); const KERNEL_BATCH_SIZE: usize = 5_000; let mut kern_count = 0; let total_kernels = pmmr::n_leaves(self.kernel_pmmr.unpruned_size()); let mut tx_kernels: Vec<TxKernel> = Vec::with_capacity(KERNEL_BATCH_SIZE); for n in 1..self.kernel_pmmr.unpruned_size() + 1 { if pmmr::is_leaf(n) { let kernel = self .kernel_pmmr .get_data(n) .ok_or_else(|| ErrorKind::TxKernelNotFound)?; tx_kernels.push(kernel); } if tx_kernels.len() >= KERNEL_BATCH_SIZE || n >= self.kernel_pmmr.unpruned_size() { TxKernel::batch_sig_verify(&tx_kernels)?; kern_count += tx_kernels.len() as u64; tx_kernels.clear(); status.on_validation_kernels(kern_count, total_kernels); debug!( "txhashset: verify_kernel_signatures: verified {} signatures", kern_count, ); } } debug!( "txhashset: verified {} kernel signatures, pmmr size {}, took {}s", kern_count, self.kernel_pmmr.unpruned_size(), now.elapsed().as_secs(), ); Ok(()) } fn verify_rangeproofs(&self, status: &dyn TxHashsetWriteStatus) -> Result<(), Error> { let now = Instant::now(); let mut commits: Vec<Commitment> = Vec::with_capacity(1_000); let mut proofs: Vec<RangeProof> = Vec::with_capacity(1_000); let mut proof_count = 0; let total_rproofs = self.output_pmmr.n_unpruned_leaves(); for pos in self.output_pmmr.leaf_pos_iter() { let output = self.output_pmmr.get_data(pos); let proof = self.rproof_pmmr.get_data(pos); // Output and corresponding rangeproof *must* exist. // It is invalid for either to be missing and we fail immediately in this case. match (output, proof) { (None, _) => { return Err(ErrorKind::OutputNotFound(format!( "at verify_rangeproofs for pos {}", pos )) .into()) } (_, None) => { return Err(ErrorKind::RangeproofNotFound(format!( "at verify_rangeproofs for pos {}", pos )) .into()) } (Some(output), Some(proof)) => { commits.push(output.commit); proofs.push(proof); } } proof_count += 1; if proofs.len() >= 1_000 { Output::batch_verify_proofs(&commits, &proofs)?; commits.clear(); proofs.clear(); info!( "txhashset: verify_rangeproofs: verified {} rangeproofs", proof_count, ); if proof_count % 1_000 == 0 { status.on_validation_rproofs(proof_count, total_rproofs); } } } // remaining part which not full of 1000 range proofs if !proofs.is_empty() { Output::batch_verify_proofs(&commits, &proofs)?; commits.clear(); proofs.clear(); info!( "txhashset: verify_rangeproofs: verified {} rangeproofs", proof_count, ); } debug!( "txhashset: verified {} rangeproofs, pmmr size {}, took {}s", proof_count, self.rproof_pmmr.unpruned_size(), now.elapsed().as_secs(), ); Ok(()) } } /// Packages the txhashset data files into a zip and returns a Read to the /// resulting file pub fn zip_read(root_dir: String, header: &BlockHeader) -> Result<File, Error> { let txhashset_zip = format!("{}_{}.zip", TXHASHSET_ZIP, header.hash().to_string()); let txhashset_path = Path::new(&root_dir).join(TXHASHSET_SUBDIR); let zip_path = Path::new(&root_dir).join(txhashset_zip); // if file exist, just re-use it let zip_file = File::open(zip_path.clone()); if let Ok(zip) = zip_file { debug!( "zip_read: {} at {}: reusing existing zip file: {:?}", header.hash(), header.height, zip_path ); return Ok(zip); } else { // clean up old zips. // Theoretically, we only need clean-up those zip files older than STATE_SYNC_THRESHOLD. // But practically, these zip files are not small ones, we just keep the zips in last 24 hours let data_dir = Path::new(&root_dir); let pattern = format!("{}_", TXHASHSET_ZIP); if let Ok(n) = clean_files_by_prefix(data_dir, &pattern, 24 * 60 * 60) { debug!( "{} zip files have been clean up in folder: {:?}", n, data_dir ); } } // otherwise, create the zip archive let path_to_be_cleanup = { // Temp txhashset directory let temp_txhashset_path = Path::new(&root_dir).join(format!( "{}_zip_{}", TXHASHSET_SUBDIR, header.hash().to_string() )); // Remove temp dir if it exist if temp_txhashset_path.exists() { fs::remove_dir_all(&temp_txhashset_path)?; } // Copy file to another dir file::copy_dir_to(&txhashset_path, &temp_txhashset_path)?; let zip_file = File::create(zip_path.clone())?; // Explicit list of files to add to our zip archive. let files = file_list(header); zip::create_zip(&zip_file, &temp_txhashset_path, files)?; temp_txhashset_path }; debug!( "zip_read: {} at {}: created zip file: {:?}", header.hash(), header.height, zip_path ); // open it again to read it back let zip_file = File::open(zip_path.clone())?; // clean-up temp txhashset directory. if let Err(e) = fs::remove_dir_all(&path_to_be_cleanup) { warn!( "txhashset zip file: {:?} fail to remove, err: {}", zip_path.to_str(), e ); } Ok(zip_file) } // Explicit list of files to extract from our zip archive. // We include *only* these files when building the txhashset zip. // We extract *only* these files when receiving a txhashset zip. // Everything else will be safely ignored. // Return Vec<PathBuf> as some of these are dynamic (specifically the "rewound" leaf files). fn file_list(header: &BlockHeader) -> Vec<PathBuf> { vec![ // kernel MMR PathBuf::from("kernel/pmmr_data.bin"), PathBuf::from("kernel/pmmr_hash.bin"), // output MMR PathBuf::from("output/pmmr_data.bin"), PathBuf::from("output/pmmr_hash.bin"), PathBuf::from("output/pmmr_prun.bin"), // rangeproof MMR PathBuf::from("rangeproof/pmmr_data.bin"), PathBuf::from("rangeproof/pmmr_hash.bin"), PathBuf::from("rangeproof/pmmr_prun.bin"), // Header specific "rewound" leaf files for output and rangeproof MMR. PathBuf::from(format!("output/pmmr_leaf.bin.{}", header.hash())), PathBuf::from(format!("rangeproof/pmmr_leaf.bin.{}", header.hash())), ] } /// Extract the txhashset data from a zip file and writes the content into the /// txhashset storage dir pub fn zip_write( root_dir: PathBuf, txhashset_data: File, header: &BlockHeader, ) -> Result<(), Error> { debug!("zip_write on path: {:?}", root_dir); let txhashset_path = root_dir.join(TXHASHSET_SUBDIR); fs::create_dir_all(&txhashset_path)?; // Explicit list of files to extract from our zip archive. let files = file_list(header); // We expect to see *exactly* the paths listed above. // No attempt is made to be permissive or forgiving with "alternative" paths. // These are the *only* files we will attempt to extract from the zip file. // If any of these are missing we will attempt to continue as some are potentially optional. zip::extract_files(txhashset_data, &txhashset_path, files)?; Ok(()) } /// Overwrite txhashset folders in "to" folder with "from" folder pub fn txhashset_replace(from: PathBuf, to: PathBuf) -> Result<(), Error> { debug!("txhashset_replace: move from {:?} to {:?}", from, to); // clean the 'to' folder firstly clean_txhashset_folder(&to); // rename the 'from' folder as the 'to' folder if let Err(e) = fs::rename(from.join(TXHASHSET_SUBDIR), to.join(TXHASHSET_SUBDIR)) { error!("hashset_replace fail on {}. err: {}", TXHASHSET_SUBDIR, e); Err(ErrorKind::TxHashSetErr("txhashset replacing fail".to_string()).into()) } else { Ok(()) } } /// Clean the txhashset folder pub fn clean_txhashset_folder(root_dir: &PathBuf) { let txhashset_path = root_dir.clone().join(TXHASHSET_SUBDIR); if txhashset_path.exists() { if let Err(e) = fs::remove_dir_all(txhashset_path.clone()) { warn!( "clean_txhashset_folder: fail on {:?}. err: {}", txhashset_path, e ); } } } /// Given a block header to rewind to and the block header at the /// head of the current chain state, we need to calculate the positions /// of all inputs (spent outputs) we need to "undo" during a rewind. /// We do this by leveraging the "block_input_bitmap" cache and OR'ing /// the set of bitmaps together for the set of blocks being rewound. fn input_pos_to_rewind( block_header: &BlockHeader, head_header: &BlockHeader, batch: &Batch<'_>, ) -> Result<Bitmap, Error> { let mut bitmap = Bitmap::create(); let mut current = head_header.clone(); while current.height > block_header.height { if let Ok(block_bitmap) = batch.get_block_input_bitmap(&current.hash()) { bitmap.or_inplace(&block_bitmap); } current = batch.get_previous_header(&current)?; } Ok(bitmap) }
// Update our bitmap_accumulator based on our extension trees.bitmap_accumulator = bitmap_accumulator; }
validators.js
export const isValidWidthUnit = (val) => ['px', 'rem', 'em', 'vw', '%', 'vmin', 'vmax'].some(unit => val.endsWith(unit), )
export const isValidComponentSize = (val) => ['', 'large', 'medium', 'small', 'mini'].includes(val)
replay.py
#!/usr/bin/env python # Copyright 2010 Google 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 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. """Replays web pages under simulated network conditions. Must be run as administrator (sudo). To record web pages: 1. Start the program in record mode. $ sudo ./replay.py --record archive.wpr 2. Load the web pages you want to record in a web browser. It is important to clear browser caches before this so that all subresources are requested from the network. 3. Kill the process to stop recording. To replay web pages: 1. Start the program in replay mode with a previously recorded archive. $ sudo ./replay.py archive.wpr 2. Load recorded pages in a web browser. A 404 will be served for any pages or resources not in the recorded archive. Network simulation examples: # 128KByte/s uplink bandwidth, 4Mbps/s downlink bandwidth with 100ms RTT time $ sudo ./replay.py --up 128KByte/s --down 4Mbit/s --delay_ms=100 archive.wpr # 1% packet loss rate $ sudo ./replay.py --packet_loss_rate=0.01 archive.wpr """ import argparse import json import logging import os import socket import sys import traceback import customhandlers import dnsproxy import httparchive import httpclient import httpproxy import net_configs import platformsettings import rules_parser import script_injector import servermanager import trafficshaper if sys.version < '2.6': print 'Need Python 2.6 or greater.' sys.exit(1) def configure_logging(log_level_name, log_file_name=None): """Configure logging level and format. Args: log_level_name: 'debug', 'info', 'warning', 'error', or 'critical'. log_file_name: a file name """ if logging.root.handlers: logging.critical('A logging method (e.g. "logging.warn(...)")' ' was called before logging was configured.') log_level = getattr(logging, log_level_name.upper()) log_format = ( '(%(levelname)s) %(asctime)s %(module)s.%(funcName)s:%(lineno)d ' '%(message)s') logging.basicConfig(level=log_level, format=log_format) logger = logging.getLogger() if log_file_name: fh = logging.FileHandler(log_file_name) fh.setLevel(log_level) fh.setFormatter(logging.Formatter(log_format)) logger.addHandler(fh) system_handler = platformsettings.get_system_logging_handler() if system_handler: logger.addHandler(system_handler) def AddDnsForward(server_manager, host): """Forward DNS traffic.""" server_manager.Append(platformsettings.set_temporary_primary_nameserver, host) def AddDnsProxy(server_manager, options, host, port, real_dns_lookup, http_archive): dns_filters = [] if options.dns_private_passthrough: private_filter = dnsproxy.PrivateIpFilter(real_dns_lookup, http_archive) dns_filters.append(private_filter) server_manager.AppendRecordCallback(private_filter.InitializeArchiveHosts) server_manager.AppendReplayCallback(private_filter.InitializeArchiveHosts) if options.shaping_dns: delay_filter = dnsproxy.DelayFilter(options.record, **options.shaping_dns) dns_filters.append(delay_filter) server_manager.AppendRecordCallback(delay_filter.SetRecordMode) server_manager.AppendReplayCallback(delay_filter.SetReplayMode) server_manager.Append(dnsproxy.DnsProxyServer, host, port, dns_lookup=dnsproxy.ReplayDnsLookup(host, dns_filters)) def AddWebProxy(server_manager, options, host, real_dns_lookup, http_archive): if options.rules_path: with open(options.rules_path) as file_obj: allowed_imports = [ name.strip() for name in options.allowed_rule_imports.split(',')] rules = rules_parser.Rules(file_obj, allowed_imports) logging.info('Parsed %s rules:\n%s', options.rules_path, rules) else: rules = rules_parser.Rules() injector = script_injector.GetScriptInjector(options.inject_scripts) custom_handlers = customhandlers.CustomHandlers(options, http_archive) custom_handlers.add_server_manager_handler(server_manager) archive_fetch = httpclient.ControllableHttpArchiveFetch( http_archive, real_dns_lookup, injector, options.diff_unknown_requests, options.record, use_closest_match=options.use_closest_match, scramble_images=options.scramble_images) server_manager.AppendRecordCallback(archive_fetch.SetRecordMode) server_manager.AppendReplayCallback(archive_fetch.SetReplayMode) allow_generate_304 = not options.record server_manager.Append( httpproxy.HttpProxyServer, archive_fetch, custom_handlers, rules, host=host, port=options.port, use_delays=options.use_server_delay, allow_generate_304=allow_generate_304, **options.shaping_http) if options.ssl: if options.should_generate_certs: server_manager.Append( httpproxy.HttpsProxyServer, archive_fetch, custom_handlers, rules, options.https_root_ca_cert_path, host=host, port=options.ssl_port, allow_generate_304=allow_generate_304, use_delays=options.use_server_delay, **options.shaping_http) else: server_manager.Append( httpproxy.SingleCertHttpsProxyServer, archive_fetch, custom_handlers, rules, options.https_root_ca_cert_path, host=host, port=options.ssl_port, use_delays=options.use_server_delay, allow_generate_304=allow_generate_304, **options.shaping_http) if options.http_to_https_port: server_manager.Append( httpproxy.HttpToHttpsProxyServer, archive_fetch, custom_handlers, rules, host=host, port=options.http_to_https_port, use_delays=options.use_server_delay, allow_generate_304=allow_generate_304, **options.shaping_http) def AddTrafficShaper(server_manager, options, host): if options.shaping_dummynet: server_manager.AppendTrafficShaper( trafficshaper.TrafficShaper, host=host, use_loopback=not options.server_mode and host == '127.0.0.1', **options.shaping_dummynet) class OptionsWrapper(object): """Add checks, updates, and methods to option values. Example: options, args = arg_parser.parse_args() options = OptionsWrapper(options, arg_parser) # run checks and updates if options.record and options.HasTrafficShaping(): [...] """ _TRAFFICSHAPING_OPTIONS = { 'down', 'up', 'delay_ms', 'packet_loss_rate', 'init_cwnd', 'net'} _CONFLICTING_OPTIONS = ( ('record', ('down', 'up', 'delay_ms', 'packet_loss_rate', 'net', 'spdy', 'use_server_delay')), ('append', ('down', 'up', 'delay_ms', 'packet_loss_rate', 'net', 'use_server_delay')), # same as --record ('net', ('down', 'up', 'delay_ms')), ('server', ('server_mode',)), ) def __init__(self, options, parser): self._options = options self._parser = parser self._nondefaults = set([ action.dest for action in parser._optionals._actions if getattr(options, action.dest, action.default) is not action.default]) self._CheckConflicts() self._CheckValidIp('host') self._CheckFeatureSupport() self._MassageValues() def _CheckConflicts(self): """Give an error if mutually exclusive options are used.""" for option, bad_options in self._CONFLICTING_OPTIONS: if option in self._nondefaults: for bad_option in bad_options: if bad_option in self._nondefaults: self._parser.error('Option --%s cannot be used with --%s.' % (bad_option, option)) def _CheckValidIp(self, name): """Give an error if option |name| is not a valid IPv4 address.""" value = getattr(self._options, name) if value: try: socket.inet_aton(value) except Exception: self._parser.error('Option --%s must be a valid IPv4 address.' % name) def _CheckFeatureSupport(self): if (self._options.should_generate_certs and not platformsettings.HasSniSupport()): self._parser.error('Option --should_generate_certs requires pyOpenSSL ' '0.13 or greater for SNI support.') def _ShapingKeywordArgs(self, shaping_key): """Return the shaping keyword args for |shaping_key|. Args: shaping_key: one of 'dummynet', 'dns', 'http'. Returns: {} # if shaping_key does not apply, or options have default values. {k: v, ...} """ kwargs = {} def AddItemIfSet(d, kw_key, opt_key=None): opt_key = opt_key or kw_key if opt_key in self._nondefaults: d[kw_key] = getattr(self, opt_key) if ((self.shaping_type == 'proxy' and shaping_key in ('dns', 'http')) or self.shaping_type == shaping_key): AddItemIfSet(kwargs, 'delay_ms') if shaping_key in ('dummynet', 'http'): AddItemIfSet(kwargs, 'down_bandwidth', opt_key='down') AddItemIfSet(kwargs, 'up_bandwidth', opt_key='up') if shaping_key == 'dummynet': AddItemIfSet(kwargs, 'packet_loss_rate') AddItemIfSet(kwargs, 'init_cwnd') elif self.shaping_type != 'none': if 'packet_loss_rate' in self._nondefaults: logging.warn('Shaping type, %s, ignores --packet_loss_rate=%s', self.shaping_type, self.packet_loss_rate) if 'init_cwnd' in self._nondefaults: logging.warn('Shaping type, %s, ignores --init_cwnd=%s', self.shaping_type, self.init_cwnd) return kwargs def _MassageValues(self): """Set options that depend on the values of other options.""" if self.append and not self.record: self._options.record = True if self.net: self._options.down, self._options.up, self._options.delay_ms = \ net_configs.GetNetConfig(self.net) self._nondefaults.update(['down', 'up', 'delay_ms']) if not self.ssl: self._options.https_root_ca_cert_path = None self.shaping_dns = self._ShapingKeywordArgs('dns') self.shaping_http = self._ShapingKeywordArgs('http') self.shaping_dummynet = self._ShapingKeywordArgs('dummynet') def __getattr__(self, name): """Make the original option values available.""" return getattr(self._options, name) def __repr__(self): """Return a json representation of the original options dictionary.""" return json.dumps(self._options.__dict__) def IsRootRequired(self): """Returns True iff the options require whole program root access.""" if self.server: return True def IsPrivilegedPort(port):
if IsPrivilegedPort(self.port) or (self.ssl and IsPrivilegedPort(self.ssl_port)): return True if self.dns_forwarding: if IsPrivilegedPort(self.dns_port): return True if not self.server_mode and self.host == '127.0.0.1': return True return False def replay(options, replay_filename): if options.record and sys.version_info < (2, 7, 9): print ('Need Python 2.7.9 or greater for recording mode.\n' 'For instructions on how to upgrade Python on Ubuntu 14.04, see:\n' 'http://mbless.de/blog/2016/01/09/upgrade-to-python-2711-on-ubuntu-1404-lts.html\n') if options.admin_check and options.IsRootRequired(): platformsettings.rerun_as_administrator() configure_logging(options.log_level, options.log_file) server_manager = servermanager.ServerManager(options.record) if options.server: AddDnsForward(server_manager, options.server) else: if options.record: httparchive.HttpArchive.AssertWritable(replay_filename) if options.append and os.path.exists(replay_filename): http_archive = httparchive.HttpArchive.Load(replay_filename) logging.info('Appending to %s (loaded %d existing responses)', replay_filename, len(http_archive)) else: http_archive = httparchive.HttpArchive() else: http_archive = httparchive.HttpArchive.Load(replay_filename) logging.info('Loaded %d responses from %s', len(http_archive), replay_filename) server_manager.AppendRecordCallback(http_archive.clear) ipfw_dns_host = None if options.dns_forwarding or options.shaping_dummynet: # compute the ip/host used for the DNS server and traffic shaping ipfw_dns_host = options.host if not ipfw_dns_host: ipfw_dns_host = platformsettings.get_server_ip_address( options.server_mode) real_dns_lookup = dnsproxy.RealDnsLookup( name_servers=[platformsettings.get_original_primary_nameserver()], dns_forwarding=options.dns_forwarding, proxy_host=ipfw_dns_host, proxy_port=options.dns_port) server_manager.AppendRecordCallback(real_dns_lookup.ClearCache) if options.dns_forwarding: if not options.server_mode and ipfw_dns_host == '127.0.0.1': AddDnsForward(server_manager, ipfw_dns_host) AddDnsProxy(server_manager, options, ipfw_dns_host, options.dns_port, real_dns_lookup, http_archive) if options.ssl and options.https_root_ca_cert_path is None: options.https_root_ca_cert_path = os.path.join(os.path.dirname(__file__), 'wpr_cert.pem') http_proxy_address = options.host if not http_proxy_address: http_proxy_address = platformsettings.get_httpproxy_ip_address( options.server_mode) AddWebProxy(server_manager, options, http_proxy_address, real_dns_lookup, http_archive) AddTrafficShaper(server_manager, options, ipfw_dns_host) exit_status = 0 try: server_manager.Run() except KeyboardInterrupt: logging.info('Shutting down.') except (dnsproxy.DnsProxyException, trafficshaper.TrafficShaperException, platformsettings.NotAdministratorError, platformsettings.DnsUpdateError) as e: logging.critical('%s: %s', e.__class__.__name__, e) exit_status = 1 except Exception: logging.critical(traceback.format_exc()) exit_status = 2 if options.record: http_archive.Persist(replay_filename) logging.info('Saved %d responses to %s', len(http_archive), replay_filename) return exit_status def GetParser(): arg_parser = argparse.ArgumentParser( usage='%(prog)s [options] replay_file', description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, epilog='http://code.google.com/p/web-page-replay/') arg_parser.add_argument('replay_filename', type=str, help='Replay file', nargs='?') arg_parser.add_argument('-r', '--record', default=False, action='store_true', help='Download real responses and record them to replay_file') arg_parser.add_argument('--append', default=False, action='store_true', help='Append responses to replay_file.') arg_parser.add_argument('-l', '--log_level', default='debug', action='store', type=str, choices=('debug', 'info', 'warning', 'error', 'critical'), help='Minimum verbosity level to log') arg_parser.add_argument('-f', '--log_file', default=None, action='store', type=str, help='Log file to use in addition to writting logs to stderr.') network_group = arg_parser.add_argument_group( title='Network Simulation Options', description=('These options configure the network simulation in ' 'replay mode')) network_group.add_argument('-u', '--up', default='0', action='store', type=str, help='Upload Bandwidth in [K|M]{bit/s|Byte/s}. Zero means unlimited.') network_group.add_argument('-d', '--down', default='0', action='store', type=str, help='Download Bandwidth in [K|M]{bit/s|Byte/s}. Zero means unlimited.') network_group.add_argument('-m', '--delay_ms', default='0', action='store', type=str, help='Propagation delay (latency) in milliseconds. Zero means no delay.') network_group.add_argument('-p', '--packet_loss_rate', default='0', action='store', type=str, help='Packet loss rate in range [0..1]. Zero means no loss.') network_group.add_argument('-w', '--init_cwnd', default='0', action='store', type=str, help='Set initial cwnd (linux only, requires kernel patch)') network_group.add_argument('--net', default=None, action='store', type=str, choices=net_configs.NET_CONFIG_NAMES, help='Select a set of network options: %s.' % ', '.join( net_configs.NET_CONFIG_NAMES)) network_group.add_argument('--shaping_type', default='dummynet', action='store', choices=('dummynet', 'proxy'), help='When shaping is configured (i.e. --up, --down, etc.) decides ' 'whether to use |dummynet| (default), or |proxy| servers.') harness_group = arg_parser.add_argument_group( title='Replay Harness Options', description=('These advanced options configure various aspects ' 'of the replay harness')) harness_group.add_argument('-S', '--server', default=None, action='store', type=str, help='IP address of host running "replay.py --server_mode". ' 'This only changes the primary DNS nameserver to use the given IP.') harness_group.add_argument('-M', '--server_mode', default=False, action='store_true', help='Run replay DNS & http proxies, and trafficshaping on --port ' 'without changing the primary DNS nameserver. ' 'Other hosts may connect to this using "replay.py --server" ' 'or by pointing their DNS to this server.') harness_group.add_argument('-i', '--inject_scripts', default='deterministic.js', action='store', dest='inject_scripts', help='A comma separated list of JavaScript sources to inject in all ' 'pages. By default a script is injected that eliminates sources ' 'of entropy such as Date() and Math.random() deterministic. ' 'CAUTION: Without deterministic.js, many pages will not replay.') harness_group.add_argument('-D', '--no-diff_unknown_requests', default=True, action='store_false', dest='diff_unknown_requests', help='During replay, do not show a diff of unknown requests against ' 'their nearest match in the archive.') harness_group.add_argument('-C', '--use_closest_match', default=False, action='store_true', dest='use_closest_match', help='During replay, if a request is not found, serve the closest match' 'in the archive instead of giving a 404.') harness_group.add_argument('-U', '--use_server_delay', default=False, action='store_true', dest='use_server_delay', help='During replay, simulate server delay by delaying response time to' 'requests.') harness_group.add_argument('-I', '--screenshot_dir', default=None, action='store', type=str, help='Save PNG images of the loaded page in the given directory.') harness_group.add_argument('-P', '--no-dns_private_passthrough', default=True, action='store_false', dest='dns_private_passthrough', help='Don\'t forward DNS requests that resolve to private network ' 'addresses. CAUTION: With this option important services like ' 'Kerberos will resolve to the HTTP proxy address.') harness_group.add_argument('-x', '--no-dns_forwarding', default=True, action='store_false', dest='dns_forwarding', help='Don\'t forward DNS requests to the local replay server. ' 'CAUTION: With this option an external mechanism must be used to ' 'forward traffic to the replay server.') harness_group.add_argument('--host', default=None, action='store', type=str, help='The IP address to bind all servers to. Defaults to 0.0.0.0 or ' '127.0.0.1, depending on --server_mode and platform.') harness_group.add_argument('-o', '--port', default=80, action='store', type=int, help='Port number to listen on.') harness_group.add_argument('--ssl_port', default=443, action='store', type=int, help='SSL port number to listen on.') harness_group.add_argument('--http_to_https_port', default=None, action='store', type=int, help='Port on which WPR will listen for HTTP requests that it will send ' 'along as HTTPS requests.') harness_group.add_argument('--dns_port', default=53, action='store', type=int, help='DNS port number to listen on.') harness_group.add_argument('-c', '--https_root_ca_cert_path', default=None, action='store', type=str, help='Certificate file to use with SSL (gets auto-generated if needed).') harness_group.add_argument('--no-ssl', default=True, action='store_false', dest='ssl', help='Do not setup an SSL proxy.') harness_group.add_argument('--should_generate_certs', default=False, action='store_true', help='Use OpenSSL to generate certificate files for requested hosts.') harness_group.add_argument('--no-admin-check', default=True, action='store_false', dest='admin_check', help='Do not check if administrator access is needed.') harness_group.add_argument('--scramble_images', default=False, action='store_true', dest='scramble_images', help='Scramble image responses.') harness_group.add_argument('--rules_path', default=None, action='store', help='Path of file containing Python rules.') harness_group.add_argument('--allowed_rule_imports', default='rules', action='store', help='A comma-separate list of allowed rule imports, or \'*\' to allow' ' all packages. Defaults to %(default)s.') return arg_parser def main(): arg_parser = GetParser() options = arg_parser.parse_args() options = OptionsWrapper(options, arg_parser) if options.server: options.replay_filename = None elif options.replay_filename is None: arg_parser.error('Must specify a replay_file') return replay(options, options.replay_filename) if __name__ == '__main__': sys.exit(main())
return port and port < 1024
sum.rs
#![crate_name = "uu_sum"] /* * This file is part of the uutils coreutils package. * * (c) T. Jameson Little <[email protected]> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uucore; use std::fs::File; use std::io::{stdin, Read, Result}; use std::path::Path; static NAME: &str = "sum"; static VERSION: &str = env!("CARGO_PKG_VERSION"); fn bsd_sum(mut reader: Box<dyn Read>) -> (usize, u16) { let mut buf = [0; 1024]; let mut blocks_read = 0; let mut checksum: u16 = 0; loop { match reader.read(&mut buf) { Ok(n) if n != 0 => { blocks_read += 1; for &byte in buf[..n].iter() { checksum = (checksum >> 1) + ((checksum & 1) << 15); checksum = checksum.wrapping_add(u16::from(byte)); } } _ => break, } } (blocks_read, checksum) } fn sysv_sum(mut reader: Box<dyn Read>) -> (usize, u16) { let mut buf = [0; 512]; let mut blocks_read = 0; let mut ret = 0u32; loop { match reader.read(&mut buf) { Ok(n) if n != 0 => { blocks_read += 1; for &byte in buf[..n].iter() { ret = ret.wrapping_add(u32::from(byte)); } } _ => break, } } ret = (ret & 0xffff) + (ret >> 16); ret = (ret & 0xffff) + (ret >> 16); (blocks_read, ret as u16) } fn open(name: &str) -> Result<Box<dyn Read>> { match name { "-" => Ok(Box::new(stdin()) as Box<dyn Read>), _ => { let f = File::open(&Path::new(name))?; Ok(Box::new(f) as Box<dyn Read>) } } } pub fn
(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("r", "", "use the BSD compatible algorithm (default)"); opts.optflag("s", "sysv", "use System V compatible algorithm"); opts.optflag("h", "help", "show this help message"); opts.optflag("v", "version", "print the version and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => crash!(1, "Invalid options\n{}", f), }; if matches.opt_present("help") { let msg = format!( "{0} {1} Usage: {0} [OPTION]... [FILE]... Checksum and count the blocks in a file.", NAME, VERSION ); println!( "{}\nWith no FILE, or when FILE is -, read standard input.", opts.usage(&msg) ); return 0; } if matches.opt_present("version") { println!("{} {}", NAME, VERSION); return 0; } let sysv = matches.opt_present("sysv"); let files = if matches.free.is_empty() { vec!["-".to_owned()] } else { matches.free }; let print_names = if sysv { files.len() > 1 || files[0] != "-" } else { files.len() > 1 }; for file in &files { let reader = match open(file) { Ok(f) => f, _ => crash!(1, "unable to open file"), }; let (blocks, sum) = if sysv { sysv_sum(reader) } else { bsd_sum(reader) }; if print_names { println!("{} {} {}", sum, blocks, file); } else { println!("{} {}", sum, blocks); } } 0 }
uumain
jinja2htmlcompress.py
# -*- coding: utf-8 -*- """ jinja2htmlcompress ~~~~~~~~~~~~~~~~~~ A Jinja2 extension that eliminates useless whitespace at template compilation time without extra overhead. :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. https://github.com/mitsuhiko/jinja2-htmlcompress """ import re from jinja2.ext import Extension from jinja2.lexer import Token, describe_token from jinja2 import TemplateSyntaxError _tag_re = re.compile(r'(?:<(/?)([a-zA-Z0-9_-]+)\s*|(>\s*))(?s)') _ws_normalize_re = re.compile(r'[ \t\r\n]+') class StreamProcessContext(object): def __init__(self, stream): self.stream = stream self.token = None self.stack = [] def fail(self, message): raise TemplateSyntaxError(message, self.token.lineno, self.stream.name, self.stream.filename) def _make_dict_from_listing(listing): rv = {}
for key in keys: rv[key] = value return rv class HTMLCompress(Extension): isolated_elements = set(['script', 'style', 'noscript', 'textarea']) void_elements = set(['br', 'img', 'area', 'hr', 'param', 'input', 'embed', 'col']) block_elements = set(['div', 'p', 'form', 'ul', 'ol', 'li', 'table', 'tr', 'tbody', 'thead', 'tfoot', 'tr', 'td', 'th', 'dl', 'dt', 'dd', 'blockquote', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre']) breaking_rules = _make_dict_from_listing([ (['p'], set(['#block'])), (['li'], set(['li'])), (['td', 'th'], set(['td', 'th', 'tr', 'tbody', 'thead', 'tfoot'])), (['tr'], set(['tr', 'tbody', 'thead', 'tfoot'])), (['thead', 'tbody', 'tfoot'], set(['thead', 'tbody', 'tfoot'])), (['dd', 'dt'], set(['dl', 'dt', 'dd'])) ]) def is_isolated(self, stack): for tag in reversed(stack): if tag in self.isolated_elements: return True return False def is_breaking(self, tag, other_tag): breaking = self.breaking_rules.get(other_tag) return breaking and (tag in breaking or ('#block' in breaking and tag in self.block_elements)) def enter_tag(self, tag, ctx): while ctx.stack and self.is_breaking(tag, ctx.stack[-1]): self.leave_tag(ctx.stack[-1], ctx) if tag not in self.void_elements: ctx.stack.append(tag) def leave_tag(self, tag, ctx): if not ctx.stack: ctx.fail('Tried to leave "%s" but something closed ' 'it already' % tag) if tag == ctx.stack[-1]: ctx.stack.pop() return for idx, other_tag in enumerate(reversed(ctx.stack)): if other_tag == tag: for num in xrange(idx + 1): ctx.stack.pop() elif not self.breaking_rules.get(other_tag): break def normalize(self, ctx): pos = 0 buffer = [] def write_data(value): if not self.is_isolated(ctx.stack): value = _ws_normalize_re.sub(' ', value.strip()) buffer.append(value) for match in _tag_re.finditer(ctx.token.value): closes, tag, sole = match.groups() preamble = ctx.token.value[pos:match.start()] write_data(preamble) if sole: write_data(sole) else: buffer.append(match.group()) (closes and self.leave_tag or self.enter_tag)(tag, ctx) pos = match.end() write_data(ctx.token.value[pos:]) return u''.join(buffer) def filter_stream(self, stream): ctx = StreamProcessContext(stream) for token in stream: if token.type != 'data': yield token continue ctx.token = token value = self.normalize(ctx) yield Token(token.lineno, 'data', value) class SelectiveHTMLCompress(HTMLCompress): def filter_stream(self, stream): ctx = StreamProcessContext(stream) strip_depth = 0 while 1: if stream.current.type == 'block_begin': if stream.look().test('name:strip') or \ stream.look().test('name:endstrip'): stream.skip() if stream.current.value == 'strip': strip_depth += 1 else: strip_depth -= 1 if strip_depth < 0: ctx.fail('Unexpected tag endstrip') stream.skip() if stream.current.type != 'block_end': ctx.fail('expected end of block, got %s' % describe_token(stream.current)) stream.skip() if strip_depth > 0 and stream.current.type == 'data': ctx.token = stream.current value = self.normalize(ctx) yield Token(stream.current.lineno, 'data', value) else: yield stream.current stream.next() def test(): from jinja2 import Environment env = Environment(extensions=[HTMLCompress]) tmpl = env.from_string(''' <html> <head> <title>{{ title }}</title> </head> <script type=text/javascript> if (foo < 42) { document.write('Foo < Bar'); } </script> <body> <li><a href="{{ href }}">{{ title }}</a><br>Test Foo <li><a href="{{ href }}">{{ title }}</a><img src=test.png> </body> </html> ''') print tmpl.render(title=42, href='index.html') env = Environment(extensions=[SelectiveHTMLCompress]) tmpl = env.from_string(''' Normal <span> unchanged </span> stuff {% strip %}Stripped <span class=foo > test </span> <a href="foo"> test </a> {{ foo }} Normal <stuff> again {{ foo }} </stuff> <p> Foo<br>Bar Baz <p> Moep <span>Test</span> Moep </p> {% endstrip %} ''') print tmpl.render(foo=42) if __name__ == '__main__': test()
for keys, value in listing:
main.rs
use std::cell::Cell; use std::fs; use std::io::Write; use actix_multipart::{Field, Multipart, MultipartError}; use actix_web::{error, middleware, web, App, Error, HttpResponse, HttpServer}; use futures::future::{err, Either}; use futures::{Future, Stream}; pub struct
{ pub counter: Cell<usize>, } pub fn save_file(field: Field) -> impl Future<Item = i64, Error = Error> { let file_path_string = "upload.png"; let file = match fs::File::create(file_path_string) { Ok(file) => file, Err(e) => return Either::A(err(error::ErrorInternalServerError(e))), }; Either::B( field .fold((file, 0i64), move |(mut file, mut acc), bytes| { // fs operations are blocking, we have to execute writes // on threadpool web::block(move || { file.write_all(bytes.as_ref()).map_err(|e| { println!("file.write_all failed: {:?}", e); MultipartError::Payload(error::PayloadError::Io(e)) })?; acc += bytes.len() as i64; Ok((file, acc)) }) .map_err(|e: error::BlockingError<MultipartError>| { match e { error::BlockingError::Error(e) => e, error::BlockingError::Canceled => MultipartError::Incomplete, } }) }) .map(|(_, acc)| acc) .map_err(|e| { println!("save_file failed, {:?}", e); error::ErrorInternalServerError(e) }), ) } pub fn upload( multipart: Multipart, counter: web::Data<Cell<usize>>, ) -> impl Future<Item = HttpResponse, Error = Error> { counter.set(counter.get() + 1); println!("{:?}", counter.get()); multipart .map_err(error::ErrorInternalServerError) .map(|field| save_file(field).into_stream()) .flatten() .collect() .map(|sizes| HttpResponse::Ok().json(sizes)) .map_err(|e| { println!("failed: {}", e); e }) } fn index() -> HttpResponse { let html = r#"<html> <head><title>Upload Test</title></head> <body> <form target="/" method="post" enctype="multipart/form-data"> <input type="file" name="file"/> <input type="submit" value="Submit"></button> </form> </body> </html>"#; HttpResponse::Ok().body(html) } fn main() -> std::io::Result<()> { std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info"); env_logger::init(); HttpServer::new(|| { App::new() .data(Cell::new(0usize)) .wrap(middleware::Logger::default()) .service( web::resource("/") .route(web::get().to(index)) .route(web::post().to_async(upload)), ) }) .bind("127.0.0.1:8080")? .run() }
AppState
factor.py
""" factor.py """ from functools import wraps from operator import attrgetter from numbers import Number from numpy import inf, where from toolz import curry from zipline.errors import UnknownRankMethod from zipline.lib.normalize import naive_grouped_rowwise_apply from zipline.lib.rank import masked_rankdata_2d from zipline.pipeline.classifiers import Classifier, Everything, Quantiles from zipline.pipeline.mixins import ( CustomTermMixin, LatestMixin, PositiveWindowLengthMixin, RestrictedDTypeMixin, SingleInputMixin, ) from zipline.pipeline.term import ( ComputableTerm, NotSpecified, NotSpecifiedType, Term, ) from zipline.pipeline.expression import ( BadBinaryOperator, COMPARISONS, is_comparison, MATH_BINOPS, method_name_for_op, NumericalExpression, NUMEXPR_MATH_FUNCS, UNARY_OPS, unary_op_name, ) from zipline.pipeline.filters import ( Filter, NumExprFilter, PercentileFilter, NullFilter, ) from zipline.utils.input_validation import expect_types from zipline.utils.math_utils import nanmean, nanstd from zipline.utils.numpy_utils import ( bool_dtype, coerce_to_dtype, datetime64ns_dtype, float64_dtype, int64_dtype, ) from zipline.utils.preprocess import preprocess _RANK_METHODS = frozenset(['average', 'min', 'max', 'dense', 'ordinal']) def coerce_numbers_to_my_dtype(f): """ A decorator for methods whose signature is f(self, other) that coerces ``other`` to ``self.dtype``. This is used to make comparison operations between numbers and `Factor` instances work independently of whether the user supplies a float or integer literal. For example, if I write:: my_filter = my_factor > 3 my_factor probably has dtype float64, but 3 is an int, so we want to coerce to float64 before doing the comparison. """ @wraps(f) def method(self, other): if isinstance(other, Number): other = coerce_to_dtype(self.dtype, other) return f(self, other) return method @curry def set_attribute(name, value): """ Decorator factory for setting attributes on a function. Doesn't change the behavior of the wrapped function. Usage ----- >>> @set_attribute('__name__', 'foo') ... def bar(): ... return 3 ... >>> bar() 3 >>> bar.__name__ 'foo' """ def decorator(f): setattr(f, name, value) return f return decorator # Decorators for setting the __name__ and __doc__ properties of a decorated # function. # Example: with_name = set_attribute('__name__') with_doc = set_attribute('__doc__') def binop_return_type(op): if is_comparison(op): return NumExprFilter else: return NumExprFactor def binop_return_dtype(op, left, right): """ Compute the expected return dtype for the given binary operator. Parameters ---------- op : str Operator symbol, (e.g. '+', '-', ...). left : numpy.dtype Dtype of left hand side. right : numpy.dtype Dtype of right hand side. Returns ------- outdtype : numpy.dtype The dtype of the result of `left <op> right`. """ if is_comparison(op): if left != right: raise TypeError( "Don't know how to compute {left} {op} {right}.\n" "Comparisons are only supported between Factors of equal " "dtypes.".format(left=left, op=op, right=right) ) return bool_dtype elif left != float64_dtype or right != float64_dtype: raise TypeError( "Don't know how to compute {left} {op} {right}.\n" "Arithmetic operators are only supported between Factors of " "dtype 'float64'.".format( left=left.name, op=op, right=right.name, ) ) return float64_dtype def binary_operator(op): """ Factory function for making binary operator methods on a Factor subclass. Returns a function, "binary_operator" suitable for implementing functions like __add__. """ # When combining a Factor with a NumericalExpression, we use this # attrgetter instance to defer to the commuted implementation of the # NumericalExpression operator. commuted_method_getter = attrgetter(method_name_for_op(op, commute=True)) @with_doc("Binary Operator: '%s'" % op) @with_name(method_name_for_op(op)) @coerce_numbers_to_my_dtype def binary_operator(self, other): # This can't be hoisted up a scope because the types returned by # binop_return_type aren't defined when the top-level function is # invoked in the class body of Factor. return_type = binop_return_type(op) if isinstance(self, NumExprFactor): self_expr, other_expr, new_inputs = self.build_binary_op( op, other, ) return return_type( "({left}) {op} ({right})".format( left=self_expr, op=op, right=other_expr, ), new_inputs, dtype=binop_return_dtype(op, self.dtype, other.dtype), ) elif isinstance(other, NumExprFactor): # NumericalExpression overrides ops to correctly handle merging of # inputs. Look up and call the appropriate reflected operator with # ourself as the input. return commuted_method_getter(other)(self) elif isinstance(other, Term): if self is other: return return_type( "x_0 {op} x_0".format(op=op), (self,), dtype=binop_return_dtype(op, self.dtype, other.dtype), ) return return_type( "x_0 {op} x_1".format(op=op), (self, other), dtype=binop_return_dtype(op, self.dtype, other.dtype), ) elif isinstance(other, Number): return return_type( "x_0 {op} ({constant})".format(op=op, constant=other), binds=(self,), # .dtype access is safe here because coerce_numbers_to_my_dtype # will convert any input numbers to numpy equivalents. dtype=binop_return_dtype(op, self.dtype, other.dtype) ) raise BadBinaryOperator(op, self, other) return binary_operator def reflected_binary_operator(op): """ Factory function for making binary operator methods on a Factor. Returns a function, "reflected_binary_operator" suitable for implementing functions like __radd__. """ assert not is_comparison(op) @with_name(method_name_for_op(op, commute=True)) @coerce_numbers_to_my_dtype def reflected_binary_operator(self, other): if isinstance(self, NumericalExpression): self_expr, other_expr, new_inputs = self.build_binary_op( op, other ) return NumExprFactor( "({left}) {op} ({right})".format( left=other_expr, right=self_expr, op=op, ), new_inputs, dtype=binop_return_dtype(op, other.dtype, self.dtype) ) # Only have to handle the numeric case because in all other valid cases # the corresponding left-binding method will be called. elif isinstance(other, Number): return NumExprFactor( "{constant} {op} x_0".format(op=op, constant=other), binds=(self,), dtype=binop_return_dtype(op, other.dtype, self.dtype), ) raise BadBinaryOperator(op, other, self) return reflected_binary_operator def unary_operator(op): """ Factory function for making unary operator methods for Factors. """ # Only negate is currently supported. valid_ops = {'-'} if op not in valid_ops: raise ValueError("Invalid unary operator %s." % op) @with_doc("Unary Operator: '%s'" % op) @with_name(unary_op_name(op)) def unary_operator(self): if self.dtype != float64_dtype: raise TypeError( "Can't apply unary operator {op!r} to instance of " "{typename!r} with dtype {dtypename!r}.\n" "{op!r} is only supported for Factors of dtype " "'float64'.".format( op=op, typename=type(self).__name__, dtypename=self.dtype.name, ) ) # This can't be hoisted up a scope because the types returned by # unary_op_return_type aren't defined when the top-level function is # invoked. if isinstance(self, NumericalExpression): return NumExprFactor( "{op}({expr})".format(op=op, expr=self._expr), self.inputs, dtype=float64_dtype, ) else: return NumExprFactor( "{op}x_0".format(op=op), (self,), dtype=float64_dtype, ) return unary_operator def function_application(func): """ Factory function for producing function application methods for Factor subclasses. """ if func not in NUMEXPR_MATH_FUNCS: raise ValueError("Unsupported mathematical function '%s'" % func) @with_name(func) def mathfunc(self): if isinstance(self, NumericalExpression): return NumExprFactor( "{func}({expr})".format(func=func, expr=self._expr), self.inputs, dtype=float64_dtype, ) else: return NumExprFactor( "{func}(x_0)".format(func=func), (self,), dtype=float64_dtype, ) return mathfunc def restrict_to_dtype(dtype, message_template): """ A factory for decorators that restricting Factor methods to only be callable on Factors with a specific dtype. This is conceptually similar to zipline.utils.input_validation.expect_dtypes, but provides more flexibility for providing error messages that are specifically targeting Factor methods. Parameters ---------- dtype : numpy.dtype The dtype on which the decorated method may be called. message_template : str A template for the error message to be raised. `message_template.format` will be called with keyword arguments `method_name`, `expected_dtype`, and `received_dtype`. Usage ----- @restrict_to_dtype( dtype=float64_dtype, message_template=( "{method_name}() was called on a factor of dtype {received_dtype}." "{method_name}() requires factors of dtype{expected_dtype}." ), ) def some_factor_method(self, ...): self.stuff_that_requires_being_float64(...) """ def processor(factor_method, _, factor_instance): factor_dtype = factor_instance.dtype if factor_dtype != dtype: raise TypeError( message_template.format( method_name=factor_method.__name__, expected_dtype=dtype.name, received_dtype=factor_dtype, ) ) return factor_instance return preprocess(self=processor) # Decorators for Factor methods. if_not_float64_tell_caller_to_use_isnull = restrict_to_dtype( dtype=float64_dtype, message_template=( "{method_name}() was called on a factor of dtype {received_dtype}.\n" "{method_name}() is only defined for dtype {expected_dtype}." "To filter missing data, use isnull() or notnull()." ) ) float64_only = restrict_to_dtype( dtype=float64_dtype, message_template=( "{method_name}() is only defined on Factors of dtype {expected_dtype}," " but it was called on a Factor of dtype {received_dtype}." ) ) FACTOR_DTYPES = frozenset([datetime64ns_dtype, float64_dtype, int64_dtype]) class Factor(RestrictedDTypeMixin, ComputableTerm): """ Pipeline API expression producing a numerical or date-valued output. Factors are the most commonly-used Pipeline term, representing the result of any computation producing a numerical result. Factors can be combined, both with other Factors and with scalar values, via any of the builtin mathematical operators (``+``, ``-``, ``*``, etc). This makes it easy to write complex expressions that combine multiple Factors. For example, constructing a Factor that computes the average of two other Factors is simply:: >>> f1 = SomeFactor(...) >>> f2 = SomeOtherFactor(...) >>> average = (f1 + f2) / 2.0 Factors can also be converted into :class:`zipline.pipeline.Filter` objects via comparison operators: (``<``, ``<=``, ``!=``, ``eq``, ``>``, ``>=``). There are many natural operators defined on Factors besides the basic numerical operators. These include methods identifying missing or extreme-valued outputs (isnull, notnull, isnan, notnan), methods for normalizing outputs (rank, demean, zscore), and methods for constructing Filters based on rank-order properties of results (top, bottom, percentile_between). """ ALLOWED_DTYPES = FACTOR_DTYPES # Used by RestrictedDTypeMixin # Dynamically add functions for creating NumExprFactor/NumExprFilter # instances. clsdict = locals() clsdict.update( { method_name_for_op(op): binary_operator(op) # Don't override __eq__ because it breaks comparisons on tuples of # Factors. for op in MATH_BINOPS.union(COMPARISONS - {'=='}) } ) clsdict.update( { method_name_for_op(op, commute=True): reflected_binary_operator(op) for op in MATH_BINOPS } ) clsdict.update( { unary_op_name(op): unary_operator(op) for op in UNARY_OPS } ) clsdict.update( { funcname: function_application(funcname) for funcname in NUMEXPR_MATH_FUNCS } ) __truediv__ = clsdict['__div__'] __rtruediv__ = clsdict['__rdiv__'] eq = binary_operator('==') @expect_types( mask=(Filter, NotSpecifiedType), groupby=(Classifier, NotSpecifiedType), ) @float64_only def demean(self, mask=NotSpecified, groupby=NotSpecified): """ Construct a Factor that computes ``self`` and subtracts the mean from row of the result. If ``mask`` is supplied, ignore values where ``mask`` returns False when computing row means, and output NaN anywhere the mask is False. If ``groupby`` is supplied, compute by partitioning each row based on the values produced by ``groupby``, de-meaning the partitioned arrays, and stitching the sub-results back together. Parameters ---------- mask : zipline.pipeline.Filter, optional A Filter defining values to ignore when computing means. groupby : zipline.pipeline.Classifier, optional A classifier defining partitions over which to compute means. Example ------- Let ``f`` be a Factor which would produce the following output:: AAPL MSFT MCD BK 2017-03-13 1.0 2.0 3.0 4.0 2017-03-14 1.5 2.5 3.5 1.0 2017-03-15 2.0 3.0 4.0 1.5 2017-03-16 2.5 3.5 1.0 2.0 Let ``c`` be a Classifier producing the following output:: AAPL MSFT MCD BK 2017-03-13 1 1 2 2 2017-03-14 1 1 2 2 2017-03-15 1 1 2 2 2017-03-16 1 1 2 2 Let ``m`` be a Filter producing the following output:: AAPL MSFT MCD BK 2017-03-13 False True True True 2017-03-14 True False True True 2017-03-15 True True False True 2017-03-16 True True True False Then ``f.demean()`` will subtract the mean from each row produced by ``f``. :: AAPL MSFT MCD BK 2017-03-13 -1.500 -0.500 0.500 1.500 2017-03-14 -0.625 0.375 1.375 -1.125 2017-03-15 -0.625 0.375 1.375 -1.125 2017-03-16 0.250 1.250 -1.250 -0.250 ``f.demean(mask=m)`` will subtract the mean from each row, but means will be calculated ignoring values on the diagonal, and NaNs will written to the diagonal in the output. Diagonal values are ignored because they are the locations where the mask ``m`` produced False. :: AAPL MSFT MCD BK 2017-03-13 NaN -1.000 0.000 1.000 2017-03-14 -0.500 NaN 1.500 -1.000 2017-03-15 -0.166 0.833 NaN -0.666 2017-03-16 0.166 1.166 -1.333 NaN ``f.demean(groupby=c)`` will subtract the group-mean of AAPL/MSFT and MCD/BK from their respective entries. The AAPL/MSFT are grouped together because both assets always produce 1 in the output of the classifier ``c``. Similarly, MCD/BK are grouped together because they always produce 2. :: AAPL MSFT MCD BK 2017-03-13 -0.500 0.500 -0.500 0.500 2017-03-14 -0.500 0.500 1.250 -1.250 2017-03-15 -0.500 0.500 1.250 -1.250 2017-03-16 -0.500 0.500 -0.500 0.500 ``f.demean(mask=m, groupby=c)`` will also subtract the group-mean of AAPL/MSFT and MCD/BK, but means will be calculated ignoring values on the diagonal , and NaNs will be written to the diagonal in the output. :: AAPL MSFT MCD BK 2017-03-13 NaN 0.000 -0.500 0.500 2017-03-14 0.000 NaN 1.250 -1.250 2017-03-15 -0.500 0.500 NaN 0.000 2017-03-16 -0.500 0.500 0.000 NaN Notes ----- Mean is sensitive to the magnitudes of outliers. When working with factor that can potentially produce large outliers, it is often useful to use the ``mask`` parameter to discard values at the extremes of the distribution:: >>> base = MyFactor(...) >>> normalized = base.demean(mask=base.percentile_between(1, 99)) ``demean()`` is only supported on Factors of dtype float64. See Also -------- :meth:`pandas.DataFrame.groupby` """ # This is a named function so that it has a __name__ for use in the # graph repr of GroupedRowTransform. def demean(row): return row - nanmean(row) return GroupedRowTransform( transform=demean, factor=self, mask=mask, groupby=groupby, ) @expect_types( mask=(Filter, NotSpecifiedType), groupby=(Classifier, NotSpecifiedType), ) @float64_only def zscore(self, mask=NotSpecified, groupby=NotSpecified): """ Construct a Factor that Z-Scores each day's results. The Z-Score of a row is defined as:: (row - row.mean()) / row.stddev() If ``mask`` is supplied, ignore values where ``mask`` returns False when computing row means and standard deviations, and output NaN anywhere the mask is False. If ``groupby`` is supplied, compute by partitioning each row based on the values produced by ``groupby``, z-scoring the partitioned arrays, and stitching the sub-results back together. Parameters ---------- mask : zipline.pipeline.Filter, optional A Filter defining values to ignore when Z-Scoring. groupby : zipline.pipeline.Classifier, optional A classifier defining partitions over which to compute Z-Scores. Returns ------- zscored : zipline.pipeline.Factor A Factor producing that z-scores the output of self. Notes ----- Mean and standard deviation are sensitive to the magnitudes of outliers. When working with factor that can potentially produce large outliers, it is often useful to use the ``mask`` parameter to discard values at the extremes of the distribution:: >>> base = MyFactor(...) >>> normalized = base.zscore(mask=base.percentile_between(1, 99)) ``zscore()`` is only supported on Factors of dtype float64. Example ------- See :meth:`~zipline.pipeline.factors.Factor.demean` for an in-depth example of the semantics for ``mask`` and ``groupby``. See Also -------- :meth:`pandas.DataFrame.groupby` """ # This is a named function so that it has a __name__ for use in the # graph repr of GroupedRowTransform. def zscore(row): return (row - nanmean(row)) / nanstd(row) return GroupedRowTransform( transform=zscore, factor=self, mask=mask, groupby=groupby, ) def rank(self, method='ordinal', ascending=True, mask=NotSpecified): """ Construct a new Factor representing the sorted rank of each column within each row. Parameters ---------- method : str, {'ordinal', 'min', 'max', 'dense', 'average'} The method used to assign ranks to tied elements. See `scipy.stats.rankdata` for a full description of the semantics for each ranking method. Default is 'ordinal'. ascending : bool, optional Whether to return sorted rank in ascending or descending order. Default is True. mask : zipline.pipeline.Filter, optional A Filter representing assets to consider when computing ranks. If mask is supplied, ranks are computed ignoring any asset/date pairs for which `mask` produces a value of False. Returns ------- ranks : zipline.pipeline.factors.Rank A new factor that will compute the ranking of the data produced by `self`. Notes ----- The default value for `method` is different from the default for `scipy.stats.rankdata`. See that function's documentation for a full description of the valid inputs to `method`. Missing or non-existent data on a given day will cause an asset to be given a rank of NaN for that day. See Also -------- :func:`scipy.stats.rankdata` :class:`zipline.pipeline.factors.factor.Rank` """ return Rank(self, method=method, ascending=ascending, mask=mask) @expect_types(bins=int, mask=(Filter, NotSpecifiedType)) def quantiles(self, bins, mask=NotSpecified): """ Construct a Classifier computing quantiles of the output of ``self``. Every non-NaN data point the output is labelled with an integer value from 0 to (bins - 1). NaNs are labelled with -1. If ``mask`` is supplied, ignore data points in locations for which ``mask`` produces False, and emit a label of -1 at those locations. Parameters ---------- bins : int Number of bins labels to compute. mask : zipline.pipeline.Filter, optional Mask of values to ignore when computing quantiles. Returns ------- quantiles : zipline.pipeline.classifiers.Quantiles A Classifier producing integer labels ranging from 0 to (bins - 1). """ if mask is NotSpecified: mask = self.mask return Quantiles(inputs=(self,), bins=bins, mask=mask) @expect_types(mask=(Filter, NotSpecifiedType)) def quartiles(self, mask=NotSpecified): """ Construct a Classifier computing quartiles over the output of ``self``. Every non-NaN data point the output is labelled with a value of either 0, 1, 2, or 3, corresponding to the first, second, third, or fourth quartile over each row. NaN data points are labelled with -1. If ``mask`` is supplied, ignore data points in locations for which ``mask`` produces False, and emit a label of -1 at those locations. Parameters ---------- mask : zipline.pipeline.Filter, optional Mask of values to ignore when computing quartiles. Returns ------- quartiles : zipline.pipeline.classifiers.Quantiles A Classifier producing integer labels ranging from 0 to 3. """ return self.quantiles(bins=4, mask=mask) @expect_types(mask=(Filter, NotSpecifiedType)) def quintiles(self, mask=NotSpecified): """ Construct a Classifier computing quintile labels on ``self``. Every non-NaN data point the output is labelled with a value of either 0, 1, 2, or 3, 4, corresonding to quintiles over each row. NaN data points are labelled with -1. If ``mask`` is supplied, ignore data points in locations for which ``mask`` produces False, and emit a label of -1 at those locations. Parameters ---------- mask : zipline.pipeline.Filter, optional Mask of values to ignore when computing quintiles. Returns ------- quintiles : zipline.pipeline.classifiers.Quantiles A Classifier producing integer labels ranging from 0 to 4. """ return self.quantiles(bins=5, mask=mask) @expect_types(mask=(Filter, NotSpecifiedType)) def deciles(self, mask=NotSpecified): """ Construct a Classifier computing decile labels on ``self``. Every non-NaN data point the output is labelled with a value from 0 to 9 corresonding to deciles over each row. NaN data points are labelled with -1. If ``mask`` is supplied, ignore data points in locations for which ``mask`` produces False, and emit a label of -1 at those locations. Parameters ---------- mask : zipline.pipeline.Filter, optional Mask of values to ignore when computing deciles. Returns ------- deciles : zipline.pipeline.classifiers.Quantiles A Classifier producing integer labels ranging from 0 to 9. """ return self.quantiles(bins=10, mask=mask) def top(self, N, mask=NotSpecified): """ Construct a Filter matching the top N asset values of self each day. Parameters ---------- N : int Number of assets passing the returned filter each day. mask : zipline.pipeline.Filter, optional A Filter representing assets to consider when computing ranks. If mask is supplied, top values are computed ignoring any asset/date pairs for which `mask` produces a value of False. Returns ------- filter : zipline.pipeline.filters.Filter """ return self.rank(ascending=False, mask=mask) <= N def bottom(self, N, mask=NotSpecified): """ Construct a Filter matching the bottom N asset values of self each day. Parameters ---------- N : int Number of assets passing the returned filter each day. mask : zipline.pipeline.Filter, optional A Filter representing assets to consider when computing ranks. If mask is supplied, bottom values are computed ignoring any asset/date pairs for which `mask` produces a value of False. Returns ------- filter : zipline.pipeline.Filter """ return self.rank(ascending=True, mask=mask) <= N def percentile_between(self, min_percentile, max_percentile, mask=NotSpecified): """ Construct a new Filter representing entries from the output of this Factor that fall within the percentile range defined by min_percentile and max_percentile. Parameters ---------- min_percentile : float [0.0, 100.0] Return True for assets falling above this percentile in the data. max_percentile : float [0.0, 100.0] Return True for assets falling below this percentile in the data. mask : zipline.pipeline.Filter, optional A Filter representing assets to consider when percentile calculating thresholds. If mask is supplied, percentile cutoffs are computed each day using only assets for which ``mask`` returns True. Assets for which ``mask`` produces False will produce False in the output of this Factor as well. Returns ------- out : zipline.pipeline.filters.PercentileFilter A new filter that will compute the specified percentile-range mask. See Also -------- zipline.pipeline.filters.filter.PercentileFilter """ return PercentileFilter( self, min_percentile=min_percentile, max_percentile=max_percentile, mask=mask, ) def isnull(self): """ A Filter producing True for values where this Factor has missing data. Equivalent to self.isnan() when ``self.dtype`` is float64. Otherwise equivalent to ``self.eq(self.missing_value)``. Returns ------- filter : zipline.pipeline.filters.Filter """ if self.dtype == float64_dtype: # Using isnan is more efficient when possible because we can fold # the isnan computation with other NumExpr expressions. return self.isnan() else: return NullFilter(self) def notnull(self): """ A Filter producing True for values where this Factor has complete data. Equivalent to ``~self.isnan()` when ``self.dtype`` is float64. Otherwise equivalent to ``(self != self.missing_value)``. """ return ~self.isnull() @if_not_float64_tell_caller_to_use_isnull def isnan(self): """ A Filter producing True for all values where this Factor is NaN. Returns ------- nanfilter : zipline.pipeline.filters.Filter """ return self != self @if_not_float64_tell_caller_to_use_isnull def notnan(self): """ A Filter producing True for values where this Factor is not NaN. Returns ------- nanfilter : zipline.pipeline.filters.Filter """ return ~self.isnan() @if_not_float64_tell_caller_to_use_isnull def isfinite(self): """ A Filter producing True for values where this Factor is anything but NaN, inf, or -inf. """ return (-inf < self) & (self < inf) class NumExprFactor(NumericalExpression, Factor): """ Factor computed from a numexpr expression. Parameters ---------- expr : string A string suitable for passing to numexpr. All variables in 'expr' should be of the form "x_i", where i is the index of the corresponding factor input in 'binds'. binds : tuple A tuple of factors to use as inputs. Notes ----- NumExprFactors are constructed by numerical operators like `+` and `-`. Users should rarely need to construct a NumExprFactor directly. """ pass class GroupedRowTransform(Factor): """ A Factor that transforms an input factor by applying a row-wise shape-preserving transformation on classifier-defined groups of that Factor. This is most often useful for normalization operators like ``zscore`` or ``demean``. Parameters ---------- transform : function[ndarray[ndim=1] -> ndarray[ndim=1]] Function to apply over each row group. factor : zipline.pipeline.Factor The factor providing baseline data to transform. mask : zipline.pipeline.Filter Mask of entries to ignore when calculating transforms. groupby : zipline.pipeline.Classifier Classifier partitioning ``factor`` into groups to use when calculating means. Notes ----- Users should rarely construct instances of this factor directly. Instead, they should construct instances via factor normalization methods like ``zscore`` and ``demean``. See Also -------- zipline.pipeline.factors.Factor.zscore zipline.pipeline.factors.Factor.demean """ window_length = 0 def __new__(cls, transform, factor, mask, groupby): if mask is NotSpecified: mask = factor.mask else: mask = mask & factor.mask if groupby is NotSpecified: groupby = Everything(mask=mask) return super(GroupedRowTransform, cls).__new__( GroupedRowTransform, transform=transform, inputs=(factor, groupby), missing_value=factor.missing_value, mask=mask, dtype=factor.dtype, ) def _init(self, transform, *args, **kwargs): self._transform = transform return super(GroupedRowTransform, self)._init(*args, **kwargs) @classmethod def static_identity(cls, transform, *args, **kwargs): return ( super(GroupedRowTransform, cls).static_identity(*args, **kwargs), transform, ) def
(self, arrays, dates, assets, mask): data = arrays[0] null_group_value = self.inputs[1].missing_value group_labels = where( mask, arrays[1], null_group_value, ) return where( group_labels != null_group_value, naive_grouped_rowwise_apply( data=data, group_labels=group_labels, func=self._transform, ), self.missing_value, ) @property def transform_name(self): return self._transform.__name__ def short_repr(self): return type(self).__name__ + '(%r)' % self.transform_name class Rank(SingleInputMixin, Factor): """ A Factor representing the row-wise rank data of another Factor. Parameters ---------- factor : zipline.pipeline.factors.Factor The factor on which to compute ranks. method : str, {'average', 'min', 'max', 'dense', 'ordinal'} The method used to assign ranks to tied elements. See `scipy.stats.rankdata` for a full description of the semantics for each ranking method. See Also -------- :func:`scipy.stats.rankdata` :class:`Factor.rank` Notes ----- Most users should call Factor.rank rather than directly construct an instance of this class. """ window_length = 0 dtype = float64_dtype def __new__(cls, factor, method, ascending, mask): return super(Rank, cls).__new__( cls, inputs=(factor,), method=method, ascending=ascending, mask=mask, ) def _init(self, method, ascending, *args, **kwargs): self._method = method self._ascending = ascending return super(Rank, self)._init(*args, **kwargs) @classmethod def static_identity(cls, method, ascending, *args, **kwargs): return ( super(Rank, cls).static_identity(*args, **kwargs), method, ascending, ) def _validate(self): """ Verify that the stored rank method is valid. """ if self._method not in _RANK_METHODS: raise UnknownRankMethod( method=self._method, choices=set(_RANK_METHODS), ) return super(Rank, self)._validate() def _compute(self, arrays, dates, assets, mask): """ For each row in the input, compute a like-shaped array of per-row ranks. """ return masked_rankdata_2d( arrays[0], mask, self.inputs[0].missing_value, self._method, self._ascending, ) def __repr__(self): return "{type}({input_}, method='{method}', mask={mask})".format( type=type(self).__name__, input_=self.inputs[0], method=self._method, mask=self.mask, ) class CustomFactor(PositiveWindowLengthMixin, CustomTermMixin, Factor): ''' Base class for user-defined Factors. Parameters ---------- inputs : iterable, optional An iterable of `BoundColumn` instances (e.g. USEquityPricing.close), describing the data to load and pass to `self.compute`. If this argument is passed to the CustomFactor constructor, we look for a class-level attribute named `inputs`. window_length : int, optional Number of rows to pass for each input. If this argument is not passed to the CustomFactor constructor, we look for a class-level attribute named `window_length`. mask : zipline.pipeline.Filter, optional A Filter describing the assets on which we should compute each day. Each call to ``CustomFactor.compute`` will only receive assets for which ``mask`` produced True on the day for which compute is being called. Notes ----- Users implementing their own Factors should subclass CustomFactor and implement a method named `compute` with the following signature: .. code-block:: python def compute(self, today, assets, out, *inputs): ... On each simulation date, ``compute`` will be called with the current date, an array of sids, an output array, and an input array for each expression passed as inputs to the CustomFactor constructor. The specific types of the values passed to `compute` are as follows:: today : np.datetime64[ns] Row label for the last row of all arrays passed as `inputs`. assets : np.array[int64, ndim=1] Column labels for `out` and`inputs`. out : np.array[self.dtype, ndim=1] Output array of the same shape as `assets`. `compute` should write its desired return values into `out`. *inputs : tuple of np.array Raw data arrays corresponding to the values of `self.inputs`. ``compute`` functions should expect to be passed NaN values for dates on which no data was available for an asset. This may include dates on which an asset did not yet exist. For example, if a CustomFactor requires 10 rows of close price data, and asset A started trading on Monday June 2nd, 2014, then on Tuesday, June 3rd, 2014, the column of input data for asset A will have 9 leading NaNs for the preceding days on which data was not yet available. Examples -------- A CustomFactor with pre-declared defaults: .. code-block:: python class TenDayRange(CustomFactor): """ Computes the difference between the highest high in the last 10 days and the lowest low. Pre-declares high and low as default inputs and `window_length` as 10. """ inputs = [USEquityPricing.high, USEquityPricing.low] window_length = 10 def compute(self, today, assets, out, highs, lows): from numpy import nanmin, nanmax highest_highs = nanmax(highs, axis=0) lowest_lows = nanmin(lows, axis=0) out[:] = highest_highs - lowest_lows # Doesn't require passing inputs or window_length because they're # pre-declared as defaults for the TenDayRange class. ten_day_range = TenDayRange() A CustomFactor without defaults: .. code-block:: python class MedianValue(CustomFactor): """ Computes the median value of an arbitrary single input over an arbitrary window.. Does not declare any defaults, so values for `window_length` and `inputs` must be passed explicitly on every construction. """ def compute(self, today, assets, out, data): from numpy import nanmedian out[:] = data.nanmedian(data, axis=0) # Values for `inputs` and `window_length` must be passed explicitly to # MedianValue. median_close10 = MedianValue([USEquityPricing.close], window_length=10) median_low15 = MedianValue([USEquityPricing.low], window_length=15) ''' dtype = float64_dtype class Latest(LatestMixin, CustomFactor): """ Factor producing the most recently-known value of `inputs[0]` on each day. The `.latest` attribute of DataSet columns returns an instance of this Factor. """ window_length = 1 def compute(self, today, assets, out, data): out[:] = data[-1]
_compute
planilla.js
$(document).on("ready",inicio); function inicio(){ planilla_usuario(); } function planilla_usuario() { var base_url = document.getElementById('base_url').value; var controlador = base_url+"salario/planilla_usuario"; $.ajax({url: controlador, type:"POST", data:{}, success:function(resul){ $("#pillados").val("- 0 -"); var registros = JSON.parse(resul); if (registros != null){ var total = Number(0); var n = registros.length; //tamaño del arreglo de la consulta //$("#pillados").html("Registros Encontrados: "+n+""); html = ""; for (var i = 0; i < n ; i++){ total += Number(registros[i]["salario_loquidopagable"]); html += "<tr>"; html += "<td>"+(i+1)+"</td>"; html += "<td><b>"+registros[i]["personal_nombre"]+"</b></td>"; html += "<td align='center'>"+registros[i]["personal_sexo"]+"</td>"; html += "<td align='center'>"+moment(registros[i]["personal_fechanac"]).format('DD/MM/YYYY')+"</td>"; html += "<td align='center'>"+registros[i]["contrato_cargo"]+"</td>"; html += "<td align='right'>"+Number(registros[i]["contrato_sueldo"]).toFixed(2)+"</td>"; html += "<td align='right'>"+Number(registros[i]["salario_ganado"]).toFixed(2)+"</td>"; html += "<td align='right'>"+Number(registros[i]["salario_bonoant"]).toFixed(2)+"</td>"; html += "<td align='right'><input size='2' id='salario_horasext"+registros[i]["salario_id"]+"' value='"+Number(registros[i]["salario_horasext"]).toFixed(2)+"' onkeyup='calcular(event,"+registros[i]["salario_id"]+")' /></td>"; html += "<td align='right'>"+Number(registros[i]["salario_bonohoras"]).toFixed(2)+"</td>"; html += "<td align='right'><input size='2' id='salario_produccion"+registros[i]["salario_id"]+"' value='"+Number(registros[i]["salario_produccion"]).toFixed(2)+"' onkeyup='calcular(event,"+registros[i]["salario_id"]+")' /></td>"; html += "<td align='right'><input size='2' id='salario_dominical"+registros[i]["salario_id"]+"' value='"+Number(registros[i]["salario_dominical"]).toFixed(2)+"' onkeyup='calcular(event,"+registros[i]["salario_id"]+")' /></td>"; html += "<td align='right'><input size='2' id='salario_otrobono"+registros[i]["salario_id"]+"' value='"+Number(registros[i]["salario_otrobono"]).toFixed(2)+"' onkeyup='calcular(event,"+registros[i]["salario_id"]+")' /></td>"; html += "<td align='right'>"+Number(registros[i]["salario_totalganado"]).toFixed(2)+"</td>"; html += "<td align='right'>"+Number(registros[i]["salario_afp"]).toFixed(2)+"</td>"; html += "<td align='right'>"+Number(registros[i]["salario_solidario"]).toFixed(2)+"</td>"; html += "<td align='right'><input size='2' id='salario_iva"+registros[i]["salario_id"]+"' value='"+Number(registros[i]["salario_iva"]).toFixed(2)+"' onkeyup='calcular(event,"+registros[i]["salario_id"]+")' /></td>"; html += "<td align='right'><input size='2' id='salario_ant"+registros[i]["salario_id"]+"' value='"+Number(registros[i]["salario_ant"]).toFixed(2)+"' onkeyup='calcular(event,"+registros[i]["salario_id"]+")' /></td>"; html += "<td align='right'>"+Number(registros[i]["salario_totaldescuento"]).toFixed(2)+"</td>"; html += "<td align='right'>"+Number(registros[i]["salario_loquidopagable"]).toFixed(2)+"</td>"; } html += "<tr>"; html += "<th colspan='4' align='right'><b>TOTAL</b></th>"; html += "<th></th>"; html += "<th></th>"; html += "<th></th>"; html += "<th></th>"; html += "<th></th>"; html += "<th></th>"; html += "<th></th>"; html += "<th></th>"; html += "<th></th>"; html += "<th></th>"; html += "<th></th>"; html += "<th></th>"; html += "<th></th>"; html += "<th></th>"; html += "<th></th>"; html += "<td align='right'>"+Number(total).toFixed(2)+"</td>"; html += "</tr>"; $("#tablaresultados").html(html); } }, error:function(resul){ // alert("Algo salio mal...!!!"); html = ""; $("#tablaresultados").html(html); } }); } function c
e,salario_id) { tecla = (document.all) ? e.keyCode : e.which; if(tecla==13){ calcularfila(salario_id); } } function calcularfila(salario_id) { var base_url = document.getElementById("base_url").value; var horas = document.getElementById("salario_horasext"+salario_id).value; var produccion = document.getElementById("salario_produccion"+salario_id).value; var dominical = document.getElementById("salario_dominical"+salario_id).value; var otro = document.getElementById("salario_otrobono"+salario_id).value; var iva = document.getElementById("salario_iva"+salario_id).value; var anticipo = document.getElementById("salario_ant"+salario_id).value; var controlador = base_url+"salario/actualizar/"+salario_id; $.ajax({url: controlador, type: "POST", data:{horas:horas,produccion:produccion,dominical:dominical,otro:otro,iva:iva,anticipo:anticipo}, success:function(resultado){ planilla_usuario(); /*var registros = JSON.parse(resultado); $("#generar_nit").val(registros["cliente_nit"]); $("#generar_razon").val(registros["cliente_razon"]); $("#generar_detalle").val("PRODUCTOS VARIOS"); $("#generar_venta_id").val(registros["venta_id"]); $("#generar_monto").val(Number(registros["venta_total"]).toFixed(2)); $("#generar_credito").val(credito_id);*/ //$("#boton_modal_factura").click(); }, error:function(resultado){ alert("Ingrese una cantidad correcta"); }, }) } function busqueda_planilla() { var base_url = document.getElementById("base_url").value; var ano = document.getElementById("ano").value; var mes = document.getElementById("mes").value; var controlador = base_url+"salario/busqueda_planilla/"; $.ajax({url: controlador, type: "POST", data:{ano:ano,mes:mes}, success:function(resultado){ var registros = JSON.parse(resultado); if (registros != ''){ alert('Ya existe una planilla procesada para '+mes+' en gestion '+ano); $("#mes").val(''); }else{ } }, error:function(resultado){ }, }) } function procesar_planilla() { var base_url = document.getElementById("base_url").value; var ano = document.getElementById("ano").value; var mes = document.getElementById("mes").value; var smn = document.getElementById("smn").value; var fecha = document.getElementById("planilla_fecha").value; var controlador = base_url+"salario/procesar_planilla/"; document.getElementById('boton').disabled=true; if(ano!='' && mes!='' && smn!='' && planilla_fecha!=''){ $.ajax({url: controlador, type: "POST", data:{ano:ano,mes:mes,smn:smn,fecha:fecha}, success:function(resultado){ document.getElementById('boton').disabled=true; window.location.href= base_url+'personal'; }, error:function(resultado){ document.getElementById('boton').disabled=false; }, }) }else{ document.getElementById('boton').disabled=false; alert('Debe llenar todos los campos'); } }
alcular(
mod.rs
use std::collections::HashMap; use crate::errors::Result; use serde_json::value::Value; pub mod array; pub mod common; pub mod number; pub mod object; pub mod string; /// The filter function type definition pub trait Filter: Sync + Send { /// The filter function type definition fn filter(&self, value: &Value, args: &HashMap<String, Value>) -> Result<Value>; } impl<F> Filter for F where F: Fn(&Value, &HashMap<String, Value>) -> Result<Value> + Sync + Send, { fn filter(&self, value: &Value, args: &HashMap<String, Value>) -> Result<Value>
}
{ self(value, args) }
main-es2015.js
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["main"],{ /***/ "./src/$$_lazy_route_resource lazy recursive": /*!**********************************************************!*\ !*** ./src/$$_lazy_route_resource lazy namespace object ***! \**********************************************************/ /*! no static exports found */ /***/ (function(module, exports) { function webpackEmptyAsyncContext(req) { // Here Promise.resolve().then() is used instead of new Promise() to prevent // uncaught exception popping up in devtools return Promise.resolve().then(function() { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; }); } webpackEmptyAsyncContext.keys = function() { return []; }; webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; module.exports = webpackEmptyAsyncContext; webpackEmptyAsyncContext.id = "./src/$$_lazy_route_resource lazy recursive"; /***/ }), /***/ "./src/app/app-routing.module.ts": /*!***************************************!*\ !*** ./src/app/app-routing.module.ts ***! \***************************************/ /*! exports provided: AppRoutingModule */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AppRoutingModule", function() { return AppRoutingModule; }); /* harmony import */ var _angular_router__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/router */ "./node_modules/@angular/router/fesm2015/router.js"); /* harmony import */ var _home_home_component__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./home/home.component */ "./src/app/home/home.component.ts"); /* harmony import */ var _dashboard_dashboard_component__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./dashboard/dashboard.component */ "./src/app/dashboard/dashboard.component.ts"); /* harmony import */ var _shared_services_auth_guard__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./shared/services/auth.guard */ "./src/app/shared/services/auth.guard.ts"); const routes = [ { path: 'home', component: _home_home_component__WEBPACK_IMPORTED_MODULE_1__["HomeComponent"] }, { path: 'dashboard', canActivate: [_shared_services_auth_guard__WEBPACK_IMPORTED_MODULE_3__["AuthGuard"]], component: _dashboard_dashboard_component__WEBPACK_IMPORTED_MODULE_2__["DashboardComponent"] }, { path: '', redirectTo: 'dashboard', pathMatch: 'full' } ]; class AppRoutingModule { } /***/ }), /***/ "./src/app/app.component.css.shim.ngstyle.js": /*!***************************************************!*\ !*** ./src/app/app.component.css.shim.ngstyle.js ***! \***************************************************/ /*! exports provided: styles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "styles", function() { return styles; }); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles = ["\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzcmMvYXBwL2FwcC5jb21wb25lbnQuY3NzIn0= */"]; /***/ }), /***/ "./src/app/app.component.ngfactory.js": /*!********************************************!*\ !*** ./src/app/app.component.ngfactory.js ***! \********************************************/ /*! exports provided: RenderType_AppComponent, View_AppComponent_0, View_AppComponent_Host_0, AppComponentNgFactory */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderType_AppComponent", function() { return RenderType_AppComponent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_AppComponent_0", function() { return View_AppComponent_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_AppComponent_Host_0", function() { return View_AppComponent_Host_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AppComponentNgFactory", function() { return AppComponentNgFactory; }); /* harmony import */ var _app_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./app.component.css.shim.ngstyle */ "./src/app/app.component.css.shim.ngstyle.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _angular_router__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/router */ "./node_modules/@angular/router/fesm2015/router.js"); /* harmony import */ var _app_component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./app.component */ "./src/app/app.component.ts"); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles_AppComponent = [_app_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__["styles"]]; var RenderType_AppComponent = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵcrt"]({ encapsulation: 0, styles: styles_AppComponent, data: {} }); function View_AppComponent_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 16777216, null, null, 1, "router-outlet", [], null, null, null, null, null)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 212992, null, 0, _angular_router__WEBPACK_IMPORTED_MODULE_2__["RouterOutlet"], [_angular_router__WEBPACK_IMPORTED_MODULE_2__["ChildrenOutletContexts"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["ComponentFactoryResolver"], [8, null], _angular_core__WEBPACK_IMPORTED_MODULE_1__["ChangeDetectorRef"]], null, null)], function (_ck, _v) { _ck(_v, 1, 0); }, null); } function View_AppComponent_Host_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 1, "app-root", [], null, null, null, View_AppComponent_0, RenderType_AppComponent)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 49152, null, 0, _app_component__WEBPACK_IMPORTED_MODULE_3__["AppComponent"], [], null, null)], null, null); } var AppComponentNgFactory = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵccf"]("app-root", _app_component__WEBPACK_IMPORTED_MODULE_3__["AppComponent"], View_AppComponent_Host_0, {}, {}, []); /***/ }), /***/ "./src/app/app.component.ts": /*!**********************************!*\ !*** ./src/app/app.component.ts ***! \**********************************/ /*! exports provided: AppComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AppComponent", function() { return AppComponent; }); class AppComponent { constructor() { this.title = 'github-analyzer-ui'; } } /***/ }), /***/ "./src/app/app.module.ngfactory.js": /*!*****************************************!*\ !*** ./src/app/app.module.ngfactory.js ***! \*****************************************/ /*! exports provided: AppModuleNgFactory */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AppModuleNgFactory", function() { return AppModuleNgFactory; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _app_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./app.module */ "./src/app/app.module.ts"); /* harmony import */ var _app_component__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./app.component */ "./src/app/app.component.ts"); /* harmony import */ var _node_modules_angular_router_router_ngfactory__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../node_modules/@angular/router/router.ngfactory */ "./node_modules/@angular/router/router.ngfactory.js"); /* harmony import */ var _home_home_component_ngfactory__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./home/home.component.ngfactory */ "./src/app/home/home.component.ngfactory.js"); /* harmony import */ var _dashboard_dashboard_component_ngfactory__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./dashboard/dashboard.component.ngfactory */ "./src/app/dashboard/dashboard.component.ngfactory.js"); /* harmony import */ var _app_component_ngfactory__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./app.component.ngfactory */ "./src/app/app.component.ngfactory.js"); /* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @angular/common */ "./node_modules/@angular/common/fesm2015/common.js"); /* harmony import */ var _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @angular/platform-browser */ "./node_modules/@angular/platform-browser/fesm2015/platform-browser.js"); /* harmony import */ var _angular_router__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @angular/router */ "./node_modules/@angular/router/fesm2015/router.js"); /* harmony import */ var _angular_common_http__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @angular/common/http */ "./node_modules/@angular/common/fesm2015/http.js"); /* harmony import */ var _angular_forms__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @angular/forms */ "./node_modules/@angular/forms/fesm2015/forms.js"); /* harmony import */ var _global_error_handler_service__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./global-error-handler.service */ "./src/app/global-error-handler.service.ts"); /* harmony import */ var _home_home_component__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./home/home.component */ "./src/app/home/home.component.ts"); /* harmony import */ var _shared_services_auth_guard__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./shared/services/auth.guard */ "./src/app/shared/services/auth.guard.ts"); /* harmony import */ var _dashboard_dashboard_component__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./dashboard/dashboard.component */ "./src/app/dashboard/dashboard.component.ts"); /* harmony import */ var _app_routing_module__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./app-routing.module */ "./src/app/app-routing.module.ts"); /* harmony import */ var _home_home_module__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./home/home.module */ "./src/app/home/home.module.ts"); /* harmony import */ var _shared_shared_module__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./shared/shared.module */ "./src/app/shared/shared.module.ts"); /* harmony import */ var _dashboard_dashboard_module__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./dashboard/dashboard.module */ "./src/app/dashboard/dashboard.module.ts"); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var AppModuleNgFactory = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵcmf"](_app_module__WEBPACK_IMPORTED_MODULE_1__["AppModule"], [_app_component__WEBPACK_IMPORTED_MODULE_2__["AppComponent"]], function (_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmod"]([_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](512, _angular_core__WEBPACK_IMPORTED_MODULE_0__["ComponentFactoryResolver"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵCodegenComponentFactoryResolver"], [[8, [_node_modules_angular_router_router_ngfactory__WEBPACK_IMPORTED_MODULE_3__["ɵangular_packages_router_router_lNgFactory"], _home_home_component_ngfactory__WEBPACK_IMPORTED_MODULE_4__["HomeComponentNgFactory"], _dashboard_dashboard_component_ngfactory__WEBPACK_IMPORTED_MODULE_5__["DashboardComponentNgFactory"], _app_component_ngfactory__WEBPACK_IMPORTED_MODULE_6__["AppComponentNgFactory"]]], [3, _angular_core__WEBPACK_IMPORTED_MODULE_0__["ComponentFactoryResolver"]], _angular_core__WEBPACK_IMPORTED_MODULE_0__["NgModuleRef"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](5120, _angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵangular_packages_core_core_p"], [[3, _angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"]]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](4608, _angular_common__WEBPACK_IMPORTED_MODULE_7__["NgLocalization"], _angular_common__WEBPACK_IMPORTED_MODULE_7__["NgLocaleLocalization"], [_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"], [2, _angular_common__WEBPACK_IMPORTED_MODULE_7__["ɵangular_packages_common_common_a"]]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](5120, _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵangular_packages_core_core_ba"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵangular_packages_core_core_r"], [_angular_core__WEBPACK_IMPORTED_MODULE_0__["NgZone"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](5120, _angular_core__WEBPACK_IMPORTED_MODULE_0__["APP_ID"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵangular_packages_core_core_f"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](5120, _angular_core__WEBPACK_IMPORTED_MODULE_0__["IterableDiffers"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵangular_packages_core_core_n"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](5120, _angular_core__WEBPACK_IMPORTED_MODULE_0__["KeyValueDiffers"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵangular_packages_core_core_o"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](4608, _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["DomSanitizer"], _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["ɵDomSanitizerImpl"], [_angular_common__WEBPACK_IMPORTED_MODULE_7__["DOCUMENT"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](6144, _angular_core__WEBPACK_IMPORTED_MODULE_0__["Sanitizer"], null, [_angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["DomSanitizer"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](4608, _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["HAMMER_GESTURE_CONFIG"], _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["HammerGestureConfig"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](5120, _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["EVENT_MANAGER_PLUGINS"], function (p0_0, p0_1, p0_2, p1_0, p2_0, p2_1, p2_2, p2_3) { return [new _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["ɵDomEventsPlugin"](p0_0, p0_1, p0_2), new _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["ɵKeyEventsPlugin"](p1_0), new _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["ɵHammerGesturesPlugin"](p2_0, p2_1, p2_2, p2_3)]; }, [_angular_common__WEBPACK_IMPORTED_MODULE_7__["DOCUMENT"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["NgZone"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["PLATFORM_ID"], _angular_common__WEBPACK_IMPORTED_MODULE_7__["DOCUMENT"], _angular_common__WEBPACK_IMPORTED_MODULE_7__["DOCUMENT"], _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["HAMMER_GESTURE_CONFIG"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵConsole"], [2, _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["HAMMER_LOADER"]]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](4608, _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["EventManager"], _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["EventManager"], [_angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["EVENT_MANAGER_PLUGINS"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["NgZone"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](135680, _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["ɵDomSharedStylesHost"], _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["ɵDomSharedStylesHost"], [_angular_common__WEBPACK_IMPORTED_MODULE_7__["DOCUMENT"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](4608, _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["ɵDomRendererFactory2"], _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["ɵDomRendererFactory2"], [_angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["EventManager"], _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["ɵDomSharedStylesHost"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["APP_ID"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](6144, _angular_core__WEBPACK_IMPORTED_MODULE_0__["RendererFactory2"], null, [_angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["ɵDomRendererFactory2"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](6144, _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["ɵSharedStylesHost"], null, [_angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["ɵDomSharedStylesHost"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](4608, _angular_core__WEBPACK_IMPORTED_MODULE_0__["Testability"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["Testability"], [_angular_core__WEBPACK_IMPORTED_MODULE_0__["NgZone"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](5120, _angular_router__WEBPACK_IMPORTED_MODULE_9__["ActivatedRoute"], _angular_router__WEBPACK_IMPORTED_MODULE_9__["ɵangular_packages_router_router_g"], [_angular_router__WEBPACK_IMPORTED_MODULE_9__["Router"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](4608, _angular_router__WEBPACK_IMPORTED_MODULE_9__["NoPreloading"], _angular_router__WEBPACK_IMPORTED_MODULE_9__["NoPreloading"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](6144, _angular_router__WEBPACK_IMPORTED_MODULE_9__["PreloadingStrategy"], null, [_angular_router__WEBPACK_IMPORTED_MODULE_9__["NoPreloading"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](135680, _angular_router__WEBPACK_IMPORTED_MODULE_9__["RouterPreloader"], _angular_router__WEBPACK_IMPORTED_MODULE_9__["RouterPreloader"], [_angular_router__WEBPACK_IMPORTED_MODULE_9__["Router"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["NgModuleFactoryLoader"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["Compiler"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["Injector"], _angular_router__WEBPACK_IMPORTED_MODULE_9__["PreloadingStrategy"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](4608, _angular_router__WEBPACK_IMPORTED_MODULE_9__["PreloadAllModules"], _angular_router__WEBPACK_IMPORTED_MODULE_9__["PreloadAllModules"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](5120, _angular_router__WEBPACK_IMPORTED_MODULE_9__["ɵangular_packages_router_router_o"], _angular_router__WEBPACK_IMPORTED_MODULE_9__["ɵangular_packages_router_router_c"], [_angular_router__WEBPACK_IMPORTED_MODULE_9__["Router"], _angular_common__WEBPACK_IMPORTED_MODULE_7__["ViewportScroller"], _angular_router__WEBPACK_IMPORTED_MODULE_9__["ROUTER_CONFIGURATION"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](5120, _angular_router__WEBPACK_IMPORTED_MODULE_9__["ROUTER_INITIALIZER"], _angular_router__WEBPACK_IMPORTED_MODULE_9__["ɵangular_packages_router_router_j"], [_angular_router__WEBPACK_IMPORTED_MODULE_9__["ɵangular_packages_router_router_h"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](5120, _angular_core__WEBPACK_IMPORTED_MODULE_0__["APP_BOOTSTRAP_LISTENER"], function (p0_0) { return [p0_0]; }, [_angular_router__WEBPACK_IMPORTED_MODULE_9__["ROUTER_INITIALIZER"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](4608, _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["HttpXsrfTokenExtractor"], _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["ɵangular_packages_common_http_http_g"], [_angular_common__WEBPACK_IMPORTED_MODULE_7__["DOCUMENT"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["PLATFORM_ID"], _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["ɵangular_packages_common_http_http_e"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](4608, _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["ɵangular_packages_common_http_http_h"], _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["ɵangular_packages_common_http_http_h"], [_angular_common_http__WEBPACK_IMPORTED_MODULE_10__["HttpXsrfTokenExtractor"], _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["ɵangular_packages_common_http_http_f"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](5120, _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["HTTP_INTERCEPTORS"], function (p0_0) { return [p0_0]; }, [_angular_common_http__WEBPACK_IMPORTED_MODULE_10__["ɵangular_packages_common_http_http_h"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](4608, _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["ɵangular_packages_common_http_http_d"], _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["ɵangular_packages_common_http_http_d"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](6144, _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["XhrFactory"], null, [_angular_common_http__WEBPACK_IMPORTED_MODULE_10__["ɵangular_packages_common_http_http_d"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](4608, _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["HttpXhrBackend"], _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["HttpXhrBackend"], [_angular_common_http__WEBPACK_IMPORTED_MODULE_10__["XhrFactory"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](6144, _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["HttpBackend"], null, [_angular_common_http__WEBPACK_IMPORTED_MODULE_10__["HttpXhrBackend"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](4608, _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["HttpHandler"], _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["ɵHttpInterceptingHandler"], [_angular_common_http__WEBPACK_IMPORTED_MODULE_10__["HttpBackend"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["Injector"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](4608, _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["HttpClient"], _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["HttpClient"], [_angular_common_http__WEBPACK_IMPORTED_MODULE_10__["HttpHandler"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](4608, _angular_forms__WEBPACK_IMPORTED_MODULE_11__["ɵangular_packages_forms_forms_o"], _angular_forms__WEBPACK_IMPORTED_MODULE_11__["ɵangular_packages_forms_forms_o"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](4608, _angular_forms__WEBPACK_IMPORTED_MODULE_11__["FormBuilder"], _angular_forms__WEBPACK_IMPORTED_MODULE_11__["FormBuilder"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](1073742336, _angular_common__WEBPACK_IMPORTED_MODULE_7__["CommonModule"], _angular_common__WEBPACK_IMPORTED_MODULE_7__["CommonModule"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](512, _angular_core__WEBPACK_IMPORTED_MODULE_0__["ErrorHandler"], _global_error_handler_service__WEBPACK_IMPORTED_MODULE_12__["GlobalErrorHandler"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](1024, _angular_core__WEBPACK_IMPORTED_MODULE_0__["NgProbeToken"], function () { return [_angular_router__WEBPACK_IMPORTED_MODULE_9__["ɵangular_packages_router_router_b"]()]; }, []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](512, _angular_router__WEBPACK_IMPORTED_MODULE_9__["ɵangular_packages_router_router_h"], _angular_router__WEBPACK_IMPORTED_MODULE_9__["ɵangular_packages_router_router_h"], [_angular_core__WEBPACK_IMPORTED_MODULE_0__["Injector"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](1024, _angular_core__WEBPACK_IMPORTED_MODULE_0__["APP_INITIALIZER"], function (p0_0, p1_0) { return [_angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["ɵangular_packages_platform_browser_platform_browser_j"](p0_0), _angular_router__WEBPACK_IMPORTED_MODULE_9__["ɵangular_packages_router_router_i"](p1_0)]; }, [[2, _angular_core__WEBPACK_IMPORTED_MODULE_0__["NgProbeToken"]], _angular_router__WEBPACK_IMPORTED_MODULE_9__["ɵangular_packages_router_router_h"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](512, _angular_core__WEBPACK_IMPORTED_MODULE_0__["ApplicationInitStatus"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["ApplicationInitStatus"], [[2, _angular_core__WEBPACK_IMPORTED_MODULE_0__["APP_INITIALIZER"]]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](131584, _angular_core__WEBPACK_IMPORTED_MODULE_0__["ApplicationRef"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["ApplicationRef"], [_angular_core__WEBPACK_IMPORTED_MODULE_0__["NgZone"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵConsole"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["Injector"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["ErrorHandler"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["ComponentFactoryResolver"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["ApplicationInitStatus"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](1073742336, _angular_core__WEBPACK_IMPORTED_MODULE_0__["ApplicationModule"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["ApplicationModule"], [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ApplicationRef"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](1073742336, _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["BrowserModule"], _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["BrowserModule"], [[3, _angular_platform_browser__WEBPACK_IMPORTED_MODULE_8__["BrowserModule"]]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](1024, _angular_router__WEBPACK_IMPORTED_MODULE_9__["ɵangular_packages_router_router_a"], _angular_router__WEBPACK_IMPORTED_MODULE_9__["ɵangular_packages_router_router_e"], [[3, _angular_router__WEBPACK_IMPORTED_MODULE_9__["Router"]]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](512, _angular_router__WEBPACK_IMPORTED_MODULE_9__["UrlSerializer"], _angular_router__WEBPACK_IMPORTED_MODULE_9__["DefaultUrlSerializer"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](512, _angular_router__WEBPACK_IMPORTED_MODULE_9__["ChildrenOutletContexts"], _angular_router__WEBPACK_IMPORTED_MODULE_9__["ChildrenOutletContexts"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](512, _angular_common__WEBPACK_IMPORTED_MODULE_7__["LocationStrategy"], _angular_common__WEBPACK_IMPORTED_MODULE_7__["HashLocationStrategy"], [_angular_common__WEBPACK_IMPORTED_MODULE_7__["PlatformLocation"], [2, _angular_common__WEBPACK_IMPORTED_MODULE_7__["APP_BASE_HREF"]]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](512, _angular_common__WEBPACK_IMPORTED_MODULE_7__["Location"], _angular_common__WEBPACK_IMPORTED_MODULE_7__["Location"], [_angular_common__WEBPACK_IMPORTED_MODULE_7__["LocationStrategy"], _angular_common__WEBPACK_IMPORTED_MODULE_7__["PlatformLocation"]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](512, _angular_core__WEBPACK_IMPORTED_MODULE_0__["Compiler"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["Compiler"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](512, _angular_core__WEBPACK_IMPORTED_MODULE_0__["NgModuleFactoryLoader"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["SystemJsNgModuleLoader"], [_angular_core__WEBPACK_IMPORTED_MODULE_0__["Compiler"], [2, _angular_core__WEBPACK_IMPORTED_MODULE_0__["SystemJsNgModuleLoaderConfig"]]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](1024, _angular_router__WEBPACK_IMPORTED_MODULE_9__["ROUTES"], function () { return [[{ path: "home", component: _home_home_component__WEBPACK_IMPORTED_MODULE_13__["HomeComponent"] }, { path: "dashboard", canActivate: [_shared_services_auth_guard__WEBPACK_IMPORTED_MODULE_14__["AuthGuard"]], component: _dashboard_dashboard_component__WEBPACK_IMPORTED_MODULE_15__["DashboardComponent"] }, { path: "", redirectTo: "dashboard", pathMatch: "full" }]]; }, []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](256, _angular_router__WEBPACK_IMPORTED_MODULE_9__["ROUTER_CONFIGURATION"], {}, []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](1024, _angular_router__WEBPACK_IMPORTED_MODULE_9__["Router"], _angular_router__WEBPACK_IMPORTED_MODULE_9__["ɵangular_packages_router_router_f"], [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ApplicationRef"], _angular_router__WEBPACK_IMPORTED_MODULE_9__["UrlSerializer"], _angular_router__WEBPACK_IMPORTED_MODULE_9__["ChildrenOutletContexts"], _angular_common__WEBPACK_IMPORTED_MODULE_7__["Location"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["Injector"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["NgModuleFactoryLoader"], _angular_core__WEBPACK_IMPORTED_MODULE_0__["Compiler"], _angular_router__WEBPACK_IMPORTED_MODULE_9__["ROUTES"], _angular_router__WEBPACK_IMPORTED_MODULE_9__["ROUTER_CONFIGURATION"], [2, _angular_router__WEBPACK_IMPORTED_MODULE_9__["UrlHandlingStrategy"]], [2, _angular_router__WEBPACK_IMPORTED_MODULE_9__["RouteReuseStrategy"]]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](1073742336, _angular_router__WEBPACK_IMPORTED_MODULE_9__["RouterModule"], _angular_router__WEBPACK_IMPORTED_MODULE_9__["RouterModule"], [[2, _angular_router__WEBPACK_IMPORTED_MODULE_9__["ɵangular_packages_router_router_a"]], [2, _angular_router__WEBPACK_IMPORTED_MODULE_9__["Router"]]]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](1073742336, _app_routing_module__WEBPACK_IMPORTED_MODULE_16__["AppRoutingModule"], _app_routing_module__WEBPACK_IMPORTED_MODULE_16__["AppRoutingModule"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](1073742336, _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["HttpClientXsrfModule"], _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["HttpClientXsrfModule"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](1073742336, _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["HttpClientModule"], _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["HttpClientModule"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](1073742336, _angular_forms__WEBPACK_IMPORTED_MODULE_11__["ɵangular_packages_forms_forms_d"], _angular_forms__WEBPACK_IMPORTED_MODULE_11__["ɵangular_packages_forms_forms_d"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](1073742336, _angular_forms__WEBPACK_IMPORTED_MODULE_11__["FormsModule"], _angular_forms__WEBPACK_IMPORTED_MODULE_11__["FormsModule"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](1073742336, _angular_forms__WEBPACK_IMPORTED_MODULE_11__["ReactiveFormsModule"], _angular_forms__WEBPACK_IMPORTED_MODULE_11__["ReactiveFormsModule"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](1073742336, _home_home_module__WEBPACK_IMPORTED_MODULE_17__["HomeModule"], _home_home_module__WEBPACK_IMPORTED_MODULE_17__["HomeModule"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](1073742336, _shared_shared_module__WEBPACK_IMPORTED_MODULE_18__["SharedModule"], _shared_shared_module__WEBPACK_IMPORTED_MODULE_18__["SharedModule"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](1073742336, _dashboard_dashboard_module__WEBPACK_IMPORTED_MODULE_19__["DashboardModule"], _dashboard_dashboard_module__WEBPACK_IMPORTED_MODULE_19__["DashboardModule"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](1073742336, _app_module__WEBPACK_IMPORTED_MODULE_1__["AppModule"], _app_module__WEBPACK_IMPORTED_MODULE_1__["AppModule"], []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](256, _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵAPP_ROOT"], true, []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](256, _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["ɵangular_packages_common_http_http_e"], "XSRF-TOKEN", []), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵmpd"](256, _angular_common_http__WEBPACK_IMPORTED_MODULE_10__["ɵangular_packages_common_http_http_f"], "X-XSRF-TOKEN", [])]); }); /***/ }), /***/ "./src/app/app.module.ts": /*!*******************************!*\ !*** ./src/app/app.module.ts ***! \*******************************/ /*! exports provided: AppModule */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AppModule", function() { return AppModule; }); class AppModule { } /***/ }), /***/ "./src/app/dashboard/analyzed-repositories/analyzed-repositories.component.css.shim.ngstyle.js": /*!*****************************************************************************************************!*\ !*** ./src/app/dashboard/analyzed-repositories/analyzed-repositories.component.css.shim.ngstyle.js ***! \*****************************************************************************************************/ /*! exports provided: styles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "styles", function() { return styles; }); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles = ["\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzcmMvYXBwL2Rhc2hib2FyZC9hbmFseXplZC1yZXBvc2l0b3JpZXMvYW5hbHl6ZWQtcmVwb3NpdG9yaWVzLmNvbXBvbmVudC5jc3MifQ== */"]; /***/ }), /***/ "./src/app/dashboard/analyzed-repositories/analyzed-repositories.component.ngfactory.js": /*!**********************************************************************************************!*\ !*** ./src/app/dashboard/analyzed-repositories/analyzed-repositories.component.ngfactory.js ***! \**********************************************************************************************/ /*! exports provided: RenderType_AnalyzedRepositoriesComponent, View_AnalyzedRepositoriesComponent_0, View_AnalyzedRepositoriesComponent_Host_0, AnalyzedRepositoriesComponentNgFactory */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderType_AnalyzedRepositoriesComponent", function() { return RenderType_AnalyzedRepositoriesComponent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_AnalyzedRepositoriesComponent_0", function() { return View_AnalyzedRepositoriesComponent_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_AnalyzedRepositoriesComponent_Host_0", function() { return View_AnalyzedRepositoriesComponent_Host_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnalyzedRepositoriesComponentNgFactory", function() { return AnalyzedRepositoriesComponentNgFactory; }); /* harmony import */ var _analyzed_repositories_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./analyzed-repositories.component.css.shim.ngstyle */ "./src/app/dashboard/analyzed-repositories/analyzed-repositories.component.css.shim.ngstyle.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/common */ "./node_modules/@angular/common/fesm2015/common.js"); /* harmony import */ var _analyzed_repositories_component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./analyzed-repositories.component */ "./src/app/dashboard/analyzed-repositories/analyzed-repositories.component.ts"); /* harmony import */ var _dashboard_service__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../dashboard.service */ "./src/app/dashboard/dashboard.service.ts"); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles_AnalyzedRepositoriesComponent = [_analyzed_repositories_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__["styles"]]; var RenderType_AnalyzedRepositoriesComponent = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵcrt"]({ encapsulation: 0, styles: styles_AnalyzedRepositoriesComponent, data: {} }); function View_AnalyzedRepositoriesComponent_2(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 3, "div", [["class", "col-auto p-0 mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 2, "span", [["class", "bg-info text-white rounded p-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 0, "i", [["class", "fas fa-exclamation-circle"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, [" Forked "]))], null, null); } function View_AnalyzedRepositoriesComponent_3(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 2, "div", [["class", "col-auto p-0 mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 1, "span", [["class", "bg-primary text-white rounded p-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](2, null, ["", ""]))], null, function (_ck, _v) { var currVal_0 = _v.parent.context.$implicit.language; _ck(_v, 2, 0, currVal_0); }); } function View_AnalyzedRepositoriesComponent_1(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 52, null, null, null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 18, "tr", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 1, "th", [["class", "align-middle"], ["scope", "row"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](3, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](4, 0, null, null, 5, "td", [["class", "align-middle"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](5, 0, null, null, 4, "button", [["aria-controls", "row_detail"], ["aria-expanded", "false"], ["class", "btn btn-primary rounded-circle p-0"], ["data-toggle", "collapse"], ["style", "width: 25px;height: 25px;"], ["type", "button"]], [[1, "data-target", 0]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](6, 0, [["plus", 1]], null, 1, "div", [], null, [[null, "click"]], function (_v, en, $event) { var ad = true; if (("click" === en)) { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 6).style.display = "none"; var pd_0 = ((_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 8).style.display = "block") !== false); ad = (pd_0 && ad); } return ad; }, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](7, 0, null, null, 0, "i", [["class", "fas fa-plus"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](8, 0, [["minus", 1]], null, 1, "div", [["style", "display: none;"]], null, [[null, "click"]], function (_v, en, $event) { var ad = true; if (("click" === en)) { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 8).style.display = "none"; var pd_0 = ((_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 6).style.display = "block") !== false); ad = (pd_0 && ad); } return ad; }, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](9, 0, null, null, 0, "i", [["class", "fas fa-minus"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](10, 0, null, null, 2, "td", [["class", "align-middle"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](11, 0, null, null, 1, "a", [], [[8, "href", 4]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](12, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](13, 0, null, null, 1, "td", [["class", "align-middle"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](14, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](15, 0, null, null, 1, "td", [["class", "align-middle"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](16, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](17, 0, null, null, 2, "td", [["class", "align-middle"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](18, null, ["", ""])), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵppd"](19, 2), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](20, 0, null, null, 32, "tr", [["style", "border:0px"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](21, 0, null, null, 31, "td", [["class", "p-0"], ["colspan", "5"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](22, 0, null, null, 30, "div", [["class", "collapse container-fluid"]], [[8, "id", 0]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](23, 0, null, null, 24, "div", [["class", "row pt-3 px-3"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_AnalyzedRepositoriesComponent_2)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](25, 16384, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgIf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"]], { ngIf: [0, "ngIf"] }, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](26, 0, null, null, 4, "div", [["class", "col-auto p-0 mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](27, 0, null, null, 3, "span", [["class", "bg-secondary text-white rounded p-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Watchers"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](29, 0, null, null, 1, "span", [["class", "badge badge-primary ml-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](30, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](31, 0, null, null, 4, "div", [["class", "col-auto p-0 mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](32, 0, null, null, 3, "span", [["class", "bg-secondary text-white rounded p-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Stars"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](34, 0, null, null, 1, "span", [["class", "badge badge-primary ml-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](35, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](36, 0, null, null, 4, "div", [["class", "col-auto p-0 mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](37, 0, null, null, 3, "span", [["class", "bg-secondary text-white rounded p-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Forks"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](39, 0, null, null, 1, "span", [["class", "badge badge-primary ml-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](40, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](41, 0, null, null, 4, "div", [["class", "col-auto p-0 mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](42, 0, null, null, 3, "span", [["class", "bg-secondary text-white rounded p-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Contributers"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](44, 0, null, null, 1, "span", [["class", "badge badge-primary ml-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](45, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_AnalyzedRepositoriesComponent_3)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](47, 16384, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgIf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"]], { ngIf: [0, "ngIf"] }, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](48, 0, null, null, 3, "div", [["class", "row pt-3 px-3"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](49, 0, null, null, 2, "div", [["class", "col p-0"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](50, 0, null, null, 1, "span", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](51, null, [" ", " "])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](52, 0, null, null, 0, "hr", [], null, null, null, null, null))], function (_ck, _v) { var currVal_8 = _v.context.$implicit.isForked; _ck(_v, 25, 0, currVal_8); var currVal_13 = _v.context.$implicit.language; _ck(_v, 47, 0, currVal_13); }, function (_ck, _v) { var currVal_0 = (_v.context.index + 1); _ck(_v, 3, 0, currVal_0); var currVal_1 = ("#repo_analyze_row_detail_" + (_v.context.index + 1)); _ck(_v, 5, 0, currVal_1); var currVal_2 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinlineInterpolate"](1, "", _v.context.$implicit.url, ""); _ck(_v, 11, 0, currVal_2); var currVal_3 = _v.context.$implicit.fullName; _ck(_v, 12, 0, currVal_3); var currVal_4 = _v.context.$implicit.commitsCount; _ck(_v, 14, 0, currVal_4); var currVal_5 = _v.context.$implicit.pullsCount; _ck(_v, 16, 0, currVal_5); var currVal_6 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵunv"](_v, 18, 0, _ck(_v, 19, 0, _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v.parent, 0), _v.context.$implicit.analyzeDateTime, "yyyy-MM-dd hh:mm")); _ck(_v, 18, 0, currVal_6); var currVal_7 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinlineInterpolate"](1, "repo_analyze_row_detail_", (_v.context.index + 1), ""); _ck(_v, 22, 0, currVal_7); var currVal_9 = _v.context.$implicit.watchersCount; _ck(_v, 30, 0, currVal_9); var currVal_10 = _v.context.$implicit.starGazersCount; _ck(_v, 35, 0, currVal_10); var currVal_11 = _v.context.$implicit.forksCount; _ck(_v, 40, 0, currVal_11); var currVal_12 = _v.context.$implicit.contributersCount; _ck(_v, 45, 0, currVal_12); var currVal_14 = _v.context.$implicit.description; _ck(_v, 51, 0, currVal_14); }); } function View_AnalyzedRepositoriesComponent_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵpid"](0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["DatePipe"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["LOCALE_ID"]]), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 22, "div", [["class", "card shadow h-100"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 3, "div", [["class", "card-header card-header py-2 px-3"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](3, 0, null, null, 2, "h5", [["class", "m-0"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](4, 0, null, null, 0, "i", [["class", "fas fa-atom mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](5, null, ["Total ", " Analyzed Repository"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](6, 0, null, null, 17, "div", [["class", "card-body pb-0 overflow-auto scout-scroll"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](7, 0, null, null, 16, "table", [["class", "table table-sm"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](8, 0, null, null, 12, "thead", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](9, 0, null, null, 11, "tr", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](10, 0, null, null, 1, "th", [["scope", "col-auto"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["#"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](12, 0, null, null, 0, "th", [["scope", "col-auto"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](13, 0, null, null, 1, "th", [["scope", "col"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Name"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](15, 0, null, null, 1, "th", [["scope", "col"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Commits"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](17, 0, null, null, 1, "th", [["scope", "col"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Pulls"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](19, 0, null, null, 1, "th", [["scope", "col"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Analyze Time"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](21, 0, null, null, 2, "tbody", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_AnalyzedRepositoriesComponent_1)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](23, 278528, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgForOf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["IterableDiffers"]], { ngForOf: [0, "ngForOf"] }, null)], function (_ck, _v) { var _co = _v.component; var currVal_1 = _co.repos; _ck(_v, 23, 0, currVal_1); }, function (_ck, _v) { var _co = _v.component; var currVal_0 = ((_co.repos == null) ? null : _co.repos.length); _ck(_v, 5, 0, currVal_0); }); } function View_AnalyzedRepositoriesComponent_Host_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 1, "app-analyzed-repositories", [], null, null, null, View_AnalyzedRepositoriesComponent_0, RenderType_AnalyzedRepositoriesComponent)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 245760, null, 0, _analyzed_repositories_component__WEBPACK_IMPORTED_MODULE_3__["AnalyzedRepositoriesComponent"], [_dashboard_service__WEBPACK_IMPORTED_MODULE_4__["DashboardService"]], null, null)], function (_ck, _v) { _ck(_v, 1, 0); }, null); } var AnalyzedRepositoriesComponentNgFactory = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵccf"]("app-analyzed-repositories", _analyzed_repositories_component__WEBPACK_IMPORTED_MODULE_3__["AnalyzedRepositoriesComponent"], View_AnalyzedRepositoriesComponent_Host_0, {}, {}, []); /***/ }), /***/ "./src/app/dashboard/analyzed-repositories/analyzed-repositories.component.ts": /*!************************************************************************************!*\ !*** ./src/app/dashboard/analyzed-repositories/analyzed-repositories.component.ts ***! \************************************************************************************/ /*! exports provided: AnalyzedRepositoriesComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnalyzedRepositoriesComponent", function() { return AnalyzedRepositoriesComponent; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _dashboard_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../dashboard.service */ "./src/app/dashboard/dashboard.service.ts"); class AnalyzedRepositoriesComponent { constructor(dashboardService) { this.dashboardService = dashboardService; } ngOnInit() { this.getAnalyzedRepos(); this.newAnalyzeHappened = this.dashboardService.newAnalyzeHappened.subscribe(x => { this.getAnalyzedRepos(); }); } getAnalyzedRepos() { this.dashboardService.getAnalyzedRepos().subscribe((data) => { this.repos = data; }); } ngOnDestroy() { this.newAnalyzeHappened.unsubscribe(); } } /***/ }), /***/ "./src/app/dashboard/dashboard.component.css.shim.ngstyle.js": /*!*******************************************************************!*\ !*** ./src/app/dashboard/dashboard.component.css.shim.ngstyle.js ***! \*******************************************************************/ /*! exports provided: styles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "styles", function() { return styles; }); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles = ["\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzcmMvYXBwL2Rhc2hib2FyZC9kYXNoYm9hcmQuY29tcG9uZW50LmNzcyJ9 */"]; /***/ }), /***/ "./src/app/dashboard/dashboard.component.ngfactory.js": /*!************************************************************!*\ !*** ./src/app/dashboard/dashboard.component.ngfactory.js ***! \************************************************************/ /*! exports provided: RenderType_DashboardComponent, View_DashboardComponent_0, View_DashboardComponent_Host_0, DashboardComponentNgFactory */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderType_DashboardComponent", function() { return RenderType_DashboardComponent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_DashboardComponent_0", function() { return View_DashboardComponent_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_DashboardComponent_Host_0", function() { return View_DashboardComponent_Host_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashboardComponentNgFactory", function() { return DashboardComponentNgFactory; }); /* harmony import */ var _dashboard_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./dashboard.component.css.shim.ngstyle */ "./src/app/dashboard/dashboard.component.css.shim.ngstyle.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _user_info_user_info_component_ngfactory__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./user-info/user-info.component.ngfactory */ "./src/app/dashboard/user-info/user-info.component.ngfactory.js"); /* harmony import */ var _user_info_user_info_component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./user-info/user-info.component */ "./src/app/dashboard/user-info/user-info.component.ts"); /* harmony import */ var _dashboard_service__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./dashboard.service */ "./src/app/dashboard/dashboard.service.ts"); /* harmony import */ var _follower_users_follower_users_component_ngfactory__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./follower-users/follower-users.component.ngfactory */ "./src/app/dashboard/follower-users/follower-users.component.ngfactory.js"); /* harmony import */ var _follower_users_follower_users_component__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./follower-users/follower-users.component */ "./src/app/dashboard/follower-users/follower-users.component.ts"); /* harmony import */ var _following_users_following_users_component_ngfactory__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./following-users/following-users.component.ngfactory */ "./src/app/dashboard/following-users/following-users.component.ngfactory.js"); /* harmony import */ var _following_users_following_users_component__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./following-users/following-users.component */ "./src/app/dashboard/following-users/following-users.component.ts"); /* harmony import */ var _repositories_repositories_component_ngfactory__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./repositories/repositories.component.ngfactory */ "./src/app/dashboard/repositories/repositories.component.ngfactory.js"); /* harmony import */ var _repositories_repositories_component__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./repositories/repositories.component */ "./src/app/dashboard/repositories/repositories.component.ts"); /* harmony import */ var _repository_search_repository_search_component_ngfactory__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./repository-search/repository-search.component.ngfactory */ "./src/app/dashboard/repository-search/repository-search.component.ngfactory.js"); /* harmony import */ var _repository_search_repository_search_component__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./repository-search/repository-search.component */ "./src/app/dashboard/repository-search/repository-search.component.ts"); /* harmony import */ var _angular_forms__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @angular/forms */ "./node_modules/@angular/forms/fesm2015/forms.js"); /* harmony import */ var _analyzed_repositories_analyzed_repositories_component_ngfactory__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./analyzed-repositories/analyzed-repositories.component.ngfactory */ "./src/app/dashboard/analyzed-repositories/analyzed-repositories.component.ngfactory.js"); /* harmony import */ var _analyzed_repositories_analyzed_repositories_component__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./analyzed-repositories/analyzed-repositories.component */ "./src/app/dashboard/analyzed-repositories/analyzed-repositories.component.ts"); /* harmony import */ var _dashboard_component__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./dashboard.component */ "./src/app/dashboard/dashboard.component.ts"); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles_DashboardComponent = [_dashboard_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__["styles"]]; var RenderType_DashboardComponent = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵcrt"]({ encapsulation: 0, styles: styles_DashboardComponent, data: {} }); function View_DashboardComponent_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 23, "div", [["class", "container-fluid p-3 h-100"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 9, "div", [["class", "row p-3 justify-content-around"], ["style", "height: 30%;"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 2, "div", [["class", "col-4 h-100"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](3, 0, null, null, 1, "app-user-info", [], null, null, null, _user_info_user_info_component_ngfactory__WEBPACK_IMPORTED_MODULE_2__["View_UserInfoComponent_0"], _user_info_user_info_component_ngfactory__WEBPACK_IMPORTED_MODULE_2__["RenderType_UserInfoComponent"])), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](4, 114688, null, 0, _user_info_user_info_component__WEBPACK_IMPORTED_MODULE_3__["UserInfoComponent"], [_dashboard_service__WEBPACK_IMPORTED_MODULE_4__["DashboardService"]], null, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](5, 0, null, null, 2, "div", [["class", "col-3 h-100"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](6, 0, null, null, 1, "app-follower-users", [], null, null, null, _follower_users_follower_users_component_ngfactory__WEBPACK_IMPORTED_MODULE_5__["View_FollowerUsersComponent_0"], _follower_users_follower_users_component_ngfactory__WEBPACK_IMPORTED_MODULE_5__["RenderType_FollowerUsersComponent"])), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](7, 114688, null, 0, _follower_users_follower_users_component__WEBPACK_IMPORTED_MODULE_6__["FollowerUsersComponent"], [_dashboard_service__WEBPACK_IMPORTED_MODULE_4__["DashboardService"]], null, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](8, 0, null, null, 2, "div", [["class", "col-3 h-100"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](9, 0, null, null, 1, "app-following-users", [], null, null, null, _following_users_following_users_component_ngfactory__WEBPACK_IMPORTED_MODULE_7__["View_FollowingUsersComponent_0"], _following_users_following_users_component_ngfactory__WEBPACK_IMPORTED_MODULE_7__["RenderType_FollowingUsersComponent"])), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](10, 114688, null, 0, _following_users_following_users_component__WEBPACK_IMPORTED_MODULE_8__["FollowingUsersComponent"], [_dashboard_service__WEBPACK_IMPORTED_MODULE_4__["DashboardService"]], null, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](11, 0, null, null, 12, "div", [["class", "row pt-3"], ["style", "height: 70%;"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](12, 0, null, null, 2, "div", [["class", "col p-3 mx-3 h-100"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](13, 0, null, null, 1, "app-repositories", [], null, null, null, _repositories_repositories_component_ngfactory__WEBPACK_IMPORTED_MODULE_9__["View_RepositoriesComponent_0"], _repositories_repositories_component_ngfactory__WEBPACK_IMPORTED_MODULE_9__["RenderType_RepositoriesComponent"])), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](14, 114688, null, 0, _repositories_repositories_component__WEBPACK_IMPORTED_MODULE_10__["RepositoriesComponent"], [_dashboard_service__WEBPACK_IMPORTED_MODULE_4__["DashboardService"]], null, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](15, 0, null, null, 8, "div", [["class", "col p-3 mx-3 h-100 d-flex flex-column"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](16, 0, null, null, 3, "div", [["class", "row"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](17, 0, null, null, 2, "div", [["class", "col"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](18, 0, null, null, 1, "app-repository-search", [], null, null, null, _repository_search_repository_search_component_ngfactory__WEBPACK_IMPORTED_MODULE_11__["View_RepositorySearchComponent_0"], _repository_search_repository_search_component_ngfactory__WEBPACK_IMPORTED_MODULE_11__["RenderType_RepositorySearchComponent"])), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](19, 114688, null, 0, _repository_search_repository_search_component__WEBPACK_IMPORTED_MODULE_12__["RepositorySearchComponent"], [_angular_forms__WEBPACK_IMPORTED_MODULE_13__["FormBuilder"], _dashboard_service__WEBPACK_IMPORTED_MODULE_4__["DashboardService"]], null, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](20, 0, null, null, 3, "div", [["class", "row h-100"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](21, 0, null, null, 2, "div", [["class", "col h-100"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](22, 0, null, null, 1, "app-analyzed-repositories", [], null, null, null, _analyzed_repositories_analyzed_repositories_component_ngfactory__WEBPACK_IMPORTED_MODULE_14__["View_AnalyzedRepositoriesComponent_0"], _analyzed_repositories_analyzed_repositories_component_ngfactory__WEBPACK_IMPORTED_MODULE_14__["RenderType_AnalyzedRepositoriesComponent"])), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](23, 245760, null, 0, _analyzed_repositories_analyzed_repositories_component__WEBPACK_IMPORTED_MODULE_15__["AnalyzedRepositoriesComponent"], [_dashboard_service__WEBPACK_IMPORTED_MODULE_4__["DashboardService"]], null, null)], function (_ck, _v) { _ck(_v, 4, 0); _ck(_v, 7, 0); _ck(_v, 10, 0); _ck(_v, 14, 0); _ck(_v, 19, 0); _ck(_v, 23, 0); }, null); } function View_DashboardComponent_Host_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 1, "app-dashboard", [], null, null, null, View_DashboardComponent_0, RenderType_DashboardComponent)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 114688, null, 0, _dashboard_component__WEBPACK_IMPORTED_MODULE_16__["DashboardComponent"], [], null, null)], function (_ck, _v) { _ck(_v, 1, 0); }, null); } var DashboardComponentNgFactory = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵccf"]("app-dashboard", _dashboard_component__WEBPACK_IMPORTED_MODULE_16__["DashboardComponent"], View_DashboardComponent_Host_0, {}, {}, []); /***/ }), /***/ "./src/app/dashboard/dashboard.component.ts": /*!**************************************************!*\ !*** ./src/app/dashboard/dashboard.component.ts ***! \**************************************************/ /*! exports provided: DashboardComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashboardComponent", function() { return DashboardComponent; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); class DashboardComponent { constructor() { } ngOnInit() { } } /***/ }), /***/ "./src/app/dashboard/dashboard.module.ts": /*!***********************************************!*\ !*** ./src/app/dashboard/dashboard.module.ts ***! \***********************************************/ /*! exports provided: DashboardModule */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashboardModule", function() { return DashboardModule; }); class DashboardModule { } /***/ }), /***/ "./src/app/dashboard/dashboard.service.ts": /*!************************************************!*\ !*** ./src/app/dashboard/dashboard.service.ts ***! \************************************************/ /*! exports provided: DashboardService */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashboardService", function() { return DashboardService; }); /* harmony import */ var _angular_common_http__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/common/http */ "./node_modules/@angular/common/fesm2015/http.js"); /* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/_esm2015/index.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); class DashboardService { constructor(http) { this.http = http; this.newAnalyzeHappened = new rxjs__WEBPACK_IMPORTED_MODULE_1__["Subject"](); } getCurrentUserInfo() { return this.http .get('github/api/v1/github/user'); } // get(url: string, options: { // headers?: HttpHeaders | { // [header: string]: string | string[]; // }; // observe?: 'body'; // params?: HttpParams | { // [param: string]: string | string[]; // }; getReadMeFile(ownerName, repoName) { const headers = new _angular_common_http__WEBPACK_IMPORTED_MODULE_0__["HttpHeaders"]() .set('Content-Type', 'text/plain; charset=utf-8'); const params = new _angular_common_http__WEBPACK_IMPORTED_MODULE_0__["HttpParams"]() .set('userName', ownerName) .set('repoName', repoName); return this.http .get('github/api/v1/github/readme/', { params: params, headers: headers, responseType: 'text' }); } getCurrentUserRepos() { return this.http .get('github/api/v1/github/repos'); } getCurrentUserFollowers() { return this.http .get('github/api/v1/github/followers'); } getCurrentUserFollowings() { return this.http .get('github/api/v1/github/followings'); } searchRepositories(userName, repoName) { const params = new _angular_common_http__WEBPACK_IMPORTED_MODULE_0__["HttpParams"]() .set('userName', userName) .set('repoName', repoName); return this.http .get('github/api/v1/github/search-repo/', { params }); } getAnalyzedRepos() { return this.http .get('github/api/v1/analyze'); } analyzeRepo(repo) { return this.http .get(`github/api/v1/analyze/${repo.owner.login}/${repo.name}`).subscribe((newAnalyzeRepo) => { this.newAnalyzeHappened.next(newAnalyzeRepo); alert('New Analyze Added'); }); } } DashboardService.ngInjectableDef = _angular_core__WEBPACK_IMPORTED_MODULE_2__["ɵɵdefineInjectable"]({ factory: function DashboardService_Factory() { return new DashboardService(_angular_core__WEBPACK_IMPORTED_MODULE_2__["ɵɵinject"](_angular_common_http__WEBPACK_IMPORTED_MODULE_0__["HttpClient"])); }, token: DashboardService, providedIn: "root" }); /***/ }), /***/ "./src/app/dashboard/follower-users/follower-users.component.css.shim.ngstyle.js": /*!***************************************************************************************!*\ !*** ./src/app/dashboard/follower-users/follower-users.component.css.shim.ngstyle.js ***! \***************************************************************************************/ /*! exports provided: styles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "styles", function() { return styles; }); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles = ["\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzcmMvYXBwL2Rhc2hib2FyZC9mb2xsb3dlci11c2Vycy9mb2xsb3dlci11c2Vycy5jb21wb25lbnQuY3NzIn0= */"]; /***/ }), /***/ "./src/app/dashboard/follower-users/follower-users.component.ngfactory.js": /*!********************************************************************************!*\ !*** ./src/app/dashboard/follower-users/follower-users.component.ngfactory.js ***! \********************************************************************************/ /*! exports provided: RenderType_FollowerUsersComponent, View_FollowerUsersComponent_0, View_FollowerUsersComponent_Host_0, FollowerUsersComponentNgFactory */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderType_FollowerUsersComponent", function() { return RenderType_FollowerUsersComponent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_FollowerUsersComponent_0", function() { return View_FollowerUsersComponent_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_FollowerUsersComponent_Host_0", function() { return View_FollowerUsersComponent_Host_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FollowerUsersComponentNgFactory", function() { return FollowerUsersComponentNgFactory; }); /* harmony import */ var _follower_users_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./follower-users.component.css.shim.ngstyle */ "./src/app/dashboard/follower-users/follower-users.component.css.shim.ngstyle.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _shared_components_users_users_component_ngfactory__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../shared/components/users/users.component.ngfactory */ "./src/app/shared/components/users/users.component.ngfactory.js"); /* harmony import */ var _shared_components_users_users_component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../shared/components/users/users.component */ "./src/app/shared/components/users/users.component.ts"); /* harmony import */ var _follower_users_component__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./follower-users.component */ "./src/app/dashboard/follower-users/follower-users.component.ts"); /* harmony import */ var _dashboard_service__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../dashboard.service */ "./src/app/dashboard/dashboard.service.ts"); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles_FollowerUsersComponent = [_follower_users_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__["styles"]]; var RenderType_FollowerUsersComponent = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵcrt"]({ encapsulation: 0, styles: styles_FollowerUsersComponent, data: {} }); function View_FollowerUsersComponent_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 1, "app-users", [], null, null, null, _shared_components_users_users_component_ngfactory__WEBPACK_IMPORTED_MODULE_2__["View_UsersComponent_0"], _shared_components_users_users_component_ngfactory__WEBPACK_IMPORTED_MODULE_2__["RenderType_UsersComponent"])), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 114688, null, 0, _shared_components_users_users_component__WEBPACK_IMPORTED_MODULE_3__["UsersComponent"], [], { users: [0, "users"], title: [1, "title"] }, null)], function (_ck, _v) { var _co = _v.component; var currVal_0 = _co.followerUsers; var currVal_1 = _co.title; _ck(_v, 1, 0, currVal_0, currVal_1); }, null); } function View_FollowerUsersComponent_Host_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 1, "app-follower-users", [], null, null, null, View_FollowerUsersComponent_0, RenderType_FollowerUsersComponent)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 114688, null, 0, _follower_users_component__WEBPACK_IMPORTED_MODULE_4__["FollowerUsersComponent"], [_dashboard_service__WEBPACK_IMPORTED_MODULE_5__["DashboardService"]], null, null)], function (_ck, _v) { _ck(_v, 1, 0); }, null); } var FollowerUsersComponentNgFactory = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵccf"]("app-follower-users", _follower_users_component__WEBPACK_IMPORTED_MODULE_4__["FollowerUsersComponent"], View_FollowerUsersComponent_Host_0, {}, {}, []); /***/ }), /***/ "./src/app/dashboard/follower-users/follower-users.component.ts": /*!**********************************************************************!*\ !*** ./src/app/dashboard/follower-users/follower-users.component.ts ***! \**********************************************************************/ /*! exports provided: FollowerUsersComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FollowerUsersComponent", function() { return FollowerUsersComponent; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _dashboard_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../dashboard.service */ "./src/app/dashboard/dashboard.service.ts"); class FollowerUsersComponent { constructor(dashboardService) { this.dashboardService = dashboardService; } ngOnInit() { this.getFollowerUsers(); } getFollowerUsers() { this.dashboardService.getCurrentUserFollowers().subscribe((data) => { this.title = `Total ${data.length} Followers`; this.followerUsers = data; }); } } /***/ }), /***/ "./src/app/dashboard/following-users/following-users.component.css.shim.ngstyle.js": /*!*****************************************************************************************!*\ !*** ./src/app/dashboard/following-users/following-users.component.css.shim.ngstyle.js ***! \*****************************************************************************************/ /*! exports provided: styles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "styles", function() { return styles; }); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles = ["\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzcmMvYXBwL2Rhc2hib2FyZC9mb2xsb3dpbmctdXNlcnMvZm9sbG93aW5nLXVzZXJzLmNvbXBvbmVudC5jc3MifQ== */"]; /***/ }), /***/ "./src/app/dashboard/following-users/following-users.component.ngfactory.js": /*!**********************************************************************************!*\ !*** ./src/app/dashboard/following-users/following-users.component.ngfactory.js ***! \**********************************************************************************/ /*! exports provided: RenderType_FollowingUsersComponent, View_FollowingUsersComponent_0, View_FollowingUsersComponent_Host_0, FollowingUsersComponentNgFactory */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderType_FollowingUsersComponent", function() { return RenderType_FollowingUsersComponent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_FollowingUsersComponent_0", function() { return View_FollowingUsersComponent_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_FollowingUsersComponent_Host_0", function() { return View_FollowingUsersComponent_Host_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FollowingUsersComponentNgFactory", function() { return FollowingUsersComponentNgFactory; }); /* harmony import */ var _following_users_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./following-users.component.css.shim.ngstyle */ "./src/app/dashboard/following-users/following-users.component.css.shim.ngstyle.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _shared_components_users_users_component_ngfactory__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../shared/components/users/users.component.ngfactory */ "./src/app/shared/components/users/users.component.ngfactory.js"); /* harmony import */ var _shared_components_users_users_component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../shared/components/users/users.component */ "./src/app/shared/components/users/users.component.ts"); /* harmony import */ var _following_users_component__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./following-users.component */ "./src/app/dashboard/following-users/following-users.component.ts"); /* harmony import */ var _dashboard_service__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../dashboard.service */ "./src/app/dashboard/dashboard.service.ts"); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles_FollowingUsersComponent = [_following_users_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__["styles"]]; var RenderType_FollowingUsersComponent = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵcrt"]({ encapsulation: 0, styles: styles_FollowingUsersComponent, data: {} }); function View_FollowingUsersComponent_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 1, "app-users", [], null, null, null, _shared_components_users_users_component_ngfactory__WEBPACK_IMPORTED_MODULE_2__["View_UsersComponent_0"], _shared_components_users_users_component_ngfactory__WEBPACK_IMPORTED_MODULE_2__["RenderType_UsersComponent"])), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 114688, null, 0, _shared_components_users_users_component__WEBPACK_IMPORTED_MODULE_3__["UsersComponent"], [], { users: [0, "users"], title: [1, "title"] }, null)], function (_ck, _v) { var _co = _v.component; var currVal_0 = _co.followingUsers; var currVal_1 = _co.title; _ck(_v, 1, 0, currVal_0, currVal_1); }, null); } function View_FollowingUsersComponent_Host_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 1, "app-following-users", [], null, null, null, View_FollowingUsersComponent_0, RenderType_FollowingUsersComponent)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 114688, null, 0, _following_users_component__WEBPACK_IMPORTED_MODULE_4__["FollowingUsersComponent"], [_dashboard_service__WEBPACK_IMPORTED_MODULE_5__["DashboardService"]], null, null)], function (_ck, _v) { _ck(_v, 1, 0); }, null); } var FollowingUsersComponentNgFactory = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵccf"]("app-following-users", _following_users_component__WEBPACK_IMPORTED_MODULE_4__["FollowingUsersComponent"], View_FollowingUsersComponent_Host_0, {}, {}, []); /***/ }), /***/ "./src/app/dashboard/following-users/following-users.component.ts": /*!************************************************************************!*\ !*** ./src/app/dashboard/following-users/following-users.component.ts ***! \************************************************************************/ /*! exports provided: FollowingUsersComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FollowingUsersComponent", function() { return FollowingUsersComponent; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var src_app_shared_models_user_model__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! src/app/shared/models/user.model */ "./src/app/shared/models/user.model.ts"); /* harmony import */ var _dashboard_service__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../dashboard.service */ "./src/app/dashboard/dashboard.service.ts"); class FollowingUsersComponent { constructor(dashboardService) { this.dashboardService = dashboardService; } ngOnInit() { this.getFollowingUsers(); } getFollowingUsers() { this.dashboardService.getCurrentUserFollowings().subscribe((data) => { this.title = `Total ${data.length} Followings`; this.followingUsers = data; }); } prepTestData() { const user = new src_app_shared_models_user_model__WEBPACK_IMPORTED_MODULE_1__["User"](); user.login = 'pattern-lab'; user.id = 4733935; user.avatarUrl = 'https://avatars3.githubusercontent.com/u/4733935?v=4'; user.url = 'https://github.com/pattern-lab'; user.name = 'Pattern Lab'; user.company = null; user.blog = 'http://patternlab.io'; user.location = null; user.email = null; user.bio = null; user.followerCount = 0; user.followingCount = 0; user.createdAt = new Date('2013-06-19T01:49:45Z'); user.updatedAt = new Date('2017-11-20T20:30:51Z'); this.followingUsers = []; this.followingUsers.push(user); this.followingUsers.push(user); this.followingUsers.push(user); this.followingUsers.push(user); this.followingUsers.push(user); this.followingUsers.push(user); this.followingUsers.push(user); this.followingUsers.push(user); this.title = `Total ${this.followingUsers.length} Following`; } } /***/ }), /***/ "./src/app/dashboard/repositories/repositories.component.css.shim.ngstyle.js": /*!***********************************************************************************!*\ !*** ./src/app/dashboard/repositories/repositories.component.css.shim.ngstyle.js ***! \***********************************************************************************/ /*! exports provided: styles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "styles", function() { return styles; }); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles = ["\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzcmMvYXBwL2Rhc2hib2FyZC9yZXBvc2l0b3JpZXMvcmVwb3NpdG9yaWVzLmNvbXBvbmVudC5jc3MifQ== */"]; /***/ }), /***/ "./src/app/dashboard/repositories/repositories.component.ngfactory.js": /*!****************************************************************************!*\ !*** ./src/app/dashboard/repositories/repositories.component.ngfactory.js ***! \****************************************************************************/ /*! exports provided: RenderType_RepositoriesComponent, View_RepositoriesComponent_0, View_RepositoriesComponent_Host_0, RepositoriesComponentNgFactory */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderType_RepositoriesComponent", function() { return RenderType_RepositoriesComponent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_RepositoriesComponent_0", function() { return View_RepositoriesComponent_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_RepositoriesComponent_Host_0", function() { return View_RepositoriesComponent_Host_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RepositoriesComponentNgFactory", function() { return RepositoriesComponentNgFactory; }); /* harmony import */ var _repositories_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./repositories.component.css.shim.ngstyle */ "./src/app/dashboard/repositories/repositories.component.css.shim.ngstyle.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _shared_components_repository_repository_component_ngfactory__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../shared/components/repository/repository.component.ngfactory */ "./src/app/shared/components/repository/repository.component.ngfactory.js"); /* harmony import */ var _shared_components_repository_repository_component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../shared/components/repository/repository.component */ "./src/app/shared/components/repository/repository.component.ts"); /* harmony import */ var _dashboard_service__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../dashboard.service */ "./src/app/dashboard/dashboard.service.ts"); /* harmony import */ var _repositories_component__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./repositories.component */ "./src/app/dashboard/repositories/repositories.component.ts"); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles_RepositoriesComponent = [_repositories_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__["styles"]]; var RenderType_RepositoriesComponent = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵcrt"]({ encapsulation: 0, styles: styles_RepositoriesComponent, data: {} }); function View_RepositoriesComponent_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 1, "app-repository", [], null, null, null, _shared_components_repository_repository_component_ngfactory__WEBPACK_IMPORTED_MODULE_2__["View_RepositoryComponent_0"], _shared_components_repository_repository_component_ngfactory__WEBPACK_IMPORTED_MODULE_2__["RenderType_RepositoryComponent"])), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 114688, null, 0, _shared_components_repository_repository_component__WEBPACK_IMPORTED_MODULE_3__["RepositoryComponent"], [_dashboard_service__WEBPACK_IMPORTED_MODULE_4__["DashboardService"]], { repositories: [0, "repositories"] }, null)], function (_ck, _v) { var _co = _v.component; var currVal_0 = _co.repositories; _ck(_v, 1, 0, currVal_0); }, null); } function View_RepositoriesComponent_Host_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 1, "app-repositories", [], null, null, null, View_RepositoriesComponent_0, RenderType_RepositoriesComponent)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 114688, null, 0, _repositories_component__WEBPACK_IMPORTED_MODULE_5__["RepositoriesComponent"], [_dashboard_service__WEBPACK_IMPORTED_MODULE_4__["DashboardService"]], null, null)], function (_ck, _v) { _ck(_v, 1, 0); }, null); } var RepositoriesComponentNgFactory = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵccf"]("app-repositories", _repositories_component__WEBPACK_IMPORTED_MODULE_5__["RepositoriesComponent"], View_RepositoriesComponent_Host_0, {}, {}, []); /***/ }), /***/ "./src/app/dashboard/repositories/repositories.component.ts": /*!******************************************************************!*\ !*** ./src/app/dashboard/repositories/repositories.component.ts ***! \******************************************************************/ /*! exports provided: RepositoriesComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RepositoriesComponent", function() { return RepositoriesComponent; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _dashboard_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../dashboard.service */ "./src/app/dashboard/dashboard.service.ts"); class RepositoriesComponent { constructor(dashboardService) { this.dashboardService = dashboardService; } ngOnInit() { this.getRepos(); } getRepos() { this.dashboardService.getCurrentUserRepos().subscribe((data) => { this.repositories = data; }); } } /***/ }), /***/ "./src/app/dashboard/repository-search/repository-search-result/repository-search-result.component.css.shim.ngstyle.js": /*!*****************************************************************************************************************************!*\ !*** ./src/app/dashboard/repository-search/repository-search-result/repository-search-result.component.css.shim.ngstyle.js ***! \*****************************************************************************************************************************/ /*! exports provided: styles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "styles", function() { return styles; }); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles = ["\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzcmMvYXBwL2Rhc2hib2FyZC9yZXBvc2l0b3J5LXNlYXJjaC9yZXBvc2l0b3J5LXNlYXJjaC1yZXN1bHQvcmVwb3NpdG9yeS1zZWFyY2gtcmVzdWx0LmNvbXBvbmVudC5jc3MifQ== */"]; /***/ }), /***/ "./src/app/dashboard/repository-search/repository-search-result/repository-search-result.component.ngfactory.js": /*!**********************************************************************************************************************!*\ !*** ./src/app/dashboard/repository-search/repository-search-result/repository-search-result.component.ngfactory.js ***! \**********************************************************************************************************************/ /*! exports provided: RenderType_RepositorySearchResultComponent, View_RepositorySearchResultComponent_0, View_RepositorySearchResultComponent_Host_0, RepositorySearchResultComponentNgFactory */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderType_RepositorySearchResultComponent", function() { return RenderType_RepositorySearchResultComponent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_RepositorySearchResultComponent_0", function() { return View_RepositorySearchResultComponent_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_RepositorySearchResultComponent_Host_0", function() { return View_RepositorySearchResultComponent_Host_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RepositorySearchResultComponentNgFactory", function() { return RepositorySearchResultComponentNgFactory; }); /* harmony import */ var _repository_search_result_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./repository-search-result.component.css.shim.ngstyle */ "./src/app/dashboard/repository-search/repository-search-result/repository-search-result.component.css.shim.ngstyle.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _shared_components_repository_repository_component_ngfactory__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../shared/components/repository/repository.component.ngfactory */ "./src/app/shared/components/repository/repository.component.ngfactory.js"); /* harmony import */ var _shared_components_repository_repository_component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../shared/components/repository/repository.component */ "./src/app/shared/components/repository/repository.component.ts"); /* harmony import */ var _dashboard_service__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../dashboard.service */ "./src/app/dashboard/dashboard.service.ts"); /* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @angular/common */ "./node_modules/@angular/common/fesm2015/common.js"); /* harmony import */ var _repository_search_result_component__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./repository-search-result.component */ "./src/app/dashboard/repository-search/repository-search-result/repository-search-result.component.ts"); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles_RepositorySearchResultComponent = [_repository_search_result_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__["styles"]]; var RenderType_RepositorySearchResultComponent = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵcrt"]({ encapsulation: 0, styles: styles_RepositorySearchResultComponent, data: {} }); function View_RepositorySearchResultComponent_1(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 16, "div", [["class", "modal-open"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 0, "div", [["class", "modal-backdrop fade show"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 14, "div", [["aria-hidden", "true"], ["aria-labelledby", "exampleModalLabel"], ["class", "modal fade show"], ["id", "exampleModal"], ["role", "dialog"], ["style", "display: block;"], ["tabindex", "-1"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](3, 0, null, null, 13, "div", [["class", "modal-dialog"], ["role", "document"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](4, 0, null, null, 12, "div", [["class", "modal-content"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](5, 0, null, null, 5, "div", [["class", "modal-header"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](6, 0, null, null, 1, "h5", [["class", "modal-title"], ["id", "exampleModalLabel"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Search Results"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](8, 0, null, null, 2, "button", [["aria-label", "Close"], ["class", "close"], ["data-dismiss", "modal"], ["type", "button"]], null, [[null, "click"]], function (_v, en, $event) { var ad = true; var _co = _v.component; if (("click" === en)) { var pd_0 = (_co.closeModal() !== false); ad = (pd_0 && ad); } return ad; }, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](9, 0, null, null, 1, "span", [["aria-hidden", "true"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["\u00D7"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](11, 0, null, null, 2, "div", [["class", "modal-body"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](12, 0, null, null, 1, "app-repository", [], null, null, null, _shared_components_repository_repository_component_ngfactory__WEBPACK_IMPORTED_MODULE_2__["View_RepositoryComponent_0"], _shared_components_repository_repository_component_ngfactory__WEBPACK_IMPORTED_MODULE_2__["RenderType_RepositoryComponent"])), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](13, 114688, null, 0, _shared_components_repository_repository_component__WEBPACK_IMPORTED_MODULE_3__["RepositoryComponent"], [_dashboard_service__WEBPACK_IMPORTED_MODULE_4__["DashboardService"]], { repositories: [0, "repositories"] }, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](14, 0, null, null, 2, "div", [["class", "modal-footer"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](15, 0, null, null, 1, "button", [["class", "btn btn-secondary"], ["data-dismiss", "modal"], ["type", "button"]], null, [[null, "click"]], function (_v, en, $event) { var ad = true; var _co = _v.component; if (("click" === en)) { var pd_0 = (_co.closeModal() !== false); ad = (pd_0 && ad); } return ad; }, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Close"]))], function (_ck, _v) { var _co = _v.component; var currVal_0 = _co.repositories; _ck(_v, 13, 0, currVal_0); }, null); } function View_RepositorySearchResultComponent_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_RepositorySearchResultComponent_1)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 16384, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_5__["NgIf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"]], { ngIf: [0, "ngIf"] }, null)], function (_ck, _v) { var _co = _v.component; var currVal_0 = _co.isVisible; _ck(_v, 1, 0, currVal_0); }, null); } function View_RepositorySearchResultComponent_Host_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 1, "app-repository-search-result", [], null, null, null, View_RepositorySearchResultComponent_0, RenderType_RepositorySearchResultComponent)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 114688, null, 0, _repository_search_result_component__WEBPACK_IMPORTED_MODULE_6__["RepositorySearchResultComponent"], [], null, null)], function (_ck, _v) { _ck(_v, 1, 0); }, null); } var RepositorySearchResultComponentNgFactory = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵccf"]("app-repository-search-result", _repository_search_result_component__WEBPACK_IMPORTED_MODULE_6__["RepositorySearchResultComponent"], View_RepositorySearchResultComponent_Host_0, { repositories: "repositories", isVisible: "isVisible" }, { close: "close" }, []); /***/ }), /***/ "./src/app/dashboard/repository-search/repository-search-result/repository-search-result.component.ts": /*!************************************************************************************************************!*\ !*** ./src/app/dashboard/repository-search/repository-search-result/repository-search-result.component.ts ***! \************************************************************************************************************/ /*! exports provided: RepositorySearchResultComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RepositorySearchResultComponent", function() { return RepositorySearchResultComponent; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); class RepositorySearchResultComponent { constructor() { this.close = new _angular_core__WEBPACK_IMPORTED_MODULE_0__["EventEmitter"](); } ngOnInit() { } closeModal() { this.isVisible = false; this.repositories = undefined; this.close.emit(); } } /***/ }), /***/ "./src/app/dashboard/repository-search/repository-search.component.css.shim.ngstyle.js": /*!*********************************************************************************************!*\ !*** ./src/app/dashboard/repository-search/repository-search.component.css.shim.ngstyle.js ***! \*********************************************************************************************/ /*! exports provided: styles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "styles", function() { return styles; }); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles = ["\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzcmMvYXBwL2Rhc2hib2FyZC9yZXBvc2l0b3J5LXNlYXJjaC9yZXBvc2l0b3J5LXNlYXJjaC5jb21wb25lbnQuY3NzIn0= */"]; /***/ }), /***/ "./src/app/dashboard/repository-search/repository-search.component.ngfactory.js": /*!**************************************************************************************!*\ !*** ./src/app/dashboard/repository-search/repository-search.component.ngfactory.js ***! \**************************************************************************************/ /*! exports provided: RenderType_RepositorySearchComponent, View_RepositorySearchComponent_0, View_RepositorySearchComponent_Host_0, RepositorySearchComponentNgFactory */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderType_RepositorySearchComponent", function() { return RenderType_RepositorySearchComponent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_RepositorySearchComponent_0", function() { return View_RepositorySearchComponent_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_RepositorySearchComponent_Host_0", function() { return View_RepositorySearchComponent_Host_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RepositorySearchComponentNgFactory", function() { return RepositorySearchComponentNgFactory; }); /* harmony import */ var _repository_search_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./repository-search.component.css.shim.ngstyle */ "./src/app/dashboard/repository-search/repository-search.component.css.shim.ngstyle.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/common */ "./node_modules/@angular/common/fesm2015/common.js"); /* harmony import */ var _angular_forms__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/forms */ "./node_modules/@angular/forms/fesm2015/forms.js"); /* harmony import */ var _repository_search_result_repository_search_result_component_ngfactory__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./repository-search-result/repository-search-result.component.ngfactory */ "./src/app/dashboard/repository-search/repository-search-result/repository-search-result.component.ngfactory.js"); /* harmony import */ var _repository_search_result_repository_search_result_component__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./repository-search-result/repository-search-result.component */ "./src/app/dashboard/repository-search/repository-search-result/repository-search-result.component.ts"); /* harmony import */ var _repository_search_component__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./repository-search.component */ "./src/app/dashboard/repository-search/repository-search.component.ts"); /* harmony import */ var _dashboard_service__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../dashboard.service */ "./src/app/dashboard/dashboard.service.ts"); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles_RepositorySearchComponent = [_repository_search_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__["styles"]]; var RenderType_RepositorySearchComponent = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵcrt"]({ encapsulation: 0, styles: styles_RepositorySearchComponent, data: {} }); function View_RepositorySearchComponent_2(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 2, "div", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 0, "i", [["class", "fas fa-exclamation-circle"], ["style", "margin-right:0.1rem"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, [" Required "]))], null, null); } function View_RepositorySearchComponent_3(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 2, "div", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 0, "i", [["class", "fas fa-exclamation-circle"], ["style", "margin-right:0.1rem"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, [" Min length 2 "]))], null, null); } function View_RepositorySearchComponent_1(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 4, "div", [["class", "invalid-tooltip"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_RepositorySearchComponent_2)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](2, 16384, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgIf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"]], { ngIf: [0, "ngIf"] }, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_RepositorySearchComponent_3)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](4, 16384, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgIf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"]], { ngIf: [0, "ngIf"] }, null)], function (_ck, _v) { var _co = _v.component; var currVal_0 = _co.searchRepositoryFormControls.userName.errors.required; _ck(_v, 2, 0, currVal_0); var currVal_1 = _co.searchRepositoryFormControls.userName.errors.minlength; _ck(_v, 4, 0, currVal_1); }, null); } function View_RepositorySearchComponent_5(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 2, "div", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 0, "i", [["class", "fas fa-exclamation-circle"], ["style", "margin-right:0.1rem"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, [" Required "]))], null, null); } function View_RepositorySearchComponent_6(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 2, "div", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 0, "i", [["class", "fas fa-exclamation-circle"], ["style", "margin-right:0.1rem"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, [" Min length 2 "]))], null, null); } function View_RepositorySearchComponent_4(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 4, "div", [["class", "invalid-tooltip"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_RepositorySearchComponent_5)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](2, 16384, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgIf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"]], { ngIf: [0, "ngIf"] }, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_RepositorySearchComponent_6)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](4, 16384, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgIf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"]], { ngIf: [0, "ngIf"] }, null)], function (_ck, _v) { var _co = _v.component; var currVal_0 = _co.searchRepositoryFormControls.repoName.errors.required; _ck(_v, 2, 0, currVal_0); var currVal_1 = _co.searchRepositoryFormControls.repoName.errors.minlength; _ck(_v, 4, 0, currVal_1); }, null); } function View_RepositorySearchComponent_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 35, "form", [["class", "form-inline"], ["novalidate", ""]], [[2, "ng-untouched", null], [2, "ng-touched", null], [2, "ng-pristine", null], [2, "ng-dirty", null], [2, "ng-valid", null], [2, "ng-invalid", null], [2, "ng-pending", null]], [[null, "ngSubmit"], [null, "submit"], [null, "reset"]], function (_v, en, $event) { var ad = true; var _co = _v.component; if (("submit" === en)) { var pd_0 = (_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 2).onSubmit($event) !== false); ad = (pd_0 && ad); } if (("reset" === en)) { var pd_1 = (_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 2).onReset() !== false); ad = (pd_1 && ad); } if (("ngSubmit" === en)) { var pd_2 = (_co.onSubmit() !== false); ad = (pd_2 && ad); } return ad; }, null, null)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 16384, null, 0, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["ɵangular_packages_forms_forms_z"], [], null, null), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](2, 540672, null, 0, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["FormGroupDirective"], [[8, null], [8, null]], { form: [0, "form"] }, { ngSubmit: "ngSubmit" }), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵprd"](2048, null, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["ControlContainer"], null, [_angular_forms__WEBPACK_IMPORTED_MODULE_3__["FormGroupDirective"]]), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](4, 16384, null, 0, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["NgControlStatusGroup"], [[4, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["ControlContainer"]]], null, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](5, 0, null, null, 13, "div", [["class", "form-group mb-2 col-3 pl-0"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](6, 0, null, null, 1, "label", [["class", "sr-only"], ["for", "gitHubUser"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["User Name"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](8, 0, null, null, 8, "input", [["class", "form-control w-100"], ["formControlName", "userName"], ["id", "gitHubUser"], ["placeholder", "User Name"], ["type", "text"]], [[2, "ng-untouched", null], [2, "ng-touched", null], [2, "ng-pristine", null], [2, "ng-dirty", null], [2, "ng-valid", null], [2, "ng-invalid", null], [2, "ng-pending", null]], [[null, "input"], [null, "blur"], [null, "compositionstart"], [null, "compositionend"]], function (_v, en, $event) { var ad = true; if (("input" === en)) { var pd_0 = (_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 12)._handleInput($event.target.value) !== false); ad = (pd_0 && ad); } if (("blur" === en)) { var pd_1 = (_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 12).onTouched() !== false); ad = (pd_1 && ad); } if (("compositionstart" === en)) { var pd_2 = (_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 12)._compositionStart() !== false); ad = (pd_2 && ad); } if (("compositionend" === en)) { var pd_3 = (_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 12)._compositionEnd($event.target.value) !== false); ad = (pd_3 && ad); } return ad; }, null, null)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵprd"](512, null, _angular_common__WEBPACK_IMPORTED_MODULE_2__["ɵNgClassImpl"], _angular_common__WEBPACK_IMPORTED_MODULE_2__["ɵNgClassR2Impl"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["IterableDiffers"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["KeyValueDiffers"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["ElementRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["Renderer2"]]), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](10, 278528, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgClass"], [_angular_common__WEBPACK_IMPORTED_MODULE_2__["ɵNgClassImpl"]], { klass: [0, "klass"], ngClass: [1, "ngClass"] }, null), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵpod"](11, { "is-invalid": 0 }), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](12, 16384, null, 0, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["DefaultValueAccessor"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["Renderer2"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["ElementRef"], [2, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["COMPOSITION_BUFFER_MODE"]]], null, null), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵprd"](1024, null, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["NG_VALUE_ACCESSOR"], function (p0_0) { return [p0_0]; }, [_angular_forms__WEBPACK_IMPORTED_MODULE_3__["DefaultValueAccessor"]]), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](14, 671744, null, 0, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["FormControlName"], [[3, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["ControlContainer"]], [8, null], [8, null], [6, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["NG_VALUE_ACCESSOR"]], [2, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["ɵangular_packages_forms_forms_q"]]], { name: [0, "name"] }, null), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵprd"](2048, null, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["NgControl"], null, [_angular_forms__WEBPACK_IMPORTED_MODULE_3__["FormControlName"]]), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](16, 16384, null, 0, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["NgControlStatus"], [[4, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["NgControl"]]], null, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_RepositorySearchComponent_1)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](18, 16384, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgIf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"]], { ngIf: [0, "ngIf"] }, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](19, 0, null, null, 13, "div", [["class", "form-group mx-sm-3 mb-2 col-3 pl-0"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](20, 0, null, null, 1, "label", [["class", "sr-only"], ["for", "gitHubRepo"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Repository Name"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](22, 0, null, null, 8, "input", [["class", "form-control w-100"], ["formControlName", "repoName"], ["id", "gitHubRepo"], ["placeholder", "Repository Name"], ["type", "text"]], [[2, "ng-untouched", null], [2, "ng-touched", null], [2, "ng-pristine", null], [2, "ng-dirty", null], [2, "ng-valid", null], [2, "ng-invalid", null], [2, "ng-pending", null]], [[null, "input"], [null, "blur"], [null, "compositionstart"], [null, "compositionend"]], function (_v, en, $event) { var ad = true; if (("input" === en)) { var pd_0 = (_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 26)._handleInput($event.target.value) !== false); ad = (pd_0 && ad); } if (("blur" === en)) { var pd_1 = (_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 26).onTouched() !== false); ad = (pd_1 && ad); } if (("compositionstart" === en)) { var pd_2 = (_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 26)._compositionStart() !== false); ad = (pd_2 && ad); } if (("compositionend" === en)) { var pd_3 = (_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 26)._compositionEnd($event.target.value) !== false); ad = (pd_3 && ad); } return ad; }, null, null)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵprd"](512, null, _angular_common__WEBPACK_IMPORTED_MODULE_2__["ɵNgClassImpl"], _angular_common__WEBPACK_IMPORTED_MODULE_2__["ɵNgClassR2Impl"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["IterableDiffers"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["KeyValueDiffers"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["ElementRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["Renderer2"]]), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](24, 278528, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgClass"], [_angular_common__WEBPACK_IMPORTED_MODULE_2__["ɵNgClassImpl"]], { klass: [0, "klass"], ngClass: [1, "ngClass"] }, null), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵpod"](25, { "is-invalid": 0 }), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](26, 16384, null, 0, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["DefaultValueAccessor"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["Renderer2"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["ElementRef"], [2, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["COMPOSITION_BUFFER_MODE"]]], null, null), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵprd"](1024, null, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["NG_VALUE_ACCESSOR"], function (p0_0) { return [p0_0]; }, [_angular_forms__WEBPACK_IMPORTED_MODULE_3__["DefaultValueAccessor"]]), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](28, 671744, null, 0, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["FormControlName"], [[3, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["ControlContainer"]], [8, null], [8, null], [6, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["NG_VALUE_ACCESSOR"]], [2, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["ɵangular_packages_forms_forms_q"]]], { name: [0, "name"] }, null), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵprd"](2048, null, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["NgControl"], null, [_angular_forms__WEBPACK_IMPORTED_MODULE_3__["FormControlName"]]), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](30, 16384, null, 0, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["NgControlStatus"], [[4, _angular_forms__WEBPACK_IMPORTED_MODULE_3__["NgControl"]]], null, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_RepositorySearchComponent_4)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](32, 16384, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgIf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"]], { ngIf: [0, "ngIf"] }, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](33, 0, null, null, 2, "button", [["class", "btn btn-primary mb-2"], ["data-target", "#exampleModal"], ["data-toggle", "modal"], ["type", "submit"]], [[8, "disabled", 0]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](34, 0, null, null, 0, "i", [["class", "fas fa-search mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Search Repo"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](36, 0, null, null, 1, "app-repository-search-result", [], null, [[null, "close"]], function (_v, en, $event) { var ad = true; var _co = _v.component; if (("close" === en)) { var pd_0 = ((_co.isSearcResultVisible = false) !== false); ad = (pd_0 && ad); } return ad; }, _repository_search_result_repository_search_result_component_ngfactory__WEBPACK_IMPORTED_MODULE_4__["View_RepositorySearchResultComponent_0"], _repository_search_result_repository_search_result_component_ngfactory__WEBPACK_IMPORTED_MODULE_4__["RenderType_RepositorySearchResultComponent"])), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](37, 114688, null, 0, _repository_search_result_repository_search_result_component__WEBPACK_IMPORTED_MODULE_5__["RepositorySearchResultComponent"], [], { repositories: [0, "repositories"], isVisible: [1, "isVisible"] }, { close: "close" })], function (_ck, _v) { var _co = _v.component; var currVal_7 = _co.searchRepositoryForm; _ck(_v, 2, 0, currVal_7); var currVal_15 = "form-control w-100"; var currVal_16 = _ck(_v, 11, 0, (_co.searchRepositoryFormControls.userName.invalid && _co.searchRepositoryFormControls.userName.dirty)); _ck(_v, 10, 0, currVal_15, currVal_16); var currVal_17 = "userName"; _ck(_v, 14, 0, currVal_17); var currVal_18 = _co.searchRepositoryFormControls.userName.invalid; _ck(_v, 18, 0, currVal_18); var currVal_26 = "form-control w-100"; var currVal_27 = _ck(_v, 25, 0, (_co.searchRepositoryFormControls.repoName.invalid && _co.searchRepositoryFormControls.repoName.dirty)); _ck(_v, 24, 0, currVal_26, currVal_27); var currVal_28 = "repoName"; _ck(_v, 28, 0, currVal_28); var currVal_29 = _co.searchRepositoryFormControls.repoName.invalid; _ck(_v, 32, 0, currVal_29); var currVal_31 = _co.foundedRepositories; var currVal_32 = _co.isSearcResultVisible; _ck(_v, 37, 0, currVal_31, currVal_32); }, function (_ck, _v) { var _co = _v.component; var currVal_0 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 4).ngClassUntouched; var currVal_1 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 4).ngClassTouched; var currVal_2 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 4).ngClassPristine; var currVal_3 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 4).ngClassDirty; var currVal_4 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 4).ngClassValid; var currVal_5 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 4).ngClassInvalid; var currVal_6 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 4).ngClassPending; _ck(_v, 0, 0, currVal_0, currVal_1, currVal_2, currVal_3, currVal_4, currVal_5, currVal_6); var currVal_8 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 16).ngClassUntouched; var currVal_9 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 16).ngClassTouched; var currVal_10 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 16).ngClassPristine; var currVal_11 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 16).ngClassDirty; var currVal_12 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 16).ngClassValid; var currVal_13 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 16).ngClassInvalid; var currVal_14 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 16).ngClassPending; _ck(_v, 8, 0, currVal_8, currVal_9, currVal_10, currVal_11, currVal_12, currVal_13, currVal_14); var currVal_19 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 30).ngClassUntouched; var currVal_20 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 30).ngClassTouched; var currVal_21 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 30).ngClassPristine; var currVal_22 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 30).ngClassDirty; var currVal_23 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 30).ngClassValid; var currVal_24 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 30).ngClassInvalid; var currVal_25 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 30).ngClassPending; _ck(_v, 22, 0, currVal_19, currVal_20, currVal_21, currVal_22, currVal_23, currVal_24, currVal_25); var currVal_30 = !_co.searchRepositoryForm.valid; _ck(_v, 33, 0, currVal_30); }); } function View_RepositorySearchComponent_Host_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 1, "app-repository-search", [], null, null, null, View_RepositorySearchComponent_0, RenderType_RepositorySearchComponent)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 114688, null, 0, _repository_search_component__WEBPACK_IMPORTED_MODULE_6__["RepositorySearchComponent"], [_angular_forms__WEBPACK_IMPORTED_MODULE_3__["FormBuilder"], _dashboard_service__WEBPACK_IMPORTED_MODULE_7__["DashboardService"]], null, null)], function (_ck, _v) { _ck(_v, 1, 0); }, null); } var RepositorySearchComponentNgFactory = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵccf"]("app-repository-search", _repository_search_component__WEBPACK_IMPORTED_MODULE_6__["RepositorySearchComponent"], View_RepositorySearchComponent_Host_0, {}, {}, []); /***/ }), /***/ "./src/app/dashboard/repository-search/repository-search.component.ts": /*!****************************************************************************!*\ !*** ./src/app/dashboard/repository-search/repository-search.component.ts ***! \****************************************************************************/ /*! exports provided: RepositorySearchComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RepositorySearchComponent", function() { return RepositorySearchComponent; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _angular_forms__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/forms */ "./node_modules/@angular/forms/fesm2015/forms.js"); /* harmony import */ var _dashboard_service__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../dashboard.service */ "./src/app/dashboard/dashboard.service.ts"); class RepositorySearchComponent { constructor(fb, dashboardService) { this.fb = fb; this.dashboardService = dashboardService; this.searchRepositoryForm = this.fb.group({ userName: ['', [_angular_forms__WEBPACK_IMPORTED_MODULE_1__["Validators"].required, _angular_forms__WEBPACK_IMPORTED_MODULE_1__["Validators"].minLength(2)]], repoName: ['', [_angular_forms__WEBPACK_IMPORTED_MODULE_1__["Validators"].required, _angular_forms__WEBPACK_IMPORTED_MODULE_1__["Validators"].minLength(2)]] }); this.isSearcResultVisible = false; } get searchRepositoryFormControls() { return this.searchRepositoryForm.controls; } ngOnInit() { } onSubmit() { this.dashboardService.searchRepositories(this.searchRepositoryForm.get('userName').value, this.searchRepositoryForm.get('repoName').value).subscribe((data) => { this.foundedRepositories = data.items; this.isSearcResultVisible = true; }); } } /***/ }), /***/ "./src/app/dashboard/user-info/user-info.component.css.shim.ngstyle.js": /*!*****************************************************************************!*\ !*** ./src/app/dashboard/user-info/user-info.component.css.shim.ngstyle.js ***! \*****************************************************************************/ /*! exports provided: styles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "styles", function() { return styles; }); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles = ["\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzcmMvYXBwL2Rhc2hib2FyZC91c2VyLWluZm8vdXNlci1pbmZvLmNvbXBvbmVudC5jc3MifQ== */"]; /***/ }), /***/ "./src/app/dashboard/user-info/user-info.component.ngfactory.js": /*!**********************************************************************!*\ !*** ./src/app/dashboard/user-info/user-info.component.ngfactory.js ***! \**********************************************************************/ /*! exports provided: RenderType_UserInfoComponent, View_UserInfoComponent_0, View_UserInfoComponent_Host_0, UserInfoComponentNgFactory */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderType_UserInfoComponent", function() { return RenderType_UserInfoComponent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_UserInfoComponent_0", function() { return View_UserInfoComponent_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_UserInfoComponent_Host_0", function() { return View_UserInfoComponent_Host_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserInfoComponentNgFactory", function() { return UserInfoComponentNgFactory; }); /* harmony import */ var _user_info_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./user-info.component.css.shim.ngstyle */ "./src/app/dashboard/user-info/user-info.component.css.shim.ngstyle.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/common */ "./node_modules/@angular/common/fesm2015/common.js"); /* harmony import */ var _user_info_component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./user-info.component */ "./src/app/dashboard/user-info/user-info.component.ts"); /* harmony import */ var _dashboard_service__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../dashboard.service */ "./src/app/dashboard/dashboard.service.ts"); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles_UserInfoComponent = [_user_info_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__["styles"]]; var RenderType_UserInfoComponent = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵcrt"]({ encapsulation: 0, styles: styles_UserInfoComponent, data: {} }); function View_UserInfoComponent_1(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 2, "div", [["class", "row"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 1, "span", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](2, null, [" ", " "]))], null, function (_ck, _v) { var _co = _v.component; var currVal_0 = ((_co.user == null) ? null : _co.user.bio); _ck(_v, 2, 0, currVal_0); }); } function View_UserInfoComponent_2(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 5, "div", [["class", "row"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 1, "div", [["class", "col-1 p-0 text-center"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 0, "i", [["class", "fas fa-user-friends"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](3, 0, null, null, 2, "div", [["class", "col"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](4, 0, null, null, 1, "span", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](5, null, [" ", " "]))], null, function (_ck, _v) { var _co = _v.component; var currVal_0 = ((_co.user == null) ? null : _co.user.company); _ck(_v, 5, 0, currVal_0); }); } function View_UserInfoComponent_3(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 5, "div", [["class", "row"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 1, "div", [["class", "col-1 p-0 text-center"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 0, "i", [["class", "fas fa-map-marker"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](3, 0, null, null, 2, "div", [["class", "col"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](4, 0, null, null, 1, "span", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](5, null, [" ", " "]))], null, function (_ck, _v) { var _co = _v.component; var currVal_0 = ((_co.user == null) ? null : _co.user.location); _ck(_v, 5, 0, currVal_0); }); } function View_UserInfoComponent_4(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 5, "div", [["class", "row"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 1, "div", [["class", "col-1 p-0 text-center"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 0, "i", [["class", "as fa-envelope"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](3, 0, null, null, 2, "div", [["class", "col"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](4, 0, null, null, 1, "span", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](5, null, [" ", " "]))], null, function (_ck, _v) { var _co = _v.component; var currVal_0 = ((_co.user == null) ? null : _co.user.email); _ck(_v, 5, 0, currVal_0); }); } function View_UserInfoComponent_5(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 5, "div", [["class", "row"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 1, "div", [["class", "col-1 p-0 text-center"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 0, "i", [["class", "fas fa-blog"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](3, 0, null, null, 2, "div", [["class", "col"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](4, 0, null, null, 1, "a", [], [[8, "href", 4]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](5, null, ["", ""]))], null, function (_ck, _v) { var _co = _v.component; var currVal_0 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinlineInterpolate"](1, "", ((_co.user == null) ? null : _co.user.blog), ""); _ck(_v, 4, 0, currVal_0); var currVal_1 = ((_co.user == null) ? null : _co.user.blog); _ck(_v, 5, 0, currVal_1); }); } function View_UserInfoComponent_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 22, "div", [["class", "container-fluid h-100 overflow-auto scout-scroll"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 21, "div", [["class", "row h-100"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 1, "div", [["class", "col h-100"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](3, 0, null, null, 0, "img", [["alt", ""], ["class", "img-fluid rounded"], ["style", "max-height: 100%;"]], [[8, "src", 4]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](4, 0, null, null, 9, "div", [["class", "col"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](5, 0, null, null, 3, "div", [["class", "row"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](6, 0, null, null, 2, "a", [], [[8, "href", 4]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](7, 0, null, null, 1, "h3", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](8, null, [" ", " "])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](9, 0, null, null, 2, "div", [["class", "row"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](10, 0, null, null, 1, "h5", [["class", "text-muted font-weight-normal"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](11, null, [" ", " "])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_UserInfoComponent_1)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](13, 16384, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgIf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"]], { ngIf: [0, "ngIf"] }, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](14, 0, null, null, 8, "div", [["class", "col"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_UserInfoComponent_2)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](16, 16384, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgIf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"]], { ngIf: [0, "ngIf"] }, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_UserInfoComponent_3)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](18, 16384, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgIf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"]], { ngIf: [0, "ngIf"] }, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_UserInfoComponent_4)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](20, 16384, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgIf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"]], { ngIf: [0, "ngIf"] }, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_UserInfoComponent_5)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](22, 16384, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgIf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"]], { ngIf: [0, "ngIf"] }, null)], function (_ck, _v) { var _co = _v.component; var currVal_4 = ((_co.user == null) ? null : _co.user.bio); _ck(_v, 13, 0, currVal_4); var currVal_5 = ((_co.user == null) ? null : _co.user.company); _ck(_v, 16, 0, currVal_5); var currVal_6 = ((_co.user == null) ? null : _co.user.location); _ck(_v, 18, 0, currVal_6); var currVal_7 = ((_co.user == null) ? null : _co.user.email); _ck(_v, 20, 0, currVal_7); var currVal_8 = ((_co.user == null) ? null : _co.user.blog); _ck(_v, 22, 0, currVal_8); }, function (_ck, _v) { var _co = _v.component; var currVal_0 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinlineInterpolate"](1, "", ((_co.user == null) ? null : _co.user.avatarUrl), ""); _ck(_v, 3, 0, currVal_0); var currVal_1 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinlineInterpolate"](1, "", ((_co.user == null) ? null : _co.user.url), ""); _ck(_v, 6, 0, currVal_1); var currVal_2 = ((_co.user == null) ? null : _co.user.name); _ck(_v, 8, 0, currVal_2); var currVal_3 = ((_co.user == null) ? null : _co.user.login); _ck(_v, 11, 0, currVal_3); }); } function View_UserInfoComponent_Host_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 1, "app-user-info", [], null, null, null, View_UserInfoComponent_0, RenderType_UserInfoComponent)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 114688, null, 0, _user_info_component__WEBPACK_IMPORTED_MODULE_3__["UserInfoComponent"], [_dashboard_service__WEBPACK_IMPORTED_MODULE_4__["DashboardService"]], null, null)], function (_ck, _v) { _ck(_v, 1, 0); }, null); } var UserInfoComponentNgFactory = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵccf"]("app-user-info", _user_info_component__WEBPACK_IMPORTED_MODULE_3__["UserInfoComponent"], View_UserInfoComponent_Host_0, {}, {}, []); /***/ }), /***/ "./src/app/dashboard/user-info/user-info.component.ts": /*!************************************************************!*\ !*** ./src/app/dashboard/user-info/user-info.component.ts ***! \************************************************************/ /*! exports provided: UserInfoComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserInfoComponent", function() { return UserInfoComponent; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _dashboard_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../dashboard.service */ "./src/app/dashboard/dashboard.service.ts"); class UserInfoComponent { constructor(dashboardService) { this.dashboardService = dashboardService; } ngOnInit() { this.getUserInfo(); } getUserInfo() { this.dashboardService.getCurrentUserInfo().subscribe((data) => { this.user = data; }); } } /***/ }), /***/ "./src/app/global-error-handler.service.ts": /*!*************************************************!*\ !*** ./src/app/global-error-handler.service.ts ***! \*************************************************/ /*! exports provided: GlobalErrorHandler */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GlobalErrorHandler", function() { return GlobalErrorHandler; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); class GlobalErrorHandler { constructor() { } handleError(error) { throw error; } } /***/ }), /***/ "./src/app/home/home.component.css.shim.ngstyle.js": /*!*********************************************************!*\ !*** ./src/app/home/home.component.css.shim.ngstyle.js ***! \*********************************************************/ /*! exports provided: styles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "styles", function() { return styles; }); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles = ["\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzcmMvYXBwL2hvbWUvaG9tZS5jb21wb25lbnQuY3NzIn0= */"]; /***/ }), /***/ "./src/app/home/home.component.ngfactory.js": /*!**************************************************!*\ !*** ./src/app/home/home.component.ngfactory.js ***! \**************************************************/ /*! exports provided: RenderType_HomeComponent, View_HomeComponent_0, View_HomeComponent_Host_0, HomeComponentNgFactory */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderType_HomeComponent", function() { return RenderType_HomeComponent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_HomeComponent_0", function() { return View_HomeComponent_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_HomeComponent_Host_0", function() { return View_HomeComponent_Host_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HomeComponentNgFactory", function() { return HomeComponentNgFactory; }); /* harmony import */ var _home_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./home.component.css.shim.ngstyle */ "./src/app/home/home.component.css.shim.ngstyle.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _top_starrred_repos_top_starrred_repos_component_ngfactory__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./top-starrred-repos/top-starrred-repos.component.ngfactory */ "./src/app/home/top-starrred-repos/top-starrred-repos.component.ngfactory.js"); /* harmony import */ var _top_starrred_repos_top_starrred_repos_component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./top-starrred-repos/top-starrred-repos.component */ "./src/app/home/top-starrred-repos/top-starrred-repos.component.ts"); /* harmony import */ var _home_service__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./home.service */ "./src/app/home/home.service.ts"); /* harmony import */ var _top_followed_users_top_followed_users_component_ngfactory__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./top-followed-users/top-followed-users.component.ngfactory */ "./src/app/home/top-followed-users/top-followed-users.component.ngfactory.js"); /* harmony import */ var _top_followed_users_top_followed_users_component__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./top-followed-users/top-followed-users.component */ "./src/app/home/top-followed-users/top-followed-users.component.ts"); /* harmony import */ var _top_reacted_issues_top_reacted_issues_component_ngfactory__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./top-reacted-issues/top-reacted-issues.component.ngfactory */ "./src/app/home/top-reacted-issues/top-reacted-issues.component.ngfactory.js"); /* harmony import */ var _top_reacted_issues_top_reacted_issues_component__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./top-reacted-issues/top-reacted-issues.component */ "./src/app/home/top-reacted-issues/top-reacted-issues.component.ts"); /* harmony import */ var _home_component__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./home.component */ "./src/app/home/home.component.ts"); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles_HomeComponent = [_home_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__["styles"]]; var RenderType_HomeComponent = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵcrt"]({ encapsulation: 0, styles: styles_HomeComponent, data: {} }); function View_HomeComponent_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 28, "div", [["class", "container-fluid bg-light d-flex h-100 flex-column p-3"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 17, "div", [["class", "row flex-fill"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 16, "div", [["class", "col align-items-center"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](3, 0, null, null, 3, "div", [["class", "row justify-content-center p-3"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](4, 0, null, null, 2, "div", [["class", "col-auto text-primary"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](5, 0, null, null, 1, "h1", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, [" GitHub Respository Analyzer "])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](7, 0, null, null, 3, "div", [["class", "row justify-content-center p-3"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](8, 0, null, null, 2, "div", [["class", "col-auto"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](9, 0, null, null, 1, "h3", [["class", "font-weight-normal"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, [" Easily analyze your repository with GitHub Analyzer, access your analyzes persistent! "])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](11, 0, null, null, 7, "div", [["class", "row justify-content-center align-items-center p-3 "]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](12, 0, null, null, 6, "div", [["class", "col-auto"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](13, 0, null, null, 5, "a", [["class", "btn btn-success p-3"], ["href", "login"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](14, 0, null, null, 4, "span", [["class", "d-flex align-items-center"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](15, 0, null, null, 1, "h1", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](16, 0, null, null, 0, "i", [["class", "fab fa-github mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](17, 0, null, null, 1, "h4", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Sign in with GitHub"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](19, 0, null, null, 9, "div", [["class", "row pt-3 "]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](20, 0, null, null, 2, "div", [["class", "col-4"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](21, 0, null, null, 1, "app-top-starrred-repos", [], null, null, null, _top_starrred_repos_top_starrred_repos_component_ngfactory__WEBPACK_IMPORTED_MODULE_2__["View_TopStarrredReposComponent_0"], _top_starrred_repos_top_starrred_repos_component_ngfactory__WEBPACK_IMPORTED_MODULE_2__["RenderType_TopStarrredReposComponent"])), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](22, 114688, null, 0, _top_starrred_repos_top_starrred_repos_component__WEBPACK_IMPORTED_MODULE_3__["TopStarrredReposComponent"], [_home_service__WEBPACK_IMPORTED_MODULE_4__["HomeService"]], null, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](23, 0, null, null, 2, "div", [["class", "col-4"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](24, 0, null, null, 1, "app-top-followed-users", [], null, null, null, _top_followed_users_top_followed_users_component_ngfactory__WEBPACK_IMPORTED_MODULE_5__["View_TopFollowedUsersComponent_0"], _top_followed_users_top_followed_users_component_ngfactory__WEBPACK_IMPORTED_MODULE_5__["RenderType_TopFollowedUsersComponent"])), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](25, 114688, null, 0, _top_followed_users_top_followed_users_component__WEBPACK_IMPORTED_MODULE_6__["TopFollowedUsersComponent"], [_home_service__WEBPACK_IMPORTED_MODULE_4__["HomeService"]], null, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](26, 0, null, null, 2, "div", [["class", "col-4"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](27, 0, null, null, 1, "app-top-reacted-issues", [], null, null, null, _top_reacted_issues_top_reacted_issues_component_ngfactory__WEBPACK_IMPORTED_MODULE_7__["View_TopReactedIssuesComponent_0"], _top_reacted_issues_top_reacted_issues_component_ngfactory__WEBPACK_IMPORTED_MODULE_7__["RenderType_TopReactedIssuesComponent"])), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](28, 114688, null, 0, _top_reacted_issues_top_reacted_issues_component__WEBPACK_IMPORTED_MODULE_8__["TopReactedIssuesComponent"], [_home_service__WEBPACK_IMPORTED_MODULE_4__["HomeService"]], null, null)], function (_ck, _v) { _ck(_v, 22, 0); _ck(_v, 25, 0); _ck(_v, 28, 0); }, null); } function View_HomeComponent_Host_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 1, "app-home", [], null, null, null, View_HomeComponent_0, RenderType_HomeComponent)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 114688, null, 0, _home_component__WEBPACK_IMPORTED_MODULE_9__["HomeComponent"], [], null, null)], function (_ck, _v) { _ck(_v, 1, 0); }, null); } var HomeComponentNgFactory = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵccf"]("app-home", _home_component__WEBPACK_IMPORTED_MODULE_9__["HomeComponent"], View_HomeComponent_Host_0, {}, {}, []); /***/ }), /***/ "./src/app/home/home.component.ts": /*!****************************************!*\ !*** ./src/app/home/home.component.ts ***! \****************************************/ /*! exports provided: HomeComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HomeComponent", function() { return HomeComponent; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); class HomeComponent { constructor() { } ngOnInit() { } } /***/ }), /***/ "./src/app/home/home.module.ts": /*!*************************************!*\ !*** ./src/app/home/home.module.ts ***! \*************************************/ /*! exports provided: HomeModule */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HomeModule", function() { return HomeModule; }); class HomeModule { } /***/ }), /***/ "./src/app/home/home.service.ts": /*!**************************************!*\ !*** ./src/app/home/home.service.ts ***! \**************************************/ /*! exports provided: HomeService */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HomeService", function() { return HomeService; }); /* harmony import */ var _angular_common_http__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/common/http */ "./node_modules/@angular/common/fesm2015/http.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); class HomeService { constructor(http) { this.http = http; } getTopStarredRepos() { return this.http .get('github/api/v1/statistics/top-starred-repos'); } getTopReactedIssueRepos() { return this.http .get('github/api/v1/statistics/top-reacted-issues'); } getTopFollowedUsers() { return this.http .get('github/api/v1/statistics/top-followed-users'); } } HomeService.ngInjectableDef = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjectable"]({ factory: function HomeService_Factory() { return new HomeService(_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵinject"](_angular_common_http__WEBPACK_IMPORTED_MODULE_0__["HttpClient"])); }, token: HomeService, providedIn: "root" }); /***/ }), /***/ "./src/app/home/top-followed-users/top-followed-users.component.css.shim.ngstyle.js": /*!******************************************************************************************!*\ !*** ./src/app/home/top-followed-users/top-followed-users.component.css.shim.ngstyle.js ***! \******************************************************************************************/ /*! exports provided: styles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "styles", function() { return styles; }); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles = ["\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzcmMvYXBwL2hvbWUvdG9wLWZvbGxvd2VkLXVzZXJzL3RvcC1mb2xsb3dlZC11c2Vycy5jb21wb25lbnQuY3NzIn0= */"]; /***/ }), /***/ "./src/app/home/top-followed-users/top-followed-users.component.ngfactory.js": /*!***********************************************************************************!*\ !*** ./src/app/home/top-followed-users/top-followed-users.component.ngfactory.js ***! \***********************************************************************************/ /*! exports provided: RenderType_TopFollowedUsersComponent, View_TopFollowedUsersComponent_0, View_TopFollowedUsersComponent_Host_0, TopFollowedUsersComponentNgFactory */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderType_TopFollowedUsersComponent", function() { return RenderType_TopFollowedUsersComponent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_TopFollowedUsersComponent_0", function() { return View_TopFollowedUsersComponent_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_TopFollowedUsersComponent_Host_0", function() { return View_TopFollowedUsersComponent_Host_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TopFollowedUsersComponentNgFactory", function() { return TopFollowedUsersComponentNgFactory; }); /* harmony import */ var _top_followed_users_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./top-followed-users.component.css.shim.ngstyle */ "./src/app/home/top-followed-users/top-followed-users.component.css.shim.ngstyle.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/common */ "./node_modules/@angular/common/fesm2015/common.js"); /* harmony import */ var _top_followed_users_component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./top-followed-users.component */ "./src/app/home/top-followed-users/top-followed-users.component.ts"); /* harmony import */ var _home_service__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../home.service */ "./src/app/home/home.service.ts"); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles_TopFollowedUsersComponent = [_top_followed_users_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__["styles"]]; var RenderType_TopFollowedUsersComponent = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵcrt"]({ encapsulation: 0, styles: styles_TopFollowedUsersComponent, data: {} }); function View_TopFollowedUsersComponent_1(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 7, null, null, null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 6, "tr", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 1, "th", [["class", "align-middle"], ["scope", "row"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](3, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](4, 0, null, null, 3, "td", [["class", "align-middle"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](5, 0, null, null, 0, "img", [["alt", ""], ["class", "rounded-circle img-thumbnail mr-2"], ["style", "width: 40px;height: 40px;"]], [[8, "src", 4]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](6, 0, null, null, 1, "a", [], [[8, "href", 4]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](7, null, ["", " "]))], null, function (_ck, _v) { var currVal_0 = (_v.context.index + 1); _ck(_v, 3, 0, currVal_0); var currVal_1 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinlineInterpolate"](1, "", _v.context.$implicit.avatarUrl, ""); _ck(_v, 5, 0, currVal_1); var currVal_2 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinlineInterpolate"](1, "", _v.context.$implicit.url, ""); _ck(_v, 6, 0, currVal_2); var currVal_3 = _v.context.$implicit.login; _ck(_v, 7, 0, currVal_3); }); } function View_TopFollowedUsersComponent_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 17, "div", [["class", "card shadow"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 3, "div", [["class", "card-header card-header py-2 px-3"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 2, "h5", [["class", "m-0"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](3, 0, null, null, 0, "i", [["class", "fas fa-user-friends mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](4, null, ["Top ", " Most Followed Users"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](5, 0, null, null, 12, "div", [["class", "card-body pb-0"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](6, 0, null, null, 1, "h6", [["class", "card-subtitle mb-2 text-muted"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](7, null, ["Total ", " User"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](8, 0, null, null, 9, "table", [["class", "table table-sm"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](9, 0, null, null, 5, "thead", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](10, 0, null, null, 4, "tr", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](11, 0, null, null, 1, "th", [["scope", "col-auto"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["#"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](13, 0, null, null, 1, "th", [["scope", "col-auto"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Name"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](15, 0, null, null, 2, "tbody", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_TopFollowedUsersComponent_1)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](17, 278528, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgForOf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["IterableDiffers"]], { ngForOf: [0, "ngForOf"] }, null)], function (_ck, _v) { var _co = _v.component; var currVal_2 = _co.users; _ck(_v, 17, 0, currVal_2); }, function (_ck, _v) { var _co = _v.component; var currVal_0 = ((_co.users == null) ? null : _co.users.length); _ck(_v, 4, 0, currVal_0); var currVal_1 = _co.totalUserCount; _ck(_v, 7, 0, currVal_1); }); } function View_TopFollowedUsersComponent_Host_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 1, "app-top-followed-users", [], null, null, null, View_TopFollowedUsersComponent_0, RenderType_TopFollowedUsersComponent)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 114688, null, 0, _top_followed_users_component__WEBPACK_IMPORTED_MODULE_3__["TopFollowedUsersComponent"], [_home_service__WEBPACK_IMPORTED_MODULE_4__["HomeService"]], null, null)], function (_ck, _v) { _ck(_v, 1, 0); }, null); } var TopFollowedUsersComponentNgFactory = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵccf"]("app-top-followed-users", _top_followed_users_component__WEBPACK_IMPORTED_MODULE_3__["TopFollowedUsersComponent"], View_TopFollowedUsersComponent_Host_0, {}, {}, []); /***/ }), /***/ "./src/app/home/top-followed-users/top-followed-users.component.ts": /*!*************************************************************************!*\ !*** ./src/app/home/top-followed-users/top-followed-users.component.ts ***! \*************************************************************************/ /*! exports provided: TopFollowedUsersComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TopFollowedUsersComponent", function() { return TopFollowedUsersComponent; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _home_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../home.service */ "./src/app/home/home.service.ts"); class TopFollowedUsersComponent { constructor(homeService) { this.homeService = homeService; } ngOnInit() { this.homeService.getTopFollowedUsers().subscribe((data) => { this.totalUserCount = data.totalCount; this.users = data.items; }); } } /***/ }), /***/ "./src/app/home/top-reacted-issues/top-reacted-issues.component.css.shim.ngstyle.js": /*!******************************************************************************************!*\ !*** ./src/app/home/top-reacted-issues/top-reacted-issues.component.css.shim.ngstyle.js ***! \******************************************************************************************/ /*! exports provided: styles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "styles", function() { return styles; }); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles = ["\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzcmMvYXBwL2hvbWUvdG9wLXJlYWN0ZWQtaXNzdWVzL3RvcC1yZWFjdGVkLWlzc3Vlcy5jb21wb25lbnQuY3NzIn0= */"]; /***/ }), /***/ "./src/app/home/top-reacted-issues/top-reacted-issues.component.ngfactory.js": /*!***********************************************************************************!*\ !*** ./src/app/home/top-reacted-issues/top-reacted-issues.component.ngfactory.js ***! \***********************************************************************************/ /*! exports provided: RenderType_TopReactedIssuesComponent, View_TopReactedIssuesComponent_0, View_TopReactedIssuesComponent_Host_0, TopReactedIssuesComponentNgFactory */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderType_TopReactedIssuesComponent", function() { return RenderType_TopReactedIssuesComponent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_TopReactedIssuesComponent_0", function() { return View_TopReactedIssuesComponent_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_TopReactedIssuesComponent_Host_0", function() { return View_TopReactedIssuesComponent_Host_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TopReactedIssuesComponentNgFactory", function() { return TopReactedIssuesComponentNgFactory; }); /* harmony import */ var _top_reacted_issues_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./top-reacted-issues.component.css.shim.ngstyle */ "./src/app/home/top-reacted-issues/top-reacted-issues.component.css.shim.ngstyle.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/common */ "./node_modules/@angular/common/fesm2015/common.js"); /* harmony import */ var _top_reacted_issues_component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./top-reacted-issues.component */ "./src/app/home/top-reacted-issues/top-reacted-issues.component.ts"); /* harmony import */ var _home_service__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../home.service */ "./src/app/home/home.service.ts"); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles_TopReactedIssuesComponent = [_top_reacted_issues_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__["styles"]]; var RenderType_TopReactedIssuesComponent = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵcrt"]({ encapsulation: 0, styles: styles_TopReactedIssuesComponent, data: {} }); function View_TopReactedIssuesComponent_1(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 10, null, null, null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 9, "tr", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 1, "th", [["class", "align-middle"], ["scope", "row"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵ
(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](4, 0, null, null, 2, "td", [["class", "align-middle"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](5, 0, null, null, 1, "a", [], [[8, "href", 4]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](6, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](7, 0, null, null, 3, "td", [["class", "align-middle"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](8, 0, null, null, 0, "img", [["alt", ""], ["class", "rounded-circle img-thumbnail mr-2"], ["style", "width: 40px;height: 40px;"]], [[8, "src", 4]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](9, 0, null, null, 1, "a", [], [[8, "href", 4]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](10, null, ["", " "]))], null, function (_ck, _v) { var currVal_0 = (_v.context.index + 1); _ck(_v, 3, 0, currVal_0); var currVal_1 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinlineInterpolate"](1, "", _v.context.$implicit.url, ""); _ck(_v, 5, 0, currVal_1); var currVal_2 = _v.context.$implicit.title; _ck(_v, 6, 0, currVal_2); var currVal_3 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinlineInterpolate"](1, "", _v.context.$implicit.user.avatarUrl, ""); _ck(_v, 8, 0, currVal_3); var currVal_4 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinlineInterpolate"](1, "", _v.context.$implicit.user.url, ""); _ck(_v, 9, 0, currVal_4); var currVal_5 = _v.context.$implicit.user.name; _ck(_v, 10, 0, currVal_5); }); } function View_TopReactedIssuesComponent_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 19, "div", [["class", "card shadow"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 3, "div", [["class", "card-header card-header py-2 px-3"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 2, "h5", [["class", "m-0"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](3, 0, null, null, 0, "i", [["class", "fas fa-radiation-alt mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](4, null, ["Top ", " Most Reacted Issues"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](5, 0, null, null, 14, "div", [["class", "card-body pb-0"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](6, 0, null, null, 1, "h6", [["class", "card-subtitle mb-2 text-muted"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](7, null, ["Total ", " Isssue"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](8, 0, null, null, 11, "table", [["class", "table table-sm"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](9, 0, null, null, 7, "thead", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](10, 0, null, null, 6, "tr", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](11, 0, null, null, 1, "th", [["scope", "col-auto"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["#"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](13, 0, null, null, 1, "th", [["scope", "col-auto"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Issue"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](15, 0, null, null, 1, "th", [["scope", "col-auto"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Created By"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](17, 0, null, null, 2, "tbody", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_TopReactedIssuesComponent_1)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](19, 278528, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgForOf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["IterableDiffers"]], { ngForOf: [0, "ngForOf"] }, null)], function (_ck, _v) { var _co = _v.component; var currVal_2 = _co.issues; _ck(_v, 19, 0, currVal_2); }, function (_ck, _v) { var _co = _v.component; var currVal_0 = ((_co.issues == null) ? null : _co.issues.length); _ck(_v, 4, 0, currVal_0); var currVal_1 = _co.totalIssueCount; _ck(_v, 7, 0, currVal_1); }); } function View_TopReactedIssuesComponent_Host_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 1, "app-top-reacted-issues", [], null, null, null, View_TopReactedIssuesComponent_0, RenderType_TopReactedIssuesComponent)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 114688, null, 0, _top_reacted_issues_component__WEBPACK_IMPORTED_MODULE_3__["TopReactedIssuesComponent"], [_home_service__WEBPACK_IMPORTED_MODULE_4__["HomeService"]], null, null)], function (_ck, _v) { _ck(_v, 1, 0); }, null); } var TopReactedIssuesComponentNgFactory = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵccf"]("app-top-reacted-issues", _top_reacted_issues_component__WEBPACK_IMPORTED_MODULE_3__["TopReactedIssuesComponent"], View_TopReactedIssuesComponent_Host_0, {}, {}, []); /***/ }), /***/ "./src/app/home/top-reacted-issues/top-reacted-issues.component.ts": /*!*************************************************************************!*\ !*** ./src/app/home/top-reacted-issues/top-reacted-issues.component.ts ***! \*************************************************************************/ /*! exports provided: TopReactedIssuesComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TopReactedIssuesComponent", function() { return TopReactedIssuesComponent; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _home_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../home.service */ "./src/app/home/home.service.ts"); class TopReactedIssuesComponent { constructor(homeService) { this.homeService = homeService; } ngOnInit() { this.homeService.getTopReactedIssueRepos().subscribe((data) => { this.totalIssueCount = data.totalCount; this.issues = data.items; }); } } /***/ }), /***/ "./src/app/home/top-starrred-repos/top-starrred-repos.component.css.shim.ngstyle.js": /*!******************************************************************************************!*\ !*** ./src/app/home/top-starrred-repos/top-starrred-repos.component.css.shim.ngstyle.js ***! \******************************************************************************************/ /*! exports provided: styles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "styles", function() { return styles; }); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles = ["\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzcmMvYXBwL2hvbWUvdG9wLXN0YXJycmVkLXJlcG9zL3RvcC1zdGFycnJlZC1yZXBvcy5jb21wb25lbnQuY3NzIn0= */"]; /***/ }), /***/ "./src/app/home/top-starrred-repos/top-starrred-repos.component.ngfactory.js": /*!***********************************************************************************!*\ !*** ./src/app/home/top-starrred-repos/top-starrred-repos.component.ngfactory.js ***! \***********************************************************************************/ /*! exports provided: RenderType_TopStarrredReposComponent, View_TopStarrredReposComponent_0, View_TopStarrredReposComponent_Host_0, TopStarrredReposComponentNgFactory */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderType_TopStarrredReposComponent", function() { return RenderType_TopStarrredReposComponent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_TopStarrredReposComponent_0", function() { return View_TopStarrredReposComponent_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_TopStarrredReposComponent_Host_0", function() { return View_TopStarrredReposComponent_Host_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TopStarrredReposComponentNgFactory", function() { return TopStarrredReposComponentNgFactory; }); /* harmony import */ var _top_starrred_repos_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./top-starrred-repos.component.css.shim.ngstyle */ "./src/app/home/top-starrred-repos/top-starrred-repos.component.css.shim.ngstyle.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/common */ "./node_modules/@angular/common/fesm2015/common.js"); /* harmony import */ var _top_starrred_repos_component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./top-starrred-repos.component */ "./src/app/home/top-starrred-repos/top-starrred-repos.component.ts"); /* harmony import */ var _home_service__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../home.service */ "./src/app/home/home.service.ts"); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles_TopStarrredReposComponent = [_top_starrred_repos_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__["styles"]]; var RenderType_TopStarrredReposComponent = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵcrt"]({ encapsulation: 0, styles: styles_TopStarrredReposComponent, data: {} }); function View_TopStarrredReposComponent_1(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 12, null, null, null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 11, "tr", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 1, "th", [["class", "align-middle"], ["scope", "row"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](3, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](4, 0, null, null, 4, "td", [["class", "align-middle"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](5, 0, null, null, 1, "a", [], [[8, "href", 4]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](6, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](7, 0, null, null, 1, "span", [["class", "badge badge-primary ml-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](8, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](9, 0, null, null, 3, "td", [["class", "align-middle"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](10, 0, null, null, 0, "img", [["alt", ""], ["class", "rounded-circle img-thumbnail mr-2"], ["style", "width: 40px;height: 40px;"]], [[8, "src", 4]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](11, 0, null, null, 1, "a", [], [[8, "href", 4]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](12, null, ["", " "]))], null, function (_ck, _v) { var currVal_0 = (_v.context.index + 1); _ck(_v, 3, 0, currVal_0); var currVal_1 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinlineInterpolate"](1, "", _v.context.$implicit.url, ""); _ck(_v, 5, 0, currVal_1); var currVal_2 = _v.context.$implicit.fullName; _ck(_v, 6, 0, currVal_2); var currVal_3 = _v.context.$implicit.starGazersCount; _ck(_v, 8, 0, currVal_3); var currVal_4 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinlineInterpolate"](1, "", _v.context.$implicit.owner.avatarUrl, ""); _ck(_v, 10, 0, currVal_4); var currVal_5 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinlineInterpolate"](1, "", _v.context.$implicit.owner.url, ""); _ck(_v, 11, 0, currVal_5); var currVal_6 = _v.context.$implicit.owner.login; _ck(_v, 12, 0, currVal_6); }); } function View_TopStarrredReposComponent_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 19, "div", [["class", "card shadow"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 3, "div", [["class", "card-header card-header py-2 px-3"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 2, "h5", [["class", "m-0"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](3, 0, null, null, 0, "i", [["class", "fas fa-star mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](4, null, ["Top ", " Most Starred Repositories"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](5, 0, null, null, 14, "div", [["class", "card-body pb-0"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](6, 0, null, null, 1, "h6", [["class", "card-subtitle mb-2 text-muted"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](7, null, ["Total ", " Repository"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](8, 0, null, null, 11, "table", [["class", "table table-sm"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](9, 0, null, null, 7, "thead", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](10, 0, null, null, 6, "tr", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](11, 0, null, null, 1, "th", [["scope", "col-auto"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["#"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](13, 0, null, null, 1, "th", [["scope", "col-auto"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Name"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](15, 0, null, null, 1, "th", [["scope", "col-auto"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Owner"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](17, 0, null, null, 2, "tbody", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_TopStarrredReposComponent_1)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](19, 278528, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgForOf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["IterableDiffers"]], { ngForOf: [0, "ngForOf"] }, null)], function (_ck, _v) { var _co = _v.component; var currVal_2 = _co.repositories; _ck(_v, 19, 0, currVal_2); }, function (_ck, _v) { var _co = _v.component; var currVal_0 = ((_co.repositories == null) ? null : _co.repositories.length); _ck(_v, 4, 0, currVal_0); var currVal_1 = _co.totalRepositoryCount; _ck(_v, 7, 0, currVal_1); }); } function View_TopStarrredReposComponent_Host_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 1, "app-top-starrred-repos", [], null, null, null, View_TopStarrredReposComponent_0, RenderType_TopStarrredReposComponent)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 114688, null, 0, _top_starrred_repos_component__WEBPACK_IMPORTED_MODULE_3__["TopStarrredReposComponent"], [_home_service__WEBPACK_IMPORTED_MODULE_4__["HomeService"]], null, null)], function (_ck, _v) { _ck(_v, 1, 0); }, null); } var TopStarrredReposComponentNgFactory = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵccf"]("app-top-starrred-repos", _top_starrred_repos_component__WEBPACK_IMPORTED_MODULE_3__["TopStarrredReposComponent"], View_TopStarrredReposComponent_Host_0, {}, {}, []); /***/ }), /***/ "./src/app/home/top-starrred-repos/top-starrred-repos.component.ts": /*!*************************************************************************!*\ !*** ./src/app/home/top-starrred-repos/top-starrred-repos.component.ts ***! \*************************************************************************/ /*! exports provided: TopStarrredReposComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TopStarrredReposComponent", function() { return TopStarrredReposComponent; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _home_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../home.service */ "./src/app/home/home.service.ts"); class TopStarrredReposComponent { constructor(homeService) { this.homeService = homeService; } ngOnInit() { this.homeService.getTopStarredRepos().subscribe((data) => { this.totalRepositoryCount = data.totalCount; this.repositories = data.items; }); } } /***/ }), /***/ "./src/app/shared/components/readme/readme.component.css.shim.ngstyle.js": /*!*******************************************************************************!*\ !*** ./src/app/shared/components/readme/readme.component.css.shim.ngstyle.js ***! \*******************************************************************************/ /*! exports provided: styles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "styles", function() { return styles; }); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles = ["\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzcmMvYXBwL3NoYXJlZC9jb21wb25lbnRzL3JlYWRtZS9yZWFkbWUuY29tcG9uZW50LmNzcyJ9 */"]; /***/ }), /***/ "./src/app/shared/components/readme/readme.component.ngfactory.js": /*!************************************************************************!*\ !*** ./src/app/shared/components/readme/readme.component.ngfactory.js ***! \************************************************************************/ /*! exports provided: RenderType_ReadmeComponent, View_ReadmeComponent_0, View_ReadmeComponent_Host_0, ReadmeComponentNgFactory */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderType_ReadmeComponent", function() { return RenderType_ReadmeComponent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_ReadmeComponent_0", function() { return View_ReadmeComponent_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_ReadmeComponent_Host_0", function() { return View_ReadmeComponent_Host_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReadmeComponentNgFactory", function() { return ReadmeComponentNgFactory; }); /* harmony import */ var _readme_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./readme.component.css.shim.ngstyle */ "./src/app/shared/components/readme/readme.component.css.shim.ngstyle.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/common */ "./node_modules/@angular/common/fesm2015/common.js"); /* harmony import */ var _readme_component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./readme.component */ "./src/app/shared/components/readme/readme.component.ts"); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles_ReadmeComponent = [_readme_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__["styles"]]; var RenderType_ReadmeComponent = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵcrt"]({ encapsulation: 0, styles: styles_ReadmeComponent, data: {} }); function View_ReadmeComponent_1(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 15, "div", [["class", "modal-open"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 0, "div", [["class", "modal-backdrop fade show"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 13, "div", [["aria-hidden", "true"], ["aria-labelledby", "exampleModalLabel"], ["class", "modal fade show"], ["id", "exampleModal"], ["role", "dialog"], ["style", "display: block;"], ["tabindex", "-1"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](3, 0, null, null, 12, "div", [["class", "modal-dialog"], ["role", "document"], ["style", "max-width: 75%;\n max-height: 75%;"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](4, 0, null, null, 11, "div", [["class", "modal-content h-100"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](5, 0, null, null, 5, "div", [["class", "modal-header"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](6, 0, null, null, 1, "h5", [["class", "modal-title"], ["id", "exampleModalLabel"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Readme.md"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](8, 0, null, null, 2, "button", [["aria-label", "Close"], ["class", "close"], ["data-dismiss", "modal"], ["type", "button"]], null, [[null, "click"]], function (_v, en, $event) { var ad = true; var _co = _v.component; if (("click" === en)) { var pd_0 = (_co.closeModal() !== false); ad = (pd_0 && ad); } return ad; }, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](9, 0, null, null, 1, "span", [["aria-hidden", "true"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["\u00D7"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](11, 0, null, null, 1, "div", [["class", "modal-body overflow-auto scout-scroll"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](12, 0, null, null, 0, "div", [], [[8, "innerHTML", 1]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](13, 0, null, null, 2, "div", [["class", "modal-footer"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](14, 0, null, null, 1, "button", [["class", "btn btn-secondary"], ["data-dismiss", "modal"], ["type", "button"]], null, [[null, "click"]], function (_v, en, $event) { var ad = true; var _co = _v.component; if (("click" === en)) { var pd_0 = (_co.closeModal() !== false); ad = (pd_0 && ad); } return ad; }, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Close"]))], null, function (_ck, _v) { var _co = _v.component; var currVal_0 = _co.readmeData; _ck(_v, 12, 0, currVal_0); }); } function View_ReadmeComponent_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_ReadmeComponent_1)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 16384, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgIf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"]], { ngIf: [0, "ngIf"] }, null)], function (_ck, _v) { var _co = _v.component; var currVal_0 = _co.isVisible; _ck(_v, 1, 0, currVal_0); }, null); } function View_ReadmeComponent_Host_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 1, "app-readme", [], null, null, null, View_ReadmeComponent_0, RenderType_ReadmeComponent)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 114688, null, 0, _readme_component__WEBPACK_IMPORTED_MODULE_3__["ReadmeComponent"], [], null, null)], function (_ck, _v) { _ck(_v, 1, 0); }, null); } var ReadmeComponentNgFactory = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵccf"]("app-readme", _readme_component__WEBPACK_IMPORTED_MODULE_3__["ReadmeComponent"], View_ReadmeComponent_Host_0, { isVisible: "isVisible", readmeData: "readmeData" }, { close: "close" }, []); /***/ }), /***/ "./src/app/shared/components/readme/readme.component.ts": /*!**************************************************************!*\ !*** ./src/app/shared/components/readme/readme.component.ts ***! \**************************************************************/ /*! exports provided: ReadmeComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReadmeComponent", function() { return ReadmeComponent; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); class ReadmeComponent { constructor() { this.close = new _angular_core__WEBPACK_IMPORTED_MODULE_0__["EventEmitter"](); } closeModal() { this.isVisible = false; this.readmeData = undefined; this.close.emit(); } ngOnInit() { } } /***/ }), /***/ "./src/app/shared/components/repository/repository.component.css.shim.ngstyle.js": /*!***************************************************************************************!*\ !*** ./src/app/shared/components/repository/repository.component.css.shim.ngstyle.js ***! \***************************************************************************************/ /*! exports provided: styles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "styles", function() { return styles; }); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles = ["\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzcmMvYXBwL3NoYXJlZC9jb21wb25lbnRzL3JlcG9zaXRvcnkvcmVwb3NpdG9yeS5jb21wb25lbnQuY3NzIn0= */"]; /***/ }), /***/ "./src/app/shared/components/repository/repository.component.ngfactory.js": /*!********************************************************************************!*\ !*** ./src/app/shared/components/repository/repository.component.ngfactory.js ***! \********************************************************************************/ /*! exports provided: RenderType_RepositoryComponent, View_RepositoryComponent_0, View_RepositoryComponent_Host_0, RepositoryComponentNgFactory */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderType_RepositoryComponent", function() { return RenderType_RepositoryComponent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_RepositoryComponent_0", function() { return View_RepositoryComponent_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_RepositoryComponent_Host_0", function() { return View_RepositoryComponent_Host_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RepositoryComponentNgFactory", function() { return RepositoryComponentNgFactory; }); /* harmony import */ var _repository_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./repository.component.css.shim.ngstyle */ "./src/app/shared/components/repository/repository.component.css.shim.ngstyle.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/common */ "./node_modules/@angular/common/fesm2015/common.js"); /* harmony import */ var _readme_readme_component_ngfactory__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../readme/readme.component.ngfactory */ "./src/app/shared/components/readme/readme.component.ngfactory.js"); /* harmony import */ var _readme_readme_component__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../readme/readme.component */ "./src/app/shared/components/readme/readme.component.ts"); /* harmony import */ var _repository_component__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./repository.component */ "./src/app/shared/components/repository/repository.component.ts"); /* harmony import */ var _dashboard_dashboard_service__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../../dashboard/dashboard.service */ "./src/app/dashboard/dashboard.service.ts"); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles_RepositoryComponent = [_repository_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__["styles"]]; var RenderType_RepositoryComponent = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵcrt"]({ encapsulation: 0, styles: styles_RepositoryComponent, data: {} }); function View_RepositoryComponent_2(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 3, "div", [["class", "col-auto p-0 mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 2, "span", [["class", "bg-info text-white rounded p-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 0, "i", [["class", "fas fa-exclamation-circle"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, [" Forked "]))], null, null); } function View_RepositoryComponent_3(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 2, "div", [["class", "col-auto p-0 mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 1, "span", [["class", "bg-primary text-white rounded p-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](2, null, ["", ""]))], null, function (_ck, _v) { var currVal_0 = _v.parent.context.$implicit.language; _ck(_v, 2, 0, currVal_0); }); } function View_RepositoryComponent_1(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 51, null, null, null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 22, "tr", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 1, "th", [["class", "align-middle fit pr-3"], ["scope", "row"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](3, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](4, 0, null, null, 5, "td", [["class", "align-middle fit pr-3"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](5, 0, null, null, 4, "button", [["aria-controls", "row_detail"], ["aria-expanded", "false"], ["class", "btn btn-primary rounded-circle p-0"], ["data-toggle", "collapse"], ["style", "width: 25px;height: 25px;"], ["title", "Detail"], ["type", "button"]], [[1, "data-target", 0]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](6, 0, [["plus", 1]], null, 1, "div", [], null, [[null, "click"]], function (_v, en, $event) { var ad = true; if (("click" === en)) { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 6).style.display = "none"; var pd_0 = ((_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 8).style.display = "block") !== false); ad = (pd_0 && ad); } return ad; }, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](7, 0, null, null, 0, "i", [["class", "fas fa-plus"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](8, 0, [["minus", 1]], null, 1, "div", [["style", "display: none;"]], null, [[null, "click"]], function (_v, en, $event) { var ad = true; if (("click" === en)) { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 8).style.display = "none"; var pd_0 = ((_angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵnov"](_v, 6).style.display = "block") !== false); ad = (pd_0 && ad); } return ad; }, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](9, 0, null, null, 0, "i", [["class", "fas fa-minus"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](10, 0, null, null, 2, "td", [["class", "align-middle fit pr-3"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](11, 0, null, null, 1, "button", [["class", "btn btn-info rounded-circle p-0"], ["style", "width: 25px;height: 25px;"], ["title", "Analyze"], ["type", "button"]], null, [[null, "click"]], function (_v, en, $event) { var ad = true; var _co = _v.component; if (("click" === en)) { var pd_0 = (_co.analyzeRepo(_v.context.$implicit) !== false); ad = (pd_0 && ad); } return ad; }, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](12, 0, null, null, 0, "i", [["class", "fas fa-cog"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](13, 0, null, null, 2, "td", [["class", "align-middle"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](14, 0, null, null, 1, "a", [], [[8, "href", 4]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](15, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](16, 0, null, null, 3, "td", [["class", "align-middle"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](17, 0, null, null, 0, "img", [["alt", ""], ["class", "rounded-circle img-thumbnail mr-2"], ["style", "width: 40px;height: 40px;"]], [[8, "src", 4]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](18, 0, null, null, 1, "a", [], [[8, "href", 4]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](19, null, ["", " "])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](20, 0, null, null, 3, "td", [["class", "align-middle fit pr-3"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](21, 0, null, null, 2, "a", [["href", "#"], ["title", "Show Readme"]], null, [[null, "click"]], function (_v, en, $event) { var ad = true; var _co = _v.component; if (("click" === en)) { var pd_0 = (_co.showReadme(_v.context.$implicit) !== false); ad = (pd_0 && ad); } return ad; }, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](22, 0, null, null, 0, "i", [["class", "fab fa-readme mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Show Readme "])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](24, 0, null, null, 27, "tr", [["style", "border:0px"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](25, 0, null, null, 26, "td", [["class", "p-0"], ["colspan", "5"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](26, 0, null, null, 25, "div", [["class", "collapse container-fluid"]], [[8, "id", 0]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](27, 0, null, null, 19, "div", [["class", "row pt-3 px-3"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_RepositoryComponent_2)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](29, 16384, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgIf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"]], { ngIf: [0, "ngIf"] }, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](30, 0, null, null, 4, "div", [["class", "col-auto p-0 mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](31, 0, null, null, 3, "span", [["class", "bg-secondary text-white rounded p-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Watchers"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](33, 0, null, null, 1, "span", [["class", "badge badge-primary ml-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](34, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](35, 0, null, null, 4, "div", [["class", "col-auto p-0 mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](36, 0, null, null, 3, "span", [["class", "bg-secondary text-white rounded p-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Stars"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](38, 0, null, null, 1, "span", [["class", "badge badge-primary ml-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](39, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](40, 0, null, null, 4, "div", [["class", "col-auto p-0 mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](41, 0, null, null, 3, "span", [["class", "bg-secondary text-white rounded p-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Forks"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](43, 0, null, null, 1, "span", [["class", "badge badge-primary ml-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](44, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_RepositoryComponent_3)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](46, 16384, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgIf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"]], { ngIf: [0, "ngIf"] }, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](47, 0, null, null, 3, "div", [["class", "row pt-3 px-3"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](48, 0, null, null, 2, "div", [["class", "col p-0"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](49, 0, null, null, 1, "span", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](50, null, [" ", " "])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](51, 0, null, null, 0, "hr", [], null, null, null, null, null))], function (_ck, _v) { var currVal_8 = _v.context.$implicit.isForked; _ck(_v, 29, 0, currVal_8); var currVal_12 = _v.context.$implicit.language; _ck(_v, 46, 0, currVal_12); }, function (_ck, _v) { var currVal_0 = (_v.context.index + 1); _ck(_v, 3, 0, currVal_0); var currVal_1 = ("#repo_row_detail_" + (_v.context.index + 1)); _ck(_v, 5, 0, currVal_1); var currVal_2 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinlineInterpolate"](1, "", _v.context.$implicit.url, ""); _ck(_v, 14, 0, currVal_2); var currVal_3 = _v.context.$implicit.fullName; _ck(_v, 15, 0, currVal_3); var currVal_4 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinlineInterpolate"](1, "", _v.context.$implicit.owner.avatarUrl, ""); _ck(_v, 17, 0, currVal_4); var currVal_5 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinlineInterpolate"](1, "", _v.context.$implicit.owner.url, ""); _ck(_v, 18, 0, currVal_5); var currVal_6 = _v.context.$implicit.owner.login; _ck(_v, 19, 0, currVal_6); var currVal_7 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinlineInterpolate"](1, "repo_row_detail_", (_v.context.index + 1), ""); _ck(_v, 26, 0, currVal_7); var currVal_9 = _v.context.$implicit.watchersCount; _ck(_v, 34, 0, currVal_9); var currVal_10 = _v.context.$implicit.starGazersCount; _ck(_v, 39, 0, currVal_10); var currVal_11 = _v.context.$implicit.forksCount; _ck(_v, 44, 0, currVal_11); var currVal_13 = _v.context.$implicit.description; _ck(_v, 50, 0, currVal_13); }); } function View_RepositoryComponent_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 22, "div", [["class", "card shadow h-100 "]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 3, "div", [["class", "card-header card-header py-2 px-3"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 2, "h5", [["class", "m-0"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](3, 0, null, null, 0, "i", [["class", "fas fa-warehouse mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](4, null, ["Total ", " Repository"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](5, 0, null, null, 15, "div", [["class", "card-body pb-0 overflow-auto scout-scroll"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](6, 0, null, null, 14, "table", [["class", "table table-sm"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](7, 0, null, null, 10, "thead", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](8, 0, null, null, 9, "tr", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](9, 0, null, null, 1, "th", [["scope", "col-auto"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["#"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](11, 0, null, null, 0, "th", [["scope", "col-auto"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](12, 0, null, null, 0, "th", [["scope", "col-auto"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](13, 0, null, null, 1, "th", [["scope", "col"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Name"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](15, 0, null, null, 1, "th", [["scope", "col"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Owner"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](17, 0, null, null, 0, "th", [["scope", "col-auto"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](18, 0, null, null, 2, "tbody", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_RepositoryComponent_1)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](20, 278528, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgForOf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["IterableDiffers"]], { ngForOf: [0, "ngForOf"] }, null), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](21, 0, null, null, 1, "div", [["class", "card-footer text-muted"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, [" 2019.08.03 15:03 "])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](23, 0, null, null, 1, "app-readme", [], null, [[null, "close"]], function (_v, en, $event) { var ad = true; var _co = _v.component; if (("close" === en)) { var pd_0 = ((_co.isReadmeVisible = false) !== false); ad = (pd_0 && ad); } return ad; }, _readme_readme_component_ngfactory__WEBPACK_IMPORTED_MODULE_3__["View_ReadmeComponent_0"], _readme_readme_component_ngfactory__WEBPACK_IMPORTED_MODULE_3__["RenderType_ReadmeComponent"])), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](24, 114688, null, 0, _readme_readme_component__WEBPACK_IMPORTED_MODULE_4__["ReadmeComponent"], [], { isVisible: [0, "isVisible"], readmeData: [1, "readmeData"] }, { close: "close" })], function (_ck, _v) { var _co = _v.component; var currVal_1 = _co.repositories; _ck(_v, 20, 0, currVal_1); var currVal_2 = _co.isReadmeVisible; var currVal_3 = _co.readmeData; _ck(_v, 24, 0, currVal_2, currVal_3); }, function (_ck, _v) { var _co = _v.component; var currVal_0 = ((_co.repositories == null) ? null : _co.repositories.length); _ck(_v, 4, 0, currVal_0); }); } function View_RepositoryComponent_Host_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 1, "app-repository", [], null, null, null, View_RepositoryComponent_0, RenderType_RepositoryComponent)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 114688, null, 0, _repository_component__WEBPACK_IMPORTED_MODULE_5__["RepositoryComponent"], [_dashboard_dashboard_service__WEBPACK_IMPORTED_MODULE_6__["DashboardService"]], null, null)], function (_ck, _v) { _ck(_v, 1, 0); }, null); } var RepositoryComponentNgFactory = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵccf"]("app-repository", _repository_component__WEBPACK_IMPORTED_MODULE_5__["RepositoryComponent"], View_RepositoryComponent_Host_0, { repositories: "repositories" }, {}, []); /***/ }), /***/ "./src/app/shared/components/repository/repository.component.ts": /*!**********************************************************************!*\ !*** ./src/app/shared/components/repository/repository.component.ts ***! \**********************************************************************/ /*! exports provided: RepositoryComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RepositoryComponent", function() { return RepositoryComponent; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var src_app_dashboard_dashboard_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! src/app/dashboard/dashboard.service */ "./src/app/dashboard/dashboard.service.ts"); class RepositoryComponent { constructor(dashboardService) { this.dashboardService = dashboardService; this.isReadmeVisible = false; } ngOnInit() { } analyzeRepo(repo) { this.dashboardService.analyzeRepo(repo); } showReadme(repo) { this.dashboardService.getReadMeFile(repo.owner.login, repo.name).subscribe(readmeData => { this.readmeData = readmeData; this.isReadmeVisible = true; }); } onReadmeClose() { this.isReadmeVisible = false; } } /***/ }), /***/ "./src/app/shared/components/users/users.component.css.shim.ngstyle.js": /*!*****************************************************************************!*\ !*** ./src/app/shared/components/users/users.component.css.shim.ngstyle.js ***! \*****************************************************************************/ /*! exports provided: styles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "styles", function() { return styles; }); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles = ["\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzcmMvYXBwL3NoYXJlZC9jb21wb25lbnRzL3VzZXJzL3VzZXJzLmNvbXBvbmVudC5jc3MifQ== */"]; /***/ }), /***/ "./src/app/shared/components/users/users.component.ngfactory.js": /*!**********************************************************************!*\ !*** ./src/app/shared/components/users/users.component.ngfactory.js ***! \**********************************************************************/ /*! exports provided: RenderType_UsersComponent, View_UsersComponent_0, View_UsersComponent_Host_0, UsersComponentNgFactory */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderType_UsersComponent", function() { return RenderType_UsersComponent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_UsersComponent_0", function() { return View_UsersComponent_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "View_UsersComponent_Host_0", function() { return View_UsersComponent_Host_0; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UsersComponentNgFactory", function() { return UsersComponentNgFactory; }); /* harmony import */ var _users_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./users.component.css.shim.ngstyle */ "./src/app/shared/components/users/users.component.css.shim.ngstyle.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/common */ "./node_modules/@angular/common/fesm2015/common.js"); /* harmony import */ var _users_component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./users.component */ "./src/app/shared/components/users/users.component.ts"); /** * @fileoverview This file was generated by the Angular template compiler. Do not edit. * * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride,checkTypes} * tslint:disable */ var styles_UsersComponent = [_users_component_css_shim_ngstyle__WEBPACK_IMPORTED_MODULE_0__["styles"]]; var RenderType_UsersComponent = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵcrt"]({ encapsulation: 0, styles: styles_UsersComponent, data: {} }); function View_UsersComponent_1(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 7, null, null, null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 6, "tr", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 1, "th", [["class", "align-middle"], ["scope", "row"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](3, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](4, 0, null, null, 3, "td", [["class", "align-middle"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](5, 0, null, null, 0, "img", [["alt", ""], ["class", "rounded-circle img-thumbnail mr-2"], ["style", "width: 40px;height: 40px;"]], [[8, "src", 4]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](6, 0, null, null, 1, "a", [], [[8, "href", 4]], null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](7, null, ["", " "]))], null, function (_ck, _v) { var currVal_0 = (_v.context.index + 1); _ck(_v, 3, 0, currVal_0); var currVal_1 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinlineInterpolate"](1, "", _v.context.$implicit.avatarUrl, ""); _ck(_v, 5, 0, currVal_1); var currVal_2 = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵinlineInterpolate"](1, "", _v.context.$implicit.url, ""); _ck(_v, 6, 0, currVal_2); var currVal_3 = _v.context.$implicit.login; _ck(_v, 7, 0, currVal_3); }); } function View_UsersComponent_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 15, "div", [["class", "card shadow h-100"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](1, 0, null, null, 3, "div", [["class", "card-header card-header py-2 px-3"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](2, 0, null, null, 2, "h5", [["class", "m-0"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](3, 0, null, null, 0, "i", [["class", "fas fa-user-friends mr-2"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](4, null, ["", ""])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](5, 0, null, null, 10, "div", [["class", "card-body pb-0 overflow-auto scout-scroll"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](6, 0, null, null, 9, "table", [["class", "table table-sm"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](7, 0, null, null, 5, "thead", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](8, 0, null, null, 4, "tr", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](9, 0, null, null, 1, "th", [["scope", "col-auto"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["#"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](11, 0, null, null, 1, "th", [["scope", "col-auto"]], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵted"](-1, null, ["Name"])), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](13, 0, null, null, 2, "tbody", [], null, null, null, null, null)), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵand"](16777216, null, null, 1, null, View_UsersComponent_1)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](15, 278528, null, 0, _angular_common__WEBPACK_IMPORTED_MODULE_2__["NgForOf"], [_angular_core__WEBPACK_IMPORTED_MODULE_1__["ViewContainerRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["TemplateRef"], _angular_core__WEBPACK_IMPORTED_MODULE_1__["IterableDiffers"]], { ngForOf: [0, "ngForOf"] }, null)], function (_ck, _v) { var _co = _v.component; var currVal_1 = _co.users; _ck(_v, 15, 0, currVal_1); }, function (_ck, _v) { var _co = _v.component; var currVal_0 = _co.title; _ck(_v, 4, 0, currVal_0); }); } function View_UsersComponent_Host_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵvid"](0, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵeld"](0, 0, null, null, 1, "app-users", [], null, null, null, View_UsersComponent_0, RenderType_UsersComponent)), _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵdid"](1, 114688, null, 0, _users_component__WEBPACK_IMPORTED_MODULE_3__["UsersComponent"], [], null, null)], function (_ck, _v) { _ck(_v, 1, 0); }, null); } var UsersComponentNgFactory = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵccf"]("app-users", _users_component__WEBPACK_IMPORTED_MODULE_3__["UsersComponent"], View_UsersComponent_Host_0, { users: "users", title: "title" }, {}, []); /***/ }), /***/ "./src/app/shared/components/users/users.component.ts": /*!************************************************************!*\ !*** ./src/app/shared/components/users/users.component.ts ***! \************************************************************/ /*! exports provided: UsersComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UsersComponent", function() { return UsersComponent; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); class UsersComponent { constructor() { } ngOnInit() { } } /***/ }), /***/ "./src/app/shared/models/user.model.ts": /*!*********************************************!*\ !*** ./src/app/shared/models/user.model.ts ***! \*********************************************/ /*! exports provided: User */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "User", function() { return User; }); class User { } /***/ }), /***/ "./src/app/shared/services/auth.guard.ts": /*!***********************************************!*\ !*** ./src/app/shared/services/auth.guard.ts ***! \***********************************************/ /*! exports provided: AuthGuard */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AuthGuard", function() { return AuthGuard; }); /* harmony import */ var _angular_router__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/router */ "./node_modules/@angular/router/fesm2015/router.js"); /* harmony import */ var _authentication_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./authentication.service */ "./src/app/shared/services/authentication.service.ts"); /* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/_esm2015/index.js"); /* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! rxjs/operators */ "./node_modules/rxjs/_esm2015/operators/index.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); class AuthGuard { constructor(authService, router) { this.authService = authService; this.router = router; } canActivate() { return this.authService.checkIsAuthenticated().pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])(() => { return true; }), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["catchError"])((err) => { this.router.navigate(['home']); return new rxjs__WEBPACK_IMPORTED_MODULE_2__["Observable"](); })); } } AuthGuard.ngInjectableDef = _angular_core__WEBPACK_IMPORTED_MODULE_4__["ɵɵdefineInjectable"]({ factory: function AuthGuard_Factory() { return new AuthGuard(_angular_core__WEBPACK_IMPORTED_MODULE_4__["ɵɵinject"](_authentication_service__WEBPACK_IMPORTED_MODULE_1__["AuthenticationService"]), _angular_core__WEBPACK_IMPORTED_MODULE_4__["ɵɵinject"](_angular_router__WEBPACK_IMPORTED_MODULE_0__["Router"])); }, token: AuthGuard, providedIn: "root" }); /***/ }), /***/ "./src/app/shared/services/authentication.service.ts": /*!***********************************************************!*\ !*** ./src/app/shared/services/authentication.service.ts ***! \***********************************************************/ /*! exports provided: AuthenticationService */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AuthenticationService", function() { return AuthenticationService; }); /* harmony import */ var _angular_common_http__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/common/http */ "./node_modules/@angular/common/fesm2015/http.js"); /* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/_esm2015/index.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); class AuthenticationService { constructor(http) { this.http = http; this.isAuthenticated = false; this.isAuthenticatedChanged = new rxjs__WEBPACK_IMPORTED_MODULE_1__["BehaviorSubject"](this.isAuthenticated); this.authenticatedUserChanged = new rxjs__WEBPACK_IMPORTED_MODULE_1__["BehaviorSubject"](this.authenticatedUser); this.checkIsAuthenticated(); } checkIsAuthenticated() { return this.http.get('github/api/v1/auth/user'); } getAuthenticatedUser() { return Object.assign({}, this.authenticatedUser); } } AuthenticationService.ngInjectableDef = _angular_core__WEBPACK_IMPORTED_MODULE_2__["ɵɵdefineInjectable"]({ factory: function AuthenticationService_Factory() { return new AuthenticationService(_angular_core__WEBPACK_IMPORTED_MODULE_2__["ɵɵinject"](_angular_common_http__WEBPACK_IMPORTED_MODULE_0__["HttpClient"])); }, token: AuthenticationService, providedIn: "root" }); /***/ }), /***/ "./src/app/shared/shared.module.ts": /*!*****************************************!*\ !*** ./src/app/shared/shared.module.ts ***! \*****************************************/ /*! exports provided: SharedModule */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SharedModule", function() { return SharedModule; }); class SharedModule { } /***/ }), /***/ "./src/environments/environment.ts": /*!*****************************************!*\ !*** ./src/environments/environment.ts ***! \*****************************************/ /*! exports provided: environment */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "environment", function() { return environment; }); // This file can be replaced during build by using the `fileReplacements` array. // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. // The list of file replacements can be found in `angular.json`. const environment = { production: false }; /* * For easier debugging in development mode, you can import the following file * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. * * This import should be commented out in production mode because it will have a negative impact * on performance if an error is thrown. */ // import 'zone.js/dist/zone-error'; // Included with Angular CLI. /***/ }), /***/ "./src/main.ts": /*!*********************!*\ !*** ./src/main.ts ***! \*********************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/fesm2015/core.js"); /* harmony import */ var _environments_environment__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./environments/environment */ "./src/environments/environment.ts"); /* harmony import */ var _app_app_module_ngfactory__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./app/app.module.ngfactory */ "./src/app/app.module.ngfactory.js"); /* harmony import */ var _angular_platform_browser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/platform-browser */ "./node_modules/@angular/platform-browser/fesm2015/platform-browser.js"); if (_environments_environment__WEBPACK_IMPORTED_MODULE_1__["environment"].production) { Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["enableProdMode"])(); } _angular_platform_browser__WEBPACK_IMPORTED_MODULE_3__["platformBrowser"]().bootstrapModuleFactory(_app_app_module_ngfactory__WEBPACK_IMPORTED_MODULE_2__["AppModuleNgFactory"]) .catch(err => console.error(err)); /***/ }), /***/ 0: /*!***************************!*\ !*** multi ./src/main.ts ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! C:\Users\Onur\Desktop\home assignment\scout24-home-assignment\frontend\github-analyzer-ui\src\ui-angular-app\src\main.ts */"./src/main.ts"); /***/ }) },[[0,"runtime","vendor"]]]); //# sourceMappingURL=main-es2015.js.map
ted"](3, null, ["", ""])), (_l()
download_cluster_logs_parameters.go
// Code generated by go-swagger; DO NOT EDIT. package installer // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "context" "net/http" "time" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" ) // NewDownloadClusterLogsParams creates a new DownloadClusterLogsParams object // with the default values initialized. func NewDownloadClusterLogsParams() *DownloadClusterLogsParams { var () return &DownloadClusterLogsParams{ timeout: cr.DefaultTimeout, } } // NewDownloadClusterLogsParamsWithTimeout creates a new DownloadClusterLogsParams object // with the default values initialized, and the ability to set a timeout on a request func NewDownloadClusterLogsParamsWithTimeout(timeout time.Duration) *DownloadClusterLogsParams { var () return &DownloadClusterLogsParams{ timeout: timeout, } } // NewDownloadClusterLogsParamsWithContext creates a new DownloadClusterLogsParams object // with the default values initialized, and the ability to set a context for a request func NewDownloadClusterLogsParamsWithContext(ctx context.Context) *DownloadClusterLogsParams { var () return &DownloadClusterLogsParams{ Context: ctx, } } // NewDownloadClusterLogsParamsWithHTTPClient creates a new DownloadClusterLogsParams object // with the default values initialized, and the ability to set a custom HTTPClient for a request func NewDownloadClusterLogsParamsWithHTTPClient(client *http.Client) *DownloadClusterLogsParams { var () return &DownloadClusterLogsParams{ HTTPClient: client, } } /*DownloadClusterLogsParams contains all the parameters to send to the API endpoint for the download cluster logs operation typically these are written to a http.Request */ type DownloadClusterLogsParams struct { /*ClusterID The cluster whose logs should be downloaded. */ ClusterID strfmt.UUID /*HostID A specific host in the cluster whose logs should be downloaded. */ HostID *strfmt.UUID /*LogsType The type of logs to be downloaded. */ LogsType *string timeout time.Duration Context context.Context HTTPClient *http.Client } // WithTimeout adds the timeout to the download cluster logs params func (o *DownloadClusterLogsParams) WithTimeout(timeout time.Duration) *DownloadClusterLogsParams { o.SetTimeout(timeout) return o } // SetTimeout adds the timeout to the download cluster logs params func (o *DownloadClusterLogsParams) SetTimeout(timeout time.Duration) { o.timeout = timeout } // WithContext adds the context to the download cluster logs params
// SetContext adds the context to the download cluster logs params func (o *DownloadClusterLogsParams) SetContext(ctx context.Context) { o.Context = ctx } // WithHTTPClient adds the HTTPClient to the download cluster logs params func (o *DownloadClusterLogsParams) WithHTTPClient(client *http.Client) *DownloadClusterLogsParams { o.SetHTTPClient(client) return o } // SetHTTPClient adds the HTTPClient to the download cluster logs params func (o *DownloadClusterLogsParams) SetHTTPClient(client *http.Client) { o.HTTPClient = client } // WithClusterID adds the clusterID to the download cluster logs params func (o *DownloadClusterLogsParams) WithClusterID(clusterID strfmt.UUID) *DownloadClusterLogsParams { o.SetClusterID(clusterID) return o } // SetClusterID adds the clusterId to the download cluster logs params func (o *DownloadClusterLogsParams) SetClusterID(clusterID strfmt.UUID) { o.ClusterID = clusterID } // WithHostID adds the hostID to the download cluster logs params func (o *DownloadClusterLogsParams) WithHostID(hostID *strfmt.UUID) *DownloadClusterLogsParams { o.SetHostID(hostID) return o } // SetHostID adds the hostId to the download cluster logs params func (o *DownloadClusterLogsParams) SetHostID(hostID *strfmt.UUID) { o.HostID = hostID } // WithLogsType adds the logsType to the download cluster logs params func (o *DownloadClusterLogsParams) WithLogsType(logsType *string) *DownloadClusterLogsParams { o.SetLogsType(logsType) return o } // SetLogsType adds the logsType to the download cluster logs params func (o *DownloadClusterLogsParams) SetLogsType(logsType *string) { o.LogsType = logsType } // WriteToRequest writes these params to a swagger request func (o *DownloadClusterLogsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { if err := r.SetTimeout(o.timeout); err != nil { return err } var res []error // path param cluster_id if err := r.SetPathParam("cluster_id", o.ClusterID.String()); err != nil { return err } if o.HostID != nil { // query param host_id var qrHostID strfmt.UUID if o.HostID != nil { qrHostID = *o.HostID } qHostID := qrHostID.String() if qHostID != "" { if err := r.SetQueryParam("host_id", qHostID); err != nil { return err } } } if o.LogsType != nil { // query param logs_type var qrLogsType string if o.LogsType != nil { qrLogsType = *o.LogsType } qLogsType := qrLogsType if qLogsType != "" { if err := r.SetQueryParam("logs_type", qLogsType); err != nil { return err } } } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
func (o *DownloadClusterLogsParams) WithContext(ctx context.Context) *DownloadClusterLogsParams { o.SetContext(ctx) return o }