repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
nekumelon/CodeXR | back-end/src/OpenAI/query.js | <gh_stars>1-10
/*
author....: nekumelon
License...: MIT (Check LICENSE)
*/
const { statusCodes } = require('../status');
const { Configuration, OpenAIApi } = require('openai');
const { encode } = require('gpt-3-encoder');
const web = require('../web');
const apiKey = process.env.OPENAI_API_KEY;
const configuration = new Configuration({
apiKey: apiKey,
organization: 'org-HWPmQsbFSGQ2l8uDPvP7YdJs'
});
const openai = new OpenAIApi(configuration);
const validEngines = ['code-cushman-001', 'code-davinci-002'];
const MAX_TOKENS = 2048; // 4000, 4096
/**
* Checks that the parameters entered by the user are valid
* @param {object} parameters The parameters the user entered
* @return {boolean} Whether or not the parameters are valid
*/
function validateParameters(parameters) {
return (
parameters.temperature >= 0 &&
parameters.temperature <= 1 &&
parameters.samples > 0 &&
validEngines.includes(parameters.engine) &&
parameters.stops !== [] &&
parameters.user &&
parameters.language
);
}
/**
* Returns context code as a string
* @param {object} parameters - An object with context
* @returns {string} - A string representing the context code
*/
function getContextCode(parameters) {
// This is a complicated line of code
let contextCode =
(parameters.context?.[0]?.code ?? '') +
(parameters.context?.[1]?.code ?? '');
if (contextCode === '') {
return '';
}
return contextCode + '\n';
}
/**
* @function createSingleLinePrompt
* @param {object} parameters - An object containing the parameters for the createSingleLinePrompt function.
* @returns {string} A string containing the next line of code.
*/
function createSingleLinePrompt(parameters) {
const contextCode = getContextCode(parameters);
return `${parameters.language}\n\n${contextCode}Create the next line of code:\n${parameters.prompt}`;
}
/**
* @function createMultiLinePrompt
* @description Takes in a parameter object containing context code and a prompt, and returns a string with the context code and prompt
* @param {object} parameters - An object containing context code and a prompt
* @returns {string} A string containing the context code and prompt
*/
function createMultiLinePrompt(parameters) {
// Get the context code
const contextCode = getContextCode(parameters);
return `${parameters.language}\n\n${contextCode}Finish this code:\n${parameters.prompt}`;
}
/**
* @param {Object} parameters
* @param {boolean} parameters.singleLine
* @returns {Prompt}
*/
function createPrompt(parameters) {
return parameters.singleLine
? createSingleLinePrompt(parameters)
: createMultiLinePrompt(parameters);
}
/**
* @async
* @param {Object} parameters
* @param {string} parameters.engine - The OpenAi engine to use
* @param {number} parameters.temperature - The temperature to use
* @param {number} parameters.stops - The number of stops to use
* @param {number} parameters.samples - The number of samples to use
* @param {string} parameters.user - The user to generate the completion for
* @returns {Object} - The status code and the completion
*/
async function query(parameters) {
if (!validateParameters(parameters)) {
return statusCodes.BAD_REQUEST;
}
// Create the prompt from the parameters
// Get the number of tokens in the prompt
const prompt = createPrompt(parameters);
const numTokens = encode(prompt).length;
// Create the completion
const response = await openai.createCompletion(parameters.engine, {
prompt: prompt,
temperature: parameters.temperature,
stop: parameters.stops,
best_of: parameters.samples,
max_tokens: MAX_TOKENS - numTokens,
top_p: 1,
presence_penalty: 0,
frequency_penalty: 0.34,
user: parameters.user
});
// Update the user's last request time
// web.updateLastRequestTime(parameters.user);
// Increment the user's request count
// web.incrementUserRequests(parameters.user);
// Increment the user's token count
// web.incrementUserTokens(parameters.user, numTokens);
return {
completion: response?.data?.choices?.[0]?.text,
prompt: prompt
};
}
module.exports = query;
|
zwkjhx/vertx-ui | src/app/action/mock/index.js | import fnApp from './fnApp'
import fnMenu from './fnMenu'
import fnDeptList from './fnDeptList'
import fnDeptColumnFull from './fnDeptColumn'
import fnDeptColumnCurrent from './fnDeptColumnCurrent'
import fnCategory from './fnCategory'
import fnCategoryList from './fnCategoryList'
import fnTreeData from './fnTreeData'
import fnTreeData1 from './fnTreeData1'
import fnTableList from './fnRoomType'
import fnTableTree from './fnPayTerm'
import fnCredits from './fnCredit';
import fnMaterials from './fnMaterials';
export default {
fnApp,
fnMenu,
fnDeptList,
fnDeptColumnFull,
fnDeptColumnCurrent,
fnCategory,
fnCategoryList,
// Tree专用
fnTreeData,
fnTreeData1,
// Table专用
fnTableList,
fnTableTree,
// 多个CheckBox专用
fnCredits,
// 穿梭框专用
fnMaterials,
} |
christianalfoni/learncode | app/common/factories/actions/redirect.js | function redirect(url) {
function action({services}) {
services.router.redirect(url);
}
action.displayName = `redirect (${url})`;
return action;
}
export default redirect;
|
monarch-initiative/SilentGenes | silent-genes-io/src/test/java/org/monarchinitiative/sgenes/io/GeneParserTestBase.java | package org.monarchinitiative.sgenes.io;
import org.monarchinitiative.svart.assembly.GenomicAssemblies;
import org.monarchinitiative.svart.assembly.GenomicAssembly;
import java.nio.file.Path;
public class GeneParserTestBase {
protected static final GenomicAssembly ASSEMBLY = GenomicAssemblies.GRCh38p13();
protected static final Path IO_TEST_BASE = Path.of("src/test/resources/org/monarchinitiative/sgenes/io");
protected static final Path JSON_TEST = IO_TEST_BASE.resolve("json").resolve("test-surf1_surf2.json");
}
|
x-ian/care-bricks | node-red-userdir/nodes/common/summary-interactive.js | <filename>node-red-userdir/nodes/common/summary-interactive.js<gh_stars>1-10
module.exports = function(RED) {
function SummaryInteractiveNode(properties) {
RED.nodes.createNode(this,properties);
this.label = properties.label;
this.datatype = properties.datatype;
var node = this;
node.on("input",function(message) {
message.label = this.label;
node.send(message);
});
}
RED.nodes.registerType("summary-interactive",SummaryInteractiveNode);
}
|
nrg12/VOOGASalad | src/structures/data/actions/params/SpriteParam.java | package structures.data.actions.params;
import java.util.List;
import exceptions.ParameterParseException;
import structures.data.DataSprite;
import utils.Utils;
public class SpriteParam implements IParameter, ISelectable {
private List<DataSprite> myPossibleSprites;
private DataSprite mySelected;
private String myOriginal;
private String myTitle;
public SpriteParam(String title) {
myTitle = title;
}
public void setSpriteList(List<DataSprite> possibleSprites) {
myPossibleSprites = possibleSprites;
}
@Override
public List<String> getOptions() {
return Utils.transform(myPossibleSprites, e -> e.getName());
}
@Override
public void parse(String string) throws ParameterParseException {
myOriginal = string;
DataSprite found = Utils.first(myPossibleSprites, e -> (e.getName().equals(string)), null);
if (found == null) {
throw new ParameterParseException("No valid sprite selected!");
}
mySelected = found;
}
@Override
public String getOriginal() {
return mySelected.getName();
}
@Override
public String getTitle() {
return myTitle;
}
@Override
public DataSprite getValue() {
return mySelected;
}
@Override
public type getType() {
return type.SPRITE_SELECT;
}
}
|
dherbst/lullaby | third_party/assimp/revision.h | <filename>third_party/assimp/revision.h
#ifndef ASSIMP_REVISION_H_INC
#define ASSIMP_REVISION_H_INC
#define GitVersion 0xe89c811b
#define GitBranch "4.1.0"
#endif // ASSIMP_REVISION_H_INC
|
ntejos/Barak | barak/sed.py | <reponame>ntejos/Barak<gh_stars>0
""" Perform calculations on Spectral Energy Distributions (SEDs).
Inspired by the SED module in astLib by <NAME>
(http://astlib.sourceforge.net)
- VEGA: The SED of Vega, used for calculation of magnitudes on the Vega system.
- AB: Flat spectrum SED, used for calculation of magnitudes on the AB system.
- SUN: The SED of the Sun.
"""
from __future__ import division, print_function, unicode_literals
try:
unicode
except NameError:
unicode = basestring = str
xrange = range
from .io import readtabfits, loadtxt
from .constants import c, c_kms, Jy
from .utilities import get_data_path
import numpy as np
from numpy.random import randn
import matplotlib.pyplot as pl
import os, math
import warnings
DATAPATH = get_data_path()
PATH_PASSBAND = DATAPATH + '/passbands/'
PATH_EXTINCT = DATAPATH + '/atmos_extinction/'
PATH_TEMPLATE = DATAPATH + '/templates/'
def _listfiles(topdir):
names = [n for n in os.listdir(topdir) if os.path.isdir(topdir + n)]
files = dict([(n, []) for n in names])
for name in sorted(names):
for n in sorted(os.listdir(topdir + name)):
if n != 'README' and not os.path.isdir(topdir + name + '/'+ n) and \
not n.startswith('effic') and \
not n.endswith('.py') and not n.endswith('.pdf'):
files[name].append(n)
return files
TEMPLATES = _listfiles(PATH_TEMPLATE)
PASSBANDS = _listfiles(PATH_PASSBAND)
def get_bands(instr=None, names=None, ccd=None):
""" Get one or more passbands by giving the instrument and
filename.
If `names` is not given, then every passband for that instrument
is returned. Passband instruments and filenames are listed in the
dictionary PASSBANDS. names can be a list, a single string, or a
comma-separated string of values.
Examples
--------
>>> sdss = get_bands('SDSS', 'u,g,r,i,z') # get the SDSS passbands
>>> U = get_bands('LBC', 'u') # get the LBC U_spec filter
"""
if instr is None:
return _listfiles(PATH_PASSBAND)
if isinstance(names, basestring):
if ',' in names:
names = [n.strip() for n in names.split(',')]
else:
return Passband(instr + '/' + names)
elif names is None:
names = PASSBANDS[instr]
return [Passband(instr + '/' + n, ccd=ccd) for n in names]
def get_SEDs(kind=None, names=None):
""" Get one or more SEDs based on their type and filename
If `names` is not given, then every SED of that type is returned.
SED types and filenames are listed in the dictionary TEMPLATES.
Examples
--------
>>> pickles = get_SEDs('pickles') # pickles stellar library SEDs
>>> lbga = get_SEDs('LBG', 'lbg_abs.dat') # LBG absorption spectrum
"""
if kind is None:
return _listfiles(PATH_TEMPLATE)
if isinstance(names, basestring):
if ',' in names:
names = [n.strip() for n in names.split(',')]
else:
return SED(kind + '/' + names)
elif names is None:
names = TEMPLATES[kind]
return [SED(kind + '/' + n) for n in names]
class Passband(object):
"""This class describes a filter transmission curve. Passband
objects are created by loading data from from text files
containing wavelength in angstroms in the first column, relative
transmission efficiency in the second column (whitespace
delimited). For example, to create a Passband object for the 2MASS
J filter:
passband = Passband('J_2MASS.res')
where 'J_2MASS.res' is a file in the current working directory
that describes the filter.
The available passbands are in PASSBANDS.
Attributes
----------
wa : array of floats
Wavelength in Angstroms
tr : array of floats
Normalised transmission, including atmospheric extinction and
detector efficiency. May or may not include extinction from the
optical path.
effective_wa : float
Effective wavelength of the passband.
Methods
-------
plot
"""
def __init__(self, filename, ccd=None):
if not filename.startswith(PATH_PASSBAND):
filepath = PATH_PASSBAND + filename
else:
filepath = filename
if filepath.endswith('.fits'):
try:
import pyfits
except ImportError:
import astropy.io.fits as pyfits
rec = pyfits.getdata(filepath, 1)
self.wa, self.tr = rec.wa, rec.tr
else:
self.wa, self.tr = loadtxt(filepath, usecols=(0,1), unpack=True)
# check wavelengths are sorted lowest -> highest
isort = self.wa.argsort()
self.wa = self.wa[isort]
self.tr = self.tr[isort]
# get the name of the filter/passband file and the name of the
# directory in which it lives (the instrument).
prefix, filtername = os.path.split(filename)
_, instr = os.path.split(prefix)
self.name = filename
if instr == 'LBC' and ccd is None:
if filtername.startswith('LBCB') or filtername in 'ug':
ccd = 'blue'
elif filtername.startswith('LBCR') or filtername in 'riz':
ccd = 'red'
elif instr == 'FORS' and ccd is None:
warnings.warn('No cdd ("red" or "blue") given, assuming red.')
ccd = 'red'
self.atmos = self.effic = None
if ccd is not None:
# apply ccd/optics efficiency
name = PATH_PASSBAND + instr + '/effic_%s.txt' % ccd
wa, effic = loadtxt(name, usecols=(0,1), unpack=1)
self.effic = np.interp(self.wa, wa, effic)
self.tr *= self.effic
extinctmap = dict(LBC='kpno_atmos.dat', FORS='paranal_atmos.dat',
HawkI='paranal_atmos.dat',
KPNO_Mosaic='kpno_atmos.dat',
CTIO_Mosaic='ctio_atmos.dat')
if instr in extinctmap:
# apply atmospheric extinction
wa, emag = loadtxt(PATH_EXTINCT + extinctmap[instr], unpack=1)
self.atmos = np.interp(self.wa, wa, 10**(-0.4 * emag))
self.tr *= self.atmos
# trim away areas where band transmission is negligibly small
# (<0.01% of peak transmission).
isort = self.tr.argsort()
sortedtr = self.tr[isort]
maxtr = sortedtr[-1]
imax = isort[-1]
ind = isort[sortedtr < 1e-4 * maxtr]
if len(ind) > 0:
i = 0
c0 = ind < imax
if c0.any():
i = ind[c0].max()
j = len(self.wa) - 1
c0 = ind > imax
if c0.any():
j = ind[c0].min()
i = min(abs(i-2), 0)
j += 1
self.wa = self.wa[i:j]
self.tr = self.tr[i:j]
if self.atmos is not None:
self.atmos = self.atmos[i:j]
if self.effic is not None:
self.effic = self.effic[i:j]
# normalise
self.ntr = self.tr / np.trapz(self.tr, self.wa)
# Calculate the effective wavelength for the passband. This is
# the same as equation (3) of Carter et al. 2009.
a = np.trapz(self.tr * self.wa)
b = np.trapz(self.tr / self.wa)
self.effective_wa = math.sqrt(a / b)
# find the AB and Vega magnitudes in this band for calculating
# magnitudes.
self.flux = {}
self.flux['Vega'] = VEGA.calc_flux(self)
self.flux['AB'] = AB.calc_flux(self)
def __repr__(self):
return 'Passband "%s"' % self.name
def plot(self, effic=False, atmos=False, ymax=None, **kwargs):
""" Plots the passband. We plot the non-normalised
transmission. This may or may not include ccd efficiency,
losses from the atmosphere and telescope optics.
"""
tr = self.tr
if ymax is not None:
tr = self.tr / self.tr.max() * ymax
pl.plot(self.wa, tr, **kwargs)
if self.effic is not None and effic:
pl.plot(self.wa, self.effic,
label='applied ccd efficiency', **kwargs)
if self.atmos is not None and atmos:
pl.plot(self.wa, self.atmos,
label='applied atmospheric extinction', **kwargs)
pl.xlabel("Wavelength ($\AA$)")
pl.ylabel("Transmission")
if atmos or effic:
pl.legend()
if pl.isinteractive():
pl.show()
class SED(object):
"""A Spectral Energy Distribution (SED).
Instantiate with either a filename or a list of wavelengths and fluxes.
Wavelengths must be in Angstroms, fluxes in erg/s/cm^2/Ang.
To convert from f_nu to f_lambda in erg/s/cm^2/Ang, substitute
using::
nu = c / lambda
f_lambda = c / lambda^2 * f_nu
Available SED template filenames are in TEMPLATES.
"""
def __init__(self, filename=None, wa=[], fl=[], z=0., label=None):
# filename overrides wave and flux keywords
if filename is not None:
if not filename.startswith(PATH_TEMPLATE):
filepath = PATH_TEMPLATE + filename
if filepath.endswith('.fits'):
rec = readtabfits(filepath)
wa, fl = rec.wa, rec.fl
else:
wa, fl = loadtxt(filepath, usecols=(0,1), unpack=1)
if label is None:
label = filename
# We keep a copy of the wavelength, flux at z = 0
self.z0wa = np.array(wa)
self.z0fl = np.array(fl)
self.z0fl_noextinct = np.array(fl)
self.EBmV = None
self.wa = np.array(wa)
self.fl = np.array(fl)
self.z = z
self.label = label
if abs(z) > 1e-6:
self.redshift_to(z)
def __repr__(self):
return 'SED "%s"' % self.label
def copy(self):
"""Copies the SED, returning a new SED object.
"""
newSED = SED(wa=self.z0wa, fl=self.z0fl, z=self.z, label=self.label)
return newSED
def integrate(self, wmin=None, wmax=None):
""" Calculates flux (erg/s/cm^2) in SED within given wavelength
range."""
if wmin is None:
wmin = self.wa[0]
if wmax is None:
wmax = self.wa[-1]
i,j = self.wa.searchsorted([wmin, wmax])
fl = np.trapz(self.fl[i:j], self.wa[i:j])
return fl
def plot(self, log=False, ymax=None, **kwargs):
fl = self.fl
if ymax is not None:
fl = self.fl / self.fl.max() * ymax
if log:
pl.loglog(self.wa, fl, **kwargs)
else:
pl.plot(self.wa, fl, **kwargs)
pl.xlabel('Wavelength ($\AA$)')
pl.ylabel('Flux (ergs s$^{-1}$cm$^{-2}$ $\AA^{-1}$)')
#pl.legend()
if pl.isinteractive():
pl.show()
def redshift_to(self, z, cosmo=None):
"""Redshifts the SED to redshift z. """
# We have to conserve energy so the area under the redshifted
# SED has to be equal to the area under the unredshifted SED,
# otherwise magnitude calculations will be wrong when
# comparing SEDs at different zs
self.wa = np.array(self.z0wa)
self.fl = np.array(self.z0fl)
z0fluxtot = np.trapz(self.z0wa, self.z0fl)
self.wa *= z + 1
zfluxtot = np.trapz(self.wa, self.fl)
self.fl *= z0fluxtot / zfluxtot
self.z = z
def normalise_to_mag(self, ABmag, band):
"""Normalises the SED to match the flux equivalent to the
given AB magnitude in the given passband.
"""
magflux = mag2flux(ABmag, band)
sedflux = self.calc_flux(band)
norm = magflux / sedflux
self.fl *= norm
self.z0fl *= norm
def calc_flux(self, band):
"""Calculate the mean flux for a passband, weighted by the
response and wavelength in the given passband.
Returns the mean flux (erg/s/cm^2/Ang) inside the band.
"""
if self.wa[0] > band.wa[0] or self.wa[-1] < band.wa[-1]:
msg = "SED does not cover the whole bandpass, extrapolating"
warnings.warn(msg)
dw = np.median(np.diff(self.wa))
sedwa = np.arange(band.wa[0], band.wa[-1]+dw, dw)
sedfl = np.interp(sedwa, self.wa, self.fl)
else:
sedwa = self.wa
sedfl = self.fl
i,j = sedwa.searchsorted([band.wa[0], band.wa[-1]])
fl = sedfl[i:j]
wa = sedwa[i:j]
dw_band = np.median(np.diff(band.wa))
dw_sed = np.median(np.diff(wa))
if dw_sed > dw_band and dw_band > 20:
warnings.warn(
'WARNING: SED wavelength sampling interval ~%.2f Ang, '
'but bandpass sampling interval ~%.2f Ang' %
(dw_sed, dw_band))
# interpolate the SED to the passband wavelengths
fl = np.interp(band.wa, wa, fl)
band_tr = band.tr
wa = band.wa
else:
# interpolate the band transmission to the SED
# wavelength values.
band_tr = np.interp(wa, band.wa, band.tr)
# weight by response and wavelength, appropriate when we're
# counting the number of photons within the band.
flux = np.trapz(band_tr * fl * wa, wa) / np.trapz(band_tr * wa, wa)
return flux
def calc_mag(self, band, system="AB"):
"""Calculates magnitude in the given passband.
Note that the distance modulus is not added.
mag_sigma : float
Add a gaussian random deviate to the magnitude, with sigma
given by this value.
`system` is either 'Vega' or 'AB'
"""
f1 = self.calc_flux(band)
if f1 > 0:
mag = -2.5 * math.log10(f1/band.flux[system])
if system == "Vega":
# Add 0.026 because Vega has V=0.026 (e.g. Bohlin & Gilliland 2004)
mag += 0.026
else:
mag = np.inf
return mag
def calc_colour(self, band1, band2, system="AB"):
"""Calculates the colour band1 - band2.
system is either 'Vega' or 'AB'.
mag_sigma : float
Add a gaussian random deviate to each magnitude, with sigma
given by this value.
"""
mag1 = self.calc_mag(band1, system=system)
mag2 = self.calc_mag(band2, system=system)
return mag1 - mag2
def apply_extinction(self, ext_type, EBmV):
""" Return a new SED instance with the extinction curve
applied at the same redshift as the template.
Allowed extinction laws are:
MW
SMC
LMC
starburst
See the extinction module for more information.
"""
import extinction as ext
ecurve = dict(MW= ext.MW_Cardelli89 ,
SMC=ext.SMC_Gordon03 ,
LMC=ext.LMC_Gordon03 ,
starburst=ext.starburst_Calzetti00
)
sed = self.copy()
sed.z0fl[:] = sed.z0fl_noextinct
tau = ecurve[ext_type](self.z0wa, EBmV=EBmV).tau
sed.z0fl *= np.exp(-tau)
sed.EBmV = EBmV
sed.redshift_to(sed.z)
return sed
def mag2flux(ABmag, band):
""" Converts given AB magnitude into flux in the given band, in
erg/s/cm^2/Angstrom.
Returns the flux in the given band.
"""
# AB mag (See Oke, J.B. 1974, ApJS, 27, 21)
# fnu in erg/s/cm^2/Hz
fnu = 10**(-(ABmag + 48.6)/2.5)
# convert to erg/s/cm^2/Ang
flambda = fnu_to_flambda(band.effective_wa, fnu)
return flambda
def flux2mag(flambda, band):
"""Converts flux in erg/s/cm^2/Angstrom into AB magnitudes.
Returns the magnitude in the given band.
"""
# convert to erg/s/cm^2/Hz
fnu = flambda_to_fnu(band.effective_wa, flambda)
mag = -2.5*math.log10(fnu) - 48.6
return mag
def mag2Jy(ABmag):
"""Converts an AB magnitude into flux density in Jy (fnu).
"""
flux_nu = 10**(-(ABmag + 48.6)/2.5) / Jy
return flux_nu
def Jy2mag(fluxJy):
"""Converts flux density in Jy into AB magnitude (fnu).
"""
ABmag = -2.5 * (np.log10(fluxJy * Jy)) - 48.6
return ABmag
def fnu_to_flambda(wa, f_nu):
""" Convert flux per unit frequency to a flux per unit wavelength.
Parameters
----------
wa : array_like
Wavelength in Angstroms
f_nu : array_like
Flux at each wavelength in erg/s/cm^2/Hz
Returns
-------
f_lambda : ndarray
Flux at each wavelength in erg/s/cm^2/Ang
"""
return c / (wa * 1e-8)**2 * f_nu * 1e-8
def flambda_to_fnu(wa, f_lambda):
""" Convert flux per unit wavelength to a flux per unit frequency.
Parameters
----------
wa : array_like
Wavelength in Angstroms
f_lambda : array_like
Flux at each wavelength in erg/s/cm^2/Ang
Returns
-------
f_nu : ndarray
Flux at each wavelength in erg/s/cm^2/Hz
"""
return (wa * 1e-8)**2 * f_lambda * 1e8 / c
def qso_template(wa, z):
""" Return a composite QSO spectrum at redshift z.
This uses the SDSS composite at wa > 1680 and a smoothed version
of the HST/COS EUV+FUV AGN composite spectrum shown in Figure 5
from Shull, Stevans, and Danforth 2012 for wa < 1680.
Parameters
----------
wa : array_like, shape (N,)
Wavelength array in Angstroms
z : float
Redshift.
Returns
-------
f_lambda : ndarray, shape (N,)
The QSO spectrum in F_lambda (the normalisation is arbitrary).
"""
wa = np.array(wa, copy=False)
wrest = wa / (1+z)
i = wrest.searchsorted(1680)
if i == len(wrest):
return qso_template_uv(wa, z)
elif i == 0:
return qso_template_sdss(wa, z)
else:
fl = np.ones(len(wa), float)
f = qso_template_uv(wa, z)
fl[:i] = f[:i] / f[i]
f = qso_template_sdss(wa, z)
fl[i:] = f[i:] / f[i]
return fl
def qso_template_sdss(wa, z):
""" Return a composite visible QSO spectrum at redshift z.
The SDSS composite spectrum as a function of F_lambda is returned
at each wavelength wa. wa must be in Angstroms.
Only good between 700 and 8000 Angstroms (rest frame).
"""
T = readtabfits(DATAPATH + '/templates/qso/dr1QSOspec.fits')
return np.interp(wa, T.wa*(1+z), T.fl)
def qso_template_uv(wa, z):
""" Return a composite UV QSO spectrum at redshift z.
Wavelengths must be in Angstroms.
This is a smoothed version of the HST/COS EUV+FUV AGN composite
spectrum shown in Figure 5 of Shull, Stevans, and Danforth 2012.
Only good between 550 and 1730 Angstroms (rest frame)
"""
T = readtabfits(DATAPATH + 'templates/qso/Shull_composite.fits')
return np.interp(wa, T.wa*(1 + z), T.fl)
def make_constant_dv_wa_scale(wmin, wmax, dv):
""" Make a wavelength scale with bin widths corresponding to a
constant velocity width scale.
Parameters
----------
wmin, wmax : floats
Start and end wavelength.
dv : float
Velocity pixel width.
Returns
-------
wa : ndarray
Wavelength scale.
See Also
--------
barak.spec.make_wa_scale
"""
dlogw = np.log10(1 + dv/c_kms)
# find the number of points needed.
npts = int(np.log10(wmax / wmin) / dlogw)
wa = wmin * 10**(np.arange(npts)*dlogw)
return wa
def vel_from_wa(wa, wa0, redshift=0):
""" Find a velocity scale from wavelengths, given a redshift and
transition rest wavelength.
Parameters
----------
wa : array, shape (N,)
Observed wavelength array.
wa0 : float
Transition rest wavelength, must be same units as `wa`.
redshift : float
Redshift. Default 0.
Returns
-------
vel : arr of shape (N,)
Velocities in km/s.
"""
obswa = wa0 * (1 + redshift)
return (wa / obswa - 1) * c_kms
# Data
VEGA = SED('reference/Vega_bohlin2006')
SUN = SED('reference/sun_stis')
# AB SED has constant flux density (f_nu) 3631 Jy, see
# http://www.sdss.org/dr5/algorithms/fluxcal.html
fnu = 3631 * Jy # erg/s/cm^2/Hz
wa = np.logspace(1, 10, 1e5) # Ang
AB = SED(wa=wa, fl=fnu_to_flambda(wa, fnu))
# don't clutter the namespace
del wa, fnu
|
cm1234567/patterns | src/main/java/patternsdemo/strategy/strategy/AuthStrategy.java | <gh_stars>0
package patternsdemo.strategy.strategy;
public interface AuthStrategy {
boolean checkLogin(String name, String password);
}
|
Mr-S-Mirzoev/CG-2021 | 1. Rogue-like game/doc/html/search/all_11.js | <gh_stars>0
var searchData=
[
['throwexceptiononglerror_1328',['ThrowExceptionOnGLError',['../common_8h.html#ace33e758fb773d4c493543f84e7417b9',1,'common.h']]],
['tile_1329',['Tile',['../classTile.html',1,'Tile'],['../classTile.html#ade8c037ee27c821937829683be8d7b82',1,'Tile::Tile()']]],
['tile_2ecpp_1330',['tile.cpp',['../tile_8cpp.html',1,'']]],
['tile_2eh_1331',['tile.h',['../tile_8h.html',1,'']]],
['tilesize_1332',['tileSize',['../Image_8h.html#a23cad1852a877fb7d9bb6c37452073c7',1,'Image.h']]],
['to_5fimage_1333',['to_image',['../matrix_8cpp.html#ab442a2fe9ac0c97808003ce6c970576b',1,'to_image(const Matrix< Pixel > &m): matrix.cpp'],['../matrix_8h.html#ab442a2fe9ac0c97808003ce6c970576b',1,'to_image(const Matrix< Pixel > &m): matrix.cpp']]],
['to_5fstring_1334',['to_string',['../classRoom.html#a9c3b8463f40e1f1b070b9fa817a663c8',1,'Room']]],
['transposed_1335',['transposed',['../classMatrix.html#a17fd5ba36ce05b358807f926c4e1bb69',1,'Matrix']]]
];
|
lobamosa/mano | app/src/scenes/Login/TeamSelection.js | import React, { useState } from 'react';
import styled from 'styled-components';
import { ActivityIndicator } from 'react-native';
import colors from '../../utils/colors';
import SceneContainer from '../../components/SceneContainer';
import ScrollContainer from '../../components/ScrollContainer';
import { MyText } from '../../components/MyText';
import Title from '../../components/Title';
import ScreenTitle from '../../components/ScreenTitle';
import { useRecoilValue, useSetRecoilState } from 'recoil';
import { currentTeamState, userState } from '../../recoil/auth';
import { refreshTriggerState } from '../../components/Loader';
const TeamBody = ({ onSelect }) => {
const [loading, setLoading] = useState(false);
const user = useRecoilValue(userState);
const setCurrentTeam = useSetRecoilState(currentTeamState);
const setRefreshTrigger = useSetRecoilState(refreshTriggerState);
const onTeamSelected = async (teamIndex) => {
setLoading(teamIndex);
setRefreshTrigger({ status: true, options: { showFullScreen: true, initialLoad: true } });
setCurrentTeam(user.teams[teamIndex]);
setLoading(false);
onSelect();
};
return (
<ScrollContainer backgroundColor="#fff">
{user?.teams?.map(({ _id, name }, i) => (
<TeamContainer disabled={loading} key={_id} onPress={() => onTeamSelected(i)}>
{loading === i ? <ActivityIndicator size="small" color={colors.app.color} /> : <Team bold>{name}</Team>}
</TeamContainer>
))}
</ScrollContainer>
);
};
export const TeamSelection = (props) => {
const onSelect = () =>
props.navigation.reset({
index: 0,
routes: [{ name: 'Home' }],
});
return (
<SceneContainer backgroundColor="#fff">
<Title>Choisissez une équipe</Title>
<Wrapper>
<TeamBody onSelect={onSelect} {...props} />
</Wrapper>
</SceneContainer>
);
};
export const ChangeTeam = (props) => {
const onSelect = () => {
props.navigation.goBack();
};
return (
<SceneContainer>
<ScreenTitle title="Choisissez une équipe" onBack={props.navigation.goBack} />
<TeamBody onSelect={onSelect} {...props} />
</SceneContainer>
);
};
const Wrapper = styled.View`
display: flex;
flex-direction: column;
padding-horizontal: 20px;
flex: 1;
padding-bottom: 20px;
`;
const TeamContainer = styled.TouchableOpacity`
margin-vertical: 10px;
padding-vertical: 25px;
background-color: ${colors.app.color}15;
border-radius: 12px;
`;
const Team = styled(MyText)`
text-align: center;
color: ${colors.app.color};
`;
|
uk-gov-dft/bluebadge-citizen-webapp | acceptance-tests/src/test/java/uk/gov/service/bluebadge/test/acceptance/steps/site/ApplicationSteps.java | package uk.gov.service.bluebadge.test.acceptance.steps.site;
import com.google.common.collect.Lists;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import java.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import uk.gov.service.bluebadge.test.acceptance.pages.site.ApplicantPage;
import uk.gov.service.bluebadge.test.acceptance.pages.site.CommonPage;
import uk.gov.service.bluebadge.test.acceptance.steps.AbstractSpringSteps;
import uk.gov.service.bluebadge.test.acceptance.steps.CommonSteps;
public class ApplicationSteps extends AbstractSpringSteps {
private CommonSteps commonSteps;
private CommonPage commonPage;
@Autowired
public ApplicationSteps(CommonPage commonPage, CommonSteps commonSteps) {
this.commonPage = commonPage;
this.commonSteps = commonSteps;
}
@Given(
"^I navigate to applicant page and validate for \"(yourself|someone else|an organisation)\"")
public void iNavigateToApplicantPageAndValidate(String applicant) throws Exception {
String journeyOption;
if ("yourself".equals(applicant.toLowerCase())) {
journeyOption = ApplicantPage.APPLICANT_TYPE_OPTION_LIST;
} else if ("someone else".equals(applicant.toLowerCase())) {
journeyOption = ApplicantPage.APPLICANT_TYPE_SOMELSE_OPTION;
} else {
journeyOption = ApplicantPage.APPLICANT_TYPE_ORG_OPTION;
}
commonPage.openByPageName("applicant");
this.verifyPageContent(journeyOption);
}
public void verifyPageContent(String journeyOption) {
commonSteps.iShouldSeeTheCorrectURL(ApplicantPage.PAGE_URL);
commonSteps.thenIShouldSeePageTitledWithGovUkSuffix(ApplicantPage.PAGE_TITLE);
commonSteps.iShouldSeeTheHeading(ApplicantPage.PAGE_HEADING);
commonSteps.iClickOnContinueButton();
commonSteps.andIshouldSeeErrorSummaryBox();
commonSteps.iShouldSeeErrorSummaryBoxWithValidationMessagesInOrder(
Lists.newArrayList(ApplicantPage.VALIDATION_MESSAGE_FOR_NO_OPTION));
commonSteps.iShouldSeeTextOnPage(ApplicantPage.VALIDATION_MESSAGE_FOR_NO_OPTION);
commonPage.selectRadioButton(journeyOption);
commonSteps.iClickOnContinueButton();
}
@And("^I complete prove benefit page for \"(yes|no)\"")
public void iCompleteProveBenefitPage(String opt) {
if (opt.equals("yes")) {
commonPage.findPageElementById("hasProof").click();
} else {
LocalDate date = LocalDate.now();
String day = Integer.toString(date.getDayOfMonth());
String month = Integer.toString(date.getMonth().getValue());
String year = Integer.toString(date.getYear() + 1);
commonPage.findPageElementById("hasProof.no").click();
commonPage.findPageElementById("awardEndDate").sendKeys(day);
commonPage.findPageElementById("awardEndDate.month").sendKeys(month);
commonPage.findPageElementById("awardEndDate.year").sendKeys(year);
}
commonSteps.iClickOnContinueButton();
}
}
|
jonathandreyer/esp-modem | src/esp_modem_factory.cpp | <reponame>jonathandreyer/esp-modem<filename>src/esp_modem_factory.cpp
// Copyright 2021 Espressif Systems (Shanghai) PTE 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.
#include <functional>
#include "cxx_include/esp_modem_types.hpp"
#include "cxx_include/esp_modem_dte.hpp"
#include "cxx_include/esp_modem_dce_module.hpp"
namespace esp_modem {
template<typename T>
std::shared_ptr<T> create_device(const std::shared_ptr<DTE> &dte, std::string &apn)
{
auto pdp = std::make_unique<PdpContext>(apn);
return std::make_shared<T>(dte, std::move(pdp));
}
std::shared_ptr<GenericModule> create_generic_module(const std::shared_ptr<DTE> &dte, std::string &apn)
{
return create_device<GenericModule>(dte, apn);
}
std::shared_ptr<SIM7600> create_SIM7600_module(const std::shared_ptr<DTE> &dte, std::string &apn)
{
return create_device<SIM7600>(dte, apn);
}
}
#include "cxx_include/esp_modem_api.hpp"
#include "cxx_include/esp_modem_dce_factory.hpp"
namespace esp_modem::dce_factory {
std::unique_ptr<PdpContext> FactoryHelper::create_pdp_context(std::string &apn)
{
return std::unique_ptr<PdpContext>();
}
} |
UnknownArkish/OS_Assginment-SZU- | OS_HW_Comprehensive_1/Part1/ZombieDemo.c | <reponame>UnknownArkish/OS_Assginment-SZU-
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main(){
pid_t pid = fork();
if( pid < 0 ){
printf("Error!\n");
}else if( pid == 0 ){
printf("Hi father! I am a ZOMBIE\n");
exit(0);
}else{
getchar();
wait(NULL);
}
return 0;
} |
usamakhan049/assignment | src/SearchMenu/SearchMenuPerformedSearchMessage.h | <filename>src/SearchMenu/SearchMenuPerformedSearchMessage.h
// Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#pragma once
#include <string>
namespace ExampleApp
{
namespace SearchMenu
{
class SearchMenuPerformedSearchMessage
{
std::string m_searchQuery;
bool m_isTag;
bool m_isInterior;
public:
SearchMenuPerformedSearchMessage(const std::string& searchQuery, bool isTag, bool isInterior);
const std::string& SearchQuery() const;
bool IsTag() const;
bool IsInterior() const;
};
}
}
|
jce-caba/GtkQR | src/encodings/8859_5_character_set.c | #include "8859_5_character_set.h"
int get8859_5_character(int unicode)
{
if ( unicode >= 0 && unicode <= 126)
return unicode;
else if ( unicode == 160)
return 160;
else if ( unicode == 173)
return 173;
else if ( unicode >= 1025 && unicode <= 1036)
return unicode - 864;
else if ( unicode >= 1038 && unicode <= 1103)
return unicode - 864;
else if ( unicode == 8470)
return 240;
else if ( unicode >= 1105 && unicode <= 1116)
return unicode - 864;
else if ( unicode == 167)
return 253;
else if ( unicode == 1118)
return 254;
else if ( unicode == 1119)
return 255;
return -1;
}
|
garytaylor/agileproxy | lib/agile_proxy/handlers/proxy_handler.rb | require 'agile_proxy/handlers/handler'
require 'eventmachine'
require 'em-synchrony/em-http'
module AgileProxy
# = The handler used for proxying the request on to the original server
#
# This handler is responsible for proxying the request through to the original server and passing back its response
#
# It works as a rack end point as usual :-)
#
class ProxyHandler
include Handler
# The endpoint called by 'rack'
#
# Requests the response back from the destination server and passes it back to the client
#
# @param env [Hash] The rack environment hash
# @return [Array] The rack response array (status, headers, body)
def call(env)
request = ActionDispatch::Request.new(env)
method = request.request_method.downcase
body = request.body.read
request.body.rewind
url = request.url
if handles_request?(request)
req = EventMachine::HttpRequest.new(request.url,
inactivity_timeout: AgileProxy.config.proxied_request_inactivity_timeout,
connect_timeout: AgileProxy.config.proxied_request_connect_timeout
)
req = req.send(method.downcase, build_request_options(request.headers, body))
if req.error
return [500, {}, ["Request to #{request.url} failed with error: #{req.error}"]]
end
if req.response
response = process_response(req)
unless allowed_response_code?(response[:status])
AgileProxy.log(:warn, "agile-proxy: Received response status code #{response[:status]} for '#{url}'")
end
AgileProxy.log(:info, "agile-proxy: PROXY #{request.request_method} succeeded for '#{request.url}'")
return [response[:status], response[:headers], response[:content]]
end
end
[404, {}, ['Not proxied']]
end
private
def handles_request?(request)
!disabled_request?(request.url)
end
def build_request_options(headers, body)
headers = Hash[headers.map { |k, v| [k.downcase, v] }]
headers.delete('accept-encoding')
req_opts = {
redirects: 0,
keepalive: false,
head: headers,
ssl: { verify: false }
}
req_opts[:body] = body if body
req_opts
end
def process_response(req)
response = {
status: req.response_header.status,
headers: req.response_header.raw,
content: [req.response.force_encoding('BINARY')] }
response[:headers].merge!('Connection' => 'close')
response[:headers].delete('Transfer-Encoding')
response[:headers].merge!('Cache-Control' => 'max-age=3600')
response
end
def disabled_request?(url)
return false unless AgileProxy.config.non_whitelisted_requests_disabled
uri = URI(url)
# In isolated environments, you may want to stop the request from happening
# or else you get "getaddrinfo: Name or service not known" errors
blacklisted_path?(uri.path) || !whitelisted_url?(uri)
end
def allowed_response_code?(status)
successful_status?(status)
end
def whitelisted_url?(url)
!AgileProxy.config.whitelist.index do |v|
v =~ /^#{url.host}(?::#{url.port})?$/
end.nil?
end
def blacklisted_path?(path)
!AgileProxy.config.path_blacklist.index { |bl| path.include?(bl) }.nil?
end
def successful_status?(status)
(200..299).include?(status) || status == 304
end
end
end
|
alphaho/TypeFlow | code_template/scala/FileInputEndpointTemplate.scala | package $PackageName$
import com.typesafe.scalalogging.Logger
import scala.io.{Source, StdIn}
import scala.util.{Failure, Success, Try}
object $DefinitionName$ extends App {
private val logger = Logger($DefinitionName$.getClass)
execute()
def execute(): Unit = {
//TODO input your file name
val source = Source.fromFile()
source.getLines.foreach { rawInput =>
val input = rawInput.toInt
Try {
$CallingChain$
} match {
case Success(value) => {
logger.info(s"processing input: $input successfully complete")
}
case Failure(exception) => {
logger.error("error occurs", exception)
}
}
}
source.close()
}
}
|
thangph9/123order-ant | src/services/image.js | import { stringify } from 'qs';
import request from '@/utils/request';
import { getAuthority } from '@/utils/authority';
export async function getProducts(params) {
return request(`/api/product/list?${stringify(params)}`);
}
export async function upload(params) {
const formData = new FormData();
formData.append('file',params);
return request(`/api/image/upload?ref=${new Date()}`,{
method : "POST",
body: formData,
headers:{'X-Access-Token':getAuthority()[0].token}
});
} |
luohongjunnn/jstorm | jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/thrift/ThriftServer.java | package com.alibaba.jstorm.yarn.thrift;
import java.util.Map;
import javax.security.auth.login.Configuration;
import org.apache.thrift7.TProcessor;
import org.apache.thrift7.server.TServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ThriftServer {
private static final Logger LOG = LoggerFactory
.getLogger(ThriftServer.class);
private Map _storm_conf; // storm configuration
protected TProcessor _processor = null;
private int _port = 0;
private TServer _server = null;
private Configuration _login_conf;
public ThriftServer(Map storm_conf, TProcessor processor, int port) {
try {
_storm_conf = storm_conf;
_processor = processor;
_port = port;
// retrieve authentication configuration
_login_conf = AuthUtils.GetConfiguration(_storm_conf);
} catch (Exception x) {
LOG.error(x.getMessage(), x);
}
}
public void stop() {
if (_server != null)
_server.stop();
}
/**
* Is ThriftServer listening to requests?
*
* @return
*/
public boolean isServing() {
if (_server == null)
return false;
return _server.isServing();
}
public void serve() {
try {
// locate our thrift transport plugin
ITransportPlugin transportPlugin = AuthUtils.GetTransportPlugin(
_storm_conf, _login_conf);
// server
_server = transportPlugin.getServer(_port, _processor);
// start accepting requests
_server.serve();
} catch (Exception ex) {
LOG.error("ThriftServer is being stopped due to: " + ex, ex);
if (_server != null)
_server.stop();
Runtime.getRuntime().halt(1); // shutdown server process since we
// could not handle Thrift requests
// any more
}
}
}
|
TolyaTalamanov/plaidml | tile/base/shape.cc | // Copyright 2018 Intel Corporation.
#include "tile/base/shape.h"
namespace vertexai {
namespace tile {
std::ostream& operator<<(std::ostream& os, const TensorShape& shape) {
os << to_string(shape.type);
if (!shape.layout.empty()) {
os << "[" << shape.layout << "]";
}
os << "(";
for (size_t i = 0; i < shape.dims.size(); i++) {
if (i > 0) {
os << ", ";
}
os << shape.dims[i].size;
}
os << "):(";
for (size_t i = 0; i < shape.dims.size(); i++) {
if (i > 0) {
os << ", ";
}
os << shape.dims[i].stride;
}
os << "):";
if (shape.byte_size() < 1024) {
os << shape.byte_size() << " bytes";
} else {
os << shape.byte_size() / 1024.0 << " KiB";
}
if (shape.is_const) {
os << " const";
}
return os;
}
std::ostream& operator<<(std::ostream& os, const TensorDimension& dim) {
os << dim.size << ":" << dim.stride;
return os;
}
void TensorShape::resize_dim(size_t pos, uint64_t size) {
assert(pos < dims.size());
dims[pos].size = size;
std::multimap<int64_t, TensorDimension*> sorted;
for (auto& dim : dims) {
sorted.emplace(dim.stride, &dim);
}
int64_t stride = 1;
for (auto& item : sorted) {
item.second->stride = stride;
stride *= item.second->size;
}
}
} // namespace tile
} // namespace vertexai
|
pi/goal | hash/race.go | <filename>hash/race.go
// +build race
package hash
const race = false
|
EthanTuttle/NinjaFastKitchenSystem3000 | src/main/java/restaurantGUI/DisplayItem.java | package src.main.java.restaurantGUI;
import java.awt.*;
import javax.swing.*;
import src.main.java.Backend.Customer;
import src.main.java.Backend.MenuItem;
import src.main.java.Backend.OrderItem;
import java.util.concurrent.TimeUnit;
import java.util.*;
/**
* Display for a specific item in the order display
*/
public class DisplayItem extends JPanel {
/**
* Time to display
*/
private JLabel time;
/**
* Customer and therefore order to display
*/
private Customer customer;
/**
* Instantiate the display item
* @param customer Customer and therefor order to display
*/
public DisplayItem(Customer customer, JButton deleteButton) {
HashMap<String, Integer> itemCount = new HashMap<>();
this.customer = customer;
setLayout(new BorderLayout());
JPanel boxPanel = new JPanel();
boxPanel.setLayout(new BoxLayout(boxPanel, BoxLayout.Y_AXIS));
if(customer.getName().toLowerCase().equals("kuzmin")){
boxPanel.setBackground(Color.YELLOW);
}
JLabel name = new JLabel();
if (customer.getName().length() > 15) {
name.setText(customer.getName().substring(0, 15) + "...");
} else {
name.setText(customer.getName());
}
Font original = name.getFont();
Font bigger = original.deriveFont(24.0f);
name.setFont(bigger);
time = new JLabel();
updateTime();
time.setFont(original.deriveFont(18.0f));
boxPanel.add(name);
boxPanel.add(time);
//add(new Box.Filler(minSize, prefSize, maxSize));
JSeparator bar = new JSeparator();
bar.setMaximumSize(new Dimension(Integer.MAX_VALUE, 5));
boxPanel.add(bar);
for (OrderItem order : customer.getOrders()) {
for (MenuItem menuItem : order.getOrder()) {
if (!itemCount.containsKey(menuItem.getName())) {
itemCount.put(menuItem.getName(), 1);
} else {
itemCount.put(menuItem.getName(), itemCount.get(menuItem.getName())+1);
}
}
}
for (String itemName : itemCount.keySet()) {
JLabel itemLabel = new JLabel(itemName + " " + (itemCount.get(itemName) > 1 ? "x"+itemCount.get(itemName) : ""), SwingConstants.CENTER);
itemLabel.setFont(original.deriveFont(18.0f));
boxPanel.add(itemLabel);
}
if (customer.getTick() >= 5) {
boxPanel.setBackground(new Color(255, 102, 102));
}
boxPanel.setBorder(BorderFactory.createLineBorder(Color.black));
JScrollPane scroll = new JScrollPane(boxPanel);
add(scroll, BorderLayout.CENTER);
add(deleteButton, BorderLayout.SOUTH);
}
/**
* Updates the time for each order and displays it
*/
public void updateTime() {
long diff = new Date().getTime() - customer.getTime().getTime();
String timeString = String.format("%d:%02d",
TimeUnit.MILLISECONDS.toMinutes(diff),
TimeUnit.MILLISECONDS.toSeconds(diff) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(diff))
);
time.setText("Time waiting: " + timeString);
}
}
|
m00g3n/kyma | tests/ui-api-layer-acceptance-tests/internal/domain/authentication/idppreset_authz_test.go | // +build acceptance
package authentication
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/kyma-project/kyma/tests/ui-api-layer-acceptance-tests/internal/dex"
"github.com/kyma-project/kyma/tests/ui-api-layer-acceptance-tests/internal/graphql"
"github.com/kyma-project/kyma/tests/ui-api-layer-acceptance-tests/internal/module"
"github.com/stretchr/testify/require"
)
const (
RBACError string = "graphql: access denied"
AuthError string = "graphql: server returned a non-200 status code: 401"
ModuleDisabledError string = "graphql: MODULE_DISABLED: The authentication module is disabled."
)
func TestAuthenticationAnonymousUser(t *testing.T) {
dex.SkipTestIfSCIEnabled(t)
c := gqlClientForUser(t, graphql.NoUser)
testResource := idpPreset("test-name", "test-issuer", "https://test-jwksUri")
resourceDetailsQuery := idpPresetDetailsFields()
// should not be able to do any request - should receive 401 Unauthorized
t.Log("Query Single IDP Preset")
res, err := querySingleIDPPreset(c, resourceDetailsQuery, testResource)
assert.EqualError(t, err, AuthError)
assert.Equal(t, IDPPreset{}, res.IDPPreset)
}
func TestAuthorizationForNoRightsUser(t *testing.T) {
dex.SkipTestIfSCIEnabled(t)
t.Run("User with no rights", func(t *testing.T) {
c := gqlClientForUser(t, graphql.NoRightsUser)
testResource := idpPreset("test-name", "test-issuer", "https://test-jwksUri")
resourceDetailsQuery := idpPresetDetailsFields()
t.Run("should not be able to get idppresets", func(t *testing.T) {
queryRes, err := querySingleIDPPreset(c, resourceDetailsQuery, testResource)
assert.Equal(t, IDPPreset{}, queryRes.IDPPreset)
assert.EqualError(t, err, RBACError)
})
t.Run("should not be able to create idppreset", func(t *testing.T) {
createRes, err := createIDPPreset(c, resourceDetailsQuery, testResource)
assert.Equal(t, IDPPreset{}, createRes.CreateIDPPreset)
assert.EqualError(t, err, RBACError)
})
t.Run("should not be able to delete idppreset", func(t *testing.T) {
deleteRes, err := deleteIDPPreset(c, resourceDetailsQuery, testResource)
assert.Equal(t, IDPPreset{}, deleteRes.DeleteIDPPreset)
assert.EqualError(t, err, RBACError)
})
})
}
func TestAuthorizationForReadOnlyUser(t *testing.T) {
dex.SkipTestIfSCIEnabled(t)
t.Run("Read only user", func(t *testing.T) {
c := gqlClientForUser(t, graphql.ReadOnlyUser)
moduleEnabled, err := module.IsEnabled(ModuleName, c)
assert.Nil(t, err)
testResource := idpPreset("test-name", "test-issuer", "https://test-jwksUri")
resourceDetailsQuery := idpPresetDetailsFields()
t.Run("should be able to get idppresets", func(t *testing.T) {
queryRes, err := querySingleIDPPreset(c, resourceDetailsQuery, testResource)
assert.Equal(t, IDPPreset{}, queryRes.IDPPreset)
if moduleEnabled {
assert.Nil(t, err)
} else {
assert.EqualError(t, err, ModuleDisabledError)
}
})
t.Run("should not be able to create idppreset", func(t *testing.T) {
createRes, err := createIDPPreset(c, resourceDetailsQuery, testResource)
assert.Equal(t, IDPPreset{}, createRes.CreateIDPPreset)
assert.EqualError(t, err, RBACError)
})
t.Run("should not be able to delete idppreset", func(t *testing.T) {
deleteRes, err := deleteIDPPreset(c, resourceDetailsQuery, testResource)
assert.Equal(t, IDPPreset{}, deleteRes.DeleteIDPPreset)
assert.EqualError(t, err, RBACError)
})
})
}
func TestAuthorizationForReadWriteUser(t *testing.T) {
dex.SkipTestIfSCIEnabled(t)
t.Run("Read write user", func(t *testing.T) {
c := gqlClientForUser(t, graphql.AdminUser)
moduleEnabled, err := module.IsEnabled(ModuleName, c)
assert.Nil(t, err)
testResource := idpPreset("test-name", "test-issuer", "https://test-jwksUri")
resourceDetailsQuery := idpPresetDetailsFields()
t.Run("should be able to get idppresets", func(t *testing.T) {
queryRes, err := querySingleIDPPreset(c, resourceDetailsQuery, testResource)
checkIDPPreset(t, IDPPreset{}, queryRes.IDPPreset)
if moduleEnabled {
assert.Nil(t, err)
} else {
assert.EqualError(t, err, ModuleDisabledError)
}
})
t.Run("should be able to create idppreset", func(t *testing.T) {
createRes, err := createIDPPreset(c, resourceDetailsQuery, testResource)
if moduleEnabled {
checkIDPPreset(t, testResource, createRes.CreateIDPPreset)
assert.Nil(t, err)
} else {
checkIDPPreset(t, IDPPreset{}, createRes.CreateIDPPreset)
assert.EqualError(t, err, ModuleDisabledError)
}
})
t.Run("should be able to delete idppreset", func(t *testing.T) {
deleteRes, err := deleteIDPPreset(c, resourceDetailsQuery, testResource)
if moduleEnabled {
checkIDPPreset(t, testResource, deleteRes.DeleteIDPPreset)
assert.Nil(t, err)
} else {
checkIDPPreset(t, IDPPreset{}, deleteRes.DeleteIDPPreset)
assert.EqualError(t, err, ModuleDisabledError)
}
})
})
}
func gqlClientForUser(t *testing.T, user graphql.User) *graphql.Client {
c, err := graphql.New()
require.NoError(t, err)
err = c.ChangeUser(user)
require.NoError(t, err)
return c
}
|
mag67/practice_atomic_design | node_modules/@storybook/addon-chapters/register.js | <gh_stars>0
'use strict';
var _storybookAdk = require('storybook-adk');
var _addonLinks = require('@storybook/addon-links');
var _store = require('storybook-adk/dist/store/store');
var _config = require('./dist/config');
var _config2 = _interopRequireDefault(_config);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var logger = {
log: function log() {}
}; // fixme: in adk
(0, _addonLinks.register)();
(0, _storybookAdk.register)(_config2.default, function (env) {
env.addonStore.watch('enabledMap', function (map) {
logger.log('enabledMap', map);
});
var setupChannel = env.channelInit(_store.ENQ_SEND, 'cp01');
/* const stopChannel = */setupChannel();
env.storybookApi.onStory(function (kind, name) {
env.addonStore.set('onStory', { kind: kind, name: name });
});
});
|
PeterSommerlad/CPPCourseIntroduction | exercises/solutions/exercise09/GardeningLibTest/src/RectangleSuite.h | <gh_stars>0
#include "cute_suite.h"
extern cute::suite make_suite_RectangleSuite();
|
KierenEinar/taobao | taobao-product/src/main/java/taobao/product/mapper/ProductParamsItemMapper.java | package taobao.product.mapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.Update;
import taobao.product.models.ProductParamsItem;
import taobao.product.models.ProductSpecs;
import java.util.List;
public interface ProductParamsItemMapper {
@Delete({
"delete from product_params_item",
"where id = #{id,jdbcType=BIGINT}"
})
int deleteByPrimaryKey(Long id);
@Insert({
"insert into product_params_item (product_id, product_specs_id, ",
"type, create_time, ",
"update_time, param_data)",
"values (#{productId,jdbcType=BIGINT}, #{productSpecsId,jdbcType=BIGINT}, ",
"#{type,jdbcType=CHAR}, #{createTime,jdbcType=TIMESTAMP}, ",
"#{updateTime,jdbcType=TIMESTAMP}, #{paramData,jdbcType=LONGVARCHAR})"
})
@SelectKey(statement="SELECT LAST_INSERT_ID()", keyProperty="id", before=false, resultType=Long.class)
int insert(ProductParamsItem record);
int insertSelective(ProductParamsItem record);
@Select({
"select",
"id, product_id, product_specs_id, type, create_time, update_time, param_data",
"from product_params_item",
"where id = #{id,jdbcType=BIGINT}"
})
@ResultMap("taobao.product.mapper.ProductParamsItemMapper.ResultMapWithBLOBs")
ProductParamsItem selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(ProductParamsItem record);
@Update({
"update product_params_item",
"set product_id = #{productId,jdbcType=BIGINT},",
"product_specs_id = #{productSpecsId,jdbcType=BIGINT},",
"type = #{type,jdbcType=CHAR},",
"create_time = #{createTime,jdbcType=TIMESTAMP},",
"update_time = #{updateTime,jdbcType=TIMESTAMP},",
"param_data = #{paramData,jdbcType=LONGVARCHAR}",
"where id = #{id,jdbcType=BIGINT}"
})
int updateByPrimaryKeyWithBLOBs(ProductParamsItem record);
@Update({
"update product_params_item",
"set product_id = #{productId,jdbcType=BIGINT},",
"product_specs_id = #{productSpecsId,jdbcType=BIGINT},",
"type = #{type,jdbcType=CHAR},",
"create_time = #{createTime,jdbcType=TIMESTAMP},",
"update_time = #{updateTime,jdbcType=TIMESTAMP}",
"where id = #{id,jdbcType=BIGINT}"
})
int updateByPrimaryKey(ProductParamsItem record);
int insertBatch(List<ProductParamsItem> items);
@Select("select id, product_id, product_specs_id, type, create_time, update_time, param_data from product_params_item where product_id = #{arg0};")
List<ProductParamsItem> selectByProductId(Long productId);
} |
Cronosus/FossilArcheology1.7 | src/main/java/mods/fossil/entity/mob/EntityFailuresaurus.java | package mods.fossil.entity.mob;
import mods.fossil.Fossil;
import net.minecraft.entity.monster.EntityZombie;
import net.minecraft.item.Item;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class EntityFailuresaurus extends EntityZombie
{
public EntityFailuresaurus(World var1)
{
super(var1);
this.experienceValue = 4;
}
protected void entityInit()
{
super.entityInit();
this.dataWatcher.addObject(18, Byte.valueOf((byte)0));
this.setSkin(this.worldObj.rand.nextInt(3));
}
public int getSkin()
{
return this.dataWatcher.getWatchableObjectByte(18);
}
public void setSkin(int par1)
{
this.dataWatcher.updateObject(18, Byte.valueOf((byte)par1));
}
/**
* (abstract) Protected helper method to write subclass entity data to NBT.
*/
public void writeEntityToNBT(NBTTagCompound par1NBTTagCompound)
{
super.writeEntityToNBT(par1NBTTagCompound);
par1NBTTagCompound.setInteger("FailuresaurusSkin", this.getSkin());
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
public void readEntityFromNBT(NBTTagCompound par1NBTTagCompound)
{
super.readEntityFromNBT(par1NBTTagCompound);
this.setSkin(par1NBTTagCompound.getInteger("FailuresaurusSkin"));
}
/**
* Returns the item ID for the item the mob drops on death.
*/
protected Item getDropItem()
{
return Fossil.biofossil;
}
@SideOnly(Side.CLIENT)
/**
* Causes this entity to do an upwards motion (jumping).
*/
protected void jump() {}
/**
* Returns the texture's file path as a String.
*/
public String getTexture()
{
return "fossil:textures/mob/Failuresaurus.png";
}
}
|
harizSalim/LOG6306-SalimAlex | lock/src/main/java/com/auth0/lock/validation/LoginValidator.java | /*
* LoginValidator.java
*
* Copyright (c) 2014 Auth0 (http://auth0.com)
*
* 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.
*/
package com.auth0.lock.validation;
import android.support.v4.app.Fragment;
import com.auth0.lock.R;
import com.auth0.lock.event.AuthenticationError;
public class LoginValidator implements Validator {
private final Validator usernameValidator;
private final Validator passwordValidator;
private final int compositeErrorMessage;
public LoginValidator(Validator usernameValidator, Validator passwordValidator, int compositeErrorMessage) {
this.usernameValidator = usernameValidator;
this.passwordValidator = passwordValidator;
this.compositeErrorMessage = compositeErrorMessage;
}
public LoginValidator(boolean useEmail, boolean requiresUsername) {
this(validatorThatUseEmail(useEmail, requiresUsername),
new PasswordValidator(R.id.com_auth0_db_login_password_field, R.string.com_auth0_invalid_credentials_title, R.string.com_auth0_invalid_password_message),
useEmail ? R.string.com_auth0_invalid_credentials_message : R.string.com_auth0_invalid_username_credentials_message);
}
@Override
public AuthenticationError validateFrom(Fragment fragment) {
final AuthenticationError usernameError = usernameValidator.validateFrom(fragment);
final AuthenticationError passwordError = passwordValidator.validateFrom(fragment);
if (usernameError != null && passwordError != null) {
return new AuthenticationError(R.string.com_auth0_invalid_credentials_title, compositeErrorMessage);
}
return usernameError != null ? usernameError : passwordError;
}
public static Validator validatorThatUseEmail(boolean useEmail, boolean requiresUsername) {
if (useEmail && !requiresUsername) {
return new EmailValidator(R.id.com_auth0_db_login_username_field, R.string.com_auth0_invalid_credentials_title, R.string.com_auth0_invalid_email_message);
}
return new UsernameValidator(R.id.com_auth0_db_login_username_field, R.string.com_auth0_invalid_credentials_title, R.string.com_auth0_invalid_username_message);
}
}
|
blockspacer/chromium_base_conan | extensions/third_party/perfetto/protos/perfetto/config/trace_config.pb.h | <reponame>blockspacer/chromium_base_conan<filename>extensions/third_party/perfetto/protos/perfetto/config/trace_config.pb.h
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: protos/perfetto/config/trace_config.proto
#ifndef GOOGLE_PROTOBUF_INCLUDED_protos_2fperfetto_2fconfig_2ftrace_5fconfig_2eproto
#define GOOGLE_PROTOBUF_INCLUDED_protos_2fperfetto_2fconfig_2ftrace_5fconfig_2eproto
#include <limits>
#include <string>
#include <google/protobuf/port_def.inc>
#if PROTOBUF_VERSION < 3009000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3009000 < PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/generated_enum_util.h>
#include "protos/perfetto/config/data_source_config.pb.h"
#include "protos/perfetto/common/builtin_clock.pb.h"
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
#define PROTOBUF_INTERNAL_EXPORT_protos_2fperfetto_2fconfig_2ftrace_5fconfig_2eproto
PROTOBUF_NAMESPACE_OPEN
namespace internal {
class AnyMetadata;
} // namespace internal
PROTOBUF_NAMESPACE_CLOSE
// Internal implementation detail -- do not use these members.
struct TableStruct_protos_2fperfetto_2fconfig_2ftrace_5fconfig_2eproto {
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[11]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[];
static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[];
static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[];
};
namespace perfetto {
namespace protos {
class TraceConfig;
class TraceConfigDefaultTypeInternal;
extern TraceConfigDefaultTypeInternal _TraceConfig_default_instance_;
class TraceConfig_BufferConfig;
class TraceConfig_BufferConfigDefaultTypeInternal;
extern TraceConfig_BufferConfigDefaultTypeInternal _TraceConfig_BufferConfig_default_instance_;
class TraceConfig_BuiltinDataSource;
class TraceConfig_BuiltinDataSourceDefaultTypeInternal;
extern TraceConfig_BuiltinDataSourceDefaultTypeInternal _TraceConfig_BuiltinDataSource_default_instance_;
class TraceConfig_DataSource;
class TraceConfig_DataSourceDefaultTypeInternal;
extern TraceConfig_DataSourceDefaultTypeInternal _TraceConfig_DataSource_default_instance_;
class TraceConfig_GuardrailOverrides;
class TraceConfig_GuardrailOverridesDefaultTypeInternal;
extern TraceConfig_GuardrailOverridesDefaultTypeInternal _TraceConfig_GuardrailOverrides_default_instance_;
class TraceConfig_IncidentReportConfig;
class TraceConfig_IncidentReportConfigDefaultTypeInternal;
extern TraceConfig_IncidentReportConfigDefaultTypeInternal _TraceConfig_IncidentReportConfig_default_instance_;
class TraceConfig_IncrementalStateConfig;
class TraceConfig_IncrementalStateConfigDefaultTypeInternal;
extern TraceConfig_IncrementalStateConfigDefaultTypeInternal _TraceConfig_IncrementalStateConfig_default_instance_;
class TraceConfig_ProducerConfig;
class TraceConfig_ProducerConfigDefaultTypeInternal;
extern TraceConfig_ProducerConfigDefaultTypeInternal _TraceConfig_ProducerConfig_default_instance_;
class TraceConfig_StatsdMetadata;
class TraceConfig_StatsdMetadataDefaultTypeInternal;
extern TraceConfig_StatsdMetadataDefaultTypeInternal _TraceConfig_StatsdMetadata_default_instance_;
class TraceConfig_TriggerConfig;
class TraceConfig_TriggerConfigDefaultTypeInternal;
extern TraceConfig_TriggerConfigDefaultTypeInternal _TraceConfig_TriggerConfig_default_instance_;
class TraceConfig_TriggerConfig_Trigger;
class TraceConfig_TriggerConfig_TriggerDefaultTypeInternal;
extern TraceConfig_TriggerConfig_TriggerDefaultTypeInternal _TraceConfig_TriggerConfig_Trigger_default_instance_;
} // namespace protos
} // namespace perfetto
PROTOBUF_NAMESPACE_OPEN
template<> ::perfetto::protos::TraceConfig* Arena::CreateMaybeMessage<::perfetto::protos::TraceConfig>(Arena*);
template<> ::perfetto::protos::TraceConfig_BufferConfig* Arena::CreateMaybeMessage<::perfetto::protos::TraceConfig_BufferConfig>(Arena*);
template<> ::perfetto::protos::TraceConfig_BuiltinDataSource* Arena::CreateMaybeMessage<::perfetto::protos::TraceConfig_BuiltinDataSource>(Arena*);
template<> ::perfetto::protos::TraceConfig_DataSource* Arena::CreateMaybeMessage<::perfetto::protos::TraceConfig_DataSource>(Arena*);
template<> ::perfetto::protos::TraceConfig_GuardrailOverrides* Arena::CreateMaybeMessage<::perfetto::protos::TraceConfig_GuardrailOverrides>(Arena*);
template<> ::perfetto::protos::TraceConfig_IncidentReportConfig* Arena::CreateMaybeMessage<::perfetto::protos::TraceConfig_IncidentReportConfig>(Arena*);
template<> ::perfetto::protos::TraceConfig_IncrementalStateConfig* Arena::CreateMaybeMessage<::perfetto::protos::TraceConfig_IncrementalStateConfig>(Arena*);
template<> ::perfetto::protos::TraceConfig_ProducerConfig* Arena::CreateMaybeMessage<::perfetto::protos::TraceConfig_ProducerConfig>(Arena*);
template<> ::perfetto::protos::TraceConfig_StatsdMetadata* Arena::CreateMaybeMessage<::perfetto::protos::TraceConfig_StatsdMetadata>(Arena*);
template<> ::perfetto::protos::TraceConfig_TriggerConfig* Arena::CreateMaybeMessage<::perfetto::protos::TraceConfig_TriggerConfig>(Arena*);
template<> ::perfetto::protos::TraceConfig_TriggerConfig_Trigger* Arena::CreateMaybeMessage<::perfetto::protos::TraceConfig_TriggerConfig_Trigger>(Arena*);
PROTOBUF_NAMESPACE_CLOSE
namespace perfetto {
namespace protos {
enum TraceConfig_BufferConfig_FillPolicy : int {
TraceConfig_BufferConfig_FillPolicy_UNSPECIFIED = 0,
TraceConfig_BufferConfig_FillPolicy_RING_BUFFER = 1,
TraceConfig_BufferConfig_FillPolicy_DISCARD = 2
};
bool TraceConfig_BufferConfig_FillPolicy_IsValid(int value);
constexpr TraceConfig_BufferConfig_FillPolicy TraceConfig_BufferConfig_FillPolicy_FillPolicy_MIN = TraceConfig_BufferConfig_FillPolicy_UNSPECIFIED;
constexpr TraceConfig_BufferConfig_FillPolicy TraceConfig_BufferConfig_FillPolicy_FillPolicy_MAX = TraceConfig_BufferConfig_FillPolicy_DISCARD;
constexpr int TraceConfig_BufferConfig_FillPolicy_FillPolicy_ARRAYSIZE = TraceConfig_BufferConfig_FillPolicy_FillPolicy_MAX + 1;
const std::string& TraceConfig_BufferConfig_FillPolicy_Name(TraceConfig_BufferConfig_FillPolicy value);
template<typename T>
inline const std::string& TraceConfig_BufferConfig_FillPolicy_Name(T enum_t_value) {
static_assert(::std::is_same<T, TraceConfig_BufferConfig_FillPolicy>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function TraceConfig_BufferConfig_FillPolicy_Name.");
return TraceConfig_BufferConfig_FillPolicy_Name(static_cast<TraceConfig_BufferConfig_FillPolicy>(enum_t_value));
}
bool TraceConfig_BufferConfig_FillPolicy_Parse(
const std::string& name, TraceConfig_BufferConfig_FillPolicy* value);
enum TraceConfig_TriggerConfig_TriggerMode : int {
TraceConfig_TriggerConfig_TriggerMode_UNSPECIFIED = 0,
TraceConfig_TriggerConfig_TriggerMode_START_TRACING = 1,
TraceConfig_TriggerConfig_TriggerMode_STOP_TRACING = 2
};
bool TraceConfig_TriggerConfig_TriggerMode_IsValid(int value);
constexpr TraceConfig_TriggerConfig_TriggerMode TraceConfig_TriggerConfig_TriggerMode_TriggerMode_MIN = TraceConfig_TriggerConfig_TriggerMode_UNSPECIFIED;
constexpr TraceConfig_TriggerConfig_TriggerMode TraceConfig_TriggerConfig_TriggerMode_TriggerMode_MAX = TraceConfig_TriggerConfig_TriggerMode_STOP_TRACING;
constexpr int TraceConfig_TriggerConfig_TriggerMode_TriggerMode_ARRAYSIZE = TraceConfig_TriggerConfig_TriggerMode_TriggerMode_MAX + 1;
const std::string& TraceConfig_TriggerConfig_TriggerMode_Name(TraceConfig_TriggerConfig_TriggerMode value);
template<typename T>
inline const std::string& TraceConfig_TriggerConfig_TriggerMode_Name(T enum_t_value) {
static_assert(::std::is_same<T, TraceConfig_TriggerConfig_TriggerMode>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function TraceConfig_TriggerConfig_TriggerMode_Name.");
return TraceConfig_TriggerConfig_TriggerMode_Name(static_cast<TraceConfig_TriggerConfig_TriggerMode>(enum_t_value));
}
bool TraceConfig_TriggerConfig_TriggerMode_Parse(
const std::string& name, TraceConfig_TriggerConfig_TriggerMode* value);
enum TraceConfig_LockdownModeOperation : int {
TraceConfig_LockdownModeOperation_LOCKDOWN_UNCHANGED = 0,
TraceConfig_LockdownModeOperation_LOCKDOWN_CLEAR = 1,
TraceConfig_LockdownModeOperation_LOCKDOWN_SET = 2
};
bool TraceConfig_LockdownModeOperation_IsValid(int value);
constexpr TraceConfig_LockdownModeOperation TraceConfig_LockdownModeOperation_LockdownModeOperation_MIN = TraceConfig_LockdownModeOperation_LOCKDOWN_UNCHANGED;
constexpr TraceConfig_LockdownModeOperation TraceConfig_LockdownModeOperation_LockdownModeOperation_MAX = TraceConfig_LockdownModeOperation_LOCKDOWN_SET;
constexpr int TraceConfig_LockdownModeOperation_LockdownModeOperation_ARRAYSIZE = TraceConfig_LockdownModeOperation_LockdownModeOperation_MAX + 1;
const std::string& TraceConfig_LockdownModeOperation_Name(TraceConfig_LockdownModeOperation value);
template<typename T>
inline const std::string& TraceConfig_LockdownModeOperation_Name(T enum_t_value) {
static_assert(::std::is_same<T, TraceConfig_LockdownModeOperation>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function TraceConfig_LockdownModeOperation_Name.");
return TraceConfig_LockdownModeOperation_Name(static_cast<TraceConfig_LockdownModeOperation>(enum_t_value));
}
bool TraceConfig_LockdownModeOperation_Parse(
const std::string& name, TraceConfig_LockdownModeOperation* value);
enum TraceConfig_CompressionType : int {
TraceConfig_CompressionType_COMPRESSION_TYPE_UNSPECIFIED = 0,
TraceConfig_CompressionType_COMPRESSION_TYPE_DEFLATE = 1
};
bool TraceConfig_CompressionType_IsValid(int value);
constexpr TraceConfig_CompressionType TraceConfig_CompressionType_CompressionType_MIN = TraceConfig_CompressionType_COMPRESSION_TYPE_UNSPECIFIED;
constexpr TraceConfig_CompressionType TraceConfig_CompressionType_CompressionType_MAX = TraceConfig_CompressionType_COMPRESSION_TYPE_DEFLATE;
constexpr int TraceConfig_CompressionType_CompressionType_ARRAYSIZE = TraceConfig_CompressionType_CompressionType_MAX + 1;
const std::string& TraceConfig_CompressionType_Name(TraceConfig_CompressionType value);
template<typename T>
inline const std::string& TraceConfig_CompressionType_Name(T enum_t_value) {
static_assert(::std::is_same<T, TraceConfig_CompressionType>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function TraceConfig_CompressionType_Name.");
return TraceConfig_CompressionType_Name(static_cast<TraceConfig_CompressionType>(enum_t_value));
}
bool TraceConfig_CompressionType_Parse(
const std::string& name, TraceConfig_CompressionType* value);
// ===================================================================
class TraceConfig_BufferConfig :
public ::PROTOBUF_NAMESPACE_ID::MessageLite /* @@protoc_insertion_point(class_definition:perfetto.protos.TraceConfig.BufferConfig) */ {
public:
TraceConfig_BufferConfig();
virtual ~TraceConfig_BufferConfig();
TraceConfig_BufferConfig(const TraceConfig_BufferConfig& from);
TraceConfig_BufferConfig(TraceConfig_BufferConfig&& from) noexcept
: TraceConfig_BufferConfig() {
*this = ::std::move(from);
}
inline TraceConfig_BufferConfig& operator=(const TraceConfig_BufferConfig& from) {
CopyFrom(from);
return *this;
}
inline TraceConfig_BufferConfig& operator=(TraceConfig_BufferConfig&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const std::string& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline std::string* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
static const TraceConfig_BufferConfig& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const TraceConfig_BufferConfig* internal_default_instance() {
return reinterpret_cast<const TraceConfig_BufferConfig*>(
&_TraceConfig_BufferConfig_default_instance_);
}
static constexpr int kIndexInFileMessages =
0;
friend void swap(TraceConfig_BufferConfig& a, TraceConfig_BufferConfig& b) {
a.Swap(&b);
}
inline void Swap(TraceConfig_BufferConfig* other) {
if (other == this) return;
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline TraceConfig_BufferConfig* New() const final {
return CreateMaybeMessage<TraceConfig_BufferConfig>(nullptr);
}
TraceConfig_BufferConfig* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<TraceConfig_BufferConfig>(arena);
}
void CheckTypeAndMergeFrom(const ::PROTOBUF_NAMESPACE_ID::MessageLite& from)
final;
void CopyFrom(const TraceConfig_BufferConfig& from);
void MergeFrom(const TraceConfig_BufferConfig& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
#else
bool MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final;
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final;
void DiscardUnknownFields();
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(TraceConfig_BufferConfig* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "perfetto.protos.TraceConfig.BufferConfig";
}
private:
inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
return nullptr;
}
public:
std::string GetTypeName() const final;
// nested types ----------------------------------------------------
typedef TraceConfig_BufferConfig_FillPolicy FillPolicy;
static constexpr FillPolicy UNSPECIFIED =
TraceConfig_BufferConfig_FillPolicy_UNSPECIFIED;
static constexpr FillPolicy RING_BUFFER =
TraceConfig_BufferConfig_FillPolicy_RING_BUFFER;
static constexpr FillPolicy DISCARD =
TraceConfig_BufferConfig_FillPolicy_DISCARD;
static inline bool FillPolicy_IsValid(int value) {
return TraceConfig_BufferConfig_FillPolicy_IsValid(value);
}
static constexpr FillPolicy FillPolicy_MIN =
TraceConfig_BufferConfig_FillPolicy_FillPolicy_MIN;
static constexpr FillPolicy FillPolicy_MAX =
TraceConfig_BufferConfig_FillPolicy_FillPolicy_MAX;
static constexpr int FillPolicy_ARRAYSIZE =
TraceConfig_BufferConfig_FillPolicy_FillPolicy_ARRAYSIZE;
template<typename T>
static inline const std::string& FillPolicy_Name(T enum_t_value) {
static_assert(::std::is_same<T, FillPolicy>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function FillPolicy_Name.");
return TraceConfig_BufferConfig_FillPolicy_Name(enum_t_value);
}
static inline bool FillPolicy_Parse(const std::string& name,
FillPolicy* value) {
return TraceConfig_BufferConfig_FillPolicy_Parse(name, value);
}
// accessors -------------------------------------------------------
enum : int {
kSizeKbFieldNumber = 1,
kFillPolicyFieldNumber = 4,
};
// optional uint32 size_kb = 1;
bool has_size_kb() const;
void clear_size_kb();
::PROTOBUF_NAMESPACE_ID::uint32 size_kb() const;
void set_size_kb(::PROTOBUF_NAMESPACE_ID::uint32 value);
// optional .perfetto.protos.TraceConfig.BufferConfig.FillPolicy fill_policy = 4;
bool has_fill_policy() const;
void clear_fill_policy();
::perfetto::protos::TraceConfig_BufferConfig_FillPolicy fill_policy() const;
void set_fill_policy(::perfetto::protos::TraceConfig_BufferConfig_FillPolicy value);
// @@protoc_insertion_point(class_scope:perfetto.protos.TraceConfig.BufferConfig)
private:
class _Internal;
::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArenaLite _internal_metadata_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::uint32 size_kb_;
int fill_policy_;
friend struct ::TableStruct_protos_2fperfetto_2fconfig_2ftrace_5fconfig_2eproto;
};
// -------------------------------------------------------------------
class TraceConfig_DataSource :
public ::PROTOBUF_NAMESPACE_ID::MessageLite /* @@protoc_insertion_point(class_definition:perfetto.protos.TraceConfig.DataSource) */ {
public:
TraceConfig_DataSource();
virtual ~TraceConfig_DataSource();
TraceConfig_DataSource(const TraceConfig_DataSource& from);
TraceConfig_DataSource(TraceConfig_DataSource&& from) noexcept
: TraceConfig_DataSource() {
*this = ::std::move(from);
}
inline TraceConfig_DataSource& operator=(const TraceConfig_DataSource& from) {
CopyFrom(from);
return *this;
}
inline TraceConfig_DataSource& operator=(TraceConfig_DataSource&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const std::string& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline std::string* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
static const TraceConfig_DataSource& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const TraceConfig_DataSource* internal_default_instance() {
return reinterpret_cast<const TraceConfig_DataSource*>(
&_TraceConfig_DataSource_default_instance_);
}
static constexpr int kIndexInFileMessages =
1;
friend void swap(TraceConfig_DataSource& a, TraceConfig_DataSource& b) {
a.Swap(&b);
}
inline void Swap(TraceConfig_DataSource* other) {
if (other == this) return;
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline TraceConfig_DataSource* New() const final {
return CreateMaybeMessage<TraceConfig_DataSource>(nullptr);
}
TraceConfig_DataSource* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<TraceConfig_DataSource>(arena);
}
void CheckTypeAndMergeFrom(const ::PROTOBUF_NAMESPACE_ID::MessageLite& from)
final;
void CopyFrom(const TraceConfig_DataSource& from);
void MergeFrom(const TraceConfig_DataSource& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
#else
bool MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final;
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final;
void DiscardUnknownFields();
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(TraceConfig_DataSource* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "perfetto.protos.TraceConfig.DataSource";
}
private:
inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
return nullptr;
}
public:
std::string GetTypeName() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kProducerNameFilterFieldNumber = 2,
kProducerNameRegexFilterFieldNumber = 3,
kConfigFieldNumber = 1,
};
// repeated string producer_name_filter = 2;
int producer_name_filter_size() const;
void clear_producer_name_filter();
const std::string& producer_name_filter(int index) const;
std::string* mutable_producer_name_filter(int index);
void set_producer_name_filter(int index, const std::string& value);
void set_producer_name_filter(int index, std::string&& value);
void set_producer_name_filter(int index, const char* value);
void set_producer_name_filter(int index, const char* value, size_t size);
std::string* add_producer_name_filter();
void add_producer_name_filter(const std::string& value);
void add_producer_name_filter(std::string&& value);
void add_producer_name_filter(const char* value);
void add_producer_name_filter(const char* value, size_t size);
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& producer_name_filter() const;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* mutable_producer_name_filter();
// repeated string producer_name_regex_filter = 3;
int producer_name_regex_filter_size() const;
void clear_producer_name_regex_filter();
const std::string& producer_name_regex_filter(int index) const;
std::string* mutable_producer_name_regex_filter(int index);
void set_producer_name_regex_filter(int index, const std::string& value);
void set_producer_name_regex_filter(int index, std::string&& value);
void set_producer_name_regex_filter(int index, const char* value);
void set_producer_name_regex_filter(int index, const char* value, size_t size);
std::string* add_producer_name_regex_filter();
void add_producer_name_regex_filter(const std::string& value);
void add_producer_name_regex_filter(std::string&& value);
void add_producer_name_regex_filter(const char* value);
void add_producer_name_regex_filter(const char* value, size_t size);
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& producer_name_regex_filter() const;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* mutable_producer_name_regex_filter();
// optional .perfetto.protos.DataSourceConfig config = 1;
bool has_config() const;
void clear_config();
const ::perfetto::protos::DataSourceConfig& config() const;
::perfetto::protos::DataSourceConfig* release_config();
::perfetto::protos::DataSourceConfig* mutable_config();
void set_allocated_config(::perfetto::protos::DataSourceConfig* config);
// @@protoc_insertion_point(class_scope:perfetto.protos.TraceConfig.DataSource)
private:
class _Internal;
::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArenaLite _internal_metadata_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> producer_name_filter_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> producer_name_regex_filter_;
::perfetto::protos::DataSourceConfig* config_;
friend struct ::TableStruct_protos_2fperfetto_2fconfig_2ftrace_5fconfig_2eproto;
};
// -------------------------------------------------------------------
class TraceConfig_BuiltinDataSource :
public ::PROTOBUF_NAMESPACE_ID::MessageLite /* @@protoc_insertion_point(class_definition:perfetto.protos.TraceConfig.BuiltinDataSource) */ {
public:
TraceConfig_BuiltinDataSource();
virtual ~TraceConfig_BuiltinDataSource();
TraceConfig_BuiltinDataSource(const TraceConfig_BuiltinDataSource& from);
TraceConfig_BuiltinDataSource(TraceConfig_BuiltinDataSource&& from) noexcept
: TraceConfig_BuiltinDataSource() {
*this = ::std::move(from);
}
inline TraceConfig_BuiltinDataSource& operator=(const TraceConfig_BuiltinDataSource& from) {
CopyFrom(from);
return *this;
}
inline TraceConfig_BuiltinDataSource& operator=(TraceConfig_BuiltinDataSource&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const std::string& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline std::string* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
static const TraceConfig_BuiltinDataSource& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const TraceConfig_BuiltinDataSource* internal_default_instance() {
return reinterpret_cast<const TraceConfig_BuiltinDataSource*>(
&_TraceConfig_BuiltinDataSource_default_instance_);
}
static constexpr int kIndexInFileMessages =
2;
friend void swap(TraceConfig_BuiltinDataSource& a, TraceConfig_BuiltinDataSource& b) {
a.Swap(&b);
}
inline void Swap(TraceConfig_BuiltinDataSource* other) {
if (other == this) return;
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline TraceConfig_BuiltinDataSource* New() const final {
return CreateMaybeMessage<TraceConfig_BuiltinDataSource>(nullptr);
}
TraceConfig_BuiltinDataSource* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<TraceConfig_BuiltinDataSource>(arena);
}
void CheckTypeAndMergeFrom(const ::PROTOBUF_NAMESPACE_ID::MessageLite& from)
final;
void CopyFrom(const TraceConfig_BuiltinDataSource& from);
void MergeFrom(const TraceConfig_BuiltinDataSource& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
#else
bool MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final;
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final;
void DiscardUnknownFields();
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(TraceConfig_BuiltinDataSource* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "perfetto.protos.TraceConfig.BuiltinDataSource";
}
private:
inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
return nullptr;
}
public:
std::string GetTypeName() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kDisableClockSnapshottingFieldNumber = 1,
kDisableTraceConfigFieldNumber = 2,
kDisableSystemInfoFieldNumber = 3,
kDisableServiceEventsFieldNumber = 4,
kPrimaryTraceClockFieldNumber = 5,
kSnapshotIntervalMsFieldNumber = 6,
};
// optional bool disable_clock_snapshotting = 1;
bool has_disable_clock_snapshotting() const;
void clear_disable_clock_snapshotting();
bool disable_clock_snapshotting() const;
void set_disable_clock_snapshotting(bool value);
// optional bool disable_trace_config = 2;
bool has_disable_trace_config() const;
void clear_disable_trace_config();
bool disable_trace_config() const;
void set_disable_trace_config(bool value);
// optional bool disable_system_info = 3;
bool has_disable_system_info() const;
void clear_disable_system_info();
bool disable_system_info() const;
void set_disable_system_info(bool value);
// optional bool disable_service_events = 4;
bool has_disable_service_events() const;
void clear_disable_service_events();
bool disable_service_events() const;
void set_disable_service_events(bool value);
// optional .perfetto.protos.BuiltinClock primary_trace_clock = 5;
bool has_primary_trace_clock() const;
void clear_primary_trace_clock();
::perfetto::protos::BuiltinClock primary_trace_clock() const;
void set_primary_trace_clock(::perfetto::protos::BuiltinClock value);
// optional uint32 snapshot_interval_ms = 6;
bool has_snapshot_interval_ms() const;
void clear_snapshot_interval_ms();
::PROTOBUF_NAMESPACE_ID::uint32 snapshot_interval_ms() const;
void set_snapshot_interval_ms(::PROTOBUF_NAMESPACE_ID::uint32 value);
// @@protoc_insertion_point(class_scope:perfetto.protos.TraceConfig.BuiltinDataSource)
private:
class _Internal;
::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArenaLite _internal_metadata_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
bool disable_clock_snapshotting_;
bool disable_trace_config_;
bool disable_system_info_;
bool disable_service_events_;
int primary_trace_clock_;
::PROTOBUF_NAMESPACE_ID::uint32 snapshot_interval_ms_;
friend struct ::TableStruct_protos_2fperfetto_2fconfig_2ftrace_5fconfig_2eproto;
};
// -------------------------------------------------------------------
class TraceConfig_ProducerConfig :
public ::PROTOBUF_NAMESPACE_ID::MessageLite /* @@protoc_insertion_point(class_definition:perfetto.protos.TraceConfig.ProducerConfig) */ {
public:
TraceConfig_ProducerConfig();
virtual ~TraceConfig_ProducerConfig();
TraceConfig_ProducerConfig(const TraceConfig_ProducerConfig& from);
TraceConfig_ProducerConfig(TraceConfig_ProducerConfig&& from) noexcept
: TraceConfig_ProducerConfig() {
*this = ::std::move(from);
}
inline TraceConfig_ProducerConfig& operator=(const TraceConfig_ProducerConfig& from) {
CopyFrom(from);
return *this;
}
inline TraceConfig_ProducerConfig& operator=(TraceConfig_ProducerConfig&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const std::string& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline std::string* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
static const TraceConfig_ProducerConfig& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const TraceConfig_ProducerConfig* internal_default_instance() {
return reinterpret_cast<const TraceConfig_ProducerConfig*>(
&_TraceConfig_ProducerConfig_default_instance_);
}
static constexpr int kIndexInFileMessages =
3;
friend void swap(TraceConfig_ProducerConfig& a, TraceConfig_ProducerConfig& b) {
a.Swap(&b);
}
inline void Swap(TraceConfig_ProducerConfig* other) {
if (other == this) return;
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline TraceConfig_ProducerConfig* New() const final {
return CreateMaybeMessage<TraceConfig_ProducerConfig>(nullptr);
}
TraceConfig_ProducerConfig* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<TraceConfig_ProducerConfig>(arena);
}
void CheckTypeAndMergeFrom(const ::PROTOBUF_NAMESPACE_ID::MessageLite& from)
final;
void CopyFrom(const TraceConfig_ProducerConfig& from);
void MergeFrom(const TraceConfig_ProducerConfig& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
#else
bool MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final;
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final;
void DiscardUnknownFields();
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(TraceConfig_ProducerConfig* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "perfetto.protos.TraceConfig.ProducerConfig";
}
private:
inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
return nullptr;
}
public:
std::string GetTypeName() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kProducerNameFieldNumber = 1,
kShmSizeKbFieldNumber = 2,
kPageSizeKbFieldNumber = 3,
};
// optional string producer_name = 1;
bool has_producer_name() const;
void clear_producer_name();
const std::string& producer_name() const;
void set_producer_name(const std::string& value);
void set_producer_name(std::string&& value);
void set_producer_name(const char* value);
void set_producer_name(const char* value, size_t size);
std::string* mutable_producer_name();
std::string* release_producer_name();
void set_allocated_producer_name(std::string* producer_name);
// optional uint32 shm_size_kb = 2;
bool has_shm_size_kb() const;
void clear_shm_size_kb();
::PROTOBUF_NAMESPACE_ID::uint32 shm_size_kb() const;
void set_shm_size_kb(::PROTOBUF_NAMESPACE_ID::uint32 value);
// optional uint32 page_size_kb = 3;
bool has_page_size_kb() const;
void clear_page_size_kb();
::PROTOBUF_NAMESPACE_ID::uint32 page_size_kb() const;
void set_page_size_kb(::PROTOBUF_NAMESPACE_ID::uint32 value);
// @@protoc_insertion_point(class_scope:perfetto.protos.TraceConfig.ProducerConfig)
private:
class _Internal;
::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArenaLite _internal_metadata_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr producer_name_;
::PROTOBUF_NAMESPACE_ID::uint32 shm_size_kb_;
::PROTOBUF_NAMESPACE_ID::uint32 page_size_kb_;
friend struct ::TableStruct_protos_2fperfetto_2fconfig_2ftrace_5fconfig_2eproto;
};
// -------------------------------------------------------------------
class TraceConfig_StatsdMetadata :
public ::PROTOBUF_NAMESPACE_ID::MessageLite /* @@protoc_insertion_point(class_definition:perfetto.protos.TraceConfig.StatsdMetadata) */ {
public:
TraceConfig_StatsdMetadata();
virtual ~TraceConfig_StatsdMetadata();
TraceConfig_StatsdMetadata(const TraceConfig_StatsdMetadata& from);
TraceConfig_StatsdMetadata(TraceConfig_StatsdMetadata&& from) noexcept
: TraceConfig_StatsdMetadata() {
*this = ::std::move(from);
}
inline TraceConfig_StatsdMetadata& operator=(const TraceConfig_StatsdMetadata& from) {
CopyFrom(from);
return *this;
}
inline TraceConfig_StatsdMetadata& operator=(TraceConfig_StatsdMetadata&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const std::string& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline std::string* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
static const TraceConfig_StatsdMetadata& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const TraceConfig_StatsdMetadata* internal_default_instance() {
return reinterpret_cast<const TraceConfig_StatsdMetadata*>(
&_TraceConfig_StatsdMetadata_default_instance_);
}
static constexpr int kIndexInFileMessages =
4;
friend void swap(TraceConfig_StatsdMetadata& a, TraceConfig_StatsdMetadata& b) {
a.Swap(&b);
}
inline void Swap(TraceConfig_StatsdMetadata* other) {
if (other == this) return;
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline TraceConfig_StatsdMetadata* New() const final {
return CreateMaybeMessage<TraceConfig_StatsdMetadata>(nullptr);
}
TraceConfig_StatsdMetadata* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<TraceConfig_StatsdMetadata>(arena);
}
void CheckTypeAndMergeFrom(const ::PROTOBUF_NAMESPACE_ID::MessageLite& from)
final;
void CopyFrom(const TraceConfig_StatsdMetadata& from);
void MergeFrom(const TraceConfig_StatsdMetadata& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
#else
bool MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final;
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final;
void DiscardUnknownFields();
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(TraceConfig_StatsdMetadata* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "perfetto.protos.TraceConfig.StatsdMetadata";
}
private:
inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
return nullptr;
}
public:
std::string GetTypeName() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kTriggeringAlertIdFieldNumber = 1,
kTriggeringConfigIdFieldNumber = 3,
kTriggeringSubscriptionIdFieldNumber = 4,
kTriggeringConfigUidFieldNumber = 2,
};
// optional int64 triggering_alert_id = 1;
bool has_triggering_alert_id() const;
void clear_triggering_alert_id();
::PROTOBUF_NAMESPACE_ID::int64 triggering_alert_id() const;
void set_triggering_alert_id(::PROTOBUF_NAMESPACE_ID::int64 value);
// optional int64 triggering_config_id = 3;
bool has_triggering_config_id() const;
void clear_triggering_config_id();
::PROTOBUF_NAMESPACE_ID::int64 triggering_config_id() const;
void set_triggering_config_id(::PROTOBUF_NAMESPACE_ID::int64 value);
// optional int64 triggering_subscription_id = 4;
bool has_triggering_subscription_id() const;
void clear_triggering_subscription_id();
::PROTOBUF_NAMESPACE_ID::int64 triggering_subscription_id() const;
void set_triggering_subscription_id(::PROTOBUF_NAMESPACE_ID::int64 value);
// optional int32 triggering_config_uid = 2;
bool has_triggering_config_uid() const;
void clear_triggering_config_uid();
::PROTOBUF_NAMESPACE_ID::int32 triggering_config_uid() const;
void set_triggering_config_uid(::PROTOBUF_NAMESPACE_ID::int32 value);
// @@protoc_insertion_point(class_scope:perfetto.protos.TraceConfig.StatsdMetadata)
private:
class _Internal;
::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArenaLite _internal_metadata_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::int64 triggering_alert_id_;
::PROTOBUF_NAMESPACE_ID::int64 triggering_config_id_;
::PROTOBUF_NAMESPACE_ID::int64 triggering_subscription_id_;
::PROTOBUF_NAMESPACE_ID::int32 triggering_config_uid_;
friend struct ::TableStruct_protos_2fperfetto_2fconfig_2ftrace_5fconfig_2eproto;
};
// -------------------------------------------------------------------
class TraceConfig_GuardrailOverrides :
public ::PROTOBUF_NAMESPACE_ID::MessageLite /* @@protoc_insertion_point(class_definition:perfetto.protos.TraceConfig.GuardrailOverrides) */ {
public:
TraceConfig_GuardrailOverrides();
virtual ~TraceConfig_GuardrailOverrides();
TraceConfig_GuardrailOverrides(const TraceConfig_GuardrailOverrides& from);
TraceConfig_GuardrailOverrides(TraceConfig_GuardrailOverrides&& from) noexcept
: TraceConfig_GuardrailOverrides() {
*this = ::std::move(from);
}
inline TraceConfig_GuardrailOverrides& operator=(const TraceConfig_GuardrailOverrides& from) {
CopyFrom(from);
return *this;
}
inline TraceConfig_GuardrailOverrides& operator=(TraceConfig_GuardrailOverrides&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const std::string& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline std::string* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
static const TraceConfig_GuardrailOverrides& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const TraceConfig_GuardrailOverrides* internal_default_instance() {
return reinterpret_cast<const TraceConfig_GuardrailOverrides*>(
&_TraceConfig_GuardrailOverrides_default_instance_);
}
static constexpr int kIndexInFileMessages =
5;
friend void swap(TraceConfig_GuardrailOverrides& a, TraceConfig_GuardrailOverrides& b) {
a.Swap(&b);
}
inline void Swap(TraceConfig_GuardrailOverrides* other) {
if (other == this) return;
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline TraceConfig_GuardrailOverrides* New() const final {
return CreateMaybeMessage<TraceConfig_GuardrailOverrides>(nullptr);
}
TraceConfig_GuardrailOverrides* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<TraceConfig_GuardrailOverrides>(arena);
}
void CheckTypeAndMergeFrom(const ::PROTOBUF_NAMESPACE_ID::MessageLite& from)
final;
void CopyFrom(const TraceConfig_GuardrailOverrides& from);
void MergeFrom(const TraceConfig_GuardrailOverrides& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
#else
bool MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final;
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final;
void DiscardUnknownFields();
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(TraceConfig_GuardrailOverrides* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "perfetto.protos.TraceConfig.GuardrailOverrides";
}
private:
inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
return nullptr;
}
public:
std::string GetTypeName() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kMaxUploadPerDayBytesFieldNumber = 1,
};
// optional uint64 max_upload_per_day_bytes = 1;
bool has_max_upload_per_day_bytes() const;
void clear_max_upload_per_day_bytes();
::PROTOBUF_NAMESPACE_ID::uint64 max_upload_per_day_bytes() const;
void set_max_upload_per_day_bytes(::PROTOBUF_NAMESPACE_ID::uint64 value);
// @@protoc_insertion_point(class_scope:perfetto.protos.TraceConfig.GuardrailOverrides)
private:
class _Internal;
::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArenaLite _internal_metadata_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::uint64 max_upload_per_day_bytes_;
friend struct ::TableStruct_protos_2fperfetto_2fconfig_2ftrace_5fconfig_2eproto;
};
// -------------------------------------------------------------------
class TraceConfig_TriggerConfig_Trigger :
public ::PROTOBUF_NAMESPACE_ID::MessageLite /* @@protoc_insertion_point(class_definition:perfetto.protos.TraceConfig.TriggerConfig.Trigger) */ {
public:
TraceConfig_TriggerConfig_Trigger();
virtual ~TraceConfig_TriggerConfig_Trigger();
TraceConfig_TriggerConfig_Trigger(const TraceConfig_TriggerConfig_Trigger& from);
TraceConfig_TriggerConfig_Trigger(TraceConfig_TriggerConfig_Trigger&& from) noexcept
: TraceConfig_TriggerConfig_Trigger() {
*this = ::std::move(from);
}
inline TraceConfig_TriggerConfig_Trigger& operator=(const TraceConfig_TriggerConfig_Trigger& from) {
CopyFrom(from);
return *this;
}
inline TraceConfig_TriggerConfig_Trigger& operator=(TraceConfig_TriggerConfig_Trigger&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const std::string& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline std::string* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
static const TraceConfig_TriggerConfig_Trigger& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const TraceConfig_TriggerConfig_Trigger* internal_default_instance() {
return reinterpret_cast<const TraceConfig_TriggerConfig_Trigger*>(
&_TraceConfig_TriggerConfig_Trigger_default_instance_);
}
static constexpr int kIndexInFileMessages =
6;
friend void swap(TraceConfig_TriggerConfig_Trigger& a, TraceConfig_TriggerConfig_Trigger& b) {
a.Swap(&b);
}
inline void Swap(TraceConfig_TriggerConfig_Trigger* other) {
if (other == this) return;
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline TraceConfig_TriggerConfig_Trigger* New() const final {
return CreateMaybeMessage<TraceConfig_TriggerConfig_Trigger>(nullptr);
}
TraceConfig_TriggerConfig_Trigger* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<TraceConfig_TriggerConfig_Trigger>(arena);
}
void CheckTypeAndMergeFrom(const ::PROTOBUF_NAMESPACE_ID::MessageLite& from)
final;
void CopyFrom(const TraceConfig_TriggerConfig_Trigger& from);
void MergeFrom(const TraceConfig_TriggerConfig_Trigger& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
#else
bool MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final;
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final;
void DiscardUnknownFields();
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(TraceConfig_TriggerConfig_Trigger* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "perfetto.protos.TraceConfig.TriggerConfig.Trigger";
}
private:
inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
return nullptr;
}
public:
std::string GetTypeName() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kNameFieldNumber = 1,
kProducerNameRegexFieldNumber = 2,
kStopDelayMsFieldNumber = 3,
kMaxPer24HFieldNumber = 4,
kSkipProbabilityFieldNumber = 5,
};
// optional string name = 1;
bool has_name() const;
void clear_name();
const std::string& name() const;
void set_name(const std::string& value);
void set_name(std::string&& value);
void set_name(const char* value);
void set_name(const char* value, size_t size);
std::string* mutable_name();
std::string* release_name();
void set_allocated_name(std::string* name);
// optional string producer_name_regex = 2;
bool has_producer_name_regex() const;
void clear_producer_name_regex();
const std::string& producer_name_regex() const;
void set_producer_name_regex(const std::string& value);
void set_producer_name_regex(std::string&& value);
void set_producer_name_regex(const char* value);
void set_producer_name_regex(const char* value, size_t size);
std::string* mutable_producer_name_regex();
std::string* release_producer_name_regex();
void set_allocated_producer_name_regex(std::string* producer_name_regex);
// optional uint32 stop_delay_ms = 3;
bool has_stop_delay_ms() const;
void clear_stop_delay_ms();
::PROTOBUF_NAMESPACE_ID::uint32 stop_delay_ms() const;
void set_stop_delay_ms(::PROTOBUF_NAMESPACE_ID::uint32 value);
// optional uint32 max_per_24_h = 4;
bool has_max_per_24_h() const;
void clear_max_per_24_h();
::PROTOBUF_NAMESPACE_ID::uint32 max_per_24_h() const;
void set_max_per_24_h(::PROTOBUF_NAMESPACE_ID::uint32 value);
// optional double skip_probability = 5;
bool has_skip_probability() const;
void clear_skip_probability();
double skip_probability() const;
void set_skip_probability(double value);
// @@protoc_insertion_point(class_scope:perfetto.protos.TraceConfig.TriggerConfig.Trigger)
private:
class _Internal;
::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArenaLite _internal_metadata_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr producer_name_regex_;
::PROTOBUF_NAMESPACE_ID::uint32 stop_delay_ms_;
::PROTOBUF_NAMESPACE_ID::uint32 max_per_24_h_;
double skip_probability_;
friend struct ::TableStruct_protos_2fperfetto_2fconfig_2ftrace_5fconfig_2eproto;
};
// -------------------------------------------------------------------
class TraceConfig_TriggerConfig :
public ::PROTOBUF_NAMESPACE_ID::MessageLite /* @@protoc_insertion_point(class_definition:perfetto.protos.TraceConfig.TriggerConfig) */ {
public:
TraceConfig_TriggerConfig();
virtual ~TraceConfig_TriggerConfig();
TraceConfig_TriggerConfig(const TraceConfig_TriggerConfig& from);
TraceConfig_TriggerConfig(TraceConfig_TriggerConfig&& from) noexcept
: TraceConfig_TriggerConfig() {
*this = ::std::move(from);
}
inline TraceConfig_TriggerConfig& operator=(const TraceConfig_TriggerConfig& from) {
CopyFrom(from);
return *this;
}
inline TraceConfig_TriggerConfig& operator=(TraceConfig_TriggerConfig&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const std::string& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline std::string* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
static const TraceConfig_TriggerConfig& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const TraceConfig_TriggerConfig* internal_default_instance() {
return reinterpret_cast<const TraceConfig_TriggerConfig*>(
&_TraceConfig_TriggerConfig_default_instance_);
}
static constexpr int kIndexInFileMessages =
7;
friend void swap(TraceConfig_TriggerConfig& a, TraceConfig_TriggerConfig& b) {
a.Swap(&b);
}
inline void Swap(TraceConfig_TriggerConfig* other) {
if (other == this) return;
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline TraceConfig_TriggerConfig* New() const final {
return CreateMaybeMessage<TraceConfig_TriggerConfig>(nullptr);
}
TraceConfig_TriggerConfig* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<TraceConfig_TriggerConfig>(arena);
}
void CheckTypeAndMergeFrom(const ::PROTOBUF_NAMESPACE_ID::MessageLite& from)
final;
void CopyFrom(const TraceConfig_TriggerConfig& from);
void MergeFrom(const TraceConfig_TriggerConfig& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
#else
bool MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final;
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final;
void DiscardUnknownFields();
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(TraceConfig_TriggerConfig* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "perfetto.protos.TraceConfig.TriggerConfig";
}
private:
inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
return nullptr;
}
public:
std::string GetTypeName() const final;
// nested types ----------------------------------------------------
typedef TraceConfig_TriggerConfig_Trigger Trigger;
typedef TraceConfig_TriggerConfig_TriggerMode TriggerMode;
static constexpr TriggerMode UNSPECIFIED =
TraceConfig_TriggerConfig_TriggerMode_UNSPECIFIED;
static constexpr TriggerMode START_TRACING =
TraceConfig_TriggerConfig_TriggerMode_START_TRACING;
static constexpr TriggerMode STOP_TRACING =
TraceConfig_TriggerConfig_TriggerMode_STOP_TRACING;
static inline bool TriggerMode_IsValid(int value) {
return TraceConfig_TriggerConfig_TriggerMode_IsValid(value);
}
static constexpr TriggerMode TriggerMode_MIN =
TraceConfig_TriggerConfig_TriggerMode_TriggerMode_MIN;
static constexpr TriggerMode TriggerMode_MAX =
TraceConfig_TriggerConfig_TriggerMode_TriggerMode_MAX;
static constexpr int TriggerMode_ARRAYSIZE =
TraceConfig_TriggerConfig_TriggerMode_TriggerMode_ARRAYSIZE;
template<typename T>
static inline const std::string& TriggerMode_Name(T enum_t_value) {
static_assert(::std::is_same<T, TriggerMode>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function TriggerMode_Name.");
return TraceConfig_TriggerConfig_TriggerMode_Name(enum_t_value);
}
static inline bool TriggerMode_Parse(const std::string& name,
TriggerMode* value) {
return TraceConfig_TriggerConfig_TriggerMode_Parse(name, value);
}
// accessors -------------------------------------------------------
enum : int {
kTriggersFieldNumber = 2,
kTriggerModeFieldNumber = 1,
kTriggerTimeoutMsFieldNumber = 3,
};
// repeated .perfetto.protos.TraceConfig.TriggerConfig.Trigger triggers = 2;
int triggers_size() const;
void clear_triggers();
::perfetto::protos::TraceConfig_TriggerConfig_Trigger* mutable_triggers(int index);
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_TriggerConfig_Trigger >*
mutable_triggers();
const ::perfetto::protos::TraceConfig_TriggerConfig_Trigger& triggers(int index) const;
::perfetto::protos::TraceConfig_TriggerConfig_Trigger* add_triggers();
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_TriggerConfig_Trigger >&
triggers() const;
// optional .perfetto.protos.TraceConfig.TriggerConfig.TriggerMode trigger_mode = 1;
bool has_trigger_mode() const;
void clear_trigger_mode();
::perfetto::protos::TraceConfig_TriggerConfig_TriggerMode trigger_mode() const;
void set_trigger_mode(::perfetto::protos::TraceConfig_TriggerConfig_TriggerMode value);
// optional uint32 trigger_timeout_ms = 3;
bool has_trigger_timeout_ms() const;
void clear_trigger_timeout_ms();
::PROTOBUF_NAMESPACE_ID::uint32 trigger_timeout_ms() const;
void set_trigger_timeout_ms(::PROTOBUF_NAMESPACE_ID::uint32 value);
// @@protoc_insertion_point(class_scope:perfetto.protos.TraceConfig.TriggerConfig)
private:
class _Internal;
::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArenaLite _internal_metadata_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_TriggerConfig_Trigger > triggers_;
int trigger_mode_;
::PROTOBUF_NAMESPACE_ID::uint32 trigger_timeout_ms_;
friend struct ::TableStruct_protos_2fperfetto_2fconfig_2ftrace_5fconfig_2eproto;
};
// -------------------------------------------------------------------
class TraceConfig_IncrementalStateConfig :
public ::PROTOBUF_NAMESPACE_ID::MessageLite /* @@protoc_insertion_point(class_definition:perfetto.protos.TraceConfig.IncrementalStateConfig) */ {
public:
TraceConfig_IncrementalStateConfig();
virtual ~TraceConfig_IncrementalStateConfig();
TraceConfig_IncrementalStateConfig(const TraceConfig_IncrementalStateConfig& from);
TraceConfig_IncrementalStateConfig(TraceConfig_IncrementalStateConfig&& from) noexcept
: TraceConfig_IncrementalStateConfig() {
*this = ::std::move(from);
}
inline TraceConfig_IncrementalStateConfig& operator=(const TraceConfig_IncrementalStateConfig& from) {
CopyFrom(from);
return *this;
}
inline TraceConfig_IncrementalStateConfig& operator=(TraceConfig_IncrementalStateConfig&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const std::string& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline std::string* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
static const TraceConfig_IncrementalStateConfig& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const TraceConfig_IncrementalStateConfig* internal_default_instance() {
return reinterpret_cast<const TraceConfig_IncrementalStateConfig*>(
&_TraceConfig_IncrementalStateConfig_default_instance_);
}
static constexpr int kIndexInFileMessages =
8;
friend void swap(TraceConfig_IncrementalStateConfig& a, TraceConfig_IncrementalStateConfig& b) {
a.Swap(&b);
}
inline void Swap(TraceConfig_IncrementalStateConfig* other) {
if (other == this) return;
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline TraceConfig_IncrementalStateConfig* New() const final {
return CreateMaybeMessage<TraceConfig_IncrementalStateConfig>(nullptr);
}
TraceConfig_IncrementalStateConfig* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<TraceConfig_IncrementalStateConfig>(arena);
}
void CheckTypeAndMergeFrom(const ::PROTOBUF_NAMESPACE_ID::MessageLite& from)
final;
void CopyFrom(const TraceConfig_IncrementalStateConfig& from);
void MergeFrom(const TraceConfig_IncrementalStateConfig& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
#else
bool MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final;
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final;
void DiscardUnknownFields();
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(TraceConfig_IncrementalStateConfig* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "perfetto.protos.TraceConfig.IncrementalStateConfig";
}
private:
inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
return nullptr;
}
public:
std::string GetTypeName() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kClearPeriodMsFieldNumber = 1,
};
// optional uint32 clear_period_ms = 1;
bool has_clear_period_ms() const;
void clear_clear_period_ms();
::PROTOBUF_NAMESPACE_ID::uint32 clear_period_ms() const;
void set_clear_period_ms(::PROTOBUF_NAMESPACE_ID::uint32 value);
// @@protoc_insertion_point(class_scope:perfetto.protos.TraceConfig.IncrementalStateConfig)
private:
class _Internal;
::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArenaLite _internal_metadata_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::uint32 clear_period_ms_;
friend struct ::TableStruct_protos_2fperfetto_2fconfig_2ftrace_5fconfig_2eproto;
};
// -------------------------------------------------------------------
class TraceConfig_IncidentReportConfig :
public ::PROTOBUF_NAMESPACE_ID::MessageLite /* @@protoc_insertion_point(class_definition:perfetto.protos.TraceConfig.IncidentReportConfig) */ {
public:
TraceConfig_IncidentReportConfig();
virtual ~TraceConfig_IncidentReportConfig();
TraceConfig_IncidentReportConfig(const TraceConfig_IncidentReportConfig& from);
TraceConfig_IncidentReportConfig(TraceConfig_IncidentReportConfig&& from) noexcept
: TraceConfig_IncidentReportConfig() {
*this = ::std::move(from);
}
inline TraceConfig_IncidentReportConfig& operator=(const TraceConfig_IncidentReportConfig& from) {
CopyFrom(from);
return *this;
}
inline TraceConfig_IncidentReportConfig& operator=(TraceConfig_IncidentReportConfig&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const std::string& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline std::string* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
static const TraceConfig_IncidentReportConfig& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const TraceConfig_IncidentReportConfig* internal_default_instance() {
return reinterpret_cast<const TraceConfig_IncidentReportConfig*>(
&_TraceConfig_IncidentReportConfig_default_instance_);
}
static constexpr int kIndexInFileMessages =
9;
friend void swap(TraceConfig_IncidentReportConfig& a, TraceConfig_IncidentReportConfig& b) {
a.Swap(&b);
}
inline void Swap(TraceConfig_IncidentReportConfig* other) {
if (other == this) return;
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline TraceConfig_IncidentReportConfig* New() const final {
return CreateMaybeMessage<TraceConfig_IncidentReportConfig>(nullptr);
}
TraceConfig_IncidentReportConfig* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<TraceConfig_IncidentReportConfig>(arena);
}
void CheckTypeAndMergeFrom(const ::PROTOBUF_NAMESPACE_ID::MessageLite& from)
final;
void CopyFrom(const TraceConfig_IncidentReportConfig& from);
void MergeFrom(const TraceConfig_IncidentReportConfig& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
#else
bool MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final;
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final;
void DiscardUnknownFields();
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(TraceConfig_IncidentReportConfig* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "perfetto.protos.TraceConfig.IncidentReportConfig";
}
private:
inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
return nullptr;
}
public:
std::string GetTypeName() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kDestinationPackageFieldNumber = 1,
kDestinationClassFieldNumber = 2,
kPrivacyLevelFieldNumber = 3,
kSkipDropboxFieldNumber = 4,
};
// optional string destination_package = 1;
bool has_destination_package() const;
void clear_destination_package();
const std::string& destination_package() const;
void set_destination_package(const std::string& value);
void set_destination_package(std::string&& value);
void set_destination_package(const char* value);
void set_destination_package(const char* value, size_t size);
std::string* mutable_destination_package();
std::string* release_destination_package();
void set_allocated_destination_package(std::string* destination_package);
// optional string destination_class = 2;
bool has_destination_class() const;
void clear_destination_class();
const std::string& destination_class() const;
void set_destination_class(const std::string& value);
void set_destination_class(std::string&& value);
void set_destination_class(const char* value);
void set_destination_class(const char* value, size_t size);
std::string* mutable_destination_class();
std::string* release_destination_class();
void set_allocated_destination_class(std::string* destination_class);
// optional int32 privacy_level = 3;
bool has_privacy_level() const;
void clear_privacy_level();
::PROTOBUF_NAMESPACE_ID::int32 privacy_level() const;
void set_privacy_level(::PROTOBUF_NAMESPACE_ID::int32 value);
// optional bool skip_dropbox = 4;
bool has_skip_dropbox() const;
void clear_skip_dropbox();
bool skip_dropbox() const;
void set_skip_dropbox(bool value);
// @@protoc_insertion_point(class_scope:perfetto.protos.TraceConfig.IncidentReportConfig)
private:
class _Internal;
::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArenaLite _internal_metadata_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr destination_package_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr destination_class_;
::PROTOBUF_NAMESPACE_ID::int32 privacy_level_;
bool skip_dropbox_;
friend struct ::TableStruct_protos_2fperfetto_2fconfig_2ftrace_5fconfig_2eproto;
};
// -------------------------------------------------------------------
class TraceConfig :
public ::PROTOBUF_NAMESPACE_ID::MessageLite /* @@protoc_insertion_point(class_definition:perfetto.protos.TraceConfig) */ {
public:
TraceConfig();
virtual ~TraceConfig();
TraceConfig(const TraceConfig& from);
TraceConfig(TraceConfig&& from) noexcept
: TraceConfig() {
*this = ::std::move(from);
}
inline TraceConfig& operator=(const TraceConfig& from) {
CopyFrom(from);
return *this;
}
inline TraceConfig& operator=(TraceConfig&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const std::string& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline std::string* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
static const TraceConfig& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const TraceConfig* internal_default_instance() {
return reinterpret_cast<const TraceConfig*>(
&_TraceConfig_default_instance_);
}
static constexpr int kIndexInFileMessages =
10;
friend void swap(TraceConfig& a, TraceConfig& b) {
a.Swap(&b);
}
inline void Swap(TraceConfig* other) {
if (other == this) return;
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline TraceConfig* New() const final {
return CreateMaybeMessage<TraceConfig>(nullptr);
}
TraceConfig* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<TraceConfig>(arena);
}
void CheckTypeAndMergeFrom(const ::PROTOBUF_NAMESPACE_ID::MessageLite& from)
final;
void CopyFrom(const TraceConfig& from);
void MergeFrom(const TraceConfig& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
#else
bool MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) final;
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const final;
void DiscardUnknownFields();
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(TraceConfig* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "perfetto.protos.TraceConfig";
}
private:
inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
return nullptr;
}
public:
std::string GetTypeName() const final;
// nested types ----------------------------------------------------
typedef TraceConfig_BufferConfig BufferConfig;
typedef TraceConfig_DataSource DataSource;
typedef TraceConfig_BuiltinDataSource BuiltinDataSource;
typedef TraceConfig_ProducerConfig ProducerConfig;
typedef TraceConfig_StatsdMetadata StatsdMetadata;
typedef TraceConfig_GuardrailOverrides GuardrailOverrides;
typedef TraceConfig_TriggerConfig TriggerConfig;
typedef TraceConfig_IncrementalStateConfig IncrementalStateConfig;
typedef TraceConfig_IncidentReportConfig IncidentReportConfig;
typedef TraceConfig_LockdownModeOperation LockdownModeOperation;
static constexpr LockdownModeOperation LOCKDOWN_UNCHANGED =
TraceConfig_LockdownModeOperation_LOCKDOWN_UNCHANGED;
static constexpr LockdownModeOperation LOCKDOWN_CLEAR =
TraceConfig_LockdownModeOperation_LOCKDOWN_CLEAR;
static constexpr LockdownModeOperation LOCKDOWN_SET =
TraceConfig_LockdownModeOperation_LOCKDOWN_SET;
static inline bool LockdownModeOperation_IsValid(int value) {
return TraceConfig_LockdownModeOperation_IsValid(value);
}
static constexpr LockdownModeOperation LockdownModeOperation_MIN =
TraceConfig_LockdownModeOperation_LockdownModeOperation_MIN;
static constexpr LockdownModeOperation LockdownModeOperation_MAX =
TraceConfig_LockdownModeOperation_LockdownModeOperation_MAX;
static constexpr int LockdownModeOperation_ARRAYSIZE =
TraceConfig_LockdownModeOperation_LockdownModeOperation_ARRAYSIZE;
template<typename T>
static inline const std::string& LockdownModeOperation_Name(T enum_t_value) {
static_assert(::std::is_same<T, LockdownModeOperation>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function LockdownModeOperation_Name.");
return TraceConfig_LockdownModeOperation_Name(enum_t_value);
}
static inline bool LockdownModeOperation_Parse(const std::string& name,
LockdownModeOperation* value) {
return TraceConfig_LockdownModeOperation_Parse(name, value);
}
typedef TraceConfig_CompressionType CompressionType;
static constexpr CompressionType COMPRESSION_TYPE_UNSPECIFIED =
TraceConfig_CompressionType_COMPRESSION_TYPE_UNSPECIFIED;
static constexpr CompressionType COMPRESSION_TYPE_DEFLATE =
TraceConfig_CompressionType_COMPRESSION_TYPE_DEFLATE;
static inline bool CompressionType_IsValid(int value) {
return TraceConfig_CompressionType_IsValid(value);
}
static constexpr CompressionType CompressionType_MIN =
TraceConfig_CompressionType_CompressionType_MIN;
static constexpr CompressionType CompressionType_MAX =
TraceConfig_CompressionType_CompressionType_MAX;
static constexpr int CompressionType_ARRAYSIZE =
TraceConfig_CompressionType_CompressionType_ARRAYSIZE;
template<typename T>
static inline const std::string& CompressionType_Name(T enum_t_value) {
static_assert(::std::is_same<T, CompressionType>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function CompressionType_Name.");
return TraceConfig_CompressionType_Name(enum_t_value);
}
static inline bool CompressionType_Parse(const std::string& name,
CompressionType* value) {
return TraceConfig_CompressionType_Parse(name, value);
}
// accessors -------------------------------------------------------
enum : int {
kBuffersFieldNumber = 1,
kDataSourcesFieldNumber = 2,
kProducersFieldNumber = 6,
kActivateTriggersFieldNumber = 18,
kUniqueSessionNameFieldNumber = 22,
kOutputPathFieldNumber = 29,
kStatsdMetadataFieldNumber = 7,
kGuardrailOverridesFieldNumber = 11,
kTriggerConfigFieldNumber = 17,
kBuiltinDataSourcesFieldNumber = 20,
kIncrementalStateConfigFieldNumber = 21,
kIncidentReportConfigFieldNumber = 25,
kDurationMsFieldNumber = 3,
kLockdownModeFieldNumber = 5,
kFileWritePeriodMsFieldNumber = 9,
kEnableExtraGuardrailsFieldNumber = 4,
kWriteIntoFileFieldNumber = 8,
kDeferredStartFieldNumber = 12,
kNotifyTraceurFieldNumber = 16,
kMaxFileSizeBytesFieldNumber = 10,
kFlushPeriodMsFieldNumber = 13,
kFlushTimeoutMsFieldNumber = 14,
kAllowUserBuildTracingFieldNumber = 19,
kDataSourceStopTimeoutMsFieldNumber = 23,
kTraceUuidMsbFieldNumber = 27,
kCompressionTypeFieldNumber = 24,
kBugreportScoreFieldNumber = 30,
kTraceUuidLsbFieldNumber = 28,
};
// repeated .perfetto.protos.TraceConfig.BufferConfig buffers = 1;
int buffers_size() const;
void clear_buffers();
::perfetto::protos::TraceConfig_BufferConfig* mutable_buffers(int index);
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_BufferConfig >*
mutable_buffers();
const ::perfetto::protos::TraceConfig_BufferConfig& buffers(int index) const;
::perfetto::protos::TraceConfig_BufferConfig* add_buffers();
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_BufferConfig >&
buffers() const;
// repeated .perfetto.protos.TraceConfig.DataSource data_sources = 2;
int data_sources_size() const;
void clear_data_sources();
::perfetto::protos::TraceConfig_DataSource* mutable_data_sources(int index);
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_DataSource >*
mutable_data_sources();
const ::perfetto::protos::TraceConfig_DataSource& data_sources(int index) const;
::perfetto::protos::TraceConfig_DataSource* add_data_sources();
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_DataSource >&
data_sources() const;
// repeated .perfetto.protos.TraceConfig.ProducerConfig producers = 6;
int producers_size() const;
void clear_producers();
::perfetto::protos::TraceConfig_ProducerConfig* mutable_producers(int index);
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_ProducerConfig >*
mutable_producers();
const ::perfetto::protos::TraceConfig_ProducerConfig& producers(int index) const;
::perfetto::protos::TraceConfig_ProducerConfig* add_producers();
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_ProducerConfig >&
producers() const;
// repeated string activate_triggers = 18;
int activate_triggers_size() const;
void clear_activate_triggers();
const std::string& activate_triggers(int index) const;
std::string* mutable_activate_triggers(int index);
void set_activate_triggers(int index, const std::string& value);
void set_activate_triggers(int index, std::string&& value);
void set_activate_triggers(int index, const char* value);
void set_activate_triggers(int index, const char* value, size_t size);
std::string* add_activate_triggers();
void add_activate_triggers(const std::string& value);
void add_activate_triggers(std::string&& value);
void add_activate_triggers(const char* value);
void add_activate_triggers(const char* value, size_t size);
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& activate_triggers() const;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* mutable_activate_triggers();
// optional string unique_session_name = 22;
bool has_unique_session_name() const;
void clear_unique_session_name();
const std::string& unique_session_name() const;
void set_unique_session_name(const std::string& value);
void set_unique_session_name(std::string&& value);
void set_unique_session_name(const char* value);
void set_unique_session_name(const char* value, size_t size);
std::string* mutable_unique_session_name();
std::string* release_unique_session_name();
void set_allocated_unique_session_name(std::string* unique_session_name);
// optional string output_path = 29;
bool has_output_path() const;
void clear_output_path();
const std::string& output_path() const;
void set_output_path(const std::string& value);
void set_output_path(std::string&& value);
void set_output_path(const char* value);
void set_output_path(const char* value, size_t size);
std::string* mutable_output_path();
std::string* release_output_path();
void set_allocated_output_path(std::string* output_path);
// optional .perfetto.protos.TraceConfig.StatsdMetadata statsd_metadata = 7;
bool has_statsd_metadata() const;
void clear_statsd_metadata();
const ::perfetto::protos::TraceConfig_StatsdMetadata& statsd_metadata() const;
::perfetto::protos::TraceConfig_StatsdMetadata* release_statsd_metadata();
::perfetto::protos::TraceConfig_StatsdMetadata* mutable_statsd_metadata();
void set_allocated_statsd_metadata(::perfetto::protos::TraceConfig_StatsdMetadata* statsd_metadata);
// optional .perfetto.protos.TraceConfig.GuardrailOverrides guardrail_overrides = 11;
bool has_guardrail_overrides() const;
void clear_guardrail_overrides();
const ::perfetto::protos::TraceConfig_GuardrailOverrides& guardrail_overrides() const;
::perfetto::protos::TraceConfig_GuardrailOverrides* release_guardrail_overrides();
::perfetto::protos::TraceConfig_GuardrailOverrides* mutable_guardrail_overrides();
void set_allocated_guardrail_overrides(::perfetto::protos::TraceConfig_GuardrailOverrides* guardrail_overrides);
// optional .perfetto.protos.TraceConfig.TriggerConfig trigger_config = 17;
bool has_trigger_config() const;
void clear_trigger_config();
const ::perfetto::protos::TraceConfig_TriggerConfig& trigger_config() const;
::perfetto::protos::TraceConfig_TriggerConfig* release_trigger_config();
::perfetto::protos::TraceConfig_TriggerConfig* mutable_trigger_config();
void set_allocated_trigger_config(::perfetto::protos::TraceConfig_TriggerConfig* trigger_config);
// optional .perfetto.protos.TraceConfig.BuiltinDataSource builtin_data_sources = 20;
bool has_builtin_data_sources() const;
void clear_builtin_data_sources();
const ::perfetto::protos::TraceConfig_BuiltinDataSource& builtin_data_sources() const;
::perfetto::protos::TraceConfig_BuiltinDataSource* release_builtin_data_sources();
::perfetto::protos::TraceConfig_BuiltinDataSource* mutable_builtin_data_sources();
void set_allocated_builtin_data_sources(::perfetto::protos::TraceConfig_BuiltinDataSource* builtin_data_sources);
// optional .perfetto.protos.TraceConfig.IncrementalStateConfig incremental_state_config = 21;
bool has_incremental_state_config() const;
void clear_incremental_state_config();
const ::perfetto::protos::TraceConfig_IncrementalStateConfig& incremental_state_config() const;
::perfetto::protos::TraceConfig_IncrementalStateConfig* release_incremental_state_config();
::perfetto::protos::TraceConfig_IncrementalStateConfig* mutable_incremental_state_config();
void set_allocated_incremental_state_config(::perfetto::protos::TraceConfig_IncrementalStateConfig* incremental_state_config);
// optional .perfetto.protos.TraceConfig.IncidentReportConfig incident_report_config = 25;
bool has_incident_report_config() const;
void clear_incident_report_config();
const ::perfetto::protos::TraceConfig_IncidentReportConfig& incident_report_config() const;
::perfetto::protos::TraceConfig_IncidentReportConfig* release_incident_report_config();
::perfetto::protos::TraceConfig_IncidentReportConfig* mutable_incident_report_config();
void set_allocated_incident_report_config(::perfetto::protos::TraceConfig_IncidentReportConfig* incident_report_config);
// optional uint32 duration_ms = 3;
bool has_duration_ms() const;
void clear_duration_ms();
::PROTOBUF_NAMESPACE_ID::uint32 duration_ms() const;
void set_duration_ms(::PROTOBUF_NAMESPACE_ID::uint32 value);
// optional .perfetto.protos.TraceConfig.LockdownModeOperation lockdown_mode = 5;
bool has_lockdown_mode() const;
void clear_lockdown_mode();
::perfetto::protos::TraceConfig_LockdownModeOperation lockdown_mode() const;
void set_lockdown_mode(::perfetto::protos::TraceConfig_LockdownModeOperation value);
// optional uint32 file_write_period_ms = 9;
bool has_file_write_period_ms() const;
void clear_file_write_period_ms();
::PROTOBUF_NAMESPACE_ID::uint32 file_write_period_ms() const;
void set_file_write_period_ms(::PROTOBUF_NAMESPACE_ID::uint32 value);
// optional bool enable_extra_guardrails = 4;
bool has_enable_extra_guardrails() const;
void clear_enable_extra_guardrails();
bool enable_extra_guardrails() const;
void set_enable_extra_guardrails(bool value);
// optional bool write_into_file = 8;
bool has_write_into_file() const;
void clear_write_into_file();
bool write_into_file() const;
void set_write_into_file(bool value);
// optional bool deferred_start = 12;
bool has_deferred_start() const;
void clear_deferred_start();
bool deferred_start() const;
void set_deferred_start(bool value);
// optional bool notify_traceur = 16;
bool has_notify_traceur() const;
void clear_notify_traceur();
bool notify_traceur() const;
void set_notify_traceur(bool value);
// optional uint64 max_file_size_bytes = 10;
bool has_max_file_size_bytes() const;
void clear_max_file_size_bytes();
::PROTOBUF_NAMESPACE_ID::uint64 max_file_size_bytes() const;
void set_max_file_size_bytes(::PROTOBUF_NAMESPACE_ID::uint64 value);
// optional uint32 flush_period_ms = 13;
bool has_flush_period_ms() const;
void clear_flush_period_ms();
::PROTOBUF_NAMESPACE_ID::uint32 flush_period_ms() const;
void set_flush_period_ms(::PROTOBUF_NAMESPACE_ID::uint32 value);
// optional uint32 flush_timeout_ms = 14;
bool has_flush_timeout_ms() const;
void clear_flush_timeout_ms();
::PROTOBUF_NAMESPACE_ID::uint32 flush_timeout_ms() const;
void set_flush_timeout_ms(::PROTOBUF_NAMESPACE_ID::uint32 value);
// optional bool allow_user_build_tracing = 19;
bool has_allow_user_build_tracing() const;
void clear_allow_user_build_tracing();
bool allow_user_build_tracing() const;
void set_allow_user_build_tracing(bool value);
// optional uint32 data_source_stop_timeout_ms = 23;
bool has_data_source_stop_timeout_ms() const;
void clear_data_source_stop_timeout_ms();
::PROTOBUF_NAMESPACE_ID::uint32 data_source_stop_timeout_ms() const;
void set_data_source_stop_timeout_ms(::PROTOBUF_NAMESPACE_ID::uint32 value);
// optional int64 trace_uuid_msb = 27;
bool has_trace_uuid_msb() const;
void clear_trace_uuid_msb();
::PROTOBUF_NAMESPACE_ID::int64 trace_uuid_msb() const;
void set_trace_uuid_msb(::PROTOBUF_NAMESPACE_ID::int64 value);
// optional .perfetto.protos.TraceConfig.CompressionType compression_type = 24;
bool has_compression_type() const;
void clear_compression_type();
::perfetto::protos::TraceConfig_CompressionType compression_type() const;
void set_compression_type(::perfetto::protos::TraceConfig_CompressionType value);
// optional int32 bugreport_score = 30;
bool has_bugreport_score() const;
void clear_bugreport_score();
::PROTOBUF_NAMESPACE_ID::int32 bugreport_score() const;
void set_bugreport_score(::PROTOBUF_NAMESPACE_ID::int32 value);
// optional int64 trace_uuid_lsb = 28;
bool has_trace_uuid_lsb() const;
void clear_trace_uuid_lsb();
::PROTOBUF_NAMESPACE_ID::int64 trace_uuid_lsb() const;
void set_trace_uuid_lsb(::PROTOBUF_NAMESPACE_ID::int64 value);
// @@protoc_insertion_point(class_scope:perfetto.protos.TraceConfig)
private:
class _Internal;
::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArenaLite _internal_metadata_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_BufferConfig > buffers_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_DataSource > data_sources_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_ProducerConfig > producers_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> activate_triggers_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr unique_session_name_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr output_path_;
::perfetto::protos::TraceConfig_StatsdMetadata* statsd_metadata_;
::perfetto::protos::TraceConfig_GuardrailOverrides* guardrail_overrides_;
::perfetto::protos::TraceConfig_TriggerConfig* trigger_config_;
::perfetto::protos::TraceConfig_BuiltinDataSource* builtin_data_sources_;
::perfetto::protos::TraceConfig_IncrementalStateConfig* incremental_state_config_;
::perfetto::protos::TraceConfig_IncidentReportConfig* incident_report_config_;
::PROTOBUF_NAMESPACE_ID::uint32 duration_ms_;
int lockdown_mode_;
::PROTOBUF_NAMESPACE_ID::uint32 file_write_period_ms_;
bool enable_extra_guardrails_;
bool write_into_file_;
bool deferred_start_;
bool notify_traceur_;
::PROTOBUF_NAMESPACE_ID::uint64 max_file_size_bytes_;
::PROTOBUF_NAMESPACE_ID::uint32 flush_period_ms_;
::PROTOBUF_NAMESPACE_ID::uint32 flush_timeout_ms_;
bool allow_user_build_tracing_;
::PROTOBUF_NAMESPACE_ID::uint32 data_source_stop_timeout_ms_;
::PROTOBUF_NAMESPACE_ID::int64 trace_uuid_msb_;
int compression_type_;
::PROTOBUF_NAMESPACE_ID::int32 bugreport_score_;
::PROTOBUF_NAMESPACE_ID::int64 trace_uuid_lsb_;
friend struct ::TableStruct_protos_2fperfetto_2fconfig_2ftrace_5fconfig_2eproto;
};
// ===================================================================
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// TraceConfig_BufferConfig
// optional uint32 size_kb = 1;
inline bool TraceConfig_BufferConfig::has_size_kb() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void TraceConfig_BufferConfig::clear_size_kb() {
size_kb_ = 0u;
_has_bits_[0] &= ~0x00000001u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 TraceConfig_BufferConfig::size_kb() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.BufferConfig.size_kb)
return size_kb_;
}
inline void TraceConfig_BufferConfig::set_size_kb(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_has_bits_[0] |= 0x00000001u;
size_kb_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.BufferConfig.size_kb)
}
// optional .perfetto.protos.TraceConfig.BufferConfig.FillPolicy fill_policy = 4;
inline bool TraceConfig_BufferConfig::has_fill_policy() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void TraceConfig_BufferConfig::clear_fill_policy() {
fill_policy_ = 0;
_has_bits_[0] &= ~0x00000002u;
}
inline ::perfetto::protos::TraceConfig_BufferConfig_FillPolicy TraceConfig_BufferConfig::fill_policy() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.BufferConfig.fill_policy)
return static_cast< ::perfetto::protos::TraceConfig_BufferConfig_FillPolicy >(fill_policy_);
}
inline void TraceConfig_BufferConfig::set_fill_policy(::perfetto::protos::TraceConfig_BufferConfig_FillPolicy value) {
assert(::perfetto::protos::TraceConfig_BufferConfig_FillPolicy_IsValid(value));
_has_bits_[0] |= 0x00000002u;
fill_policy_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.BufferConfig.fill_policy)
}
// -------------------------------------------------------------------
// TraceConfig_DataSource
// optional .perfetto.protos.DataSourceConfig config = 1;
inline bool TraceConfig_DataSource::has_config() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline const ::perfetto::protos::DataSourceConfig& TraceConfig_DataSource::config() const {
const ::perfetto::protos::DataSourceConfig* p = config_;
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.DataSource.config)
return p != nullptr ? *p : *reinterpret_cast<const ::perfetto::protos::DataSourceConfig*>(
&::perfetto::protos::_DataSourceConfig_default_instance_);
}
inline ::perfetto::protos::DataSourceConfig* TraceConfig_DataSource::release_config() {
// @@protoc_insertion_point(field_release:perfetto.protos.TraceConfig.DataSource.config)
_has_bits_[0] &= ~0x00000001u;
::perfetto::protos::DataSourceConfig* temp = config_;
config_ = nullptr;
return temp;
}
inline ::perfetto::protos::DataSourceConfig* TraceConfig_DataSource::mutable_config() {
_has_bits_[0] |= 0x00000001u;
if (config_ == nullptr) {
auto* p = CreateMaybeMessage<::perfetto::protos::DataSourceConfig>(GetArenaNoVirtual());
config_ = p;
}
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.DataSource.config)
return config_;
}
inline void TraceConfig_DataSource::set_allocated_config(::perfetto::protos::DataSourceConfig* config) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == nullptr) {
delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(config_);
}
if (config) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
config = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, config, submessage_arena);
}
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
config_ = config;
// @@protoc_insertion_point(field_set_allocated:perfetto.protos.TraceConfig.DataSource.config)
}
// repeated string producer_name_filter = 2;
inline int TraceConfig_DataSource::producer_name_filter_size() const {
return producer_name_filter_.size();
}
inline void TraceConfig_DataSource::clear_producer_name_filter() {
producer_name_filter_.Clear();
}
inline const std::string& TraceConfig_DataSource::producer_name_filter(int index) const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.DataSource.producer_name_filter)
return producer_name_filter_.Get(index);
}
inline std::string* TraceConfig_DataSource::mutable_producer_name_filter(int index) {
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.DataSource.producer_name_filter)
return producer_name_filter_.Mutable(index);
}
inline void TraceConfig_DataSource::set_producer_name_filter(int index, const std::string& value) {
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.DataSource.producer_name_filter)
producer_name_filter_.Mutable(index)->assign(value);
}
inline void TraceConfig_DataSource::set_producer_name_filter(int index, std::string&& value) {
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.DataSource.producer_name_filter)
producer_name_filter_.Mutable(index)->assign(std::move(value));
}
inline void TraceConfig_DataSource::set_producer_name_filter(int index, const char* value) {
GOOGLE_DCHECK(value != nullptr);
producer_name_filter_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:perfetto.protos.TraceConfig.DataSource.producer_name_filter)
}
inline void TraceConfig_DataSource::set_producer_name_filter(int index, const char* value, size_t size) {
producer_name_filter_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:perfetto.protos.TraceConfig.DataSource.producer_name_filter)
}
inline std::string* TraceConfig_DataSource::add_producer_name_filter() {
// @@protoc_insertion_point(field_add_mutable:perfetto.protos.TraceConfig.DataSource.producer_name_filter)
return producer_name_filter_.Add();
}
inline void TraceConfig_DataSource::add_producer_name_filter(const std::string& value) {
producer_name_filter_.Add()->assign(value);
// @@protoc_insertion_point(field_add:perfetto.protos.TraceConfig.DataSource.producer_name_filter)
}
inline void TraceConfig_DataSource::add_producer_name_filter(std::string&& value) {
producer_name_filter_.Add(std::move(value));
// @@protoc_insertion_point(field_add:perfetto.protos.TraceConfig.DataSource.producer_name_filter)
}
inline void TraceConfig_DataSource::add_producer_name_filter(const char* value) {
GOOGLE_DCHECK(value != nullptr);
producer_name_filter_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:perfetto.protos.TraceConfig.DataSource.producer_name_filter)
}
inline void TraceConfig_DataSource::add_producer_name_filter(const char* value, size_t size) {
producer_name_filter_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:perfetto.protos.TraceConfig.DataSource.producer_name_filter)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>&
TraceConfig_DataSource::producer_name_filter() const {
// @@protoc_insertion_point(field_list:perfetto.protos.TraceConfig.DataSource.producer_name_filter)
return producer_name_filter_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>*
TraceConfig_DataSource::mutable_producer_name_filter() {
// @@protoc_insertion_point(field_mutable_list:perfetto.protos.TraceConfig.DataSource.producer_name_filter)
return &producer_name_filter_;
}
// repeated string producer_name_regex_filter = 3;
inline int TraceConfig_DataSource::producer_name_regex_filter_size() const {
return producer_name_regex_filter_.size();
}
inline void TraceConfig_DataSource::clear_producer_name_regex_filter() {
producer_name_regex_filter_.Clear();
}
inline const std::string& TraceConfig_DataSource::producer_name_regex_filter(int index) const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.DataSource.producer_name_regex_filter)
return producer_name_regex_filter_.Get(index);
}
inline std::string* TraceConfig_DataSource::mutable_producer_name_regex_filter(int index) {
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.DataSource.producer_name_regex_filter)
return producer_name_regex_filter_.Mutable(index);
}
inline void TraceConfig_DataSource::set_producer_name_regex_filter(int index, const std::string& value) {
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.DataSource.producer_name_regex_filter)
producer_name_regex_filter_.Mutable(index)->assign(value);
}
inline void TraceConfig_DataSource::set_producer_name_regex_filter(int index, std::string&& value) {
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.DataSource.producer_name_regex_filter)
producer_name_regex_filter_.Mutable(index)->assign(std::move(value));
}
inline void TraceConfig_DataSource::set_producer_name_regex_filter(int index, const char* value) {
GOOGLE_DCHECK(value != nullptr);
producer_name_regex_filter_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:perfetto.protos.TraceConfig.DataSource.producer_name_regex_filter)
}
inline void TraceConfig_DataSource::set_producer_name_regex_filter(int index, const char* value, size_t size) {
producer_name_regex_filter_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:perfetto.protos.TraceConfig.DataSource.producer_name_regex_filter)
}
inline std::string* TraceConfig_DataSource::add_producer_name_regex_filter() {
// @@protoc_insertion_point(field_add_mutable:perfetto.protos.TraceConfig.DataSource.producer_name_regex_filter)
return producer_name_regex_filter_.Add();
}
inline void TraceConfig_DataSource::add_producer_name_regex_filter(const std::string& value) {
producer_name_regex_filter_.Add()->assign(value);
// @@protoc_insertion_point(field_add:perfetto.protos.TraceConfig.DataSource.producer_name_regex_filter)
}
inline void TraceConfig_DataSource::add_producer_name_regex_filter(std::string&& value) {
producer_name_regex_filter_.Add(std::move(value));
// @@protoc_insertion_point(field_add:perfetto.protos.TraceConfig.DataSource.producer_name_regex_filter)
}
inline void TraceConfig_DataSource::add_producer_name_regex_filter(const char* value) {
GOOGLE_DCHECK(value != nullptr);
producer_name_regex_filter_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:perfetto.protos.TraceConfig.DataSource.producer_name_regex_filter)
}
inline void TraceConfig_DataSource::add_producer_name_regex_filter(const char* value, size_t size) {
producer_name_regex_filter_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:perfetto.protos.TraceConfig.DataSource.producer_name_regex_filter)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>&
TraceConfig_DataSource::producer_name_regex_filter() const {
// @@protoc_insertion_point(field_list:perfetto.protos.TraceConfig.DataSource.producer_name_regex_filter)
return producer_name_regex_filter_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>*
TraceConfig_DataSource::mutable_producer_name_regex_filter() {
// @@protoc_insertion_point(field_mutable_list:perfetto.protos.TraceConfig.DataSource.producer_name_regex_filter)
return &producer_name_regex_filter_;
}
// -------------------------------------------------------------------
// TraceConfig_BuiltinDataSource
// optional bool disable_clock_snapshotting = 1;
inline bool TraceConfig_BuiltinDataSource::has_disable_clock_snapshotting() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void TraceConfig_BuiltinDataSource::clear_disable_clock_snapshotting() {
disable_clock_snapshotting_ = false;
_has_bits_[0] &= ~0x00000001u;
}
inline bool TraceConfig_BuiltinDataSource::disable_clock_snapshotting() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.BuiltinDataSource.disable_clock_snapshotting)
return disable_clock_snapshotting_;
}
inline void TraceConfig_BuiltinDataSource::set_disable_clock_snapshotting(bool value) {
_has_bits_[0] |= 0x00000001u;
disable_clock_snapshotting_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.BuiltinDataSource.disable_clock_snapshotting)
}
// optional bool disable_trace_config = 2;
inline bool TraceConfig_BuiltinDataSource::has_disable_trace_config() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void TraceConfig_BuiltinDataSource::clear_disable_trace_config() {
disable_trace_config_ = false;
_has_bits_[0] &= ~0x00000002u;
}
inline bool TraceConfig_BuiltinDataSource::disable_trace_config() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.BuiltinDataSource.disable_trace_config)
return disable_trace_config_;
}
inline void TraceConfig_BuiltinDataSource::set_disable_trace_config(bool value) {
_has_bits_[0] |= 0x00000002u;
disable_trace_config_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.BuiltinDataSource.disable_trace_config)
}
// optional bool disable_system_info = 3;
inline bool TraceConfig_BuiltinDataSource::has_disable_system_info() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void TraceConfig_BuiltinDataSource::clear_disable_system_info() {
disable_system_info_ = false;
_has_bits_[0] &= ~0x00000004u;
}
inline bool TraceConfig_BuiltinDataSource::disable_system_info() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.BuiltinDataSource.disable_system_info)
return disable_system_info_;
}
inline void TraceConfig_BuiltinDataSource::set_disable_system_info(bool value) {
_has_bits_[0] |= 0x00000004u;
disable_system_info_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.BuiltinDataSource.disable_system_info)
}
// optional bool disable_service_events = 4;
inline bool TraceConfig_BuiltinDataSource::has_disable_service_events() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
inline void TraceConfig_BuiltinDataSource::clear_disable_service_events() {
disable_service_events_ = false;
_has_bits_[0] &= ~0x00000008u;
}
inline bool TraceConfig_BuiltinDataSource::disable_service_events() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.BuiltinDataSource.disable_service_events)
return disable_service_events_;
}
inline void TraceConfig_BuiltinDataSource::set_disable_service_events(bool value) {
_has_bits_[0] |= 0x00000008u;
disable_service_events_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.BuiltinDataSource.disable_service_events)
}
// optional .perfetto.protos.BuiltinClock primary_trace_clock = 5;
inline bool TraceConfig_BuiltinDataSource::has_primary_trace_clock() const {
return (_has_bits_[0] & 0x00000010u) != 0;
}
inline void TraceConfig_BuiltinDataSource::clear_primary_trace_clock() {
primary_trace_clock_ = 0;
_has_bits_[0] &= ~0x00000010u;
}
inline ::perfetto::protos::BuiltinClock TraceConfig_BuiltinDataSource::primary_trace_clock() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.BuiltinDataSource.primary_trace_clock)
return static_cast< ::perfetto::protos::BuiltinClock >(primary_trace_clock_);
}
inline void TraceConfig_BuiltinDataSource::set_primary_trace_clock(::perfetto::protos::BuiltinClock value) {
assert(::perfetto::protos::BuiltinClock_IsValid(value));
_has_bits_[0] |= 0x00000010u;
primary_trace_clock_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.BuiltinDataSource.primary_trace_clock)
}
// optional uint32 snapshot_interval_ms = 6;
inline bool TraceConfig_BuiltinDataSource::has_snapshot_interval_ms() const {
return (_has_bits_[0] & 0x00000020u) != 0;
}
inline void TraceConfig_BuiltinDataSource::clear_snapshot_interval_ms() {
snapshot_interval_ms_ = 0u;
_has_bits_[0] &= ~0x00000020u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 TraceConfig_BuiltinDataSource::snapshot_interval_ms() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.BuiltinDataSource.snapshot_interval_ms)
return snapshot_interval_ms_;
}
inline void TraceConfig_BuiltinDataSource::set_snapshot_interval_ms(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_has_bits_[0] |= 0x00000020u;
snapshot_interval_ms_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.BuiltinDataSource.snapshot_interval_ms)
}
// -------------------------------------------------------------------
// TraceConfig_ProducerConfig
// optional string producer_name = 1;
inline bool TraceConfig_ProducerConfig::has_producer_name() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void TraceConfig_ProducerConfig::clear_producer_name() {
producer_name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& TraceConfig_ProducerConfig::producer_name() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.ProducerConfig.producer_name)
return producer_name_.GetNoArena();
}
inline void TraceConfig_ProducerConfig::set_producer_name(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
producer_name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.ProducerConfig.producer_name)
}
inline void TraceConfig_ProducerConfig::set_producer_name(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
producer_name_.SetNoArena(
&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:perfetto.protos.TraceConfig.ProducerConfig.producer_name)
}
inline void TraceConfig_ProducerConfig::set_producer_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
producer_name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:perfetto.protos.TraceConfig.ProducerConfig.producer_name)
}
inline void TraceConfig_ProducerConfig::set_producer_name(const char* value, size_t size) {
_has_bits_[0] |= 0x00000001u;
producer_name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:perfetto.protos.TraceConfig.ProducerConfig.producer_name)
}
inline std::string* TraceConfig_ProducerConfig::mutable_producer_name() {
_has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.ProducerConfig.producer_name)
return producer_name_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline std::string* TraceConfig_ProducerConfig::release_producer_name() {
// @@protoc_insertion_point(field_release:perfetto.protos.TraceConfig.ProducerConfig.producer_name)
if (!has_producer_name()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return producer_name_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline void TraceConfig_ProducerConfig::set_allocated_producer_name(std::string* producer_name) {
if (producer_name != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
producer_name_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), producer_name);
// @@protoc_insertion_point(field_set_allocated:perfetto.protos.TraceConfig.ProducerConfig.producer_name)
}
// optional uint32 shm_size_kb = 2;
inline bool TraceConfig_ProducerConfig::has_shm_size_kb() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void TraceConfig_ProducerConfig::clear_shm_size_kb() {
shm_size_kb_ = 0u;
_has_bits_[0] &= ~0x00000002u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 TraceConfig_ProducerConfig::shm_size_kb() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.ProducerConfig.shm_size_kb)
return shm_size_kb_;
}
inline void TraceConfig_ProducerConfig::set_shm_size_kb(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_has_bits_[0] |= 0x00000002u;
shm_size_kb_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.ProducerConfig.shm_size_kb)
}
// optional uint32 page_size_kb = 3;
inline bool TraceConfig_ProducerConfig::has_page_size_kb() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void TraceConfig_ProducerConfig::clear_page_size_kb() {
page_size_kb_ = 0u;
_has_bits_[0] &= ~0x00000004u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 TraceConfig_ProducerConfig::page_size_kb() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.ProducerConfig.page_size_kb)
return page_size_kb_;
}
inline void TraceConfig_ProducerConfig::set_page_size_kb(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_has_bits_[0] |= 0x00000004u;
page_size_kb_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.ProducerConfig.page_size_kb)
}
// -------------------------------------------------------------------
// TraceConfig_StatsdMetadata
// optional int64 triggering_alert_id = 1;
inline bool TraceConfig_StatsdMetadata::has_triggering_alert_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void TraceConfig_StatsdMetadata::clear_triggering_alert_id() {
triggering_alert_id_ = PROTOBUF_LONGLONG(0);
_has_bits_[0] &= ~0x00000001u;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 TraceConfig_StatsdMetadata::triggering_alert_id() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.StatsdMetadata.triggering_alert_id)
return triggering_alert_id_;
}
inline void TraceConfig_StatsdMetadata::set_triggering_alert_id(::PROTOBUF_NAMESPACE_ID::int64 value) {
_has_bits_[0] |= 0x00000001u;
triggering_alert_id_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.StatsdMetadata.triggering_alert_id)
}
// optional int32 triggering_config_uid = 2;
inline bool TraceConfig_StatsdMetadata::has_triggering_config_uid() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
inline void TraceConfig_StatsdMetadata::clear_triggering_config_uid() {
triggering_config_uid_ = 0;
_has_bits_[0] &= ~0x00000008u;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 TraceConfig_StatsdMetadata::triggering_config_uid() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.StatsdMetadata.triggering_config_uid)
return triggering_config_uid_;
}
inline void TraceConfig_StatsdMetadata::set_triggering_config_uid(::PROTOBUF_NAMESPACE_ID::int32 value) {
_has_bits_[0] |= 0x00000008u;
triggering_config_uid_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.StatsdMetadata.triggering_config_uid)
}
// optional int64 triggering_config_id = 3;
inline bool TraceConfig_StatsdMetadata::has_triggering_config_id() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void TraceConfig_StatsdMetadata::clear_triggering_config_id() {
triggering_config_id_ = PROTOBUF_LONGLONG(0);
_has_bits_[0] &= ~0x00000002u;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 TraceConfig_StatsdMetadata::triggering_config_id() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.StatsdMetadata.triggering_config_id)
return triggering_config_id_;
}
inline void TraceConfig_StatsdMetadata::set_triggering_config_id(::PROTOBUF_NAMESPACE_ID::int64 value) {
_has_bits_[0] |= 0x00000002u;
triggering_config_id_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.StatsdMetadata.triggering_config_id)
}
// optional int64 triggering_subscription_id = 4;
inline bool TraceConfig_StatsdMetadata::has_triggering_subscription_id() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void TraceConfig_StatsdMetadata::clear_triggering_subscription_id() {
triggering_subscription_id_ = PROTOBUF_LONGLONG(0);
_has_bits_[0] &= ~0x00000004u;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 TraceConfig_StatsdMetadata::triggering_subscription_id() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.StatsdMetadata.triggering_subscription_id)
return triggering_subscription_id_;
}
inline void TraceConfig_StatsdMetadata::set_triggering_subscription_id(::PROTOBUF_NAMESPACE_ID::int64 value) {
_has_bits_[0] |= 0x00000004u;
triggering_subscription_id_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.StatsdMetadata.triggering_subscription_id)
}
// -------------------------------------------------------------------
// TraceConfig_GuardrailOverrides
// optional uint64 max_upload_per_day_bytes = 1;
inline bool TraceConfig_GuardrailOverrides::has_max_upload_per_day_bytes() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void TraceConfig_GuardrailOverrides::clear_max_upload_per_day_bytes() {
max_upload_per_day_bytes_ = PROTOBUF_ULONGLONG(0);
_has_bits_[0] &= ~0x00000001u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 TraceConfig_GuardrailOverrides::max_upload_per_day_bytes() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.GuardrailOverrides.max_upload_per_day_bytes)
return max_upload_per_day_bytes_;
}
inline void TraceConfig_GuardrailOverrides::set_max_upload_per_day_bytes(::PROTOBUF_NAMESPACE_ID::uint64 value) {
_has_bits_[0] |= 0x00000001u;
max_upload_per_day_bytes_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.GuardrailOverrides.max_upload_per_day_bytes)
}
// -------------------------------------------------------------------
// TraceConfig_TriggerConfig_Trigger
// optional string name = 1;
inline bool TraceConfig_TriggerConfig_Trigger::has_name() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void TraceConfig_TriggerConfig_Trigger::clear_name() {
name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& TraceConfig_TriggerConfig_Trigger::name() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.TriggerConfig.Trigger.name)
return name_.GetNoArena();
}
inline void TraceConfig_TriggerConfig_Trigger::set_name(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.TriggerConfig.Trigger.name)
}
inline void TraceConfig_TriggerConfig_Trigger::set_name(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
name_.SetNoArena(
&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:perfetto.protos.TraceConfig.TriggerConfig.Trigger.name)
}
inline void TraceConfig_TriggerConfig_Trigger::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:perfetto.protos.TraceConfig.TriggerConfig.Trigger.name)
}
inline void TraceConfig_TriggerConfig_Trigger::set_name(const char* value, size_t size) {
_has_bits_[0] |= 0x00000001u;
name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:perfetto.protos.TraceConfig.TriggerConfig.Trigger.name)
}
inline std::string* TraceConfig_TriggerConfig_Trigger::mutable_name() {
_has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.TriggerConfig.Trigger.name)
return name_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline std::string* TraceConfig_TriggerConfig_Trigger::release_name() {
// @@protoc_insertion_point(field_release:perfetto.protos.TraceConfig.TriggerConfig.Trigger.name)
if (!has_name()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return name_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline void TraceConfig_TriggerConfig_Trigger::set_allocated_name(std::string* name) {
if (name != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name);
// @@protoc_insertion_point(field_set_allocated:perfetto.protos.TraceConfig.TriggerConfig.Trigger.name)
}
// optional string producer_name_regex = 2;
inline bool TraceConfig_TriggerConfig_Trigger::has_producer_name_regex() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void TraceConfig_TriggerConfig_Trigger::clear_producer_name_regex() {
producer_name_regex_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& TraceConfig_TriggerConfig_Trigger::producer_name_regex() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.TriggerConfig.Trigger.producer_name_regex)
return producer_name_regex_.GetNoArena();
}
inline void TraceConfig_TriggerConfig_Trigger::set_producer_name_regex(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
producer_name_regex_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.TriggerConfig.Trigger.producer_name_regex)
}
inline void TraceConfig_TriggerConfig_Trigger::set_producer_name_regex(std::string&& value) {
_has_bits_[0] |= 0x00000002u;
producer_name_regex_.SetNoArena(
&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:perfetto.protos.TraceConfig.TriggerConfig.Trigger.producer_name_regex)
}
inline void TraceConfig_TriggerConfig_Trigger::set_producer_name_regex(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000002u;
producer_name_regex_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:perfetto.protos.TraceConfig.TriggerConfig.Trigger.producer_name_regex)
}
inline void TraceConfig_TriggerConfig_Trigger::set_producer_name_regex(const char* value, size_t size) {
_has_bits_[0] |= 0x00000002u;
producer_name_regex_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:perfetto.protos.TraceConfig.TriggerConfig.Trigger.producer_name_regex)
}
inline std::string* TraceConfig_TriggerConfig_Trigger::mutable_producer_name_regex() {
_has_bits_[0] |= 0x00000002u;
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.TriggerConfig.Trigger.producer_name_regex)
return producer_name_regex_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline std::string* TraceConfig_TriggerConfig_Trigger::release_producer_name_regex() {
// @@protoc_insertion_point(field_release:perfetto.protos.TraceConfig.TriggerConfig.Trigger.producer_name_regex)
if (!has_producer_name_regex()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
return producer_name_regex_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline void TraceConfig_TriggerConfig_Trigger::set_allocated_producer_name_regex(std::string* producer_name_regex) {
if (producer_name_regex != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
producer_name_regex_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), producer_name_regex);
// @@protoc_insertion_point(field_set_allocated:perfetto.protos.TraceConfig.TriggerConfig.Trigger.producer_name_regex)
}
// optional uint32 stop_delay_ms = 3;
inline bool TraceConfig_TriggerConfig_Trigger::has_stop_delay_ms() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void TraceConfig_TriggerConfig_Trigger::clear_stop_delay_ms() {
stop_delay_ms_ = 0u;
_has_bits_[0] &= ~0x00000004u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 TraceConfig_TriggerConfig_Trigger::stop_delay_ms() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.TriggerConfig.Trigger.stop_delay_ms)
return stop_delay_ms_;
}
inline void TraceConfig_TriggerConfig_Trigger::set_stop_delay_ms(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_has_bits_[0] |= 0x00000004u;
stop_delay_ms_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.TriggerConfig.Trigger.stop_delay_ms)
}
// optional uint32 max_per_24_h = 4;
inline bool TraceConfig_TriggerConfig_Trigger::has_max_per_24_h() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
inline void TraceConfig_TriggerConfig_Trigger::clear_max_per_24_h() {
max_per_24_h_ = 0u;
_has_bits_[0] &= ~0x00000008u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 TraceConfig_TriggerConfig_Trigger::max_per_24_h() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.TriggerConfig.Trigger.max_per_24_h)
return max_per_24_h_;
}
inline void TraceConfig_TriggerConfig_Trigger::set_max_per_24_h(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_has_bits_[0] |= 0x00000008u;
max_per_24_h_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.TriggerConfig.Trigger.max_per_24_h)
}
// optional double skip_probability = 5;
inline bool TraceConfig_TriggerConfig_Trigger::has_skip_probability() const {
return (_has_bits_[0] & 0x00000010u) != 0;
}
inline void TraceConfig_TriggerConfig_Trigger::clear_skip_probability() {
skip_probability_ = 0;
_has_bits_[0] &= ~0x00000010u;
}
inline double TraceConfig_TriggerConfig_Trigger::skip_probability() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.TriggerConfig.Trigger.skip_probability)
return skip_probability_;
}
inline void TraceConfig_TriggerConfig_Trigger::set_skip_probability(double value) {
_has_bits_[0] |= 0x00000010u;
skip_probability_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.TriggerConfig.Trigger.skip_probability)
}
// -------------------------------------------------------------------
// TraceConfig_TriggerConfig
// optional .perfetto.protos.TraceConfig.TriggerConfig.TriggerMode trigger_mode = 1;
inline bool TraceConfig_TriggerConfig::has_trigger_mode() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void TraceConfig_TriggerConfig::clear_trigger_mode() {
trigger_mode_ = 0;
_has_bits_[0] &= ~0x00000001u;
}
inline ::perfetto::protos::TraceConfig_TriggerConfig_TriggerMode TraceConfig_TriggerConfig::trigger_mode() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.TriggerConfig.trigger_mode)
return static_cast< ::perfetto::protos::TraceConfig_TriggerConfig_TriggerMode >(trigger_mode_);
}
inline void TraceConfig_TriggerConfig::set_trigger_mode(::perfetto::protos::TraceConfig_TriggerConfig_TriggerMode value) {
assert(::perfetto::protos::TraceConfig_TriggerConfig_TriggerMode_IsValid(value));
_has_bits_[0] |= 0x00000001u;
trigger_mode_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.TriggerConfig.trigger_mode)
}
// repeated .perfetto.protos.TraceConfig.TriggerConfig.Trigger triggers = 2;
inline int TraceConfig_TriggerConfig::triggers_size() const {
return triggers_.size();
}
inline void TraceConfig_TriggerConfig::clear_triggers() {
triggers_.Clear();
}
inline ::perfetto::protos::TraceConfig_TriggerConfig_Trigger* TraceConfig_TriggerConfig::mutable_triggers(int index) {
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.TriggerConfig.triggers)
return triggers_.Mutable(index);
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_TriggerConfig_Trigger >*
TraceConfig_TriggerConfig::mutable_triggers() {
// @@protoc_insertion_point(field_mutable_list:perfetto.protos.TraceConfig.TriggerConfig.triggers)
return &triggers_;
}
inline const ::perfetto::protos::TraceConfig_TriggerConfig_Trigger& TraceConfig_TriggerConfig::triggers(int index) const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.TriggerConfig.triggers)
return triggers_.Get(index);
}
inline ::perfetto::protos::TraceConfig_TriggerConfig_Trigger* TraceConfig_TriggerConfig::add_triggers() {
// @@protoc_insertion_point(field_add:perfetto.protos.TraceConfig.TriggerConfig.triggers)
return triggers_.Add();
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_TriggerConfig_Trigger >&
TraceConfig_TriggerConfig::triggers() const {
// @@protoc_insertion_point(field_list:perfetto.protos.TraceConfig.TriggerConfig.triggers)
return triggers_;
}
// optional uint32 trigger_timeout_ms = 3;
inline bool TraceConfig_TriggerConfig::has_trigger_timeout_ms() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void TraceConfig_TriggerConfig::clear_trigger_timeout_ms() {
trigger_timeout_ms_ = 0u;
_has_bits_[0] &= ~0x00000002u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 TraceConfig_TriggerConfig::trigger_timeout_ms() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.TriggerConfig.trigger_timeout_ms)
return trigger_timeout_ms_;
}
inline void TraceConfig_TriggerConfig::set_trigger_timeout_ms(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_has_bits_[0] |= 0x00000002u;
trigger_timeout_ms_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.TriggerConfig.trigger_timeout_ms)
}
// -------------------------------------------------------------------
// TraceConfig_IncrementalStateConfig
// optional uint32 clear_period_ms = 1;
inline bool TraceConfig_IncrementalStateConfig::has_clear_period_ms() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void TraceConfig_IncrementalStateConfig::clear_clear_period_ms() {
clear_period_ms_ = 0u;
_has_bits_[0] &= ~0x00000001u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 TraceConfig_IncrementalStateConfig::clear_period_ms() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.IncrementalStateConfig.clear_period_ms)
return clear_period_ms_;
}
inline void TraceConfig_IncrementalStateConfig::set_clear_period_ms(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_has_bits_[0] |= 0x00000001u;
clear_period_ms_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.IncrementalStateConfig.clear_period_ms)
}
// -------------------------------------------------------------------
// TraceConfig_IncidentReportConfig
// optional string destination_package = 1;
inline bool TraceConfig_IncidentReportConfig::has_destination_package() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void TraceConfig_IncidentReportConfig::clear_destination_package() {
destination_package_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& TraceConfig_IncidentReportConfig::destination_package() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.IncidentReportConfig.destination_package)
return destination_package_.GetNoArena();
}
inline void TraceConfig_IncidentReportConfig::set_destination_package(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
destination_package_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.IncidentReportConfig.destination_package)
}
inline void TraceConfig_IncidentReportConfig::set_destination_package(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
destination_package_.SetNoArena(
&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:perfetto.protos.TraceConfig.IncidentReportConfig.destination_package)
}
inline void TraceConfig_IncidentReportConfig::set_destination_package(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
destination_package_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:perfetto.protos.TraceConfig.IncidentReportConfig.destination_package)
}
inline void TraceConfig_IncidentReportConfig::set_destination_package(const char* value, size_t size) {
_has_bits_[0] |= 0x00000001u;
destination_package_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:perfetto.protos.TraceConfig.IncidentReportConfig.destination_package)
}
inline std::string* TraceConfig_IncidentReportConfig::mutable_destination_package() {
_has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.IncidentReportConfig.destination_package)
return destination_package_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline std::string* TraceConfig_IncidentReportConfig::release_destination_package() {
// @@protoc_insertion_point(field_release:perfetto.protos.TraceConfig.IncidentReportConfig.destination_package)
if (!has_destination_package()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return destination_package_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline void TraceConfig_IncidentReportConfig::set_allocated_destination_package(std::string* destination_package) {
if (destination_package != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
destination_package_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), destination_package);
// @@protoc_insertion_point(field_set_allocated:perfetto.protos.TraceConfig.IncidentReportConfig.destination_package)
}
// optional string destination_class = 2;
inline bool TraceConfig_IncidentReportConfig::has_destination_class() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void TraceConfig_IncidentReportConfig::clear_destination_class() {
destination_class_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& TraceConfig_IncidentReportConfig::destination_class() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.IncidentReportConfig.destination_class)
return destination_class_.GetNoArena();
}
inline void TraceConfig_IncidentReportConfig::set_destination_class(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
destination_class_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.IncidentReportConfig.destination_class)
}
inline void TraceConfig_IncidentReportConfig::set_destination_class(std::string&& value) {
_has_bits_[0] |= 0x00000002u;
destination_class_.SetNoArena(
&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:perfetto.protos.TraceConfig.IncidentReportConfig.destination_class)
}
inline void TraceConfig_IncidentReportConfig::set_destination_class(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000002u;
destination_class_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:perfetto.protos.TraceConfig.IncidentReportConfig.destination_class)
}
inline void TraceConfig_IncidentReportConfig::set_destination_class(const char* value, size_t size) {
_has_bits_[0] |= 0x00000002u;
destination_class_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:perfetto.protos.TraceConfig.IncidentReportConfig.destination_class)
}
inline std::string* TraceConfig_IncidentReportConfig::mutable_destination_class() {
_has_bits_[0] |= 0x00000002u;
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.IncidentReportConfig.destination_class)
return destination_class_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline std::string* TraceConfig_IncidentReportConfig::release_destination_class() {
// @@protoc_insertion_point(field_release:perfetto.protos.TraceConfig.IncidentReportConfig.destination_class)
if (!has_destination_class()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
return destination_class_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline void TraceConfig_IncidentReportConfig::set_allocated_destination_class(std::string* destination_class) {
if (destination_class != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
destination_class_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), destination_class);
// @@protoc_insertion_point(field_set_allocated:perfetto.protos.TraceConfig.IncidentReportConfig.destination_class)
}
// optional int32 privacy_level = 3;
inline bool TraceConfig_IncidentReportConfig::has_privacy_level() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void TraceConfig_IncidentReportConfig::clear_privacy_level() {
privacy_level_ = 0;
_has_bits_[0] &= ~0x00000004u;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 TraceConfig_IncidentReportConfig::privacy_level() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.IncidentReportConfig.privacy_level)
return privacy_level_;
}
inline void TraceConfig_IncidentReportConfig::set_privacy_level(::PROTOBUF_NAMESPACE_ID::int32 value) {
_has_bits_[0] |= 0x00000004u;
privacy_level_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.IncidentReportConfig.privacy_level)
}
// optional bool skip_dropbox = 4;
inline bool TraceConfig_IncidentReportConfig::has_skip_dropbox() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
inline void TraceConfig_IncidentReportConfig::clear_skip_dropbox() {
skip_dropbox_ = false;
_has_bits_[0] &= ~0x00000008u;
}
inline bool TraceConfig_IncidentReportConfig::skip_dropbox() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.IncidentReportConfig.skip_dropbox)
return skip_dropbox_;
}
inline void TraceConfig_IncidentReportConfig::set_skip_dropbox(bool value) {
_has_bits_[0] |= 0x00000008u;
skip_dropbox_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.IncidentReportConfig.skip_dropbox)
}
// -------------------------------------------------------------------
// TraceConfig
// repeated .perfetto.protos.TraceConfig.BufferConfig buffers = 1;
inline int TraceConfig::buffers_size() const {
return buffers_.size();
}
inline void TraceConfig::clear_buffers() {
buffers_.Clear();
}
inline ::perfetto::protos::TraceConfig_BufferConfig* TraceConfig::mutable_buffers(int index) {
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.buffers)
return buffers_.Mutable(index);
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_BufferConfig >*
TraceConfig::mutable_buffers() {
// @@protoc_insertion_point(field_mutable_list:perfetto.protos.TraceConfig.buffers)
return &buffers_;
}
inline const ::perfetto::protos::TraceConfig_BufferConfig& TraceConfig::buffers(int index) const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.buffers)
return buffers_.Get(index);
}
inline ::perfetto::protos::TraceConfig_BufferConfig* TraceConfig::add_buffers() {
// @@protoc_insertion_point(field_add:perfetto.protos.TraceConfig.buffers)
return buffers_.Add();
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_BufferConfig >&
TraceConfig::buffers() const {
// @@protoc_insertion_point(field_list:perfetto.protos.TraceConfig.buffers)
return buffers_;
}
// repeated .perfetto.protos.TraceConfig.DataSource data_sources = 2;
inline int TraceConfig::data_sources_size() const {
return data_sources_.size();
}
inline void TraceConfig::clear_data_sources() {
data_sources_.Clear();
}
inline ::perfetto::protos::TraceConfig_DataSource* TraceConfig::mutable_data_sources(int index) {
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.data_sources)
return data_sources_.Mutable(index);
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_DataSource >*
TraceConfig::mutable_data_sources() {
// @@protoc_insertion_point(field_mutable_list:perfetto.protos.TraceConfig.data_sources)
return &data_sources_;
}
inline const ::perfetto::protos::TraceConfig_DataSource& TraceConfig::data_sources(int index) const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.data_sources)
return data_sources_.Get(index);
}
inline ::perfetto::protos::TraceConfig_DataSource* TraceConfig::add_data_sources() {
// @@protoc_insertion_point(field_add:perfetto.protos.TraceConfig.data_sources)
return data_sources_.Add();
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_DataSource >&
TraceConfig::data_sources() const {
// @@protoc_insertion_point(field_list:perfetto.protos.TraceConfig.data_sources)
return data_sources_;
}
// optional .perfetto.protos.TraceConfig.BuiltinDataSource builtin_data_sources = 20;
inline bool TraceConfig::has_builtin_data_sources() const {
return (_has_bits_[0] & 0x00000020u) != 0;
}
inline void TraceConfig::clear_builtin_data_sources() {
if (builtin_data_sources_ != nullptr) builtin_data_sources_->Clear();
_has_bits_[0] &= ~0x00000020u;
}
inline const ::perfetto::protos::TraceConfig_BuiltinDataSource& TraceConfig::builtin_data_sources() const {
const ::perfetto::protos::TraceConfig_BuiltinDataSource* p = builtin_data_sources_;
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.builtin_data_sources)
return p != nullptr ? *p : *reinterpret_cast<const ::perfetto::protos::TraceConfig_BuiltinDataSource*>(
&::perfetto::protos::_TraceConfig_BuiltinDataSource_default_instance_);
}
inline ::perfetto::protos::TraceConfig_BuiltinDataSource* TraceConfig::release_builtin_data_sources() {
// @@protoc_insertion_point(field_release:perfetto.protos.TraceConfig.builtin_data_sources)
_has_bits_[0] &= ~0x00000020u;
::perfetto::protos::TraceConfig_BuiltinDataSource* temp = builtin_data_sources_;
builtin_data_sources_ = nullptr;
return temp;
}
inline ::perfetto::protos::TraceConfig_BuiltinDataSource* TraceConfig::mutable_builtin_data_sources() {
_has_bits_[0] |= 0x00000020u;
if (builtin_data_sources_ == nullptr) {
auto* p = CreateMaybeMessage<::perfetto::protos::TraceConfig_BuiltinDataSource>(GetArenaNoVirtual());
builtin_data_sources_ = p;
}
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.builtin_data_sources)
return builtin_data_sources_;
}
inline void TraceConfig::set_allocated_builtin_data_sources(::perfetto::protos::TraceConfig_BuiltinDataSource* builtin_data_sources) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == nullptr) {
delete builtin_data_sources_;
}
if (builtin_data_sources) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
builtin_data_sources = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, builtin_data_sources, submessage_arena);
}
_has_bits_[0] |= 0x00000020u;
} else {
_has_bits_[0] &= ~0x00000020u;
}
builtin_data_sources_ = builtin_data_sources;
// @@protoc_insertion_point(field_set_allocated:perfetto.protos.TraceConfig.builtin_data_sources)
}
// optional uint32 duration_ms = 3;
inline bool TraceConfig::has_duration_ms() const {
return (_has_bits_[0] & 0x00000100u) != 0;
}
inline void TraceConfig::clear_duration_ms() {
duration_ms_ = 0u;
_has_bits_[0] &= ~0x00000100u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 TraceConfig::duration_ms() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.duration_ms)
return duration_ms_;
}
inline void TraceConfig::set_duration_ms(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_has_bits_[0] |= 0x00000100u;
duration_ms_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.duration_ms)
}
// optional bool enable_extra_guardrails = 4;
inline bool TraceConfig::has_enable_extra_guardrails() const {
return (_has_bits_[0] & 0x00000800u) != 0;
}
inline void TraceConfig::clear_enable_extra_guardrails() {
enable_extra_guardrails_ = false;
_has_bits_[0] &= ~0x00000800u;
}
inline bool TraceConfig::enable_extra_guardrails() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.enable_extra_guardrails)
return enable_extra_guardrails_;
}
inline void TraceConfig::set_enable_extra_guardrails(bool value) {
_has_bits_[0] |= 0x00000800u;
enable_extra_guardrails_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.enable_extra_guardrails)
}
// optional .perfetto.protos.TraceConfig.LockdownModeOperation lockdown_mode = 5;
inline bool TraceConfig::has_lockdown_mode() const {
return (_has_bits_[0] & 0x00000200u) != 0;
}
inline void TraceConfig::clear_lockdown_mode() {
lockdown_mode_ = 0;
_has_bits_[0] &= ~0x00000200u;
}
inline ::perfetto::protos::TraceConfig_LockdownModeOperation TraceConfig::lockdown_mode() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.lockdown_mode)
return static_cast< ::perfetto::protos::TraceConfig_LockdownModeOperation >(lockdown_mode_);
}
inline void TraceConfig::set_lockdown_mode(::perfetto::protos::TraceConfig_LockdownModeOperation value) {
assert(::perfetto::protos::TraceConfig_LockdownModeOperation_IsValid(value));
_has_bits_[0] |= 0x00000200u;
lockdown_mode_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.lockdown_mode)
}
// repeated .perfetto.protos.TraceConfig.ProducerConfig producers = 6;
inline int TraceConfig::producers_size() const {
return producers_.size();
}
inline void TraceConfig::clear_producers() {
producers_.Clear();
}
inline ::perfetto::protos::TraceConfig_ProducerConfig* TraceConfig::mutable_producers(int index) {
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.producers)
return producers_.Mutable(index);
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_ProducerConfig >*
TraceConfig::mutable_producers() {
// @@protoc_insertion_point(field_mutable_list:perfetto.protos.TraceConfig.producers)
return &producers_;
}
inline const ::perfetto::protos::TraceConfig_ProducerConfig& TraceConfig::producers(int index) const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.producers)
return producers_.Get(index);
}
inline ::perfetto::protos::TraceConfig_ProducerConfig* TraceConfig::add_producers() {
// @@protoc_insertion_point(field_add:perfetto.protos.TraceConfig.producers)
return producers_.Add();
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::perfetto::protos::TraceConfig_ProducerConfig >&
TraceConfig::producers() const {
// @@protoc_insertion_point(field_list:perfetto.protos.TraceConfig.producers)
return producers_;
}
// optional .perfetto.protos.TraceConfig.StatsdMetadata statsd_metadata = 7;
inline bool TraceConfig::has_statsd_metadata() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void TraceConfig::clear_statsd_metadata() {
if (statsd_metadata_ != nullptr) statsd_metadata_->Clear();
_has_bits_[0] &= ~0x00000004u;
}
inline const ::perfetto::protos::TraceConfig_StatsdMetadata& TraceConfig::statsd_metadata() const {
const ::perfetto::protos::TraceConfig_StatsdMetadata* p = statsd_metadata_;
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.statsd_metadata)
return p != nullptr ? *p : *reinterpret_cast<const ::perfetto::protos::TraceConfig_StatsdMetadata*>(
&::perfetto::protos::_TraceConfig_StatsdMetadata_default_instance_);
}
inline ::perfetto::protos::TraceConfig_StatsdMetadata* TraceConfig::release_statsd_metadata() {
// @@protoc_insertion_point(field_release:perfetto.protos.TraceConfig.statsd_metadata)
_has_bits_[0] &= ~0x00000004u;
::perfetto::protos::TraceConfig_StatsdMetadata* temp = statsd_metadata_;
statsd_metadata_ = nullptr;
return temp;
}
inline ::perfetto::protos::TraceConfig_StatsdMetadata* TraceConfig::mutable_statsd_metadata() {
_has_bits_[0] |= 0x00000004u;
if (statsd_metadata_ == nullptr) {
auto* p = CreateMaybeMessage<::perfetto::protos::TraceConfig_StatsdMetadata>(GetArenaNoVirtual());
statsd_metadata_ = p;
}
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.statsd_metadata)
return statsd_metadata_;
}
inline void TraceConfig::set_allocated_statsd_metadata(::perfetto::protos::TraceConfig_StatsdMetadata* statsd_metadata) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == nullptr) {
delete statsd_metadata_;
}
if (statsd_metadata) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
statsd_metadata = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, statsd_metadata, submessage_arena);
}
_has_bits_[0] |= 0x00000004u;
} else {
_has_bits_[0] &= ~0x00000004u;
}
statsd_metadata_ = statsd_metadata;
// @@protoc_insertion_point(field_set_allocated:perfetto.protos.TraceConfig.statsd_metadata)
}
// optional bool write_into_file = 8;
inline bool TraceConfig::has_write_into_file() const {
return (_has_bits_[0] & 0x00001000u) != 0;
}
inline void TraceConfig::clear_write_into_file() {
write_into_file_ = false;
_has_bits_[0] &= ~0x00001000u;
}
inline bool TraceConfig::write_into_file() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.write_into_file)
return write_into_file_;
}
inline void TraceConfig::set_write_into_file(bool value) {
_has_bits_[0] |= 0x00001000u;
write_into_file_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.write_into_file)
}
// optional string output_path = 29;
inline bool TraceConfig::has_output_path() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void TraceConfig::clear_output_path() {
output_path_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& TraceConfig::output_path() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.output_path)
return output_path_.GetNoArena();
}
inline void TraceConfig::set_output_path(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
output_path_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.output_path)
}
inline void TraceConfig::set_output_path(std::string&& value) {
_has_bits_[0] |= 0x00000002u;
output_path_.SetNoArena(
&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:perfetto.protos.TraceConfig.output_path)
}
inline void TraceConfig::set_output_path(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000002u;
output_path_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:perfetto.protos.TraceConfig.output_path)
}
inline void TraceConfig::set_output_path(const char* value, size_t size) {
_has_bits_[0] |= 0x00000002u;
output_path_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:perfetto.protos.TraceConfig.output_path)
}
inline std::string* TraceConfig::mutable_output_path() {
_has_bits_[0] |= 0x00000002u;
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.output_path)
return output_path_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline std::string* TraceConfig::release_output_path() {
// @@protoc_insertion_point(field_release:perfetto.protos.TraceConfig.output_path)
if (!has_output_path()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
return output_path_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline void TraceConfig::set_allocated_output_path(std::string* output_path) {
if (output_path != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
output_path_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), output_path);
// @@protoc_insertion_point(field_set_allocated:perfetto.protos.TraceConfig.output_path)
}
// optional uint32 file_write_period_ms = 9;
inline bool TraceConfig::has_file_write_period_ms() const {
return (_has_bits_[0] & 0x00000400u) != 0;
}
inline void TraceConfig::clear_file_write_period_ms() {
file_write_period_ms_ = 0u;
_has_bits_[0] &= ~0x00000400u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 TraceConfig::file_write_period_ms() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.file_write_period_ms)
return file_write_period_ms_;
}
inline void TraceConfig::set_file_write_period_ms(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_has_bits_[0] |= 0x00000400u;
file_write_period_ms_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.file_write_period_ms)
}
// optional uint64 max_file_size_bytes = 10;
inline bool TraceConfig::has_max_file_size_bytes() const {
return (_has_bits_[0] & 0x00008000u) != 0;
}
inline void TraceConfig::clear_max_file_size_bytes() {
max_file_size_bytes_ = PROTOBUF_ULONGLONG(0);
_has_bits_[0] &= ~0x00008000u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 TraceConfig::max_file_size_bytes() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.max_file_size_bytes)
return max_file_size_bytes_;
}
inline void TraceConfig::set_max_file_size_bytes(::PROTOBUF_NAMESPACE_ID::uint64 value) {
_has_bits_[0] |= 0x00008000u;
max_file_size_bytes_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.max_file_size_bytes)
}
// optional .perfetto.protos.TraceConfig.GuardrailOverrides guardrail_overrides = 11;
inline bool TraceConfig::has_guardrail_overrides() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
inline void TraceConfig::clear_guardrail_overrides() {
if (guardrail_overrides_ != nullptr) guardrail_overrides_->Clear();
_has_bits_[0] &= ~0x00000008u;
}
inline const ::perfetto::protos::TraceConfig_GuardrailOverrides& TraceConfig::guardrail_overrides() const {
const ::perfetto::protos::TraceConfig_GuardrailOverrides* p = guardrail_overrides_;
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.guardrail_overrides)
return p != nullptr ? *p : *reinterpret_cast<const ::perfetto::protos::TraceConfig_GuardrailOverrides*>(
&::perfetto::protos::_TraceConfig_GuardrailOverrides_default_instance_);
}
inline ::perfetto::protos::TraceConfig_GuardrailOverrides* TraceConfig::release_guardrail_overrides() {
// @@protoc_insertion_point(field_release:perfetto.protos.TraceConfig.guardrail_overrides)
_has_bits_[0] &= ~0x00000008u;
::perfetto::protos::TraceConfig_GuardrailOverrides* temp = guardrail_overrides_;
guardrail_overrides_ = nullptr;
return temp;
}
inline ::perfetto::protos::TraceConfig_GuardrailOverrides* TraceConfig::mutable_guardrail_overrides() {
_has_bits_[0] |= 0x00000008u;
if (guardrail_overrides_ == nullptr) {
auto* p = CreateMaybeMessage<::perfetto::protos::TraceConfig_GuardrailOverrides>(GetArenaNoVirtual());
guardrail_overrides_ = p;
}
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.guardrail_overrides)
return guardrail_overrides_;
}
inline void TraceConfig::set_allocated_guardrail_overrides(::perfetto::protos::TraceConfig_GuardrailOverrides* guardrail_overrides) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == nullptr) {
delete guardrail_overrides_;
}
if (guardrail_overrides) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
guardrail_overrides = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, guardrail_overrides, submessage_arena);
}
_has_bits_[0] |= 0x00000008u;
} else {
_has_bits_[0] &= ~0x00000008u;
}
guardrail_overrides_ = guardrail_overrides;
// @@protoc_insertion_point(field_set_allocated:perfetto.protos.TraceConfig.guardrail_overrides)
}
// optional bool deferred_start = 12;
inline bool TraceConfig::has_deferred_start() const {
return (_has_bits_[0] & 0x00002000u) != 0;
}
inline void TraceConfig::clear_deferred_start() {
deferred_start_ = false;
_has_bits_[0] &= ~0x00002000u;
}
inline bool TraceConfig::deferred_start() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.deferred_start)
return deferred_start_;
}
inline void TraceConfig::set_deferred_start(bool value) {
_has_bits_[0] |= 0x00002000u;
deferred_start_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.deferred_start)
}
// optional uint32 flush_period_ms = 13;
inline bool TraceConfig::has_flush_period_ms() const {
return (_has_bits_[0] & 0x00010000u) != 0;
}
inline void TraceConfig::clear_flush_period_ms() {
flush_period_ms_ = 0u;
_has_bits_[0] &= ~0x00010000u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 TraceConfig::flush_period_ms() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.flush_period_ms)
return flush_period_ms_;
}
inline void TraceConfig::set_flush_period_ms(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_has_bits_[0] |= 0x00010000u;
flush_period_ms_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.flush_period_ms)
}
// optional uint32 flush_timeout_ms = 14;
inline bool TraceConfig::has_flush_timeout_ms() const {
return (_has_bits_[0] & 0x00020000u) != 0;
}
inline void TraceConfig::clear_flush_timeout_ms() {
flush_timeout_ms_ = 0u;
_has_bits_[0] &= ~0x00020000u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 TraceConfig::flush_timeout_ms() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.flush_timeout_ms)
return flush_timeout_ms_;
}
inline void TraceConfig::set_flush_timeout_ms(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_has_bits_[0] |= 0x00020000u;
flush_timeout_ms_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.flush_timeout_ms)
}
// optional uint32 data_source_stop_timeout_ms = 23;
inline bool TraceConfig::has_data_source_stop_timeout_ms() const {
return (_has_bits_[0] & 0x00080000u) != 0;
}
inline void TraceConfig::clear_data_source_stop_timeout_ms() {
data_source_stop_timeout_ms_ = 0u;
_has_bits_[0] &= ~0x00080000u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 TraceConfig::data_source_stop_timeout_ms() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.data_source_stop_timeout_ms)
return data_source_stop_timeout_ms_;
}
inline void TraceConfig::set_data_source_stop_timeout_ms(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_has_bits_[0] |= 0x00080000u;
data_source_stop_timeout_ms_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.data_source_stop_timeout_ms)
}
// optional bool notify_traceur = 16;
inline bool TraceConfig::has_notify_traceur() const {
return (_has_bits_[0] & 0x00004000u) != 0;
}
inline void TraceConfig::clear_notify_traceur() {
notify_traceur_ = false;
_has_bits_[0] &= ~0x00004000u;
}
inline bool TraceConfig::notify_traceur() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.notify_traceur)
return notify_traceur_;
}
inline void TraceConfig::set_notify_traceur(bool value) {
_has_bits_[0] |= 0x00004000u;
notify_traceur_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.notify_traceur)
}
// optional int32 bugreport_score = 30;
inline bool TraceConfig::has_bugreport_score() const {
return (_has_bits_[0] & 0x00400000u) != 0;
}
inline void TraceConfig::clear_bugreport_score() {
bugreport_score_ = 0;
_has_bits_[0] &= ~0x00400000u;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 TraceConfig::bugreport_score() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.bugreport_score)
return bugreport_score_;
}
inline void TraceConfig::set_bugreport_score(::PROTOBUF_NAMESPACE_ID::int32 value) {
_has_bits_[0] |= 0x00400000u;
bugreport_score_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.bugreport_score)
}
// optional .perfetto.protos.TraceConfig.TriggerConfig trigger_config = 17;
inline bool TraceConfig::has_trigger_config() const {
return (_has_bits_[0] & 0x00000010u) != 0;
}
inline void TraceConfig::clear_trigger_config() {
if (trigger_config_ != nullptr) trigger_config_->Clear();
_has_bits_[0] &= ~0x00000010u;
}
inline const ::perfetto::protos::TraceConfig_TriggerConfig& TraceConfig::trigger_config() const {
const ::perfetto::protos::TraceConfig_TriggerConfig* p = trigger_config_;
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.trigger_config)
return p != nullptr ? *p : *reinterpret_cast<const ::perfetto::protos::TraceConfig_TriggerConfig*>(
&::perfetto::protos::_TraceConfig_TriggerConfig_default_instance_);
}
inline ::perfetto::protos::TraceConfig_TriggerConfig* TraceConfig::release_trigger_config() {
// @@protoc_insertion_point(field_release:perfetto.protos.TraceConfig.trigger_config)
_has_bits_[0] &= ~0x00000010u;
::perfetto::protos::TraceConfig_TriggerConfig* temp = trigger_config_;
trigger_config_ = nullptr;
return temp;
}
inline ::perfetto::protos::TraceConfig_TriggerConfig* TraceConfig::mutable_trigger_config() {
_has_bits_[0] |= 0x00000010u;
if (trigger_config_ == nullptr) {
auto* p = CreateMaybeMessage<::perfetto::protos::TraceConfig_TriggerConfig>(GetArenaNoVirtual());
trigger_config_ = p;
}
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.trigger_config)
return trigger_config_;
}
inline void TraceConfig::set_allocated_trigger_config(::perfetto::protos::TraceConfig_TriggerConfig* trigger_config) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == nullptr) {
delete trigger_config_;
}
if (trigger_config) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
trigger_config = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, trigger_config, submessage_arena);
}
_has_bits_[0] |= 0x00000010u;
} else {
_has_bits_[0] &= ~0x00000010u;
}
trigger_config_ = trigger_config;
// @@protoc_insertion_point(field_set_allocated:perfetto.protos.TraceConfig.trigger_config)
}
// repeated string activate_triggers = 18;
inline int TraceConfig::activate_triggers_size() const {
return activate_triggers_.size();
}
inline void TraceConfig::clear_activate_triggers() {
activate_triggers_.Clear();
}
inline const std::string& TraceConfig::activate_triggers(int index) const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.activate_triggers)
return activate_triggers_.Get(index);
}
inline std::string* TraceConfig::mutable_activate_triggers(int index) {
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.activate_triggers)
return activate_triggers_.Mutable(index);
}
inline void TraceConfig::set_activate_triggers(int index, const std::string& value) {
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.activate_triggers)
activate_triggers_.Mutable(index)->assign(value);
}
inline void TraceConfig::set_activate_triggers(int index, std::string&& value) {
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.activate_triggers)
activate_triggers_.Mutable(index)->assign(std::move(value));
}
inline void TraceConfig::set_activate_triggers(int index, const char* value) {
GOOGLE_DCHECK(value != nullptr);
activate_triggers_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:perfetto.protos.TraceConfig.activate_triggers)
}
inline void TraceConfig::set_activate_triggers(int index, const char* value, size_t size) {
activate_triggers_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:perfetto.protos.TraceConfig.activate_triggers)
}
inline std::string* TraceConfig::add_activate_triggers() {
// @@protoc_insertion_point(field_add_mutable:perfetto.protos.TraceConfig.activate_triggers)
return activate_triggers_.Add();
}
inline void TraceConfig::add_activate_triggers(const std::string& value) {
activate_triggers_.Add()->assign(value);
// @@protoc_insertion_point(field_add:perfetto.protos.TraceConfig.activate_triggers)
}
inline void TraceConfig::add_activate_triggers(std::string&& value) {
activate_triggers_.Add(std::move(value));
// @@protoc_insertion_point(field_add:perfetto.protos.TraceConfig.activate_triggers)
}
inline void TraceConfig::add_activate_triggers(const char* value) {
GOOGLE_DCHECK(value != nullptr);
activate_triggers_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:perfetto.protos.TraceConfig.activate_triggers)
}
inline void TraceConfig::add_activate_triggers(const char* value, size_t size) {
activate_triggers_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:perfetto.protos.TraceConfig.activate_triggers)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>&
TraceConfig::activate_triggers() const {
// @@protoc_insertion_point(field_list:perfetto.protos.TraceConfig.activate_triggers)
return activate_triggers_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>*
TraceConfig::mutable_activate_triggers() {
// @@protoc_insertion_point(field_mutable_list:perfetto.protos.TraceConfig.activate_triggers)
return &activate_triggers_;
}
// optional .perfetto.protos.TraceConfig.IncrementalStateConfig incremental_state_config = 21;
inline bool TraceConfig::has_incremental_state_config() const {
return (_has_bits_[0] & 0x00000040u) != 0;
}
inline void TraceConfig::clear_incremental_state_config() {
if (incremental_state_config_ != nullptr) incremental_state_config_->Clear();
_has_bits_[0] &= ~0x00000040u;
}
inline const ::perfetto::protos::TraceConfig_IncrementalStateConfig& TraceConfig::incremental_state_config() const {
const ::perfetto::protos::TraceConfig_IncrementalStateConfig* p = incremental_state_config_;
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.incremental_state_config)
return p != nullptr ? *p : *reinterpret_cast<const ::perfetto::protos::TraceConfig_IncrementalStateConfig*>(
&::perfetto::protos::_TraceConfig_IncrementalStateConfig_default_instance_);
}
inline ::perfetto::protos::TraceConfig_IncrementalStateConfig* TraceConfig::release_incremental_state_config() {
// @@protoc_insertion_point(field_release:perfetto.protos.TraceConfig.incremental_state_config)
_has_bits_[0] &= ~0x00000040u;
::perfetto::protos::TraceConfig_IncrementalStateConfig* temp = incremental_state_config_;
incremental_state_config_ = nullptr;
return temp;
}
inline ::perfetto::protos::TraceConfig_IncrementalStateConfig* TraceConfig::mutable_incremental_state_config() {
_has_bits_[0] |= 0x00000040u;
if (incremental_state_config_ == nullptr) {
auto* p = CreateMaybeMessage<::perfetto::protos::TraceConfig_IncrementalStateConfig>(GetArenaNoVirtual());
incremental_state_config_ = p;
}
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.incremental_state_config)
return incremental_state_config_;
}
inline void TraceConfig::set_allocated_incremental_state_config(::perfetto::protos::TraceConfig_IncrementalStateConfig* incremental_state_config) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == nullptr) {
delete incremental_state_config_;
}
if (incremental_state_config) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
incremental_state_config = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, incremental_state_config, submessage_arena);
}
_has_bits_[0] |= 0x00000040u;
} else {
_has_bits_[0] &= ~0x00000040u;
}
incremental_state_config_ = incremental_state_config;
// @@protoc_insertion_point(field_set_allocated:perfetto.protos.TraceConfig.incremental_state_config)
}
// optional bool allow_user_build_tracing = 19;
inline bool TraceConfig::has_allow_user_build_tracing() const {
return (_has_bits_[0] & 0x00040000u) != 0;
}
inline void TraceConfig::clear_allow_user_build_tracing() {
allow_user_build_tracing_ = false;
_has_bits_[0] &= ~0x00040000u;
}
inline bool TraceConfig::allow_user_build_tracing() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.allow_user_build_tracing)
return allow_user_build_tracing_;
}
inline void TraceConfig::set_allow_user_build_tracing(bool value) {
_has_bits_[0] |= 0x00040000u;
allow_user_build_tracing_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.allow_user_build_tracing)
}
// optional string unique_session_name = 22;
inline bool TraceConfig::has_unique_session_name() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void TraceConfig::clear_unique_session_name() {
unique_session_name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& TraceConfig::unique_session_name() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.unique_session_name)
return unique_session_name_.GetNoArena();
}
inline void TraceConfig::set_unique_session_name(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
unique_session_name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.unique_session_name)
}
inline void TraceConfig::set_unique_session_name(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
unique_session_name_.SetNoArena(
&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:perfetto.protos.TraceConfig.unique_session_name)
}
inline void TraceConfig::set_unique_session_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
unique_session_name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:perfetto.protos.TraceConfig.unique_session_name)
}
inline void TraceConfig::set_unique_session_name(const char* value, size_t size) {
_has_bits_[0] |= 0x00000001u;
unique_session_name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:perfetto.protos.TraceConfig.unique_session_name)
}
inline std::string* TraceConfig::mutable_unique_session_name() {
_has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.unique_session_name)
return unique_session_name_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline std::string* TraceConfig::release_unique_session_name() {
// @@protoc_insertion_point(field_release:perfetto.protos.TraceConfig.unique_session_name)
if (!has_unique_session_name()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return unique_session_name_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline void TraceConfig::set_allocated_unique_session_name(std::string* unique_session_name) {
if (unique_session_name != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
unique_session_name_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), unique_session_name);
// @@protoc_insertion_point(field_set_allocated:perfetto.protos.TraceConfig.unique_session_name)
}
// optional .perfetto.protos.TraceConfig.CompressionType compression_type = 24;
inline bool TraceConfig::has_compression_type() const {
return (_has_bits_[0] & 0x00200000u) != 0;
}
inline void TraceConfig::clear_compression_type() {
compression_type_ = 0;
_has_bits_[0] &= ~0x00200000u;
}
inline ::perfetto::protos::TraceConfig_CompressionType TraceConfig::compression_type() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.compression_type)
return static_cast< ::perfetto::protos::TraceConfig_CompressionType >(compression_type_);
}
inline void TraceConfig::set_compression_type(::perfetto::protos::TraceConfig_CompressionType value) {
assert(::perfetto::protos::TraceConfig_CompressionType_IsValid(value));
_has_bits_[0] |= 0x00200000u;
compression_type_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.compression_type)
}
// optional .perfetto.protos.TraceConfig.IncidentReportConfig incident_report_config = 25;
inline bool TraceConfig::has_incident_report_config() const {
return (_has_bits_[0] & 0x00000080u) != 0;
}
inline void TraceConfig::clear_incident_report_config() {
if (incident_report_config_ != nullptr) incident_report_config_->Clear();
_has_bits_[0] &= ~0x00000080u;
}
inline const ::perfetto::protos::TraceConfig_IncidentReportConfig& TraceConfig::incident_report_config() const {
const ::perfetto::protos::TraceConfig_IncidentReportConfig* p = incident_report_config_;
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.incident_report_config)
return p != nullptr ? *p : *reinterpret_cast<const ::perfetto::protos::TraceConfig_IncidentReportConfig*>(
&::perfetto::protos::_TraceConfig_IncidentReportConfig_default_instance_);
}
inline ::perfetto::protos::TraceConfig_IncidentReportConfig* TraceConfig::release_incident_report_config() {
// @@protoc_insertion_point(field_release:perfetto.protos.TraceConfig.incident_report_config)
_has_bits_[0] &= ~0x00000080u;
::perfetto::protos::TraceConfig_IncidentReportConfig* temp = incident_report_config_;
incident_report_config_ = nullptr;
return temp;
}
inline ::perfetto::protos::TraceConfig_IncidentReportConfig* TraceConfig::mutable_incident_report_config() {
_has_bits_[0] |= 0x00000080u;
if (incident_report_config_ == nullptr) {
auto* p = CreateMaybeMessage<::perfetto::protos::TraceConfig_IncidentReportConfig>(GetArenaNoVirtual());
incident_report_config_ = p;
}
// @@protoc_insertion_point(field_mutable:perfetto.protos.TraceConfig.incident_report_config)
return incident_report_config_;
}
inline void TraceConfig::set_allocated_incident_report_config(::perfetto::protos::TraceConfig_IncidentReportConfig* incident_report_config) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == nullptr) {
delete incident_report_config_;
}
if (incident_report_config) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr;
if (message_arena != submessage_arena) {
incident_report_config = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, incident_report_config, submessage_arena);
}
_has_bits_[0] |= 0x00000080u;
} else {
_has_bits_[0] &= ~0x00000080u;
}
incident_report_config_ = incident_report_config;
// @@protoc_insertion_point(field_set_allocated:perfetto.protos.TraceConfig.incident_report_config)
}
// optional int64 trace_uuid_msb = 27;
inline bool TraceConfig::has_trace_uuid_msb() const {
return (_has_bits_[0] & 0x00100000u) != 0;
}
inline void TraceConfig::clear_trace_uuid_msb() {
trace_uuid_msb_ = PROTOBUF_LONGLONG(0);
_has_bits_[0] &= ~0x00100000u;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 TraceConfig::trace_uuid_msb() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.trace_uuid_msb)
return trace_uuid_msb_;
}
inline void TraceConfig::set_trace_uuid_msb(::PROTOBUF_NAMESPACE_ID::int64 value) {
_has_bits_[0] |= 0x00100000u;
trace_uuid_msb_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.trace_uuid_msb)
}
// optional int64 trace_uuid_lsb = 28;
inline bool TraceConfig::has_trace_uuid_lsb() const {
return (_has_bits_[0] & 0x00800000u) != 0;
}
inline void TraceConfig::clear_trace_uuid_lsb() {
trace_uuid_lsb_ = PROTOBUF_LONGLONG(0);
_has_bits_[0] &= ~0x00800000u;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 TraceConfig::trace_uuid_lsb() const {
// @@protoc_insertion_point(field_get:perfetto.protos.TraceConfig.trace_uuid_lsb)
return trace_uuid_lsb_;
}
inline void TraceConfig::set_trace_uuid_lsb(::PROTOBUF_NAMESPACE_ID::int64 value) {
_has_bits_[0] |= 0x00800000u;
trace_uuid_lsb_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.TraceConfig.trace_uuid_lsb)
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// @@protoc_insertion_point(namespace_scope)
} // namespace protos
} // namespace perfetto
PROTOBUF_NAMESPACE_OPEN
template <> struct is_proto_enum< ::perfetto::protos::TraceConfig_BufferConfig_FillPolicy> : ::std::true_type {};
template <> struct is_proto_enum< ::perfetto::protos::TraceConfig_TriggerConfig_TriggerMode> : ::std::true_type {};
template <> struct is_proto_enum< ::perfetto::protos::TraceConfig_LockdownModeOperation> : ::std::true_type {};
template <> struct is_proto_enum< ::perfetto::protos::TraceConfig_CompressionType> : ::std::true_type {};
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_protos_2fperfetto_2fconfig_2ftrace_5fconfig_2eproto
|
prosyslab-warehouse/graphicsmagick-1.3.25 | magick/quantize.c | <gh_stars>0
/*
% Copyright (C) 2003 - 2015 GraphicsMagick Group
% Copyright (C) 2002 ImageMagick Studio
% Copyright 1991-1999 <NAME> and Company
%
% This program is covered by multiple licenses, which are described in
% Copyright.txt. You should have received a copy of Copyright.txt with this
% package; otherwise see http://www.graphicsmagick.org/www/Copyright.html.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% QQQ U U AAA N N TTTTT IIIII ZZZZZ EEEEE %
% Q Q U U A A NN N T I ZZ E %
% Q Q U U AAAAA N N N T I ZZZ EEEEE %
% Q QQ U U A A N NN T I ZZ E %
% QQQQ UUU A A N N T IIIII ZZZZZ EEEEE %
% %
% %
% Methods to Reduce the Number of Unique Colors in an Image %
% %
% %
% Software Design %
% <NAME> %
% July 1992 %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Realism in computer graphics typically requires using 24 bits/pixel to
% generate an image. Yet many graphic display devices do not contain the
% amount of memory necessary to match the spatial and color resolution of
% the human eye. The Quantize methods takes a 24 bit image and reduces
% the number of colors so it can be displayed on raster device with less
% bits per pixel. In most instances, the quantized image closely
% resembles the original reference image.
%
% A reduction of colors in an image is also desirable for image
% transmission and real-time animation.
%
% QuantizeImage() takes a standard RGB or monochrome images and quantizes
% them down to some fixed number of colors.
%
% For purposes of color allocation, an image is a set of n pixels, where
% each pixel is a point in RGB space. RGB space is a 3-dimensional
% vector space, and each pixel, Pi, is defined by an ordered triple of
% red, green, and blue coordinates, (Ri, Gi, Bi).
%
% Each primary color component (red, green, or blue) represents an
% intensity which varies linearly from 0 to a maximum value, Cmax, which
% corresponds to full saturation of that color. Color allocation is
% defined over a domain consisting of the cube in RGB space with opposite
% vertices at (0,0,0) and (Cmax, Cmax, Cmax). QUANTIZE requires Cmax =
% 255.
%
% The algorithm maps this domain onto a tree in which each node
% represents a cube within that domain. In the following discussion
% these cubes are defined by the coordinate of two opposite vertices:
% The vertex nearest the origin in RGB space and the vertex farthest from
% the origin.
%
% The tree's root node represents the the entire domain, (0,0,0) through
% (Cmax,Cmax,Cmax). Each lower level in the tree is generated by
% subdividing one node's cube into eight smaller cubes of equal size.
% This corresponds to bisecting the parent cube with planes passing
% through the midpoints of each edge.
%
% The basic algorithm operates in three phases: Classification,
% Reduction, and Assignment. Classification builds a color description
% tree for the image. Reduction collapses the tree until the number it
% represents, at most, the number of colors desired in the output image.
% Assignment defines the output image's color map and sets each pixel's
% color by restorage_class in the reduced tree. Our goal is to minimize
% the numerical discrepancies between the original colors and quantized
% colors (quantization error).
%
% Classification begins by initializing a color description tree of
% sufficient depth to represent each possible input color in a leaf.
% However, it is impractical to generate a fully-formed color description
% tree in the storage_class phase for realistic values of Cmax. If
% colors components in the input image are quantized to k-bit precision,
% so that Cmax= 2k-1, the tree would need k levels below the root node to
% allow representing each possible input color in a leaf. This becomes
% prohibitive because the tree's total number of nodes is 1 +
% sum(i=1, k, 8k).
%
% A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
% Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
% Initializes data structures for nodes only as they are needed; (2)
% Chooses a maximum depth for the tree as a function of the desired
% number of colors in the output image (currently log2(colormap size)).
%
% For each pixel in the input image, storage_class scans downward from
% the root of the color description tree. At each level of the tree it
% identifies the single node which represents a cube in RGB space
% containing the pixel's color. It updates the following data for each
% such node:
%
% n1: Number of pixels whose color is contained in the RGB cube which
% this node represents;
%
% n2: Number of pixels whose color is not represented in a node at
% lower depth in the tree; initially, n2 = 0 for all nodes except
% leaves of the tree.
%
% Sr, Sg, Sb: Sums of the red, green, and blue component values for all
% pixels not classified at a lower depth. The combination of these sums
% and n2 will ultimately characterize the mean color of a set of
% pixels represented by this node.
%
% E: The distance squared in RGB space between each pixel contained
% within a node and the nodes' center. This represents the
% quantization error for a node.
%
% Reduction repeatedly prunes the tree until the number of nodes with n2
% > 0 is less than or equal to the maximum number of colors allowed in
% the output image. On any given iteration over the tree, it selects
% those nodes whose E count is minimal for pruning and merges their color
% statistics upward. It uses a pruning threshold, Ep, to govern node
% selection as follows:
%
% Ep = 0
% while number of nodes with (n2 > 0) > required maximum number of colors
% prune all nodes such that E <= Ep
% Set Ep to minimum E in remaining nodes
%
% This has the effect of minimizing any quantization error when merging
% two nodes together.
%
% When a node to be pruned has offspring, the pruning procedure invokes
% itself recursively in order to prune the tree from the leaves upward.
% n2, Sr, Sg, and Sb in a node being pruned are always added to the
% corresponding data in that node's parent. This retains the pruned
% node's color characteristics for later averaging.
%
% For each node, n2 pixels exist for which that node represents the
% smallest volume in RGB space containing those pixel's colors. When n2
% > 0 the node will uniquely define a color in the output image. At the
% beginning of reduction, n2 = 0 for all nodes except a the leaves of
% the tree which represent colors present in the input image.
%
% The other pixel count, n1, indicates the total number of colors within
% the cubic volume which the node represents. This includes n1 - n2
% pixels whose colors should be defined by nodes at a lower level in the
% tree.
%
% Assignment generates the output image from the pruned tree. The output
% image consists of two parts: (1) A color map, which is an array of
% color descriptions (RGB triples) for each color present in the output
% image; (2) A pixel array, which represents each pixel as an index
% into the color map array.
%
% First, the assignment phase makes one pass over the pruned color
% description tree to establish the image's color map. For each node
% with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
% color of all pixels that classify no lower than this node. Each of
% these colors becomes an entry in the color map.
%
% Finally, the assignment phase reclassifies each pixel in the pruned
% tree to identify the deepest node containing the pixel's color. The
% pixel's value in the pixel array becomes the index of this node's mean
% color in the color map.
%
% This method is based on a similar algorithm written by <NAME>.
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/analyze.h"
#include "magick/color.h"
#include "magick/colormap.h"
#include "magick/enhance.h"
#include "magick/monitor.h"
#include "magick/pixel_cache.h"
#include "magick/quantize.h"
#include "magick/utility.h"
/*
Define declarations.
*/
#define CacheShift (QuantumDepth-6)
#define ExceptionQueueLength 16
#define MaxNodes 266817
#define MaxTreeDepth 8
#define NodesInAList 1536
#define ColorToNodeId(red,green,blue,index) ((unsigned int) \
(((ScaleQuantumToChar(red) >> index) & 0x01) << 2 | \
((ScaleQuantumToChar(green) >> index) & 0x01) << 1 | \
((ScaleQuantumToChar(blue) >> index) & 0x01)))
/*
Typedef declarations.
*/
#if QuantumDepth > 16 && defined(HAVE_LONG_DOUBLE_WIDER)
typedef long double ErrorSumType;
#else
typedef double ErrorSumType;
#endif
typedef struct _NodeInfo
{
struct _NodeInfo
*parent,
*child[MaxTreeDepth];
double
number_unique;
double /* was ErrorSumType */
total_red,
total_green,
total_blue;
ErrorSumType
quantize_error;
unsigned long
color_number;
unsigned char
id,
level;
} NodeInfo;
typedef struct _Nodes
{
NodeInfo
*nodes;
struct _Nodes
*next;
} Nodes;
typedef struct _CubeInfo
{
NodeInfo
*root;
unsigned long
colors;
DoublePixelPacket
color;
double /* was ErrorSumType */
distance;
ErrorSumType
pruning_threshold,
next_threshold;
unsigned long
nodes,
free_nodes,
color_number;
NodeInfo
*next_node;
Nodes
*node_queue;
long
*cache;
DoublePixelPacket
error[ExceptionQueueLength];
double
weights[ExceptionQueueLength];
const QuantizeInfo
*quantize_info;
long
x,
y;
unsigned long
depth;
} CubeInfo;
/*
Method prototypes.
*/
static void
ClosestColor(Image *,CubeInfo *,const NodeInfo *);
static NodeInfo
*GetNodeInfo(CubeInfo *,const unsigned int,const unsigned int,NodeInfo *);
static unsigned int
DitherImage(CubeInfo *,Image *);
static void
DefineImageColormap(Image *,NodeInfo *),
HilbertCurve(CubeInfo *,Image *,const unsigned long,const unsigned int),
PruneLevel(CubeInfo *,const NodeInfo *),
PruneToCubeDepth(CubeInfo *,const NodeInfo *),
ReduceImageColors(const char *filename,CubeInfo *,const unsigned long,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A s s i g n I m a g e C o l o r s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AssignImageColors() generates the output image from the pruned tree. The
% output image consists of two parts: (1) A color map, which is an array
% of color descriptions (RGB triples) for each color present in the
% output image; (2) A pixel array, which represents each pixel as an
% index into the color map array.
%
% First, the assignment phase makes one pass over the pruned color
% description tree to establish the image's color map. For each node
% with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
% color of all pixels that classify no lower than this node. Each of
% these colors becomes an entry in the color map.
%
% Finally, the assignment phase reclassifies each pixel in the pruned
% tree to identify the deepest node containing the pixel's color. The
% pixel's value in the pixel array becomes the index of this node's mean
% color in the color map.
%
% The format of the AssignImageColors() method is:
%
% unsigned int AssignImageColors(CubeInfo *cube_info,Image *image)
%
% A description of each parameter follows.
%
% o cube_info: A pointer to the Cube structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
%
*/
static MagickPassFail AssignImageColors(CubeInfo *cube_info,Image *image)
{
#define AssignImageText "[%s] Assign colors..."
IndexPacket
index;
long
count,
y;
register IndexPacket
*indexes;
register long
i,
x;
register const NodeInfo
*node_info;
register PixelPacket
*q;
unsigned int
dither;
unsigned int
id,
is_grayscale,
is_monochrome;
MagickPassFail
status=MagickPass;
/*
Allocate image colormap.
*/
if (!AllocateImageColormap(image,cube_info->colors))
ThrowBinaryException3(ResourceLimitError,MemoryAllocationFailed,
UnableToQuantizeImage);
image->colors=0;
is_grayscale=image->is_grayscale;
is_monochrome=image->is_monochrome;
DefineImageColormap(image,cube_info->root);
if (cube_info->quantize_info->colorspace == TransparentColorspace)
image->storage_class=DirectClass;
/*
Create a reduced color image.
*/
dither=cube_info->quantize_info->dither;
if (dither)
dither=DitherImage(cube_info,image);
if (!dither)
for (y=0; y < (long) image->rows; y++)
{
q=GetImagePixels(image,0,y,image->columns,1);
if (q == (PixelPacket *) NULL)
{
status=MagickFail;
break;
}
indexes=AccessMutableIndexes(image);
for (x=0; x < (long) image->columns; x+=count)
{
/*
Identify the deepest node containing the pixel's color.
*/
for (count=1; (x+count) < (long) image->columns; count++)
if (NotColorMatch(q,q+count))
break;
node_info=cube_info->root;
for (index=MaxTreeDepth-1; (long) index > 0; index--)
{
id=ColorToNodeId(q->red,q->green,q->blue,index);
if (node_info->child[id] == (NodeInfo *) NULL)
break;
node_info=node_info->child[id];
}
/*
Find closest color among siblings and their children.
*/
cube_info->color.red=q->red;
cube_info->color.green=q->green;
cube_info->color.blue=q->blue;
cube_info->distance=3.0*((double) MaxRGB+1.0)*((double) MaxRGB+1.0);
ClosestColor(image,cube_info,node_info->parent);
index=(IndexPacket) cube_info->color_number;
for (i=0; i < count; i++)
{
if (image->storage_class == PseudoClass)
indexes[x+i]=index;
if (!cube_info->quantize_info->measure_error)
{
q->red=image->colormap[index].red;
q->green=image->colormap[index].green;
q->blue=image->colormap[index].blue;
}
q++;
}
}
if (!SyncImagePixels(image))
{
status=MagickFail;
break;
}
if (QuantumTick(y,image->rows))
if (!MagickMonitorFormatted(y,image->rows,&image->exception,
AssignImageText,image->filename))
{
status=MagickFail;
break;
}
}
if ((cube_info->quantize_info->number_colors == 2) &&
(IsGrayColorspace(cube_info->quantize_info->colorspace)))
{
Quantum
intensity;
/*
Monochrome image.
*/
is_monochrome=True;
q=image->colormap;
for (i=(long) image->colors; i > 0; i--)
{
intensity=(Quantum) (PixelIntensityToQuantum(q) <
(MaxRGB/2) ? 0 : MaxRGB);
q->red=intensity;
q->green=intensity;
q->blue=intensity;
q++;
}
}
if (cube_info->quantize_info->measure_error)
(void) GetImageQuantizeError(image);
status &= SyncImage(image);
image->is_grayscale=is_grayscale;
image->is_monochrome=is_monochrome;
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C l a s s i f y I m a g e C o l o r s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClassifyImageColors() begins by initializing a color description tree
% of sufficient depth to represent each possible input color in a leaf.
% However, it is impractical to generate a fully-formed color
% description tree in the storage_class phase for realistic values of
% Cmax. If colors components in the input image are quantized to k-bit
% precision, so that Cmax= 2k-1, the tree would need k levels below the
% root node to allow representing each possible input color in a leaf.
% This becomes prohibitive because the tree's total number of nodes is
% 1 + sum(i=1,k,8k).
%
% A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
% Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
% Initializes data structures for nodes only as they are needed; (2)
% Chooses a maximum depth for the tree as a function of the desired
% number of colors in the output image (currently log2(colormap size)).
%
% For each pixel in the input image, storage_class scans downward from
% the root of the color description tree. At each level of the tree it
% identifies the single node which represents a cube in RGB space
% containing It updates the following data for each such node:
%
% n1 : Number of pixels whose color is contained in the RGB cube
% which this node represents;
%
% n2 : Number of pixels whose color is not represented in a node at
% lower depth in the tree; initially, n2 = 0 for all nodes except
% leaves of the tree.
%
% Sr, Sg, Sb : Sums of the red, green, and blue component values for
% all pixels not classified at a lower depth. The combination of
% these sums and n2 will ultimately characterize the mean color of a
% set of pixels represented by this node.
%
% E: The distance squared in RGB space between each pixel contained
% within a node and the nodes' center. This represents the quantization
% error for a node.
%
% The format of the ClassifyImageColors() method is:
%
% unsigned int ClassifyImageColorsCubeInfo *cube_info,const Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o cube_info: A pointer to the Cube structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
%
*/
static MagickPassFail ClassifyImageColors(CubeInfo *cube_info,const Image *image,
ExceptionInfo *exception)
{
#define ClassifyImageText "[%s] Classify colors..."
double
bisect;
DoublePixelPacket
mid,
pixel;
long
count,
y;
NodeInfo
*node_info;
register long
x;
register const PixelPacket
*p;
unsigned long
index,
level;
unsigned int
id;
MagickPassFail
status=MagickPass;
/*
Classify the first 256 colors to a tree depth of 8.
*/
for (y=0; (y < (long) image->rows) && (cube_info->colors < 256); y++)
{
p=AcquireImagePixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
{
status=MagickFail;
break;
}
if (cube_info->nodes > MaxNodes)
{
/*
Prune one level if the color tree is too large.
*/
PruneLevel(cube_info,cube_info->root);
cube_info->depth--;
}
for (x=0; x < (long) image->columns; x+=count)
{
/*
Start at the root and descend the color cube tree.
*/
for (count=1; (x+count) < (long) image->columns; count++)
if (NotColorMatch(p,p+count))
break;
index=MaxTreeDepth-1;
bisect=((double) MaxRGB+1.0)/2.0;
mid.red=MaxRGB/2.0;
mid.green=MaxRGB/2.0;
mid.blue=MaxRGB/2.0;
node_info=cube_info->root;
for (level=1; level <= 8; level++)
{
bisect/=2;
id=ColorToNodeId(p->red,p->green,p->blue,index);
mid.red+=id & 4 ? bisect : -bisect;
mid.green+=id & 2 ? bisect : -bisect;
mid.blue+=id & 1 ? bisect : -bisect;
if (node_info->child[id] == (NodeInfo *) NULL)
{
/*
Set colors of new node to contain pixel.
*/
node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
if (node_info->child[id] == (NodeInfo *) NULL)
ThrowException3(exception,ResourceLimitError,
MemoryAllocationFailed,UnableToQuantizeImage);
if (level == MaxTreeDepth)
cube_info->colors++;
}
/*
Approximate the quantization error represented by this node.
*/
node_info=node_info->child[id];
pixel.red=p->red-mid.red;
pixel.green=p->green-mid.green;
pixel.blue=p->blue-mid.blue;
node_info->quantize_error+=count*pixel.red*pixel.red+
count*pixel.green*pixel.green+count*pixel.blue*pixel.blue;
cube_info->root->quantize_error+=node_info->quantize_error;
index--;
}
/*
Sum RGB for this leaf for later derivation of the mean cube color.
*/
node_info->number_unique+=count;
node_info->total_red+=(double) count*p->red;
node_info->total_green+=(double) count*p->green;
node_info->total_blue+=(double) count*p->blue;
p+=count;
}
if (QuantumTick(y,image->rows))
if (!MagickMonitorFormatted(y,image->rows,exception,
ClassifyImageText,image->filename))
{
status=MagickFail;
break;
}
}
if (y == (long) image->rows)
return(True);
/*
More than 256 colors; classify to the cube_info->depth tree depth.
*/
PruneToCubeDepth(cube_info,cube_info->root);
for ( ; y < (long) image->rows; y++)
{
p=AcquireImagePixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
{
status=MagickFail;
break;
}
if (cube_info->nodes > MaxNodes)
{
/*
Prune one level if the color tree is too large.
*/
PruneLevel(cube_info,cube_info->root);
cube_info->depth--;
}
for (x=0; x < (long) image->columns; x+=count)
{
/*
Start at the root and descend the color cube tree.
*/
for (count=1; (x+count) < (long) image->columns; count++)
if (NotColorMatch(p,p+count))
break;
index=MaxTreeDepth-1;
bisect=((double) MaxRGB+1.0)/2.0;
mid.red=MaxRGB/2.0;
mid.green=MaxRGB/2.0;
mid.blue=MaxRGB/2.0;
node_info=cube_info->root;
for (level=1; level <= cube_info->depth; level++)
{
bisect/=2;
id=ColorToNodeId(p->red,p->green,p->blue,index);
mid.red+=id & 4 ? bisect : -bisect;
mid.green+=id & 2 ? bisect : -bisect;
mid.blue+=id & 1 ? bisect : -bisect;
if (node_info->child[id] == (NodeInfo *) NULL)
{
/*
Set colors of new node to contain pixel.
*/
node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
if (node_info->child[id] == (NodeInfo *) NULL)
ThrowException3(exception,ResourceLimitError,
MemoryAllocationFailed,UnableToQuantizeImage);
if (level == cube_info->depth)
cube_info->colors++;
}
/*
Approximate the quantization error represented by this node.
*/
node_info=node_info->child[id];
pixel.red=p->red-mid.red;
pixel.green=p->green-mid.green;
pixel.blue=p->blue-mid.blue;
node_info->quantize_error+=count*pixel.red*pixel.red+
count*pixel.green*pixel.green+count*pixel.blue*pixel.blue;
cube_info->root->quantize_error+=node_info->quantize_error;
index--;
}
/*
Sum RGB for this leaf for later derivation of the mean cube color.
*/
node_info->number_unique+=count;
node_info->total_red+=(double) count*p->red;
node_info->total_green+=(double) count*p->green;
node_info->total_blue+=(double) count*p->blue;
p+=count;
}
if (QuantumTick(y,image->rows))
if (!MagickMonitorFormatted(y,image->rows,exception,
ClassifyImageText,image->filename))
{
status=MagickFail;
break;
}
}
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e Q u a n t i z e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
% or if quantize info is NULL, a new one.
%
% The format of the CloneQuantizeInfo method is:
%
% QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
%
% A description of each parameter follows:
%
% o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
% quantize info, or if image info is NULL a new one.
%
% o quantize_info: a structure of type info.
%
%
*/
MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
{
QuantizeInfo
*clone_info;
clone_info=MagickAllocateMemory(QuantizeInfo *,sizeof(QuantizeInfo));
if (clone_info == (QuantizeInfo *) NULL)
MagickFatalError3(ResourceLimitFatalError,MemoryAllocationFailed,
UnableToAllocateQuantizeInfo);
GetQuantizeInfo(clone_info);
if (quantize_info == (QuantizeInfo *) NULL)
return(clone_info);
clone_info->number_colors=quantize_info->number_colors;
clone_info->tree_depth=quantize_info->tree_depth;
clone_info->dither=quantize_info->dither;
clone_info->colorspace=quantize_info->colorspace;
clone_info->measure_error=quantize_info->measure_error;
return(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C l o s e s t C o l o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClosestColor() traverses the color cube tree at a particular node and
% determines which colormap entry best represents the input color.
%
% The format of the ClosestColor method is:
%
% void ClosestColor(Image *image,CubeInfo *cube_info,
% const NodeInfo *node_info)
%
% A description of each parameter follows.
%
% o image: The image.
%
% o cube_info: A pointer to the Cube structure.
%
% o node_info: The address of a structure of type NodeInfo which points to a
% node in the color cube tree that is to be pruned.
%
%
*/
static void ClosestColor(Image *image,CubeInfo *cube_info,
const NodeInfo *node_info)
{
register unsigned int
id;
/*
Traverse any children.
*/
for (id=0; id < MaxTreeDepth; id++)
if (node_info->child[id] != (NodeInfo *) NULL)
ClosestColor(image,cube_info,node_info->child[id]);
if (node_info->number_unique != 0)
{
double
distance;
DoublePixelPacket
pixel;
register PixelPacket
*color;
/*
Determine if this color is "closest".
*/
color=image->colormap+node_info->color_number;
pixel.red=color->red-cube_info->color.red;
distance=pixel.red*pixel.red;
if (distance < cube_info->distance)
{
pixel.green=color->green-cube_info->color.green;
distance+=pixel.green*pixel.green;
if (distance < cube_info->distance)
{
pixel.blue=color->blue-cube_info->color.blue;
distance+=pixel.blue*pixel.blue;
if (distance < cube_info->distance)
{
cube_info->distance=distance;
cube_info->color_number=node_info->color_number;
}
}
}
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o m p r e s s I m a g e C o l o r m a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CompressImageColormap() compresses an image colormap by removing any
% duplicate or unused color entries.
%
% The format of the CompressImageColormap method is:
%
% void CompressImageColormap(Image *image)
%
% A description of each parameter follows:
%
% o image: The image.
%
%
*/
MagickExport void CompressImageColormap(Image *image)
{
QuantizeInfo
quantize_info;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (!IsPaletteImage(image,&image->exception))
return;
GetQuantizeInfo(&quantize_info);
quantize_info.number_colors=image->colors;
quantize_info.tree_depth=MaxTreeDepth;
(void) QuantizeImage(&quantize_info,image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e f i n e I m a g e C o l o r m a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DefineImageColormap() traverses the color cube tree and notes each colormap
% entry. A colormap entry is any node in the color cube tree where the
% of unique colors is not zero.
%
% The format of the DefineImageColormap method is:
%
% DefineImageColormap(Image *image,NodeInfo *node_info)
%
% A description of each parameter follows.
%
% o image: The image.
%
% o node_info: The address of a structure of type NodeInfo which points to a
% node in the color cube tree that is to be pruned.
%
%
*/
static void DefineImageColormap(Image *image,NodeInfo *node_info)
{
register unsigned int
id;
/*
Traverse any children.
*/
for (id=0; id < MaxTreeDepth; id++)
if (node_info->child[id] != (NodeInfo *) NULL)
DefineImageColormap(image,node_info->child[id]);
if (node_info->number_unique != 0)
{
register double
number_unique;
/*
Colormap entry is defined by the mean color in this cube.
*/
number_unique=node_info->number_unique;
image->colormap[image->colors].red=(Quantum)
(node_info->total_red/number_unique+0.5);
image->colormap[image->colors].green=(Quantum)
(node_info->total_green/number_unique+0.5);
image->colormap[image->colors].blue=(Quantum)
(node_info->total_blue/number_unique+0.5);
node_info->color_number=image->colors++;
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y C u b e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyCubeInfo() deallocates memory associated with an image.
%
% The format of the DestroyCubeInfo method is:
%
% DestroyCubeInfo(CubeInfo *cube_info)
%
% A description of each parameter follows:
%
% o cube_info: The address of a structure of type CubeInfo.
%
%
*/
static void DestroyCubeInfo(CubeInfo *cube_info)
{
register Nodes
*nodes;
/*
Release color cube tree storage.
*/
do
{
nodes=cube_info->node_queue->next;
MagickFreeMemory(cube_info->node_queue->nodes);
MagickFreeMemory(cube_info->node_queue);
cube_info->node_queue=nodes;
} while (cube_info->node_queue != (Nodes *) NULL);
if (cube_info->quantize_info->dither)
MagickFreeMemory(cube_info->cache);
MagickFreeMemory(cube_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y Q u a n t i z e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
% structure.
%
% The format of the DestroyQuantizeInfo method is:
%
% DestroyQuantizeInfo(QuantizeInfo *quantize_info)
%
% A description of each parameter follows:
%
% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
%
%
*/
MagickExport void DestroyQuantizeInfo(QuantizeInfo *quantize_info)
{
assert(quantize_info != (QuantizeInfo *) NULL);
assert(quantize_info->signature == MagickSignature);
MagickFreeMemory(quantize_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D i t h e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Dither() distributes the difference between an original image and the
% corresponding color reduced algorithm to neighboring pixels along a Hilbert
% curve.
%
% The format of the Dither method is:
%
% unsigned int Dither(CubeInfo *cube_info,Image *image,
% const unsigned int direction)
%
% A description of each parameter follows.
%
% o cube_info: A pointer to the Cube structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
% o direction: This unsigned direction describes which direction
% to move to next to follow the Hilbert curve.
%
*/
static MagickPassFail Dither(CubeInfo *cube_info,Image *image,
const unsigned int direction)
{
DoublePixelPacket
error;
IndexPacket
index;
PixelPacket
pixel;
register CubeInfo
*p;
register IndexPacket
*indexes;
register long
i;
register PixelPacket
*q;
p=cube_info;
if ((p->x >= 0) && (p->x < (long) image->columns) &&
(p->y >= 0) && (p->y < (long) image->rows))
{
/*
Distribute error.
*/
q=GetImagePixels(image,p->x,p->y,1,1);
if (q == (PixelPacket *) NULL)
return(MagickFail);
indexes=AccessMutableIndexes(image);
error.red=q->red;
error.green=q->green;
error.blue=q->blue;
for (i=0; i < ExceptionQueueLength; i++)
{
error.red+=p->error[i].red*p->weights[i];
error.green+=p->error[i].green*p->weights[i];
error.blue+=p->error[i].blue*p->weights[i];
}
pixel.red=RoundDoubleToQuantum(error.red);
pixel.green=RoundDoubleToQuantum(error.green);
pixel.blue=RoundDoubleToQuantum(error.blue);
i=(pixel.blue >> CacheShift) << 12 | (pixel.green >> CacheShift) << 6 |
(pixel.red >> CacheShift);
if (p->cache[i] < 0)
{
register NodeInfo
*node_info;
register unsigned int
id;
/*
Identify the deepest node containing the pixel's color.
*/
node_info=p->root;
for (index=MaxTreeDepth-1; (long) index > 0; index--)
{
id=ColorToNodeId(pixel.red,pixel.green,pixel.blue,index);
if (node_info->child[id] == (NodeInfo *) NULL)
break;
node_info=node_info->child[id];
}
/*
Find closest color among siblings and their children.
*/
p->color.red=pixel.red;
p->color.green=pixel.green;
p->color.blue=pixel.blue;
p->distance=3.0*((double) MaxRGB+1.0)*((double) MaxRGB+1.0);
ClosestColor(image,p,node_info->parent);
p->cache[i]=(long) p->color_number;
}
/*
Assign pixel to closest colormap entry.
*/
index=(IndexPacket) p->cache[i];
if (image->storage_class == PseudoClass)
*indexes=index;
if (!cube_info->quantize_info->measure_error)
{
q->red=image->colormap[index].red;
q->green=image->colormap[index].green;
q->blue=image->colormap[index].blue;
}
if (!SyncImagePixels(image))
return(MagickFail);
/*
Propagate the error as the last entry of the error queue.
*/
for (i=0; i < (ExceptionQueueLength-1); i++)
p->error[i]=p->error[i+1];
p->error[i].red=pixel.red-(double) image->colormap[index].red;
p->error[i].green=pixel.green-(double) image->colormap[index].green;
p->error[i].blue=pixel.blue-(double) image->colormap[index].blue;
}
switch (direction)
{
case WestGravity: p->x--; break;
case EastGravity: p->x++; break;
case NorthGravity: p->y--; break;
case SouthGravity: p->y++; break;
}
return(MagickPass);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D i t h e r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DitherImage() distributes the difference between an original image and the
% corresponding color reduced algorithm to neighboring pixels along a Hilbert
% curve. DitherImage returns True if the image is dithered otherwise False.
%
% This algorithm is strongly based on a similar algorithm by Thiadmer
% Riemersma.
%
% The format of the DitherImage method is:
%
% unsigned int DitherImage(CubeInfo *cube_info,Image *image)
%
% A description of each parameter follows.
%
% o cube_info: A pointer to the Cube structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
%
*/
static MagickPassFail DitherImage(CubeInfo *cube_info,Image *image)
{
register unsigned long
i;
unsigned long
depth;
/*
Initialize error queue.
*/
for (i=0; i < ExceptionQueueLength; i++)
{
cube_info->error[i].red=0.0;
cube_info->error[i].green=0.0;
cube_info->error[i].blue=0.0;
}
/*
Distribute quantization error along a Hilbert curve.
*/
cube_info->x=0;
cube_info->y=0;
i=image->columns > image->rows ? image->columns : image->rows;
for (depth=1; i != 0; depth++)
i>>=1;
HilbertCurve(cube_info,image,depth-1,NorthGravity);
(void) Dither(cube_info,image,ForgetGravity);
return(MagickPass);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t C u b e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetCubeInfo() initialize the Cube data structure.
%
% The format of the GetCubeInfo method is:
%
% CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
% unsigned int depth)
%
% A description of each parameter follows.
%
% o cube_info: A pointer to the Cube structure.
%
% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
%
% o depth: Normally, this integer value is zero or one. A zero or
% one tells Quantize to choose a optimal tree depth of Log4(number_colors).
% A tree of this depth generally allows the best representation of the
% reference image with the least amount of memory and the fastest
% computational speed. In some cases, such as an image with low color
% dispersion (a few number of colors), a value other than
% Log4(number_colors) is required. To expand the color tree completely,
% use a value of 8.
%
%
*/
static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
unsigned long depth)
{
CubeInfo
*cube_info;
double
sum,
weight;
register long
i;
/*
Initialize tree to describe color cube_info.
*/
cube_info=MagickAllocateMemory(CubeInfo *,sizeof(CubeInfo));
if (cube_info == (CubeInfo *) NULL)
return((CubeInfo *) NULL);
(void) memset(cube_info,0,sizeof(CubeInfo));
if (depth > MaxTreeDepth)
depth=MaxTreeDepth;
if (depth < 2)
depth=2;
cube_info->depth=depth;
/*
Initialize root node.
*/
cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
if (cube_info->root == (NodeInfo *) NULL)
return((CubeInfo *) NULL);
cube_info->root->parent=cube_info->root;
cube_info->quantize_info=quantize_info;
if (!cube_info->quantize_info->dither)
return(cube_info);
/*
Initialize dither resources.
*/
cube_info->cache=MagickAllocateMemory(long *,(1 << 18)*sizeof(long));
if (cube_info->cache == (long *) NULL)
return((CubeInfo *) NULL);
/*
Initialize color cache.
*/
for (i=0; i < (1 << 18); i++)
cube_info->cache[i]=(-1);
/*
Distribute weights along a curve of exponential decay.
*/
weight=1.0;
for (i=0; i < ExceptionQueueLength; i++)
{
cube_info->weights[ExceptionQueueLength-i-1]=1.0/weight;
weight*=exp(log(((double) MaxRGB+1.0))/(ExceptionQueueLength-1.0));
}
/*
Normalize the weighting factors.
*/
weight=0.0;
for (i=0; i < ExceptionQueueLength; i++)
weight+=cube_info->weights[i];
sum=0.0;
for (i=0; i < ExceptionQueueLength; i++)
{
cube_info->weights[i]/=weight;
sum+=cube_info->weights[i];
}
cube_info->weights[0]+=1.0-sum;
return(cube_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t N o d e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetNodeInfo() allocates memory for a new node in the color cube tree and
% presets all fields to zero.
%
% The format of the GetNodeInfo method is:
%
% NodeInfo *GetNodeInfo(CubeInfo *cube_info,const unsigned int id,
% const unsigned int level,NodeInfo *parent)
%
% A description of each parameter follows.
%
% o node: The GetNodeInfo method returns this integer address.
%
% o id: Specifies the child number of the node.
%
% o level: Specifies the level in the storage_class the node resides.
%
%
*/
static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const unsigned int id,
const unsigned int level,NodeInfo *parent)
{
NodeInfo
*node_info;
if (cube_info->free_nodes == 0)
{
Nodes
*nodes;
/*
Allocate a new nodes of nodes.
*/
nodes=MagickAllocateMemory(Nodes *,sizeof(Nodes));
if (nodes == (Nodes *) NULL)
return((NodeInfo *) NULL);
nodes->nodes=MagickAllocateMemory(NodeInfo *,(NodesInAList*sizeof(NodeInfo)));
if (nodes->nodes == (NodeInfo *) NULL)
return((NodeInfo *) NULL);
nodes->next=cube_info->node_queue;
cube_info->node_queue=nodes;
cube_info->next_node=nodes->nodes;
cube_info->free_nodes=NodesInAList;
}
cube_info->nodes++;
cube_info->free_nodes--;
node_info=cube_info->next_node++;
(void) memset(node_info,0,sizeof(NodeInfo));
node_info->parent=parent;
node_info->id=id;
node_info->level=level;
return(node_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e Q u a n t i z e E r r o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageQuantizeError() measures the difference between the original
% and quantized images. This difference is the total quantization error.
% The error is computed by summing over all pixels in an image the distance
% squared in RGB space between each reference pixel value and its quantized
% value. These values are computed:
%
% o mean_error_per_pixel: This value is the mean error for any single
% pixel in the image.
%
% o normalized_mean_square_error: This value is the normalized mean
% quantization error for any single pixel in the image. This distance
% measure is normalized to a range between 0 and 1. It is independent
% of the range of red, green, and blue values in the image.
%
% o normalized_maximum_square_error: This value is the normalized
% maximum quantization error for any single pixel in the image. This
% distance measure is normalized to a range between 0 and 1. It is
% independent of the range of red, green, and blue values in your image.
%
%
% The format of the GetImageQuantizeError method is:
%
% unsigned int GetImageQuantizeError(Image *image)
%
% A description of each parameter follows.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
%
*/
MagickExport MagickPassFail GetImageQuantizeError(Image *image)
{
double
distance,
maximum_error_per_pixel,
normalize;
DoublePixelPacket
pixel;
IndexPacket
index;
long
y;
ErrorSumType
total_error;
register const PixelPacket
*p;
register const IndexPacket
*indexes;
register long
x;
MagickPassFail
status=MagickPass;
/*
Initialize measurement.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception);
(void) memset(&image->error,0,sizeof(ErrorInfo));
if (image->storage_class == DirectClass)
return(MagickFail);
/*
For each pixel, collect error statistics.
*/
maximum_error_per_pixel=0;
total_error=0;
for (y=0; y < (long) image->rows; y++)
{
p=AcquireImagePixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
{
status=MagickFail;
break;
}
indexes=AccessImmutableIndexes(image);
for (x=0; x < (long) image->columns; x++)
{
index=indexes[x];
pixel.red=p->red-(double) image->colormap[index].red;
pixel.green=p->green-(double) image->colormap[index].green;
pixel.blue=p->blue-(double) image->colormap[index].blue;
distance=pixel.red*pixel.red+pixel.green*pixel.green+
pixel.blue*pixel.blue;
total_error+=distance;
if (distance > maximum_error_per_pixel)
maximum_error_per_pixel=distance;
p++;
}
}
/*
Compute final error statistics.
*/
normalize=3.0*((double) MaxRGB+1.0)*((double) MaxRGB+1.0);
image->error.mean_error_per_pixel=total_error/image->columns/image->rows;
image->error.normalized_mean_error=
image->error.mean_error_per_pixel/normalize;
image->error.normalized_maximum_error=maximum_error_per_pixel/normalize;
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t Q u a n t i z e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetQuantizeInfo() initializes the QuantizeInfo structure.
%
% The format of the GetQuantizeInfo method is:
%
% GetQuantizeInfo(QuantizeInfo *quantize_info)
%
% A description of each parameter follows:
%
% o quantize_info: Specifies a pointer to a QuantizeInfo structure.
%
%
*/
MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
{
assert(quantize_info != (QuantizeInfo *) NULL);
(void) memset(quantize_info,0,sizeof(QuantizeInfo));
quantize_info->number_colors=256;
quantize_info->dither=True;
quantize_info->colorspace=RGBColorspace;
quantize_info->signature=MagickSignature;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G r a y s c a l e P s e u d o C l a s s I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GrayscalePseudoClassImage converts an image to a PseudoClass
% grayscale representation with an (optionally) compressed and sorted
% colormap. Colormap is ordered by increasing intensity.
%
% The format of the GrayscalePseudoClassImage method is:
%
% void GrayscalePseudoClassImage(Image *image)
%
% A description of each parameter follows:
%
% o image: The image.
%
% o optimize_colormap: If true, produce an optimimal (compact) colormap.
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int IntensityCompare(const void *x,const void *y)
{
long
intensity;
PixelPacket
*color_1,
*color_2;
color_1=(PixelPacket *) x;
color_2=(PixelPacket *) y;
intensity=PixelIntensityToQuantum(color_1)-
(long) PixelIntensityToQuantum(color_2);
return(intensity);
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
MagickExport void GrayscalePseudoClassImage(Image *image,
unsigned int optimize_colormap)
{
long
y;
register long
x;
register IndexPacket
*indexes;
register const PixelPacket
*q;
register unsigned int
i;
int
*colormap_index=(int *) NULL;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (!image->is_grayscale)
(void) TransformColorspace(image,GRAYColorspace);
if (image->storage_class != PseudoClass)
{
/*
Allocate maximum sized grayscale image colormap
*/
if (!AllocateImageColormap(image,MaxColormapSize))
{
ThrowException3(&image->exception,ResourceLimitError,
MemoryAllocationFailed,UnableToSortImageColormap);
return;
}
if (optimize_colormap)
{
/*
Use minimal colormap method.
*/
/*
Allocate memory for colormap index
*/
colormap_index=MagickAllocateMemory(int *,MaxColormapSize*sizeof(int));
if (colormap_index == (int *) NULL)
{
ThrowException3(&image->exception,ResourceLimitError,
MemoryAllocationFailed,UnableToSortImageColormap);
return;
}
/*
Initial colormap index value is -1 so we can tell if it
is initialized.
*/
for (i=0; i < MaxColormapSize; i++)
colormap_index[i]=-1;
image->colors=0;
for (y=0; y < (long) image->rows; y++)
{
q=GetImagePixels(image,0,y,image->columns,1);
if (q == (PixelPacket *) NULL)
break;
indexes=AccessMutableIndexes(image);
for (x=(long) image->columns; x > 0; x--)
{
register int
intensity;
/*
If index is new, create index to colormap
*/
intensity=ScaleQuantumToMap(q->red);
if (colormap_index[intensity] < 0)
{
colormap_index[intensity]=image->colors;
image->colormap[image->colors]=*q;
image->colors++;
}
*indexes++=colormap_index[intensity];
q++;
}
if (!SyncImagePixels(image))
{
MagickFreeMemory(colormap_index);
return;
}
}
}
else
{
/*
Use fast-cut linear colormap method.
*/
for (y=0; y < (long) image->rows; y++)
{
q=GetImagePixels(image,0,y,image->columns,1);
if (q == (PixelPacket *) NULL)
break;
indexes=AccessMutableIndexes(image);
for (x=(long) image->columns; x > 0; x--)
{
*indexes=ScaleQuantumToIndex(q->red);
q++;
indexes++;
}
if (!SyncImagePixels(image))
break;
}
image->is_grayscale=True;
return;
}
}
if (optimize_colormap)
{
/*
Sort and compact the colormap
*/
/*
Allocate memory for colormap index
*/
if (colormap_index == (int *) NULL)
{
colormap_index=MagickAllocateArray(int *,MaxColormapSize,sizeof(int));
if (colormap_index == (int *) NULL)
{
ThrowException3(&image->exception,ResourceLimitError,
MemoryAllocationFailed,UnableToSortImageColormap);
return;
}
}
/*
Assign index values to colormap entries.
*/
for (i=0; i < image->colors; i++)
image->colormap[i].opacity=(unsigned short) i;
/*
Sort image colormap by increasing intensity.
*/
qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
IntensityCompare);
/*
Create mapping between original indexes and reduced/sorted
colormap.
*/
{
PixelPacket
*new_colormap;
int
j;
new_colormap=MagickAllocateMemory(PixelPacket *,image->colors*sizeof(PixelPacket));
if (new_colormap == (PixelPacket *) NULL)
{
MagickFreeMemory(colormap_index);
ThrowException3(&image->exception,ResourceLimitError,
MemoryAllocationFailed,UnableToSortImageColormap);
return;
}
j=0;
new_colormap[j]=image->colormap[0];
for (i=0; i < image->colors; i++)
{
if (NotColorMatch(&new_colormap[j],&image->colormap[i]))
{
j++;
new_colormap[j]=image->colormap[i];
}
colormap_index[image->colormap[i].opacity]=j;
}
image->colors=j+1;
MagickFreeMemory(image->colormap);
image->colormap=new_colormap;
}
/*
Reassign image colormap indexes
*/
for (y=0; y < (long) image->rows; y++)
{
q=GetImagePixels(image,0,y,image->columns,1);
if (q == (PixelPacket *) NULL)
break;
indexes=AccessMutableIndexes(image);
for (x=(long) image->columns; x > 0; x--)
{
*indexes=colormap_index[*indexes];
indexes++;
}
if (!SyncImagePixels(image))
break;
}
MagickFreeMemory(colormap_index);
}
image->is_monochrome=IsMonochromeImage(image,&image->exception);
image->is_grayscale=True;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ H i l b e r t C u r v e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% HilbertCurve() s a space filling curve that visits every point in a square
% grid with any power of 2. Hilbert is useful in dithering due to the
% coherence between neighboring pixels. Here, the quantization error is
% distributed along the Hilbert curve.
%
% The format of the HilbertCurve method is:
%
% void HilbertCurve(CubeInfo *cube_info,Image *image,
% const unsigned long level,const unsigned int direction)
%
% A description of each parameter follows.
%
% o cube_info: A pointer to the Cube structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
% o direction: This unsigned direction describes which direction
% to move to next to follow the Hilbert curve.
%
%
*/
static void HilbertCurve(CubeInfo *cube_info,Image *image,
const unsigned long level,const unsigned int direction)
{
if (level == 1)
{
switch (direction)
{
case WestGravity:
{
(void) Dither(cube_info,image,EastGravity);
(void) Dither(cube_info,image,SouthGravity);
(void) Dither(cube_info,image,WestGravity);
break;
}
case EastGravity:
{
(void) Dither(cube_info,image,WestGravity);
(void) Dither(cube_info,image,NorthGravity);
(void) Dither(cube_info,image,EastGravity);
break;
}
case NorthGravity:
{
(void) Dither(cube_info,image,SouthGravity);
(void) Dither(cube_info,image,EastGravity);
(void) Dither(cube_info,image,NorthGravity);
break;
}
case SouthGravity:
{
(void) Dither(cube_info,image,NorthGravity);
(void) Dither(cube_info,image,WestGravity);
(void) Dither(cube_info,image,SouthGravity);
break;
}
default:
break;
}
return;
}
switch (direction)
{
case WestGravity:
{
HilbertCurve(cube_info,image,level-1,NorthGravity);
(void) Dither(cube_info,image,EastGravity);
HilbertCurve(cube_info,image,level-1,WestGravity);
(void) Dither(cube_info,image,SouthGravity);
HilbertCurve(cube_info,image,level-1,WestGravity);
(void) Dither(cube_info,image,WestGravity);
HilbertCurve(cube_info,image,level-1,SouthGravity);
break;
}
case EastGravity:
{
HilbertCurve(cube_info,image,level-1,SouthGravity);
(void) Dither(cube_info,image,WestGravity);
HilbertCurve(cube_info,image,level-1,EastGravity);
(void) Dither(cube_info,image,NorthGravity);
HilbertCurve(cube_info,image,level-1,EastGravity);
(void) Dither(cube_info,image,EastGravity);
HilbertCurve(cube_info,image,level-1,NorthGravity);
break;
}
case NorthGravity:
{
HilbertCurve(cube_info,image,level-1,WestGravity);
(void) Dither(cube_info,image,SouthGravity);
HilbertCurve(cube_info,image,level-1,NorthGravity);
(void) Dither(cube_info,image,EastGravity);
HilbertCurve(cube_info,image,level-1,NorthGravity);
(void) Dither(cube_info,image,NorthGravity);
HilbertCurve(cube_info,image,level-1,EastGravity);
break;
}
case SouthGravity:
{
HilbertCurve(cube_info,image,level-1,EastGravity);
(void) Dither(cube_info,image,NorthGravity);
HilbertCurve(cube_info,image,level-1,SouthGravity);
(void) Dither(cube_info,image,WestGravity);
HilbertCurve(cube_info,image,level-1,SouthGravity);
(void) Dither(cube_info,image,SouthGravity);
HilbertCurve(cube_info,image,level-1,WestGravity);
break;
}
default:
break;
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M a p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MapImage() replaces the colors of an image with the closest color from a
% reference image.
%
% The format of the MapImage method is:
%
% unsigned int MapImage(Image *image,const Image *map_image,
% const unsigned int dither)
%
% A description of each parameter follows:
%
% o image: Specifies a pointer to an Image structure.
%
% o map_image: Specifies a pointer to an Image structure. Reduce
% image to a set of colors represented by this image.
%
% o dither: Set this integer value to something other than zero to
% dither the quantized image.
%
%
*/
MagickExport MagickPassFail MapImage(Image *image,const Image *map_image,
const unsigned int dither)
{
CubeInfo
*cube_info;
QuantizeInfo
quantize_info;
MagickPassFail
status=MagickPass;
/*
Initialize color cube.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
assert(map_image != (Image *) NULL);
assert(map_image->signature == MagickSignature);
GetQuantizeInfo(&quantize_info);
quantize_info.dither=dither;
quantize_info.colorspace=
image->matte ? TransparentColorspace : RGBColorspace;
cube_info=GetCubeInfo(&quantize_info,MaxTreeDepth);
if (cube_info == (CubeInfo *) NULL)
ThrowBinaryException3(ResourceLimitError,MemoryAllocationFailed,
UnableToMapImage);
status=ClassifyImageColors(cube_info,map_image,&image->exception);
if (status != MagickFail)
{
/*
Classify image colors from the reference image.
*/
quantize_info.number_colors=cube_info->colors;
status=AssignImageColors(cube_info,image);
}
DestroyCubeInfo(cube_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M a p I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MapImages() replaces the colors of a sequence of images with the closest
% color from a reference image. If the reference image does not contain a
% colormap, then a colormap will be created based on existing colors in the
% reference image. The order and number of colormap entries does not match
% the reference image. If the order and number of colormap entries needs to
% match the reference image, then the ReplaceImageColormap() function may be
% used after invoking MapImages() in order to apply the reference colormap.
%
% The format of the MapImage method is:
%
% unsigned int MapImages(Image *images,Image *map_image,
% const unsigned int dither)
%
% A description of each parameter follows:
%
% o image: Specifies a pointer to a set of Image structures.
%
% o map_image: Specifies a pointer to an Image structure. Reduce
% image to a set of colors represented by this image.
%
% o dither: Set this integer value to something other than zero to
% dither the quantized image.
%
%
*/
MagickExport MagickPassFail MapImages(Image *images,const Image *map_image,
const unsigned int dither)
{
CubeInfo
*cube_info;
Image
*image;
QuantizeInfo
quantize_info;
MagickPassFail
status;
assert(images != (Image *) NULL);
assert(images->signature == MagickSignature);
GetQuantizeInfo(&quantize_info);
quantize_info.dither=dither;
image=images;
if (map_image == (Image *) NULL)
{
/*
Create a global colormap for an image sequence.
*/
for ( ; image != (Image *) NULL; image=image->next)
if (image->matte)
quantize_info.colorspace=TransparentColorspace;
status=QuantizeImages(&quantize_info,images);
return(status);
}
/*
Classify image colors from the reference image.
*/
cube_info=GetCubeInfo(&quantize_info,8);
if (cube_info == (CubeInfo *) NULL)
ThrowBinaryException3(ResourceLimitError,MemoryAllocationFailed,
UnableToMapImageSequence);
status=ClassifyImageColors(cube_info,map_image,&image->exception);
if (status != MagickFail)
{
/*
Classify image colors from the reference image.
*/
quantize_info.number_colors=cube_info->colors;
for (image=images; image != (Image *) NULL; image=image->next)
{
quantize_info.colorspace=image->matte ? TransparentColorspace :
RGBColorspace;
status=AssignImageColors(cube_info,image);
if (status == MagickFail)
break;
}
}
DestroyCubeInfo(cube_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% O r d e r e d D i t h e r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OrderedDitherImage() uses the ordered dithering technique of reducing color
% images to monochrome using positional information to retain as much
% information as possible.
%
% The format of the OrderedDitherImage method is:
%
% unsigned int OrderedDitherImage(Image *image)
%
% A description of each parameter follows.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
%
*/
MagickExport MagickPassFail OrderedDitherImage(Image *image)
{
#define DitherImageText "[%s] Ordered dither..."
static Quantum
DitherMatrix[8][8] =
{
{ 0, 192, 48, 240, 12, 204, 60, 252 },
{ 128, 64, 176, 112, 140, 76, 188, 124 },
{ 32, 224, 16, 208, 44, 236, 28, 220 },
{ 160, 96, 144, 80, 172, 108, 156, 92 },
{ 8, 200, 56, 248, 4, 196, 52, 244 },
{ 136, 72, 184, 120, 132, 68, 180, 116 },
{ 40, 232, 24, 216, 36, 228, 20, 212 },
{ 168, 104, 152, 88, 164, 100, 148, 84 }
};
IndexPacket
index;
long
y;
register IndexPacket
*indexes;
register long
x;
register PixelPacket
*q;
MagickPassFail
status=MagickPass;
/*
Initialize colormap.
*/
(void) NormalizeImage(image);
if (!AllocateImageColormap(image,2))
ThrowBinaryException3(ResourceLimitError,MemoryAllocationFailed,
UnableToDitherImage);
/*
Dither image with the ordered dithering technique.
*/
for (y=0; y < (long) image->rows; y++)
{
q=GetImagePixels(image,0,y,image->columns,1);
if (q == (PixelPacket *) NULL)
{
status=MagickFail;
break;
}
indexes=AccessMutableIndexes(image);
for (x=0; x < (long) image->columns; x++)
{
index=(Quantum) (PixelIntensityToQuantum(q) >
ScaleCharToQuantum(DitherMatrix[y & 0x07][x & 0x07]) ? 1 : 0);
indexes[x]=index;
q->red=image->colormap[index].red;
q->green=image->colormap[index].green;
q->blue=image->colormap[index].blue;
q++;
}
if (!SyncImagePixels(image))
{
status=MagickFail;
break;
}
if (QuantumTick(y,image->rows))
if (!MagickMonitorFormatted(y,image->rows,&image->exception,
DitherImageText,image->filename))
{
status=MagickFail;
break;
}
}
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ P r u n e C h i l d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PruneChild() deletes the given node and merges its statistics into its
% parent.
%
% The format of the PruneSubtree method is:
%
% PruneChild(CubeInfo *cube_info,const NodeInfo *node_info)
%
% A description of each parameter follows.
%
% o cube_info: A pointer to the Cube structure.
%
% o node_info: pointer to node in color cube tree that is to be pruned.
%
%
*/
static void PruneChild(CubeInfo *cube_info,const NodeInfo *node_info)
{
NodeInfo
*parent;
register unsigned int
id;
/*
Traverse any children.
*/
for (id=0; id < MaxTreeDepth; id++)
if (node_info->child[id] != (NodeInfo *) NULL)
PruneChild(cube_info,node_info->child[id]);
/*
Merge color statistics into parent.
*/
parent=node_info->parent;
parent->number_unique+=node_info->number_unique;
parent->total_red+=node_info->total_red;
parent->total_green+=node_info->total_green;
parent->total_blue+=node_info->total_blue;
parent->child[node_info->id]=(NodeInfo *) NULL;
cube_info->nodes--;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ P r u n e L e v e l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PruneLevel() deletes all nodes at the bottom level of the color tree merging
% their color statistics into their parent node.
%
% The format of the PruneLevel method is:
%
% PruneLevel(CubeInfo *cube_info,const NodeInfo *node_info)
%
% A description of each parameter follows.
%
% o cube_info: A pointer to the Cube structure.
%
% o node_info: pointer to node in color cube tree that is to be pruned.
%
%
*/
static void PruneLevel(CubeInfo *cube_info,const NodeInfo *node_info)
{
register unsigned int
id;
/*
Traverse any children.
*/
for (id=0; id < MaxTreeDepth; id++)
if (node_info->child[id] != (NodeInfo *) NULL)
PruneLevel(cube_info,node_info->child[id]);
if (node_info->level == cube_info->depth)
PruneChild(cube_info,node_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ P r u n e T o C u b e D e p t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PruneToCubeDepth() deletes any nodes ar a depth greater than
% cube_info->depth while merging their color statistics into their parent
% node.
%
% The format of the PruneToCubeDepth method is:
%
% PruneToCubeDepth(CubeInfo *cube_info,const NodeInfo *node_info)
%
% A description of each parameter follows.
%
% o cube_info: A pointer to the Cube structure.
%
% o node_info: pointer to node in color cube tree that is to be pruned.
%
%
*/
static void PruneToCubeDepth(CubeInfo *cube_info,const NodeInfo *node_info)
{
register unsigned int
id;
/*
Traverse any children.
*/
for (id=0; id < MaxTreeDepth; id++)
if (node_info->child[id] != (NodeInfo *) NULL)
PruneToCubeDepth(cube_info,node_info->child[id]);
if (node_info->level > cube_info->depth)
PruneChild(cube_info,node_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% Q u a n t i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% QuantizeImage() analyzes the colors within a reference image and chooses a
% fixed number of colors to represent the image. The goal of the algorithm
% is to minimize the color difference between the input and output image while
% minimizing the processing time.
%
% The format of the QuantizeImage method is:
%
% unsigned int QuantizeImage(const QuantizeInfo *quantize_info,
% Image *image)
%
% A description of each parameter follows:
%
% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
%
% o image: Specifies a pointer to an Image structure.
%
*/
MagickExport MagickPassFail QuantizeImage(const QuantizeInfo *quantize_info,
Image *image)
{
CubeInfo
*cube_info;
MagickPassFail
status;
unsigned long
depth,
number_colors;
assert(quantize_info != (const QuantizeInfo *) NULL);
assert(quantize_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
number_colors=quantize_info->number_colors;
if (number_colors == 0)
number_colors=MaxColormapSize;
if (number_colors > MaxColormapSize)
number_colors=MaxColormapSize;
/*
For grayscale images, use a fast translation to PseudoClass,
which assures that the maximum number of colors is equal to, or
less than MaxColormapSize.
*/
if (IsGrayColorspace(quantize_info->colorspace))
(void) TransformColorspace(image,quantize_info->colorspace);
if (IsGrayImage(image,&image->exception))
GrayscalePseudoClassImage(image,True);
/*
If the image colors do not require further reduction, then simply
return.
*/
if ((image->storage_class == PseudoClass) &&
(image->colors <= number_colors))
return(MagickPass);
depth=quantize_info->tree_depth;
if (depth == 0)
{
unsigned long
colors;
/*
Depth of color tree is: Log4(colormap size)+2.
*/
colors=number_colors;
for (depth=1; colors != 0; depth++)
colors>>=2;
if (quantize_info->dither)
depth--;
if (image->storage_class == PseudoClass)
depth+=2;
}
/*
Initialize color cube.
*/
cube_info=GetCubeInfo(quantize_info,depth);
if (cube_info == (CubeInfo *) NULL)
ThrowBinaryException3(ResourceLimitError,
MemoryAllocationFailed,UnableToQuantizeImage);
if (quantize_info->colorspace != RGBColorspace)
(void) TransformColorspace(image,quantize_info->colorspace);
status=ClassifyImageColors(cube_info,image,&image->exception);
if (status != MagickFail)
{
/*
Reduce the number of colors in the image.
*/
ReduceImageColors(image->filename,cube_info,number_colors,&image->exception);
status=AssignImageColors(cube_info,image);
if (quantize_info->colorspace != RGBColorspace)
(void) TransformColorspace(image,quantize_info->colorspace);
}
DestroyCubeInfo(cube_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% Q u a n t i z e I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% QuantizeImages() analyzes the colors within a set of reference images and
% chooses a fixed number of colors to represent the set. The goal of the
% algorithm is to minimize the color difference between the input and output
% images while minimizing the processing time.
%
% The format of the QuantizeImages method is:
%
% unsigned int QuantizeImages(const QuantizeInfo *quantize_info,
% Image *images)
%
% A description of each parameter follows:
%
% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
%
% o images: Specifies a pointer to a list of Image structures.
%
%
*/
MagickExport MagickPassFail QuantizeImages(const QuantizeInfo *quantize_info,
Image *images)
{
CubeInfo
*cube_info;
int
depth;
MonitorHandler
handler;
Image
*image;
register long
i;
unsigned int
status;
unsigned long
number_colors,
number_images;
assert(quantize_info != (const QuantizeInfo *) NULL);
assert(quantize_info->signature == MagickSignature);
assert(images != (Image *) NULL);
assert(images->signature == MagickSignature);
if (images->next == (Image *) NULL)
{
/*
Handle a single image with QuantizeImage.
*/
status=QuantizeImage(quantize_info,images);
return(status);
}
status=False;
image=images;
number_colors=quantize_info->number_colors;
if (number_colors == 0)
number_colors=MaxColormapSize;
if (number_colors > MaxColormapSize)
number_colors=MaxColormapSize;
depth=quantize_info->tree_depth;
if (depth == 0)
{
int
pseudo_class;
unsigned long
colors;
/*
Depth of color tree is: Log4(colormap size)+2.
*/
colors=number_colors;
for (depth=1; colors != 0; depth++)
colors>>=2;
if (quantize_info->dither)
depth--;
pseudo_class=True;
for (image=images; image != (Image *) NULL; image=image->next)
pseudo_class|=(image->storage_class == PseudoClass);
if (pseudo_class)
depth+=2;
}
/*
Initialize color cube.
*/
cube_info=GetCubeInfo(quantize_info,depth);
if (cube_info == (CubeInfo *) NULL)
ThrowBinaryException3(ResourceLimitError,MemoryAllocationFailed,
UnableToQuantizeImageSequence);
image=images;
for (i=0; image != (Image *) NULL; i++)
{
if (quantize_info->colorspace != RGBColorspace)
(void) TransformColorspace(image,quantize_info->colorspace);
image=image->next;
}
number_images=i;
image=images;
for (i=0; image != (Image *) NULL; i++)
{
handler=SetMonitorHandler((MonitorHandler) NULL);
status=ClassifyImageColors(cube_info,image,&image->exception);
if (status == MagickFail)
break;
image=image->next;
(void) SetMonitorHandler(handler);
if ((image != (Image *) NULL) &&
(!MagickMonitorFormatted(i,number_images,&image->exception,
ClassifyImageText,image->filename)))
break;
}
if (status != MagickFail)
{
/*
Reduce the number of colors in an image sequence.
*/
ReduceImageColors(image->filename,cube_info,number_colors,&image->exception);
image=images;
for (i=0; image != (Image *) NULL; i++)
{
handler=SetMonitorHandler((MonitorHandler) NULL);
status=AssignImageColors(cube_info,image);
if (status == MagickFail)
break;
if (quantize_info->colorspace != RGBColorspace)
(void) TransformColorspace(image,quantize_info->colorspace);
image=image->next;
(void) SetMonitorHandler(handler);
if ((image != (Image *) NULL) &&
(!MagickMonitorFormatted(i,number_images,&image->exception,
AssignImageText,image->filename)))
{
status=MagickFail;
break;
}
}
}
DestroyCubeInfo(cube_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e d u c e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Reduce() traverses the color cube tree and prunes any node whose
% quantization error falls below a particular threshold.
%
% The format of the Reduce method is:
%
% Reduce(CubeInfo *cube_info,const NodeInfo *node_info)
%
% A description of each parameter follows.
%
% o cube_info: A pointer to the Cube structure.
%
% o node_info: pointer to node in color cube tree that is to be pruned.
%
%
*/
static void Reduce(CubeInfo *cube_info,const NodeInfo *node_info)
{
register unsigned int
id;
/*
Traverse any children.
*/
for (id=0; id < MaxTreeDepth; id++)
if (node_info->child[id] != (NodeInfo *) NULL)
Reduce(cube_info,node_info->child[id]);
if (node_info->quantize_error <= cube_info->pruning_threshold)
PruneChild(cube_info,node_info);
else
{
/*
Find minimum pruning threshold.
*/
if (node_info->number_unique > 0)
cube_info->colors++;
if (node_info->quantize_error < cube_info->next_threshold)
cube_info->next_threshold=node_info->quantize_error;
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e d u c e I m a g e C o l o r s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReduceImageColors() repeatedly prunes the tree until the number of nodes
% with n2 > 0 is less than or equal to the maximum number of colors allowed
% in the output image. On any given iteration over the tree, it selects
% those nodes whose E value is minimal for pruning and merges their
% color statistics upward. It uses a pruning threshold, Ep, to govern
% node selection as follows:
%
% Ep = 0
% while number of nodes with (n2 > 0) > required maximum number of colors
% prune all nodes such that E <= Ep
% Set Ep to minimum E in remaining nodes
%
% This has the effect of minimizing any quantization error when merging
% two nodes together.
%
% When a node to be pruned has offspring, the pruning procedure invokes
% itself recursively in order to prune the tree from the leaves upward.
% n2, Sr, Sg, and Sb in a node being pruned are always added to the
% corresponding data in that node's parent. This retains the pruned
% node's color characteristics for later averaging.
%
% For each node, n2 pixels exist for which that node represents the
% smallest volume in RGB space containing those pixel's colors. When n2
% > 0 the node will uniquely define a color in the output image. At the
% beginning of reduction, n2 = 0 for all nodes except a the leaves of
% the tree which represent colors present in the input image.
%
% The other pixel count, n1, indicates the total number of colors
% within the cubic volume which the node represents. This includes n1 -
% n2 pixels whose colors should be defined by nodes at a lower level in
% the tree.
%
% The format of the ReduceImageColors method is:
%
% ReduceImageColors(const char *filename, CubeInfo *cube_info,
% const unsigned int number_colors, ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o filename: Filename for use in progress messages.
%
% o cube_info: A pointer to the Cube structure.
%
% o number_colors: This integer value indicates the maximum number of
% colors in the quantized image or colormap. The actual number of
% colors allocated to the colormap may be less than this value, but
% never more.
%
% o exception: Return any errors or warnings in this structure.
%
*/
static void ReduceImageColors(const char *filename,CubeInfo *cube_info,
const unsigned long number_colors,ExceptionInfo *exception)
{
#define ReduceImageText "[%s] Reduce colors: %lu..."
unsigned int
status;
unsigned long
span;
span=cube_info->colors;
cube_info->next_threshold=0.0;
while (cube_info->colors > number_colors)
{
cube_info->pruning_threshold=cube_info->next_threshold;
cube_info->next_threshold=cube_info->root->quantize_error-1;
cube_info->colors=0;
Reduce(cube_info,cube_info->root);
status=MagickMonitorFormatted(span-cube_info->colors,
span-number_colors+1,exception,
ReduceImageText,
filename,
number_colors);
if (status == False)
break;
}
}
|
thadguidry/incubator-hop | plugins/transforms/dynamicsqlrow/src/main/java/org/apache/hop/pipeline/transforms/dynamicsqlrow/DynamicSqlRow.java | <filename>plugins/transforms/dynamicsqlrow/src/main/java/org/apache/hop/pipeline/transforms/dynamicsqlrow/DynamicSqlRow.java
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hop.pipeline.transforms.dynamicsqlrow;
import org.apache.hop.core.Const;
import org.apache.hop.core.database.Database;
import org.apache.hop.core.exception.HopException;
import org.apache.hop.core.row.IRowMeta;
import org.apache.hop.core.row.IValueMeta;
import org.apache.hop.core.row.RowDataUtil;
import org.apache.hop.core.util.Utils;
import org.apache.hop.i18n.BaseMessages;
import org.apache.hop.pipeline.Pipeline;
import org.apache.hop.pipeline.PipelineMeta;
import org.apache.hop.pipeline.transform.BaseTransform;
import org.apache.hop.pipeline.transform.ITransform;
import org.apache.hop.pipeline.transform.TransformMeta;
import java.sql.ResultSet;
/**
* Run dynamic SQL. SQL is defined in a field.
*/
public class DynamicSqlRow extends BaseTransform<DynamicSqlRowMeta, DynamicSqlRowData>
implements ITransform<DynamicSqlRowMeta, DynamicSqlRowData> {
private static final Class<?> PKG = DynamicSqlRowMeta.class; // For Translator
public DynamicSqlRow(
TransformMeta transformMeta,
DynamicSqlRowMeta meta,
DynamicSqlRowData data,
int copyNr,
PipelineMeta pipelineMeta,
Pipeline pipeline) {
super(transformMeta, meta, data, copyNr, pipelineMeta, pipeline);
}
private synchronized void lookupValues(IRowMeta rowMeta, Object[] rowData) throws HopException {
boolean loadFromBuffer = true;
if (first) {
first = false;
data.outputRowMeta = rowMeta.clone();
meta.getFields(
data.outputRowMeta,
getTransformName(),
new IRowMeta[] {
meta.getTableFields(this),
},
null,
this,
metadataProvider);
loadFromBuffer = false;
}
if (log.isDetailed()) {
logDetailed(
BaseMessages.getString(PKG, "DynamicSQLRow.Log.CheckingRow")
+ rowMeta.getString(rowData));
}
// get dynamic SQL statement
String sqlTemp = getInputRowMeta().getString(rowData, data.indexOfSqlField);
String sql = null;
if (meta.isReplaceVariables()) {
sql = resolve(sqlTemp);
} else {
sql = sqlTemp;
}
if (log.isDebug()) {
logDebug(BaseMessages.getString(PKG, "DynamicSQLRow.Log.SQLStatement", sql));
}
if (meta.isQueryOnlyOnChange()) {
if (loadFromBuffer) {
if (data.previousSql != null && !data.previousSql.equals(sql)) {
loadFromBuffer = false;
}
}
// Save current parameters value as previous ones
data.previousSql = sql;
} else {
loadFromBuffer = false;
}
if (loadFromBuffer) {
incrementLinesInput();
if (!data.skipPreviousRow) {
Object[] newRow = RowDataUtil.resizeArray(rowData, data.outputRowMeta.size());
int newIndex = rowMeta.size();
IRowMeta addMeta = data.db.getReturnRowMeta();
// read from Buffer
for (int p = 0; p < data.previousrowbuffer.size(); p++) {
Object[] getBufferRow = data.previousrowbuffer.get(p);
for (int i = 0; i < addMeta.size(); i++) {
newRow[newIndex++] = getBufferRow[i];
}
putRow(data.outputRowMeta, data.outputRowMeta.cloneRow(newRow));
}
}
} else {
if (meta.isQueryOnlyOnChange()) {
data.previousrowbuffer.clear();
}
// Set the values on the prepared statement (for faster exec.)
ResultSet rs = data.db.openQuery(sql);
// Get a row from the database...
Object[] add = data.db.getRow(rs);
IRowMeta addMeta = data.db.getReturnRowMeta();
// Also validate the data types to make sure we've not place an incorrect template in the
// dialog...
//
if (add != null) {
int nrTemplateFields = data.outputRowMeta.size() - getInputRowMeta().size();
if (addMeta.size() != nrTemplateFields) {
throw new HopException(
BaseMessages.getString(
PKG,
"DynamicSQLRow.Exception.IncorrectNrTemplateFields",
nrTemplateFields,
addMeta.size(),
sql));
}
StringBuilder typeErrors = new StringBuilder();
for (int i = 0; i < addMeta.size(); i++) {
IValueMeta templateValueMeta = addMeta.getValueMeta(i);
IValueMeta outputValueMeta =
data.outputRowMeta.getValueMeta(getInputRowMeta().size() + i);
if (templateValueMeta.getType() != outputValueMeta.getType()) {
if (typeErrors.length() > 0) {
typeErrors.append(Const.CR);
}
typeErrors.append(
BaseMessages.getString(
PKG,
"DynamicSQLRow.Exception.TemplateReturnDataTypeError",
templateValueMeta.toString(),
outputValueMeta.toString()));
}
}
if (typeErrors.length() > 0) {
throw new HopException(typeErrors.toString());
}
}
incrementLinesInput();
int counter = 0;
while (add != null && (meta.getRowLimit() == 0 || counter < meta.getRowLimit())) {
counter++;
Object[] newRow = RowDataUtil.resizeArray(rowData, data.outputRowMeta.size());
int newIndex = rowMeta.size();
for (int i = 0; i < addMeta.size(); i++) {
newRow[newIndex++] = add[i];
}
// we have to clone, otherwise we only get the last new value
putRow(data.outputRowMeta, data.outputRowMeta.cloneRow(newRow));
if (meta.isQueryOnlyOnChange()) {
// add row to the previous rows buffer
data.previousrowbuffer.add(add);
data.skipPreviousRow = false;
}
if (log.isRowLevel()) {
logRowlevel(
BaseMessages.getString(PKG, "DynamicSQLRow.Log.PutoutRow")
+ data.outputRowMeta.getString(newRow));
}
// Get a new row
if (meta.getRowLimit() == 0 || counter < meta.getRowLimit()) {
add = data.db.getRow(rs);
incrementLinesInput();
}
}
// Nothing found? Perhaps we have to put something out after all?
if (counter == 0 && meta.isOuterJoin()) {
if (data.notfound == null) {
data.notfound = new Object[data.db.getReturnRowMeta().size()];
}
Object[] newRow = RowDataUtil.resizeArray(rowData, data.outputRowMeta.size());
int newIndex = rowMeta.size();
for (int i = 0; i < data.notfound.length; i++) {
newRow[newIndex++] = data.notfound[i];
}
putRow(data.outputRowMeta, newRow);
if (meta.isQueryOnlyOnChange()) {
// add row to the previous rows buffer
data.previousrowbuffer.add(data.notfound);
data.skipPreviousRow = false;
}
} else {
if (meta.isQueryOnlyOnChange() && counter == 0 && !meta.isOuterJoin()) {
data.skipPreviousRow = true;
}
}
if (data.db != null) {
data.db.closeQuery(rs);
}
}
}
@Override
public boolean processRow() throws HopException {
Object[] r = getRow(); // Get row from input rowset & set row busy!
if (r == null) { // no more input to be expected...
setOutputDone();
return false;
}
if (first) {
if (Utils.isEmpty(meta.getSqlFieldName())) {
throw new HopException(
BaseMessages.getString(PKG, "DynamicSQLRow.Exception.SQLFieldNameEmpty"));
}
if (Utils.isEmpty(meta.getSql())) {
throw new HopException(BaseMessages.getString(PKG, "DynamicSQLRow.Exception.SQLEmpty"));
}
// cache the position of the field
if (data.indexOfSqlField < 0) {
data.indexOfSqlField = getInputRowMeta().indexOfValue(meta.getSqlFieldName());
if (data.indexOfSqlField < 0) {
// The field is unreachable !
throw new HopException(
BaseMessages.getString(
PKG, "DynamicSQLRow.Exception.FieldNotFound", meta.getSqlFieldName()));
}
}
}
try {
lookupValues(getInputRowMeta(), r);
if (checkFeedback(getLinesRead())) {
if (log.isDetailed()) {
logDetailed(BaseMessages.getString(PKG, "DynamicSQLRow.Log.LineNumber") + getLinesRead());
}
}
} catch (HopException e) {
boolean sendToErrorRow = false;
String errorMessage = null;
if (getTransformMeta().isDoingErrorHandling()) {
sendToErrorRow = true;
errorMessage = e.toString();
} else {
logError(
BaseMessages.getString(PKG, "DynamicSQLRow.Log.ErrorInTransformRunning")
+ e.getMessage());
setErrors(1);
stopAll();
setOutputDone(); // signal end to receiver(s)
return false;
}
if (sendToErrorRow) {
// Simply add this row to the error row
putError(getInputRowMeta(), r, 1, errorMessage, null, "DynamicSQLRow001");
}
}
return true;
}
/** Stop the running query */
@Override
public void stopRunning() throws HopException {
if (data.db != null && !data.isCanceled) {
synchronized (data.db) {
data.db.cancelQuery();
}
setStopped(true);
data.isCanceled = true;
}
}
@Override
public boolean init() {
if (super.init()) {
if (meta.getConnection() != null) {
meta.setDatabaseMeta(getPipelineMeta().findDatabase(meta.getConnection(), variables));
}
if (meta.getDatabaseMeta() == null) {
logError(
BaseMessages.getString(
PKG, "DynmaicSQLRow.Init.ConnectionMissing", getTransformName()));
return false;
}
data.db = new Database(this, variables, meta.getDatabaseMeta());
try {
data.db.connect();
data.db.setCommit(100); // we never get a commit, but it just turns off auto-commit.
if (log.isDetailed()) {
logDetailed(BaseMessages.getString(PKG, "DynamicSQLRow.Log.ConnectedToDB"));
}
data.db.setQueryLimit(meta.getRowLimit());
return true;
} catch (HopException e) {
logError(BaseMessages.getString(PKG, "DynamicSQLRow.Log.DatabaseError") + e.getMessage());
if (data.db != null) {
data.db.disconnect();
}
}
}
return false;
}
@Override
public void dispose() {
if (data.db != null) {
data.db.disconnect();
}
super.dispose();
}
}
|
ScaledByDesign/cloudboost | home-ui/public/app.js | var __isDevelopment = false;
var isLocalhost = window.location.host.indexOf('localhost') > -1;
var isStaging = window.location.host.indexOf('staging') > -1;
if (isLocalhost || isStaging) {
__isDevelopment = true;
}
var serverURL = null,
dashboardURL = null;
var signUpURL = '';
var loginURL = '';
var tutorialURL = '';
var selfServerUrl = '';
if (isLocalhost) {
serverURL = "http://localhost:3000";
dashboardURL = "http://localhost:1440";
signUpURL = "http://localhost:1447/signup";
loginURL = "http://localhost:1447";
tutorialURL = "http://localhost:1446";
selfServerUrl = "http://localhost:1444";
} else if (isStaging) {
serverURL = "https://staging.cloudboost.io";
dashboardURL = "https://staging.cloudboost.io/dashboard";
signUpURL = "https://staging.cloudboost.io/accounts/signup";
loginURL = "https://staging.cloudboost.io/accounts";
tutorialURL = "https://staging-tutorials.cloudboost.io";
selfServerUrl = "https://staging.cloudboost.io";
} else {
serverURL = "https://cloudboost.io";
dashboardURL = "https://dashboard.cloudboost.io";
signUpURL = "https://accounts.cloudboost.io/signup";
loginURL = "https://accounts.cloudboost.io";
tutorialURL = "https://tutorials.cloudboost.io";
selfServerUrl = "https://cloudboost.io";
}
|
lvyitian/mapleall | mapleall/maple_ir/include/mpl_atomic.h | /*
* Copyright (c) [2020] Huawei Technologies Co., Ltd. All rights reserved.
*
* OpenArkCompiler is licensed under the Mulan Permissive Software License v2.
* You can use this software according to the terms and conditions of the MulanPSL - 2.0.
* You may obtain a copy of MulanPSL - 2.0 at:
*
* https://opensource.org/licenses/MulanPSL-2.0
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the MulanPSL - 2.0 for more details.
*/
#ifndef MAPLE_IR_INCLUDE_MPLATOMIC_H
#define MAPLE_IR_INCLUDE_MPLATOMIC_H
#include <cstdint>
#include "mpl_logging.h"
namespace maple {
enum class MemOrd : uint32_t {
kNotAtomic = 0,
#define ATTR(STR) STR,
#include "memory_order_attrs.def"
#undef ATTR
};
inline MemOrd MemOrdFromU32(uint32_t val) {
CHECK_FATAL(val <= 6 && val != 2, "Illegal number for MemOrd: %u", val);
static MemOrd tab[] = {
MemOrd::kNotAtomic,
MemOrd::memory_order_relaxed,
// memory_order_consume Disabled. Its semantics is debatable.
// We don't support it now, but reserve the number. Use memory_order_acquire instead.
MemOrd::memory_order_acquire, // padding entry
MemOrd::memory_order_acquire,
MemOrd::memory_order_release,
MemOrd::memory_order_acq_rel,
MemOrd::memory_order_seq_cst,
};
return tab[val];
}
inline bool MemOrdIsAcquire(MemOrd ord) {
static bool tab[] = {
false, // kNotAtomic
false, // memory_order_relaxed
true, // memory_order_consume
true, // memory_order_acquire
false, // memory_order_release
true, // memory_order_acq_rel
true, // memory_order_seq_cst
};
return tab[static_cast<uint32_t>(ord)];
}
inline bool MemOrdIsRelease(MemOrd ord) {
static bool tab[] = {
false, // kNotAtomic
false, // memory_order_relaxed
false, // memory_order_consume
false, // memory_order_acquire
true, // memory_order_release
true, // memory_order_acq_rel
true, // memory_order_seq_cst
};
return tab[static_cast<uint32_t>(ord)];
}
} // namespace maple
#endif // MAPLE_IR_INCLUDE_MPLATOMIC_H
|
lgalis/approval-api | lib/exceptions.rb | <gh_stars>0
module Exceptions
class ApprovalError < StandardError; end
end
|
torvigoes/Exercicios-Python3 | Mundo 1/ex025.py | <filename>Mundo 1/ex025.py
# PROCURANDO UMA STRING DENTRO DA OUTRA
nome = str(input('Digite seu nome: ').strip().lower())
print("silva" in nome.split()) # DESSA MANEIRA EVITA-SE QUE SILVA SEJA CONFUNDIDO DENTRO DE OUTRA STRING.
|
deathm1/zstmx | app/src/main/java/in/koshurtech/zstmx/tabFragments/tab13.java | <filename>app/src/main/java/in/koshurtech/zstmx/tabFragments/tab13.java<gh_stars>0
package in.koshurtech.zstmx.tabFragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import java.util.ArrayList;
import in.koshurtech.zstmx.R;
import in.koshurtech.zstmx.adapters.recyclerInfoViewAdapter;
import in.koshurtech.zstmx.database.entities.thermalInformation;
import in.koshurtech.zstmx.javaClasses.recyclerInfoView;
import in.koshurtech.zstmx.viewModels.thermalInfoViewModel;
public class tab13 extends Fragment {
RecyclerView recyclerView;
in.koshurtech.zstmx.adapters.sensorViewAdapter sensorViewAdapter;
SwipeRefreshLayout swipeRefreshLayout;
ArrayList<recyclerInfoView> recyclerInfoViewArrayList = new ArrayList<>();
ArrayList<thermalInformation> thermalInformationArrayList = new ArrayList<>();
in.koshurtech.zstmx.adapters.recyclerInfoViewAdapter recyclerInfoViewAdapter;
ProgressBar ProgressBar;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_tab14, container, false);
recyclerInfoViewArrayList.clear();
recyclerView = (RecyclerView) v.findViewById(R.id.thermalRV);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(),2);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerInfoViewAdapter = new recyclerInfoViewAdapter(recyclerInfoViewArrayList,getActivity().getApplicationContext(),getActivity());
recyclerView.setAdapter(recyclerInfoViewAdapter);
ProgressBar = (ProgressBar) v.findViewById(R.id.progressbarthermals);
thermalInfoViewModel = new ViewModelProvider(getActivity()).get(in.koshurtech.zstmx.viewModels.thermalInfoViewModel.class);
thermalInfoViewModel.setContext(getActivity().getApplicationContext());
thermalInfoViewModel.invoke();
try {
LiveData<String> out = thermalInfoViewModel.getThermalInfo();
out.observe(getActivity(), new Observer<String>() {
@Override
public void onChanged(String s) {
ProgressBar.setVisibility(View.INVISIBLE);
recyclerInfoViewArrayList.clear();
String[] data = s.split("--");
for(int i=0;i<data.length; i++){
String[] spl = data[i].split(":");
if(spl.length>1){
recyclerInfoViewArrayList.add(new recyclerInfoView(spl[1],spl[0]));
}
}
recyclerInfoViewAdapter.notifyDataSetChanged();
}
});
}
catch (Exception e){
e.printStackTrace();
}
return v;
}
thermalInfoViewModel thermalInfoViewModel;
} |
connorbrinton/gql | tests/fixtures/aws/fake_request.py | <filename>tests/fixtures/aws/fake_request.py
import pytest
class FakeRequest(object):
headers = None
def __init__(self, request_props=None):
if not isinstance(request_props, dict):
return
self.method = request_props.get("method")
self.url = request_props.get("url")
self.headers = request_props.get("headers")
self.context = request_props.get("context")
self.body = request_props.get("body")
@pytest.fixture
def fake_request_factory():
def _fake_request_factory(request_props=None):
return FakeRequest(request_props=request_props)
yield _fake_request_factory
|
Redman1037/clash-royale-api | src/models/user-model.js | const Model = require('../libraries/model');
const User = require('../schemas/user-schema');
const config = require('../config/config');
const username = config.ADMIN_USERNAME;
const password = <PASSWORD>.ADMIN_PASSWORD;
class UserModel extends Model {
constructor(SchemaModel) {
super(SchemaModel);
Promise.resolve(this.SchemaModel.findOne({ username })
.then(user => {
if (!user) {
this.create({ username, password }).execAsync();
}
}));
}
findOneWithPassword(query, populate) {
return this.SchemaModel.findOne(query)
.select('_id username password')
.populate(populate || '')
.execAsync();
}
}
module.exports = new UserModel(User);
|
frasieroh/quxer | src/templates/sequence.c | <reponame>frasieroh/quxer
#ifndef SEQUENCE_C
#define SEQUENCE_C
#include <stdlib.h>
#include <string.h>
#include "templates/sequence.h"
#include "templates/templates.h"
static char* generate_free_trees_string(pnode_t* node, uint32_t how_many);
static char* generate_set_children_string(pnode_t* node);
void write_sequence(FILE* file, writer_config_t* config, pnode_t* node)
/*
1 uint32_t current_position_<id> = start_<id>;
// for every child:
2 uint32_t start_<child_id> = current_position_<id>;
3 rnode_t* result_<child_id> = NULL;
... child parser ...
4 if (result_<child_id> == NULL) {
s ... free all previous rnode_ts ...
5 goto exit_<id>;
}
6 current_working_<id> = result_<child_id>->end;
// then (all children have succeeded):
7 result_<id> = malloc(sizeof(rnode_t) + sizeof(rnode_t*) * <node->num_data>);
8 result_<id>->flags = <flags_str>
9 result_<id>->type = SEQUENCE_T;
10 result_<id>->start = start_<id>;
11 result_<id>->end = result_<last_child_id>->end;
12 result_<id>->num_children = <node->num_children>;
result_<id>->children[0] = result_<child_0_id>;
result_<id>->children[1] = result_<child_1_id>;
s2 ...
13 result_<id>->id = <id>
14 exit_<id>:
*/
{
uint32_t id = node->id;
pnode_t* child_node;
uint32_t child_id;
fprintf(file,
/*1*/ "uint32_t current_position_%u = start_%u;\n",
/*1*/ id, id);
for (uint32_t i = 0; i < node->num_data; ++i) {
child_node = node->data.node[i];
child_id = child_node->id;
// set up start and return values
fprintf(file,
/*2*/ "uint32_t start_%u = current_position_%u;\n"
/*3*/ "rnode_t* result_%u = NULL;\n",
/*2*/ child_id, id,
/*3*/ child_id);
write_template(file, config, child_node);
// heap allocated
char* free_trees_string = generate_free_trees_string(node, i);
fprintf(file,
/*4*/ "if (result_%u == NULL) {\n"
/*s*/ "%s"
/*5*/ "goto exit_%u;\n"
"}\n",
/*4*/ child_id,
/*s*/ free_trees_string,
/*5*/ id);
// heap allocated
free(free_trees_string);
fprintf(file,
/*6*/ "current_position_%u = result_%u->end;\n",
/*6*/ id, child_id);
}
char* set_children_string = generate_set_children_string(node);
char* flags_str = generate_flags_str(node);
uint32_t last_child_id = node->data.node[node->num_data - 1]->id;
fprintf(file,
/*7*/ "result_%u = malloc(sizeof(rnode_t) + sizeof(rnode_t*) * %u);\n"
/*8*/ "result_%u->flags = %s"
/*9*/ "result_%u->type = SEQUENCE_T;\n"
/*10*/ "result_%u->start = start_%u;\n"
/*11*/ "result_%u->end = result_%u->end;\n"
/*12*/ "result_%u->num_children = %u;\n"
/*s2*/ "%s"
/*13*/ "result_%u->id = %u;\n"
/*14*/ "exit_%u:\n",
/*7*/ id, node->num_data,
/*8*/ id, flags_str,
/*9*/ id,
/*10*/ id, id,
/*11*/ id, last_child_id,
/*12*/ id, node->num_data,
/*s2*/ set_children_string,
/*13*/ id, id,
/*14*/ id);
free(set_children_string);
free(flags_str);
return;
}
char* generate_free_trees_string(pnode_t* node, uint32_t how_many)
{
char buf[128];
char* result = calloc(sizeof(char), 1);
uint32_t child_id;
for (uint32_t i = 0; i < how_many; ++i) {
child_id = node->data.node[i]->id;
sprintf(buf, "free_tree(result_%u, IS_CACHED);\n", child_id);
append_str(buf, &result);
}
return result;
}
char* generate_set_children_string(pnode_t* node)
{
char buf[128];
char* result = calloc(sizeof(char), 1);
uint32_t id = node->id;
uint32_t child_id;
for (uint32_t i = 0; i < node->num_data; ++i) {
child_id = node->data.node[i]->id;
sprintf(buf, "result_%u->children[%u] = result_%u;\n",
id, i, child_id);
append_str(buf, &result);
}
return result;
}
#endif
|
eid101/InjazErp | modules/org.openbravo.client.application/src/org/openbravo/client/application/event/WindowPersonalizationEventHandler.java | /*
*************************************************************************
* The contents of this file are subject to the Openbravo Public License
* Version 1.1 (the "License"), being the Mozilla Public License
* Version 1.1 with a permitted attribution clause; you may not use this
* file except in compliance with the License. You may obtain a copy of
* the License at http://www.openbravo.com/legal/license.html
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
* The Original Code is Openbravo ERP.
* The Initial Developer of the Original Code is Openbravo SLU
* All portions are Copyright (C) 2013 Openbravo SLU
* All Rights Reserved.
* Contributor(s): ______________________________________.
************************************************************************
*/
package org.openbravo.client.application.event;
import java.util.List;
import javax.enterprise.event.Observes;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.openbravo.base.exception.OBException;
import org.openbravo.base.model.Entity;
import org.openbravo.base.model.ModelProvider;
import org.openbravo.client.application.UIPersonalization;
import org.openbravo.client.kernel.event.EntityDeleteEvent;
import org.openbravo.client.kernel.event.EntityPersistenceEventObserver;
import org.openbravo.client.kernel.event.EntityUpdateEvent;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBCriteria;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.ConnectionProvider;
import org.openbravo.erpCommon.utility.Utility;
import org.openbravo.model.ad.domain.Preference;
import org.openbravo.model.ad.ui.Tab;
import org.openbravo.model.ad.ui.Window;
import org.openbravo.service.db.DalConnectionProvider;
public class WindowPersonalizationEventHandler extends EntityPersistenceEventObserver {
private static Entity[] entities = { ModelProvider.getInstance().getEntity(
UIPersonalization.ENTITY_NAME) };
protected Logger logger = Logger.getLogger(this.getClass());
@Override
protected Entity[] getObservedEntities() {
return entities;
}
public void onUpdate(@Observes EntityUpdateEvent event) {
if (!isValidEvent(event)) {
return;
}
final UIPersonalization uiPersonalization = (UIPersonalization) event.getTargetInstance();
String personalizationType = uiPersonalization.getType();
Tab personalizationTab = uiPersonalization.getTab();
Window personalizationWindow = uiPersonalization.getWindow();
if ("Window".equals(personalizationType) && (personalizationWindow == null)) {
String language = OBContext.getOBContext().getLanguage().getLanguage();
ConnectionProvider conn = new DalConnectionProvider(false);
throw new OBException(Utility.messageBD(conn, "OBUIAPP_WindowFieldMandatory", language));
}
if ("Form".equals(personalizationType) && (personalizationTab == null)) {
String language = OBContext.getOBContext().getLanguage().getLanguage();
ConnectionProvider conn = new DalConnectionProvider(false);
throw new OBException(Utility.messageBD(conn, "OBUIAPP_TabFieldMandatory", language));
}
}
public void onDelete(@Observes EntityDeleteEvent event) {
if (!isValidEvent(event)) {
return;
}
final UIPersonalization uiPersonalization = (UIPersonalization) event.getTargetInstance();
deleteDefaultViewPreferences(uiPersonalization);
}
/**
* Given an UIPersonalization, deletes the OBUIAPP_DefaultSavedView preferences that reference it
*/
private void deleteDefaultViewPreferences(UIPersonalization uiPersonalization) {
try {
List<Preference> preferenceList = this
.getDefaultViewPreferencesForUiPersonalization(uiPersonalization);
// don't do a client access check, the preference to delete might belong to another client
// (i.e. System)
OBContext.setAdminMode(false);
for (Preference preference : preferenceList) {
OBDal.getInstance().remove(preference);
}
} catch (Exception e) {
logger.error("Error while deleting a default view preference", e);
} finally {
OBContext.restorePreviousMode();
}
}
/**
* Given an UIPersonalization, returns the list of OBUIAPP_DefaultSavedView preferences that
* reference it
*/
private List<Preference> getDefaultViewPreferencesForUiPersonalization(
UIPersonalization uiPersonalization) {
OBCriteria<Preference> preferenceCriteria = OBDal.getInstance()
.createCriteria(Preference.class);
// filter out the preferences that do not store the default view
preferenceCriteria.add(Restrictions
.eq(Preference.PROPERTY_PROPERTY, "OBUIAPP_DefaultSavedView"));
// filter out the preferences whose default view is not the one being deleted
preferenceCriteria
.add(Restrictions.eq(Preference.PROPERTY_SEARCHKEY, uiPersonalization.getId()));
return preferenceCriteria.list();
}
}
|
seekersapp2013/new | node_modules/carbon-icons-svelte/lib/OverflowMenuHorizontal32/index.js | import OverflowMenuHorizontal32 from "./OverflowMenuHorizontal32.svelte";
export default OverflowMenuHorizontal32; |
ethankhall/pity.io | bootstrap/src/main/java/io/pity/bootstrap/HelpOutputGenerator.java | package io.pity.bootstrap;
import com.google.inject.Inject;
import io.pity.api.PropertyValueProvider;
import io.pity.api.environment.EnvironmentCollector;
import io.pity.api.execution.CommandExecutor;
import io.pity.api.reporting.ReportPublisher;
import io.pity.bootstrap.injection.ReflectionUtils;
import io.pity.bootstrap.provider.cli.CliArgumentProviderImpl;
import io.pity.bootstrap.provider.container.CommandExecutorContainer;
import io.pity.bootstrap.provider.container.EnvironmentCollectorContainer;
import io.pity.bootstrap.provider.container.FilteringContainer;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.IOException;
import java.util.Set;
import java.util.TreeSet;
/**
* Used to generate the help output.
*/
public class HelpOutputGenerator {
private final CommandExecutorContainer commandContainer;
private final EnvironmentCollectorContainer environmentContainer;
private final PropertyValueProvider propertyValueProvider;
@Inject
HelpOutputGenerator(CommandExecutorContainer commandExecutorContainer,
EnvironmentCollectorContainer environmentCollectorContainer,
PropertyValueProvider propertyValueProvider) {
this.commandContainer = commandExecutorContainer;
this.environmentContainer = environmentCollectorContainer;
this.propertyValueProvider = propertyValueProvider;
}
public String getHelpOutput(CliArgumentProviderImpl cliArgumentProvider) throws IOException {
StringBuilder usageBuilder = new StringBuilder();
usageBuilder.append(cliArgumentProvider.usage());
usageBuilder.append(String.format("\nPity Version: %s\n", propertyValueProvider.getProperty("pity.version")));
appendClasspath(usageBuilder);
appendReporters(usageBuilder);
appendCollectorData(usageBuilder, CommandExecutor.class.getSimpleName(), commandContainer);
appendCollectorData(usageBuilder, EnvironmentCollector.class.getSimpleName(), environmentContainer);
return usageBuilder.toString();
}
private void appendReporters(StringBuilder usageBuilder) {
Class<ReportPublisher> reportPublisherClass = ReportPublisher.class;
usageBuilder.append("\n").append(reportPublisherClass.getSimpleName()).append("'s Available\n");
for (Class<? extends ReportPublisher> reportClass : new ReflectionUtils().searchForClass(reportPublisherClass)) {
usageBuilder.append(String.format(" %s", reportClass.getName()));
usageBuilder.append("\n");
}
}
/**
* Appends the classpath to the help output
* @param usageBuilder Builder that should be used to add the help contents to
*/
private void appendClasspath(StringBuilder usageBuilder) {
String property = System.getProperty("java.class.path");
Set<String> urls = new TreeSet<String>();
for (String path : property.split(":")) {
File url = new File(path);
urls.add(url.getName());
}
usageBuilder.append(String.format("Classpath: %s\n", StringUtils.join(urls, ", ")));
}
/**
* Used to append {@link FilteringContainer} to the help output
*
* @param usageBuilder Where the output should be added to
* @param name title used for the {@link FilteringContainer}
* @param objects the {@link FilteringContainer}
* @throws IOException
*/
private void appendCollectorData(StringBuilder usageBuilder, String name, FilteringContainer objects) throws IOException {
usageBuilder.append("\n").append(name).append("'s Available\n");
for (Object object : objects.getAvailable()) {
usageBuilder.append(String.format(" %s\n", object.getClass().getName()));
}
for (Object object : objects.getFiltered()) {
usageBuilder.append(String.format(" %s - (excluded)\n", object.getClass().getName()));
}
}
}
|
cragkhit/elasticsearch | references/bcb_chosen_clones/selected#648404#66#81.java | private void detachFile(File file, Block b) throws IOException {
File tmpFile = volume.createDetachFile(b, file.getName());
try {
IOUtils.copyBytes(new FileInputStream(file), new FileOutputStream(tmpFile), 16 * 1024, true);
if (file.length() != tmpFile.length()) {
throw new IOException("Copy of file " + file + " size " + file.length() + " into file " + tmpFile + " resulted in a size of " + tmpFile.length());
}
FileUtil.replaceFile(tmpFile, file);
} catch (IOException e) {
boolean done = tmpFile.delete();
if (!done) {
DataNode.LOG.info("detachFile failed to delete temporary file " + tmpFile);
}
throw e;
}
}
|
mdhillmancmcl/TheWorldAvatar-CMCL-Fork | thermo/CoMoMath/src/main/java/uk/ac/cam/ceb/como/math/average/Mean.java | <reponame>mdhillmancmcl/TheWorldAvatar-CMCL-Fork<gh_stars>10-100
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package uk.ac.cam.ceb.como.math.average;
/**
*
* @author pb556
*/
public class Mean extends Average {
@Override
public double calculate(int[] values) throws Exception {
double[] val = new double[values.length];
for (int i = 0; i < values.length; i++) {
val[i] = (double) values[i];
}
return this.calculate(val);
}
@Override
public double calculate(long[] values) throws Exception {
double[] val = new double[values.length];
for (int i = 0; i < values.length; i++) {
val[i] = (double) values[i];
}
return this.calculate(val);
}
@Override
public double calculate(float[] values) throws Exception {
double[] val = new double[values.length];
for (int i = 0; i < values.length; i++) {
val[i] = (double) values[i];
}
return this.calculate(val);
}
@Override
public double calculate(double[] values) throws Exception {
double mean = 0;
for (int i = 0; i < values.length; i++) {
mean += values[i];
}
return mean / (double) values.length;
}
}
|
slawekjaranowski/bc-java | core/src/test/java/org/bouncycastle/crypto/test/ZucTest.java | package org.bouncycastle.crypto.test;
import org.bouncycastle.crypto.Mac;
import org.bouncycastle.crypto.StreamCipher;
import org.bouncycastle.crypto.engines.Zuc128CoreEngine;
import org.bouncycastle.crypto.engines.Zuc128Engine;
import org.bouncycastle.crypto.engines.Zuc256CoreEngine;
import org.bouncycastle.crypto.engines.Zuc256Engine;
import org.bouncycastle.crypto.macs.Zuc128Mac;
import org.bouncycastle.crypto.macs.Zuc256Mac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.encoders.Hex;
import org.bouncycastle.util.test.SimpleTest;
/**
* Test Cases for Zuc128 and Zuc256.
* Test Vectors taken from https://www.gsma.com/aboutus/wp-content/uploads/2014/12/eea3eia3zucv16.pdf for Zuc128
* and http://www.is.cas.cn/ztzl2016/zouchongzhi/201801/W020180126529970733243.pdf for Zuc256.
*/
public class ZucTest
extends SimpleTest
{
private static final int INT_SIZE = 32;
private static final int BYTE_SIZE = 8;
/**
* Test Keys and IV.
*/
private static final String KEY128_1 =
"00000000000000000000000000000000";
private static final String KEY128_2 =
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
private static final String KEY256_1 =
"00000000000000000000000000000000" +
"00000000000000000000000000000000";
private static final String KEY256_2 =
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
private static final String IV128_1 = "00000000000000000000000000000000";
private static final String IV128_2 = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
private static final String IV200_1 = "00000000000000000000000000000000000000000000000000";
private static final String IV200_2 = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF3F3F3F3F3F3F3F3F";
/**
* Define the bit limits for engines.
*/
private static final int ZUC256LIMIT = 20000;
private static final int ZUC128LIMIT = 65504;
public String getName()
{
return "Zuc";
}
public void performTest()
throws Exception
{
new Zuc128Test().testTheCipher();
new Zuc256Test().testTheCipher();
new Zuc128MacTest().testTheMac();
new Zuc256Mac32Test().testTheMac();
new Zuc256Mac64Test().testTheMac();
new Zuc256Mac128Test().testTheMac();
}
/**
* The TestCase.
*/
private static class TestCase
{
/**
* The testCase.
*/
private final String theKey;
private final String theIV;
private final String thePlainText;
private final String theExpected;
/**
* Constructor.
*
* @param pKey the key
* @param pIV the IV
* @param pExpected the expected results.
*/
TestCase(final String pKey,
final String pIV,
final String pExpected)
{
this(pKey, pIV, null, pExpected);
}
/**
* Constructor.
*
* @param pKey the key
* @param pIV the IV
* @param pPlain the plainText
* @param pExpected the expected results.
*/
TestCase(final String pKey,
final String pIV,
final String pPlain,
final String pExpected)
{
theKey = pKey;
theIV = pIV;
thePlainText = pPlain;
theExpected = pExpected;
}
}
/**
* Zuc128.
*/
class Zuc128Test
{
/**
* TestCases.
*/
private final TestCase TEST4 = new TestCase(KEY128_1, IV128_1,
"<KEY>"
);
private final TestCase TEST5 = new TestCase(KEY128_2, IV128_2,
"<KEY>"
);
/**
* Test cipher.
*/
void testTheCipher()
{
final Zuc128CoreEngine myEngine = new Zuc128Engine();
testCipher(myEngine, TEST4);
testCipher(myEngine, TEST5);
testStreamLimit(myEngine, TEST5, ZUC128LIMIT);
}
}
/**
* Zuc256.
*/
class Zuc256Test
{
/**
* TestCases.
*/
private final TestCase TEST4 = new TestCase(KEY256_1, IV200_1,
"<KEY>"
);
private final TestCase TEST5 = new TestCase(KEY256_2, IV200_2,
"3356cbaed1a1c18b6baa4ffe343f777c9e15128f251ab65b949f7b26ef7157f296dd2fa9df95e3ee7a5be02ec32ba585505af316c2f9ded27cdbd935e441ce11"
);
/**
* Test cipher.
*/
void testTheCipher()
{
final Zuc256CoreEngine myEngine = new Zuc256Engine();
testCipher(myEngine, TEST4);
testCipher(myEngine, TEST5);
testStreamLimit(myEngine, TEST5, ZUC256LIMIT);
}
}
/**
* Zuc128Mac.
*/
class Zuc128MacTest
{
/**
* TestCases.
*/
private final TestCase TEST1 = new TestCase(KEY128_1, IV128_1,
"508dd5ff"
);
private final TestCase TEST2 = new TestCase(KEY128_1, IV128_1,
"fbed4c12"
);
private final TestCase TEST3 = new TestCase(KEY128_2, IV128_2,
"55e01504"
);
private final TestCase TEST4 = new TestCase(KEY128_2, IV128_2,
"9ce9a0c4"
);
/**
* Test Mac.
*/
void testTheMac()
{
final Zuc128Mac myMac = new Zuc128Mac();
testMac(myMac, false, TEST1);
testMac(myMac, true, TEST2);
testMac(myMac, false, TEST3);
testMac(myMac, true, TEST4);
testMacLimit(myMac, TEST4, ZUC128LIMIT - (2 * INT_SIZE));
// reset without init().
Zuc128Mac xMac = new Zuc128Mac();
xMac.reset();
}
}
/**
* Zuc256Mac32.
*/
class Zuc256Mac32Test
{
/**
* TestCases.
*/
private final TestCase TEST1 = new TestCase(KEY256_1, IV200_1,
"9b972a74"
);
private final TestCase TEST2 = new TestCase(KEY256_1, IV200_1,
"8754f5cf"
);
private final TestCase TEST3 = new TestCase(KEY256_2, IV200_2,
"1f3079b4"
);
private final TestCase TEST4 = new TestCase(KEY256_2, IV200_2,
"5c7c8b88"
);
/**
* Test Mac.
*/
void testTheMac()
{
final Zuc256Mac myMac = new Zuc256Mac(32);
testMac(myMac, false, TEST1);
testMac(myMac, true, TEST2);
testMac(myMac, false, TEST3);
testMac(myMac, true, TEST4);
testMacLimit(myMac, TEST4, ZUC256LIMIT - (2 * myMac.getMacSize() * BYTE_SIZE));
// reset without init().
Zuc256Mac xMac = new Zuc256Mac(32);
xMac.reset();
}
}
/**
* Zuc256Mac64.
*/
class Zuc256Mac64Test
{
/**
* TestCases.
*/
private final TestCase TEST1 = new TestCase(KEY256_1, IV200_1,
"673e54990034d38c"
);
private final TestCase TEST2 = new TestCase(KEY256_1, IV200_1,
"130dc225e72240cc"
);
private final TestCase TEST3 = new TestCase(KEY256_2, IV200_2,
"8c71394d39957725"
);
private final TestCase TEST4 = new TestCase(KEY256_2, IV200_2,
"ea1dee544bb6223b"
);
/**
* Test Mac.
*/
void testTheMac()
{
final Zuc256Mac myMac = new Zuc256Mac(64);
testMac(myMac, false, TEST1);
testMac(myMac, true, TEST2);
testMac(myMac, false, TEST3);
testMac(myMac, true, TEST4);
testMacLimit(myMac, TEST4, ZUC256LIMIT - (2 * myMac.getMacSize() * BYTE_SIZE));
}
}
/**
* Zuc256Mac128.
*/
class Zuc256Mac128Test
{
/**
* TestCases.
*/
private final TestCase TEST1 = new TestCase(KEY256_1, IV200_1,
"d85e54bbcb9600967084c952a1654b26"
);
private final TestCase TEST2 = new TestCase(KEY256_1, IV200_1,
"df1e8307b31cc62beca1ac6f8190c22f"
);
private final TestCase TEST3 = new TestCase(KEY256_2, IV200_2,
"a35bb274b567c48b28319f111af34fbd"
);
private final TestCase TEST4 = new TestCase(KEY256_2, IV200_2,
"3a83b554be408ca5494124ed9d473205"
);
/**
* Test Mac.
*/
void testTheMac()
{
final Zuc256Mac myMac = new Zuc256Mac(128);
testMac(myMac, false, TEST1);
testMac(myMac, true, TEST2);
testMac(myMac, false, TEST3);
testMac(myMac, true, TEST4);
testMacLimit(myMac, TEST4, ZUC256LIMIT - (2 * myMac.getMacSize() * BYTE_SIZE));
}
}
/**
* Test the Cipher against the results.
*
* @param pCipher the cipher to test.
* @param pTestCase the testCase
*/
void testCipher(final StreamCipher pCipher,
final TestCase pTestCase)
{
/* Access the expected bytes */
final byte[] myExpected = Hex.decode(pTestCase.theExpected);
/* Create the output buffer */
final byte[] myOutput = new byte[myExpected.length];
/* Access plainText or nulls */
final byte[] myData = pTestCase.thePlainText != null
? Hex.decode(pTestCase.thePlainText)
: new byte[myExpected.length];
/* Access the key and the iv */
final KeyParameter myKey = new KeyParameter(Hex.decode(pTestCase.theKey));
final byte[] myIV = Hex.decode(pTestCase.theIV);
final ParametersWithIV myParms = new ParametersWithIV(myKey, myIV);
/* Initialise the cipher and create the keyStream */
pCipher.init(true, myParms);
pCipher.processBytes(myData, 0, myData.length, myOutput, 0);
/* Check the encryption */
isTrue("Encryption mismatch", Arrays.areEqual(myExpected, myOutput));
}
/**
* Test the Mac against the results.
*
* @param pMac the mac to test.
* @param pOnes use all ones as data?
* @param pTestCase the testCase
*/
void testMac(final Mac pMac,
final boolean pOnes,
final TestCase pTestCase)
{
/* Access the expected bytes */
final byte[] myExpected = Hex.decode(pTestCase.theExpected);
/* Create the output buffer and the data */
final byte[] myOutput = new byte[pMac.getMacSize()];
final byte[] myData = new byte[(pOnes ? 4000 : 400) / 8];
Arrays.fill(myData, (byte)(pOnes ? 0x11 : 0));
/* Access the key and the iv */
final KeyParameter myKey = new KeyParameter(Hex.decode(pTestCase.theKey));
final byte[] myIV = Hex.decode(pTestCase.theIV);
final ParametersWithIV myParms = new ParametersWithIV(myKey, myIV);
/* Initialise the cipher and create the keyStream */
pMac.init(myParms);
pMac.update(myData, 0, myData.length);
pMac.doFinal(myOutput, 0);
/* Check the mac */
isTrue("Mac mismatch", Arrays.areEqual(myExpected, myOutput));
/* Check doFinal reset */
pMac.update(myData, 0, myData.length);
pMac.doFinal(myOutput, 0);
isTrue("DoFinal Mac mismatch", Arrays.areEqual(myExpected, myOutput));
/* Check reset() */
pMac.update(myData, 0, myData.length);
pMac.reset();
pMac.update(myData, 0, myData.length);
pMac.doFinal(myOutput, 0);
isTrue("Reset Mac mismatch", Arrays.areEqual(myExpected, myOutput));
}
/**
* Test the Stream Cipher against the limit.
*
* @param pCipher the cipher to test.
* @param pTestCase the testCase
* @param pLimit the limit in bits.
*/
void testStreamLimit(final StreamCipher pCipher,
final TestCase pTestCase,
final int pLimit)
{
/* Check the limit is a whole number of integers */
isTrue("Invalid limit", (pLimit % INT_SIZE == 0));
final int myNumBytes = pLimit / BYTE_SIZE;
/* Create the maximum # of bytes */
final byte[] myData = new byte[myNumBytes];
final byte[] myOutput = new byte[myNumBytes];
/* Access the key and the iv */
final KeyParameter myKey = new KeyParameter(Hex.decode(pTestCase.theKey));
final byte[] myIV = Hex.decode(pTestCase.theIV);
final ParametersWithIV myParms = new ParametersWithIV(myKey, myIV);
/* Initialise the cipher and create the keyStream */
pCipher.init(true, myParms);
pCipher.processBytes(myData, 0, myData.length, myOutput, 0);
/* Check that next encryption throws exception */
try
{
pCipher.processBytes(myData, 0, 1, myOutput, 0);
fail("Limit Failure");
}
catch (IllegalStateException e)
{
/* OK */
}
}
/**
* Test the Mac against the limit.
*
* @param pMac the mac to test.
* @param pTestCase the testCase
* @param pLimit the limit in bits.
*/
void testMacLimit(final Mac pMac,
final TestCase pTestCase,
final int pLimit)
{
/* Check the limit is a whole numbet of integers */
isTrue("Invalid limit", (pLimit % INT_SIZE == 0));
final int myNumBytes = pLimit / BYTE_SIZE;
/* Create the maximum # of bytes */
final byte[] myData = new byte[myNumBytes];
final byte[] myOutput = new byte[myNumBytes];
/* Access the key and the iv */
final KeyParameter myKey = new KeyParameter(Hex.decode(pTestCase.theKey));
final byte[] myIV = Hex.decode(pTestCase.theIV);
final ParametersWithIV myParms = new ParametersWithIV(myKey, myIV);
/* Initialise the mac and create the result */
pMac.init(myParms);
pMac.update(myData, 0, myData.length);
pMac.doFinal(myOutput, 0);
/* Initialise the mac and process as much data as possible */
pMac.init(myParms);
pMac.update(myData, 0, myData.length);
/* We expect a failure on processing a further byte */
try
{
pMac.update(myData, 0, 1);
pMac.doFinal(myOutput, 0);
fail("Limit Failure");
}
catch (IllegalStateException e)
{
/* OK */
}
}
/**
* Main entry point.
*
* @param args the argyments
*/
public static void main(String[] args)
{
runTest(new ZucTest());
}
}
|
brucexia1/DesignPattern | src/designpattern/ClassAdapter.hpp | #pragma once
class ClassTarget
{
public:
ClassTarget();
virtual ~ClassTarget();
virtual void Request() = 0;
};
class ClassAdaptee
{
public:
ClassAdaptee();
~ClassAdaptee();
void SpecificRequest();
};
//通过private继承ClassAdaptee获得实现继承的效果,
//而通过public继承ClassTarget获得接口继承的效果。
//在 C++中的 public继承既是接口继承又是实现继承,因为子类在继承了父类后既可以
//对外提供父类中的接口操作,又可以获得父类的接口实现。
class ClassAdapter : public ClassTarget, private ClassAdaptee
{
public:
ClassAdapter(void);
~ClassAdapter(void);
void Request();
};
|
hyoo/p3_web | public/js/release/dijit/form/nls/id/ComboBox.js | <reponame>hyoo/p3_web
define(
"dijit/form/nls/id/ComboBox", ({
previousMessage: "Pilihan sebelumnya",
nextMessage: "Pilihan lain"
})
);
|
pancelor/necrobot | necrobot/test/asynctest.py | import asyncio
def async_test(loop):
def real_decorator(f):
def func_wrapper(*args, **kwargs):
coro = asyncio.coroutine(f)
future = coro(*args, **kwargs)
loop.run_until_complete(future)
return func_wrapper
return real_decorator
|
rahul-y/intermine | intermine/webapp/src/main/java/org/intermine/web/logic/query/QueryMonitor.java | <gh_stars>1-10
package org.intermine.web.logic.query;
/*
* Copyright (C) 2002-2019 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
/**
* Interface passed to SessionMethods runQuery method which is polled every so-often while the
* query runs in order to decide whether or not to cancel the query. Instances of this
* interface are used in conjunction with a periodic browser refresh to detect and act upon
* user cancellation (the user closing their browser window or navigating to a different page).
*
* @author <NAME>
*/
public interface QueryMonitor
{
/**
* Called intermittently while a query is run providing an opportunity to cancel
* the query.
*
* param results the Results object associated with the running query
* param request the http servlet request
* @return false if the query should be cancelled, otherwise true
*/
boolean shouldCancelQuery();
/**
* Called when the query has completed.
*/
void queryCompleted();
/**
* Called when the query stopped with an error. The error message should be
* in the session.
*/
void queryCancelledWithError();
/**
* Called when the query is cancelled. Usually as a result of shouldCancelQuery
* returning true.
*/
void queryCancelled();
}
|
sodero/clib2-1 | test_programs/network/client_server2/client.c | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
assert(sockfd != -1);
struct sockaddr_in saddr;
memset(&saddr, 0, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(6000);
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
int res = connect(sockfd, (struct sockaddr *) &saddr, sizeof(saddr));//Link to server
assert(res != -1);
while (1) {
char buff[128] = {0};
printf("Please Input:");
fgets(buff, 128, stdin);
if (strncmp(buff, "end", 3) == 0) {
break;
}
send(sockfd, buff, strlen(buff), 0);
memset(buff, 0, 128);
recv(sockfd, buff, 127, 0);
printf("RecvBuff:%s\n", buff);
printf("\n");
}
close(sockfd);
}
|
Ravi116/unimrcp-1.5.0 | libs/sofia-sip/libsofia-sip-ua/soa/test_soa.c | <reponame>Ravi116/unimrcp-1.5.0<filename>libs/sofia-sip/libsofia-sip-ua/soa/test_soa.c
/*
* This file is part of the Sofia-SIP package
*
* Copyright (C) 2005 Nokia Corporation.
*
* Contact: <NAME> <<EMAIL>>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
/**@CFILE test_soa.c
* @brief High-level tester for Sofia SDP Offer/Answer Engine
*
* @author <NAME> <<EMAIL>>
*
* @date Created: Wed Aug 17 12:12:12 EEST 2005 ppessi
*/
#include "config.h"
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#if HAVE_ALARM
#include <unistd.h>
#include <signal.h>
#endif
struct context;
#define SOA_MAGIC_T struct context
#include "sofia-sip/soa.h"
#include "sofia-sip/soa_tag.h"
#include "sofia-sip/soa_add.h"
#include <sofia-sip/sdp.h>
#include <sofia-sip/su_log.h>
#include <sofia-sip/sip_tag.h>
#include <s2_localinfo.h>
S2_LOCALINFO_STUBS();
extern su_log_t soa_log[];
char const name[] = "test_soa";
int tstflags = 0;
#define TSTFLAGS tstflags
#include <sofia-sip/tstdef.h>
#if HAVE_FUNC
#elif HAVE_FUNCTION
#define __func__ __FUNCTION__
#else
#define __func__ name
#endif
#define NONE ((void*)-1)
static char const *test_ifaces1[] = {
"eth0\0" "11.12.13.14\0" "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:a0ff:fe71:813\0" "fe80::21a:a0ff:fe71:813\0",
"eth1\0" "12.13.14.15\0" "fdf8:f53e:61e4::18:a0ff:fe71:814\0" "fe80::21a:a0ff:fe71:814\0",
"eth2\0" "192.168.2.15\0" "fc00:db20:35b:7399::5:a0ff:fe71:815\0" "fe80::21a:a0ff:fe71:815\0",
"lo0\0" "127.0.0.1\0" "::1\0",
NULL
};
int test_localinfo_replacement(void)
{
BEGIN();
su_localinfo_t *res, *li, hints[1];
int error, n;
struct results {
struct afresult { unsigned global, site, link, host; } ip6[1], ip4[1];
} results[1];
s2_localinfo_ifaces(test_ifaces1);
error = su_getlocalinfo(NULL, &res);
TEST(error, ELI_NOERROR);
TEST_1(res != NULL);
memset(results, 0, sizeof results);
for (li = res, n = 0; li; li = li->li_next) {
struct afresult *afr;
TEST_1(li->li_family == AF_INET || li->li_family == AF_INET6);
if (li->li_family == AF_INET)
afr = results->ip4;
else
afr = results->ip6;
if (li->li_scope == LI_SCOPE_GLOBAL)
afr->global++;
else if (li->li_scope == LI_SCOPE_SITE)
afr->site++;
else if (li->li_scope == LI_SCOPE_LINK)
afr->link++;
else if (li->li_scope == LI_SCOPE_HOST)
afr->host++;
n++;
}
TEST(n, 11);
TEST(results->ip4->global, 2);
TEST(results->ip4->site, 1);
TEST(results->ip4->link, 0);
TEST(results->ip4->host, 1);
#if SU_HAVE_IN6
TEST(results->ip6->global, 2);
TEST(results->ip6->site, 1);
TEST(results->ip6->link, 3);
TEST(results->ip6->host, 1);
#endif
su_freelocalinfo(res);
error = su_getlocalinfo(memset(hints, 0, sizeof hints), &res);
TEST(error, ELI_NOERROR);
TEST_1(res != NULL);
for (li = res, n = 0; li; li = li->li_next)
n++;
TEST(n, 11);
su_freelocalinfo(res);
hints->li_flags = LI_CANONNAME;
error = su_getlocalinfo(hints, &res);
TEST(error, ELI_NOERROR);
TEST_1(res != NULL);
for (li = res, n = 0; li; li = li->li_next) {
TEST_1(li->li_canonname != NULL);
n++;
}
TEST(n, 11);
su_freelocalinfo(res);
hints->li_flags = LI_IFNAME | LI_CANONNAME;
hints->li_ifname = "eth1";
error = su_getlocalinfo(hints, &res);
TEST(error, ELI_NOERROR);
TEST_1(res != NULL);
for (li = res, n = 0; li; li = li->li_next) {
TEST_1(li->li_canonname != NULL);
TEST_S(li->li_ifname, "eth1");
n++;
}
TEST(n, 3);
su_freelocalinfo(res);
s2_localinfo_teardown();
END();
}
/* ========================================================================= */
struct context
{
su_home_t home[1];
su_root_t *root;
struct {
soa_session_t *a;
soa_session_t *b;
} asynch;
soa_session_t *a;
soa_session_t *b;
soa_session_t *completed;
};
int test_api_completed(struct context *arg, soa_session_t *session)
{
return 0;
}
int test_api_errors(struct context *ctx)
{
BEGIN();
char const *phrase = NULL;
char const *null = NULL;
TEST_1(!soa_create("default", NULL, NULL));
TEST_1(!soa_clone(NULL, NULL, NULL));
TEST_VOID(soa_destroy(NULL));
TEST_1(-1 == soa_set_params(NULL, TAG_END()));
TEST_1(-1 == soa_get_params(NULL, TAG_END()));
TEST_1(!soa_get_paramlist(NULL, TAG_END()));
TEST(soa_error_as_sip_response(NULL, &phrase), 500);
TEST_S(phrase, "Internal Server Error");
TEST_1(soa_error_as_sip_reason(NULL));
TEST_1(!soa_media_features(NULL, 0, NULL));
TEST_1(!soa_sip_require(NULL));
TEST_1(!soa_sip_supported(NULL));
TEST_1(-1 == soa_remote_sip_features(NULL, &null, &null));
TEST_1(soa_set_capability_sdp(NULL, NULL, NULL, -1) < 0);
TEST_1(soa_set_remote_sdp(NULL, NULL, NULL, -1) < 0);
TEST_1(soa_set_user_sdp(NULL, NULL, NULL, -1) < 0);
TEST_1(soa_get_capability_sdp(NULL, NULL, NULL, NULL) < 0);
TEST_1(soa_get_remote_sdp(NULL, NULL, NULL, NULL) < 0);
TEST_1(soa_get_user_sdp(NULL, NULL, NULL, NULL) < 0);
TEST_1(soa_get_local_sdp(NULL, NULL, NULL, NULL) < 0);
TEST_1(-1 == soa_generate_offer(NULL, 0, test_api_completed));
TEST_1(-1 == soa_generate_answer(NULL, test_api_completed));
TEST_1(-1 == soa_process_answer(NULL, test_api_completed));
TEST_1(-1 == soa_process_reject(NULL, test_api_completed));
TEST(soa_activate(NULL, "both"), -1);
TEST(soa_deactivate(NULL, "both"), -1);
TEST_VOID(soa_terminate(NULL, "both"));
TEST_1(!soa_is_complete(NULL));
TEST_1(!soa_init_offer_answer(NULL));
TEST(soa_is_audio_active(NULL), SOA_ACTIVE_DISABLED);
TEST(soa_is_video_active(NULL), SOA_ACTIVE_DISABLED);
TEST(soa_is_image_active(NULL), SOA_ACTIVE_DISABLED);
TEST(soa_is_chat_active(NULL), SOA_ACTIVE_DISABLED);
TEST(soa_is_remote_audio_active(NULL), SOA_ACTIVE_DISABLED);
TEST(soa_is_remote_video_active(NULL), SOA_ACTIVE_DISABLED);
TEST(soa_is_remote_image_active(NULL), SOA_ACTIVE_DISABLED);
TEST(soa_is_remote_chat_active(NULL), SOA_ACTIVE_DISABLED);
END();
}
int test_soa_tags(struct context *ctx)
{
BEGIN();
su_home_t home[1] = { SU_HOME_INIT(home) };
tagi_t *t;
tagi_t const soafilter[] = {
{ TAG_FILTER(soa_tag_filter) },
{ TAG_NULL() }
};
t = tl_filtered_tlist(home, soafilter,
SIPTAG_FROM_STR("sip:my.domain"),
SOATAG_USER_SDP_STR("v=0"),
SOATAG_HOLD("*"),
TAG_END());
TEST_1(t);
TEST_P(t[0].t_tag, soatag_user_sdp_str);
TEST_P(t[1].t_tag, soatag_hold);
TEST_1(t[2].t_tag == NULL || t[2].t_tag == tag_null);
su_home_deinit(home);
END();
}
int test_init(struct context *ctx, char *argv[])
{
BEGIN();
int n;
ctx->root = su_root_create(ctx); TEST_1(ctx->root);
ctx->asynch.a = soa_create("asynch", ctx->root, ctx);
TEST_1(!ctx->asynch.a);
#if 0
TEST_1(!soa_find("asynch"));
TEST_1(soa_find("default"));
n = soa_add("asynch", &soa_asynch_actions); TEST(n, 0);
TEST_1(soa_find("asynch"));
ctx->asynch.a = soa_create("asynch", ctx->root, ctx);
TEST_1(ctx->asynch.a);
ctx->asynch.b = soa_create("asynch", ctx->root, ctx);
TEST_1(ctx->asynch.b);
#endif
/* Create asynchronous endpoints */
ctx->a = soa_create("static", ctx->root, ctx);
TEST_1(!ctx->a);
TEST_1(!soa_find("static"));
TEST_1(soa_find("default"));
n = soa_add("static", &soa_default_actions); TEST(n, 0);
TEST_1(soa_find("static"));
ctx->a = soa_create("static", ctx->root, ctx);
TEST_1(ctx->a);
ctx->b = soa_create("static", ctx->root, ctx);
TEST_1(ctx->b);
END();
}
int test_params(struct context *ctx)
{
BEGIN();
int n;
int af;
char const *address;
char const *hold;
int rtp_select, rtp_sort;
int rtp_mismatch;
int srtp_enable, srtp_confidentiality, srtp_integrity;
int delayed_offer_enable;
soa_session_t *a = ctx->a, *b = ctx->b;
n = soa_set_params(a, TAG_END()); TEST(n, 0);
n = soa_set_params(b, TAG_END()); TEST(n, 0);
af = -42;
address = NONE;
hold = NONE;
rtp_select = -1, rtp_sort = -1, rtp_mismatch = -1;
srtp_enable = -1, srtp_confidentiality = -1, srtp_integrity = -1;
delayed_offer_enable = -1;
TEST(soa_get_params(a,
SOATAG_AF_REF(af),
SOATAG_ADDRESS_REF(address),
SOATAG_HOLD_REF(hold),
SOATAG_RTP_SELECT_REF(rtp_select),
SOATAG_RTP_SORT_REF(rtp_sort),
SOATAG_RTP_MISMATCH_REF(rtp_mismatch),
SOATAG_SRTP_ENABLE_REF(srtp_enable),
SOATAG_SRTP_CONFIDENTIALITY_REF(srtp_confidentiality),
SOATAG_SRTP_INTEGRITY_REF(srtp_integrity),
SOATAG_DELAYED_OFFER_ENABLE_REF(delayed_offer_enable),
TAG_END()),
10);
TEST(af, SOA_AF_ANY);
TEST_P(address, 0);
TEST_P(hold, 0);
TEST(rtp_select, SOA_RTP_SELECT_SINGLE);
TEST(rtp_sort, SOA_RTP_SORT_DEFAULT);
TEST(rtp_mismatch, 0);
TEST(srtp_enable, 0);
TEST(srtp_confidentiality, 0);
TEST(rtp_mismatch, 0);
TEST(srtp_integrity, 0);
TEST(delayed_offer_enable, 0);
TEST(soa_set_params(a,
SOATAG_AF(SOA_AF_IP4_IP6),
SOATAG_ADDRESS("127.0.0.1"),
SOATAG_HOLD("audio"),
SOATAG_RTP_SELECT(SOA_RTP_SELECT_ALL),
SOATAG_RTP_SORT(SOA_RTP_SORT_LOCAL),
SOATAG_RTP_MISMATCH(1),
SOATAG_SRTP_ENABLE(1),
SOATAG_SRTP_CONFIDENTIALITY(1),
SOATAG_SRTP_INTEGRITY(1),
SOATAG_DELAYED_OFFER_ENABLE(1),
TAG_END()),
10);
TEST(soa_get_params(a,
SOATAG_AF_REF(af),
SOATAG_ADDRESS_REF(address),
SOATAG_HOLD_REF(hold),
SOATAG_RTP_SELECT_REF(rtp_select),
SOATAG_RTP_SORT_REF(rtp_sort),
SOATAG_RTP_MISMATCH_REF(rtp_mismatch),
SOATAG_SRTP_ENABLE_REF(srtp_enable),
SOATAG_SRTP_CONFIDENTIALITY_REF(srtp_confidentiality),
SOATAG_SRTP_INTEGRITY_REF(srtp_integrity),
SOATAG_DELAYED_OFFER_ENABLE_REF(delayed_offer_enable),
TAG_END()),
10);
TEST(af, SOA_AF_IP4_IP6);
TEST_S(address, "127.0.0.1");
TEST_S(hold, "audio");
TEST(rtp_select, SOA_RTP_SELECT_ALL);
TEST(rtp_sort, SOA_RTP_SORT_LOCAL);
TEST(rtp_mismatch, 1);
TEST(srtp_enable, 1);
TEST(srtp_confidentiality, 1);
TEST(srtp_integrity, 1);
TEST(delayed_offer_enable, 1);
/* Restore defaults */
TEST(soa_set_params(a,
SOATAG_AF(SOA_AF_IP4_IP6),
SOATAG_ADDRESS(NULL),
SOATAG_HOLD(NULL),
SOATAG_RTP_SELECT(SOA_RTP_SELECT_SINGLE),
SOATAG_RTP_SORT(SOA_RTP_SORT_DEFAULT),
SOATAG_RTP_MISMATCH(0),
SOATAG_SRTP_ENABLE(0),
SOATAG_SRTP_CONFIDENTIALITY(0),
SOATAG_SRTP_INTEGRITY(0),
SOATAG_DELAYED_OFFER_ENABLE(0),
TAG_END()),
10);
END();
}
int test_completed(struct context *ctx, soa_session_t *session)
{
ctx->completed = session;
su_root_break(ctx->root);
return 0;
}
int test_static_offer_answer(struct context *ctx)
{
BEGIN();
int n;
soa_session_t *a, *b;
char const *caps = NONE, *offer = NONE, *answer = NONE;
isize_t capslen = (isize_t)-1;
isize_t offerlen = (isize_t)-1;
isize_t answerlen = (isize_t)-1;
su_home_t home[1] = { SU_HOME_INIT(home) };
char const a_caps[] =
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=audio 0 RTP/AVP 0 8\r\n";
char const b_caps[] =
"m=audio 5004 RTP/AVP 96 8\n"
"m=rtpmap:96 GSM/8000\n";
TEST(soa_set_capability_sdp(ctx->a, 0, "m=audio 0 RTP/AVP 0 8", -1),
1);
TEST(soa_set_capability_sdp(ctx->a, 0, a_caps, strlen(a_caps)),
1);
TEST(soa_get_capability_sdp(ctx->a, NULL, &caps, &capslen), 1);
TEST_1(caps != NULL && caps != NONE);
TEST_1(capslen > 0);
TEST(soa_set_user_sdp(ctx->b, 0, b_caps, strlen(b_caps)), 1);
TEST(soa_get_capability_sdp(ctx->a, NULL, &caps, &capslen), 1);
TEST_1(a = soa_clone(ctx->a, ctx->root, ctx));
TEST_1(b = soa_clone(ctx->b, ctx->root, ctx));
n = soa_get_local_sdp(a, NULL, &offer, &offerlen); TEST(n, 0);
n = soa_set_user_sdp(a, 0, "m=audio 5004 RTP/AVP 0 8", -1); TEST(n, 1);
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, NULL, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_get_local_sdp(b, NULL, &answer, &answerlen); TEST(n, 0);
n = soa_set_params(b,
SOATAG_LOCAL_SDP_STR("m=audio 5004 RTP/AVP 8"),
SOATAG_AF(SOA_AF_IP4_ONLY),
SOATAG_ADDRESS("1.2.3.4"),
TAG_END());
n = soa_generate_answer(b, test_completed); TEST(n, 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
n = soa_get_local_sdp(b, NULL, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
TEST_1(strstr(answer, "c=IN IP4 1.2.3.4"));
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_video_active(a), SOA_ACTIVE_DISABLED);
TEST(soa_is_image_active(a), SOA_ACTIVE_DISABLED);
TEST(soa_is_chat_active(a), SOA_ACTIVE_DISABLED);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_video_active(a), SOA_ACTIVE_DISABLED);
TEST(soa_is_remote_image_active(a), SOA_ACTIVE_DISABLED);
TEST(soa_is_remote_chat_active(a), SOA_ACTIVE_DISABLED);
/* 'A' will put call on hold */
offer = NONE;
TEST(soa_set_params(a, SOATAG_HOLD("*"), TAG_END()), 1);
TEST(soa_generate_offer(a, 1, test_completed), 0);
TEST(soa_get_local_sdp(a, NULL, &offer, &offerlen), 1);
TEST_1(offer != NULL && offer != NONE);
TEST_1(strstr(offer, "a=sendonly"));
TEST(soa_set_remote_sdp(b, 0, offer, offerlen), 1);
TEST(soa_generate_answer(b, test_completed), 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST(soa_get_local_sdp(b, NULL, &answer, &answerlen), 1);
TEST_1(answer != NULL && answer != NONE);
TEST_1(strstr(answer, "a=recvonly"));
TEST(soa_set_remote_sdp(a, 0, answer, -1), 1);
TEST(soa_process_answer(a, test_completed), 0);
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDONLY);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDONLY);
/* 'A' will put call inactive */
offer = NONE;
TEST(soa_set_params(a, SOATAG_HOLD("#"), TAG_END()), 1);
TEST(soa_generate_offer(a, 1, test_completed), 0);
TEST(soa_get_local_sdp(a, NULL, &offer, &offerlen), 1);
TEST_1(offer != NULL && offer != NONE);
TEST_1(strstr(offer, "a=inactive"));
TEST(soa_set_remote_sdp(b, 0, offer, offerlen), 1);
TEST(soa_generate_answer(b, test_completed), 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST(soa_get_local_sdp(b, NULL, &answer, &answerlen), 1);
TEST_1(answer != NULL && answer != NONE);
TEST_1(strstr(answer, "a=inactive"));
TEST(soa_set_remote_sdp(a, 0, answer, -1), 1);
TEST(soa_process_answer(a, test_completed), 0);
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_INACTIVE);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_INACTIVE);
/* B will send an offer to A, but there is no change in O/A status */
TEST(soa_generate_offer(b, 1, test_completed), 0);
TEST(soa_get_local_sdp(b, NULL, &offer, &offerlen), 1);
TEST_1(offer != NULL && offer != NONE);
TEST_1(!strstr(offer, "a=inactive"));
/* printf("offer:\n%s", offer); */
TEST(soa_set_remote_sdp(a, 0, offer, offerlen), 1);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_generate_answer(a, test_completed), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_INACTIVE);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_INACTIVE);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_get_local_sdp(a, NULL, &answer, &answerlen), 1);
TEST_1(answer != NULL && answer != NONE);
TEST_1(strstr(answer, "a=inactive"));
/* printf("answer:\n%s", answer); */
TEST(soa_set_remote_sdp(b, 0, answer, -1), 1);
TEST(soa_process_answer(b, test_completed), 0);
TEST(soa_activate(b, NULL), 0);
TEST(soa_is_audio_active(b), SOA_ACTIVE_INACTIVE);
TEST(soa_is_remote_audio_active(b), SOA_ACTIVE_INACTIVE);
/* 'A' will release hold. */
TEST(soa_set_params(a, SOATAG_HOLD(NULL), TAG_END()), 1);
TEST(soa_generate_offer(a, 1, test_completed), 0);
TEST(soa_get_local_sdp(a, NULL, &offer, &offerlen), 1);
TEST_1(offer != NULL && offer != NONE);
TEST_1(!strstr(offer, "a=sendonly") && !strstr(offer, "a=inactive"));
TEST(soa_set_remote_sdp(b, 0, offer, offerlen), 1);
TEST(soa_generate_answer(b, test_completed), 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST(soa_get_local_sdp(b, NULL, &answer, &answerlen), 1);
TEST_1(answer != NULL && answer != NONE);
TEST_1(!strstr(answer, "a=recvonly") && !strstr(answer, "a=inactive"));
TEST(soa_set_remote_sdp(a, 0, answer, -1), 1);
TEST(soa_process_answer(a, test_completed), 0);
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
/* 'A' will put B on hold but this time with c=IN IP4 0.0.0.0 */
TEST(soa_set_params(a, SOATAG_HOLD("*"), TAG_END()), 1);
TEST(soa_generate_offer(a, 1, test_completed), 0);
{
sdp_session_t const *o_sdp;
sdp_session_t *sdp;
sdp_printer_t *p;
sdp_connection_t *c;
TEST(soa_get_local_sdp(a, &o_sdp, NULL, NULL), 1);
TEST_1(o_sdp != NULL && o_sdp != NONE);
TEST_1(sdp = sdp_session_dup(home, o_sdp));
/* Remove mode, change c=, encode offer */
if (sdp->sdp_media->m_connections)
c = sdp->sdp_media->m_connections;
else
c = sdp->sdp_connection;
TEST_1(c);
c->c_address = "0.0.0.0";
TEST_1(p = sdp_print(home, sdp, NULL, 0, sdp_f_realloc));
TEST_1(sdp_message(p));
offer = sdp_message(p); offerlen = strlen(offer);
}
TEST(soa_set_remote_sdp(b, 0, offer, -1), 1);
TEST(soa_generate_answer(b, test_completed), 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST(soa_get_local_sdp(b, NULL, &answer, &answerlen), 1);
TEST_1(answer != NULL && answer != NONE);
TEST_1(strstr(answer, "a=recvonly"));
TEST(soa_set_remote_sdp(a, 0, answer, -1), 1);
TEST(soa_process_answer(a, test_completed), 0);
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDONLY);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDONLY);
TEST(soa_is_audio_active(b), SOA_ACTIVE_RECVONLY);
TEST(soa_is_remote_audio_active(b), SOA_ACTIVE_RECVONLY);
/* 'A' will propose adding video. */
/* 'B' will reject. */
TEST(soa_set_params(a,
SOATAG_HOLD(NULL), /* 'A' will release hold. */
SOATAG_USER_SDP_STR("m=audio 5008 RTP/AVP 0 8\r\ni=x\r\n"
"m=video 5006 RTP/AVP 34\r\n"),
TAG_END()), 2);
TEST(soa_generate_offer(a, 1, test_completed), 0);
TEST(soa_get_local_sdp(a, NULL, &offer, &offerlen), 1);
TEST_1(offer != NULL && offer != NONE);
TEST_1(!strstr(offer, "a=sendonly"));
TEST_1(strstr(offer, "m=video"));
TEST(soa_set_remote_sdp(b, 0, offer, offerlen), 1);
TEST(soa_generate_answer(b, test_completed), 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST(soa_get_local_sdp(b, NULL, &answer, &answerlen), 1);
TEST_1(answer != NULL && answer != NONE);
TEST_1(!strstr(answer, "a=recvonly"));
TEST_1(strstr(answer, "m=video"));
TEST(soa_set_remote_sdp(a, 0, answer, -1), 1);
TEST(soa_process_answer(a, test_completed), 0);
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_video_active(a), SOA_ACTIVE_REJECTED);
{
/* Test tags */
sdp_session_t const *l = NULL, *u = NULL, *r = NULL;
sdp_media_t const *m;
TEST(soa_get_params(b,
SOATAG_LOCAL_SDP_REF(l),
SOATAG_USER_SDP_REF(u),
SOATAG_REMOTE_SDP_REF(r),
TAG_END()), 3);
TEST_1(l); TEST_1(u); TEST_1(r);
TEST_1(m = l->sdp_media); TEST(m->m_type, sdp_media_audio);
TEST_1(!m->m_rejected);
TEST_1(m = m->m_next); TEST(m->m_type, sdp_media_video);
TEST_1(m->m_rejected);
}
/* 'B' will now propose adding video. */
/* 'A' will accept. */
TEST(soa_set_params(b,
SOATAG_USER_SDP_STR("m=audio 5004 RTP/AVP 0 8\r\n"
"m=video 5006 RTP/AVP 34\r\n"),
TAG_END()), 1);
TEST(soa_generate_offer(b, 1, test_completed), 0);
TEST(soa_get_local_sdp(b, NULL, &offer, &offerlen), 1);
TEST_1(offer != NULL && offer != NONE);
TEST_1(!strstr(offer, "b=sendonly"));
TEST_1(strstr(offer, "m=video"));
TEST(soa_set_remote_sdp(a, 0, offer, offerlen), 1);
TEST(soa_generate_answer(a, test_completed), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_get_local_sdp(a, NULL, &answer, &answerlen), 1);
TEST_1(answer != NULL && answer != NONE);
TEST_1(!strstr(answer, "b=recvonly"));
TEST_1(strstr(answer, "m=video"));
TEST(soa_set_remote_sdp(b, 0, answer, -1), 1);
TEST(soa_process_answer(b, test_completed), 0);
TEST(soa_activate(b, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_video_active(a), SOA_ACTIVE_SENDRECV);
TEST_VOID(soa_terminate(a, NULL));
TEST(soa_is_audio_active(a), SOA_ACTIVE_DISABLED);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_DISABLED);
TEST_VOID(soa_terminate(b, NULL));
TEST_VOID(soa_destroy(a));
TEST_VOID(soa_destroy(b));
su_home_deinit(home);
END();
}
int test_codec_selection(struct context *ctx)
{
BEGIN();
int n;
soa_session_t *a, *b;
char const *offer = NONE, *answer = NONE;
isize_t offerlen = (isize_t)-1, answerlen = (isize_t)-1;
sdp_session_t const *a_sdp, *b_sdp;
sdp_media_t const *m;
sdp_rtpmap_t const *rm;
char const a_caps[] =
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=audio 5008 RTP/AVP 0 8 97\r\n"
"a=rtpmap:97 GSM/8000\n"
;
char const b_caps[] =
"m=audio 5004 RTP/AVP 96 97\n"
"a=rtpmap:96 G7231/8000\n"
"a=rtpmap:97 G729/8000\n";
TEST_1(a = soa_create("static", ctx->root, ctx));
TEST_1(b = soa_create("static", ctx->root, ctx));
TEST(soa_set_user_sdp(a, 0, a_caps, strlen(a_caps)), 1);
TEST(soa_set_user_sdp(b, 0, b_caps, strlen(b_caps)), 1);
TEST(soa_set_params(a, SOATAG_AUDIO_AUX("cn telephone-event"), TAG_END()), 1);
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, NULL, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_get_local_sdp(b, NULL, &answer, &answerlen); TEST(n, 0);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_REJECTED);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_REJECTED);
TEST_1(m = b_sdp->sdp_media); TEST_1(m->m_rejected);
TEST_1(rm = m->m_rtpmaps); TEST(rm->rm_pt, 96);
TEST_S(rm->rm_encoding, "G7231");
/* Not reusing payload type 97 from offer */
TEST_1(rm = rm->rm_next); TEST(rm->rm_pt, 98);
TEST_S(rm->rm_encoding, "G729");
TEST_1(!rm->rm_next);
/* ---------------------------------------------------------------------- */
/* Re-O/A: A generates new SDP */
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 0);
n = soa_process_answer(a, test_completed); TEST(n, 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
/* Re-O/A: no-one regenerates new SDP */
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 0);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 0);
n = soa_process_answer(a, test_completed); TEST(n, 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
/* ---------------------------------------------------------------------- */
/* Re-O/A: accept media without common codecs */
/* Accept media without common codecs */
TEST_1(soa_set_params(a, SOATAG_RTP_MISMATCH(1), TAG_END()));
TEST_1(soa_set_params(b, SOATAG_RTP_MISMATCH(1), TAG_END()));
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST_1(m = b_sdp->sdp_media); TEST_1(!m->m_rejected);
TEST_1(rm = m->m_rtpmaps); TEST(rm->rm_pt, 96);
TEST_S(rm->rm_encoding, "G7231");
/* Not using payload type 97 from offer */
TEST_1(rm = rm->rm_next); TEST(rm->rm_pt, 98);
TEST_S(rm->rm_encoding, "G729");
TEST_1(!rm->rm_next);
/* ---------------------------------------------------------------------- */
/* Re-O/A: add a common codec */
/* Accept media without common codecs */
TEST_1(soa_set_params(a, SOATAG_RTP_MISMATCH(0),
SOATAG_USER_SDP_STR(
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=audio 5008 RTP/AVP 0 8 96 3 127\r\n"
"a=rtpmap:96 G729/8000\n"
"a=rtpmap:127 CN/8000\n"
),
SOATAG_RTP_SORT(SOA_RTP_SORT_REMOTE),
SOATAG_RTP_SELECT(SOA_RTP_SELECT_ALL),
TAG_END()));
TEST_1(soa_set_params(b, SOATAG_RTP_MISMATCH(0),
SOATAG_USER_SDP_STR(
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=audio 5004 RTP/AVP 96 3 97 111\r\n"
"a=rtpmap:96 G7231/8000\n"
"a=rtpmap:97 G729/8000\n"
"a=rtpmap:111 telephone-event/8000\n"
"a=fmtp:111 0-15\n"
),
SOATAG_AUDIO_AUX("cn telephone-event"),
SOATAG_RTP_SORT(SOA_RTP_SORT_LOCAL),
SOATAG_RTP_SELECT(SOA_RTP_SELECT_COMMON),
TAG_END()));
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, NULL, NULL); TEST(n, 1);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST_1(m = a_sdp->sdp_media); TEST_1(!m->m_rejected);
TEST_1(rm = m->m_rtpmaps); TEST(rm->rm_pt, 3);
TEST_S(rm->rm_encoding, "GSM");
TEST_1(rm = rm->rm_next); TEST(rm->rm_pt, 96);
TEST_S(rm->rm_encoding, "G729");
TEST_1(rm = rm->rm_next); TEST(rm->rm_pt, 0);
TEST_S(rm->rm_encoding, "PCMU");
TEST_1(rm = rm->rm_next); TEST(rm->rm_pt, 8);
TEST_S(rm->rm_encoding, "PCMA");
TEST_1(rm = rm->rm_next); TEST(rm->rm_pt, 127);
TEST_S(rm->rm_encoding, "CN");
TEST_1(!rm->rm_next);
TEST_1(m = b_sdp->sdp_media); TEST_1(!m->m_rejected);
TEST_1(rm = m->m_rtpmaps); TEST(rm->rm_pt, 3);
TEST_S(rm->rm_encoding, "GSM");
/* Using payload type 96 from offer */
TEST_1(rm = rm->rm_next); TEST(rm->rm_pt, 96);
TEST_S(rm->rm_encoding, "G729");
TEST_1(rm = rm->rm_next); TEST(rm->rm_pt, 111);
TEST_S(rm->rm_encoding, "telephone-event");
TEST_1(!rm->rm_next);
/* ---------------------------------------------------------------------- */
/* Re-O/A: prune down to single codec. */
TEST_1(soa_set_params(a,
SOATAG_USER_SDP_STR(
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=audio 5008 RTP/AVP 0 8 97 96 127\r\n"
"a=rtpmap:96 G729/8000\n"
"a=rtpmap:97 GSM/8000\n"
"a=rtpmap:127 CN/8000\n"
),
SOATAG_RTP_MISMATCH(0),
SOATAG_RTP_SELECT(SOA_RTP_SELECT_COMMON),
TAG_END()));
TEST_1(soa_set_params(b,
SOATAG_RTP_MISMATCH(0),
SOATAG_RTP_SORT(SOA_RTP_SORT_LOCAL),
SOATAG_RTP_SELECT(SOA_RTP_SELECT_SINGLE),
TAG_END()));
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, &offer, &offerlen); TEST(n, 1);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST_1(m = a_sdp->sdp_media); TEST_1(!m->m_rejected);
TEST_1(rm = m->m_rtpmaps); TEST(rm->rm_pt, 97);
TEST_S(rm->rm_encoding, "GSM");
TEST_1(rm = rm->rm_next); TEST(rm->rm_pt, 127);
TEST_S(rm->rm_encoding, "CN");
TEST_1(!rm->rm_next);
/* Answering end matches payload types
then sorts by local preference,
then select best codec => GSM with pt 97 */
TEST_1(m = b_sdp->sdp_media); TEST_1(!m->m_rejected);
TEST_1(rm = m->m_rtpmaps); TEST(rm->rm_pt, 97);
TEST_S(rm->rm_encoding, "GSM");
TEST_1(rm = rm->rm_next); TEST(rm->rm_pt, 111);
TEST_S(rm->rm_encoding, "telephone-event");
TEST_1(!rm->rm_next);
/* ---------------------------------------------------------------------- */
/* Re-O/A: A generates new SDP offer with single codec only */
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
TEST_1(m = a_sdp->sdp_media); TEST_1(!m->m_rejected);
TEST_1(rm = m->m_rtpmaps); TEST(rm->rm_pt, 97);
TEST_S(rm->rm_encoding, "GSM");
TEST_1(rm = rm->rm_next); TEST(rm->rm_pt, 127);
TEST_S(rm->rm_encoding, "CN");
TEST_1(!rm->rm_next);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
/* Answer from B is identical to previous one */
n = soa_generate_answer(b, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 0);
n = soa_process_answer(a, test_completed); TEST(n, 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
/* ---------------------------------------------------------------------- */
/* Add new media - without common codecs */
TEST_1(soa_set_params(a,
SOATAG_RTP_MISMATCH(0),
SOATAG_USER_SDP_STR(
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=audio 5008 RTP/AVP 0 8 96 3 127\r\n"
"a=rtpmap:96 G729/8000\n"
"a=rtpmap:127 CN/8000\n"
"m=video 5010 RTP/AVP 31\r\n"
"m=audio 6008 RTP/SAVP 3\n"
),
TAG_END()));
TEST_1(soa_set_params(b,
SOATAG_RTP_MISMATCH(0),
SOATAG_USER_SDP_STR(
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=audio 5004 RTP/AVP 96 3 97 111\r\n"
"a=rtpmap:96 G7231/8000\n"
"a=rtpmap:97 G729/8000\n"
"a=rtpmap:111 telephone-event/8000\n"
"a=fmtp:111 0-15\n"
"m=audio 6004 RTP/SAVP 96\n"
"a=rtpmap:96 G729/8000\n"
"m=video 5006 RTP/AVP 34\n"
),
TAG_END()));
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
TEST_1(m = a_sdp->sdp_media); TEST_1(!m->m_rejected);
TEST_1(m = m->m_next); TEST_1(!m->m_rejected);
TEST_1(m = m->m_next); TEST_1(!m->m_rejected);
TEST_1(!m->m_next);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
/* Answer from B rejects video */
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, &offer, &offerlen); TEST(n, 1);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_video_active(a), SOA_ACTIVE_REJECTED);
TEST(soa_is_remote_video_active(a), SOA_ACTIVE_REJECTED);
TEST_1(m = a_sdp->sdp_media); TEST_1(!m->m_rejected);
TEST_1(m = m->m_next); TEST_1(m->m_rejected);
TEST_1(m = m->m_next); TEST_1(m->m_rejected);
TEST_1(!m->m_next);
TEST_1(m = b_sdp->sdp_media); TEST_1(!m->m_rejected);
TEST_1(m = m->m_next); TEST_1(m->m_rejected);
/* Rejected but tell what we support */
TEST_1(rm = m->m_rtpmaps); TEST(rm->rm_pt, 34);
TEST_S(rm->rm_encoding, "H263");
TEST_1(m = m->m_next); TEST_1(m->m_rejected);
TEST_1(!m->m_next);
/* ---------------------------------------------------------------------- */
/* A adds H.263 to video */
TEST_1(soa_set_params(a,
SOATAG_USER_SDP_STR(
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=audio 5008 RTP/AVP 0 8 96 3 127\r\n"
"a=rtpmap:96 G729/8000\n"
"a=rtpmap:127 CN/8000\n"
"m=video 5010 RTP/AVP 31 34\r\n"
"m=audio 6008 RTP/SAVP 3\n"
),
TAG_END()));
/* B adds GSM to SRTP */
TEST_1(soa_set_params(b,
SOATAG_USER_SDP_STR(
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=audio 5004 RTP/AVP 96 3 97 111\r\n"
"a=rtpmap:96 G7231/8000\n"
"a=rtpmap:97 G729/8000\n"
"a=rtpmap:111 telephone-event/8000\n"
"a=fmtp:111 0-15\n"
"m=audio 6004 RTP/SAVP 96 3\n"
"a=rtpmap:96 G729/8000\n"
"m=video 5006 RTP/AVP 34\n"
),
TAG_END()));
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
TEST_1(m = a_sdp->sdp_media); TEST_1(!m->m_rejected);
TEST_1(m = m->m_next); TEST_1(!m->m_rejected);
TEST_1(m = m->m_next); TEST_1(!m->m_rejected);
TEST_1(!m->m_next);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
/* Answer from B now accepts video */
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, &offer, &offerlen); TEST(n, 1);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_video_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_video_active(a), SOA_ACTIVE_SENDRECV);
TEST_1(m = a_sdp->sdp_media); TEST_1(!m->m_rejected);
TEST_1(m = m->m_next); TEST_1(!m->m_rejected);
TEST_1(rm = m->m_rtpmaps); TEST(rm->rm_pt, 34);
TEST_S(rm->rm_encoding, "H263");
TEST_1(m = m->m_next); TEST_1(!m->m_rejected);
TEST_1(!m->m_next);
TEST_1(m = b_sdp->sdp_media); TEST_1(!m->m_rejected);
TEST_1(m = m->m_next); TEST_1(!m->m_rejected);
TEST_1(rm = m->m_rtpmaps); TEST(rm->rm_pt, 34);
TEST_S(rm->rm_encoding, "H263");
TEST_1(m = m->m_next); TEST_1(!m->m_rejected);
TEST_1(!m->m_next);
/* ---------------------------------------------------------------------- */
/* A drops GSM support */
TEST_1(soa_set_params(a,
SOATAG_USER_SDP_STR(
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=audio 5008 RTP/AVP 0 8 96 127\r\n"
"a=rtpmap:96 G729/8000\n"
"a=rtpmap:127 CN/8000\n"
"m=video 5010 RTP/AVP 31 34\r\n"
"m=audio 6008 RTP/SAVP 3\n"
),
TAG_END()));
/* B adds GSM to SRTP, changes IP address */
TEST_1(soa_set_params(b,
SOATAG_USER_SDP_STR(
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.3\r\n"
"m=audio 5004 RTP/AVP 96 3 97 111\r\n"
"a=rtpmap:96 G7231/8000\n"
"a=rtpmap:97 G729/8000\n"
"a=rtpmap:111 telephone-event/8000\n"
"a=fmtp:111 0-15\n"
"m=audio 6004 RTP/SAVP 96 3\n"
"a=rtpmap:96 G729/8000\n"
"m=video 5006 RTP/AVP 34\n"
),
TAG_END()));
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
TEST_1(m = a_sdp->sdp_media); TEST_1(!m->m_rejected);
TEST_1(m = m->m_next); TEST_1(!m->m_rejected);
TEST_1(m = m->m_next); TEST_1(!m->m_rejected);
TEST_1(!m->m_next);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
/* Answer from B now accepts video */
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
/* Check that updated c= line is propagated */
TEST_1(b_sdp->sdp_connection);
TEST_S(b_sdp->sdp_connection->c_address, "127.0.0.3");
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, &offer, &offerlen); TEST(n, 1);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_video_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_video_active(a), SOA_ACTIVE_SENDRECV);
TEST_1(m = a_sdp->sdp_media); TEST_1(!m->m_rejected);
TEST_1(rm = m->m_rtpmaps); TEST(rm->rm_pt, 96);
TEST_S(rm->rm_encoding, "G729");
TEST_1(rm = rm->rm_next); TEST(rm->rm_pt, 127);
TEST_S(rm->rm_encoding, "CN");
TEST_1(m = m->m_next); TEST_1(!m->m_rejected);
TEST_1(rm = m->m_rtpmaps); TEST(rm->rm_pt, 34);
TEST_S(rm->rm_encoding, "H263");
TEST_1(m = m->m_next); TEST_1(!m->m_rejected);
TEST_1(!m->m_next);
TEST_1(m = b_sdp->sdp_media); TEST_1(!m->m_rejected);
TEST_1(rm = m->m_rtpmaps); TEST(rm->rm_pt, 96);
TEST_S(rm->rm_encoding, "G729");
TEST_1(rm = rm->rm_next); TEST(rm->rm_pt, 111);
TEST_S(rm->rm_encoding, "telephone-event");
TEST_1(m = m->m_next); TEST_1(!m->m_rejected);
TEST_1(rm = m->m_rtpmaps); TEST(rm->rm_pt, 34);
TEST_S(rm->rm_encoding, "H263");
TEST_1(m = m->m_next); TEST_1(!m->m_rejected);
TEST_1(!m->m_next);
/* ---------------------------------------------------------------------- */
TEST_VOID(soa_terminate(a, NULL));
TEST_VOID(soa_terminate(b, NULL));
TEST_VOID(soa_destroy(a));
TEST_VOID(soa_destroy(b));
END();
}
int test_media_mode(struct context *ctx)
{
BEGIN();
int n;
soa_session_t *a, *b;
char const *offer = NONE, *answer = NONE;
isize_t offerlen = (isize_t)-1;
isize_t answerlen = (isize_t)-1;
su_home_t home[1] = { SU_HOME_INIT(home) };
char const a_caps[] = "m=audio 5008 RTP/AVP 0 8\r\n";
char const b_caps[] = "m=audio 5004 RTP/AVP 8 0\n";
char const b_recvonly[] = "m=audio 5004 RTP/AVP 8 0\na=recvonly\n";
TEST_1(a = soa_clone(ctx->a, ctx->root, ctx));
TEST_1(b = soa_clone(ctx->b, ctx->root, ctx));
TEST(soa_set_user_sdp(a, 0, a_caps, -1), 1);
TEST(soa_set_user_sdp(b, 0, b_recvonly, -1), 1);
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, NULL, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
n = soa_get_local_sdp(b, NULL, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDONLY);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDONLY);
/* Put B as sendrecv */
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, NULL, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
TEST(soa_set_user_sdp(b, 0, b_caps, -1), 1);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
n = soa_get_local_sdp(b, NULL, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
/* 'A' will put call on hold */
offer = NONE;
TEST(soa_set_params(a, SOATAG_HOLD("*"), TAG_END()), 1);
TEST(soa_generate_offer(a, 1, test_completed), 0);
TEST(soa_get_local_sdp(a, NULL, &offer, &offerlen), 1);
TEST_1(offer != NULL && offer != NONE);
TEST_1(strstr(offer, "a=sendonly"));
TEST(soa_set_user_sdp(b, 0,
"m=audio 5004 RTP/AVP 8 0\n"
"a=inactive\n", -1), 1);
TEST(soa_set_remote_sdp(b, 0, offer, offerlen), 1);
TEST(soa_generate_answer(b, test_completed), 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST(soa_get_local_sdp(b, NULL, &answer, &answerlen), 1);
TEST_1(answer != NULL && answer != NONE);
TEST_1(strstr(answer, "a=inactive"));
TEST(soa_set_remote_sdp(a, 0, answer, -1), 1);
TEST(soa_process_answer(a, test_completed), 0);
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_INACTIVE);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_INACTIVE);
/* 'A' will retrieve call, 'B' will keep call on hold */
offer = NONE;
TEST(soa_set_params(a, SOATAG_HOLD(NULL), TAG_END()), 1);
TEST(soa_generate_offer(a, 1, test_completed), 0);
TEST(soa_get_local_sdp(a, NULL, &offer, &offerlen), 1);
TEST_1(offer != NULL && offer != NONE);
TEST_1(!strstr(offer, "a=sendonly"));
TEST(soa_set_user_sdp(b, 0,
"m=audio 5004 RTP/AVP 8 0\n"
"a=sendonly\n", -1), 1);
TEST(soa_set_remote_sdp(b, 0, offer, offerlen), 1);
TEST(soa_generate_answer(b, test_completed), 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST(soa_get_local_sdp(b, NULL, &answer, &answerlen), 1);
TEST_1(answer != NULL && answer != NONE);
TEST_1(strstr(answer, "a=sendonly"));
TEST(soa_set_remote_sdp(a, 0, answer, -1), 1);
TEST(soa_process_answer(a, test_completed), 0);
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_RECVONLY);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_RECVONLY);
TEST_VOID(soa_terminate(a, NULL));
TEST_VOID(soa_terminate(b, NULL));
TEST_VOID(soa_destroy(a));
TEST_VOID(soa_destroy(b));
su_home_deinit(home);
END();
}
int test_media_replace(struct context *ctx)
{
BEGIN();
int n;
soa_session_t *a, *b;
char const *offer = NONE, *answer = NONE;
isize_t offerlen = (isize_t)-1, answerlen = (isize_t)-1;
sdp_session_t const *a_sdp, *b_sdp;
sdp_media_t const *m;
char const a_caps[] =
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=audio 5008 RTP/AVP 0 8\r\n"
;
char const b_caps[] =
"m=audio 5004 RTP/AVP 0 8\n"
"a=rtpmap:96 G7231/8000\n"
"a=rtpmap:97 G729/8000\n"
"m=image 5556 UDPTL t38\r\n"
"a=T38FaxVersion:0\r\n"
"a=T38MaxBitRate:9600\r\n"
"a=T38FaxFillBitRemoval:0\r\n"
"a=T38FaxTranscodingMMR:0\r\n"
"a=T38FaxTranscodingJBIG:0\r\n"
"a=T38FaxRateManagement:transferredTCF\r\n"
"a=T38FaxMaxDatagram:400\r\n";
TEST_1(a = soa_create("static", ctx->root, ctx));
TEST_1(b = soa_create("static", ctx->root, ctx));
TEST(soa_set_user_sdp(a, 0, a_caps, strlen(a_caps)), 1);
TEST(soa_set_user_sdp(b, 0, b_caps, strlen(b_caps)), 1);
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, NULL, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_get_local_sdp(b, NULL, &answer, &answerlen); TEST(n, 0);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
/* ---------------------------------------------------------------------- */
/* Re-O/A: replace media stream */
/* Accept media without common codecs */
TEST_1(soa_set_params(a, SOATAG_RTP_MISMATCH(0),
SOATAG_ORDERED_USER(1),
SOATAG_USER_SDP_STR(
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=image 16384 UDPTL t38\r\n"
"a=T38FaxVersion:0\r\n"
"a=T38MaxBitRate:9600\r\n"
"a=T38FaxFillBitRemoval:0\r\n"
"a=T38FaxTranscodingMMR:0\r\n"
"a=T38FaxTranscodingJBIG:0\r\n"
"a=T38FaxRateManagement:transferredTCF\r\n"
"a=T38FaxMaxDatagram:400\r\n"
),
TAG_END()));
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, NULL, NULL); TEST(n, 1);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST_1(m = a_sdp->sdp_media); TEST_1(!m->m_rejected);
TEST(m->m_type, sdp_media_image);
TEST(m->m_proto, sdp_proto_udptl);
TEST_1(m->m_format);
TEST_S(m->m_format->l_text, "t38");
TEST_1(m = b_sdp->sdp_media); TEST_1(!m->m_rejected);
TEST(m->m_type, sdp_media_image);
TEST(m->m_proto, sdp_proto_udptl);
TEST_1(m->m_format);
TEST_S(m->m_format->l_text, "t38");
TEST(soa_is_audio_active(a), SOA_ACTIVE_DISABLED);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_DISABLED);
TEST_VOID(soa_terminate(a, NULL));
TEST_VOID(soa_terminate(b, NULL));
TEST_VOID(soa_destroy(a));
TEST_VOID(soa_destroy(b));
END();
}
int test_media_removal(struct context *ctx)
{
BEGIN();
int n;
soa_session_t *a, *b;
char const *offer = NONE, *answer = NONE;
isize_t offerlen = (isize_t)-1, answerlen = (isize_t)-1;
sdp_session_t const *a_sdp, *b_sdp;
sdp_media_t const *m;
char const a_caps[] =
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=audio 5008 RTP/AVP 0 8\r\n"
;
char const b_caps[] =
"v=0\n"
"m=audio 5004 RTP/AVP 0 8\n"
"a=rtpmap:96 G7231/8000\n"
"a=rtpmap:97 G729/8000\n";
TEST_1(a = soa_create("static", ctx->root, ctx));
TEST_1(b = soa_create("static", ctx->root, ctx));
TEST(soa_set_user_sdp(a, 0, a_caps, strlen(a_caps)), 1);
TEST(soa_set_user_sdp(b, 0, b_caps, strlen(b_caps)), 1);
TEST_1(soa_set_params(b, SOATAG_RTP_MISMATCH(0),
SOATAG_ORDERED_USER(1),
TAG_END()));
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, NULL, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_get_local_sdp(b, NULL, &answer, &answerlen); TEST(n, 0);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
/* ---------------------------------------------------------------------- */
/* Re-O/A: remove media stream */
TEST(soa_set_user_sdp(b, 0, "v=0", -1), 1);
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(m = b_sdp->sdp_media); TEST_1(m->m_rejected);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, NULL, NULL); TEST(n, 1);
TEST_1(m = a_sdp->sdp_media); TEST_1(m->m_rejected);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_REJECTED);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_REJECTED);
TEST_VOID(soa_terminate(a, NULL));
TEST_VOID(soa_terminate(b, NULL));
TEST_VOID(soa_destroy(a));
TEST_VOID(soa_destroy(b));
/* ---------------------------------------------------------------------- */
TEST_1(a = soa_create("static", ctx->root, ctx));
TEST_1(b = soa_create("static", ctx->root, ctx));
TEST(soa_set_user_sdp(a, 0, a_caps, strlen(a_caps)), 1);
TEST(soa_set_user_sdp(b, 0, b_caps, strlen(b_caps)), 1);
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, NULL, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_get_local_sdp(b, NULL, &answer, &answerlen); TEST(n, 0);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
/* ---------------------------------------------------------------------- */
/* Re-O/A: offerer remove media stream from user sdp */
TEST(soa_set_user_sdp(a, 0, "v=0", -1), 1);
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, &offer, &offerlen); TEST(n, 1);
TEST_1(m = a_sdp->sdp_media); TEST_1(m->m_rejected);
TEST_1(offer != NULL && offer != NONE);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(m = b_sdp->sdp_media); TEST_1(m->m_rejected);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, NULL, NULL); TEST(n, 1);
TEST_1(m = a_sdp->sdp_media); TEST_1(m->m_rejected);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_REJECTED);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_REJECTED);
TEST_VOID(soa_terminate(a, NULL));
TEST_VOID(soa_terminate(b, NULL));
TEST_VOID(soa_destroy(a));
TEST_VOID(soa_destroy(b));
END();
}
int test_media_reject(struct context *ctx)
{
BEGIN();
int n;
soa_session_t *a, *b;
char const *offer = NONE, *answer = NONE;
isize_t offerlen = (isize_t)-1, answerlen = (isize_t)-1;
sdp_session_t const *b_sdp;
char const a_caps[] =
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=audio 5008 RTP/AVP 0 8 97\r\n"
"a=rtpmap:97 GSM/8000\n"
;
char const b_caps[] =
"m=audio 0 RTP/AVP 96 97\n"
"a=rtpmap:96 G7231/8000\n"
"a=rtpmap:97 G729/8000\n";
TEST_1(a = soa_create("static", ctx->root, ctx));
TEST_1(b = soa_create("static", ctx->root, ctx));
TEST(soa_set_user_sdp(a, 0, a_caps, strlen(a_caps)), 1);
TEST(soa_set_user_sdp(b, 0, b_caps, strlen(b_caps)), 1);
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, NULL, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_get_local_sdp(b, NULL, &answer, &answerlen); TEST(n, 0);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_REJECTED);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_REJECTED);
TEST_VOID(soa_terminate(a, NULL));
TEST_VOID(soa_terminate(b, NULL));
TEST_VOID(soa_destroy(a));
TEST_VOID(soa_destroy(b));
END();
}
int test_media_replace2(struct context *ctx)
{
BEGIN();
int n;
soa_session_t *a, *b;
char const *offer = NONE, *answer = NONE;
isize_t offerlen = (isize_t)-1, answerlen = (isize_t)-1;
sdp_session_t const *a_sdp, *b_sdp;
sdp_media_t const *m;
char const a_caps[] =
"v=0\r\n"
"o=a 432432423423 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=image 5556 UDPTL t38\r\n"
"a=T38FaxVersion:0\r\n"
"a=T38MaxBitRate:9600\r\n"
"a=T38FaxFillBitRemoval:0\r\n"
"a=T38FaxTranscodingMMR:0\r\n"
"a=T38FaxTranscodingJBIG:0\r\n"
"a=T38FaxRateManagement:transferredTCF\r\n"
"a=T38FaxMaxDatagram:400\r\n"
"m=audio 5004 RTP/AVP 0 8\n"
"a=rtpmap:96 G7231/8000\n"
"a=rtpmap:97 G729/8000\n";
char const a_caps2[] =
"v=0\r\n"
"o=a 432432423423 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=image 0 UDPTL t38\r\n"
"m=image 5004 UDPTL t38\r\n"
"a=T38FaxVersion:0\r\n"
"a=T38MaxBitRate:9600\r\n"
"a=T38FaxFillBitRemoval:0\r\n"
"a=T38FaxTranscodingMMR:0\r\n"
"a=T38FaxTranscodingJBIG:0\r\n"
"a=T38FaxRateManagement:transferredTCF\r\n"
"a=T38FaxMaxDatagram:400\r\n";
char const b_caps[] =
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=audio 5008 RTP/AVP 0 8\r\n"
;
char const b_caps2[] =
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=image 5008 UDPTL t38\r\n"
;
TEST_1(a = soa_create("static", ctx->root, ctx));
TEST_1(b = soa_create("static", ctx->root, ctx));
TEST_1(soa_set_params(a, SOATAG_ORDERED_USER(1),
SOATAG_REUSE_REJECTED(1),
TAG_END()) > 0);
TEST_1(soa_set_params(b, SOATAG_ORDERED_USER(1),
SOATAG_REUSE_REJECTED(1),
TAG_END()) > 0);
TEST(soa_set_user_sdp(a, 0, a_caps, strlen(a_caps)), 1);
TEST(soa_set_user_sdp(b, 0, b_caps, strlen(b_caps)), 1);
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, NULL, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_get_local_sdp(b, NULL, &answer, &answerlen); TEST(n, 0);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, NULL, NULL); TEST(n, 1);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST_1(a_sdp->sdp_media);
TEST_1(a_sdp->sdp_media->m_type == sdp_media_image);
TEST_1(a_sdp->sdp_media->m_next);
TEST_1(a_sdp->sdp_media->m_next->m_type == sdp_media_audio);
/* ---------------------------------------------------------------------- */
/* Re-O/A: replace media stream */
/* Do not accept media without common codecs */
TEST_1(soa_set_params(b, SOATAG_RTP_MISMATCH(0),
SOATAG_USER_SDP_STR(b_caps2),
TAG_END()) > 0);
n = soa_generate_offer(b, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
n = soa_set_remote_sdp(a, 0, offer, offerlen); TEST(n, 1);
TEST_1(soa_set_params(a, SOATAG_RTP_MISMATCH(0),
SOATAG_USER_SDP_STR(a_caps2),
TAG_END()) > 0);
n = soa_generate_answer(a, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
n = soa_set_remote_sdp(b, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(b, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, NULL, NULL); TEST(n, 1);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(m = a_sdp->sdp_media); TEST_1(m->m_rejected);
TEST_1(m = m->m_next);
TEST(m->m_type, sdp_media_image);
TEST(m->m_proto, sdp_proto_udptl);
TEST_1(m->m_format);
TEST_S(m->m_format->l_text, "t38");
TEST_1(m = b_sdp->sdp_media); TEST_1(m->m_rejected);
TEST_1(m = m->m_next);
TEST(m->m_type, sdp_media_image);
TEST(m->m_proto, sdp_proto_udptl);
TEST_1(m->m_format);
TEST_S(m->m_format->l_text, "t38");
TEST(soa_is_audio_active(a), SOA_ACTIVE_DISABLED);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_DISABLED);
TEST_VOID(soa_terminate(a, NULL));
TEST_VOID(soa_terminate(b, NULL));
TEST_VOID(soa_destroy(a));
TEST_VOID(soa_destroy(b));
END();
}
int test_large_sessions(struct context *ctx)
{
BEGIN();
int n;
soa_session_t *a, *b;
char const *offer = NONE, *answer = NONE;
isize_t offerlen = (isize_t)-1, answerlen = (isize_t)-1;
sdp_session_t const *a_sdp, *b_sdp;
sdp_media_t const *m;
char const a_caps[] =
"v=0\r\n"
"o=a 432432423423 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=image 5556 UDPTL t38\r\n"
"m=audio 5004 RTP/AVP 0 8\n"
;
char const a_caps2[] =
"v=0\r\n"
"o=a 432432423423 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=image 5556 UDPTL t38\r\n"
"m=audio 5004 RTP/AVP 0\n"
"m=audio1 5006 RTP/AVP 8\n"
"m=audio2 5008 RTP/AVP 3\n"
"m=audio3 5010 RTP/AVP 9\n"
"m=audio4 5010 RTP/AVP 15\n"
;
char const b_caps[] =
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=audio 5008 RTP/AVP 0 8\r\n"
;
char const b_caps2[] =
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=audio 5008 RTP/AVP 0 8\r\n"
"m=image 5008 UDPTL t38\r\n"
"m=audio00 5008 RTP/AVP 0 8\r\n"
"m=audio01 5006 RTP/AVP 8\n"
"m=audio02 5008 RTP/AVP 3\n"
"m=audio03 5010 RTP/AVP 9\n"
"m=audio04 5010 RTP/AVP 15\n"
;
TEST_1(a = soa_create("static", ctx->root, ctx));
TEST_1(b = soa_create("static", ctx->root, ctx));
TEST_1(soa_set_params(a, SOATAG_ORDERED_USER(1),
TAG_END()) > 0);
TEST_1(soa_set_params(b, SOATAG_ORDERED_USER(1),
TAG_END()) > 0);
TEST(soa_set_user_sdp(a, 0, a_caps, strlen(a_caps)), 1);
TEST(soa_set_user_sdp(b, 0, b_caps, strlen(b_caps)), 1);
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, NULL, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
soa_process_reject(a, test_completed);
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, NULL, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
/* printf("offer1: %s\n", offer); */
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_get_local_sdp(b, NULL, &answer, &answerlen); TEST(n, 0);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
/* printf("answer1: %s\n", answer); */
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, NULL, NULL); TEST(n, 1);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST_1(a_sdp->sdp_media);
TEST_1(a_sdp->sdp_media->m_type == sdp_media_image);
TEST_1(a_sdp->sdp_media->m_next);
TEST_1(a_sdp->sdp_media->m_next->m_type == sdp_media_audio);
/* ---------------------------------------------------------------------- */
/* Re-O/A - activate image, add incompatible m= lines */
TEST_1(soa_set_params(b, SOATAG_RTP_MISMATCH(0),
SOATAG_USER_SDP_STR(b_caps2),
SOATAG_REUSE_REJECTED(1),
TAG_END()) > 0);
n = soa_generate_offer(b, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
n = soa_set_remote_sdp(a, 0, offer, offerlen); TEST(n, 1);
/* printf("offer2: %s\n", offer); */
n = soa_generate_answer(a, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
/* printf("answer2: %s\n", answer); */
n = soa_set_remote_sdp(b, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(b, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, NULL, NULL); TEST(n, 1);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(m = a_sdp->sdp_media);
TEST(m->m_type, sdp_media_image); TEST(m->m_proto, sdp_proto_udptl);
TEST_1(m->m_format); TEST_S(m->m_format->l_text, "t38");
TEST_1(m = b_sdp->sdp_media);
TEST(m->m_type, sdp_media_image); TEST(m->m_proto, sdp_proto_udptl);
TEST_1(m->m_format); TEST_S(m->m_format->l_text, "t38");
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
/* 2nd re-offer */
/* Add even more incompatible lines */
TEST_1(soa_set_params(a, SOATAG_RTP_MISMATCH(0),
SOATAG_USER_SDP_STR(a_caps2),
TAG_END()) > 0);
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, NULL, &offer, &offerlen); TEST(n, 1);
TEST_1(offer != NULL && offer != NONE);
/* printf("offer3: %s\n", offer); */
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_get_local_sdp(b, NULL, &answer, &answerlen); TEST(n, 1);
n = soa_generate_answer(b, test_completed); TEST(n, 0);
n = soa_get_local_sdp(b, &b_sdp, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
/* printf("answer3: %s\n", answer); */
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
n = soa_get_local_sdp(a, &a_sdp, NULL, NULL); TEST(n, 1);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST_VOID(soa_terminate(a, NULL));
TEST_VOID(soa_terminate(b, NULL));
TEST_VOID(soa_destroy(a));
TEST_VOID(soa_destroy(b));
END();
}
int test_asynch_offer_answer(struct context *ctx)
{
BEGIN();
#if 0 /* This has never been implemented */
int n;
char const *caps = NONE, *offer = NONE, *answer = NONE;
isize_t capslen = -1, offerlen = -1, answerlen = -1;
char const a[] =
"v=0\r\n"
"o=left 219498671 2 IN IP4 127.0.0.2\r\n"
"c=IN IP4 127.0.0.2\r\n"
"m=audio 5004 RTP/AVP 0 8\r\n";
char const b[] =
"v=0\n"
"o=right 93298573265 321974 IN IP4 127.0.0.3\n"
"c=IN IP4 127.0.0.3\n"
"m=audio 5006 RTP/AVP 96\n"
"m=rtpmap:96 GSM/8000\n";
n = soa_set_capability_sdp(ctx->asynch.a, 0,
"m=audio 5004 RTP/AVP 0 8", -1);
TEST(n, 1);
n = soa_set_capability_sdp(ctx->asynch.a, 0, a, strlen(a)); TEST(n, 1);
n = soa_get_capability_sdp(ctx->asynch.a, 0, &caps, &capslen); TEST(n, 1);
TEST_1(caps != NULL && caps != NONE);
TEST_1(capslen > 0);
n = soa_set_capability_sdp(ctx->asynch.b, 0, b, strlen(b)); TEST(n, 1);
n = soa_generate_offer(ctx->asynch.a, 1, test_completed); TEST(n, 1);
su_root_run(ctx->root); TEST(ctx->completed, ctx->asynch.a);
ctx->completed = NULL;
n = soa_get_local_sdp(ctx->asynch.a, 0, &offer, &offerlen); TEST(n, 1);
n = soa_set_remote_sdp(ctx->asynch.b, 0, offer, offerlen); TEST(n, 1);
n = soa_generate_answer(ctx->asynch.b, test_completed); TEST(n, 1);
su_root_run(ctx->root); TEST(ctx->completed, ctx->asynch.b);
ctx->completed = NULL;
TEST_1(soa_is_complete(ctx->asynch.b));
TEST(soa_activate(ctx->asynch.b, NULL), 0);
n = soa_get_local_sdp(ctx->asynch.b, 0, &answer, &answerlen); TEST(n, 1);
n = soa_set_remote_sdp(ctx->asynch.a, 0, answer, answerlen); TEST(n, 1);
n = soa_process_answer(ctx->asynch.a, test_completed); TEST(n, 1);
su_root_run(ctx->root); TEST(ctx->completed, ctx->asynch.a);
ctx->completed = NULL;
TEST_1(soa_is_complete(ctx->asynch.a));
TEST(soa_activate(ctx->asynch.a, NULL), 0);
TEST(soa_is_audio_active(ctx->asynch.a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_video_active(ctx->asynch.a), SOA_ACTIVE_DISABLED);
TEST(soa_is_image_active(ctx->asynch.a), SOA_ACTIVE_DISABLED);
TEST(soa_is_chat_active(ctx->asynch.a), SOA_ACTIVE_DISABLED);
TEST(soa_is_remote_audio_active(ctx->asynch.a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_video_active(ctx->asynch.a), SOA_ACTIVE_DISABLED);
TEST(soa_is_remote_image_active(ctx->asynch.a), SOA_ACTIVE_DISABLED);
TEST(soa_is_remote_chat_active(ctx->asynch.a), SOA_ACTIVE_DISABLED);
TEST(soa_deactivate(ctx->asynch.a, NULL), 0);
TEST(soa_deactivate(ctx->asynch.b, NULL), 0);
TEST_VOID(soa_terminate(ctx->asynch.a, NULL));
TEST(soa_is_audio_active(ctx->asynch.a), SOA_ACTIVE_DISABLED);
TEST(soa_is_remote_audio_active(ctx->asynch.a), SOA_ACTIVE_DISABLED);
TEST_VOID(soa_terminate(ctx->asynch.b, NULL));
#endif
END();
}
#define TEST_OC_ADDRESS(s, address, ip) \
TEST(test_address_in_offer(s, address, sdp_addr_ ## ip, address, sdp_addr_ ## ip), 0);
static int
test_address_in_offer(soa_session_t *ss,
char const *o_address,
int o_addrtype,
char const *c_address,
int c_addrtype)
{
sdp_session_t const *sdp = NULL;
sdp_connection_t const *c;
TEST(soa_get_local_sdp(ss, &sdp, NULL, NULL), 1);
TEST_1(sdp != NULL);
TEST_1(c = sdp->sdp_connection);
TEST(c->c_nettype, sdp_net_in);
if (c_addrtype) TEST(c->c_addrtype, c_addrtype);
if (c_address) TEST_S(c->c_address, c_address);
TEST_1(c = sdp->sdp_origin->o_address);
TEST(c->c_nettype, sdp_net_in);
if (o_addrtype) TEST(c->c_addrtype, o_addrtype);
if (o_address) TEST_S(c->c_address, o_address);
return 0;
}
/** This tests the IP address selection logic.
*
* The IP address is selected based on the SOATAG_AF() preference,
* SOATAG_ADDRESS(), and locally obtained address list.
*/
int test_address_selection(struct context *ctx)
{
BEGIN();
int n;
static char const *ifaces1[] = {
"eth2\0" "192.168.2.15\0" "fc00:db20:35b:7399::5:a0ff:fe71:815\0" "fe80::21a:a0ff:fe71:815\0",
"eth0\0" "1192.168.127.12\0" "2fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:fe71:813\0" "fe80::21a:a0ff:fe71:813\0",
"eth1\0" "12.13.14.15\0" "fdf8:f53e:61e4::18:a0ff:fe71:814\0" "fe80::21a:a0ff:fe71:814\0",
"lo0\0" "127.0.0.1\0" "::1\0",
NULL
};
static char const *ifaces_ip6only[] = {
"eth2\0" "fc00:db20:35b:7399::5:a0ff:fe71:815\0" "fe80::21a:a0ff:fe71:815\0",
"eth0\0" "fdf8:f53e:61e4::18:813\0" "fe80::21a:a0ff:fe71:813\0",
"eth1\0" "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:fe71:814\0" "fe80::21a:a0ff:fe71:814\0",
"lo0\0" "127.0.0.1\0" "::1\0",
NULL
};
static char const *ifaces_ip4only[] = {
"eth2\0" "192.168.2.15\0" "fe80::21a:a0ff:fe71:815\0",
"eth0\0" "11.12.13.14\0" "fe80::21a:a0ff:fe71:813\0",
"eth1\0" "12.13.14.15\0" "fe80::21a:a0ff:fe71:814\0",
"lo0\0" "127.0.0.1\0" "::1\0",
NULL
};
soa_session_t *a, *b;
sdp_origin_t *o;
su_home_t home[1] = { SU_HOME_INIT(home) };
s2_localinfo_ifaces(ifaces1);
TEST_1(a = soa_clone(ctx->a, ctx->root, ctx));
/* SOATAG_AF(SOA_AF_IP4_ONLY) => select IP4 address */
n = soa_set_params(a, SOATAG_AF(SOA_AF_IP4_ONLY), TAG_END());
n = soa_set_user_sdp(a, 0, "m=audio 5008 RTP/AVP 0 8", -1); TEST(n, 1);
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
TEST_OC_ADDRESS(a, "11.12.13.14", ip4);
/* Should flush the session */
TEST_VOID(soa_process_reject(a, NULL));
/* SOATAG_AF(SOA_AF_IP6_ONLY) => select IP6 address */
n = soa_set_params(a, SOATAG_AF(SOA_AF_IP6_ONLY), TAG_END());
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
TEST_OC_ADDRESS(a, "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:a0ff:fe71:813", ip6);
TEST_VOID(soa_terminate(a, NULL));
/* SOATAG_AF(SOA_AF_IP4_IP6) => select IP4 address */
n = soa_set_params(a, SOATAG_AF(SOA_AF_IP4_IP6), TAG_END());
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
TEST_OC_ADDRESS(a, "11.12.13.14", ip4);
TEST_VOID(soa_process_reject(a, NULL));
/* SOATAG_AF(SOA_AF_IP6_IP4) => select IP6 address */
n = soa_set_params(a, SOATAG_AF(SOA_AF_IP6_IP4), TAG_END());
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
TEST_OC_ADDRESS(a, "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:a0ff:fe71:813", ip6);
TEST_VOID(soa_terminate(a, NULL));
/* SOATAG_AF(SOA_AF_IP4_IP6) but session mentions IP6 => select IP6 */
n = soa_set_params(a, SOATAG_AF(SOA_AF_IP4_IP6), TAG_END());
n = soa_set_user_sdp(a, 0, "c=IN IP6 ::\r\nm=audio 5008 RTP/AVP 0 8", -1); TEST(n, 1);
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
TEST_OC_ADDRESS(a, "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:a0ff:fe71:813", ip6);
TEST_VOID(soa_terminate(a, NULL));
/* SOATAG_AF(SOA_AF_IP4_IP6), o= mentions IP6 => select IP4 */
n = soa_set_user_sdp(a, 0, "o=- 1 1 IN IP6 ::\r\n"
"m=audio 5008 RTP/AVP 0 8", -1); TEST(n, 1);
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
TEST_OC_ADDRESS(a, "11.12.13.14", ip4);
TEST_VOID(soa_process_reject(a, NULL));
/* SOATAG_AF(SOA_AF_IP4_IP6), c= uses non-local IP6
=> select local IP6 on o= */
n = soa_set_user_sdp(a, 0,
"c=IN IP6 fdf8:f53e:61e4::18:a0ff:fe71:819\r\n"
"m=audio 5008 RTP/AVP 0 8", -1);
TEST(n, 1);
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
TEST(test_address_in_offer(a,
/* o= has local address */
"fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:a0ff:fe71:813", sdp_addr_ip6,
/* c= has sdp-provided address */
"fdf8:f53e:61e4::18:a0ff:fe71:819", sdp_addr_ip6), 0);
TEST_VOID(soa_terminate(a, NULL));
/* SOATAG_AF(SOA_AF_IP4_ONLY), no IP4 addresses */
s2_localinfo_ifaces(ifaces_ip6only);
n = soa_set_params(a, SOATAG_AF(SOA_AF_IP4_ONLY), TAG_END());
n = soa_set_user_sdp(a, 0, "m=audio 5008 RTP/AVP 0 8", -1);
TEST(soa_generate_offer(a, 1, test_completed), -1);
/* Retry with IP6 enabled */
n = soa_set_params(a, SOATAG_AF(SOA_AF_IP4_IP6), TAG_END());
TEST(soa_generate_offer(a, 1, test_completed), 0);
TEST_OC_ADDRESS(a, "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:a0ff:fe71:813", ip6);
TEST_VOID(soa_terminate(a, NULL));
/* SOATAG_AF(SOA_AF_IP6_ONLY), no IP6 addresses */
s2_localinfo_ifaces(ifaces_ip4only);
n = soa_set_params(a, SOATAG_AF(SOA_AF_IP6_ONLY), TAG_END());
TEST(soa_generate_offer(a, 1, test_completed), -1); /* should fail */
TEST_VOID(soa_terminate(a, NULL));
/* SOATAG_AF(SOA_AF_IP4_ONLY), no IP4 addresses */
s2_localinfo_ifaces(ifaces_ip6only);
n = soa_set_params(a, SOATAG_AF(SOA_AF_IP4_ONLY), TAG_END());
TEST(soa_generate_offer(a, 1, test_completed), -1); /* should fail */
TEST_VOID(soa_terminate(a, NULL));
/* Select locally available address from the SOATAG_ADDRESS() list */
s2_localinfo_ifaces(ifaces1);
n = soa_set_params(a, SOATAG_AF(SOA_AF_IP4_IP6),
SOATAG_ADDRESS("test.com 17.18.19.20 12.13.14.15"),
TAG_END());
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
TEST_OC_ADDRESS(a, "12.13.14.15", ip4);
TEST_VOID(soa_process_reject(a, NULL));
/* Select locally available IP6 address from the SOATAG_ADDRESS() list */
n = soa_set_params(a, SOATAG_AF(SOA_AF_IP6_IP4),
SOATAG_ADDRESS("test.com 12.13.14.15 ffc00:e968:6179::de52:7100:a0ff:fe71:815"),
TAG_END());
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
TEST_OC_ADDRESS(a, "fc00:db20:35b:7399::5:a0ff:fe71:815", ip6);
TEST_VOID(soa_process_reject(a, NULL));
/* Select first available address from the SOATAG_ADDRESS() list */
n = soa_set_params(a, SOATAG_AF(SOA_AF_ANY),
SOATAG_ADDRESS("test.com 12.13.14.15 ffc00:e968:6179::de52:7100:a0ff:fe71:815"),
TAG_END());
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
TEST_OC_ADDRESS(a, "12.13.14.15", ip4);
TEST_VOID(soa_process_reject(a, NULL));
/* Select preferred address from the SOATAG_ADDRESS() list */
s2_localinfo_ifaces(ifaces1);
n = soa_set_params(a, SOATAG_AF(SOA_AF_IP4_IP6),
SOATAG_ADDRESS("test.com ffc00:e968:6179::de52:7100:a0ff:fe71:815 19.18.19.20"),
TAG_END());
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
TEST_OC_ADDRESS(a, "19.18.19.20", ip4);
TEST_VOID(soa_process_reject(a, NULL));
/* Select preferred address from the SOATAG_ADDRESS() list */
s2_localinfo_ifaces(ifaces1);
n = soa_set_params(a, SOATAG_AF(SOA_AF_IP6_IP4),
SOATAG_ADDRESS("test.com 19.18.19.20 ffc00:e968:6179::de52:7100:a0ff:fe71:815 ffc00:e968:6179::de52:7100:a0ff:fe71:819"),
TAG_END());
n = soa_generate_offer(a, 1, test_completed); TEST(n, 0);
TEST_OC_ADDRESS(a, "fdf8:f53e:61e4::18:a0ff:fe71:815", ip6);
TEST_VOID(soa_process_reject(a, NULL));
TEST_VOID(soa_destroy(a));
(void)b; (void)o;
#if 0
TEST_1(b = soa_clone(ctx->b, ctx->root, ctx));
n = soa_set_remote_sdp(b, 0, offer, offerlen); TEST(n, 1);
n = soa_get_local_sdp(b, NULL, &answer, &answerlen); TEST(n, 0);
n = soa_set_params(b,
SOATAG_LOCAL_SDP_STR("m=audio 5004 RTP/AVP 8"),
SOATAG_AF(SOA_AF_IP4_ONLY),
SOATAG_ADDRESS("1.2.3.4"),
TAG_END());
n = soa_generate_answer(b, test_completed); TEST(n, 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
n = soa_get_local_sdp(b, NULL, &answer, &answerlen); TEST(n, 1);
TEST_1(answer != NULL && answer != NONE);
TEST_1(strstr(answer, "c=IN IP4 1.2.3.4"));
n = soa_set_remote_sdp(a, 0, answer, -1); TEST(n, 1);
n = soa_process_answer(a, test_completed); TEST(n, 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_video_active(a), SOA_ACTIVE_DISABLED);
TEST(soa_is_image_active(a), SOA_ACTIVE_DISABLED);
TEST(soa_is_chat_active(a), SOA_ACTIVE_DISABLED);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_video_active(a), SOA_ACTIVE_DISABLED);
TEST(soa_is_remote_image_active(a), SOA_ACTIVE_DISABLED);
TEST(soa_is_remote_chat_active(a), SOA_ACTIVE_DISABLED);
/* 'A' will put call on hold */
offer = NONE;
TEST(soa_set_params(a, SOATAG_HOLD("*"), TAG_END()), 1);
TEST(soa_generate_offer(a, 1, test_completed), 0);
TEST(soa_get_local_sdp(a, NULL, &offer, &offerlen), 1);
TEST_1(offer != NULL && offer != NONE);
TEST_1(strstr(offer, "a=sendonly"));
TEST(soa_set_remote_sdp(b, 0, offer, offerlen), 1);
TEST(soa_generate_answer(b, test_completed), 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST(soa_get_local_sdp(b, NULL, &answer, &answerlen), 1);
TEST_1(answer != NULL && answer != NONE);
TEST_1(strstr(answer, "a=recvonly"));
TEST(soa_set_remote_sdp(a, 0, answer, -1), 1);
TEST(soa_process_answer(a, test_completed), 0);
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDONLY);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDONLY);
/* 'A' will put call inactive */
offer = NONE;
TEST(soa_set_params(a, SOATAG_HOLD("#"), TAG_END()), 1);
TEST(soa_generate_offer(a, 1, test_completed), 0);
TEST(soa_get_local_sdp(a, NULL, &offer, &offerlen), 1);
TEST_1(offer != NULL && offer != NONE);
TEST_1(strstr(offer, "a=inactive"));
TEST(soa_set_remote_sdp(b, 0, offer, offerlen), 1);
TEST(soa_generate_answer(b, test_completed), 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST(soa_get_local_sdp(b, NULL, &answer, &answerlen), 1);
TEST_1(answer != NULL && answer != NONE);
TEST_1(strstr(answer, "a=inactive"));
TEST(soa_set_remote_sdp(a, 0, answer, -1), 1);
TEST(soa_process_answer(a, test_completed), 0);
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_INACTIVE);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_INACTIVE);
/* B will send an offer to A, but there is no change in O/A status */
TEST(soa_generate_offer(b, 1, test_completed), 0);
TEST(soa_get_local_sdp(b, NULL, &offer, &offerlen), 1);
TEST_1(offer != NULL && offer != NONE);
TEST_1(!strstr(offer, "a=inactive"));
/* printf("offer:\n%s", offer); */
TEST(soa_set_remote_sdp(a, 0, offer, offerlen), 1);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_generate_answer(a, test_completed), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_INACTIVE);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_INACTIVE);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_get_local_sdp(a, NULL, &answer, &answerlen), 1);
TEST_1(answer != NULL && answer != NONE);
TEST_1(strstr(answer, "a=inactive"));
/* printf("answer:\n%s", answer); */
TEST(soa_set_remote_sdp(b, 0, answer, -1), 1);
TEST(soa_process_answer(b, test_completed), 0);
TEST(soa_activate(b, NULL), 0);
TEST(soa_is_audio_active(b), SOA_ACTIVE_INACTIVE);
TEST(soa_is_remote_audio_active(b), SOA_ACTIVE_INACTIVE);
/* 'A' will release hold. */
TEST(soa_set_params(a, SOATAG_HOLD(NULL), TAG_END()), 1);
TEST(soa_generate_offer(a, 1, test_completed), 0);
TEST(soa_get_local_sdp(a, NULL, &offer, &offerlen), 1);
TEST_1(offer != NULL && offer != NONE);
TEST_1(!strstr(offer, "a=sendonly") && !strstr(offer, "a=inactive"));
TEST(soa_set_remote_sdp(b, 0, offer, offerlen), 1);
TEST(soa_generate_answer(b, test_completed), 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST(soa_get_local_sdp(b, NULL, &answer, &answerlen), 1);
TEST_1(answer != NULL && answer != NONE);
TEST_1(!strstr(answer, "a=recvonly") && !strstr(answer, "a=inactive"));
TEST(soa_set_remote_sdp(a, 0, answer, -1), 1);
TEST(soa_process_answer(a, test_completed), 0);
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
/* 'A' will put B on hold but this time with c=IN IP4 0.0.0.0 */
TEST(soa_set_params(a, SOATAG_HOLD("*"), TAG_END()), 1);
TEST(soa_generate_offer(a, 1, test_completed), 0);
{
sdp_session_t const *o_sdp;
sdp_session_t *sdp;
sdp_printer_t *p;
sdp_connection_t *c;
TEST(soa_get_local_sdp(a, &o_sdp, NULL, NULL), 1);
TEST_1(o_sdp != NULL && o_sdp != NONE);
TEST_1(sdp = sdp_session_dup(home, o_sdp));
/* Remove mode, change c=, encode offer */
if (sdp->sdp_media->m_connections)
c = sdp->sdp_media->m_connections;
else
c = sdp->sdp_connection;
TEST_1(c);
c->c_address = "0.0.0.0";
TEST_1(p = sdp_print(home, sdp, NULL, 0, sdp_f_realloc));
TEST_1(sdp_message(p));
offer = sdp_message(p); offerlen = strlen(offer);
}
TEST(soa_set_remote_sdp(b, 0, offer, -1), 1);
TEST(soa_generate_answer(b, test_completed), 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST(soa_get_local_sdp(b, NULL, &answer, &answerlen), 1);
TEST_1(answer != NULL && answer != NONE);
TEST_1(strstr(answer, "a=recvonly"));
TEST(soa_set_remote_sdp(a, 0, answer, -1), 1);
TEST(soa_process_answer(a, test_completed), 0);
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDONLY);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDONLY);
TEST(soa_is_audio_active(b), SOA_ACTIVE_RECVONLY);
TEST(soa_is_remote_audio_active(b), SOA_ACTIVE_RECVONLY);
/* 'A' will propose adding video. */
/* 'B' will reject. */
TEST(soa_set_params(a,
SOATAG_HOLD(NULL), /* 'A' will release hold. */
SOATAG_USER_SDP_STR("m=audio 5008 RTP/AVP 0 8\r\ni=x\r\n"
"m=video 5006 RTP/AVP 34\r\n"),
TAG_END()), 2);
TEST(soa_generate_offer(a, 1, test_completed), 0);
TEST(soa_get_local_sdp(a, NULL, &offer, &offerlen), 1);
TEST_1(offer != NULL && offer != NONE);
TEST_1(!strstr(offer, "a=sendonly"));
TEST_1(strstr(offer, "m=video"));
TEST(soa_set_remote_sdp(b, 0, offer, offerlen), 1);
TEST(soa_generate_answer(b, test_completed), 0);
TEST_1(soa_is_complete(b));
TEST(soa_activate(b, NULL), 0);
TEST(soa_get_local_sdp(b, NULL, &answer, &answerlen), 1);
TEST_1(answer != NULL && answer != NONE);
TEST_1(!strstr(answer, "a=recvonly"));
TEST_1(strstr(answer, "m=video"));
TEST(soa_set_remote_sdp(a, 0, answer, -1), 1);
TEST(soa_process_answer(a, test_completed), 0);
TEST(soa_activate(a, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_video_active(a), SOA_ACTIVE_REJECTED);
{
/* Test tags */
sdp_session_t const *l = NULL, *u = NULL, *r = NULL;
sdp_media_t const *m;
TEST(soa_get_params(b,
SOATAG_LOCAL_SDP_REF(l),
SOATAG_USER_SDP_REF(u),
SOATAG_REMOTE_SDP_REF(r),
TAG_END()), 3);
TEST_1(l); TEST_1(u); TEST_1(r);
TEST_1(m = l->sdp_media); TEST(m->m_type, sdp_media_audio);
TEST_1(!m->m_rejected);
TEST_1(m = m->m_next); TEST(m->m_type, sdp_media_video);
TEST_1(m->m_rejected);
}
/* 'B' will now propose adding video. */
/* 'A' will accept. */
TEST(soa_set_params(b,
SOATAG_USER_SDP_STR("m=audio 5004 RTP/AVP 0 8\r\n"
"m=video 5006 RTP/AVP 34\r\n"),
TAG_END()), 1);
TEST(soa_generate_offer(b, 1, test_completed), 0);
TEST(soa_get_local_sdp(b, NULL, &offer, &offerlen), 1);
TEST_1(offer != NULL && offer != NONE);
TEST_1(!strstr(offer, "b=sendonly"));
TEST_1(strstr(offer, "m=video"));
TEST(soa_set_remote_sdp(a, 0, offer, offerlen), 1);
TEST(soa_generate_answer(a, test_completed), 0);
TEST_1(soa_is_complete(a));
TEST(soa_activate(a, NULL), 0);
TEST(soa_get_local_sdp(a, NULL, &answer, &answerlen), 1);
TEST_1(answer != NULL && answer != NONE);
TEST_1(!strstr(answer, "b=recvonly"));
TEST_1(strstr(answer, "m=video"));
TEST(soa_set_remote_sdp(b, 0, answer, -1), 1);
TEST(soa_process_answer(b, test_completed), 0);
TEST(soa_activate(b, NULL), 0);
TEST(soa_is_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_SENDRECV);
TEST(soa_is_video_active(a), SOA_ACTIVE_SENDRECV);
TEST_VOID(soa_terminate(a, NULL));
TEST(soa_is_audio_active(a), SOA_ACTIVE_DISABLED);
TEST(soa_is_remote_audio_active(a), SOA_ACTIVE_DISABLED);
TEST_VOID(soa_terminate(b, NULL));
TEST_VOID(soa_destroy(a));
TEST_VOID(soa_destroy(b));
#endif
su_home_deinit(home);
s2_localinfo_teardown();
END();
}
int test_deinit(struct context *ctx)
{
BEGIN();
su_root_destroy(ctx->root), ctx->root = NULL;
soa_destroy(ctx->a);
soa_destroy(ctx->b);
END();
}
#if HAVE_ALARM
static RETSIGTYPE sig_alarm(int s)
{
fprintf(stderr, "%s: FAIL! test timeout!\n", name);
exit(1);
}
#endif
void usage(int exitcode)
{
fprintf(stderr,
"usage: %s [-v|-q] [-a] [-l level] [-p outbound-proxy-uri]\n",
name);
exit(exitcode);
}
int main(int argc, char *argv[])
{
int retval = 0, quit_on_single_failure = 0;
int i, o_attach = 0, o_alarm = 1;
struct context ctx[1] = {{{ SU_HOME_INIT(ctx) }}};
for (i = 1; argv[i]; i++) {
if (strcmp(argv[i], "-v") == 0)
tstflags |= tst_verbatim;
else if (strcmp(argv[i], "-a") == 0)
tstflags |= tst_abort;
else if (strcmp(argv[i], "-q") == 0)
tstflags &= ~tst_verbatim;
else if (strcmp(argv[i], "-1") == 0)
quit_on_single_failure = 1;
else if (strncmp(argv[i], "-l", 2) == 0) {
int level = 3;
char *rest = NULL;
if (argv[i][2])
level = strtol(argv[i] + 2, &rest, 10);
else if (argv[i + 1])
level = strtol(argv[i + 1], &rest, 10), i++;
else
level = 3, rest = "";
if (rest == NULL || *rest)
usage(1);
su_log_set_level(soa_log, level);
}
else if (strcmp(argv[i], "--attach") == 0) {
o_attach = 1;
}
else if (strcmp(argv[i], "--no-alarm") == 0) {
o_alarm = 0;
}
else if (strcmp(argv[i], "-") == 0) {
i++; break;
}
else if (argv[i][0] != '-') {
break;
}
else
usage(1);
}
#if HAVE_OPEN_C
tstflags |= tst_verbatim;
#endif
if (o_attach) {
char line[10], *cr;
printf("%s: pid %u\n", name, getpid());
printf("<Press RETURN to continue>\n");
cr = fgets(line, sizeof line, stdin);
(void)cr;
}
#if HAVE_ALARM
else if (o_alarm) {
alarm(60);
signal(SIGALRM, sig_alarm);
}
#endif
su_init();
if (!(TSTFLAGS & tst_verbatim)) {
su_log_soft_set_level(soa_log, 0);
}
#define SINGLE_FAILURE_CHECK() \
do { fflush(stdout); \
if (retval && quit_on_single_failure) { su_deinit(); return retval; } \
} while(0)
retval |= test_localinfo_replacement(); SINGLE_FAILURE_CHECK();
retval |= test_api_errors(ctx); SINGLE_FAILURE_CHECK();
retval |= test_soa_tags(ctx); SINGLE_FAILURE_CHECK();
retval |= test_init(ctx, argv + i); SINGLE_FAILURE_CHECK();
if (retval == 0) {
retval |= test_address_selection(ctx); SINGLE_FAILURE_CHECK();
retval |= test_large_sessions(ctx); SINGLE_FAILURE_CHECK();
retval |= test_params(ctx); SINGLE_FAILURE_CHECK();
retval |= test_static_offer_answer(ctx); SINGLE_FAILURE_CHECK();
retval |= test_codec_selection(ctx); SINGLE_FAILURE_CHECK();
retval |= test_media_replace(ctx); SINGLE_FAILURE_CHECK();
retval |= test_media_removal(ctx); SINGLE_FAILURE_CHECK();
retval |= test_media_reject(ctx); SINGLE_FAILURE_CHECK();
retval |= test_media_replace2(ctx); SINGLE_FAILURE_CHECK();
retval |= test_media_mode(ctx); SINGLE_FAILURE_CHECK();
retval |= test_asynch_offer_answer(ctx); SINGLE_FAILURE_CHECK();
}
retval |= test_deinit(ctx); SINGLE_FAILURE_CHECK();
su_deinit();
#if HAVE_OPEN_C
sleep(5);
#endif
return retval;
}
|
rajkumarc2000/Insights | PlatformEngine/src/main/java/com/cognizant/devops/platformengine/modules/correlation/EngineCorrelationNodeBuilderModule.java | /*******************************************************************************
* Copyright 2017 Cognizant Technology Solutions
*
* 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 com.cognizant.devops.platformengine.modules.correlation;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.cognizant.devops.platformcommons.constants.ConfigOptions;
import com.cognizant.devops.platformcommons.dal.neo4j.GraphDBException;
import com.cognizant.devops.platformcommons.dal.neo4j.Neo4jDBHandler;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
public class EngineCorrelationNodeBuilderModule {
private static Logger log = LogManager.getLogger(EngineCorrelationNodeBuilderModule.class.getName());
public void initializeCorrelationNodes() {
BufferedReader reader = null;
InputStream in = null;
File correlationTemplate = new File(ConfigOptions.CORRELATION_FILE_RESOLVED_PATH);
try {
if (correlationTemplate.exists()) {
reader = new BufferedReader(new FileReader(correlationTemplate));
} else {
in = getClass().getResourceAsStream("/" + ConfigOptions.CORRELATION_TEMPLATE);
reader = new BufferedReader(new InputStreamReader(in));
}
JsonElement correlationJson = new JsonParser().parse(reader);
// reader.close();
JsonArray correlations = correlationJson.getAsJsonObject().get("correlations").getAsJsonArray();
Neo4jDBHandler graphDBHandler = new Neo4jDBHandler();
for (JsonElement correlation : correlations) {
graphDBHandler.executeCypherQuery(
"MERGE (n:CORRELATION { query : '" + correlation.getAsString() + "' } ) return n");
}
} catch (FileNotFoundException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
} catch (GraphDBException e) {
log.error(e);
} finally {
try {
if (in != null) {
in.close();
}
if (reader != null) {
reader.close();
}
} catch (IOException e) {
log.error(e);
}
}
}
}
|
Magnarox/model | src/main/java/com/magnarox/snds/model/repositories/ErInvFRepository.java | <reponame>Magnarox/model
package com.magnarox.snds.model.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import com.magnarox.snds.model.entities.ErInvF;
public interface ErInvFRepository extends JpaRepository<ErInvF, Void>, JpaSpecificationExecutor<ErInvF> {
} |
charlievieth/utils | watchman-completion/main.go | <gh_stars>1-10
package main
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"runtime"
"strings"
"github.com/posener/complete/v2"
"github.com/posener/complete/v2/predict"
)
/*
Usage: watchman [opts] command
-h, --help Show this help
--inetd Spawning from an inetd style supervisor
-v, --version Show version number
-U, --sockname=PATH Specify alternate sockname
-o, --logfile=PATH Specify path to logfile
--log-level set the log level (0 = off, default is 1, verbose = 2)
--pidfile=PATH Specify path to pidfile
-p, --persistent Persist and wait for further responses
-n, --no-save-state Don't save state between invocations
--statefile=PATH Specify path to file to hold watch and trigger state
-j, --json-command Instead of parsing CLI arguments, take a single json object from stdin
--output-encoding=ARG CLI output encoding. json (default) or bser
--server-encoding=ARG CLI<->server encoding. bser (default) or json
-f, --foreground Run the service in the foreground
--no-pretty Don't pretty print JSON
--no-spawn Don't try to start the service if it is not available
--no-local When no-spawn is enabled, don't try to handle request in client mode if service is unavailable
Available commands:
clock
debug-ageout
debug-contenthash
debug-drop-privs
debug-fsevents-inject-drop
debug-get-subscriptions
debug-poison
debug-recrawl
debug-set-subscriptions-paused
debug-show-cursors
find
flush-subscriptions
get-config
get-pid
get-sockname
list-capabilities
log
log-level
query
shutdown-server
since
state-enter
state-leave
subscribe
trigger
trigger-del
trigger-list
unsubscribe
version
watch
watch-del
watch-del-all
watch-list
watch-project
See https://github.com/facebook/watchman#watchman for more help
Watchman, by <NAME>.
Copyright 2012-2017 Facebook, Inc.
*/
/*
{
"version": "4.9.0",
"roots": [
"/Users/cvieth/go/src/github.com/posener/complete",
"/Users/cvieth/go/src/github.com/cockroachlabs/managed-service"
]
}
*/
type ListResponse struct {
Version string `json:"version"`
Roots []string `json:"roots"`
}
func WatchList() []string {
out, err := exec.Command("watchman", "watch-list").Output()
if err != nil {
if e, ok := err.(*exec.ExitError); ok {
fmt.Fprintf(os.Stderr, "Error: %s\n%s\n",
e.Error(), string(bytes.TrimSpace(e.Stderr)))
os.Exit(1)
}
}
var res ListResponse
if err := json.Unmarshal(out, &res); err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
return res.Roots
}
const CaseInsensitive = runtime.GOOS == "darwin" || runtime.GOOS == "windows"
func HasPathPrefix(s, prefix string) bool {
return len(s) >= len(prefix) && (s[0:len(prefix)] == prefix ||
(CaseInsensitive && strings.EqualFold(s[0:len(prefix)], prefix)))
}
func CompleteWatchList(prefix string) []string {
watches := WatchList()
if len(watches) == 0 {
return nil
}
a := watches[:0]
for _, s := range watches {
if HasPathPrefix(s, prefix) {
a = append(a, s)
}
}
return a
}
func main() {
watch := &complete.Command{
Flags: map[string]complete.Predictor{
"inetd": predict.Nothing,
"log-level": predict.Nothing,
"no-local": predict.Nothing,
"no-pretty": predict.Nothing,
"no-spawn": predict.Nothing,
"output-encoding": predict.Set{"json", "bser"},
"pidfile": predict.Files("*"),
"server-encoding": predict.Set{"bser", "json"},
"statefile": predict.Files("*"),
"f": predict.Nothing,
"foreground": predict.Nothing,
"h": predict.Nothing,
"help": predict.Nothing,
"j": predict.Nothing,
"json-command": predict.Nothing,
"n": predict.Nothing,
"no-save-state": predict.Nothing,
"o": predict.Nothing,
"logfile": predict.Files("*"),
"p": predict.Nothing,
"persistent": predict.Nothing,
"U": predict.Nothing,
"sockname": predict.Files("*"),
"v": predict.Nothing,
"version": predict.Nothing,
},
Sub: map[string]*complete.Command{
"clock": {},
"debug-ageout": {},
"debug-contenthash": {},
"debug-drop-privs": {},
"debug-fsevents-inject-drop": {},
"debug-get-subscriptions": {},
"debug-poison": {},
"debug-recrawl": {},
"debug-set-subscriptions-paused": {},
"debug-show-cursors": {},
"find": {},
"flush-subscriptions": {},
"get-config": {},
"get-pid": {},
"get-sockname": {},
"list-capabilities": {},
"log": {},
"log-level": {},
"query": {},
"shutdown-server": {
Args: predict.Nothing,
},
"since": {},
"state-enter": {},
"state-leave": {},
"subscribe": {},
"trigger": {
Args: complete.PredictFunc(CompleteWatchList),
},
"trigger-del": {},
"trigger-list": {
Args: complete.PredictFunc(CompleteWatchList),
},
"unsubscribe": {
Args: complete.PredictFunc(CompleteWatchList),
},
"version": {},
"watch": {
Args: predict.Or(predict.Dirs("*"), predict.Files("*")),
},
"watch-del": {
Args: complete.PredictFunc(CompleteWatchList),
},
"watch-del-all": {},
"watch-list": {
Args: complete.PredictFunc(CompleteWatchList),
},
"watch-project": {
Args: predict.Or(predict.Dirs("*"), predict.Files("*")),
},
},
}
watch.Complete("watchman")
}
|
Ecotrust/formhub | main/tests/test_google_doc.py | <filename>main/tests/test_google_doc.py
import os
from django.test import TestCase
from main.views import GoogleDoc
class TestGoogleDoc(TestCase):
def test_view(self):
doc = GoogleDoc()
folder = os.path.join(
os.path.dirname(__file__), "fixtures", "google_doc"
)
input_path = os.path.join(folder, "input.html")
with open(input_path) as f:
input_html = f.read()
doc.set_html(input_html)
self.assertEqual(doc._html, input_html)
self.assertEqual(len(doc._sections), 14)
output_path = os.path.join(folder, "navigation.html")
with open(output_path) as f:
self.assertEquals(doc._navigation_html(), f.read())
|
YAPP-18th/Android-Team-1-Backend | mureng-batch/src/main/java/net/mureng/batch/todayexpression/maintain/service/TodayUsefulExpressionMaintainServiceImpl.java | package net.mureng.batch.todayexpression.maintain.service;
import lombok.RequiredArgsConstructor;
import net.mureng.core.core.component.NumberRandomizer;
import net.mureng.core.core.exception.MurengException;
import net.mureng.core.todayexpression.entity.TodayUsefulExpression;
import net.mureng.core.todayexpression.entity.UsefulExpression;
import net.mureng.core.todayexpression.repository.TodayUsefulExpressionRepository;
import net.mureng.core.todayexpression.repository.UsefulExpressionRepository;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static net.mureng.core.core.message.ErrorMessage.EXPRESSION_REFRESH_FAIL;
@Service
@RequiredArgsConstructor
public class TodayUsefulExpressionMaintainServiceImpl implements TodayUsefulExpressionMaintainService {
private static final int MAXIMUM_USEFUL_EXPRESSION_COUNT = 2;
private static final int MAX_TOLERATE = 1000;
private final UsefulExpressionRepository usefulExpressionRepository;
private final TodayUsefulExpressionRepository todayUsefulExpressionRepository;
private final NumberRandomizer numberRandomizer;
// 2개까지 유지
public void maintain() {
List<TodayUsefulExpression> todayUsefulExpressions = todayUsefulExpressionRepository.findAll();
if (todayUsefulExpressions.size() == MAXIMUM_USEFUL_EXPRESSION_COUNT) {
return;
}
if (todayUsefulExpressions.size() < MAXIMUM_USEFUL_EXPRESSION_COUNT) {
int rest = MAXIMUM_USEFUL_EXPRESSION_COUNT - todayUsefulExpressions.size();
long[] randomIds = getRandomIds(rest);
for (long randomId : randomIds) {
TodayUsefulExpression todayUsefulExpression = TodayUsefulExpression.builder()
.usefulExpression(UsefulExpression.builder()
.expId(randomId).build())
.build();
todayUsefulExpressionRepository.save(todayUsefulExpression);
}
} else {
for (int i = todayUsefulExpressions.size() - 1; i > MAXIMUM_USEFUL_EXPRESSION_COUNT; i--) {
todayUsefulExpressionRepository.delete(todayUsefulExpressions.get(i));
}
}
todayUsefulExpressionRepository.flush();
}
private long[] getRandomIds(int count) { // TODO 중복 제거
Set<Long> checked = new HashSet<>();
long[] randomIds = new long[count];
int retry = 0;
int index = 0;
while (retry < MAX_TOLERATE) {
retry++;
long randomId = getRandomId();
if (checked.contains(randomId)) {
continue;
}
checked.add(randomId);
randomIds[index] = randomId;
if (++index == count) {
return randomIds;
}
}
throw new MurengException(EXPRESSION_REFRESH_FAIL);
}
private long getRandomId() {
int highestId = getHighestId();
for (int i = 0; i < MAX_TOLERATE; i++) {
long randomId = numberRandomizer.getRandomInt(highestId);
if (! usefulExpressionRepository.existsById(randomId)) {
continue;
}
return randomId;
}
return highestId;
}
private int getHighestId() {
return (int)(long)usefulExpressionRepository.findAll(PageRequest.of(0, 1,
Sort.by(Sort.Direction.DESC, "expId")))
.getContent().get(0).getExpId();
}
}
|
nvaller/newrelic-client-go | pkg/plugins/components.go | package plugins
import (
"fmt"
"time"
)
// ListComponentsParams represents a set of filters to be
// used when querying New Relic applications.
type ListComponentsParams struct {
Name string `url:"filter[name],omitempty"`
IDs []int `url:"filter[ids],omitempty,comma"`
PluginID int `url:"filter[plugin_id],omitempty"`
HealthStatus bool `url:"health_status,omitempty"`
}
// ListComponents is used to retrieve the components associated with
// a New Relic account.
func (p *Plugins) ListComponents(params *ListComponentsParams) ([]*Component, error) {
response := componentsResponse{}
c := []*Component{}
nextURL := "/components.json"
for nextURL != "" {
resp, err := p.client.Get(nextURL, ¶ms, &response)
if err != nil {
return nil, err
}
c = append(c, response.Components...)
paging := p.pager.Parse(resp)
nextURL = paging.Next
}
return c, nil
}
// GetComponent is used to retrieve a specific New Relic component.
func (p *Plugins) GetComponent(componentID int) (*Component, error) {
response := componentResponse{}
url := fmt.Sprintf("/components/%d.json", componentID)
_, err := p.client.Get(url, nil, &response)
if err != nil {
return nil, err
}
return &response.Component, nil
}
// ListComponentMetricsParams represents a set of parameters to be
// used when querying New Relic component metrics.
type ListComponentMetricsParams struct {
// Name allows for filtering the returned list of metrics by name.
Name string `url:"name,omitempty"`
}
// ListComponentMetrics is used to retrieve the metrics for a specific New Relic component.
func (p *Plugins) ListComponentMetrics(componentID int, params *ListComponentMetricsParams) ([]*ComponentMetric, error) {
m := []*ComponentMetric{}
response := componentMetricsResponse{}
nextURL := fmt.Sprintf("/components/%d/metrics.json", componentID)
for nextURL != "" {
resp, err := p.client.Get(nextURL, ¶ms, &response)
if err != nil {
return nil, err
}
m = append(m, response.Metrics...)
paging := p.pager.Parse(resp)
nextURL = paging.Next
}
return m, nil
}
// GetComponentMetricDataParams represents a set of parameters to be
// used when querying New Relic component metric data.
type GetComponentMetricDataParams struct {
// Names allows retrieval of specific metrics by name.
// At least one metric name is required.
Names []string `url:"names[],omitempty"`
// Values allows retrieval of specific metric values.
Values []string `url:"values[],omitempty"`
// From specifies a begin time for the query.
From *time.Time `url:"from,omitempty"`
// To specifies an end time for the query.
To *time.Time `url:"to,omitempty"`
// Period represents the period of timeslices in seconds.
Period int `url:"period,omitempty"`
// Summarize will summarize the data when set to true.
Summarize bool `url:"summarize,omitempty"`
// Raw will return unformatted raw values when set to true.
Raw bool `url:"raw,omitempty"`
}
// GetComponentMetricData is used to retrieve the metric timeslice data for a specific component metric.
func (p *Plugins) GetComponentMetricData(componentID int, params *GetComponentMetricDataParams) ([]*Metric, error) {
m := []*Metric{}
response := componentMetricDataResponse{}
nextURL := fmt.Sprintf("/components/%d/metrics/data.json", componentID)
for nextURL != "" {
resp, err := p.client.Get(nextURL, ¶ms, &response)
if err != nil {
return nil, err
}
m = append(m, response.MetricData.Metrics...)
paging := p.pager.Parse(resp)
nextURL = paging.Next
}
return m, nil
}
type componentsResponse struct {
Components []*Component `json:"components,omitempty"`
}
type componentResponse struct {
Component Component `json:"component,omitempty"`
}
type componentMetricsResponse struct {
Metrics []*ComponentMetric `json:"metrics,omitempty"`
}
type componentMetricDataResponse struct {
MetricData struct {
Metrics []*Metric `json:"metrics,omitempty"`
} `json:"metric_data,omitempty"`
}
|
LaughingBlue/openairinterface5g | cmake_targets/lte_build_oai/build/CMakeFiles/RRC_Rel14/LTE_SystemInformationBlockType1-NB-v1450.h | /*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "NBIOT-RRC-Definitions"
* found in "/home/labuser/Desktop/openairinterface5g_f1ap/openair2/RRC/LTE/MESSAGES/asn1c/ASN1_files/lte-rrc-14.7.0.asn1"
* `asn1c -pdu=all -fcompound-names -gen-PER -no-gen-OER -no-gen-example -D /home/labuser/Desktop/openairinterface5g_f1ap/cmake_targets/lte_build_oai/build/CMakeFiles/RRC_Rel14`
*/
#ifndef _LTE_SystemInformationBlockType1_NB_v1450_H_
#define _LTE_SystemInformationBlockType1_NB_v1450_H_
#include <asn_application.h>
/* Including external dependencies */
#include <NativeEnumerated.h>
#include <constr_SEQUENCE.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Dependencies */
typedef enum LTE_SystemInformationBlockType1_NB_v1450__nrs_CRS_PowerOffset_v1450 {
LTE_SystemInformationBlockType1_NB_v1450__nrs_CRS_PowerOffset_v1450_dB_6 = 0,
LTE_SystemInformationBlockType1_NB_v1450__nrs_CRS_PowerOffset_v1450_dB_4dot77 = 1,
LTE_SystemInformationBlockType1_NB_v1450__nrs_CRS_PowerOffset_v1450_dB_3 = 2,
LTE_SystemInformationBlockType1_NB_v1450__nrs_CRS_PowerOffset_v1450_dB_1dot77 = 3,
LTE_SystemInformationBlockType1_NB_v1450__nrs_CRS_PowerOffset_v1450_dB0 = 4,
LTE_SystemInformationBlockType1_NB_v1450__nrs_CRS_PowerOffset_v1450_dB1 = 5,
LTE_SystemInformationBlockType1_NB_v1450__nrs_CRS_PowerOffset_v1450_dB1dot23 = 6,
LTE_SystemInformationBlockType1_NB_v1450__nrs_CRS_PowerOffset_v1450_dB2 = 7,
LTE_SystemInformationBlockType1_NB_v1450__nrs_CRS_PowerOffset_v1450_dB3 = 8,
LTE_SystemInformationBlockType1_NB_v1450__nrs_CRS_PowerOffset_v1450_dB4 = 9,
LTE_SystemInformationBlockType1_NB_v1450__nrs_CRS_PowerOffset_v1450_dB4dot23 = 10,
LTE_SystemInformationBlockType1_NB_v1450__nrs_CRS_PowerOffset_v1450_dB5 = 11,
LTE_SystemInformationBlockType1_NB_v1450__nrs_CRS_PowerOffset_v1450_dB6 = 12,
LTE_SystemInformationBlockType1_NB_v1450__nrs_CRS_PowerOffset_v1450_dB7 = 13,
LTE_SystemInformationBlockType1_NB_v1450__nrs_CRS_PowerOffset_v1450_dB8 = 14,
LTE_SystemInformationBlockType1_NB_v1450__nrs_CRS_PowerOffset_v1450_dB9 = 15
} e_LTE_SystemInformationBlockType1_NB_v1450__nrs_CRS_PowerOffset_v1450;
/* LTE_SystemInformationBlockType1-NB-v1450 */
typedef struct LTE_SystemInformationBlockType1_NB_v1450 {
long *nrs_CRS_PowerOffset_v1450; /* OPTIONAL */
struct LTE_SystemInformationBlockType1_NB_v1450__nonCriticalExtension {
/* Context for parsing across buffer boundaries */
asn_struct_ctx_t _asn_ctx;
} *nonCriticalExtension;
/* Context for parsing across buffer boundaries */
asn_struct_ctx_t _asn_ctx;
} LTE_SystemInformationBlockType1_NB_v1450_t;
/* Implementation */
/* extern asn_TYPE_descriptor_t asn_DEF_LTE_nrs_CRS_PowerOffset_v1450_2; // (Use -fall-defs-global to expose) */
extern asn_TYPE_descriptor_t asn_DEF_LTE_SystemInformationBlockType1_NB_v1450;
extern asn_SEQUENCE_specifics_t asn_SPC_LTE_SystemInformationBlockType1_NB_v1450_specs_1;
extern asn_TYPE_member_t asn_MBR_LTE_SystemInformationBlockType1_NB_v1450_1[2];
#ifdef __cplusplus
}
#endif
#endif /* _LTE_SystemInformationBlockType1_NB_v1450_H_ */
#include <asn_internal.h>
|
laszlokorte/reform-java | reform-tools/src/main/java/reform/stage/tooling/modifiers/InvertedModifier.java | package reform.stage.tooling.modifiers;
public class InvertedModifier implements Modifier
{
private final Modifier _originalModifier;
public InvertedModifier(final Modifier originalModifier)
{
_originalModifier = originalModifier;
}
@Override
public void setState(final boolean newState)
{
_originalModifier.setState(!newState);
}
@Override
public boolean isActive()
{
return !_originalModifier.isActive();
}
}
|
navikt/pensjon-selvbetjening-jsf | src/main/java/no/nav/presentation/pensjon/pselv/skjema/SkjemaCommonConstants.java | package no.nav.presentation.pensjon.pselv.skjema;
public interface SkjemaCommonConstants {
String STEP_HOLDER = "stepHolder";
String OPEN_STEP_INDEX = "openStepIndex";
String PUS012_SKJEMAOVERSIKT_FLOW = "/skjema/skjemaoversikt.jsf";
}
|
Adore-Infotech/New-IOS2021 | Pods/OLMKit/src/pickle_encoding.c | <gh_stars>1-10
/* Copyright 2016 OpenMarket 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.
*/
#include "olm/pickle_encoding.h"
#include "olm/base64.h"
#include "olm/cipher.h"
#include "olm/olm.h"
static const struct _olm_cipher_aes_sha_256 PICKLE_CIPHER =
OLM_CIPHER_INIT_AES_SHA_256("Pickle");
size_t _olm_enc_output_length(
size_t raw_length
) {
const struct _olm_cipher *cipher = OLM_CIPHER_BASE(&PICKLE_CIPHER);
size_t length = cipher->ops->encrypt_ciphertext_length(cipher, raw_length);
length += cipher->ops->mac_length(cipher);
return _olm_encode_base64_length(length);
}
uint8_t * _olm_enc_output_pos(
uint8_t * output,
size_t raw_length
) {
const struct _olm_cipher *cipher = OLM_CIPHER_BASE(&PICKLE_CIPHER);
size_t length = cipher->ops->encrypt_ciphertext_length(cipher, raw_length);
length += cipher->ops->mac_length(cipher);
return output + _olm_encode_base64_length(length) - length;
}
size_t _olm_enc_output(
uint8_t const * key, size_t key_length,
uint8_t * output, size_t raw_length
) {
const struct _olm_cipher *cipher = OLM_CIPHER_BASE(&PICKLE_CIPHER);
size_t ciphertext_length = cipher->ops->encrypt_ciphertext_length(
cipher, raw_length
);
size_t length = ciphertext_length + cipher->ops->mac_length(cipher);
size_t base64_length = _olm_encode_base64_length(length);
uint8_t * raw_output = output + base64_length - length;
cipher->ops->encrypt(
cipher,
key, key_length,
raw_output, raw_length,
raw_output, ciphertext_length,
raw_output, length
);
_olm_encode_base64(raw_output, length, output);
return base64_length;
}
size_t _olm_enc_input(uint8_t const * key, size_t key_length,
uint8_t * input, size_t b64_length,
enum OlmErrorCode * last_error
) {
size_t enc_length = _olm_decode_base64_length(b64_length);
if (enc_length == (size_t)-1) {
if (last_error) {
*last_error = OLM_INVALID_BASE64;
}
return (size_t)-1;
}
_olm_decode_base64(input, b64_length, input);
const struct _olm_cipher *cipher = OLM_CIPHER_BASE(&PICKLE_CIPHER);
size_t raw_length = enc_length - cipher->ops->mac_length(cipher);
size_t result = cipher->ops->decrypt(
cipher,
key, key_length,
input, enc_length,
input, raw_length,
input, raw_length
);
if (result == (size_t)-1 && last_error) {
*last_error = OLM_BAD_ACCOUNT_KEY;
}
return result;
}
|
hofstadter-io/hof-starter-kit | dsl/type/default/partials/client/components/form-fields.js | <filename>dsl/type/default/partials/client/components/form-fields.js
{{#each TYPE.fields as |FIELD|}}
<Field
name="{{camel FIELD.name}}"
component={RenderField}
{{#if (eq FIELD.type "string")}}
type="text"
{{else if (eq FIELD.type "text")}}
type="textarea"
{{else if (eq FIELD.type "datetime")}}
type="datetime"
{{else if (eq FIELD.type "date")}}
type="date"
{{else if (eq FIELD.type "time")}}
type="time"
{{else if (eq FIELD.type "integer")}}
type="number"
{{else if (eq FIELD.type "decimal")}}
type="number"
{{else if (eq FIELD.type "boolean")}}
type="checkbox"
{{else}}
type="text"
{{/if}}
label={t('{{typeName}}.field.{{camel FIELD.name}}')}
value={ values.{{FIELD.name}} }
/>
{{/each}}
{{#if TYPE.visibility.enabled}}
{{#if TYPE.visibility.public}}
<Field
name="{{TYPE.visibility.public}}"
component={RenderCheckBox}
type="checkbox"
label={t('{{typeName}}.field.{{TYPE.visibility.public}}')}
checked={ values.{{TYPE.visibility.public}} }
/>
{{else}}
<Field
name="isPublic"
component={RenderCheckBox}
type="checkbox"
label={t('{{typeName}}.field.isPublic')}
checked={ values.isPublic }
/>
{{/if}}
{{/if}}
|
leginee/netbeans | cnd/cnd.makeproject.ui/src/org/netbeans/modules/cnd/makeproject/api/ui/wizard/IteratorExtension.java | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.modules.cnd.makeproject.api.ui.wizard;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import org.netbeans.api.project.Project;
import org.openide.WizardDescriptor;
import org.openide.filesystems.FileObject;
/**
*
*/
public interface IteratorExtension {
/**
* Method discover additional project artifacts by folder or binary file
*
* @param map input/output map
*/
void discoverArtifacts(Map<String,Object> map);
/**
* Method delegates a project creating to discovery.
* Instantiate make project in simple mode.
*
* @param wizard
* @return set of make projects
* @throws java.io.IOException
*/
Set<FileObject> createProject(WizardDescriptor wizard) throws IOException;
/**
* Method invoke discovery for created project.
*
* @param map input map
* @param project that will be configured or created
* @param projectKind fullness of configured project
*/
void discoverProject(Map<String,Object> map, Project project, ProjectKind projectKind);
/**
* Adds headers items in the project, changes exclude/include state of headers items
* according to code model. Returns immediately, listens until parse in done,
* tunes project on parse finish.
*
* @param project
*/
void discoverHeadersByModel(Project project);
/**
* Method disable code model for project
*
* @param project
*/
void disableModel(Project project);
public enum ProjectKind {
Minimal, // include in project com
IncludeDependencies,
CreateDependencies
}
}
|
HellicarAndLewis/Triptych | Test_Roxlu_Flock_Windows/src/application/BoidTypes.h | #ifndef ROXLU_BOID_TYPESH
#define ROXLU_BOID_TYPESH
#include <roxlu/math/Vec2.h>
#include <pbd/PBD.h>
#include <application/Settings.h>
#include <application/visuals/Trail.h>
/*
#include "PBD.h"
#include "Vec2.h"
#include <deque>
#include "Settings.h"
#include "Trail.h"
*/
template<class T>
struct BoidParticle : public Particle<T> {
BoidParticle(const T& pos, float m = 1.0);
void update(const float dt);
void removeTrail();
// std::deque<T> trail;
Trail2PC trail;
uint64_t grow_trail_end;
uint64_t glow_end;
};
template<class T>
BoidParticle<T>::BoidParticle(const T& pos, float m)
:Particle<T>(pos, m)
,grow_trail_end(0)
,glow_end(0)
{
}
template<class T>
void BoidParticle<T>::update(const float dt) {
}
template<class T>
inline void BoidParticle<T>::removeTrail() {
trail.clear();
}
typedef Particles<Vec2, BoidParticle<Vec2>, Spring<Vec2> > Boids2;
typedef BoidParticle<Vec2> Boid2;
typedef Flocking<Vec2, BoidParticle<Vec2> > BoidFlocking2;
#endif |
Jojo1542/DarkBot-reborn | core/src/main/java/org/darkstorm/minecraft/darkbot/wrapper/commands/FollowCommand.java | <reponame>Jojo1542/DarkBot-reborn
package org.darkstorm.minecraft.darkbot.wrapper.commands;
import org.darkstorm.minecraft.darkbot.ai.FollowTask;
import org.darkstorm.minecraft.darkbot.util.ChatColor;
import org.darkstorm.minecraft.darkbot.world.entity.*;
import org.darkstorm.minecraft.darkbot.wrapper.MinecraftBotWrapper;
public class FollowCommand extends AbstractCommand {
public FollowCommand(MinecraftBotWrapper bot) {
super(bot, "follow", "Follow a player or yourself", "[player]", "([\\w]{1,16})?");
}
@Override
public void execute(String[] args) {
FollowTask followTask = bot.getTaskManager().getTaskFor(FollowTask.class);
if(followTask.isActive())
followTask.stop();
for(Entity entity : bot.getWorld().getEntities()) {
if(entity instanceof PlayerEntity && isFollowable(args, ((PlayerEntity) entity).getName())) {
followTask.follow(entity);
controller.say("Now following " + (args.length > 0 ? ChatColor.stripColor(((PlayerEntity) entity).getName()) : "you") + ".");
return;
}
}
if(args.length > 0)
controller.say("Player " + args[0] + " not found.");
else
controller.say("Owner not found.");
}
private boolean isFollowable(String[] args, String name) {
name = ChatColor.stripColor(name);
if(args.length > 0)
return args[0].equalsIgnoreCase(name);
for(String owner : controller.getOwners())
if(owner.equalsIgnoreCase(name))
return true;
return false;
}
}
|
Tobi2001/asr_ivt | IVT/src/VideoCapture/OpenCVCapture.cpp | <reponame>Tobi2001/asr_ivt<gh_stars>0
// ****************************************************************************
// This file is part of the Integrating Vision Toolkit (IVT).
//
// The IVT is maintained by the Karlsruhe Institute of Technology (KIT)
// (www.kit.edu) in cooperation with the company Keyetech (www.keyetech.de).
//
// Copyright (C) 2014 Karlsruhe Institute of Technology (KIT).
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the KIT nor the names of its contributors may be
// used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE KIT AND CONTRIBUTORS “AS IS” AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE KIT OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ****************************************************************************
// ****************************************************************************
// Includes
// ****************************************************************************
#include "OpenCVCapture.h"
#include "Image/ImageProcessor.h"
#include "Image/ByteImage.h"
// ****************************************************************************
// Constructor / Destructor
// ****************************************************************************
COpenCVCapture::COpenCVCapture(int nIndex, const char *pFilename) : m_nIndex(nIndex)
{
m_pCapture = 0;
m_pIplImage = 0;
m_sFilename = "";
if (pFilename)
m_sFilename += pFilename;
}
COpenCVCapture::~COpenCVCapture()
{
CloseCamera();
}
// ****************************************************************************
// Methods
// ****************************************************************************
bool COpenCVCapture::OpenCamera()
{
CloseCamera();
if (m_sFilename.length() > 0)
m_pCapture = cvCaptureFromFile(m_sFilename.c_str());
else
m_pCapture = cvCaptureFromCAM(m_nIndex);
if (!m_pCapture)
return false;
cvSetCaptureProperty(m_pCapture, CV_CAP_PROP_FPS, 30);
cvSetCaptureProperty(m_pCapture, CV_CAP_PROP_FRAME_WIDTH, 640);
cvSetCaptureProperty(m_pCapture, CV_CAP_PROP_FRAME_HEIGHT, 480);
m_pIplImage = cvQueryFrame(m_pCapture);
return true;
}
void COpenCVCapture::CloseCamera()
{
cvReleaseCapture(&m_pCapture);
m_pIplImage = 0;
}
bool COpenCVCapture::CaptureImage(CByteImage **ppImages)
{
m_pIplImage = cvQueryFrame(m_pCapture);
if (!m_pIplImage)
return false;
CByteImage *pImage = ppImages[0];
if (!pImage || pImage->width != m_pIplImage->width || pImage->height != m_pIplImage->height)
return false;
if (m_pIplImage->depth != IPL_DEPTH_8U)
return false;
else if (m_pIplImage->nChannels != 1 && m_pIplImage->nChannels != 3)
return false;
else if (m_pIplImage->nChannels == 1 && pImage->type != CByteImage::eGrayScale)
return false;
else if (m_pIplImage->nChannels == 3 && pImage->type != CByteImage::eRGB24)
return false;
const int nBytes = pImage->width * pImage->height * pImage->bytesPerPixel;
unsigned char *input = (unsigned char *) m_pIplImage->imageData;
unsigned char *output = pImage->pixels;
if (pImage->type == CByteImage::eGrayScale)
{
memcpy(output, input, nBytes);
}
else if (pImage->type == CByteImage::eRGB24)
{
for (int i = 0; i < nBytes; i += 3)
{
output[i] = input[i + 2];
output[i + 1] = input[i + 1];
output[i + 2] = input[i];
}
}
#ifdef WIN32
ImageProcessor::FlipY(pImage, pImage);
#endif
return true;
}
int COpenCVCapture::GetWidth()
{
return m_pIplImage ? m_pIplImage->width : -1;
}
int COpenCVCapture::GetHeight()
{
return m_pIplImage ? m_pIplImage->height : -1;
}
CByteImage::ImageType COpenCVCapture::GetType()
{
return m_pIplImage ? (m_pIplImage->nChannels == 3 ? CByteImage::eRGB24 : CByteImage::eGrayScale) : (CByteImage::ImageType) -1;
}
|
zhijunzhou/letterpad | admin/components/select/index.js | <gh_stars>1-10
import React, { Component } from "react";
import PropTypes from "prop-types";
import StyledSelect from "./Select.css";
class Select extends Component {
static propTypes = {
options: PropTypes.array,
selected: PropTypes.string,
onChange: PropTypes.func,
bold: PropTypes.any,
label: PropTypes.any,
};
state = {
open: false,
options: this.props.options,
selected: "",
};
componentDidMount() {
const { options, selected } = this.props;
const option = options.filter(option => option.value == selected);
if (option.length > 0) {
this.setState({ selected: option[0].name });
}
}
toggleSelect = () => {
this.setState({ open: !this.state.open });
};
onChange = (e, newOption) => {
e.preventDefault();
this.props.onChange(newOption.value);
this.setState({ open: false, selected: newOption.name });
};
render() {
/* eslint-disable no-unused-vars */
const { options, selected, onChange, label, ...props } = this.props;
return (
<StyledSelect {...props}>
{label && (
<label
className="custom-label"
dangerouslySetInnerHTML={{ __html: label }}
/>
)}
<div className="select-name" onClick={this.toggleSelect}>
{this.state.selected}
<i className="material-icons">arrow_drop_down</i>
</div>
{this.state.open && (
<ul isOpen={this.state.open} className="options">
{options.map(option => {
let className =
option.name === this.state.selected ? " selected" : "";
return (
<li
onClick={e => this.onChange(e, option)}
key={option.name}
className={className}
value={option.value}
>
{option.name}
</li>
);
})}
</ul>
)}
</StyledSelect>
);
}
}
export default Select;
|
jesushilarioh/C-Plus-Plus | Snippits/compareTwoArrays.cpp | //*******************************************************************
// The following function accepts two int arrays. The arrays are *
// compared. If they contain the same values, true is returned. *
// If they contain different values, false is returned. *
//*******************************************************************
bool testPIN(const int customerPIN[], const int databasePIN[], int size)
{
for(int index = 0; index < size; index++)
{
if (customerPIN[index] != databasePIN[index])
return false;
}
return true;
} |
LishenZz/my_project | venv/Lib/site-packages/rest_framework_extras/tests/test_users.py | import unittest
import json
from django.contrib.auth import get_user_model
from django.test.client import Client, RequestFactory
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
from rest_framework.test import APIRequestFactory, APIClient
from rest_framework_extras.tests import models
class UsersTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.factory = APIRequestFactory()
cls.client = APIClient()
cls.user_model = get_user_model()
# Superuser
cls.superuser = cls.user_model.objects.create(
username="superuser",
email="<EMAIL>",
is_superuser=True,
is_staff=True
)
cls.superuser.set_password("password")
cls.superuser.save()
# Staff
cls.staff = cls.user_model.objects.create(
username="staff",
email="<EMAIL>",
is_staff=True
)
cls.staff.set_password("password")
cls.staff.save()
# Plain user
cls.user = cls.user_model.objects.create(
username="user",
email="<EMAIL>"
)
cls.user.set_password("password")
cls.user.save()
def setUp(self):
self.client.logout()
super(UsersTestCase, self).setUp()
def test_anonymous_create_user(self):
data = {
"username": "tacu",
"password": "password"
}
response = self.client.post("/auth-user/")
self.assertEqual(response.status_code, 403)
def test_anonymous_get_user(self):
response = self.client.get("/auth-user/")
self.assertEqual(response.status_code, 403)
response = self.client.get("/auth-user/1/")
self.assertEqual(response.status_code, 403)
def test_superuser_create_user(self):
self.client.login(username="superuser", password="password")
new_pk = self.user_model.objects.all().last().id + 1
data = {
"username": "tsucu",
"password": "password"
}
response = self.client.post("/auth-user/", data)
as_json = response.json()
self.assertEqual(as_json["username"], "tsucu")
self.failIf("password" in as_json)
query = self.user_model.objects.filter(pk=new_pk)
self.assertTrue(query.exists())
# Password must exist and be hashed
obj = query[0]
self.assertNotEqual(obj.password, None)
self.assertNotEqual(obj.password, "password")
def test_superuser_get_user(self):
self.client.login(username="superuser", password="password")
response = self.client.get("/auth-user/")
as_json = response.json()
self.failIf("password" in as_json[0])
response = self.client.get("/auth-user/1/")
as_json = response.json()
self.failIf("password" in as_json)
def test_staff_create_user(self):
self.client.login(username="staff", password="password")
new_pk = self.user_model.objects.all().last().id + 1
data = {
"username": "tscu",
"password": "password"
}
response = self.client.post("/auth-user/", data)
as_json = response.json()
self.assertEqual(as_json["username"], "tscu")
self.failIf("password" in as_json)
query = self.user_model.objects.filter(pk=new_pk)
self.assertTrue(query.exists())
# Password must exist and be hashed
obj = query[0]
self.assertNotEqual(obj.password, None)
self.assertNotEqual(obj.password, "password")
# Staff can't create superusers. That field is discarded.
new_pk = self.user_model.objects.all().last().id + 1
data = {
"username": "tscu1",
"password": "password",
"is_superuser": True
}
response = self.client.post("/auth-user/", data)
as_json = response.json()
self.failIf("is_superuser" in as_json)
query = self.user_model.objects.filter(pk=new_pk)
self.assertTrue(query.exists())
obj = query[0]
self.failIf(obj.is_superuser)
def test_staff_update_user(self):
# Staff can't bump users to superuser
self.client.login(username="staff", password="password")
data = {
"is_superuser": True
}
response = self.client.patch("/auth-user/%s/" % self.staff.pk, data)
as_json = response.json()
self.failIf("is_superuser" in as_json)
self.failIf(self.user_model.objects.get(pk=self.staff.pk).is_superuser)
def test_staff_update_superuser(self):
# Staff can't edit superusers
self.client.login(username="staff", password="password")
data = {
"email": "<EMAIL>"
}
response = self.client.patch("/auth-user/%s/" % self.superuser.pk, data)
self.assertEqual(response.status_code, 403)
self.assertNotEqual(
self.user_model.objects.get(pk=self.superuser.pk).email,
"<EMAIL>"
)
def test_staff_get_user(self):
self.client.login(username="staff", password="password")
response = self.client.get("/auth-user/")
as_json = response.json()
self.failIf("password" in as_json[0])
response = self.client.get("/auth-user/1/")
as_json = response.json()
self.failIf("password" in as_json)
def test_user_create_user(self):
self.client.login(username="user", password="password")
data = {
"username": "tucu",
"password": "password"
}
response = self.client.post("/auth-user/", data)
self.assertEqual(response.status_code, 403)
def test_user_get_user(self):
# User may only get himself
self.client.login(username="user", password="password")
response = self.client.get("/auth-user/")
self.assertEqual(response.status_code, 403)
response = self.client.get("/auth-user/%s/" % self.staff.pk)
self.assertEqual(response.status_code, 403)
response = self.client.get("/auth-user/%s/" % self.user.pk)
as_json = response.json()
self.assertEqual(as_json["username"], self.user.username)
self.failIf("password" in as_json)
def test_user_update_user(self):
# User may only update himself
self.client.login(username="user", password="password")
data = {
"email": "<EMAIL>"
}
response = self.client.patch("/auth-user/%s/" % self.staff.pk, data)
self.assertEqual(response.status_code, 403)
response = self.client.patch("/auth-user/%s/" % self.user.pk, data)
as_json = response.json()
self.assertEqual(as_json["email"], "<EMAIL>")
self.assertEqual(
self.user_model.objects.get(pk=self.user.pk).email, "<EMAIL>"
)
# User may not bump himself to superuser or staff
data = {
"is_superuser": True
}
response = self.client.patch("/auth-user/%s/" % self.user.pk, data)
as_json = response.json()
self.failIf("is_superuser" in as_json)
self.failIf(self.user_model.objects.get(pk=self.user.pk).is_superuser)
data = {
"is_staff": True
}
response = self.client.patch("/auth-user/%s/" % self.user.pk, data)
self.failIf("is_staff" in as_json)
self.failIf(self.user_model.objects.get(pk=self.user.pk).is_staff)
|
PreciousNiphemi/Belves-1 | src/database/repositories/token.repo.js | const BaseRepository = require('../repository');
const Token = require('../models/token.model');
class TokenRepository extends BaseRepository {
constructor() {
super(Token);
}
}
module.exports = new TokenRepository();
|
ardaasln/pmd | pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/properties/TypeProperty.java | <filename>pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/properties/TypeProperty.java
/**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.properties;
import java.util.Map;
import net.sourceforge.pmd.PropertyDescriptorFactory;
import net.sourceforge.pmd.lang.rule.properties.factories.BasicPropertyDescriptorFactory;
import net.sourceforge.pmd.util.ClassUtil;
import net.sourceforge.pmd.util.StringUtil;
/**
* Defines a property that supports single class types, even for primitive
* values!
*
* TODO - untested for array types
*
* @author <NAME>
*/
public class TypeProperty extends AbstractPackagedProperty<Class> {
public static final PropertyDescriptorFactory FACTORY = new BasicPropertyDescriptorFactory<TypeProperty>(
Class.class, PACKAGED_FIELD_TYPES_BY_KEY) {
public TypeProperty createWith(Map<String, String> valuesById) {
char delimiter = delimiterIn(valuesById);
return new TypeProperty(nameIn(valuesById), descriptionIn(valuesById), defaultValueIn(valuesById),
legalPackageNamesIn(valuesById, delimiter), 0f);
}
};
/**
* Constructor for TypeProperty.
*
* @param theName String
* @param theDescription String
* @param theDefault Class
* @param legalPackageNames String[]
* @param theUIOrder float
* @throws IllegalArgumentException
*/
public TypeProperty(String theName, String theDescription, Class<?> theDefault, String[] legalPackageNames,
float theUIOrder) {
super(theName, theDescription, theDefault, legalPackageNames, theUIOrder);
}
/**
*
* @param theName String
* @param theDescription String
* @param defaultTypeStr String
* @param legalPackageNames String[]
* @param theUIOrder float
* @throws IllegalArgumentException
*/
public TypeProperty(String theName, String theDescription, String defaultTypeStr, String[] legalPackageNames,
float theUIOrder) {
this(theName, theDescription, classFrom(defaultTypeStr), legalPackageNames, theUIOrder);
}
/**
*
* @param theName String
* @param theDescription String
* @param defaultTypeStr String
* @param otherParams Map<String, String>
* @param theUIOrder float
* @throws IllegalArgumentException
*/
public TypeProperty(String theName, String theDescription, String defaultTypeStr, Map<String, String> otherParams,
float theUIOrder) {
this(theName, theDescription, classFrom(defaultTypeStr), packageNamesIn(otherParams), theUIOrder);
}
/**
* @return String
*/
protected String defaultAsString() {
return asString(defaultValue());
}
/**
* Method packageNameOf.
*
* @param item Object
* @return String
*/
@Override
protected String packageNameOf(Object item) {
return ((Class<?>) item).getName();
}
/**
* @return Class
* @see net.sourceforge.pmd.PropertyDescriptor#type()
*/
public Class<Class> type() {
return Class.class;
}
/**
* @return String
*/
@Override
protected String itemTypeName() {
return "type";
}
/**
* @param value Object
* @return String
*/
@Override
protected String asString(Object value) {
return value == null ? "" : ((Class<?>) value).getName();
}
/**
* @param className String
* @return Class
* @throws IllegalArgumentException
*/
static Class<?> classFrom(String className) {
if (StringUtil.isEmpty(className)) {
return null;
}
Class<?> cls = ClassUtil.getTypeFor(className);
if (cls != null) {
return cls;
}
try {
return Class.forName(className);
} catch (Exception ex) {
throw new IllegalArgumentException(className);
}
}
/**
* @param valueString String
* @return Object
* @see net.sourceforge.pmd.PropertyDescriptor#valueFrom(String)
*/
public Class<?> valueFrom(String valueString) {
return classFrom(valueString);
}
}
|
dahankzter/manticore | arch/aarch64/setup.c | #include <arch/setup.h>
void arch_early_setup(void)
{
init_memory_map();
}
void arch_late_setup(void)
{
}
|
Pattamite/Course-FullStackOpen | part6/project/unisafe/src/CounterReducer.js | <filename>part6/project/unisafe/src/CounterReducer.js
const initialState = {
good: 0,
ok: 0,
bad: 0
}
const actionGood = 'GOOD';
const actionOk = 'OK';
const actionBad = 'BAD';
const actionZero = 'ZERO';
function reducer(state = initialState, action) {
console.log(action);
switch (action.type) {
case actionGood:
return {
...state,
good: state.good + 1,
};
case actionOk:
return {
...state,
ok: state.ok + 1,
};
case actionBad:
return {
...state,
bad: state.bad + 1,
};
case actionZero:
return {
...state,
good: 0,
ok: 0,
bad: 0,
};
default:
return state;
}
}
const counterReducer = {
reducer,
actionGood,
actionOk,
actionBad,
actionZero
};
export default counterReducer; |
opatrascoiu/jdmn | dmn-core/src/main/java/com/gs/dmn/feel/analysis/semantics/type/BuiltinOverloadedFunctionType.java | <filename>dmn-core/src/main/java/com/gs/dmn/feel/analysis/semantics/type/BuiltinOverloadedFunctionType.java
/*
* Copyright 2016 <NAME>.
*
* 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 com.gs.dmn.feel.analysis.semantics.type;
import com.gs.dmn.feel.analysis.semantics.SemanticError;
import com.gs.dmn.feel.analysis.semantics.environment.Declaration;
import com.gs.dmn.feel.analysis.syntax.ast.expression.function.FormalParameter;
import com.gs.dmn.feel.analysis.syntax.ast.expression.function.ParameterConversions;
import com.gs.dmn.feel.analysis.syntax.ast.expression.function.ParameterTypes;
import com.gs.dmn.runtime.Pair;
import java.util.List;
public class BuiltinOverloadedFunctionType extends FunctionType {
private final List<Declaration> declarations;
public BuiltinOverloadedFunctionType(List<Declaration> declarations) {
super(null, null);
this.declarations = declarations;
}
@Override
protected boolean equivalentTo(Type other) {
for (Declaration d: this.declarations) {
Type type = d.getType();
if (type.equivalentTo(other)) {
return true;
}
}
return false;
}
@Override
protected boolean conformsTo(Type other) {
for (Declaration d: this.declarations) {
Type type = d.getType();
if (type.conformsTo(other)) {
return true;
}
}
return false;
}
public List<FormalParameter> getParameters() {
throw new SemanticError("Not supported yet");
}
public List<Type> getParameterTypes() {
throw new SemanticError("Not supported yet");
}
public Type getReturnType() {
throw new SemanticError("Not supported yet");
}
public void setReturnType(Type returnType) {
throw new SemanticError("Not supported yet");
}
@Override
public boolean isFullySpecified() {
throw new SemanticError("Not supported yet");
}
@Override
public boolean match(ParameterTypes parameterTypes) {
throw new SemanticError("Not supported yet");
}
@Override
protected List<Pair<ParameterTypes, ParameterConversions>> matchCandidates(List<Type> argumentTypes) {
throw new SemanticError("Not supported yet");
}
}
|
poojavade/Genomics_Docker | Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/pybedtools-0.7.6-py2.7-linux-x86_64.egg/pybedtools/contrib/bigwig.py | <gh_stars>1-10
"""
Module to help create scaled bigWig files from BAM
"""
import pybedtools
import os
import subprocess
def mapped_read_count(bam, force=False):
"""
Scale is cached in a bam.scale file containing the number of mapped reads.
Use force=True to override caching.
"""
scale_fn = bam + '.scale'
if os.path.exists(scale_fn) and not force:
for line in open(scale_fn):
if line.startswith('#'):
continue
readcount = float(line.strip())
return readcount
cmds = ['samtools',
'view',
'-c',
'-F', '0x4',
bam]
p = subprocess.Popen(cmds, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if stderr:
raise ValueError('samtools says: %s' % stderr)
readcount = float(stdout)
# write to file so the next time you need the lib size you can access
# it quickly
if not os.path.exists(scale_fn):
fout = open(scale_fn, 'w')
fout.write(str(readcount) + '\n')
fout.close()
return readcount
def bedgraph_to_bigwig(bedgraph, genome, output):
genome_file = pybedtools.chromsizes_to_file(pybedtools.chromsizes(genome))
cmds = [
'bedGraphToBigWig',
bedgraph.fn,
genome_file,
output]
os.system(' '.join(cmds))
return output
def wig_to_bigwig(wig, genome, output):
genome_file = pybedtools.chromsizes_to_file(pybedtools.chromsizes(genome))
cmds = [
'wigToBigWig',
wig.fn,
genome_file,
output]
os.system(' '.join(cmds))
return output
def bam_to_bigwig(bam, genome, output, scale=False):
"""
Given a BAM file `bam` and assembly `genome`, create a bigWig file scaled
such that the values represent scaled reads -- that is, reads per million
mapped reads.
(Disable this scaling step with scale=False; in this case values will
indicate number of reads)
Assumes that `bedGraphToBigWig` from UCSC tools is installed; see
http://genome.ucsc.edu/goldenPath/help/bigWig.html for more details on the
format.
"""
genome_file = pybedtools.chromsizes_to_file(pybedtools.chromsizes(genome))
kwargs = dict(bg=True, split=True, g=genome_file)
if scale:
readcount = mapped_read_count(bam)
_scale = 1 / (readcount / 1e6)
kwargs['scale'] = _scale
x = pybedtools.BedTool(bam).genome_coverage(**kwargs)
cmds = [
'bedGraphToBigWig',
x.fn,
genome_file,
output]
os.system(' '.join(cmds))
|
risavkarna/spring-boot-multi-package-demo | control-core/src/main/java/co/sys/concept/patterns/things/adt/entities/env/contexts/ContextSequence.java | package co.sys.concept.patterns.things.adt.entities.env.contexts;
import co.sys.concept.patterns.things.adt.entities.env.space.Sequence;
import java.util.LinkedHashMap;
public abstract class ContextSequence<Context, ContextCompound> implements Sequence<Context, ContextCompound> {
private LinkedHashMap<Context, ContextCompound> contexts;
public ContextSequence(LinkedHashMap<Context, ContextCompound> contexts) {
this.contexts = contexts;
}
public ContextSequence() {
this.contexts = new LinkedHashMap<>();
}
public ContextSequence(Context context) {
set(context);
}
@Override
public LinkedHashMap<Context, ContextCompound> get() {
return contexts;
}
@Override
public ContextSequence<Context, ContextCompound> set(LinkedHashMap<Context, ContextCompound> contexts) {
this.contexts = contexts;
return this;
}
@Override
public ContextSequence<Context, ContextCompound> set(Context context) {
this.contexts = new LinkedHashMap<>();
this.contexts.put(context, null);
return this;
}
@Override
public ContextCompound get(Context context){
return contexts.get(context);
}
}
|
duc110789/vnpay | src/components/FeeTableDetail/index.js | import React, { useState } from 'react';
import { Collapse, CardBody, Card } from 'reactstrap';
import './index.scss';
const FeeTableDetail = (props) => {
const [isOpen, setIsOpen] = useState(true);
const toggle = () => setIsOpen(!isOpen);
return (
<div className="page-content">
<div className="page-content-area">
<form className="form-horizontal" role="form" action="#">
<div className="row">
<div className="col-md-12">
<div className="widget-box transparent">
<div className="widget-header widget-header-flat" onClick={toggle}>
<h4 className="widget-title lighter">LÝ DO TỪ CHỐI</h4>
<div className="widget-toolbar">
<span data-action="collapse"> <i className="ace-icon fa fa-chevron-up" /> </span>
</div>
</div>
<Collapse isOpen={isOpen} className="show-information">
<Card>
<CardBody>
<div className="widget-body">
<div className="widget-main">
<div className="box row">
<div className="col-md-6">
<div className="form-group">
<label className="col-sm-4 control-label p_top">Người từ chối</label>
<div className="col-sm-8">
<label><b>Kế toán</b></label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Nội dung</label>
<div className="col-sm-8">
<label className="clred"><b>Thông tin chung không đúng</b></label>
</div>
</div>
</div>
<div className="col-md-6">
<div className="form-group">
<label className="col-sm-4 control-label p_top">Thời gian</label>
<div className="col-sm-8">
<label><b>01/01/2016 00:00:00</b></label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Chi tiết</label>
<div className="col-sm-8">
<label><b>Nhầm LHDN</b></label>
</div>
</div>
</div>
</div>
{/* /.col */}
</div>
{/* /.widget-main */}
</div>
{/* /.widget-body */}
</CardBody>
</Card>
</Collapse>
</div>
</div>
<div className="col-md-12">
<div className="widget-box transparent">
<div className="widget-header widget-header-flat">
<h4 className="widget-title lighter">Thông tin chung</h4>
<div className="widget-toolbar">
<a href="#" data-action="collapse">
<i className="ace-icon fa fa-chevron-up" />
</a>
</div>
</div>
<Collapse isOpen={true} className="show-information">
<Card>
<CardBody>
<div className="widget-body">
<div className="widget-main">
<div className="box row">
<div className="col-md-6">
<div className="form-group">
<label className="col-sm-4 control-label p_top">Loại phí</label>
<div className="col-sm-8">
<label>
<b>Phí thu merchant</b>
</label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Phân loại ký kết</label>
<div className="col-sm-8">
<label>
<b>Hợp đồng</b>
</label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Số lượng mức phí</label>
<div className="col-sm-8">
<label>
<b>3</b>
</label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Trạng thái</label>
<div className="col-sm-8">
<label className="label label-sm label-success">
<b>Hoạt động</b>
</label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Người tạo</label>
<div className="col-sm-8">
<label>
<b>Lapnv</b>
</label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Người chỉnh sửa</label>
<div className="col-sm-8">
<label>
<b>Lapnv</b>
</label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Thời gian tạo</label>
<div className="col-sm-8">
<label>
<b>20/09/2018 09:00:00</b>
</label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Thời gian chỉnh sửa</label>
<div className="col-sm-8">
<label>
<b>20/09/2018 09:00:00</b>
</label>
</div>
</div>
</div>
<div className="col-md-6">
<div className="row">
<div className="col-md-5">
<div className="form-group">
<label className="col-sm-5 control-label p_top">Người duyệt</label>
<div className="col-sm-7">
<label>
<b>admin</b>
</label>
</div>
</div>
</div>
<div className="col-md-7">
<div className="form-group">
<label className="col-sm-5 control-label p_top">Thời gian duyệt</label>
<div className="col-sm-7">
<label>
<b>20/09/2018 09:00:00</b>
</label>
</div>
</div>
</div>
</div>
<div className="row">
<div className="col-md-5">
<div className="form-group">
<label className="col-sm-5 control-label p_top">Người khóa</label>
<div className="col-sm-7">
<label>
<b>admin</b>
</label>
</div>
</div>
</div>
<div className="col-md-7">
<div className="form-group">
<label className="col-sm-5 control-label p_top">Thời gian khóa</label>
<div className="col-sm-7">
<label>
<b>20/09/2018 09:00:00</b>
</label>
</div>
</div>
</div>
</div>
<div className="row">
<div className="col-md-5">
<div className="form-group">
<label className="col-sm-5 control-label p_top">Người mở khóa</label>
<div className="col-sm-7">
<label>
<b>admin</b>
</label>
</div>
</div>
</div>
<div className="col-md-7">
<div className="form-group">
<label className="col-sm-5 control-label p_top">Thời gian mở khóa</label>
<div className="col-sm-7">
<label>
<b>20/09/2018 09:00:00</b>
</label>
</div>
</div>
</div>
</div>
<div className="row">
<div className="col-md-5">
<div className="form-group">
<label className="col-sm-5 control-label p_top">Người chỉnh sửa</label>
<div className="col-sm-7">
<label>
<b>admin</b>
</label>
</div>
</div>
</div>
<div className="col-md-7">
<div className="form-group">
<label className="col-sm-5 control-label p_top">Thời gian chỉnh sửa</label>
<div className="col-sm-7">
<label>
<b>20/09/2018 09:00:00</b>
</label>
</div>
</div>
</div>
</div>
</div>
</div>
{/* /.col */}
</div>
{/* /.widget-main */}
</div>
</CardBody>
</Card>
</Collapse>
{/* /.widget-body */}
</div>
<div className="clearfix">
</div>
</div>
<div className="col-md-12">
<div className="widget-box transparent">
<div className="widget-header widget-header-flat">
<h4 className="widget-title lighter">Công thức phí</h4>
<div className="widget-toolbar">
<a href="#" data-action="collapse">
<i className="ace-icon fa fa-chevron-up" />
</a>
</div>
</div>
<div className="widget-body">
<div className="widget-main">
<div className="box">
<div className="box-seperate">
<div className="row">
<div className="col-md-6">
<div className="form-group">
<label className="col-sm-4 control-label p_top">Mã phí</label>
<div className="col-sm-8">
<label><b>01</b></label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Tên mức phí</label>
<div className="col-sm-8">
<label><b>Mức 1</b></label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Thuế GTGT</label>
<div className="col-sm-8">
<label><b>10%</b></label>
</div>
</div>
</div>
<div className="col-md-6">
<div className="form-group">
<label className="col-sm-12 control-label p_top"><b>Thông tin công thức phí</b></label>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">HÌnh thức tính</label>
<div className="col-sm-8">
<label><b>Theo công thức</b></label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Quy luật tính</label>
<div className="col-sm-8">
<label><b /></label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Tính theo</label>
<div className="col-sm-8">
<label><b /></label>
</div>
</div>
</div>
</div>
<table className="table table-bordered">
<thead>
<tr>
<th colSpan={2} className="text-center" bgcolor="#ececec">Phí cố định</th>
<th colSpan={4} className="text-center" bgcolor="#ececec">Phí xử lý thanh toán</th>
<th colSpan={2} className="text-center" bgcolor="#ececec">Giá trị giao dịch</th>
<th colSpan={2} className="text-center" bgcolor="#ececec">Số lượng giao dịch</th>
</tr>
<tr>
<th rowSpan={2} className="text-center">Theo số tiền</th>
<th rowSpan={2} className="text-center">Theo phần trăm</th>
<th rowSpan={2} className="text-center">Theo số tiền</th>
<th rowSpan={2} className="text-center">Theo phần trăm</th>
<th colSpan={2} className="text-center">Giới hạn phí thanh toán</th>
<th rowSpan={2} className="text-center">Từ</th>
<th rowSpan={2} className="text-center">Đến</th>
<th rowSpan={2} className="text-center">Từ</th>
<th rowSpan={2} className="text-center">Đến</th>
</tr>
<tr>
<th className="text-center">Tối thiểu</th>
<th className="text-center">Tối đa</th>
</tr>
</thead>
<tbody>
<tr className="text-center">
<td>3.300</td>
<td> </td>
<td> </td>
<td>0.30</td>
<td>3.300</td>
<td>1.000.000</td>
<td />
<td />
<td />
<td />
</tr>
</tbody>
</table>
</div>
<div className="box-seperate">
<div className="row">
<div className="col-md-6">
<div className="form-group">
<label className="col-sm-4 control-label p_top">Mã phí</label>
<div className="col-sm-8">
<label><b>02</b></label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Tên mức phí</label>
<div className="col-sm-8">
<label><b>Mức 2</b></label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Thuế GTGT</label>
<div className="col-sm-8">
<label><b>10%</b></label>
</div>
</div>
</div>
<div className="col-md-6">
<div className="form-group">
<label className="col-sm-12 control-label p_top"><b>Thông tin công thức phí</b></label>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">HÌnh thức tính</label>
<div className="col-sm-8">
<label><b>Theo bậc thang</b></label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Quy luật tính</label>
<div className="col-sm-8">
<label><b /></label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Tính theo</label>
<div className="col-sm-8">
<label><b>Tháng</b></label>
</div>
</div>
</div>
</div>
<table className="table table-bordered">
<thead>
<tr>
<th colSpan={2} className="text-center" bgcolor="#ececec">Phí cố định</th>
<th colSpan={4} className="text-center" bgcolor="#ececec">Phí xử lý thanh toán</th>
<th colSpan={2} className="text-center" bgcolor="#ececec">Giá trị giao dịch</th>
<th colSpan={2} className="text-center" bgcolor="#ececec">Số lượng giao dịch</th>
</tr>
<tr>
<th rowSpan={2} className="text-center">Theo số tiền</th>
<th rowSpan={2} className="text-center">Theo phần trăm</th>
<th rowSpan={2} className="text-center">Theo số tiền</th>
<th rowSpan={2} className="text-center">Theo phần trăm</th>
<th colSpan={2} className="text-center">Giới hạn phí thanh toán</th>
<th rowSpan={2} className="text-center">Từ</th>
<th rowSpan={2} className="text-center">Đến</th>
<th rowSpan={2} className="text-center">Từ</th>
<th rowSpan={2} className="text-center">Đến</th>
</tr>
<tr>
<th className="text-center">Tối thiểu</th>
<th className="text-center">Tối đa</th>
</tr>
</thead>
<tbody>
<tr className="text-center">
<td>3.300</td>
<td> </td>
<td> </td>
<td>0.30</td>
<td>3.300</td>
<td>1.000.000</td>
<td />
<td />
<td />
<td />
</tr>
</tbody>
</table>
</div>
<div className="box-seperate">
<div className="row">
<div className="col-md-6">
<div className="form-group">
<label className="col-sm-4 control-label p_top">Mã phí</label>
<div className="col-sm-8">
<label><b>03</b></label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Tên mức phí</label>
<div className="col-sm-8">
<label><b>Mức 3</b></label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Thuế GTGT</label>
<div className="col-sm-8">
<label><b>10%</b></label>
</div>
</div>
</div>
<div className="col-md-6">
<div className="form-group">
<label className="col-sm-12 control-label p_top"><b>Thông tin công thức phí</b></label>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">HÌnh thức tính</label>
<div className="col-sm-8">
<label><b>Theo bậc thang</b></label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Quy luật tính</label>
<div className="col-sm-8">
<label><b>Giá trị giao dịch</b></label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Giá trị giao dịch</label>
<div className="col-sm-8">
<label><b /></label>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label p_top">Tính theo</label>
<div className="col-sm-8">
<label><b>Tháng</b></label>
</div>
</div>
</div>
</div>
<table className="table table-bordered">
<thead>
<tr>
<th colSpan={2} className="text-center" bgcolor="#ececec">Phí cố định</th>
<th colSpan={4} className="text-center" bgcolor="#ececec">Phí xử lý thanh toán</th>
<th colSpan={2} className="text-center" bgcolor="#ececec">Giá trị giao dịch</th>
<th colSpan={2} className="text-center" bgcolor="#ececec">Số lượng giao dịch</th>
</tr>
<tr>
<th rowSpan={2} className="text-center">Theo số tiền</th>
<th rowSpan={2} className="text-center">Theo phần trăm</th>
<th rowSpan={2} className="text-center">Theo số tiền</th>
<th rowSpan={2} className="text-center">Theo phần trăm</th>
<th colSpan={2} className="text-center">Giới hạn phí thanh toán</th>
<th rowSpan={2} className="text-center">Từ</th>
<th rowSpan={2} className="text-center">Đến</th>
<th rowSpan={2} className="text-center">Từ</th>
<th rowSpan={2} className="text-center">Đến</th>
</tr>
<tr>
<th className="text-center">Tối thiểu</th>
<th className="text-center">Tối đa</th>
</tr>
</thead>
<tbody>
<tr className="text-center">
<td>3.300</td>
<td> </td>
<td> </td>
<td>0.30</td>
<td>3.300</td>
<td>1.000.000</td>
<td />
<td />
<td />
<td />
</tr>
</tbody>
</table>
</div>
</div>
{/* /.col */}
</div>
{/* /.widget-main */}
</div>
{/* /.widget-body */}
</div>
</div>
</div>
<div className="clearfix bottom20" />
<div className="clearfix form-actions row">
<div className="col-md-12 text-center">
<a title="Về danh sách" className="btn bggrey bigger-150" href="13-1-1-qly-bang-phi.html">
<i className="fa fa-arrow-left" aria-hidden="true" /> Quay lại</a>
</div>
</div>
</form>
</div>
</div>
);
}
export default FeeTableDetail;
FeeTableDetail.propTypes = {
// changeFeeTable: PropTypes.func.isRequired,
}; |
pulumi/pulumi-aws-native | sdk/go/aws/ecs/getCapacityProvider.go | // Code generated by the Pulumi SDK Generator DO NOT EDIT.
// *** WARNING: Do not edit by hand unless you're certain you know what you are doing! ***
package ecs
import (
"context"
"reflect"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)
// Resource Type definition for AWS::ECS::CapacityProvider.
func LookupCapacityProvider(ctx *pulumi.Context, args *LookupCapacityProviderArgs, opts ...pulumi.InvokeOption) (*LookupCapacityProviderResult, error) {
var rv LookupCapacityProviderResult
err := ctx.Invoke("aws-native:ecs:getCapacityProvider", args, &rv, opts...)
if err != nil {
return nil, err
}
return &rv, nil
}
type LookupCapacityProviderArgs struct {
Name string `pulumi:"name"`
}
type LookupCapacityProviderResult struct {
AutoScalingGroupProvider *CapacityProviderAutoScalingGroupProvider `pulumi:"autoScalingGroupProvider"`
Tags []CapacityProviderTag `pulumi:"tags"`
}
func LookupCapacityProviderOutput(ctx *pulumi.Context, args LookupCapacityProviderOutputArgs, opts ...pulumi.InvokeOption) LookupCapacityProviderResultOutput {
return pulumi.ToOutputWithContext(context.Background(), args).
ApplyT(func(v interface{}) (LookupCapacityProviderResult, error) {
args := v.(LookupCapacityProviderArgs)
r, err := LookupCapacityProvider(ctx, &args, opts...)
var s LookupCapacityProviderResult
if r != nil {
s = *r
}
return s, err
}).(LookupCapacityProviderResultOutput)
}
type LookupCapacityProviderOutputArgs struct {
Name pulumi.StringInput `pulumi:"name"`
}
func (LookupCapacityProviderOutputArgs) ElementType() reflect.Type {
return reflect.TypeOf((*LookupCapacityProviderArgs)(nil)).Elem()
}
type LookupCapacityProviderResultOutput struct{ *pulumi.OutputState }
func (LookupCapacityProviderResultOutput) ElementType() reflect.Type {
return reflect.TypeOf((*LookupCapacityProviderResult)(nil)).Elem()
}
func (o LookupCapacityProviderResultOutput) ToLookupCapacityProviderResultOutput() LookupCapacityProviderResultOutput {
return o
}
func (o LookupCapacityProviderResultOutput) ToLookupCapacityProviderResultOutputWithContext(ctx context.Context) LookupCapacityProviderResultOutput {
return o
}
func (o LookupCapacityProviderResultOutput) AutoScalingGroupProvider() CapacityProviderAutoScalingGroupProviderPtrOutput {
return o.ApplyT(func(v LookupCapacityProviderResult) *CapacityProviderAutoScalingGroupProvider {
return v.AutoScalingGroupProvider
}).(CapacityProviderAutoScalingGroupProviderPtrOutput)
}
func (o LookupCapacityProviderResultOutput) Tags() CapacityProviderTagArrayOutput {
return o.ApplyT(func(v LookupCapacityProviderResult) []CapacityProviderTag { return v.Tags }).(CapacityProviderTagArrayOutput)
}
func init() {
pulumi.RegisterOutputType(LookupCapacityProviderResultOutput{})
}
|
vprusa/echoIrc | server/test/LoginUtil.scala | <reponame>vprusa/echoIrc
import org.specs2.execute.AsResult
import org.specs2.execute.Result
import play.api.test.{FakeRequest, RouteInvokers, WithApplication, Writeables}
import play.api.mvc.Cookie
import play.api.test.Helpers
import play.api.test.Helpers.cookies
import play.api.test.Helpers.defaultAwaitTimeout
import play.api.{Application, Logger}
import play.filters.csrf.CSRF.Token
import play.filters.csrf.{CSRFConfigProvider, CSRFFilter}
import play.api.Application
import play.api.test.FakeRequest
import play.filters.csrf.CSRF.Token
import play.filters.csrf.{CSRFConfigProvider, CSRFFilter}
import javax.inject.{Inject, Singleton}
import akka.actor.ActorSystem
import com.typesafe.config.ConfigFactory
import org.specs2.mutable.Specification
import org.specs2.mutable._
import play.api.test.WithApplication
import play.api.test._
import play.api.test.Helpers._
import play.api.mvc._
import securesocial.core._
import play.Play
import play.api.test.Helpers.defaultAwaitTimeout
import controllers.{RestController, WebJarAssets, routes}
import org.specs2.mock.Mockito
import play.api.Logger
import play.api.Application
import play.api.i18n.MessagesApi
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test.FakeRequest
import play.filters.csrf.CSRF.Token
import play.filters.csrf.{CSRFConfigProvider, CSRFFilter}
import play.api.mvc._
import play.api.test._
import service.MyEnvironment
import scala.concurrent.Future
import scala.language.postfixOps
trait CSRFTest {
def getTokenNameValue()(implicit app: Application): (String, String, String) = {
Logger.debug("CSRFTest.getTokenNameValue")
val csrfConfig = app.injector.instanceOf[CSRFConfigProvider].get
val csrfFilter = app.injector.instanceOf[CSRFFilter]
val token = csrfFilter.tokenProvider.generateToken
Logger.debug(csrfConfig.toString)
Logger.debug(csrfConfig.headerName.toString)
Logger.debug(csrfConfig.tokenName.toString)
Logger.debug(csrfConfig.cookieName.toString)
Logger.debug(csrfFilter.toString)
Logger.debug(csrfFilter.tokenProvider.toString)
(csrfConfig.headerName, csrfConfig.tokenName, token)
}
def addToken[T](fakeRequest: FakeRequest[T])(implicit app: Application) = {
Logger.debug("CSRFTest.addToken")
val tokenNameVal = getTokenNameValue()
val headerName = tokenNameVal._1
val tokenName = tokenNameVal._2
val tokenVal = tokenNameVal._3
Logger.debug("CSRFTest.addToken>token")
Logger.debug(tokenName)
fakeRequest.copyFakeRequest(tags = fakeRequest.tags ++ Map(
Token.NameRequestTag -> tokenName,
Token.RequestTag -> tokenVal
)).withHeaders((headerName, tokenVal))
}
}
object LoginUtil extends RouteInvokers with Writeables with CSRFTest {
val username = "owner"
val password = "password"
val loginRequest = FakeRequest(Helpers.POST, "/auth/authenticate/userpass")
.withFormUrlEncodedBody(("username", username), ("password", password))
var _cookie: Cookie = _
var _playSessionCookie: Cookie = _
def cookie = _cookie
def sessionCookie = _playSessionCookie
def login(implicit app: Application) {
Logger.debug(s"Login as user: ${username}")
val credentials = cookies(route(addToken(loginRequest)).get)
//val credentials = cookies(route(newLoginRequest).get)
Logger.debug("credentials")
Logger.debug(credentials.toString())
val playSessionCookie = credentials.get("PLAY_SESSION")
_playSessionCookie = playSessionCookie.get
val idCookie = credentials.get("id")
_cookie = idCookie.get
}
}
abstract class WithAppLogin extends WithApplication with Mockito {
override def around[T: AsResult](t: => T): Result = super.around {
LoginUtil.login
implicit val actorSystem = ActorSystem("testActorSystem", ConfigFactory.load())
//implicit val actorSystem = mock[ActorSystem]
implicit val env = mock[MyEnvironment]
implicit val webJarAssets = mock[WebJarAssets]
implicit val messagesApi = mock[MessagesApi]
t
}
}
abstract class ServerWithAppLogin extends WithServer(app = GuiceApplicationBuilder().configure("logger.application" -> "DEBUG").build(), port = 9000)
//with Mockito
// with org.specs2.matcher.ShouldThrownExpectations
//with org.specs2.matcher.MustThrownExpectations
{
override def around[T: AsResult](t: => T): Result = super.around {
LoginUtil.login
/* implicit val actorSystem = ActorSystem("testActorSystem", ConfigFactory.load())
//implicit val actorSystem = mock[ActorSystem]
implicit val env = mock[MyEnvironment]
implicit val webJarAssets = mock[WebJarAssets]
implicit val messagesApi = mock[MessagesApi]
*/
t
}
implicit val actorSystem = ActorSystem("testActorSystem", ConfigFactory.load())
//implicit val actorSystem = mock[ActorSystem]
implicit val env = app.injector.instanceOf[MyEnvironment]
implicit val webJarAssets = app.injector.instanceOf[WebJarAssets]
implicit val messagesApi = app.injector.instanceOf[MessagesApi]
/* override def around[T: AsResult](t: => T): Result = super.around {
LoginUtil.login
t
}*/
}
|
dddddai/karmada | pkg/util/rbac.go | <gh_stars>1-10
package util
import (
"context"
rbacv1 "k8s.io/api/rbac/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kubeclient "k8s.io/client-go/kubernetes"
)
// IsClusterRoleExist tells if specific ClusterRole already exists.
func IsClusterRoleExist(client kubeclient.Interface, name string) (bool, error) {
_, err := client.RbacV1().ClusterRoles().Get(context.TODO(), name, metav1.GetOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
return false, nil
}
return false, err
}
return true, nil
}
// CreateClusterRole just try to create the ClusterRole.
func CreateClusterRole(client kubeclient.Interface, clusterRoleObj *rbacv1.ClusterRole) (*rbacv1.ClusterRole, error) {
createdObj, err := client.RbacV1().ClusterRoles().Create(context.TODO(), clusterRoleObj, metav1.CreateOptions{})
if err != nil {
if apierrors.IsAlreadyExists(err) {
return clusterRoleObj, nil
}
return nil, err
}
return createdObj, nil
}
// DeleteClusterRole just try to delete the ClusterRole.
func DeleteClusterRole(client kubeclient.Interface, name string) error {
err := client.RbacV1().ClusterRoles().Delete(context.TODO(), name, metav1.DeleteOptions{})
if err != nil && !apierrors.IsNotFound(err) {
return err
}
return nil
}
// IsClusterRoleBindingExist tells if specific ClusterRole already exists.
func IsClusterRoleBindingExist(client kubeclient.Interface, name string) (bool, error) {
_, err := client.RbacV1().ClusterRoleBindings().Get(context.TODO(), name, metav1.GetOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
return false, nil
}
return false, err
}
return true, nil
}
// CreateClusterRoleBinding just try to create the ClusterRoleBinding.
func CreateClusterRoleBinding(client kubeclient.Interface, clusterRoleBindingObj *rbacv1.ClusterRoleBinding) (*rbacv1.ClusterRoleBinding, error) {
createdObj, err := client.RbacV1().ClusterRoleBindings().Create(context.TODO(), clusterRoleBindingObj, metav1.CreateOptions{})
if err != nil {
if apierrors.IsAlreadyExists(err) {
return clusterRoleBindingObj, nil
}
return nil, err
}
return createdObj, nil
}
// DeleteClusterRoleBinding just try to delete the ClusterRoleBinding.
func DeleteClusterRoleBinding(client kubeclient.Interface, name string) error {
err := client.RbacV1().ClusterRoleBindings().Delete(context.TODO(), name, metav1.DeleteOptions{})
if err != nil && !apierrors.IsNotFound(err) {
return err
}
return nil
}
// PolicyRuleAPIGroupMatches determines if the given policy rule is applied for requested group.
func PolicyRuleAPIGroupMatches(rules *rbacv1.PolicyRule, requestedGroup string) bool {
for _, ruleGroup := range rules.APIGroups {
if ruleGroup == rbacv1.APIGroupAll {
return true
}
if ruleGroup == requestedGroup {
return true
}
}
return false
}
// PolicyRuleResourceMatches determines if the given policy rule is applied for requested resource.
func PolicyRuleResourceMatches(rules *rbacv1.PolicyRule, requestedResource string) bool {
for _, ruleResource := range rules.Resources {
if ruleResource == rbacv1.ResourceAll {
return true
}
if ruleResource == requestedResource {
return true
}
}
return false
}
// PolicyRuleResourceNameMatches determines if the given policy rule is applied for named resource.
func PolicyRuleResourceNameMatches(rule *rbacv1.PolicyRule, requestedName string) bool {
if len(rule.ResourceNames) == 0 {
return true
}
for _, ruleName := range rule.ResourceNames {
if ruleName == requestedName {
return true
}
}
return false
}
// GenerateImpersonationRules generate PolicyRules from given subjects for impersonation.
func GenerateImpersonationRules(allSubjects []rbacv1.Subject) []rbacv1.PolicyRule {
if len(allSubjects) == 0 {
return nil
}
var users, serviceAccounts, groups []string
for _, subject := range allSubjects {
switch subject.Kind {
case rbacv1.UserKind:
users = append(users, subject.Name)
case rbacv1.ServiceAccountKind:
serviceAccounts = append(serviceAccounts, subject.Name)
case rbacv1.GroupKind:
groups = append(groups, subject.Name)
}
}
var rules []rbacv1.PolicyRule
if len(users) != 0 {
rules = append(rules, rbacv1.PolicyRule{Verbs: []string{"impersonate"}, Resources: []string{"users"}, APIGroups: []string{""}, ResourceNames: users})
}
if len(serviceAccounts) != 0 {
rules = append(rules, rbacv1.PolicyRule{Verbs: []string{"impersonate"}, Resources: []string{"serviceaccounts"}, APIGroups: []string{""}, ResourceNames: serviceAccounts})
}
if len(groups) != 0 {
rules = append(rules, rbacv1.PolicyRule{Verbs: []string{"impersonate"}, Resources: []string{"groups"}, APIGroups: []string{""}, ResourceNames: groups})
}
return rules
}
|
ShunqinChen/practice-spring | spring-boot-2.x/spring-data-mongodb/src/main/java/lol/kent/practice/spring/mongo/dao/PostRepository.java | <gh_stars>0
package lol.kent.practice.spring.mongo.dao;
import lol.kent.practice.spring.mongo.entity.Post;
import org.springframework.data.repository.CrudRepository;
/**
* <pre>
* 类描述:
* </pre>
* <p>
* Copyright: Copyright (c) 2020年08月25日 16:02
* <p>
* Company: AMPM Fit
* <p>
*
* @author Shunqin.Chen
* @version 1.0.0
*/
public interface PostRepository extends CrudRepository<Post, String> {
Post getPostById(String id);
}
|
lateefojulari/unify-framework | unify-core/src/test/java/com/tcdng/unify/core/database/BranchExt.java | /*
* Copyright 2018-2020 The Code Department.
*
* 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 com.tcdng.unify.core.database;
import com.tcdng.unify.core.annotation.Column;
import com.tcdng.unify.core.annotation.ForeignKey;
import com.tcdng.unify.core.annotation.ListOnly;
import com.tcdng.unify.core.annotation.TableExt;
import com.tcdng.unify.core.constant.BooleanType;
/**
* Test branch extension record.
*
* @author <NAME>
* @since 1.0
*/
@TableExt
public class BranchExt extends Branch {
@ForeignKey(type = Office.class)
private Long officeId;
@Column
private String state;
@Column
private String country;
@ForeignKey
private BooleanType closed;
@ListOnly(key = "officeId", property = "address")
private String officeAddress;
@ListOnly(key = "officeId", property = "telephone")
private String officeTelephone;
@ListOnly(key = "closed", property = "description")
private String closedDesc;
public BranchExt(String code, String description, String sortCode, Long officeId, String state, String country,
BooleanType closed) {
super(code, description, sortCode);
this.officeId = officeId;
this.state = state;
this.country = country;
this.closed = closed;
}
public BranchExt() {
}
public Long getOfficeId() {
return officeId;
}
public void setOfficeId(Long officeId) {
this.officeId = officeId;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public BooleanType getClosed() {
return closed;
}
public void setClosed(BooleanType closed) {
this.closed = closed;
}
public String getOfficeAddress() {
return officeAddress;
}
public void setOfficeAddress(String officeAddress) {
this.officeAddress = officeAddress;
}
public String getOfficeTelephone() {
return officeTelephone;
}
public void setOfficeTelephone(String officeTelephone) {
this.officeTelephone = officeTelephone;
}
public String getClosedDesc() {
return closedDesc;
}
public void setClosedDesc(String closedDesc) {
this.closedDesc = closedDesc;
}
}
|
AliciaHu/plumelog | plumelog-server/src/main/java/com/plumelog/server/monitor/DingTalkClient.java | <filename>plumelog-server/src/main/java/com/plumelog/server/monitor/DingTalkClient.java
package com.plumelog.server.monitor;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import org.slf4j.LoggerFactory;
public class DingTalkClient {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(DingTalkClient.class);
public static void sendToDingTalk(PlumeLogMonitorTextMessage plumeLogMonitorTextMessage, String URL) {
com.dingtalk.api.DingTalkClient client = new DefaultDingTalkClient(URL);
OapiRobotSendRequest request = new OapiRobotSendRequest();
request.setMsgtype("markdown");
OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
markdown.setTitle("报警通知");
markdown.setText(plumeLogMonitorTextMessage.getText());
request.setMarkdown(markdown);
OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
at.setAtMobiles(plumeLogMonitorTextMessage.getAtMobiles());
at.setIsAtAll(plumeLogMonitorTextMessage.isAtAll());
request.setAt(at);
OapiRobotSendResponse response = null;
try {
response = client.execute(request);
} catch (ApiException e) {
e.printStackTrace();
logger.error(response.getErrmsg());
}
}
}
|
Fappp/Gamejolt | src/app/components/shell/top-nav/top-nav-directive.js | angular.module( 'App.Shell' ).directive( 'gjShellTopNav', function( App, Shell )
{
return {
restrict: 'E',
templateUrl: '/app/components/shell/top-nav/top-nav.html',
scope: true,
link: function( scope )
{
scope.App = App;
scope.Shell = Shell;
scope.notificationsCount = 0;
scope.friendRequestCount = 0;
}
};
} );
|
pdepaepe/ovh-manager-cloud | client/app/kubernetes/kubernetes.service.js | <reponame>pdepaepe/ovh-manager-cloud
angular.module('managerApp').service('Kubernetes', class Kubernetes {
constructor(
$q, $translate,
OvhApiCloudProject, OvhApiCloudProjectFlavor, OvhApiCloudProjectInstance,
OvhApiKube, OvhApiCloudProjectQuota,
KUBERNETES,
) {
this.$q = $q;
this.$translate = $translate;
this.OvhApiCloudProject = OvhApiCloudProject;
this.OvhApiCloudProjectFlavor = OvhApiCloudProjectFlavor;
this.OvhApiCloudProjectInstance = OvhApiCloudProjectInstance;
this.OvhApiKube = OvhApiKube;
this.OvhApiCloudProjectQuota = OvhApiCloudProjectQuota;
this.KUBERNETES = KUBERNETES;
}
getKubernetesCluster(serviceName) {
return this.OvhApiKube.v6().get({ serviceName }).$promise;
}
getKubernetesServiceInfos(serviceName) {
return this.OvhApiKube.v6().getServiceInfos({ serviceName }).$promise;
}
getKubernetesConfig(serviceName) {
return this.OvhApiKube.v6().getKubeConfig({ serviceName }).$promise;
}
getAssociatedPublicCloudProjects(serviceName) {
return this.OvhApiKube.PublicCloud().Project().v6().query({ serviceName }).$promise;
}
getAssociatedInstance(projectId, instanceId) {
return this.OvhApiCloudProjectInstance
.v6()
.get({ serviceName: projectId, instanceId })
.$promise;
}
getProject(projectId) {
return this.OvhApiCloudProject.v6().get({ serviceName: projectId }).$promise;
}
getProjectQuota(serviceName) {
return this.OvhApiCloudProjectQuota
.v6()
.query({ serviceName })
.$promise;
}
getNodes(serviceName) {
return this.OvhApiKube.PublicCloud().Node().v6().query({ serviceName }).$promise;
}
addNode(serviceName, flavorName) {
return this.OvhApiKube.PublicCloud().Node().v6().save({ serviceName }, { flavorName }).$promise;
}
deleteNode(serviceName, nodeId) {
return this.OvhApiKube.PublicCloud().Node().v6().delete({ serviceName, nodeId }).$promise;
}
resetNodesCache() {
this.OvhApiKube.PublicCloud().Node().v6().resetCache();
this.OvhApiKube.PublicCloud().Node().v6().resetQueryCache();
}
getFlavors(serviceName) {
// Region is constant for now
return this.OvhApiCloudProjectFlavor
.v6()
.query({ serviceName, region: this.KUBERNETES.region })
.$promise;
}
getFlavorDetails(serviceName, flavorId) {
return this.OvhApiCloudProjectFlavor.get({ serviceName, flavorId }).$promise;
}
formatFlavor(flavor) {
return this.$translate.instant('kube_flavor', {
name: flavor.name.toUpperCase(),
cpuNumber: flavor.vcpus,
ramCapacity: flavor.ram / 1000,
diskCapacity: flavor.disk,
});
}
resetCluster(serviceName) {
return this.OvhApiKube.v6().reset({ serviceName }, {}).$promise;
}
resetClusterCache() {
this.OvhApiKube.v6().resetCache();
}
});
|
georghe-crihan/ext2fsx | src/e2fsprogs/e2fsck/util.c | /*
* util.c --- miscellaneous utilities
*
* Copyright (C) 1993, 1994, 1995, 1996, 1997 <NAME>.
*
* %Begin-Header%
* This file may be redistributed under the terms of the GNU Public
* License.
* %End-Header%
*/
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#ifdef HAVE_CONIO_H
#undef HAVE_TERMIOS_H
#include <conio.h>
#define read_a_char() getch()
#else
#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif
#include <stdio.h>
#endif
#ifdef HAVE_MALLOC_H
#include <malloc.h>
#endif
#include "e2fsck.h"
extern e2fsck_t e2fsck_global_ctx; /* Try your very best not to use this! */
#include <sys/time.h>
#include <sys/resource.h>
void fatal_error(e2fsck_t ctx, const char *msg)
{
if (msg)
fprintf (stderr, "e2fsck: %s\n", msg);
if (ctx->fs && ctx->fs->io) {
if (ctx->fs->io->magic == EXT2_ET_MAGIC_IO_CHANNEL)
io_channel_flush(ctx->fs->io);
else
fprintf(stderr, "e2fsck: io manager magic bad!\n");
}
ctx->flags |= E2F_FLAG_ABORT;
if (ctx->flags & E2F_FLAG_SETJMP_OK)
longjmp(ctx->abort_loc, 1);
exit(FSCK_ERROR);
}
void *e2fsck_allocate_memory(e2fsck_t ctx, unsigned int size,
const char *description)
{
void *ret;
char buf[256];
#ifdef DEBUG_ALLOCATE_MEMORY
printf("Allocating %d bytes for %s...\n", size, description);
#endif
ret = malloc(size);
if (!ret) {
sprintf(buf, "Can't allocate %s\n", description);
fatal_error(ctx, buf);
}
memset(ret, 0, size);
return ret;
}
char *string_copy(e2fsck_t ctx EXT2FS_ATTR((unused)),
const char *str, int len)
{
char *ret;
if (!str)
return NULL;
if (!len)
len = strlen(str);
ret = malloc(len+1);
if (ret) {
strncpy(ret, str, len);
ret[len] = 0;
}
return ret;
}
#ifndef HAVE_STRNLEN
/*
* Incredibly, libc5 doesn't appear to have strnlen. So we have to
* provide our own.
*/
int e2fsck_strnlen(const char * s, int count)
{
const char *cp = s;
while (count-- && *cp)
cp++;
return cp - s;
}
#endif
#ifndef HAVE_CONIO_H
static int read_a_char(void)
{
char c;
int r;
int fail = 0;
while(1) {
if (e2fsck_global_ctx &&
(e2fsck_global_ctx->flags & E2F_FLAG_CANCEL)) {
return 3;
}
r = read(0, &c, 1);
if (r == 1)
return c;
if (fail++ > 100)
break;
}
return EOF;
}
#endif
int ask_yn(const char * string, int def)
{
int c;
const char *defstr;
const char *short_yes = _("yY");
const char *short_no = _("nN");
#ifdef HAVE_TERMIOS_H
struct termios termios, tmp;
tcgetattr (0, &termios);
tmp = termios;
tmp.c_lflag &= ~(ICANON | ECHO);
tmp.c_cc[VMIN] = 1;
tmp.c_cc[VTIME] = 0;
tcsetattr (0, TCSANOW, &tmp);
#endif
if (def == 1)
defstr = _(_("<y>"));
else if (def == 0)
defstr = _(_("<n>"));
else
defstr = _(" (y/n)");
printf("%s%s? ", string, defstr);
while (1) {
fflush (stdout);
if ((c = read_a_char()) == EOF)
break;
if (c == 3) {
#ifdef HAVE_TERMIOS_H
tcsetattr (0, TCSANOW, &termios);
#endif
if (e2fsck_global_ctx &&
e2fsck_global_ctx->flags & E2F_FLAG_SETJMP_OK) {
puts("\n");
longjmp(e2fsck_global_ctx->abort_loc, 1);
}
puts(_("cancelled!\n"));
return 0;
}
if (strchr(short_yes, (char) c)) {
def = 1;
break;
}
else if (strchr(short_no, (char) c)) {
def = 0;
break;
}
else if ((c == ' ' || c == '\n') && (def != -1))
break;
}
if (def)
puts(_("yes\n"));
else
puts (_("no\n"));
#ifdef HAVE_TERMIOS_H
tcsetattr (0, TCSANOW, &termios);
#endif
return def;
}
int ask (e2fsck_t ctx, const char * string, int def)
{
if (ctx->options & E2F_OPT_NO) {
printf (_("%s? no\n\n"), string);
return 0;
}
if (ctx->options & E2F_OPT_YES) {
printf (_("%s? yes\n\n"), string);
return 1;
}
if (ctx->options & E2F_OPT_PREEN) {
printf ("%s? %s\n\n", string, def ? _("yes") : _("no"));
return def;
}
return ask_yn(string, def);
}
void e2fsck_read_bitmaps(e2fsck_t ctx)
{
ext2_filsys fs = ctx->fs;
errcode_t retval;
if (ctx->invalid_bitmaps) {
com_err(ctx->program_name, 0,
_("e2fsck_read_bitmaps: illegal bitmap block(s) for %s"),
ctx->device_name);
fatal_error(ctx, 0);
}
ehandler_operation(_("reading inode and block bitmaps"));
retval = ext2fs_read_bitmaps(fs);
ehandler_operation(0);
if (retval) {
com_err(ctx->program_name, retval,
_("while retrying to read bitmaps for %s"),
ctx->device_name);
fatal_error(ctx, 0);
}
}
void e2fsck_write_bitmaps(e2fsck_t ctx)
{
ext2_filsys fs = ctx->fs;
errcode_t retval;
if (ext2fs_test_bb_dirty(fs)) {
ehandler_operation(_("writing block bitmaps"));
retval = ext2fs_write_block_bitmap(fs);
ehandler_operation(0);
if (retval) {
com_err(ctx->program_name, retval,
_("while retrying to write block bitmaps for %s"),
ctx->device_name);
fatal_error(ctx, 0);
}
}
if (ext2fs_test_ib_dirty(fs)) {
ehandler_operation(_("writing inode bitmaps"));
retval = ext2fs_write_inode_bitmap(fs);
ehandler_operation(0);
if (retval) {
com_err(ctx->program_name, retval,
_("while retrying to write inode bitmaps for %s"),
ctx->device_name);
fatal_error(ctx, 0);
}
}
}
void preenhalt(e2fsck_t ctx)
{
ext2_filsys fs = ctx->fs;
if (!(ctx->options & E2F_OPT_PREEN))
return;
fprintf(stderr, _("\n\n%s: UNEXPECTED INCONSISTENCY; "
"RUN fsck MANUALLY.\n\t(i.e., without -a or -p options)\n"),
ctx->device_name);
if (fs != NULL) {
fs->super->s_state |= EXT2_ERROR_FS;
ext2fs_mark_super_dirty(fs);
ext2fs_close(fs);
}
exit(FSCK_UNCORRECTED);
}
#ifdef RESOURCE_TRACK
void init_resource_track(struct resource_track *track)
{
#ifdef HAVE_GETRUSAGE
struct rusage r;
#endif
track->brk_start = sbrk(0);
gettimeofday(&track->time_start, 0);
#ifdef HAVE_GETRUSAGE
#ifdef sun
memset(&r, 0, sizeof(struct rusage));
#endif
getrusage(RUSAGE_SELF, &r);
track->user_start = r.ru_utime;
track->system_start = r.ru_stime;
#else
track->user_start.tv_sec = track->user_start.tv_usec = 0;
track->system_start.tv_sec = track->system_start.tv_usec = 0;
#endif
}
#ifdef __GNUC__
#define _INLINE_ __inline__
#else
#define _INLINE_
#endif
static _INLINE_ float timeval_subtract(struct timeval *tv1,
struct timeval *tv2)
{
return ((tv1->tv_sec - tv2->tv_sec) +
((float) (tv1->tv_usec - tv2->tv_usec)) / 1000000);
}
void print_resource_track(const char *desc, struct resource_track *track)
{
#ifdef HAVE_GETRUSAGE
struct rusage r;
#endif
#ifdef HAVE_MALLINFO
struct mallinfo malloc_info;
#endif
struct timeval time_end;
gettimeofday(&time_end, 0);
if (desc)
printf("%s: ", desc);
#ifdef HAVE_MALLINFO
#define kbytes(x) (((x) + 1023) / 1024)
malloc_info = mallinfo();
printf(_("Memory used: %dk/%dk (%dk/%dk), "),
kbytes(malloc_info.arena), kbytes(malloc_info.hblkhd),
kbytes(malloc_info.uordblks), kbytes(malloc_info.fordblks));
#else
printf(_("Memory used: %d, "),
(int) (((char *) sbrk(0)) - ((char *) track->brk_start)));
#endif
#ifdef HAVE_GETRUSAGE
getrusage(RUSAGE_SELF, &r);
printf(_("time: %5.2f/%5.2f/%5.2f\n"),
timeval_subtract(&time_end, &track->time_start),
timeval_subtract(&r.ru_utime, &track->user_start),
timeval_subtract(&r.ru_stime, &track->system_start));
#else
printf(_("elapsed time: %6.3f\n"),
timeval_subtract(&time_end, &track->time_start));
#endif
}
#endif /* RESOURCE_TRACK */
void e2fsck_read_inode(e2fsck_t ctx, unsigned long ino,
struct ext2_inode * inode, const char *proc)
{
int retval;
retval = ext2fs_read_inode(ctx->fs, ino, inode);
if (retval) {
com_err("ext2fs_read_inode", retval,
_("while reading inode %ld in %s"), ino, proc);
fatal_error(ctx, 0);
}
}
extern void e2fsck_write_inode_full(e2fsck_t ctx, unsigned long ino,
struct ext2_inode * inode, int bufsize,
const char *proc)
{
int retval;
retval = ext2fs_write_inode_full(ctx->fs, ino, inode, bufsize);
if (retval) {
com_err("ext2fs_write_inode", retval,
_("while writing inode %ld in %s"), ino, proc);
fatal_error(ctx, 0);
}
}
extern void e2fsck_write_inode(e2fsck_t ctx, unsigned long ino,
struct ext2_inode * inode, const char *proc)
{
int retval;
retval = ext2fs_write_inode(ctx->fs, ino, inode);
if (retval) {
com_err("ext2fs_write_inode", retval,
_("while writing inode %ld in %s"), ino, proc);
fatal_error(ctx, 0);
}
}
#ifdef MTRACE
void mtrace_print(char *mesg)
{
FILE *malloc_get_mallstream();
FILE *f = malloc_get_mallstream();
if (f)
fprintf(f, "============= %s\n", mesg);
}
#endif
blk_t get_backup_sb(e2fsck_t ctx, ext2_filsys fs, const char *name,
io_manager manager)
{
struct ext2_super_block *sb;
io_channel io = NULL;
void *buf = NULL;
int blocksize;
blk_t superblock, ret_sb = 8193;
if (fs && fs->super) {
ret_sb = (fs->super->s_blocks_per_group +
fs->super->s_first_data_block);
if (ctx) {
ctx->superblock = ret_sb;
ctx->blocksize = fs->blocksize;
}
return ret_sb;
}
if (ctx) {
if (ctx->blocksize) {
ret_sb = ctx->blocksize * 8;
if (ctx->blocksize == 1024)
ret_sb++;
ctx->superblock = ret_sb;
return ret_sb;
}
ctx->superblock = ret_sb;
ctx->blocksize = 1024;
}
if (!name || !manager)
goto cleanup;
if (manager->open(name, 0, &io) != 0)
goto cleanup;
if (ext2fs_get_mem(SUPERBLOCK_SIZE, &buf))
goto cleanup;
sb = (struct ext2_super_block *) buf;
for (blocksize = EXT2_MIN_BLOCK_SIZE;
blocksize <= EXT2_MAX_BLOCK_SIZE ; blocksize *= 2) {
superblock = blocksize*8;
if (blocksize == 1024)
superblock++;
io_channel_set_blksize(io, blocksize);
if (io_channel_read_blk(io, superblock,
-SUPERBLOCK_SIZE, buf))
continue;
#ifdef EXT2FS_ENABLE_SWAPFS
if (sb->s_magic == ext2fs_swab16(EXT2_SUPER_MAGIC))
ext2fs_swap_super(sb);
#endif
if (sb->s_magic == EXT2_SUPER_MAGIC) {
ret_sb = superblock;
if (ctx) {
ctx->superblock = superblock;
ctx->blocksize = blocksize;
}
break;
}
}
cleanup:
if (io)
io_channel_close(io);
if (buf)
ext2fs_free_mem(&buf);
return (ret_sb);
}
/*
* Given a mode, return the ext2 file type
*/
int ext2_file_type(unsigned int mode)
{
if (LINUX_S_ISREG(mode))
return EXT2_FT_REG_FILE;
if (LINUX_S_ISDIR(mode))
return EXT2_FT_DIR;
if (LINUX_S_ISCHR(mode))
return EXT2_FT_CHRDEV;
if (LINUX_S_ISBLK(mode))
return EXT2_FT_BLKDEV;
if (LINUX_S_ISLNK(mode))
return EXT2_FT_SYMLINK;
if (LINUX_S_ISFIFO(mode))
return EXT2_FT_FIFO;
if (LINUX_S_ISSOCK(mode))
return EXT2_FT_SOCK;
return 0;
}
|
Khoronus/StoreData | module/record/src/record/create_file.cpp | /* @file create_file.cpp
* @brief Body of the defined class.
*
* @section LICENSE
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR/AUTHORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author <NAME> <<EMAIL>>
* @bug No known bugs.
* @version 0.3.0.0
*
*/
#include "record/inc/record/create_file.hpp"
namespace storedata
{
// ----------------------------------------------------------------------------
MemorizeFileManager::MemorizeFileManager() {}
// ----------------------------------------------------------------------------
MemorizeFileManager::~MemorizeFileManager() {
release();
}
// ----------------------------------------------------------------------------
void MemorizeFileManager::release() {
fout_.close();
fout_.clear();
}
// ----------------------------------------------------------------------------
void MemorizeFileManager::setup(size_t memory_max_allocable,
const std::string &filename,
const std::string &dot_extension) {
memory_expected_allocated_ = 0;
memory_max_allocable_ = memory_max_allocable;
filename_ = filename;
dot_extension_ = dot_extension;
}
// ----------------------------------------------------------------------------
int MemorizeFileManager::generate(const std::string &appendix, bool append) {
if (!fout_.is_open()) {
std::string filename = filename_ + appendix + dot_extension_;
std::cout << filename << std::endl;
// get the current time
if (append) {
fout_.open(filename.c_str(), std::ios::binary | std::ios::app);
} else {
fout_.open(filename.c_str(), std::ios::binary);
}
// Get the file size
memory_expected_allocated_ = filesize(filename.c_str());
return kSuccess;
}
return kFail;
}
// ----------------------------------------------------------------------------
int MemorizeFileManager::check_memory(size_t size) {
//std::cout << ">> " << memory_expected_allocated_ << " " << size << " " << memory_max_allocable_ << std::endl;
if (memory_expected_allocated_ + size < memory_max_allocable_) {
return kSuccess;
}
return kFail;
}
// ----------------------------------------------------------------------------
int MemorizeFileManager::push(const std::vector<char> &data) {
if (!fout_.is_open()) return kFileIsNotOpen;
if (data.size() > 0) {
if (check_memory(data.size())) {
fout_.write(&data[0], data.size());
fout_.flush();
memory_expected_allocated_ += data.size();
return kSuccess;
} else {
// out of memory
return kOutOfMemory;
}
}
// The data is empty
return kDataIsEmpty;
}
// ----------------------------------------------------------------------------
FileGeneratorManagerAsync::FileGeneratorManagerAsync(){
verbose_ = false;
under_writing_ = false;
}
// ----------------------------------------------------------------------------
FileGeneratorManagerAsync::~FileGeneratorManagerAsync() {
close();
}
// ----------------------------------------------------------------------------
int FileGeneratorManagerAsync::setup(
unsigned int max_memory_allocable,
std::map<int, FileGeneratorParams> &vgp, int record_framerate) {
std::cout << "FileGeneratorManagerAsync::setup" << std::endl;
int return_status = kSuccess;
// set framerate to record and capture at
record_framerate_ = record_framerate;
#ifdef BOOST_BUILD
// initialize initial timestamps
nextFrameTimestamp_ = boost::posix_time::microsec_clock::local_time();
currentFrameTimestamp_ = nextFrameTimestamp_;
td_ = (currentFrameTimestamp_ - nextFrameTimestamp_);
#endif
// Get the appendix to add to the video
std::string appendix = DateTime::time2string();
std::cout << "FileGeneratorManagerAsync::setup:appendix: " <<
appendix << std::endl;
for (int i = 0; i < appendix.length(); i++)
{
if (appendix[i] == ':') appendix[i] = '_';
}
// callback to inform that a new file will be created
if (callback_createfile_) {
callback_createfile_(appendix);
}
// Create the video writer
#if _MSC_VER && !__INTEL_COMPILER && (_MSC_VER > 1600)
for (auto it = vgp.begin(); it != vgp.end(); it++)
#else
for (std::map<int, FileGeneratorParams>::const_iterator it = vgp.begin(); it != vgp.end(); it++)
#endif
{
m_files_[it->first] = new MemorizeFileManager();
m_files_[it->first]->setup(max_memory_allocable,
it->second.filename(), it->second.dot_extension());
if (!m_files_[it->first]->generate(appendix, false)) {
return_status = kFail;
}
}
//number_addframe_requests_ = 0;
under_writing_ = false;
return return_status;
}
// ----------------------------------------------------------------------------
bool FileGeneratorManagerAsync::under_writing() {
return under_writing_;
}
// ----------------------------------------------------------------------------
bool FileGeneratorManagerAsync::procedure() {
#ifdef BOOST_BUILD
bool result_out = false;
boost::mutex::scoped_lock lock(mutex_, boost::try_to_lock);
if (lock) {
under_writing_ = true;
//determine current elapsed time
currentFrameTimestamp_ = boost::posix_time::microsec_clock::local_time();
td_ = (currentFrameTimestamp_ - nextFrameTimestamp_);
// wait for X microseconds until 1second/framerate time has passed after previous frame write
if (record_framerate_ < 0 ||
td_.total_microseconds() >= 1000000 / record_framerate_) {
// determine time at start of write
initialLoopTimestamp_ = boost::posix_time::microsec_clock::local_time();
// Check the memory
bool memory_ok = true;
#if _MSC_VER && !__INTEL_COMPILER && (_MSC_VER > 1600)
for (auto it = data_in_.begin(); it != data_in_.end(); it++)
#else
for (std::map<int, std::vector<char> >::const_iterator it = data_in_.begin(); it != data_in_.end(); it++)
#endif
{
// Test the data
if (m_files_.find(it->first) != m_files_.end()) {
if (!m_files_[it->first]->check_memory(it->second.size())) {
memory_ok = false;
break;
}
}
}
// At least one file has not enough memory.
// Close all the files and create a new one
if (!memory_ok) {
// Get the appendix to add to the video
std::string appendix = DateTime::time2string();
for (int i = 0; i < appendix.length(); i++)
{
if (appendix[i] == ':') appendix[i] = '_';
}
// callback to inform that a new file will be created
if (callback_createfile_) {
callback_createfile_(appendix);
}
#if _MSC_VER && !__INTEL_COMPILER && (_MSC_VER > 1600)
for (auto it = m_files_.begin(); it != m_files_.end(); it++)
#else
for (std::map<int, MemorizeFileManager* >::const_iterator it = m_files_.begin(); it != m_files_.end(); it++)
#endif
{
it->second->release();
it->second->generate(appendix, false);
}
}
// Add the data
#if _MSC_VER && !__INTEL_COMPILER && (_MSC_VER > 1600)
for (auto it = data_in_.begin(); it != data_in_.end(); it++)
#else
for (std::map<int, std::vector<char> >::const_iterator it = data_in_.begin(); it != data_in_.end(); it++)
#endif
{
// Test if the file manager exists
if (m_files_.find(it->first) != m_files_.end()) {
// If able to write to disk
if (m_files_[it->first]->push(it->second) ==
kSuccess) {
result_out = true;
}
}
}
//write previous and current frame timestamp to console
if (verbose_) {
std::cout << nextFrameTimestamp_ << " " << currentFrameTimestamp_ << " ";
}
// add 1second/framerate time for next loop pause
nextFrameTimestamp_ = nextFrameTimestamp_ +
boost::posix_time::microsec(1000000 / record_framerate_);
// reset time_duration so while loop engages
td_ = (currentFrameTimestamp_ - nextFrameTimestamp_);
//determine and print out delay in ms, should be less than 1000/FPS
//occasionally, if delay is larger than said value, correction will occur
//if delay is consistently larger than said value, then CPU is not powerful
// enough to capture/decompress/record/compress that fast.
finalLoopTimestamp_ = boost::posix_time::microsec_clock::local_time();
td1_ = (finalLoopTimestamp_ - initialLoopTimestamp_);
delayFound_ = td1_.total_milliseconds();
if (verbose_) {
std::cout << delayFound_ << std::endl;
}
}
under_writing_ = false;
}
return result_out;
#endif
}
// ----------------------------------------------------------------------------
void FileGeneratorManagerAsync::check() {
std::cout << "FileGeneratorManagerAsync::check(): " << under_writing_ <<
std::endl;//" " << number_addframe_requests_ << std::endl;
}
// ----------------------------------------------------------------------------
int FileGeneratorManagerAsync::push_data_write_not_guarantee_can_replace(
const std::map<int, std::vector<char> > &data_in) {
bool write_success = false;
#ifdef BOOST_BUILD
if (!under_writing_) {
{
boost::mutex::scoped_lock lock(mutex_, boost::try_to_lock);
if (lock) {
//++number_addframe_requests_;
#if _MSC_VER && !__INTEL_COMPILER && (_MSC_VER > 1600)
for (auto it = data_in.begin(); it != data_in.end(); it++)
#else
for (std::map<int, std::vector<char> >::const_iterator it = data_in.begin(); it != data_in.end(); it++)
#endif
{
data_in_[it->first] = it->second;
}
write_success = true;
}
}
//boost::thread* thr = new boost::thread(
// boost::bind(&FileGeneratorManagerAsync::procedure, this));
if (write_success) {
auto a = std::async(
&FileGeneratorManagerAsync::procedure, this);
}
// used only for test to detect lost frames
//container_future_.push(std::async(&FileGeneratorManagerAsync::procedure, this));
//return kSuccess;
}
#endif
//return kFail;
return write_success;
}
// ----------------------------------------------------------------------------
void FileGeneratorManagerAsync::close() {
#ifdef BOOST_BUILD
while (under_writing_ ){ //|| number_addframe_requests_ > 0) {
//std::cout << under_writing_ << " " << number_addframe_requests_ << std::endl;
boost::this_thread::sleep(boost::posix_time::milliseconds(10));
}
#endif
#if _MSC_VER && !__INTEL_COMPILER && (_MSC_VER > 1600)
for (auto it = m_files_.begin(); it != m_files_.end(); it++)
#else
for (std::map<int, MemorizeFileManager* >::const_iterator it = m_files_.begin(); it != m_files_.end(); it++)
#endif
{
delete it->second;
}
m_files_.clear();
// used only for test to detect lost frames
//// Container with the future result
//while (!container_future_.empty())
//{
// std::cout << "res:" << container_future_.front().get() << std::endl;
// container_future_.pop();
//}
}
// ----------------------------------------------------------------------------
void FileGeneratorManagerAsync::set_verbose(bool verbose) {
verbose_ = verbose;
}
// ----------------------------------------------------------------------------
void FileGeneratorManagerAsync::set_callback_createfile(
cbk_fname_changed callback_createfile) {
callback_createfile_ = callback_createfile;
}
} // namespace storedata
|
rhabbachi/ckanext-issues | ckanext/issues/tests/controllers/test_search.py | from ckan.plugins import toolkit
try:
from ckan.tests import helpers
from ckan.tests import factories
except ImportError:
from ckan.new_tests import helpers
from ckan.new_tests import factories
from ckanext.issues.tests import factories as issue_factories
from ckanext.issues import model as issue_model
from nose.tools import (assert_is_not_none, assert_equals, assert_in,
assert_not_in)
import bs4
class TestSearchBox(helpers.FunctionalTestBase):
def setup(self):
super(TestSearchBox, self).setup()
self.owner = factories.User()
self.org = factories.Organization(user=self.owner)
self.dataset = factories.Dataset(user=self.owner,
owner_org=self.org['name'])
self.issue = issue_factories.Issue(user=self.owner,
dataset_id=self.dataset['id'])
self.app = self._get_test_app()
def test_search_box_appears_issue_dataset_page(self):
response = self.app.get(
url=toolkit.url_for('issues_dataset',
dataset_id=self.dataset['id'],
issue_number=self.issue['number']),
)
soup = bs4.BeautifulSoup(response.body)
edit_button = soup.find('form', {'class': 'search-form'})
assert_is_not_none(edit_button)
def test_search_box_submits_q_get(self):
in_search = [issue_factories.Issue(user_id=self.owner['id'],
dataset_id=self.dataset['id'],
title=title)
for title in ['some titLe', 'another Title']]
# some issues not in the search
[issue_factories.Issue(user_id=self.owner['id'],
dataset_id=self.dataset['id'],
title=title)
for title in ['blah', 'issue']]
issue_dataset = self.app.get(
url=toolkit.url_for('issues_dataset',
dataset_id=self.dataset['id'],
issue_number=self.issue['number']),
)
search_form = issue_dataset.forms[1]
search_form['q'] = 'title'
res = search_form.submit()
soup = bs4.BeautifulSoup(res.body)
issue_links = soup.find(id='issue-list').find_all('h4')
titles = set([i.a.text.strip() for i in issue_links])
assert_equals(set([i['title'] for i in in_search]), titles)
class TestSearchFilters(helpers.FunctionalTestBase):
def setup(self):
super(TestSearchFilters, self).setup()
self.owner = factories.User()
self.org = factories.Organization(user=self.owner)
self.dataset = factories.Dataset(user=self.owner,
owner_org=self.org['name'])
self.issues = {
'visible': issue_factories.Issue(user=self.owner,
title='visible_issue',
dataset_id=self.dataset['id']),
'closed': issue_factories.Issue(user=self.owner,
title='closed_issue',
dataset_id=self.dataset['id']),
'hidden': issue_factories.Issue(user=self.owner,
title='hidden_issue',
dataset_id=self.dataset['id'],
visibility='hidden'),
}
# close our issue
helpers.call_action(
'issue_update',
issue_number=self.issues['closed']['number'],
dataset_id=self.dataset['id'],
context={'user': self.owner['name']},
status='closed'
)
issue = issue_model.Issue.get(self.issues['hidden']['id'])
issue.visibility = 'hidden'
issue.save()
self.app = self._get_test_app()
def test_click_visiblity_links(self):
env = {'REMOTE_USER': self.owner['name'].encode('ascii')}
response = self.app.get(
url=toolkit.url_for('issues_dataset',
dataset_id=self.dataset['id']),
extra_environ=env,
)
# visible and hidden should be shown, but not closed
assert_in('2 issues found', response)
assert_in('visible_issue', response)
assert_in('hidden_issue', response)
assert_not_in('closed_issue', response)
# click the hidden filter
response = response.click(linkid='hidden-filter', extra_environ=env)
assert_in('1 issue found', response)
assert_not_in('visible_issue', response)
assert_in('hidden_issue', response)
assert_not_in('closed_issue', response)
# click the visible filter
response = response.click(linkid='visible-filter', extra_environ=env)
assert_in('1 issue found', response)
assert_in('visible_issue', response)
assert_not_in('hidden_issue', response)
assert_not_in('closed_issue', response)
# clear the filter by clikcing on visible again
response = response.click(linkid='visible-filter', extra_environ=env)
assert_in('2 issues found', response)
assert_in('visible_issue', response)
assert_in('hidden_issue', response)
assert_not_in('closed_issue', response)
def test_click_status_links(self):
env = {'REMOTE_USER': self.owner['name'].encode('ascii')}
response = self.app.get(
url=toolkit.url_for('issues_dataset',
dataset_id=self.dataset['id']),
extra_environ=env,
)
# visible and hidden should be shown, but not closed
assert_in('2 issues found', response)
assert_in('visible_issue', response)
assert_in('hidden_issue', response)
assert_not_in('closed_issue', response)
# click the closed filter
response = response.click(linkid='closed-filter', extra_environ=env)
assert_in('1 issue found', response)
assert_not_in('visible_issue', response)
assert_not_in('hidden_issue', response)
assert_in('closed_issue', response)
# click the open filter
response = response.click(linkid='open-filter', extra_environ=env)
assert_in('2 issues found', response)
assert_in('visible_issue', response)
assert_in('hidden_issue', response)
assert_not_in('closed_issue', response)
def test_visiblity_links_do_not_appear_for_unauthed_user(self):
response = self.app.get(
url=toolkit.url_for('issues_dataset',
dataset_id=self.dataset['id']),
)
assert_not_in('filter-hidden', response)
assert_not_in('filter-visible', response)
|
MouchenHung-QUANTA/OpenBIC | meta-facebook/yv35-bb/src/platform/plat_isr.c | <reponame>MouchenHung-QUANTA/OpenBIC
#include "plat_isr.h"
#include <stdlib.h>
#include "libipmi.h"
#include "libutil.h"
#include "kcs.h"
#include "power_status.h"
#include "ipmi.h"
#include "sensor.h"
#include "snoop.h"
#include "oem_handler.h"
#include "oem_1s_handler.h"
#include "plat_gpio.h"
#include "plat_ipmb.h"
#include "plat_ipmi.h"
#include "plat_sensor_table.h"
#include "plat_i2c.h"
void sled_cycle_work_handler(struct k_work *item);
K_WORK_DELAYABLE_DEFINE(sled_cycle_work, sled_cycle_work_handler);
void ISR_PWROK_SLOT1()
{
set_BIC_slot_isolator(PWROK_STBY_BIC_SLOT1_R, FM_BIC_SLOT1_ISOLATED_EN_R);
}
void ISR_PWROK_SLOT3()
{
set_BIC_slot_isolator(PWROK_STBY_BIC_SLOT3_R, FM_BIC_SLOT3_ISOLATED_EN_R);
}
void ISR_SLED_CYCLE()
{
uint8_t bb_btn_status = GPIO_HIGH;
bb_btn_status = gpio_get(BB_BUTTON_BMC_BIC_N_R);
// press sled cycle button
if (bb_btn_status == GPIO_LOW) {
k_work_schedule(&sled_cycle_work, K_SECONDS(MAX_PRESS_SLED_BTN_TIME_s));
// release sled cycle button
} else if (bb_btn_status == GPIO_HIGH) {
k_work_cancel_delayable(&sled_cycle_work);
}
}
void ISR_SLOT1_PRESENT()
{
k_msleep(1000); // HW need 1s delay to correct the register
uint8_t mask = 1 << 0;
uint8_t retry = 5;
I2C_MSG i2c_msg_bb_cpld;
i2c_msg_bb_cpld.bus = CPLD_IO_I2C_BUS;
i2c_msg_bb_cpld.target_addr = CPLD_IO_I2C_ADDR;
i2c_msg_bb_cpld.rx_len = 1;
i2c_msg_bb_cpld.tx_len = 1;
i2c_msg_bb_cpld.data[0] = CPLD_IO_REG_CABLE_PRESENT;
if (i2c_master_read(&i2c_msg_bb_cpld, retry)) {
printf("%s Request i2c BB CPLD register failed\n", __func__);
return;
}
uint8_t cable_ret = ((i2c_msg_bb_cpld.data[0] & mask) >> 0);
uint8_t gpio_ret = gpio_get(PRSNT_MB_BIC_SLOT1_BB_N_R);
common_addsel_msg_t *sel_msg = (common_addsel_msg_t *)malloc(sizeof(common_addsel_msg_t));
if (sel_msg == NULL) {
printf("%s Memory allocation failed!\n", __func__);
return;
}
sel_msg->InF_target = SLOT3_BIC;
sel_msg->sensor_type = IPMI_OEM_SENSOR_TYPE_OEM;
sel_msg->event_type = IPMI_EVENT_TYPE_SENSOR_SPEC;
sel_msg->sensor_number = CMD_OEM_CABLE_DETECTION;
sel_msg->event_data2 = 0xFF;
sel_msg->event_data3 = 0xFF;
if (cable_ret == CABLE_ABSENT) {
sel_msg->event_data1 = IPMI_OEM_EVENT_OFFSET_SLOT1_CABLE_ABSENT;
} else if (gpio_ret == SYSTEM_ABSENT) {
sel_msg->event_data1 = IPMI_OEM_EVENT_OFFSET_SLOT1_SYSTEM_ABSENT;
} else {
sel_msg->event_data1 = IPMI_OEM_EVENT_OFFSET_SLOT1_SYSTEM_PRESENT;
}
common_add_sel_evt_record(sel_msg);
SAFE_FREE(sel_msg);
return;
}
void ISR_SLOT3_PRESENT()
{
k_msleep(1000); // HW need 1s delay to correct the register
uint8_t mask = 1 << 2;
uint8_t retry = 5;
I2C_MSG i2c_msg_bb_cpld;
i2c_msg_bb_cpld.bus = CPLD_IO_I2C_BUS;
i2c_msg_bb_cpld.target_addr = CPLD_IO_I2C_ADDR;
i2c_msg_bb_cpld.rx_len = 1;
i2c_msg_bb_cpld.tx_len = 1;
i2c_msg_bb_cpld.data[0] = CPLD_IO_REG_CABLE_PRESENT;
if (i2c_master_read(&i2c_msg_bb_cpld, retry)) {
printf("%s Request i2c BB CPLD register failed\n", __func__);
return;
}
uint8_t cable_ret = ((i2c_msg_bb_cpld.data[0] & mask) >> 2);
uint8_t gpio_ret = gpio_get(PRSNT_MB_BIC_SLOT3_BB_N_R);
common_addsel_msg_t *sel_msg = (common_addsel_msg_t *)malloc(sizeof(common_addsel_msg_t));
if (sel_msg == NULL) {
printf("%s Memory allocation failed!\n", __func__);
return;
}
sel_msg->InF_target = SLOT1_BIC;
sel_msg->sensor_type = IPMI_OEM_SENSOR_TYPE_OEM;
sel_msg->event_type = IPMI_EVENT_TYPE_SENSOR_SPEC;
sel_msg->sensor_number = CMD_OEM_CABLE_DETECTION;
sel_msg->event_data2 = 0xFF;
sel_msg->event_data3 = 0xFF;
if (cable_ret == CABLE_ABSENT) {
sel_msg->event_data1 = IPMI_OEM_EVENT_OFFSET_SLOT3_CABLE_ABSENT;
} else if (gpio_ret == SYSTEM_ABSENT) {
sel_msg->event_data1 = IPMI_OEM_EVENT_OFFSET_SLOT3_SYSTEM_ABSENT;
} else {
sel_msg->event_data1 = IPMI_OEM_EVENT_OFFSET_SLOT3_SYSTEM_PRESENT;
}
common_add_sel_evt_record(sel_msg);
SAFE_FREE(sel_msg);
return;
}
void set_BIC_slot_isolator(uint8_t pwr_state_gpio_num, uint8_t isolator_gpio_num)
{
int ret = 0;
uint8_t slot_pwr_status = GPIO_LOW;
slot_pwr_status = gpio_get(pwr_state_gpio_num);
if (slot_pwr_status == GPIO_HIGH) {
ret = gpio_set(isolator_gpio_num, GPIO_HIGH);
} else if (slot_pwr_status == GPIO_LOW) {
ret = gpio_set(isolator_gpio_num, GPIO_LOW);
}
if (ret < 0) {
printf("failed to set slot isolator due to set gpio %d is failed\n",
isolator_gpio_num);
}
}
void sled_cycle_work_handler(struct k_work *item)
{
set_sled_cycle();
}
void set_sled_cycle()
{
uint8_t retry = 5;
I2C_MSG msg;
msg.bus = CPLD_IO_I2C_BUS;
msg.target_addr = CPLD_IO_I2C_ADDR;
msg.tx_len = 2;
msg.data[0] = CPLD_IO_REG_OFS_SLED_CYCLE; // offset
msg.data[1] = 0x01; // value
if (i2c_master_write(&msg, retry) < 0) {
printf("sled cycle fail\n");
}
}
|
midoks/hammer | vendor/golang.org/x/crypto/blake2s/register.go | // Copyright 2017 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.
// +build go1.9
package blake2s
import (
"crypto"
"hash"
)
func init() {
newHash256 := func() hash.Hash {
h, _ := New256(nil)
return h
}
crypto.RegisterHash(crypto.BLAKE2s_256, newHash256)
}
|
rasputtim/SGPacMan | sgf/3.0/headers/Gamecore/lists/liststructs.h | /*
SGF - Salvat Game Fabric (https://sourceforge.net/projects/sgfabric/)
Copyright (C) 2010-2011 <NAME> <<EMAIL>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#pragma once
#ifndef _LIST_STRUCTS_H_
#define _LISTSTRUCTS_H_
#include "../../ExternalLibs/SDL2-2.0.3/include/SDL.h"
#include "../SGF_Config.h"
using namespace std;
namespace SGF{
struct ClsnRECT
{
short x,y;
short h,w;
};
//Clsn Struct to hold one Clns Rectangle with type
struct Clsn
{
bool bClsn1;
ClsnRECT ClsnRect;
};
//Element Strcut to save one Elment of an Action Block
struct Element
{
int nGroupNumber;
int nImageNumber;
int x;
int y;
int nDuringTime;
Uint16 FlipFlags;
Uint16 ColorFlags;
Clsn *pClnsData;
int nNumberOfClsn;
};
//Action Element to hold one Action Block with its Elements
struct ActionElement
{
int nActionNumber;
Element* AnimationElement;
int loopStart;
int nNumberOfElements;
int nCurrentImage;
Uint16 dwStartTime;
Uint16 dwCompletAnimTime;
Uint16 dwCurrTime;
Uint16 dwCurrentImageTime;
bool bLooped;
};
//Linked list struct for Airmanger
struct AirLinkedList
{
ActionElement ElementData;
AirLinkedList *Sucessor;
AirLinkedList *Antecessor;
};
struct ImageList
{
ImageList *Next;
ImageList *Prev;
short nGroupNumber;
short nImageNumber;
void *lpBitmap; //pointer to CBitmap
};
} //end SGF
#endif |
samleb/rubinius | spec/compiler/zsuper_spec.rb | <filename>spec/compiler/zsuper_spec.rb
require File.dirname(__FILE__) + '/../spec_helper'
describe "A Zsuper node" do
relates <<-ruby do
def x
super
end
ruby
parse do
[:defn, :x, [:args], [:scope, [:block, [:zsuper]]]]
end
compile do |g|
in_method :x do |d|
d.push_block
d.send_super :x, 0
end
end
end
end
|
arulvijay/awssum | lib/amazon/ec2-config.js | // --------------------------------------------------------------------------------------------------------------------
//
// ec2-config.js - config for AWS Elastic Compute Cloud
//
// Copyright (c) 2011, 2012 AppsAttic Ltd - http://www.appsattic.com/
// Written by <NAME> <<EMAIL>>
//
// License: http://opensource.org/licenses/MIT
//
// --------------------------------------------------------------------------------------------------------------------
var required = { required : true, type : 'param' };
var optional = { required : false, type : 'param' };
var requiredArray = { required : true, type : 'param-array' };
var optionalArray = { required : false, type : 'param-array' };
var requiredData = { required : true, type : 'param-data' };
var optionalData = { required : false, type : 'param-data' };
// --------------------------------------------------------------------------------------------------------------------
module.exports = {
AllocateAddress : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AllocateAddress.html',
defaults : {
Action : 'AllocateAddress'
},
args : {
Action : required,
Domain : optional,
},
},
AssignPrivateIpAddresses : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AssignPrivateIpAddresses.html',
defaults : {
Action : 'AssignPrivateIpAddresses',
},
args : {
Action : required,
NetworkInterfaceId : required,
PrivateIpAddress : optionalArray,
SecondaryPrivateIpAddressCount : optional,
AllowReassignment : optional,
},
},
AssociateAddress : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AssociateAddress.html',
defaults : {
Action : 'AssociateAddress',
},
args : {
Action : required,
PublicIp : optional,
InstanceId : optional,
AllocationId : optional,
NetworkInterfaceId : optional,
PrivateIpAddress : optional,
AllowReassociation : optional,
},
},
AssociateDhcpOptions : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AssociateDhcpOptions.html',
defaults : {
Action : 'AssociateDhcpOptions',
},
args : {
Action : required,
DhcpOptionsId : required,
VpcId : required,
},
},
AssociateRouteTable : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AssociateRouteTable.html',
defaults : {
Action : 'AssociateRouteTable',
},
args : {
Action : required,
RouteTableId : required,
SubnetId : required
},
},
AttachInternetGateway : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AttachInternetGateway.html',
defaults : {
Action : 'AttachInternetGateway',
},
args : {
Action : required,
InternetGatewayId : required,
VpcId : required,
},
},
AttachNetworkInterface : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AttachNetworkInterface.html',
defaults : {
Action : 'AttachNetworkInterface',
},
args : {
Action : required,
NetworkInterfaceId : required,
InstanceId : required,
DeviceIndex : required,
},
},
AttachVolume : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AttachVolume.html',
defaults : {
Action : 'AttachVolume',
},
args : {
Action : required,
VolumeId : required,
InstanceId : required,
Device : required,
},
},
AttachVpnGateway : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AttachVpnGateway.html',
defaults : {
Action : 'AttachVpnGateway',
},
args : {
Action : required,
VpnGatewayId : required,
VpcId : required,
},
},
AuthorizeSecurityGroupEgress : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AuthorizeSecurityGroupEgress.html',
defaults : {
Action : 'AuthorizeSecurityGroupEgress',
},
args : {
Action : required,
GroupId : required,
IpPermissions : requiredData,
},
},
AuthorizeSecurityGroupIngress : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AuthorizeSecurityGroupIngress.html',
defaults : {
Action : 'AuthorizeSecurityGroupIngress',
},
args : {
Action : required,
UserId : optional,
GroupId : optional,
GroupName : optional,
IpPermissions : requiredData,
},
},
BundleInstance : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-BundleInstance.html',
defaults : {
Action : 'BundleInstance',
},
args : {
Action : required,
InstanceId : required,
Storage : required,
},
},
CancelBundleTask : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CancelBundleTask.html',
defaults : {
Action : 'CancelBundleTask',
},
args : {
Action : required,
BundleId : required,
},
},
CancelConversionTask : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CancelConversionTask.html',
defaults : {
Action : 'CancelConversionTask',
},
args : {
Action : required,
ConversionTaskId : required,
},
},
CancelExportTask : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CancelExportTask.html',
defaults : {
Action : 'CancelExportTask',
},
args : {
Action : required,
ExportTaskId : required,
},
},
CancelReservedInstancesListing : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CancelReservedInstancesListing.html',
defaults : {
Action : 'CancelReservedInstancesListing',
},
args : {
Action : required,
ReservedInstancesListingId : requiredArray,
},
},
CancelSpotInstanceRequests : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CancelSpotInstanceRequests.html',
defaults : {
Action : 'CancelSpotInstanceRequests',
},
args : {
Action : required,
SpotInstanceRequestId : requiredArray,
},
},
ConfirmProductInstance : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ConfirmProductInstance.html',
defaults : {
Action : 'ConfirmProductInstance',
},
args : {
Action : required,
ProductCode : required,
InstanceId : required,
},
},
CreateCustomerGateway : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateCustomerGateway.html',
defaults : {
Action : 'CreateCustomerGateway',
},
args : {
Action : required,
Type : required,
IpAddress : required,
BgpAsn : required,
},
},
CreateDhcpOptions : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateDhcpOptions.html',
defaults : {
Action : 'CreateDhcpOptions',
},
args : {
Action : required,
DhcpConfiguration : requiredData,
},
},
CreateImage : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateImage.html',
defaults : {
Action : 'CreateImage',
},
args : {
Action : required,
InstanceId : required,
Name : required,
Description : optional,
NoReboot : optional,
},
},
CreateInstanceExportTask : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateInstanceExportTask.html',
defaults : {
Action : 'CreateInstanceExportTask',
},
args : {
Action : required,
Description : optional,
InstanceId : required,
TargetEnvironment : required,
ExportToS3 : required,
},
},
CreateInternetGateway : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateInternetGateway.html',
defaults : {
Action : 'CreateInternetGateway',
},
args : {
Action : required,
},
},
CreateKeyPair : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateKeyPair.html',
defaults : {
Action : 'CreateKeyPair',
},
args : {
Action : required,
KeyName : required,
},
},
CreateNetworkAcl : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateNetworkAcl.html',
defaults : {
Action : 'CreateNetworkAcl',
},
args : {
Action : required,
VpcId : required,
},
},
CreateNetworkAclEntry : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateNetworkAclEntry.html',
defaults : {
Action : 'CreateNetworkAclEntry',
},
args : {
Action : required,
NetworkAclId : required,
RuleNumber : required,
Protocol : required,
RuleAction : required,
Egress : optional,
CidrBlock : required,
Icmp : optionalData,
PortRange : optionalData,
},
},
CreateNetworkInterface : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateNetworkInterface.html',
defaults : {
Action : 'CreateNetworkInterface',
},
args : {
Action : required,
SubnetId : required,
PrivateIpAddress : optional,
PrivateIpAddresses : optional,
SecondaryPrivateIpAddressCount : optional,
Description : optional,
SecurityGroupId : optional,
},
},
CreateReservedInstancesListing : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateReservedInstancesListing.html',
defaults : {
Action : 'CreateReservedInstancesListing',
},
args : {
Action : required,
ReservedInstancesId : required,
InstanceCount : required,
PriceSchedules : requiredData,
ClientToken : required,
},
},
CreatePlacementGroup : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreatePlacementGroup.html',
defaults : {
Action : 'CreatePlacementGroup',
},
args : {
Action : required,
GroupName : required,
Strategy : required,
},
},
CreateRoute : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateRoute.html',
defaults : {
Action : 'CreateRoute',
},
args : {
Action : required,
RouteTableId : required,
DestinationCidrBlock : required,
GatewayId : optional,
InstanceId : optional,
NetworkInterfaceId : optional,
},
},
CreateRouteTable : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateRouteTable.html',
defaults : {
Action : 'CreateRouteTable',
},
args : {
Action : required,
VpcId : required,
},
},
CreateSecurityGroup : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateSecurityGroup.html',
defaults : {
Action : 'CreateSecurityGroup',
},
args : {
Action : required,
GroupName : required,
GroupDescription : required,
VpcId : optional,
},
},
CreateSnapshot : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateSnapshot.html',
defaults : {
Action : 'CreateSnapshot',
},
args : {
Action : required,
VolumeId : required,
Description : optional,
},
},
CreateSpotDatafeedSubscription : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateSpotDatafeedSubscription.html',
defaults : {
Action : 'CreateSpotDatafeedSubscription',
},
args : {
Action : required,
Bucket : required,
Prefix : optional,
},
},
CreateSubnet : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateSubnet.html',
defaults : {
Action : 'CreateSubnet',
},
args : {
Action : required,
VpcId : required,
CidrBlock : required,
AvailabilityZone : optional,
},
},
CreateTags : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateTags.html',
defaults : {
Action : 'CreateTags',
},
args : {
Action : required,
ResourceId : requiredArray,
Tag : requiredData,
},
},
CreateVolume : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVolume.html',
defaults : {
Action : 'CreateVolume',
},
args : {
Action : required,
Size : optional,
SnapshotId : optional,
AvailabilityZone : required,
},
},
CreateVpc : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVpc.html',
defaults : {
Action : 'CreateVpc',
},
args : {
Action : required,
CidrBlock : required,
InstanceTenancy : { required : false, type : 'param', name : 'instanceTenancy' },
},
},
CreateVpnConnection : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVpnConnection.html',
defaults : {
Action : 'CreateVpnConnection',
},
args : {
Action : required,
Type : required,
CustomerGatewayId : required,
VpnGatewayId : required,
AvailabilityZone : optional,
},
},
CreateVpnConnectionRoute : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVpnConnectionRoute.html',
defaults : {
Action : 'CreateVpnConnectionRoute',
},
args : {
Action : required,
DestinationCidrBlock : required,
VpnConnectionId : required,
},
},
CreateVpnGateway : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVpnGateway.html',
defaults : {
Action : 'CreateVpnGateway',
},
args : {
Action : required,
Type : required,
// AvailabilityZone - deprecated, the API ignores it anyway
},
},
DeleteCustomerGateway : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteCustomerGateway.html',
defaults : {
Action : 'DeleteCustomerGateway',
},
args : {
Action : required,
CustomerGatewayId : required,
},
},
DeleteDhcpOptions : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteDhcpOptions.html',
defaults : {
Action : 'DeleteDhcpOptions',
},
args : {
Action : required,
DhcpOptionsId : required,
},
},
DeleteInternetGateway : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteInternetGateway.html',
defaults : {
Action : 'DeleteInternetGateway',
},
args : {
Action : required,
InternetGatewayId : required,
},
},
DeleteKeyPair : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteKeyPair.html',
defaults : {
Action : 'DeleteKeyPair',
},
args : {
Action : required,
KeyName : required,
},
},
DeleteNetworkAcl : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteNetworkAcl.html',
defaults : {
Action : 'DeleteNetworkAcl',
},
args : {
Action : required,
NetworkAclId : required,
},
},
DeleteNetworkAclEntry : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteNetworkAclEntry.html',
defaults : {
Action : 'DeleteNetworkAclEntry',
},
args : {
Action : required,
NetworkAclId : required,
RuleNumber : required,
Egress : optional,
},
},
DeleteNetworkInterface : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteNetworkInterface.html',
defaults : {
Action : 'DeleteNetworkInterface',
},
args : {
Action : required,
NetworkInterfaceId : required,
},
},
DeletePlacementGroup : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeletePlacementGroup.html',
defaults : {
Action : 'DeletePlacementGroup',
},
args : {
Action : required,
GroupName : required,
},
},
DeleteRoute : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteRoute.html',
defaults : {
Action : 'DeleteRoute',
},
args : {
Action : required,
RouteTableId : required,
DestinationCidrBlock : required,
},
},
DeleteRouteTable : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteRouteTable.html',
defaults : {
Action : 'DeleteRouteTable',
},
args : {
Action : required,
RouteTableId : required,
},
},
DeleteSecurityGroup : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteSecurityGroup.html',
defaults : {
Action : 'DeleteSecurityGroup',
},
args : {
Action : required,
GroupName : optional,
GroupId : optional,
},
},
DeleteSnapshot : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteSnapshot.html',
defaults : {
Action : 'DeleteSnapshot',
},
args : {
Action : required,
SnapshotId : required,
},
},
DeleteSpotDatafeedSubscription : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteSpotDatafeedSubscription.html',
defaults : {
Action : 'DeleteSpotDatafeedSubscription',
},
args : {
Action : required,
},
},
DeleteSubnet : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteSubnet.html',
defaults : {
Action : 'DeleteSubnet',
},
args : {
Action : required,
SubnetId : required,
},
},
DeleteTags : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteTags.html',
defaults : {
Action : 'DeleteTags',
},
args : {
Action : required,
ResourceId : requiredArray,
Tag : requiredData,
},
},
DeleteVolume : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteVolume.html',
defaults : {
Action : 'DeleteVolume',
},
args : {
Action : required,
VolumeId : required,
},
},
DeleteVpc : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteVpc.html',
defaults : {
Action : 'DeleteVpc',
},
args : {
Action : required,
VpcId : required,
},
},
DeleteVpnConnection : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteVpnConnection.html',
defaults : {
Action : 'DeleteVpnConnection',
},
args : {
Action : required,
VpnConnectionId : required,
},
},
DeleteVpnConnectionRoute : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteVpnConnectionRoute.html',
defaults : {
Action : 'DeleteVpnConnectionRoute',
},
args : {
Action : required,
DestinationCidrBlock : required,
VpnConnectionId : required,
},
},
DeleteVpnGateway : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteVpnGateway.html',
defaults : {
Action : 'DeleteVpnGateway',
},
args : {
Action : required,
VpnGatewayId : required,
},
},
DeregisterImage : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeregisterImage.html',
defaults : {
Action : 'DeregisterImage',
},
args : {
Action : required,
ImageId : required,
},
},
DescribeAddresses : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeAddresses.html',
defaults : {
Action : 'DescribeAddresses',
},
args : {
Action : required,
PublicIp : optionalArray,
AllocationId : optionalArray,
Filter : optionalData,
},
},
DescribeAvailabilityZones : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeAvailabilityZones.html',
defaults : {
Action : 'DescribeAvailabilityZones',
},
args : {
Action : required,
ZoneName : optionalArray,
Filter : optionalData,
},
},
DescribeBundleTasks : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeBundleTasks.html',
defaults : {
Action : 'DescribeBundleTasks',
},
args : {
Action : required,
BundleId : optionalArray,
Filter : optionalData,
},
},
DescribeConversionTasks : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeConversionTasks.html',
defaults : {
Action : 'DescribeConversionTasks',
},
args : {
Action : required,
ConversionTaskId : optionalArray,
},
},
DescribeCustomerGateways : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeCustomerGateways.html',
defaults : {
Action : 'DescribeCustomerGateways',
},
args : {
Action : required,
CustomerGatewayId : optionalArray,
Filter : optionalData,
},
},
DescribeDhcpOptions : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeDhcpOptions.html',
defaults : {
Action : 'DescribeDhcpOptions',
},
args : {
Action : required,
DhcpOptionsId : optionalArray,
Filter : optionalData,
},
},
DescribeExportTasks : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeExportTasks.html',
defaults : {
Action : 'DescribeExportTasks',
},
args : {
Action : required,
ExportTaskId : optionalArray,
},
},
DescribeImageAttribute : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeImageAttribute.html',
defaults : {
Action : 'DescribeImageAttribute',
},
args : {
Action : required,
ImageId : required,
Attribute : required,
},
},
DescribeImages : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeImages.html',
defaults : {
Action : 'DescribeImages',
},
args : {
Action : required,
ExecutableBy : optionalArray,
ImageId : optionalArray,
Owner : optionalArray,
Filter : optionalData,
},
},
DescribeInstanceAttribute : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstanceAttribute.html',
defaults : {
Action : 'DescribeInstanceAttribute',
},
args : {
Action : required,
InstanceId : required,
Attribute : required,
},
},
DescribeInstances : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstances.html',
defaults : {
Action : 'DescribeInstances',
},
args : {
Action : required,
InstanceId : optionalArray,
Filter : optionalData,
},
},
DescribeInstanceStatus : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstanceStatus.html',
defaults : {
Action : 'DescribeInstanceStatus',
},
args : {
Action : required,
InstanceId : optional,
IncludeAllInstances : optional,
MaxResults : optional,
NextToken : optional,
},
},
DescribeInternetGateways : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInternetGateways.html',
defaults : {
Action : 'DescribeInternetGateways',
},
args : {
Action : required,
InternetGatewayId : optionalArray,
Filter : optionalData,
},
},
DescribeKeyPairs : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeKeyPairs.html',
defaults : {
Action : 'DescribeKeyPairs',
},
args : {
Action : required,
KeyName : optionalArray,
Filter : optionalData,
},
},
DescribeNetworkAcls : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeNetworkAcls.html',
defaults : {
Action : 'DescribeNetworkAcls',
},
args : {
Action : required,
NetworkAclId : optionalArray,
Filter : optionalData,
},
},
DescribeNetworkInterfaceAttribute : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeNetworkInterfaceAttribute.html',
defaults : {
Action : 'DescribeNetworkInterfaceAttribute',
},
args : {
Action : required,
NetworkInterfaceId : required,
Attribute : required,
},
},
DescribeNetworkInterfaces : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeNetworkInterfaces.html',
defaults : {
Action : 'DescribeNetworkInterfaces',
},
args : {
Action : required,
NetworkInterfaceId : optionalArray,
Filter : optionalData,
},
},
DescribePlacementGroups : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribePlacementGroups.html',
defaults : {
Action : 'DescribePlacementGroups',
},
args : {
Action : required,
GroupName : optionalArray,
Filter : optionalData,
},
},
DescribeRegions : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeRegions.html',
defaults : {
Action : 'DescribeRegions',
},
args : {
Action : required,
RegionName : optionalArray,
Filter : optionalData,
},
},
DescribeReservedInstances : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeReservedInstances.html',
defaults : {
Action : 'DescribeReservedInstances',
},
args : {
Action : required,
ReservedInstancesId : optionalArray,
Filter : optionalData,
OfferingType : { required : false, type : 'param', name : 'offeringType' },
},
},
DescribeReservedInstancesListings : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeReservedInstancesListings.html',
defaults : {
Action : 'DescribeReservedInstancesListings',
},
args : {
Action : required,
ReservedInstancesListingId : optionalArray,
ReservedInstancesId : optionalArray,
Filter : optionalData,
},
},
DescribeReservedInstancesOfferings : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeReservedInstancesOfferings.html',
defaults : {
Action : 'DescribeReservedInstancesOfferings',
},
args : {
Action : required,
ReservedInstancesOfferingId : optionalArray,
InstanceType : optional,
AvailabilityZone : optional,
ProductDescription : optional,
Filter : optionalData,
InstanceTenancy : { required : false, type : 'param', name : 'instanceTenancy' },
OfferingType : { required : false, type : 'param', name : 'offeringType' },
},
},
DescribeRouteTables : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeRouteTables.html',
defaults : {
Action : 'DescribeRouteTables',
},
args : {
Action : required,
RouteTableId : optionalArray,
Filter : optionalData,
},
},
DescribeSecurityGroups : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSecurityGroups.html',
defaults : {
Action : 'DescribeSecurityGroups',
},
args : {
Action : required,
GroupName : optionalArray,
GroupId : optionalArray,
Filter : optionalData,
},
},
DescribeSnapshotAttribute : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSnapshotAttribute.html',
defaults : {
Action : 'DescribeSnapshotAttribute',
},
args : {
Action : required,
SnapshotId : required,
Attribute : required,
},
},
DescribeSnapshots : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSnapshots.html',
defaults : {
Action : 'DescribeSnapshots',
},
args : {
Action : required,
SnapshotId : optionalArray,
Owner : optionalArray,
RestorableBy : optionalArray,
Filter : optionalData,
},
},
DescribeSpotDatafeedSubscription : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSpotDatafeedSubscription.html',
defaults : {
Action : 'DescribeSpotDatafeedSubscription',
},
args : {
Action : required,
},
},
DescribeSpotInstanceRequests : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSpotInstanceRequests.html',
defaults : {
Action : 'DescribeSpotInstanceRequests',
},
args : {
Action : required,
SpotInstanceRequestId : optionalArray,
Filter : optionalData,
},
},
DescribeSpotPriceHistory : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSpotPriceHistory.html',
defaults : {
Action : 'DescribeSpotPriceHistory',
},
args : {
Action : required,
StartTime : optional,
EndTime : optional,
InstanceType : optionalArray,
ProductDescription : optionalArray,
Filter : optionalData,
AvailabilityZone : optional,
MaxResults : optional,
NextToken : optional,
},
},
DescribeSubnets : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSubnets.html',
defaults : {
Action : 'DescribeSubnets',
},
args : {
Action : required,
SubnetId : optionalArray,
Filter : optionalData,
},
},
DescribeTags : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeTags.html',
defaults : {
Action : 'DescribeTags',
},
args : {
Action : required,
Filter : optionalData,
},
},
DescribeVolumes : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVolumes.html',
defaults : {
Action : 'DescribeVolumes',
},
args : {
Action : required,
VolumeId : optionalArray,
Filter : optionalData,
},
},
DescribeVolumeAttribute : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVolumeAttribute.html',
defaults : {
Action : 'DescribeVolumeAttribute',
},
args : {
Action : required,
VolumeId : required,
Attribute : required,
},
},
DescribeVolumeStatus : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVolumeStatus.html',
defaults : {
Action : 'DescribeVolumeStatus',
},
args : {
Action : required,
VolumeId : optionalArray,
Filter : optionalData,
MaxResults : optional,
NextToken : optional,
},
},
DescribeVpcs : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVpcs.html',
defaults : {
Action : 'DescribeVpcs',
},
args : {
Action : required,
VpcId : optionalArray,
Filter : optionalData,
},
},
DescribeVpnConnections : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVpnConnections.html',
defaults : {
Action : 'DescribeVpnConnections',
},
args : {
Action : required,
VpnConnectionId : optionalArray,
Filter : optionalData,
},
},
DescribeVpnGateways : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVpnGateways.html',
defaults : {
Action : 'DescribeVpnGateways',
},
args : {
Action : required,
VpnGatewayId : optionalArray,
Filter : optionalData,
},
},
DetachInternetGateway : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DetachInternetGateway.html',
defaults : {
Action : 'DetachInternetGateway',
},
args : {
Action : required,
InternetGatewayId : required,
VpcId : required,
},
},
DetachNetworkInterface : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DetachNetworkInterface.html',
defaults : {
Action : 'DetachNetworkInterface',
},
args : {
Action : required,
AttachmentId : required,
Force : optional,
},
},
DetachVolume : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DetachVolume.html',
defaults : {
Action : 'DetachVolume',
},
args : {
Action : required,
VolumeId : required,
InstanceId : optional,
Device : optional,
Force : optional,
},
},
DetachVpnGateway : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DetachVpnGateway.html',
defaults : {
Action : 'DetachVpnGateway',
},
args : {
Action : required,
VpnGatewayId : required,
VpcId : required,
},
},
DisableVgwRoutePropagation : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DisableVGWRoutePropagation.html',
defaults : {
Action : 'DisableVgwRoutePropagation',
},
args : {
Action : required,
RouteTableId : required,
GatewayId : required,
},
},
DisassociateAddress : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DisassociateAddress.html',
defaults : {
Action : 'DisassociateAddress',
},
args : {
Action : required,
PublicIp : optional,
AssociationId : optional,
},
},
DisassociateRouteTable : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DisassociateRouteTable.html',
defaults : {
Action : 'DisassociateRouteTable',
},
args : {
Action : required,
AssociationId : required,
},
},
EnableVgwRoutePropagation : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-EnableVGWRoutePropagation.html',
defaults : {
Action : 'EnableVgwRoutePropagation',
},
args : {
Action : required,
RouteTableId : required,
GatewayId : required,
},
},
EnableVolumeIo : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-EnableVolumeIO.html',
defaults : {
Action : 'EnableVolumeIO',
},
args : {
Action : required,
VolumeId : required,
},
},
GetConsoleOutput : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-GetConsoleOutput.html',
defaults : {
Action : 'GetConsoleOutput',
},
args : {
Action : required,
InstanceId : required,
},
},
GetPasswordData : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-GetPasswordData.html',
defaults : {
Action : 'GetPasswordData',
},
args : {
Action : required,
InstanceId : required,
},
},
ImportInstance : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ImportInstance.html',
defaults : {
Action : 'ImportInstance',
},
args : {
Action : required,
Description : optional,
Architecture : required,
SecurityGroup : optionalArray,
UserData : optional,
InstanceType : required,
Placement : optionalData,
Monitoring : optionalData,
SubnetId : optional,
InstanceInitiatedShutdownBehavior : optional,
PrivateIpAddress : optional,
DiskImage : requiredData,
Platform : required,
},
},
ImportKeyPair : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ImportKeyPair.html',
defaults : {
Action : 'ImportKeyPair',
},
args : {
Action : required,
KeyName : required,
PublicKeyMaterial : required,
},
},
ImportVolume : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ImportVolume.html',
defaults : {
Action : 'ImportVolume',
},
args : {
Action : required,
AvailabilityZone : required,
Image : requiredData,
Description : optional,
Volume : requiredData,
},
},
ModifyImageAttribute : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyImageAttribute.html',
defaults : {
Action : 'ModifyImageAttribute',
},
args : {
Action : required,
ImageId : required,
LaunchPermission : optionalData,
ProductCode : optional,
Description : optional,
},
},
ModifyInstanceAttribute : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyInstanceAttribute.html',
defaults : {
Action : 'ModifyInstanceAttribute',
},
args : {
Action : required,
InstanceId : required,
InstanceType : optionalData,
Kernel : optionalData,
Ramdisk : optionalData,
UserData : optionalData,
DisableApiTermination : optionalData,
InstanceInitiatedShutdownBehavior : optionalData,
BlockMappingDevice : optionalData,
SourceDestCheck : optionalData,
GroupId : optionalArray,
EbsOptimized : optional,
},
},
ModifyNetworkInterfaceAttribute : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyNetworkInterfaceAttribute.html',
defaults : {
Action : 'ModifyNetworkInterfaceAttribute',
},
args : {
Action : required,
NetworkInterfaceId : required,
Description : optionalData,
SecurityGroupId : optionalArray,
SourceDestCheck : optionalData,
Attachment : optionalData,
},
},
ModifySnapshotAttribute : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifySnapshotAttribute.html',
defaults : {
Action : 'ModifySnapshotAttribute',
},
args : {
Action : required,
SnapshotId : required,
CreateVolumePermission : requiredData,
},
},
ModifyVolumeAttribute : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyVolumeAttribute.html',
defaults : {
Action : 'ModifyVolumeAttribute',
},
args : {
Action : required,
VolumeId : required,
AutoEnableIO : requiredData,
},
},
MonitorInstances : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-MonitorInstances.html',
defaults : {
Action : 'MonitorInstances',
},
args : {
Action : required,
InstanceId : requiredArray,
},
},
PurchaseReservedInstancesOffering : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-PurchaseReservedInstancesOffering.html',
defaults : {
Action : 'PurchaseReservedInstancesOffering',
},
args : {
Action : required,
ReservedInstancesOfferingId : required,
InstanceCount : optional,
},
},
RebootInstances : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-RebootInstances.html',
defaults : {
Action : 'RebootInstances',
},
args : {
Action : required,
InstanceId : requiredArray,
},
},
RegisterImage : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-RegisterImage.html',
defaults : {
Action : 'RegisterImage',
},
args : {
Action : required,
ImageLocation : optional,
Name : required,
Description : optional,
Architecture : optional,
KernelId : optional,
RamdiskId : optional,
RootDeviceName : optional,
BlockDeviceMapping : optionalData,
},
},
ReleaseAddress : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ReleaseAddress.html',
defaults : {
Action : 'ReleaseAddress',
},
args : {
Action : required,
PublicIp : optional,
AllocationId : optional,
},
},
ReplaceNetworkAclAssociation : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ReplaceNetworkAclAssociation.html',
defaults : {
Action : 'ReplaceNetworkAclAssociation',
},
args : {
Action : required,
AssociationId : required,
NetworkAclId : required,
},
},
ReplaceNetworkAclEntry : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ReplaceNetworkAclEntry.html',
defaults : {
Action : 'ReplaceNetworkAclEntry',
},
args : {
Action : required,
NetworkAclId : required,
RuleNumber : required,
Protocol : required,
RuleAction : required,
Egress : optional,
CidrBlock : required,
Icmp : optionalData,
PortRange : optionalData,
},
},
ReplaceRoute : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ReplaceRoute.html',
defaults : {
Action : 'ReplaceRoute',
},
args : {
Action : required,
RouteTableId : required,
DestinationCidrBlock : required,
GatewayId : optional,
InstanceId : optional,
NetworkInterfaceId : optional,
},
},
ReplaceRouteTableAssociation : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ReplaceRouteTableAssociation.html',
defaults : {
Action : 'ReplaceRouteTableAssociation',
},
args : {
Action : required,
AssociationId : required,
RouteTableId : required,
},
},
ReportInstanceStatus : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ReportInstanceStatus.html',
defaults : {
Action : 'ReportInstanceStatus',
},
args : {
Action : required,
InstanceID : requiredArray,
Status : required,
StartTime : optional,
EndTime : optional,
ReasonCodes : requiredArray,
Description : optional,
},
},
RequestSpotInstances : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-RequestSpotInstances.html',
defaults : {
Action : 'RequestSpotInstances',
},
args : {
Action : required,
SpotPrice : required,
InstanceCount : optional,
Type : optional,
ValidFrom : optional,
ValidUntil : optional,
Subnet : optional,
LaunchGroup : optional,
AvailabilityZoneGroup : optional,
Placement : optionalData,
LaunchSpecification : requiredData, // because of LaunchSpecification.{ImageId,InstanceType}
},
},
ResetImageAttribute : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ResetImageAttribute.html',
defaults : {
Action : 'ResetImageAttribute',
},
args : {
Action : required,
ImageId : required,
Attribute : required,
},
},
ResetInstanceAttribute : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ResetInstanceAttribute.html',
defaults : {
Action : 'ResetInstanceAttribute',
},
args : {
Action : required,
InstanceId : required,
Attribute : required,
},
},
ResetNetworkInterfaceAttribute : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ResetNetworkInterfaceAttribute.html',
defaults : {
Action : 'ResetNetworkInterfaceAttribute',
},
args : {
Action : required,
NetworkInterfaceId : required,
Attribute : required,
},
},
ResetSnapshotAttribute : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ResetSnapshotAttribute.html',
defaults : {
Action : 'ResetSnapshotAttribute',
},
args : {
Action : required,
SnapshotId : required,
Attribute : required,
},
},
RevokeSecurityGroupEgress : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-RevokeSecurityGroupEgress.html',
defaults : {
Action : 'RevokeSecurityGroupEgress',
},
args : {
Action : required,
GroupId : required,
IpPermissions : requiredData,
},
},
RevokeSecurityGroupIngress : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-RevokeSecurityGroupIngress.html',
defaults : {
Action : 'RevokeSecurityGroupIngress',
},
args : {
Action : required,
UserId : optional,
GroupId : optional,
GroupName : optional,
IpPermissions : requiredData,
},
},
RunInstances : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-RunInstances.html',
defaults : {
Action : 'RunInstances',
},
args : {
Action : required,
ImageId : required,
MinCount : required,
MaxCount : required,
KeyName : optional,
SecurityGroupId : optionalArray,
SecurityGroup : optionalArray,
UserData : optional,
AddressingType : optional,
InstanceType : optional,
Placement : optionalData,
KernelId : optional,
RamdiskId : optional,
BlockDeviceMapping : optionalData,
Monitoring : optionalData,
SubnetId : optional,
DisableApiTermination : optional,
InstanceInitiatedShutdownBehavior : optional,
PrivateIpAddress : optional,
ClientToken : optional,
NetworkInterface : optionalData,
IamInstanceProfile : optionalData,
EbsOptimized : optional,
},
},
StartInstances : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-StartInstances.html',
defaults : {
Action : 'StartInstances',
},
args : {
Action : required,
InstanceId : requiredArray,
},
},
StopInstances : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-StopInstances.html',
defaults : {
Action : 'StopInstances',
},
args : {
Action : required,
InstanceId : requiredArray,
Force : optional,
},
},
TerminateInstances : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-TerminateInstances.html',
defaults : {
Action : 'TerminateInstances',
},
args : {
Action : required,
InstanceId : requiredArray,
},
},
UnassignPrivateIpAddresses : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-UnassignPrivateIpAddresses.html',
defaults : {
Action : 'UnassignPrivateIpAddresses',
},
args : {
Action : required,
NetworkInterfaceId : required,
PrivateIpAddress : requiredArray,
},
},
UnmonitorInstances : {
url : 'http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-UnmonitorInstances.html',
defaults : {
Action : 'UnmonitorInstances',
},
args : {
Action : required,
InstanceId : requiredArray,
},
},
};
// --------------------------------------------------------------------------------------------------------------------
|
woutdenolf/spectrocrunch | spectrocrunch/xrf/parse_xia.py | <reponame>woutdenolf/spectrocrunch<filename>spectrocrunch/xrf/parse_xia.py
# -*- coding: utf-8 -*-
from PyMca5.PyMcaCore import XiaCorrect
from PyMca5.PyMcaCore import XiaEdf
from glob import glob
import os
import numpy as np
def log_dummy(message, verbose_level=None, verbose_ask=None):
pass
def parse_xia_esrf(
datadir,
scanname,
scannumber,
outdir,
outname,
exclude_detectors=[],
deadtime=True,
add=True,
willbefitted=True,
deadtimeifsingle=True,
):
"""Parse an XIA XRF scan with ESRF naming convention
Input files:
[scanname]_xia[xianum]_[scannumber]_0000_[linenumber].edf
xianum = detector number or "st"
Output files:
[scanname]_[outname]_xia[xianum]_[scannumber]_0000_[linenumber].edf
xianum = detector number or "S1" for sum
Args:
datadir(list(str)): directory of the xia files
scanname(list(str)): radix of the xia files
scannumber(list(int)): scan number of the xia files
outdir(str): directory for the corrected/summed xia files if any
outname(str): radix for the corrected/summed xia files if any
exclude_detectors(Optional(list[int])): detector numbers to be excluded
deadtime(Optional(bool)): apply deadtime correction to spectra
add(Optional(bool)): add spectra (after deadtime correction if any)
willbefitted(Optional(bool)): spectra will be fitted
deadtimeifsingle(Optional(bool)): deadtime can be skipped for a single detector (will be done afterwards)
"""
# Raw data
if not isinstance(datadir, list):
datadir = [datadir]
if not isinstance(scanname, list):
scanname = [scanname]
if not isinstance(scannumber, list):
scannumber = [scannumber]
if not isinstance(scannumber, list):
scannumber = [scannumber]
files_raw = []
for ddir, sname, snum in zip(datadir, scanname, scannumber):
filemask = os.path.join(ddir, "%s_xia*_%04d_0000_*.edf" % (sname, snum))
files_raw.extend(glob(filemask))
files_raw = sorted(files_raw)
# Check files
xiafiles = XiaCorrect.parseFiles(files_raw, log_cb=log_dummy)
# - files which only differ by their xianum are grouped together (i.e. each linescan or ct)
# - missing but existing xianum's are added
if xiafiles is None:
return [[]], []
# Exclude detectors
if len(exclude_detectors) != 0:
xiafiles = [
[f for f in fs if f.getDetector() not in exclude_detectors]
for fs in xiafiles
]
# Detector numbers
tmp = list(exclude_detectors)
tmp.append(None) # exclude "st" detector
detnums = [f.getDetector() for f in xiafiles[0] if f.getDetector() not in tmp]
ndet = len(detnums)
# Only count detectors and not save sum/dtcorrection?
if ndet < 2:
add = False
if deadtimeifsingle == False:
deadtime = False
if ndet == 0:
add = False
deadtime = False
willbefitted = False
if willbefitted == False and deadtime == False and add == False:
return [[]], detnums
# DT correction and optional summation
if add or deadtime:
if not os.path.exists(outdir):
os.makedirs(outdir)
if add:
sums = [detnums]
else:
sums = None
XiaCorrect.correctFiles(
xiafiles,
deadtime=deadtime,
livetime=0,
sums=sums,
avgflag=0,
outdir=outdir,
outname=outname,
force=1,
log_cb=None,
)
# Output files
files_out = []
for ddir, sname, snum in zip(datadir, scanname, scannumber):
if add:
filemask = os.path.join(
outdir, "%s_%s_xiaS1_%04d_0000_*.edf" % (ddir, sname, snum)
)
else:
filemask = os.path.join(
outdir, "%s_%s_xia[0-9]*_%04d_0000_*.edf" % (ddir, sname, snum)
)
files_out.extend(glob(filemask))
files_out = sorted(files_out)
else:
files_out = sorted(
[
file.get()
for detfiles in xiafiles
for file in detfiles
if not file.isStat()
]
)
# Group according to detector
if add:
files_out = [files_out]
else:
nf = len(files_out)
nfdet = nf // ndet
files_out = [files_out[i : i + nfdet] for i in range(0, nf, nfdet)]
return files_out, detnums
|
CorfuDB/CORFU | infrastructure/src/main/java/org/corfudb/infrastructure/RemoteMonitoringService.java | package org.corfudb.infrastructure;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.corfudb.common.result.Result;
import org.corfudb.infrastructure.log.FileSystemAgent;
import org.corfudb.infrastructure.log.FileSystemAgent.PartitionAgent.PartitionAttribute;
import org.corfudb.infrastructure.management.ClusterAdvisor;
import org.corfudb.infrastructure.management.ClusterAdvisorFactory;
import org.corfudb.infrastructure.management.ClusterStateContext;
import org.corfudb.infrastructure.management.ClusterType;
import org.corfudb.infrastructure.management.FailureDetector;
import org.corfudb.infrastructure.management.FileSystemAdvisor;
import org.corfudb.infrastructure.management.PollReport;
import org.corfudb.infrastructure.management.failuredetector.EpochHandler;
import org.corfudb.infrastructure.management.failuredetector.FailureDetectorDataStore;
import org.corfudb.infrastructure.management.failuredetector.FailureDetectorException;
import org.corfudb.infrastructure.management.failuredetector.FailureDetectorHelper;
import org.corfudb.infrastructure.management.failuredetector.FailuresAgent;
import org.corfudb.infrastructure.management.failuredetector.HealingAgent;
import org.corfudb.protocols.wireprotocol.ClusterState;
import org.corfudb.protocols.wireprotocol.NodeState;
import org.corfudb.protocols.wireprotocol.SequencerMetrics;
import org.corfudb.protocols.wireprotocol.failuredetector.FileSystemStats;
import org.corfudb.protocols.wireprotocol.failuredetector.FileSystemStats.PartitionAttributeStats;
import org.corfudb.runtime.CorfuRuntime;
import org.corfudb.runtime.view.Layout;
import org.corfudb.util.LambdaUtils;
import org.corfudb.util.concurrent.SingletonResource;
import java.time.Duration;
import java.util.Collections;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
* Remote Monitoring Service constitutes of failure and healing monitoring and handling.
* This service is responsible for heartbeat and aggregating the cluster view. This is
* updated in the shared context with the management server which serves the heartbeat responses.
* The failure detector updates the unreachable nodes in the layout.
* The healing detector heals nodes which were previously marked unresponsive but have now healed.
* Created by zlokhandwala on 11/2/18.
*/
@Slf4j
public class RemoteMonitoringService implements ManagementService {
private static final CompletableFuture<DetectorTask> DETECTOR_TASK_NOT_COMPLETED
= CompletableFuture.completedFuture(DetectorTask.NOT_COMPLETED);
private static final CompletableFuture<DetectorTask> DETECTOR_TASK_SKIPPED
= CompletableFuture.completedFuture(DetectorTask.SKIPPED);
/**
* Detectors to be used to detect failures and healing.
*/
@Getter
private final FailureDetector failureDetector;
/**
* Detection Task Scheduler Service
* This service schedules the following tasks every POLICY_EXECUTE_INTERVAL (1 sec):
* - Detection of failed nodes.
* - Detection of healed nodes.
*/
@Getter
private final ScheduledExecutorService detectionTasksScheduler;
/**
* To dispatch tasks for failure or healed nodes detection.
*/
@Getter
private final ExecutorService failureDetectorWorker;
private final ServerContext serverContext;
private final SingletonResource<CorfuRuntime> runtimeSingletonResource;
private final ClusterStateContext clusterContext;
private final LocalMonitoringService localMonitoringService;
/**
* Future for periodic failure and healed nodes detection task.
*/
private CompletableFuture<DetectorTask> failureDetectorFuture = DETECTOR_TASK_NOT_COMPLETED;
private final ClusterAdvisor advisor;
private final HealingAgent healingAgent;
private final FailuresAgent failuresAgent;
private final FailureDetectorDataStore fdDataStore;
/**
* The management agent attempts to bootstrap a NOT_READY sequencer if the
* sequencerNotReadyCounter counter exceeds this value.
*/
private final int sequencerNotReadyThreshold = 3;
/**
* Number of workers for failure detector. Three workers used by default:
* - failure/healing detection
* - bootstrap sequencer
* - merge segments
*/
private final int detectionWorkersCount = 3;
/**
* This tuple maintains, in an epoch, how many heartbeats the primary sequencer has responded
* in not bootstrapped (NOT_READY) state.
*/
@Getter
@Setter
@AllArgsConstructor
private static class SequencerNotReadyCounter {
private final long epoch;
private int counter;
public void increment() {
counter += 1;
}
}
private volatile SequencerNotReadyCounter sequencerNotReadyCounter = new SequencerNotReadyCounter(0, 0);
RemoteMonitoringService(@NonNull ServerContext serverContext,
@NonNull SingletonResource<CorfuRuntime> runtimeSingletonResource,
@NonNull ClusterStateContext clusterContext,
@NonNull FailureDetector failureDetector,
@NonNull LocalMonitoringService localMonitoringService) {
this.serverContext = serverContext;
this.runtimeSingletonResource = runtimeSingletonResource;
this.clusterContext = clusterContext;
this.failureDetector = failureDetector;
this.localMonitoringService = localMonitoringService;
this.advisor = ClusterAdvisorFactory.createForStrategy(
ClusterType.COMPLETE_GRAPH,
serverContext.getLocalEndpoint()
);
this.detectionTasksScheduler = Executors.newSingleThreadScheduledExecutor(
new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat(serverContext.getThreadPrefix() + "RemoteMonitoringService")
.build());
// Creating the detection worker thread pool.
// This thread pool is utilized to dispatch detection tasks at regular intervals in the
// detectorTaskScheduler.
ThreadFactory fdThreadFactory = new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat(serverContext.getThreadPrefix() + "DetectionWorker-%d")
.build();
this.failureDetectorWorker = Executors.newFixedThreadPool(detectionWorkersCount, fdThreadFactory);
fdDataStore = FailureDetectorDataStore.builder()
.localEndpoint(serverContext.getLocalEndpoint())
.dataStore(serverContext.getDataStore())
.build();
FileSystemAdvisor fsAdvisor = new FileSystemAdvisor();
healingAgent = HealingAgent.builder()
.advisor(advisor)
.fsAdvisor(fsAdvisor)
.localEndpoint(serverContext.getLocalEndpoint())
.runtimeSingleton(runtimeSingletonResource)
.failureDetectorWorker(failureDetectorWorker)
.dataStore(fdDataStore)
.build();
failuresAgent = FailuresAgent.builder()
.localEndpoint(serverContext.getLocalEndpoint())
.fdDataStore(fdDataStore)
.advisor(advisor)
.fsAdvisor(fsAdvisor)
.runtimeSingleton(runtimeSingletonResource)
.build();
}
private CorfuRuntime getCorfuRuntime() {
return runtimeSingletonResource.get();
}
/**
* Executes task to run failure and healing detection every poll interval. (Default: 1 sec)
* <p>
* During the initialization step, the method:
* - triggers sequencer bootstrap
* - starts failure and healing detection mechanism, by running <code>runDetectionTasks</code>
* every second (by default). Next iteration of detection task can be run only if current iteration is completed.
*/
@Override
public void start(Duration monitoringInterval) {
// Trigger sequencer bootstrap on startup.
sequencerBootstrap(serverContext);
Runnable task = () -> {
if (!failureDetectorFuture.isDone()) {
return;
}
failureDetectorFuture = runDetectionTasks();
};
detectionTasksScheduler.scheduleAtFixedRate(
() -> LambdaUtils.runSansThrow(task),
0,
monitoringInterval.toMillis(),
TimeUnit.MILLISECONDS
);
}
/**
* Trigger sequencer bootstrap mechanism. Get current layout management view and execute async bootstrap
*
* @param serverContext server context
*/
private CompletableFuture<DetectorTask> sequencerBootstrap(ServerContext serverContext) {
log.info("Trigger sequencer bootstrap on startup");
return getCorfuRuntime()
.getLayoutManagementView()
.asyncSequencerBootstrap(serverContext.copyManagementLayout(), failureDetectorWorker)
.thenApply(DetectorTask::fromBool);
}
/**
* Schedules the failure detection and handling mechanism by detectorTaskScheduler.
* It schedules exactly one instance of the following tasks.
* - Failure detection tasks.
* - Healing detection tasks.
*
* <pre>
* The algorithm:
* - wait until previous iteration finishes
* - On every invocation, this task refreshes the runtime to fetch the latest layout and also updates
* the local persisted copy of the latest layout.
* - get corfu metrics (Sequencer, LogUnit etc).
* - executes the poll using the failureDetector which generates a pollReport at the end of the round.
* The report contains latest information about cluster: connectivity graph, failed and healed nodes, wrong epochs.
* - refresh cluster state context by latest {@link ClusterState} collected on poll report step.
* - run failure detector task composed from:
* - the outOfPhase epoch server errors are corrected by resealing and patching these trailing layout servers.
* - all unresponsive server failures are handled by either removing or marking
* them as unresponsive based on a failure handling policy.
* - make healed node responsive based on a healing detection mechanism
* </pre>
*/
private synchronized CompletableFuture<DetectorTask> runDetectionTasks() {
return getCorfuRuntime()
.invalidateLayout()
.thenApply(serverContext::saveManagementLayout)
//check if this node can handle failures (if the node is in the cluster)
.thenCompose(ourLayout -> {
String localEndpoint = serverContext.getLocalEndpoint();
FailureDetectorHelper helper = new FailureDetectorHelper(ourLayout, localEndpoint);
return helper.handleReconfigurationsAsync();
})
.thenCompose(ourLayout -> {
//Get metrics from local monitoring service (local monitoring works in it's own thread)
return localMonitoringService.getMetrics() //Poll report asynchronously using failureDetectorWorker executor
.thenCompose(metrics -> pollReport(ourLayout, metrics))
//Update cluster view by latest cluster state given by the poll report. No need to be asynchronous
.thenApply(pollReport -> {
log.trace("Update cluster view: {}", pollReport.getClusterState());
clusterContext.refreshClusterView(ourLayout, pollReport);
return pollReport;
})
.thenApply(pollReport -> {
if (!pollReport.getClusterState().isReady()) {
throw FailureDetectorException.notReady(pollReport.getClusterState());
}
return pollReport;
})
//Execute failure detector task using failureDetectorWorker executor
.thenCompose(pollReport -> runFailureDetectorTask(pollReport, ourLayout));
})
//Print exceptions to log
.whenComplete((taskResult, ex) -> {
if (ex != null) {
log.error("Failure detection task finished with an error", ex);
}
});
}
private CompletableFuture<PollReport> pollReport(Layout layout, SequencerMetrics sequencerMetrics) {
return CompletableFuture.supplyAsync(() -> {
PartitionAttribute partition = FileSystemAgent.getPartitionAttribute();
PartitionAttributeStats partitionAttributeStats = new PartitionAttributeStats(
partition.isReadOnly(),
partition.getAvailableSpace(),
partition.getTotalSpace()
);
FileSystemStats fsStats = new FileSystemStats(partitionAttributeStats);
CorfuRuntime corfuRuntime = getCorfuRuntime();
return failureDetector.poll(layout, corfuRuntime, sequencerMetrics, fsStats);
}, failureDetectorWorker);
}
/**
* <pre>
* Failure/Healing detector task. Detects faults in the cluster and heals servers also corrects wrong epochs:
* - correct wrong epochs by resealing the servers and updating trailing layout servers.
* Fetch quorum layout and update the epoch according to the quorum.
* - check if current layout slot is unfilled then update layout to latest one.
* - handle healed nodes.
* - Looking for link failures in the cluster, handle failure if found.
* - Restore redundancy and merge segments if present in the layout.
* - bootstrap sequencer if needed
* </pre>
*
* @param pollReport cluster status
* @return async detection task
*/
private CompletableFuture<DetectorTask> runFailureDetectorTask(PollReport pollReport, Layout ourLayout) {
EpochHandler epochHandler = EpochHandler.builder()
.corfuRuntime(getCorfuRuntime())
.serverContext(serverContext)
.failureDetectorWorker(failureDetectorWorker)
.build();
// Corrects out of phase epoch issues if present in the report. This method
// performs re-sealing of all nodes if required and catchup of a layout server to
// the current state.
CompletableFuture<Layout> wrongEpochTask = epochHandler.correctWrongEpochs(pollReport, ourLayout);
return wrongEpochTask.thenApplyAsync(latestLayout -> {
// This is just an optimization in case we receive a WrongEpochException
// while one of the other management clients is trying to move to a new layout.
// This check is merely trying to minimize the scenario in which we end up
// filling the slot with an outdated layout.
if (!pollReport.areAllResponsiveServersSealed()) {
log.debug("All responsive servers have not been sealed yet. Skipping.");
return DetectorTask.COMPLETED;
}
Result<DetectorTask, RuntimeException> failure = Result.of(() -> {
Optional<Long> unfilledSlot = pollReport.getLayoutSlotUnFilled(latestLayout);
// If the latest slot has not been filled, fill it with the previous known layout.
if (unfilledSlot.isPresent()) {
log.info("Trying to fill an unfilled slot {}. PollReport: {}",
unfilledSlot.get(), pollReport);
failuresAgent.handleFailure(latestLayout, Collections.emptySet(), pollReport).join();
return DetectorTask.COMPLETED;
}
return DetectorTask.NOT_COMPLETED;
});
if (!pollReport.getWrongEpochs().isEmpty()) {
log.debug("Wait for next iteration. Poll report contains wrong epochs: {}",
pollReport.getWrongEpochs()
);
return DetectorTask.COMPLETED;
}
// If layout was updated by correcting wrong epochs,
// we can't continue with failure detection,
// as the cluster state has changed.
if (!latestLayout.equals(ourLayout)) {
log.warn("Layout was updated by correcting wrong epochs. " +
"Cancel current round of failure detection.");
return DetectorTask.COMPLETED;
}
failure.ifError(err -> log.error("Can't fill slot. Poll report: {}", pollReport, err));
if (failure.isValue() && failure.get() == DetectorTask.COMPLETED) {
return DetectorTask.COMPLETED;
}
DetectorTask healing = healingAgent.detectAndHandleHealing(pollReport, ourLayout).join();
//If local node healed it causes change in the cluster state which means the layout is changed also.
//If the cluster status is changed let failure detector detect the change on next iteration and
//behave according to latest cluster state.
if (healing == DetectorTask.COMPLETED) {
return DetectorTask.COMPLETED;
}
// Analyze the poll report and trigger failure handler if needed.
DetectorTask handleFailure = failuresAgent.detectAndHandleFailure(pollReport, ourLayout);
//If a failure is detected (which means we have updated a layout)
// then don't try to heal anything, wait for next iteration.
if (handleFailure == DetectorTask.COMPLETED) {
return DetectorTask.COMPLETED;
}
// Restores redundancy and merges multiple segments if present.
healingAgent.restoreRedundancyAndMergeSegments(ourLayout);
handleSequencer(ourLayout);
return DetectorTask.COMPLETED;
}, failureDetectorWorker);
}
/**
* Checks sequencer state, triggers a new task to bootstrap the sequencer for the specified layout (if needed).
*
* @param layout current layout
*/
private CompletableFuture<DetectorTask> handleSequencer(Layout layout) {
log.trace("Handling sequencer failures");
ClusterState clusterState = clusterContext.getClusterView();
Optional<NodeState> primarySequencer = clusterState.getNode(layout.getPrimarySequencer());
if (primarySequencer.isPresent() && primarySequencer.get().getSequencerMetrics() == SequencerMetrics.READY) {
log.trace("Primary sequencer is already ready at: {} in {}", primarySequencer.get(), clusterState);
return DETECTOR_TASK_SKIPPED;
}
// If failures are not present we can check if the primary sequencer has been
// bootstrapped from the heartbeat responses received.
if (sequencerNotReadyCounter.getEpoch() != layout.getEpoch()) {
// If the epoch is different than the poll epoch, we reset the timeout state.
log.trace("Current epoch is different to layout epoch. Update current epoch to: {}", layout.getEpoch());
sequencerNotReadyCounter = new SequencerNotReadyCounter(layout.getEpoch(), 1);
return DETECTOR_TASK_SKIPPED;
}
// If the epoch is same as the epoch being tracked in the tuple, we need to
// increment the count and attempt to bootstrap the sequencer if the count has
// crossed the threshold.
sequencerNotReadyCounter.increment();
if (sequencerNotReadyCounter.getCounter() < sequencerNotReadyThreshold) {
return DETECTOR_TASK_SKIPPED;
}
// Launch task to bootstrap the primary sequencer.
log.trace("Attempting to bootstrap the primary sequencer. ClusterState {}", clusterState);
// We do not care about the result of the trigger.
// If it fails, we detect this again and retry in the next polling cycle.
return getCorfuRuntime()
.getLayoutManagementView()
.asyncSequencerBootstrap(layout, failureDetectorWorker)
.thenApply(DetectorTask::fromBool);
}
@Override
public void shutdown() {
// Shutting the fault detector.
detectionTasksScheduler.shutdownNow();
failureDetectorWorker.shutdownNow();
log.info("Fault detection service shutting down.");
}
public enum DetectorTask {
/**
* The task is completed successfully
*/
COMPLETED,
/**
* The task is completed with an exception
*/
NOT_COMPLETED,
/**
* Skipped task
*/
SKIPPED;
public static DetectorTask fromBool(boolean taskResult) {
return taskResult ? COMPLETED : NOT_COMPLETED;
}
}
}
|
pdobrowo/libcs2 | src/mat44f.c | /**
* Copyright (c) 2015-2019 <NAME>
*
* This file is part of the Configuration Space Library (libcs2), a library
* for creating configuration spaces of various motion planning problems.
*
* 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.
*/
#include "cs2/mat44f.h"
#include "cs2/assert.h"
#include <stddef.h>
void cs2_mat44f_zero(struct cs2_mat44f_s *m)
{
m->e00 = m->e01 = m->e02 = m->e03 = 0.0;
m->e10 = m->e11 = m->e12 = m->e13 = 0.0;
m->e20 = m->e21 = m->e22 = m->e23 = 0.0;
m->e30 = m->e31 = m->e32 = m->e33 = 0.0;
}
void cs2_mat44f_identity(struct cs2_mat44f_s *m)
{
m->e00 = m->e11 = m->e22 = m->e33 = 1.0;
m->e01 = m->e02 = m->e03 = 0.0;
m->e10 = m->e12 = m->e13 = 0.0;
m->e20 = m->e21 = m->e23 = 0.0;
m->e30 = m->e31 = m->e32 = 0.0;
}
void cs2_mat44f_transform(struct cs2_vec4f_s *v, const struct cs2_mat44f_s *ma, const struct cs2_vec4f_s *va)
{
CS2_ASSERT(v != va);
v->x = ma->e00 * va->x + ma->e01 * va->y + ma->e02 * va->z + ma->e03 * va->w;
v->y = ma->e10 * va->x + ma->e11 * va->y + ma->e12 * va->z + ma->e13 * va->w;
v->z = ma->e20 * va->x + ma->e21 * va->y + ma->e22 * va->z + ma->e23 * va->w;
v->w = ma->e30 * va->x + ma->e31 * va->y + ma->e32 * va->z + ma->e33 * va->w;
}
|
gbtorrance/test | core/src/main/java/org/tdc/model/CompositorNode.java | package org.tdc.model;
/**
* Interface for compositor nodes.
*/
public interface CompositorNode extends NonAttribNode {
CompositorType getCompositorType();
}
|
talenet/talenet | src/renderer/models/Pub.js | import { filterFields } from '../util/objects'
import { addGetters } from '../util/immutableBean'
const FIELDS = ['key', 'host', 'port', 'timestamp']
/**
* Immutable class holding data for a pub.
*/
export default class Pub {
constructor (data = {}) {
this._data = filterFields(data, FIELDS)
addGetters(this, this._data, FIELDS)
}
static fromSsb (address, timestamp) {
return new Pub({
...address,
timestamp
})
}
}
|
johnrob1880/fx-audio-kit-core | lib/__tests__/fx-arrangement-test.js | /**
* Copyright 2015, FxAudioKit
* All rights reserved.
*
* This source code is licensed under the MIT-style license found in the
* LICENSE file in the root directory of this source tree.
*
*/
'use strict';
var FxArrangement;
jest.dontMock('./../objects/fx-class');
jest.dontMock('./../audio/fx-arrangement');
describe("FxArrangement", function () {
beforeEach(function () {
FxArrangement = require('./../audio/fx-arrangement');
});
it('should set values in constructor', function () {
var id = "Arrangement Number One";
var title = "Some Title";
var artist = "<NAME>";
var arr = new FxArrangement(id, title, artist);
expect(arr.id).toEqual(id);
expect(arr.title).toEqual(title);
expect(arr.artist).toEqual(artist);
});
it('should add track to tracks', function () {
var arr = new FxArrangement("Arrangement", "Title", "Artist");
arr.addTrack({id: "Track1", title: "Test Track"});
expect(arr.tracks["Track1"]).toBeDefined();
expect(arr.tracks["Track1"].title).toEqual("Test Track");
});
it('should remove track', function() {
var arr = new FxArrangement("Arrangement", "Title", "Artist");
var track = {id: "Track1", title: "Test Track"};
arr.addTrack(track);
expect(arr.tracks["Track1"]).toBeDefined();
arr.removeTrack(track);
expect(arr.tracks["Track1"]).toBeUndefined();
});
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.