repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
googleapis/google-cloud-php-osconfig | src/V1/VulnerabilityReport/Vulnerability/Item.php | 7814 | <?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/osconfig/v1/vulnerability.proto
namespace Google\Cloud\OsConfig\V1\VulnerabilityReport\Vulnerability;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
* OS inventory item that is affected by a vulnerability or fixed as a
* result of a vulnerability.
*
* Generated from protobuf message <code>google.cloud.osconfig.v1.VulnerabilityReport.Vulnerability.Item</code>
*/
class Item extends \Google\Protobuf\Internal\Message
{
/**
* Corresponds to the `INSTALLED_PACKAGE` inventory item on the VM.
* This field displays the inventory items affected by this vulnerability.
* If the vulnerability report was not updated after the VM inventory
* update, these values might not display in VM inventory. For some
* operating systems, this field might be empty.
*
* Generated from protobuf field <code>string installed_inventory_item_id = 1;</code>
*/
private $installed_inventory_item_id = '';
/**
* Corresponds to the `AVAILABLE_PACKAGE` inventory item on the VM.
* If the vulnerability report was not updated after the VM inventory
* update, these values might not display in VM inventory. If there is no
* available fix, the field is empty. The `inventory_item` value specifies
* the latest `SoftwarePackage` available to the VM that fixes the
* vulnerability.
*
* Generated from protobuf field <code>string available_inventory_item_id = 2;</code>
*/
private $available_inventory_item_id = '';
/**
* The recommended [CPE URI](https://cpe.mitre.org/specification/) update
* that contains a fix for this vulnerability.
*
* Generated from protobuf field <code>string fixed_cpe_uri = 3;</code>
*/
private $fixed_cpe_uri = '';
/**
* The upstream OS patch, packages or KB that fixes the vulnerability.
*
* Generated from protobuf field <code>string upstream_fix = 4;</code>
*/
private $upstream_fix = '';
/**
* Constructor.
*
* @param array $data {
* Optional. Data for populating the Message object.
*
* @type string $installed_inventory_item_id
* Corresponds to the `INSTALLED_PACKAGE` inventory item on the VM.
* This field displays the inventory items affected by this vulnerability.
* If the vulnerability report was not updated after the VM inventory
* update, these values might not display in VM inventory. For some
* operating systems, this field might be empty.
* @type string $available_inventory_item_id
* Corresponds to the `AVAILABLE_PACKAGE` inventory item on the VM.
* If the vulnerability report was not updated after the VM inventory
* update, these values might not display in VM inventory. If there is no
* available fix, the field is empty. The `inventory_item` value specifies
* the latest `SoftwarePackage` available to the VM that fixes the
* vulnerability.
* @type string $fixed_cpe_uri
* The recommended [CPE URI](https://cpe.mitre.org/specification/) update
* that contains a fix for this vulnerability.
* @type string $upstream_fix
* The upstream OS patch, packages or KB that fixes the vulnerability.
* }
*/
public function __construct($data = NULL) {
\GPBMetadata\Google\Cloud\Osconfig\V1\Vulnerability::initOnce();
parent::__construct($data);
}
/**
* Corresponds to the `INSTALLED_PACKAGE` inventory item on the VM.
* This field displays the inventory items affected by this vulnerability.
* If the vulnerability report was not updated after the VM inventory
* update, these values might not display in VM inventory. For some
* operating systems, this field might be empty.
*
* Generated from protobuf field <code>string installed_inventory_item_id = 1;</code>
* @return string
*/
public function getInstalledInventoryItemId()
{
return $this->installed_inventory_item_id;
}
/**
* Corresponds to the `INSTALLED_PACKAGE` inventory item on the VM.
* This field displays the inventory items affected by this vulnerability.
* If the vulnerability report was not updated after the VM inventory
* update, these values might not display in VM inventory. For some
* operating systems, this field might be empty.
*
* Generated from protobuf field <code>string installed_inventory_item_id = 1;</code>
* @param string $var
* @return $this
*/
public function setInstalledInventoryItemId($var)
{
GPBUtil::checkString($var, True);
$this->installed_inventory_item_id = $var;
return $this;
}
/**
* Corresponds to the `AVAILABLE_PACKAGE` inventory item on the VM.
* If the vulnerability report was not updated after the VM inventory
* update, these values might not display in VM inventory. If there is no
* available fix, the field is empty. The `inventory_item` value specifies
* the latest `SoftwarePackage` available to the VM that fixes the
* vulnerability.
*
* Generated from protobuf field <code>string available_inventory_item_id = 2;</code>
* @return string
*/
public function getAvailableInventoryItemId()
{
return $this->available_inventory_item_id;
}
/**
* Corresponds to the `AVAILABLE_PACKAGE` inventory item on the VM.
* If the vulnerability report was not updated after the VM inventory
* update, these values might not display in VM inventory. If there is no
* available fix, the field is empty. The `inventory_item` value specifies
* the latest `SoftwarePackage` available to the VM that fixes the
* vulnerability.
*
* Generated from protobuf field <code>string available_inventory_item_id = 2;</code>
* @param string $var
* @return $this
*/
public function setAvailableInventoryItemId($var)
{
GPBUtil::checkString($var, True);
$this->available_inventory_item_id = $var;
return $this;
}
/**
* The recommended [CPE URI](https://cpe.mitre.org/specification/) update
* that contains a fix for this vulnerability.
*
* Generated from protobuf field <code>string fixed_cpe_uri = 3;</code>
* @return string
*/
public function getFixedCpeUri()
{
return $this->fixed_cpe_uri;
}
/**
* The recommended [CPE URI](https://cpe.mitre.org/specification/) update
* that contains a fix for this vulnerability.
*
* Generated from protobuf field <code>string fixed_cpe_uri = 3;</code>
* @param string $var
* @return $this
*/
public function setFixedCpeUri($var)
{
GPBUtil::checkString($var, True);
$this->fixed_cpe_uri = $var;
return $this;
}
/**
* The upstream OS patch, packages or KB that fixes the vulnerability.
*
* Generated from protobuf field <code>string upstream_fix = 4;</code>
* @return string
*/
public function getUpstreamFix()
{
return $this->upstream_fix;
}
/**
* The upstream OS patch, packages or KB that fixes the vulnerability.
*
* Generated from protobuf field <code>string upstream_fix = 4;</code>
* @param string $var
* @return $this
*/
public function setUpstreamFix($var)
{
GPBUtil::checkString($var, True);
$this->upstream_fix = $var;
return $this;
}
}
| apache-2.0 |
tst-ahernandez/earthenterprise | earth_enterprise/src/fusion/config/gefConfigUtil.cpp | 5241 | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "fusion/config/gefConfigUtil.h"
#include <cstdlib>
#include <algorithm>
#include "fusion/autoingest/.idl/Systemrc.h"
#include "fusion/autoingest/.idl/VolumeStorage.h"
#include "fusion/autoingest/geAssetRoot.h"
#include "common/khSpawn.h"
#include "common/khException.h"
#include "common/geUsers.h"
#include "common/khFileUtils.h"
#include "common/config/geConfigUtil.h"
#include "common/config/geCapabilities.h"
namespace {
const uint32 kMaxNumJobsDefault = 8;
uint32 GetDefaultMaxNumJobs() {
char* variable;
uint32 max_num_jobs = kMaxNumJobsDefault;
if ((variable = getenv("KH_GOOGLE_MAX_NUM_JOBS")) != NULL) {
char *endptr = NULL;
const uint32 value = static_cast<uint32>(
std::strtoul(variable, &endptr, 0));
if (endptr != variable) {
max_num_jobs = value;
}
}
return max_num_jobs;
}
} // namespace
// ****************************************************************************
// *** ValidateHostReadyForConfig
// ****************************************************************************
bool IsFusionRunning(void) {
return (geCheckPidFile("gesystemmanager") ||
geCheckPidFile("geresourceprovider"));
}
namespace {
void AssertFusionNotRunning(void) {
if (IsFusionRunning()) {
throw khException(kh::tr("Please stop fusion before proceeding.\n"
"(e.g. /etc/init.d/gefusion stop)"));
}
}
}
std::string ValidateHostReadyForConfig(void) {
AssertRunningAsRoot();
AssertFusionNotRunning();
return GetAndValidateHostname();
}
void LoadSystemrc(Systemrc &systemrc) {
static Systemrc cached_systemrc;
static bool use_cached = false;
if (use_cached) {
systemrc = cached_systemrc;
return;
}
if (khExists(Systemrc::Filename())) {
use_cached = true;
// load into a tmp to avoid a partial load on an earlier file
// affecting the defaults for this load
Systemrc tmp;
if (tmp.Load()) {
uint32 max_num_jobs = GetMaxNumJobs();
// If uninitialized or greater than maximum allowable number of
// concurrent jobs, the maxjobs defaults to the min of the values:
// maximum allowable number of concurrent jobs or limit on max number
// of jobs.
if (tmp.maxjobs == 0 || tmp.maxjobs > max_num_jobs) {
tmp.maxjobs = std::min(max_num_jobs, kMaxNumJobsLimit);
}
systemrc = cached_systemrc = tmp;
}
} else {
throw khException(kh::tr("'%1' is missing").arg(Systemrc::Filename()));
}
}
std::string CommandlineAssetRootDefault(void) {
Systemrc systemrc;
LoadSystemrc(systemrc);
return systemrc.assetroot;
}
uint32 CommandlineNumCPUsDefault(void) {
Systemrc systemrc;
LoadSystemrc(systemrc);
return systemrc.maxjobs;
}
// ****************************************************************************
// *** Volume routines
// ****************************************************************************
void LoadVolumesOrThrow(const std::string &assetroot, VolumeDefList &volumes) {
std::string volumefname =
geAssetRoot::Filename(assetroot, geAssetRoot::VolumeFile);
if (!khExists(volumefname) || !volumes.Load(volumefname)) {
throw khException(kh::tr("Unable to load volumes for %1")
.arg(assetroot));
}
}
void SaveVolumesOrThrow(const std::string &assetroot,
const VolumeDefList &volumes) {
std::string volumefname =
geAssetRoot::Filename(assetroot, geAssetRoot::VolumeFile);
if (!volumes.Save(volumefname)) {
throw khException(kh::tr("Unable to save volumes for %1")
.arg(assetroot));
}
(void)khChmod(volumefname, geAssetRoot::FilePerms(geAssetRoot::VolumeFile));
}
void SwitchToUser(const std::string username,
const std::string group_name) {
geUserId ge_user(username, group_name);
ge_user.SwitchEffectiveToThis();
}
uint32 GetMaxNumJobs() {
uint32 max_num_jobs = 0;
// Get maximum allowable number of concurrent jobs.
// Note: KH_MAX_NUM_JOBS_COEFF can be used to build GEE Fusion licensing
// KH_MAX_NUM_JOBS_COEFF*kMaxNumJobsDefault (8/16/24..) concurrent jobs.
#ifdef KH_MAX_NUM_JOBS_COEFF
max_num_jobs = kMaxNumJobsDefault *
static_cast<uint32>(KH_MAX_NUM_JOBS_COEFF);
#endif
// Note: Apply an internal multiplier in case of GEE Fusion is built
// with maximum number of concurrent jobs equals 0 (internal usage).
if (max_num_jobs == 0) {
max_num_jobs = GetDefaultMaxNumJobs();
}
// Set the max_num_jobs to the min of the values: number of CPUs or max
// allowable number of jobs.
max_num_jobs = std::min(max_num_jobs, GetNumCPUs());
return max_num_jobs;
}
| apache-2.0 |
SiddharthChatrolaMs/azure-sdk-for-net | src/SDKs/DataFactory/Management.DataFactory/Generated/Models/SparkLinkedService.cs | 10901 | // <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.DataFactory.Models
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Spark Server linked service.
/// </summary>
[Newtonsoft.Json.JsonObject("Spark")]
[Rest.Serialization.JsonTransformation]
public partial class SparkLinkedService : LinkedService
{
/// <summary>
/// Initializes a new instance of the SparkLinkedService class.
/// </summary>
public SparkLinkedService()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the SparkLinkedService class.
/// </summary>
/// <param name="host">IP address or host name of the Spark
/// server</param>
/// <param name="port">The TCP port that the Spark server uses to
/// listen for client connections.</param>
/// <param name="authenticationType">The authentication method used to
/// access the Spark server. Possible values include: 'Anonymous',
/// 'Username', 'UsernameAndPassword',
/// 'WindowsAzureHDInsightService'</param>
/// <param name="additionalProperties">Unmatched properties from the
/// message are deserialized this collection</param>
/// <param name="connectVia">The integration runtime reference.</param>
/// <param name="description">Linked service description.</param>
/// <param name="serverType">The type of Spark server. Possible values
/// include: 'SharkServer', 'SharkServer2', 'SparkThriftServer'</param>
/// <param name="thriftTransportProtocol">The transport protocol to use
/// in the Thrift layer. Possible values include: 'Binary', 'SASL',
/// 'HTTP '</param>
/// <param name="username">The user name that you use to access Spark
/// Server.</param>
/// <param name="password">The password corresponding to the user name
/// that you provided in the Username field</param>
/// <param name="httpPath">The partial URL corresponding to the Spark
/// server.</param>
/// <param name="enableSsl">Specifies whether the connections to the
/// server are encrypted using SSL. The default value is false.</param>
/// <param name="trustedCertPath">The full path of the .pem file
/// containing trusted CA certificates for verifying the server when
/// connecting over SSL. This property can only be set when using SSL
/// on self-hosted IR. The default value is the cacerts.pem file
/// installed with the IR.</param>
/// <param name="useSystemTrustStore">Specifies whether to use a CA
/// certificate from the system trust store or from a specified PEM
/// file. The default value is false.</param>
/// <param name="allowHostNameCNMismatch">Specifies whether to require
/// a CA-issued SSL certificate name to match the host name of the
/// server when connecting over SSL. The default value is
/// false.</param>
/// <param name="allowSelfSignedServerCert">Specifies whether to allow
/// self-signed certificates from the server. The default value is
/// false.</param>
/// <param name="encryptedCredential">The encrypted credential used for
/// authentication. Credentials are encrypted using the integration
/// runtime credential manager. Type: string (or Expression with
/// resultType string).</param>
public SparkLinkedService(object host, object port, string authenticationType, IDictionary<string, object> additionalProperties = default(IDictionary<string, object>), IntegrationRuntimeReference connectVia = default(IntegrationRuntimeReference), string description = default(string), string serverType = default(string), string thriftTransportProtocol = default(string), object username = default(object), SecretBase password = default(SecretBase), object httpPath = default(object), object enableSsl = default(object), object trustedCertPath = default(object), object useSystemTrustStore = default(object), object allowHostNameCNMismatch = default(object), object allowSelfSignedServerCert = default(object), object encryptedCredential = default(object))
: base(additionalProperties, connectVia, description)
{
Host = host;
Port = port;
ServerType = serverType;
ThriftTransportProtocol = thriftTransportProtocol;
AuthenticationType = authenticationType;
Username = username;
Password = password;
HttpPath = httpPath;
EnableSsl = enableSsl;
TrustedCertPath = trustedCertPath;
UseSystemTrustStore = useSystemTrustStore;
AllowHostNameCNMismatch = allowHostNameCNMismatch;
AllowSelfSignedServerCert = allowSelfSignedServerCert;
EncryptedCredential = encryptedCredential;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets IP address or host name of the Spark server
/// </summary>
[JsonProperty(PropertyName = "typeProperties.host")]
public object Host { get; set; }
/// <summary>
/// Gets or sets the TCP port that the Spark server uses to listen for
/// client connections.
/// </summary>
[JsonProperty(PropertyName = "typeProperties.port")]
public object Port { get; set; }
/// <summary>
/// Gets or sets the type of Spark server. Possible values include:
/// 'SharkServer', 'SharkServer2', 'SparkThriftServer'
/// </summary>
[JsonProperty(PropertyName = "typeProperties.serverType")]
public string ServerType { get; set; }
/// <summary>
/// Gets or sets the transport protocol to use in the Thrift layer.
/// Possible values include: 'Binary', 'SASL', 'HTTP '
/// </summary>
[JsonProperty(PropertyName = "typeProperties.thriftTransportProtocol")]
public string ThriftTransportProtocol { get; set; }
/// <summary>
/// Gets or sets the authentication method used to access the Spark
/// server. Possible values include: 'Anonymous', 'Username',
/// 'UsernameAndPassword', 'WindowsAzureHDInsightService'
/// </summary>
[JsonProperty(PropertyName = "typeProperties.authenticationType")]
public string AuthenticationType { get; set; }
/// <summary>
/// Gets or sets the user name that you use to access Spark Server.
/// </summary>
[JsonProperty(PropertyName = "typeProperties.username")]
public object Username { get; set; }
/// <summary>
/// Gets or sets the password corresponding to the user name that you
/// provided in the Username field
/// </summary>
[JsonProperty(PropertyName = "typeProperties.password")]
public SecretBase Password { get; set; }
/// <summary>
/// Gets or sets the partial URL corresponding to the Spark server.
/// </summary>
[JsonProperty(PropertyName = "typeProperties.httpPath")]
public object HttpPath { get; set; }
/// <summary>
/// Gets or sets specifies whether the connections to the server are
/// encrypted using SSL. The default value is false.
/// </summary>
[JsonProperty(PropertyName = "typeProperties.enableSsl")]
public object EnableSsl { get; set; }
/// <summary>
/// Gets or sets the full path of the .pem file containing trusted CA
/// certificates for verifying the server when connecting over SSL.
/// This property can only be set when using SSL on self-hosted IR. The
/// default value is the cacerts.pem file installed with the IR.
/// </summary>
[JsonProperty(PropertyName = "typeProperties.trustedCertPath")]
public object TrustedCertPath { get; set; }
/// <summary>
/// Gets or sets specifies whether to use a CA certificate from the
/// system trust store or from a specified PEM file. The default value
/// is false.
/// </summary>
[JsonProperty(PropertyName = "typeProperties.useSystemTrustStore")]
public object UseSystemTrustStore { get; set; }
/// <summary>
/// Gets or sets specifies whether to require a CA-issued SSL
/// certificate name to match the host name of the server when
/// connecting over SSL. The default value is false.
/// </summary>
[JsonProperty(PropertyName = "typeProperties.allowHostNameCNMismatch")]
public object AllowHostNameCNMismatch { get; set; }
/// <summary>
/// Gets or sets specifies whether to allow self-signed certificates
/// from the server. The default value is false.
/// </summary>
[JsonProperty(PropertyName = "typeProperties.allowSelfSignedServerCert")]
public object AllowSelfSignedServerCert { get; set; }
/// <summary>
/// Gets or sets the encrypted credential used for authentication.
/// Credentials are encrypted using the integration runtime credential
/// manager. Type: string (or Expression with resultType string).
/// </summary>
[JsonProperty(PropertyName = "typeProperties.encryptedCredential")]
public object EncryptedCredential { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public override void Validate()
{
base.Validate();
if (Host == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Host");
}
if (Port == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Port");
}
if (AuthenticationType == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "AuthenticationType");
}
}
}
}
| apache-2.0 |
mdanielwork/intellij-community | platform/platform-tests/testSrc/com/intellij/psi/search/GlobalSearchScopeTest.java | 7120 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.search;
import com.intellij.openapi.fileTypes.PlainTextLanguage;
import com.intellij.openapi.roots.ModuleRootModificationUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.testFramework.PlatformTestCase;
import com.intellij.testFramework.PsiTestUtil;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
public class GlobalSearchScopeTest extends PlatformTestCase {
public void testUniteDirectorySearchScopeDoesNotSOE() throws Exception {
VirtualFile genRoot = getVirtualFile(createTempDir("genSrcRoot"));
VirtualFile srcRoot = getVirtualFile(createTempDir("srcRoot"));
VirtualFile child = createChildDirectory(srcRoot, "child");
GlobalSearchScope childScope = GlobalSearchScopesCore.directoryScope(getProject(), child, true);
GlobalSearchScope directoryScope = GlobalSearchScopesCore.directoryScope(getProject(), srcRoot, true);
GlobalSearchScope scope = GlobalSearchScope.EMPTY_SCOPE.uniteWith(directoryScope);
assertSame(scope, directoryScope);
scope = scope.uniteWith(directoryScope);
assertSame(scope, directoryScope);
scope = scope.uniteWith(childScope);
assertSame(scope, directoryScope);
GlobalSearchScope s = childScope;
int N = 1000;
VirtualFile[] d = new VirtualFile[N];
for (int i=0; i< N;i++) {
d[i] = createChildDirectory(srcRoot, "d"+i);
GlobalSearchScope united = s.uniteWith(GlobalSearchScopesCore.directoryScope(getProject(), d[i], true));
assertNotSame(s, united);
s = united;
assertTrue(s instanceof GlobalSearchScopesCore.DirectoriesScope);
}
for (VirtualFile file : d) {
VirtualFile f = createChildData(file, "f");
assertTrue(s.contains(f));
}
assertFalse(s.contains(genRoot));
assertSame(s.uniteWith(childScope), s);
assertSame(s.uniteWith(s), s);
}
public void testNotScope() {
VirtualFile moduleRoot = getTempDir().createTempVDir();
ModuleRootModificationUtil.addContentRoot(getModule(), moduleRoot.getPath());
GlobalSearchScope projectScope = GlobalSearchScope.projectScope(getProject());
assertFalse(projectScope.isSearchInLibraries());
assertTrue(projectScope.isSearchInModuleContent(getModule()));
assertTrue(projectScope.contains(moduleRoot));
GlobalSearchScope notProjectScope = GlobalSearchScope.notScope(projectScope);
assertTrue(notProjectScope.isSearchInLibraries());
assertFalse(notProjectScope.contains(moduleRoot));
GlobalSearchScope allScope = GlobalSearchScope.allScope(getProject());
assertTrue(allScope.isSearchInLibraries());
assertTrue(allScope.contains(moduleRoot));
GlobalSearchScope notAllScope = GlobalSearchScope.notScope(allScope);
assertFalse(notAllScope.contains(moduleRoot));
}
public void testIntersectionPreservesOrderInCaseClientsWantToPutCheaperChecksFirst() throws IOException {
AtomicInteger targetCalled = new AtomicInteger();
GlobalSearchScope alwaysTrue = new DelegatingGlobalSearchScope(new EverythingGlobalScope()) {
@Override
public boolean contains(@NotNull VirtualFile file) {
return true;
}
};
GlobalSearchScope target = new DelegatingGlobalSearchScope(new EverythingGlobalScope()) {
@Override
public boolean contains(@NotNull VirtualFile file) {
targetCalled.incrementAndGet();
return true;
}
};
GlobalSearchScope trueIntersection = target.intersectWith(alwaysTrue);
VirtualFile file1 = getVirtualFile(createTempFile("file1", ""));
VirtualFile file2 = getVirtualFile(createTempFile("file2", ""));
assertTrue(trueIntersection.contains(file2));
assertEquals(1, targetCalled.get());
assertFalse(GlobalSearchScope.fileScope(myProject, file1).intersectWith(trueIntersection).contains(file2));
assertEquals(1, targetCalled.get());
}
public void testDirScopeSearchInLibraries() throws IOException {
VirtualFile libRoot = getVirtualFile(createTempDir("libRoot"));
VirtualFile contentRoot = getVirtualFile(createTempDir("contentRoot"));
PsiTestUtil.removeAllRoots(getModule(), null);
PsiTestUtil.addContentRoot(getModule(), contentRoot);
PsiTestUtil.addLibrary(getModule(), libRoot.getPath());
assertTrue(GlobalSearchScopesCore.directoryScope(myProject, libRoot, true).isSearchInLibraries());
assertTrue(GlobalSearchScopesCore.directoriesScope(myProject, true, libRoot, contentRoot).isSearchInLibraries());
}
public void testUnionWithEmptyScopeMustNotAffectCompare() {
VirtualFile moduleRoot = getTempDir().createTempVDir();
assertNotNull(moduleRoot);
PsiTestUtil.addSourceRoot(getModule(), moduleRoot);
VirtualFile moduleRoot2 = getTempDir().createTempVDir();
assertNotNull(moduleRoot2);
PsiTestUtil.addSourceRoot(getModule(), moduleRoot2);
GlobalSearchScope modScope = getModule().getModuleContentScope();
int compare = modScope.compare(moduleRoot, moduleRoot2);
assertTrue(compare != 0);
GlobalSearchScope union = modScope.uniteWith(GlobalSearchScope.EMPTY_SCOPE);
int compare2 = union.compare(moduleRoot, moduleRoot2);
assertEquals(compare, compare2);
assertEquals(modScope.compare(moduleRoot2, moduleRoot), union.compare(moduleRoot2, moduleRoot));
}
public void testIsInScopeDoesNotAcceptRandomNonPhysicalFilesByDefault() {
PsiFile file = PsiFileFactory.getInstance(myProject).createFileFromText(PlainTextLanguage.INSTANCE, "");
VirtualFile vFile = file.getViewProvider().getVirtualFile();
assertFalse(GlobalSearchScope.allScope(myProject).contains(vFile));
assertFalse(PsiSearchScopeUtil.isInScope(GlobalSearchScope.allScope(myProject), file));
assertTrue(file.getResolveScope().contains(vFile));
assertTrue(PsiSearchScopeUtil.isInScope(file.getResolveScope(), file));
}
public void testUnionWithEmptyAndUnion() {
GlobalSearchScope scope = GlobalSearchScope.EMPTY_SCOPE.uniteWith(GlobalSearchScope.EMPTY_SCOPE);
assertEquals(GlobalSearchScope.EMPTY_SCOPE, scope);
GlobalSearchScope scope2 = GlobalSearchScope.union(new GlobalSearchScope[]{GlobalSearchScope.EMPTY_SCOPE, GlobalSearchScope.EMPTY_SCOPE});
assertEquals(GlobalSearchScope.EMPTY_SCOPE, scope2);
GlobalSearchScope p = GlobalSearchScope.projectScope(getProject());
GlobalSearchScope scope3 = GlobalSearchScope.union(new GlobalSearchScope[]{GlobalSearchScope.EMPTY_SCOPE, p, GlobalSearchScope.EMPTY_SCOPE});
assertEquals(p, scope3);
GlobalSearchScope m = GlobalSearchScope.moduleScope(getModule());
GlobalSearchScope pm = m.uniteWith(p);
Assert.assertNotEquals(m, pm);
GlobalSearchScope scope4 = GlobalSearchScope.union(new GlobalSearchScope[]{GlobalSearchScope.EMPTY_SCOPE, p, GlobalSearchScope.EMPTY_SCOPE, pm, m});
assertEquals(pm, scope4);
}
} | apache-2.0 |
ty-po/code-dot-org | i18n/locales/et-EE/hourofcode/whole-school.md | 136 | * * *
layout: wide
* * *
# Kutsu oma terve kool osalema
Teave selle kohta, kuidas terve kool saaks osaleda Koodi Tunnil, tuleb siia. | apache-2.0 |
gingerwizard/elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/IndexLifecycleFeatureSetUsageTests.java | 2384 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.core.ilm;
import org.elasticsearch.common.io.stream.Writeable.Reader;
import org.elasticsearch.test.AbstractWireSerializingTestCase;
import org.elasticsearch.xpack.core.ilm.IndexLifecycleFeatureSetUsage.PolicyStats;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class IndexLifecycleFeatureSetUsageTests extends AbstractWireSerializingTestCase<IndexLifecycleFeatureSetUsage> {
@Override
protected IndexLifecycleFeatureSetUsage createTestInstance() {
boolean enabled = randomBoolean();
boolean available = randomBoolean();
List<PolicyStats> policyStats = null;
if (enabled) {
int size = randomIntBetween(0, 10);
policyStats = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
policyStats.add(PolicyStatsTests.createRandomInstance());
}
}
return new IndexLifecycleFeatureSetUsage(available, policyStats);
}
@Override
protected IndexLifecycleFeatureSetUsage mutateInstance(IndexLifecycleFeatureSetUsage instance) throws IOException {
boolean available = instance.available();
List<PolicyStats> policyStats = instance.getPolicyStats();
switch (between(0, 1)) {
case 0:
available = available == false;
break;
case 1:
if (policyStats == null) {
policyStats = new ArrayList<>();
policyStats.add(PolicyStatsTests.createRandomInstance());
} else if (randomBoolean()) {
policyStats = null;
} else {
policyStats = new ArrayList<>(policyStats);
policyStats.add(PolicyStatsTests.createRandomInstance());
}
break;
default:
throw new AssertionError("Illegal randomisation branch");
}
return new IndexLifecycleFeatureSetUsage(available, policyStats);
}
@Override
protected Reader<IndexLifecycleFeatureSetUsage> instanceReader() {
return IndexLifecycleFeatureSetUsage::new;
}
}
| apache-2.0 |
alexzaitzev/ignite | modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/pagemem/PagesWriteSpeedBasedThrottle.java | 19621 | /*
* 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.ignite.internal.processors.cache.persistence.pagemem;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.LockSupport;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.internal.processors.cache.persistence.CheckpointLockStateChecker;
import org.apache.ignite.internal.processors.cache.persistence.CheckpointWriteProgressSupplier;
import org.apache.ignite.internal.util.GridConcurrentHashSet;
import org.apache.ignite.internal.util.typedef.internal.U;
/**
* Throttles threads that generate dirty pages during ongoing checkpoint.
* Designed to avoid zero dropdowns that can happen if checkpoint buffer is overflowed.
* Uses average checkpoint write speed and moment speed of marking pages as dirty.
*/
public class PagesWriteSpeedBasedThrottle implements PagesWriteThrottlePolicy {
/** Maximum dirty pages in region. */
private static final double MAX_DIRTY_PAGES = 0.75;
/** Page memory. */
private final PageMemoryImpl pageMemory;
/** Database manager. */
private final CheckpointWriteProgressSupplier cpProgress;
/** Starting throttle time. Limits write speed to 1000 MB/s. */
private static final long STARTING_THROTTLE_NANOS = 4000;
/** Backoff ratio. Each next park will be this times longer. */
private static final double BACKOFF_RATIO = 1.05;
/** Percent of dirty pages which will not cause throttling. */
private static final double MIN_RATIO_NO_THROTTLE = 0.03;
/** Exponential backoff counter. */
private final AtomicInteger exponentialBackoffCntr = new AtomicInteger(0);
/** Counter of written pages from checkpoint. Value is saved here for detecting checkpoint start. */
private final AtomicInteger lastObservedWritten = new AtomicInteger(0);
/**
* Dirty pages ratio was observed at checkpoint start (here start is moment when first page was actually saved to
* store). This ratio is excluded from throttling.
*/
private volatile double initDirtyRatioAtCpBegin = MIN_RATIO_NO_THROTTLE;
/**
* Target (maximum) dirty pages ratio, after which throttling will start using
* {@link #getParkTime(double, long, int, int, long, long)}.
*/
private volatile double targetDirtyRatio;
/**
* Current dirty pages ratio (percent of dirty pages in most used segment), negative value means no cp is running.
*/
private volatile double currDirtyRatio;
/** Speed average checkpoint write speed. Current and 3 past checkpoints used. Pages/second. */
private final IntervalBasedMeasurement speedCpWrite = new IntervalBasedMeasurement();
/** Last estimated speed for marking all clear pages as dirty till the end of checkpoint. */
private volatile long speedForMarkAll;
/** Threads set. Contains identifiers of all threads which were marking pages for current checkpoint. */
private final GridConcurrentHashSet<Long> threadIds = new GridConcurrentHashSet<>();
/**
* Used for calculating speed of marking pages dirty.
* Value from past 750-1000 millis only.
* {@link IntervalBasedMeasurement#getSpeedOpsPerSec(long)} returns pages marked/second.
* {@link IntervalBasedMeasurement#getAverage()} returns average throttle time.
* */
private final IntervalBasedMeasurement speedMarkAndAvgParkTime = new IntervalBasedMeasurement(250, 3);
/** Total pages which is possible to store in page memory. */
private long totalPages;
/** Checkpoint lock state provider. */
private CheckpointLockStateChecker cpLockStateChecker;
/** Logger. */
private IgniteLogger log;
/** Previous warning time, nanos. */
private AtomicLong prevWarnTime = new AtomicLong();
/** Warning min delay nanoseconds. */
private static final long WARN_MIN_DELAY_NS = TimeUnit.SECONDS.toNanos(10);
/** Warning threshold: minimal level of pressure that causes warning messages to log. */
static final double WARN_THRESHOLD = 0.2;
/**
* @param pageMemory Page memory.
* @param cpProgress Database manager.
* @param stateChecker Checkpoint lock state provider.
* @param log Logger.
*/
public PagesWriteSpeedBasedThrottle(
PageMemoryImpl pageMemory,
CheckpointWriteProgressSupplier cpProgress,
CheckpointLockStateChecker stateChecker,
IgniteLogger log
) {
this.pageMemory = pageMemory;
this.cpProgress = cpProgress;
totalPages = pageMemory.totalPages();
this.cpLockStateChecker = stateChecker;
this.log = log;
}
/** {@inheritDoc} */
@Override public void onMarkDirty(boolean isPageInCheckpoint) {
assert cpLockStateChecker.checkpointLockIsHeldByThread();
AtomicInteger writtenPagesCntr = cpProgress.writtenPagesCounter();
if (writtenPagesCntr == null) {
speedForMarkAll = 0;
targetDirtyRatio = -1;
currDirtyRatio = -1;
return; // Don't throttle if checkpoint is not running.
}
int cpWrittenPages = writtenPagesCntr.get();
long fullyCompletedPages = (cpWrittenPages + cpSyncedPages()) / 2; // written & sync'ed
long curNanoTime = System.nanoTime();
speedCpWrite.setCounter(fullyCompletedPages, curNanoTime);
long markDirtySpeed = speedMarkAndAvgParkTime.getSpeedOpsPerSec(curNanoTime);
long curCpWriteSpeed = speedCpWrite.getSpeedOpsPerSec(curNanoTime);
threadIds.add(Thread.currentThread().getId());
ThrottleMode level = ThrottleMode.NO; //should apply delay (throttling) for current page modification
if (isPageInCheckpoint) {
int checkpointBufLimit = pageMemory.checkpointBufferPagesSize() * 2 / 3;
if (pageMemory.checkpointBufferPagesCount() > checkpointBufLimit)
level = ThrottleMode.EXPONENTIAL;
}
long throttleParkTimeNs = 0;
if (level == ThrottleMode.NO) {
int nThreads = threadIds.size();
int cpTotalPages = cpTotalPages();
if (cpTotalPages == 0) {
boolean throttleByCpSpeed = curCpWriteSpeed > 0 && markDirtySpeed > curCpWriteSpeed;
if (throttleByCpSpeed) {
throttleParkTimeNs = calcDelayTime(curCpWriteSpeed, nThreads, 1);
level = ThrottleMode.LIMITED;
}
}
else {
double dirtyPagesRatio = pageMemory.getDirtyPagesRatio();
currDirtyRatio = dirtyPagesRatio;
detectCpPagesWriteStart(cpWrittenPages, dirtyPagesRatio);
if (dirtyPagesRatio >= MAX_DIRTY_PAGES)
level = ThrottleMode.NO; // too late to throttle, will wait on safe to update instead.
else {
int notEvictedPagesTotal = cpTotalPages - cpEvictedPages();
throttleParkTimeNs = getParkTime(dirtyPagesRatio,
fullyCompletedPages,
notEvictedPagesTotal < 0 ? 0 : notEvictedPagesTotal,
nThreads,
markDirtySpeed,
curCpWriteSpeed);
level = throttleParkTimeNs == 0 ? ThrottleMode.NO : ThrottleMode.LIMITED;
}
}
}
if (level == ThrottleMode.EXPONENTIAL) {
int exponent = exponentialBackoffCntr.getAndIncrement();
throttleParkTimeNs = (long)(STARTING_THROTTLE_NANOS * Math.pow(BACKOFF_RATIO, exponent));
}
else {
if (isPageInCheckpoint)
exponentialBackoffCntr.set(0);
if (level == ThrottleMode.NO)
throttleParkTimeNs = 0;
}
if (throttleParkTimeNs > 0) {
recurrentLogIfNeed();
doPark(throttleParkTimeNs);
}
speedMarkAndAvgParkTime.addMeasurementForAverageCalculation(throttleParkTimeNs);
}
/**
* Disables the current thread for thread scheduling purposes. May be overriden by subclasses for tests
*
* @param throttleParkTimeNs the maximum number of nanoseconds to wait
*/
protected void doPark(long throttleParkTimeNs) {
if (throttleParkTimeNs > LOGGING_THRESHOLD) {
U.warn(log, "Parking thread=" + Thread.currentThread().getName()
+ " for timeout(ms)=" + (throttleParkTimeNs / 1_000_000));
}
LockSupport.parkNanos(throttleParkTimeNs);
}
/**
* @return number of written pages.
*/
private int cpWrittenPages() {
AtomicInteger writtenPagesCntr = cpProgress.writtenPagesCounter();
return writtenPagesCntr == null ? 0 : writtenPagesCntr.get();
}
/**
* @return Number of pages in current checkpoint.
*/
private int cpTotalPages() {
return cpProgress.currentCheckpointPagesCount();
}
/**
* @return Counter for fsynced checkpoint pages.
*/
private int cpSyncedPages() {
AtomicInteger syncedPagesCntr = cpProgress.syncedPagesCounter();
return syncedPagesCntr == null ? 0 : syncedPagesCntr.get();
}
/**
* @return number of evicted pages.
*/
private int cpEvictedPages() {
AtomicInteger evictedPagesCntr = cpProgress.evictedPagesCntr();
return evictedPagesCntr == null ? 0 : evictedPagesCntr.get();
}
/**
* Prints warning to log if throttling is occurred and requires markable amount of time.
*/
private void recurrentLogIfNeed() {
long prevWarningNs = prevWarnTime.get();
long curNs = System.nanoTime();
if (prevWarningNs != 0 && (curNs - prevWarningNs) <= WARN_MIN_DELAY_NS)
return;
double weight = throttleWeight();
if (weight <= WARN_THRESHOLD)
return;
if (prevWarnTime.compareAndSet(prevWarningNs, curNs)) {
String msg = String.format("Throttling is applied to page modifications " +
"[percentOfPartTime=%.2f, markDirty=%d pages/sec, checkpointWrite=%d pages/sec, " +
"estIdealMarkDirty=%d pages/sec, curDirty=%.2f, maxDirty=%.2f, avgParkTime=%d ns, " +
"pages: (total=%d, evicted=%d, written=%d, synced=%d, cpBufUsed=%d, cpBufTotal=%d)]",
weight, getMarkDirtySpeed(), getCpWriteSpeed(),
getLastEstimatedSpeedForMarkAll(), getCurrDirtyRatio(), getTargetDirtyRatio(), throttleParkTime(),
cpTotalPages(), cpEvictedPages(), cpWrittenPages(), cpSyncedPages(),
pageMemory.checkpointBufferPagesCount(), pageMemory.checkpointBufferPagesSize());
log.info(msg);
}
}
/**
* @param dirtyPagesRatio actual percent of dirty pages.
* @param fullyCompletedPages written & fsynced pages count.
* @param cpTotalPages total checkpoint scope.
* @param nThreads number of threads providing data during current checkpoint.
* @param markDirtySpeed registered mark dirty speed, pages/sec.
* @param curCpWriteSpeed average checkpoint write speed, pages/sec.
* @return time in nanoseconds to part or 0 if throttling is not required.
*/
long getParkTime(
double dirtyPagesRatio,
long fullyCompletedPages,
int cpTotalPages,
int nThreads,
long markDirtySpeed,
long curCpWriteSpeed) {
long speedForMarkAll = calcSpeedToMarkAllSpaceTillEndOfCp(dirtyPagesRatio,
fullyCompletedPages,
curCpWriteSpeed,
cpTotalPages);
double targetDirtyRatio = calcTargetDirtyRatio(fullyCompletedPages, cpTotalPages);
this.speedForMarkAll = speedForMarkAll; //publish for metrics
this.targetDirtyRatio = targetDirtyRatio; //publish for metrics
boolean lowSpaceLeft = dirtyPagesRatio > targetDirtyRatio && (dirtyPagesRatio + 0.05 > MAX_DIRTY_PAGES);
int slowdown = lowSpaceLeft ? 3 : 1;
double multiplierForSpeedForMarkAll = lowSpaceLeft
? 0.8
: 1.0;
boolean markingTooFast = speedForMarkAll > 0 && markDirtySpeed > multiplierForSpeedForMarkAll * speedForMarkAll;
boolean throttleBySizeAndMarkSpeed = dirtyPagesRatio > targetDirtyRatio && markingTooFast;
//for case of speedForMarkAll >> markDirtySpeed, allow write little bit faster than CP average
double allowWriteFasterThanCp = (speedForMarkAll > 0 && markDirtySpeed > 0 && speedForMarkAll > markDirtySpeed)
? (0.1 * speedForMarkAll / markDirtySpeed)
: (dirtyPagesRatio > targetDirtyRatio ? 0.0 : 0.1);
double fasterThanCpWriteSpeed = lowSpaceLeft
? 1.0
: 1.0 + allowWriteFasterThanCp;
boolean throttleByCpSpeed = curCpWriteSpeed > 0 && markDirtySpeed > (fasterThanCpWriteSpeed * curCpWriteSpeed);
long delayByCpWrite = throttleByCpSpeed ? calcDelayTime(curCpWriteSpeed, nThreads, slowdown) : 0;
long delayByMarkAllWrite = throttleBySizeAndMarkSpeed ? calcDelayTime(speedForMarkAll, nThreads, slowdown) : 0;
return Math.max(delayByCpWrite, delayByMarkAllWrite);
}
/**
* @param dirtyPagesRatio current percent of dirty pages.
* @param fullyCompletedPages count of written and sync'ed pages
* @param curCpWriteSpeed pages/second checkpoint write speed. 0 speed means 'no data'.
* @param cpTotalPages total pages in checkpoint.
* @return pages/second to mark to mark all clean pages as dirty till the end of checkpoint. 0 speed means 'no
* data'.
*/
private long calcSpeedToMarkAllSpaceTillEndOfCp(double dirtyPagesRatio,
long fullyCompletedPages,
long curCpWriteSpeed,
int cpTotalPages) {
if (curCpWriteSpeed == 0)
return 0;
if (cpTotalPages <= 0)
return 0;
if (dirtyPagesRatio >= MAX_DIRTY_PAGES)
return 0;
double remainedClear = (MAX_DIRTY_PAGES - dirtyPagesRatio) * totalPages;
double timeRemainedSeconds = 1.0 * (cpTotalPages - fullyCompletedPages) / curCpWriteSpeed;
return (long)(remainedClear / timeRemainedSeconds);
}
/**
* @param fullyCompletedPages number of completed.
* @param cpTotalPages Total amount of pages under checkpoint.
* @return size-based calculation of target ratio.
*/
private double calcTargetDirtyRatio(long fullyCompletedPages, int cpTotalPages) {
double cpProgress = ((double)fullyCompletedPages) / cpTotalPages;
// Starting with initialDirtyRatioAtCpBegin to avoid throttle right after checkpoint start
double constStart = initDirtyRatioAtCpBegin;
double throttleTotalWeight = 1.0 - constStart;
// .75 is maximum ratio of dirty pages
return (cpProgress * throttleTotalWeight + constStart) * MAX_DIRTY_PAGES;
}
/**
* @param baseSpeed speed to slow down.
* @param nThreads operating threads.
* @param coefficient how much it is needed to slowdown base speed. 1.0 means delay to get exact base speed.
* @return sleep time in nanoseconds.
*/
private long calcDelayTime(long baseSpeed, int nThreads, double coefficient) {
if (coefficient <= 0.0)
return 0;
if (baseSpeed <= 0)
return 0;
long updTimeNsForOnePage = TimeUnit.SECONDS.toNanos(1) * nThreads / (baseSpeed);
return (long)(coefficient * updTimeNsForOnePage);
}
/**
* @param cpWrittenPages current counter of written pages.
* @param dirtyPagesRatio current percent of dirty pages.
*/
private void detectCpPagesWriteStart(int cpWrittenPages, double dirtyPagesRatio) {
if (cpWrittenPages > 0 && lastObservedWritten.compareAndSet(0, cpWrittenPages)) {
double newMinRatio = dirtyPagesRatio;
if (newMinRatio < MIN_RATIO_NO_THROTTLE)
newMinRatio = MIN_RATIO_NO_THROTTLE;
if (newMinRatio > 1)
newMinRatio = 1;
//for slow cp is completed now, drop previous dirty page percent
initDirtyRatioAtCpBegin = newMinRatio;
}
}
/** {@inheritDoc} */
@Override public void onBeginCheckpoint() {
speedCpWrite.setCounter(0L, System.nanoTime());
initDirtyRatioAtCpBegin = MIN_RATIO_NO_THROTTLE;
lastObservedWritten.set(0);
}
/** {@inheritDoc} */
@Override public void onFinishCheckpoint() {
exponentialBackoffCntr.set(0);
speedCpWrite.finishInterval();
speedMarkAndAvgParkTime.finishInterval();
threadIds.clear();
}
/**
* @return Exponential backoff counter.
*/
public long throttleParkTime() {
return speedMarkAndAvgParkTime.getAverage();
}
/**
* @return Target (maximum) dirty pages ratio, after which throttling will start.
*/
public double getTargetDirtyRatio() {
return targetDirtyRatio;
}
/**
* @return Current dirty pages ratio.
*/
public double getCurrDirtyRatio() {
double ratio = currDirtyRatio;
if (ratio >= 0)
return ratio;
return pageMemory.getDirtyPagesRatio();
}
/**
* @return Speed of marking pages dirty. Value from past 750-1000 millis only. Pages/second.
*/
public long getMarkDirtySpeed() {
return speedMarkAndAvgParkTime.getSpeedOpsPerSec(System.nanoTime());
}
/**
* @return Speed average checkpoint write speed. Current and 3 past checkpoints used. Pages/second.
*/
public long getCpWriteSpeed() {
return speedCpWrite.getSpeedOpsPerSecReadOnly();
}
/**
* @return Returns {@link #speedForMarkAll}.
*/
public long getLastEstimatedSpeedForMarkAll() {
return speedForMarkAll;
}
/**
* Measurement shows how much throttling time is involved into average marking time.
* @return metric started from 0.0 and showing how much throttling is involved into current marking process.
*/
public double throttleWeight() {
long speed = speedMarkAndAvgParkTime.getSpeedOpsPerSec(System.nanoTime());
if (speed <= 0)
return 0;
long timeForOnePage = calcDelayTime(speed, threadIds.size(), 1);
if (timeForOnePage == 0)
return 0;
return 1.0 * throttleParkTime() / timeForOnePage;
}
/**
* Throttling mode for page.
*/
private enum ThrottleMode {
/** No delay is applied. */
NO,
/** Limited, time is based on target speed. */
LIMITED,
/** Exponential. */
EXPONENTIAL
}
}
| apache-2.0 |
scala/scala | test/files/run/t9920d.scala | 182 | class C { object O }
trait T { _: C =>
def foo: Unit = {
class D { O }
new D
}
}
object Test extends C with T {
def main(args: Array[String]): Unit = {
foo
}
}
| apache-2.0 |
interseroh/document-container-confluence | src/main/resources/com/lofidewanto/demo/resource/themes/interseroh/bootstrap/css/bootstrap.css | 146397 | /*!
* Bootstrap v3.3.7 (http://getbootstrap.com)
* Copyright 2011-2017 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
/*!
* Generated using the Bootstrap Customizer (http://getbootstrap.com/customize/?id=d369388fc44f055ccd12bec7bfd669af)
* Config saved to config.json and https://gist.github.com/d369388fc44f055ccd12bec7bfd669af
*/
/*!
* Bootstrap v3.3.7 (http://getbootstrap.com)
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
/*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */
html {
font-family: sans-serif;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
}
body {
margin: 0;
}
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
menu,
nav,
section,
summary {
display: block;
}
audio,
canvas,
progress,
video {
display: inline-block;
vertical-align: baseline;
}
audio:not([controls]) {
display: none;
height: 0;
}
[hidden],
template {
display: none;
}
a {
background-color: transparent;
}
a:active,
a:hover {
outline: 0;
}
abbr[title] {
border-bottom: 1px dotted;
}
b,
strong {
font-weight: bold;
}
dfn {
font-style: italic;
}
h1 {
font-size: 2em;
margin: 0.67em 0;
}
mark {
background: #ff0;
color: #000;
}
small {
font-size: 80%;
}
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
img {
border: 0;
}
svg:not(:root) {
overflow: hidden;
}
figure {
margin: 1em 40px;
}
hr {
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
height: 0;
}
pre {
overflow: auto;
}
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
button,
input,
optgroup,
select,
textarea {
color: inherit;
font: inherit;
margin: 0;
}
button {
overflow: visible;
}
button,
select {
text-transform: none;
}
button,
html input[type="button"],
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button;
cursor: pointer;
}
button[disabled],
html input[disabled] {
cursor: default;
}
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
input {
line-height: normal;
}
input[type="checkbox"],
input[type="radio"] {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 0;
}
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto;
}
input[type="search"] {
-webkit-appearance: textfield;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
legend {
border: 0;
padding: 0;
}
textarea {
overflow: auto;
}
optgroup {
font-weight: bold;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
td,
th {
padding: 0;
}
/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */
@media print {
*,
*:before,
*:after {
background: transparent !important;
color: #000 !important;
-webkit-box-shadow: none !important;
box-shadow: none !important;
text-shadow: none !important;
}
a,
a:visited {
text-decoration: underline;
}
a[href]:after {
content: " (" attr(href) ")";
}
abbr[title]:after {
content: " (" attr(title) ")";
}
a[href^="#"]:after,
a[href^="javascript:"]:after {
content: "";
}
pre,
blockquote {
border: 1px solid #999;
page-break-inside: avoid;
}
thead {
display: table-header-group;
}
tr,
img {
page-break-inside: avoid;
}
img {
max-width: 100% !important;
}
p,
h2,
h3 {
orphans: 3;
widows: 3;
}
h2,
h3 {
page-break-after: avoid;
}
.navbar {
display: none;
}
.btn > .caret,
.dropup > .btn > .caret {
border-top-color: #000 !important;
}
.label {
border: 1px solid #000;
}
.table {
border-collapse: collapse !important;
}
.table td,
.table th {
background-color: #fff !important;
}
.table-bordered th,
.table-bordered td {
border: 1px solid #ddd !important;
}
}
@font-face {
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff2') format('woff2'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
}
.glyphicon {
position: relative;
top: 1px;
display: inline-block;
font-family: 'Glyphicons Halflings';
font-style: normal;
font-weight: normal;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.glyphicon-asterisk:before {
content: "\002a";
}
.glyphicon-plus:before {
content: "\002b";
}
.glyphicon-euro:before,
.glyphicon-eur:before {
content: "\20ac";
}
.glyphicon-minus:before {
content: "\2212";
}
.glyphicon-cloud:before {
content: "\2601";
}
.glyphicon-envelope:before {
content: "\2709";
}
.glyphicon-pencil:before {
content: "\270f";
}
.glyphicon-glass:before {
content: "\e001";
}
.glyphicon-music:before {
content: "\e002";
}
.glyphicon-search:before {
content: "\e003";
}
.glyphicon-heart:before {
content: "\e005";
}
.glyphicon-star:before {
content: "\e006";
}
.glyphicon-star-empty:before {
content: "\e007";
}
.glyphicon-user:before {
content: "\e008";
}
.glyphicon-film:before {
content: "\e009";
}
.glyphicon-th-large:before {
content: "\e010";
}
.glyphicon-th:before {
content: "\e011";
}
.glyphicon-th-list:before {
content: "\e012";
}
.glyphicon-ok:before {
content: "\e013";
}
.glyphicon-remove:before {
content: "\e014";
}
.glyphicon-zoom-in:before {
content: "\e015";
}
.glyphicon-zoom-out:before {
content: "\e016";
}
.glyphicon-off:before {
content: "\e017";
}
.glyphicon-signal:before {
content: "\e018";
}
.glyphicon-cog:before {
content: "\e019";
}
.glyphicon-trash:before {
content: "\e020";
}
.glyphicon-home:before {
content: "\e021";
}
.glyphicon-file:before {
content: "\e022";
}
.glyphicon-time:before {
content: "\e023";
}
.glyphicon-road:before {
content: "\e024";
}
.glyphicon-download-alt:before {
content: "\e025";
}
.glyphicon-download:before {
content: "\e026";
}
.glyphicon-upload:before {
content: "\e027";
}
.glyphicon-inbox:before {
content: "\e028";
}
.glyphicon-play-circle:before {
content: "\e029";
}
.glyphicon-repeat:before {
content: "\e030";
}
.glyphicon-refresh:before {
content: "\e031";
}
.glyphicon-list-alt:before {
content: "\e032";
}
.glyphicon-lock:before {
content: "\e033";
}
.glyphicon-flag:before {
content: "\e034";
}
.glyphicon-headphones:before {
content: "\e035";
}
.glyphicon-volume-off:before {
content: "\e036";
}
.glyphicon-volume-down:before {
content: "\e037";
}
.glyphicon-volume-up:before {
content: "\e038";
}
.glyphicon-qrcode:before {
content: "\e039";
}
.glyphicon-barcode:before {
content: "\e040";
}
.glyphicon-tag:before {
content: "\e041";
}
.glyphicon-tags:before {
content: "\e042";
}
.glyphicon-book:before {
content: "\e043";
}
.glyphicon-bookmark:before {
content: "\e044";
}
.glyphicon-print:before {
content: "\e045";
}
.glyphicon-camera:before {
content: "\e046";
}
.glyphicon-font:before {
content: "\e047";
}
.glyphicon-bold:before {
content: "\e048";
}
.glyphicon-italic:before {
content: "\e049";
}
.glyphicon-text-height:before {
content: "\e050";
}
.glyphicon-text-width:before {
content: "\e051";
}
.glyphicon-align-left:before {
content: "\e052";
}
.glyphicon-align-center:before {
content: "\e053";
}
.glyphicon-align-right:before {
content: "\e054";
}
.glyphicon-align-justify:before {
content: "\e055";
}
.glyphicon-list:before {
content: "\e056";
}
.glyphicon-indent-left:before {
content: "\e057";
}
.glyphicon-indent-right:before {
content: "\e058";
}
.glyphicon-facetime-video:before {
content: "\e059";
}
.glyphicon-picture:before {
content: "\e060";
}
.glyphicon-map-marker:before {
content: "\e062";
}
.glyphicon-adjust:before {
content: "\e063";
}
.glyphicon-tint:before {
content: "\e064";
}
.glyphicon-edit:before {
content: "\e065";
}
.glyphicon-share:before {
content: "\e066";
}
.glyphicon-check:before {
content: "\e067";
}
.glyphicon-move:before {
content: "\e068";
}
.glyphicon-step-backward:before {
content: "\e069";
}
.glyphicon-fast-backward:before {
content: "\e070";
}
.glyphicon-backward:before {
content: "\e071";
}
.glyphicon-play:before {
content: "\e072";
}
.glyphicon-pause:before {
content: "\e073";
}
.glyphicon-stop:before {
content: "\e074";
}
.glyphicon-forward:before {
content: "\e075";
}
.glyphicon-fast-forward:before {
content: "\e076";
}
.glyphicon-step-forward:before {
content: "\e077";
}
.glyphicon-eject:before {
content: "\e078";
}
.glyphicon-chevron-left:before {
content: "\e079";
}
.glyphicon-chevron-right:before {
content: "\e080";
}
.glyphicon-plus-sign:before {
content: "\e081";
}
.glyphicon-minus-sign:before {
content: "\e082";
}
.glyphicon-remove-sign:before {
content: "\e083";
}
.glyphicon-ok-sign:before {
content: "\e084";
}
.glyphicon-question-sign:before {
content: "\e085";
}
.glyphicon-info-sign:before {
content: "\e086";
}
.glyphicon-screenshot:before {
content: "\e087";
}
.glyphicon-remove-circle:before {
content: "\e088";
}
.glyphicon-ok-circle:before {
content: "\e089";
}
.glyphicon-ban-circle:before {
content: "\e090";
}
.glyphicon-arrow-left:before {
content: "\e091";
}
.glyphicon-arrow-right:before {
content: "\e092";
}
.glyphicon-arrow-up:before {
content: "\e093";
}
.glyphicon-arrow-down:before {
content: "\e094";
}
.glyphicon-share-alt:before {
content: "\e095";
}
.glyphicon-resize-full:before {
content: "\e096";
}
.glyphicon-resize-small:before {
content: "\e097";
}
.glyphicon-exclamation-sign:before {
content: "\e101";
}
.glyphicon-gift:before {
content: "\e102";
}
.glyphicon-leaf:before {
content: "\e103";
}
.glyphicon-fire:before {
content: "\e104";
}
.glyphicon-eye-open:before {
content: "\e105";
}
.glyphicon-eye-close:before {
content: "\e106";
}
.glyphicon-warning-sign:before {
content: "\e107";
}
.glyphicon-plane:before {
content: "\e108";
}
.glyphicon-calendar:before {
content: "\e109";
}
.glyphicon-random:before {
content: "\e110";
}
.glyphicon-comment:before {
content: "\e111";
}
.glyphicon-magnet:before {
content: "\e112";
}
.glyphicon-chevron-up:before {
content: "\e113";
}
.glyphicon-chevron-down:before {
content: "\e114";
}
.glyphicon-retweet:before {
content: "\e115";
}
.glyphicon-shopping-cart:before {
content: "\e116";
}
.glyphicon-folder-close:before {
content: "\e117";
}
.glyphicon-folder-open:before {
content: "\e118";
}
.glyphicon-resize-vertical:before {
content: "\e119";
}
.glyphicon-resize-horizontal:before {
content: "\e120";
}
.glyphicon-hdd:before {
content: "\e121";
}
.glyphicon-bullhorn:before {
content: "\e122";
}
.glyphicon-bell:before {
content: "\e123";
}
.glyphicon-certificate:before {
content: "\e124";
}
.glyphicon-thumbs-up:before {
content: "\e125";
}
.glyphicon-thumbs-down:before {
content: "\e126";
}
.glyphicon-hand-right:before {
content: "\e127";
}
.glyphicon-hand-left:before {
content: "\e128";
}
.glyphicon-hand-up:before {
content: "\e129";
}
.glyphicon-hand-down:before {
content: "\e130";
}
.glyphicon-circle-arrow-right:before {
content: "\e131";
}
.glyphicon-circle-arrow-left:before {
content: "\e132";
}
.glyphicon-circle-arrow-up:before {
content: "\e133";
}
.glyphicon-circle-arrow-down:before {
content: "\e134";
}
.glyphicon-globe:before {
content: "\e135";
}
.glyphicon-wrench:before {
content: "\e136";
}
.glyphicon-tasks:before {
content: "\e137";
}
.glyphicon-filter:before {
content: "\e138";
}
.glyphicon-briefcase:before {
content: "\e139";
}
.glyphicon-fullscreen:before {
content: "\e140";
}
.glyphicon-dashboard:before {
content: "\e141";
}
.glyphicon-paperclip:before {
content: "\e142";
}
.glyphicon-heart-empty:before {
content: "\e143";
}
.glyphicon-link:before {
content: "\e144";
}
.glyphicon-phone:before {
content: "\e145";
}
.glyphicon-pushpin:before {
content: "\e146";
}
.glyphicon-usd:before {
content: "\e148";
}
.glyphicon-gbp:before {
content: "\e149";
}
.glyphicon-sort:before {
content: "\e150";
}
.glyphicon-sort-by-alphabet:before {
content: "\e151";
}
.glyphicon-sort-by-alphabet-alt:before {
content: "\e152";
}
.glyphicon-sort-by-order:before {
content: "\e153";
}
.glyphicon-sort-by-order-alt:before {
content: "\e154";
}
.glyphicon-sort-by-attributes:before {
content: "\e155";
}
.glyphicon-sort-by-attributes-alt:before {
content: "\e156";
}
.glyphicon-unchecked:before {
content: "\e157";
}
.glyphicon-expand:before {
content: "\e158";
}
.glyphicon-collapse-down:before {
content: "\e159";
}
.glyphicon-collapse-up:before {
content: "\e160";
}
.glyphicon-log-in:before {
content: "\e161";
}
.glyphicon-flash:before {
content: "\e162";
}
.glyphicon-log-out:before {
content: "\e163";
}
.glyphicon-new-window:before {
content: "\e164";
}
.glyphicon-record:before {
content: "\e165";
}
.glyphicon-save:before {
content: "\e166";
}
.glyphicon-open:before {
content: "\e167";
}
.glyphicon-saved:before {
content: "\e168";
}
.glyphicon-import:before {
content: "\e169";
}
.glyphicon-export:before {
content: "\e170";
}
.glyphicon-send:before {
content: "\e171";
}
.glyphicon-floppy-disk:before {
content: "\e172";
}
.glyphicon-floppy-saved:before {
content: "\e173";
}
.glyphicon-floppy-remove:before {
content: "\e174";
}
.glyphicon-floppy-save:before {
content: "\e175";
}
.glyphicon-floppy-open:before {
content: "\e176";
}
.glyphicon-credit-card:before {
content: "\e177";
}
.glyphicon-transfer:before {
content: "\e178";
}
.glyphicon-cutlery:before {
content: "\e179";
}
.glyphicon-header:before {
content: "\e180";
}
.glyphicon-compressed:before {
content: "\e181";
}
.glyphicon-earphone:before {
content: "\e182";
}
.glyphicon-phone-alt:before {
content: "\e183";
}
.glyphicon-tower:before {
content: "\e184";
}
.glyphicon-stats:before {
content: "\e185";
}
.glyphicon-sd-video:before {
content: "\e186";
}
.glyphicon-hd-video:before {
content: "\e187";
}
.glyphicon-subtitles:before {
content: "\e188";
}
.glyphicon-sound-stereo:before {
content: "\e189";
}
.glyphicon-sound-dolby:before {
content: "\e190";
}
.glyphicon-sound-5-1:before {
content: "\e191";
}
.glyphicon-sound-6-1:before {
content: "\e192";
}
.glyphicon-sound-7-1:before {
content: "\e193";
}
.glyphicon-copyright-mark:before {
content: "\e194";
}
.glyphicon-registration-mark:before {
content: "\e195";
}
.glyphicon-cloud-download:before {
content: "\e197";
}
.glyphicon-cloud-upload:before {
content: "\e198";
}
.glyphicon-tree-conifer:before {
content: "\e199";
}
.glyphicon-tree-deciduous:before {
content: "\e200";
}
.glyphicon-cd:before {
content: "\e201";
}
.glyphicon-save-file:before {
content: "\e202";
}
.glyphicon-open-file:before {
content: "\e203";
}
.glyphicon-level-up:before {
content: "\e204";
}
.glyphicon-copy:before {
content: "\e205";
}
.glyphicon-paste:before {
content: "\e206";
}
.glyphicon-alert:before {
content: "\e209";
}
.glyphicon-equalizer:before {
content: "\e210";
}
.glyphicon-king:before {
content: "\e211";
}
.glyphicon-queen:before {
content: "\e212";
}
.glyphicon-pawn:before {
content: "\e213";
}
.glyphicon-bishop:before {
content: "\e214";
}
.glyphicon-knight:before {
content: "\e215";
}
.glyphicon-baby-formula:before {
content: "\e216";
}
.glyphicon-tent:before {
content: "\26fa";
}
.glyphicon-blackboard:before {
content: "\e218";
}
.glyphicon-bed:before {
content: "\e219";
}
.glyphicon-apple:before {
content: "\f8ff";
}
.glyphicon-erase:before {
content: "\e221";
}
.glyphicon-hourglass:before {
content: "\231b";
}
.glyphicon-lamp:before {
content: "\e223";
}
.glyphicon-duplicate:before {
content: "\e224";
}
.glyphicon-piggy-bank:before {
content: "\e225";
}
.glyphicon-scissors:before {
content: "\e226";
}
.glyphicon-bitcoin:before {
content: "\e227";
}
.glyphicon-btc:before {
content: "\e227";
}
.glyphicon-xbt:before {
content: "\e227";
}
.glyphicon-yen:before {
content: "\00a5";
}
.glyphicon-jpy:before {
content: "\00a5";
}
.glyphicon-ruble:before {
content: "\20bd";
}
.glyphicon-rub:before {
content: "\20bd";
}
.glyphicon-scale:before {
content: "\e230";
}
.glyphicon-ice-lolly:before {
content: "\e231";
}
.glyphicon-ice-lolly-tasted:before {
content: "\e232";
}
.glyphicon-education:before {
content: "\e233";
}
.glyphicon-option-horizontal:before {
content: "\e234";
}
.glyphicon-option-vertical:before {
content: "\e235";
}
.glyphicon-menu-hamburger:before {
content: "\e236";
}
.glyphicon-modal-window:before {
content: "\e237";
}
.glyphicon-oil:before {
content: "\e238";
}
.glyphicon-grain:before {
content: "\e239";
}
.glyphicon-sunglasses:before {
content: "\e240";
}
.glyphicon-text-size:before {
content: "\e241";
}
.glyphicon-text-color:before {
content: "\e242";
}
.glyphicon-text-background:before {
content: "\e243";
}
.glyphicon-object-align-top:before {
content: "\e244";
}
.glyphicon-object-align-bottom:before {
content: "\e245";
}
.glyphicon-object-align-horizontal:before {
content: "\e246";
}
.glyphicon-object-align-left:before {
content: "\e247";
}
.glyphicon-object-align-vertical:before {
content: "\e248";
}
.glyphicon-object-align-right:before {
content: "\e249";
}
.glyphicon-triangle-right:before {
content: "\e250";
}
.glyphicon-triangle-left:before {
content: "\e251";
}
.glyphicon-triangle-bottom:before {
content: "\e252";
}
.glyphicon-triangle-top:before {
content: "\e253";
}
.glyphicon-console:before {
content: "\e254";
}
.glyphicon-superscript:before {
content: "\e255";
}
.glyphicon-subscript:before {
content: "\e256";
}
.glyphicon-menu-left:before {
content: "\e257";
}
.glyphicon-menu-right:before {
content: "\e258";
}
.glyphicon-menu-down:before {
content: "\e259";
}
.glyphicon-menu-up:before {
content: "\e260";
}
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
*:before,
*:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
html {
font-size: 10px;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
body {
font-family: "FranklinGothic-Book", Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 1.625;
color: #002652;
background-color: #ffffff;
}
input,
button,
select,
textarea {
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
a {
color: #009dd3;
text-decoration: none;
}
a:hover,
a:focus {
color: #006486;
text-decoration: underline;
}
a:focus {
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
figure {
margin: 0;
}
img {
vertical-align: middle;
}
.img-responsive,
.thumbnail > img,
.thumbnail a > img,
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
display: block;
max-width: 100%;
height: auto;
}
.img-rounded {
border-radius: 6px;
}
.img-thumbnail {
padding: 4px;
line-height: 1.625;
background-color: #ffffff;
border: 1px solid #dddddd;
border-radius: 3px;
-webkit-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out;
transition: all 0.2s ease-in-out;
display: inline-block;
max-width: 100%;
height: auto;
}
.img-circle {
border-radius: 50%;
}
hr {
margin-top: 26px;
margin-bottom: 26px;
border: 0;
border-top: 1px solid #eeeeee;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
margin: -1px;
padding: 0;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}
.sr-only-focusable:active,
.sr-only-focusable:focus {
position: static;
width: auto;
height: auto;
margin: 0;
overflow: visible;
clip: auto;
}
[role="button"] {
cursor: pointer;
}
h1,
h2,
h3,
h4,
h5,
h6,
.h1,
.h2,
.h3,
.h4,
.h5,
.h6 {
font-family: inherit;
font-weight: 500;
line-height: 1.1;
color: inherit;
}
h1 small,
h2 small,
h3 small,
h4 small,
h5 small,
h6 small,
.h1 small,
.h2 small,
.h3 small,
.h4 small,
.h5 small,
.h6 small,
h1 .small,
h2 .small,
h3 .small,
h4 .small,
h5 .small,
h6 .small,
.h1 .small,
.h2 .small,
.h3 .small,
.h4 .small,
.h5 .small,
.h6 .small {
font-weight: normal;
line-height: 1;
color: #777777;
}
h1,
.h1,
h2,
.h2,
h3,
.h3 {
margin-top: 26px;
margin-bottom: 13px;
}
h1 small,
.h1 small,
h2 small,
.h2 small,
h3 small,
.h3 small,
h1 .small,
.h1 .small,
h2 .small,
.h2 .small,
h3 .small,
.h3 .small {
font-size: 65%;
}
h4,
.h4,
h5,
.h5,
h6,
.h6 {
margin-top: 13px;
margin-bottom: 13px;
}
h4 small,
.h4 small,
h5 small,
.h5 small,
h6 small,
.h6 small,
h4 .small,
.h4 .small,
h5 .small,
.h5 .small,
h6 .small,
.h6 .small {
font-size: 75%;
}
h1,
.h1 {
font-size: 48px;
}
h2,
.h2 {
font-size: 36px;
}
h3,
.h3 {
font-size: 25px;
}
h4,
.h4 {
font-size: 22px;
}
h5,
.h5 {
font-size: 16px;
}
h6,
.h6 {
font-size: 14px;
}
p {
margin: 0 0 13px;
}
.lead {
margin-bottom: 26px;
font-size: 18px;
font-weight: 300;
line-height: 1.4;
}
@media (min-width: 768px) {
.lead {
font-size: 24px;
}
}
small,
.small {
font-size: 68%;
}
mark,
.mark {
background-color: #fcf8e3;
padding: .2em;
}
.text-left {
text-align: left;
}
.text-right {
text-align: right;
}
.text-center {
text-align: center;
}
.text-justify {
text-align: justify;
}
.text-nowrap {
white-space: nowrap;
}
.text-lowercase {
text-transform: lowercase;
}
.text-uppercase {
text-transform: uppercase;
}
.text-capitalize {
text-transform: capitalize;
}
.text-muted {
color: #777777;
}
.text-primary {
color: #009dd3;
}
a.text-primary:hover,
a.text-primary:focus {
color: #0077a0;
}
.text-success {
color: #3c763d;
}
a.text-success:hover,
a.text-success:focus {
color: #2b542c;
}
.text-info {
color: #31708f;
}
a.text-info:hover,
a.text-info:focus {
color: #245269;
}
.text-warning {
color: #8a6d3b;
}
a.text-warning:hover,
a.text-warning:focus {
color: #66512c;
}
.text-danger {
color: #a94442;
}
a.text-danger:hover,
a.text-danger:focus {
color: #843534;
}
.bg-primary {
color: #fff;
background-color: #009dd3;
}
a.bg-primary:hover,
a.bg-primary:focus {
background-color: #0077a0;
}
.bg-success {
background-color: #dff0d8;
}
a.bg-success:hover,
a.bg-success:focus {
background-color: #c1e2b3;
}
.bg-info {
background-color: #d9edf7;
}
a.bg-info:hover,
a.bg-info:focus {
background-color: #afd9ee;
}
.bg-warning {
background-color: #fcf8e3;
}
a.bg-warning:hover,
a.bg-warning:focus {
background-color: #f7ecb5;
}
.bg-danger {
background-color: #f2dede;
}
a.bg-danger:hover,
a.bg-danger:focus {
background-color: #e4b9b9;
}
.page-header {
padding-bottom: 12px;
margin: 52px 0 26px;
border-bottom: 1px solid #eeeeee;
}
ul,
ol {
margin-top: 0;
margin-bottom: 13px;
}
ul ul,
ol ul,
ul ol,
ol ol {
margin-bottom: 0;
}
.list-unstyled {
padding-left: 0;
list-style: none;
}
.list-inline {
padding-left: 0;
list-style: none;
margin-left: -5px;
}
.list-inline > li {
display: inline-block;
padding-left: 5px;
padding-right: 5px;
}
dl {
margin-top: 0;
margin-bottom: 26px;
}
dt,
dd {
line-height: 1.625;
}
dt {
font-weight: bold;
}
dd {
margin-left: 0;
}
@media (min-width: 768px) {
.dl-horizontal dt {
float: left;
width: 160px;
clear: left;
text-align: right;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.dl-horizontal dd {
margin-left: 180px;
}
}
abbr[title],
abbr[data-original-title] {
cursor: help;
border-bottom: 1px dotted #777777;
}
.initialism {
font-size: 90%;
text-transform: uppercase;
}
blockquote {
padding: 13px 26px;
margin: 0 0 26px;
font-size: 20px;
border-left: 5px solid #eeeeee;
}
blockquote p:last-child,
blockquote ul:last-child,
blockquote ol:last-child {
margin-bottom: 0;
}
blockquote footer,
blockquote small,
blockquote .small {
display: block;
font-size: 80%;
line-height: 1.625;
color: #777777;
}
blockquote footer:before,
blockquote small:before,
blockquote .small:before {
content: '\2014 \00A0';
}
.blockquote-reverse,
blockquote.pull-right {
padding-right: 15px;
padding-left: 0;
border-right: 5px solid #eeeeee;
border-left: 0;
text-align: right;
}
.blockquote-reverse footer:before,
blockquote.pull-right footer:before,
.blockquote-reverse small:before,
blockquote.pull-right small:before,
.blockquote-reverse .small:before,
blockquote.pull-right .small:before {
content: '';
}
.blockquote-reverse footer:after,
blockquote.pull-right footer:after,
.blockquote-reverse small:after,
blockquote.pull-right small:after,
.blockquote-reverse .small:after,
blockquote.pull-right .small:after {
content: '\00A0 \2014';
}
address {
margin-bottom: 26px;
font-style: normal;
line-height: 1.625;
}
code,
kbd,
pre,
samp {
font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
}
code {
padding: 2px 4px;
font-size: 90%;
color: #c7254e;
background-color: #f9f2f4;
border-radius: 3px;
}
kbd {
padding: 2px 4px;
font-size: 90%;
color: #ffffff;
background-color: #333333;
border-radius: 3px;
-webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.25);
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.25);
}
kbd kbd {
padding: 0;
font-size: 100%;
font-weight: bold;
-webkit-box-shadow: none;
box-shadow: none;
}
pre {
display: block;
padding: 12.5px;
margin: 0 0 13px;
font-size: 15px;
line-height: 1.625;
word-break: break-all;
word-wrap: break-word;
color: #333333;
background-color: #f5f5f5;
border: 1px solid #cccccc;
border-radius: 3px;
}
pre code {
padding: 0;
font-size: inherit;
color: inherit;
white-space: pre-wrap;
background-color: transparent;
border-radius: 0;
}
.pre-scrollable {
max-height: 340px;
overflow-y: scroll;
}
.container {
margin-right: auto;
margin-left: auto;
padding-left: 15px;
padding-right: 15px;
}
@media (min-width: 768px) {
.container {
width: 750px;
}
}
@media (min-width: 992px) {
.container {
width: 970px;
}
}
@media (min-width: 1200px) {
.container {
width: 1170px;
}
}
.container-fluid {
margin-right: auto;
margin-left: auto;
padding-left: 15px;
padding-right: 15px;
}
.row {
margin-left: -15px;
margin-right: -15px;
}
.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
position: relative;
min-height: 1px;
padding-left: 15px;
padding-right: 15px;
}
.col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11, .col-xs-12 {
float: left;
}
.col-xs-12 {
width: 100%;
}
.col-xs-11 {
width: 91.66666667%;
}
.col-xs-10 {
width: 83.33333333%;
}
.col-xs-9 {
width: 75%;
}
.col-xs-8 {
width: 66.66666667%;
}
.col-xs-7 {
width: 58.33333333%;
}
.col-xs-6 {
width: 50%;
}
.col-xs-5 {
width: 41.66666667%;
}
.col-xs-4 {
width: 33.33333333%;
}
.col-xs-3 {
width: 25%;
}
.col-xs-2 {
width: 16.66666667%;
}
.col-xs-1 {
width: 8.33333333%;
}
.col-xs-pull-12 {
right: 100%;
}
.col-xs-pull-11 {
right: 91.66666667%;
}
.col-xs-pull-10 {
right: 83.33333333%;
}
.col-xs-pull-9 {
right: 75%;
}
.col-xs-pull-8 {
right: 66.66666667%;
}
.col-xs-pull-7 {
right: 58.33333333%;
}
.col-xs-pull-6 {
right: 50%;
}
.col-xs-pull-5 {
right: 41.66666667%;
}
.col-xs-pull-4 {
right: 33.33333333%;
}
.col-xs-pull-3 {
right: 25%;
}
.col-xs-pull-2 {
right: 16.66666667%;
}
.col-xs-pull-1 {
right: 8.33333333%;
}
.col-xs-pull-0 {
right: auto;
}
.col-xs-push-12 {
left: 100%;
}
.col-xs-push-11 {
left: 91.66666667%;
}
.col-xs-push-10 {
left: 83.33333333%;
}
.col-xs-push-9 {
left: 75%;
}
.col-xs-push-8 {
left: 66.66666667%;
}
.col-xs-push-7 {
left: 58.33333333%;
}
.col-xs-push-6 {
left: 50%;
}
.col-xs-push-5 {
left: 41.66666667%;
}
.col-xs-push-4 {
left: 33.33333333%;
}
.col-xs-push-3 {
left: 25%;
}
.col-xs-push-2 {
left: 16.66666667%;
}
.col-xs-push-1 {
left: 8.33333333%;
}
.col-xs-push-0 {
left: auto;
}
.col-xs-offset-12 {
margin-left: 100%;
}
.col-xs-offset-11 {
margin-left: 91.66666667%;
}
.col-xs-offset-10 {
margin-left: 83.33333333%;
}
.col-xs-offset-9 {
margin-left: 75%;
}
.col-xs-offset-8 {
margin-left: 66.66666667%;
}
.col-xs-offset-7 {
margin-left: 58.33333333%;
}
.col-xs-offset-6 {
margin-left: 50%;
}
.col-xs-offset-5 {
margin-left: 41.66666667%;
}
.col-xs-offset-4 {
margin-left: 33.33333333%;
}
.col-xs-offset-3 {
margin-left: 25%;
}
.col-xs-offset-2 {
margin-left: 16.66666667%;
}
.col-xs-offset-1 {
margin-left: 8.33333333%;
}
.col-xs-offset-0 {
margin-left: 0%;
}
@media (min-width: 768px) {
.col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 {
float: left;
}
.col-sm-12 {
width: 100%;
}
.col-sm-11 {
width: 91.66666667%;
}
.col-sm-10 {
width: 83.33333333%;
}
.col-sm-9 {
width: 75%;
}
.col-sm-8 {
width: 66.66666667%;
}
.col-sm-7 {
width: 58.33333333%;
}
.col-sm-6 {
width: 50%;
}
.col-sm-5 {
width: 41.66666667%;
}
.col-sm-4 {
width: 33.33333333%;
}
.col-sm-3 {
width: 25%;
}
.col-sm-2 {
width: 16.66666667%;
}
.col-sm-1 {
width: 8.33333333%;
}
.col-sm-pull-12 {
right: 100%;
}
.col-sm-pull-11 {
right: 91.66666667%;
}
.col-sm-pull-10 {
right: 83.33333333%;
}
.col-sm-pull-9 {
right: 75%;
}
.col-sm-pull-8 {
right: 66.66666667%;
}
.col-sm-pull-7 {
right: 58.33333333%;
}
.col-sm-pull-6 {
right: 50%;
}
.col-sm-pull-5 {
right: 41.66666667%;
}
.col-sm-pull-4 {
right: 33.33333333%;
}
.col-sm-pull-3 {
right: 25%;
}
.col-sm-pull-2 {
right: 16.66666667%;
}
.col-sm-pull-1 {
right: 8.33333333%;
}
.col-sm-pull-0 {
right: auto;
}
.col-sm-push-12 {
left: 100%;
}
.col-sm-push-11 {
left: 91.66666667%;
}
.col-sm-push-10 {
left: 83.33333333%;
}
.col-sm-push-9 {
left: 75%;
}
.col-sm-push-8 {
left: 66.66666667%;
}
.col-sm-push-7 {
left: 58.33333333%;
}
.col-sm-push-6 {
left: 50%;
}
.col-sm-push-5 {
left: 41.66666667%;
}
.col-sm-push-4 {
left: 33.33333333%;
}
.col-sm-push-3 {
left: 25%;
}
.col-sm-push-2 {
left: 16.66666667%;
}
.col-sm-push-1 {
left: 8.33333333%;
}
.col-sm-push-0 {
left: auto;
}
.col-sm-offset-12 {
margin-left: 100%;
}
.col-sm-offset-11 {
margin-left: 91.66666667%;
}
.col-sm-offset-10 {
margin-left: 83.33333333%;
}
.col-sm-offset-9 {
margin-left: 75%;
}
.col-sm-offset-8 {
margin-left: 66.66666667%;
}
.col-sm-offset-7 {
margin-left: 58.33333333%;
}
.col-sm-offset-6 {
margin-left: 50%;
}
.col-sm-offset-5 {
margin-left: 41.66666667%;
}
.col-sm-offset-4 {
margin-left: 33.33333333%;
}
.col-sm-offset-3 {
margin-left: 25%;
}
.col-sm-offset-2 {
margin-left: 16.66666667%;
}
.col-sm-offset-1 {
margin-left: 8.33333333%;
}
.col-sm-offset-0 {
margin-left: 0%;
}
}
@media (min-width: 992px) {
.col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 {
float: left;
}
.col-md-12 {
width: 100%;
}
.col-md-11 {
width: 91.66666667%;
}
.col-md-10 {
width: 83.33333333%;
}
.col-md-9 {
width: 75%;
}
.col-md-8 {
width: 66.66666667%;
}
.col-md-7 {
width: 58.33333333%;
}
.col-md-6 {
width: 50%;
}
.col-md-5 {
width: 41.66666667%;
}
.col-md-4 {
width: 33.33333333%;
}
.col-md-3 {
width: 25%;
}
.col-md-2 {
width: 16.66666667%;
}
.col-md-1 {
width: 8.33333333%;
}
.col-md-pull-12 {
right: 100%;
}
.col-md-pull-11 {
right: 91.66666667%;
}
.col-md-pull-10 {
right: 83.33333333%;
}
.col-md-pull-9 {
right: 75%;
}
.col-md-pull-8 {
right: 66.66666667%;
}
.col-md-pull-7 {
right: 58.33333333%;
}
.col-md-pull-6 {
right: 50%;
}
.col-md-pull-5 {
right: 41.66666667%;
}
.col-md-pull-4 {
right: 33.33333333%;
}
.col-md-pull-3 {
right: 25%;
}
.col-md-pull-2 {
right: 16.66666667%;
}
.col-md-pull-1 {
right: 8.33333333%;
}
.col-md-pull-0 {
right: auto;
}
.col-md-push-12 {
left: 100%;
}
.col-md-push-11 {
left: 91.66666667%;
}
.col-md-push-10 {
left: 83.33333333%;
}
.col-md-push-9 {
left: 75%;
}
.col-md-push-8 {
left: 66.66666667%;
}
.col-md-push-7 {
left: 58.33333333%;
}
.col-md-push-6 {
left: 50%;
}
.col-md-push-5 {
left: 41.66666667%;
}
.col-md-push-4 {
left: 33.33333333%;
}
.col-md-push-3 {
left: 25%;
}
.col-md-push-2 {
left: 16.66666667%;
}
.col-md-push-1 {
left: 8.33333333%;
}
.col-md-push-0 {
left: auto;
}
.col-md-offset-12 {
margin-left: 100%;
}
.col-md-offset-11 {
margin-left: 91.66666667%;
}
.col-md-offset-10 {
margin-left: 83.33333333%;
}
.col-md-offset-9 {
margin-left: 75%;
}
.col-md-offset-8 {
margin-left: 66.66666667%;
}
.col-md-offset-7 {
margin-left: 58.33333333%;
}
.col-md-offset-6 {
margin-left: 50%;
}
.col-md-offset-5 {
margin-left: 41.66666667%;
}
.col-md-offset-4 {
margin-left: 33.33333333%;
}
.col-md-offset-3 {
margin-left: 25%;
}
.col-md-offset-2 {
margin-left: 16.66666667%;
}
.col-md-offset-1 {
margin-left: 8.33333333%;
}
.col-md-offset-0 {
margin-left: 0%;
}
}
@media (min-width: 1200px) {
.col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12 {
float: left;
}
.col-lg-12 {
width: 100%;
}
.col-lg-11 {
width: 91.66666667%;
}
.col-lg-10 {
width: 83.33333333%;
}
.col-lg-9 {
width: 75%;
}
.col-lg-8 {
width: 66.66666667%;
}
.col-lg-7 {
width: 58.33333333%;
}
.col-lg-6 {
width: 50%;
}
.col-lg-5 {
width: 41.66666667%;
}
.col-lg-4 {
width: 33.33333333%;
}
.col-lg-3 {
width: 25%;
}
.col-lg-2 {
width: 16.66666667%;
}
.col-lg-1 {
width: 8.33333333%;
}
.col-lg-pull-12 {
right: 100%;
}
.col-lg-pull-11 {
right: 91.66666667%;
}
.col-lg-pull-10 {
right: 83.33333333%;
}
.col-lg-pull-9 {
right: 75%;
}
.col-lg-pull-8 {
right: 66.66666667%;
}
.col-lg-pull-7 {
right: 58.33333333%;
}
.col-lg-pull-6 {
right: 50%;
}
.col-lg-pull-5 {
right: 41.66666667%;
}
.col-lg-pull-4 {
right: 33.33333333%;
}
.col-lg-pull-3 {
right: 25%;
}
.col-lg-pull-2 {
right: 16.66666667%;
}
.col-lg-pull-1 {
right: 8.33333333%;
}
.col-lg-pull-0 {
right: auto;
}
.col-lg-push-12 {
left: 100%;
}
.col-lg-push-11 {
left: 91.66666667%;
}
.col-lg-push-10 {
left: 83.33333333%;
}
.col-lg-push-9 {
left: 75%;
}
.col-lg-push-8 {
left: 66.66666667%;
}
.col-lg-push-7 {
left: 58.33333333%;
}
.col-lg-push-6 {
left: 50%;
}
.col-lg-push-5 {
left: 41.66666667%;
}
.col-lg-push-4 {
left: 33.33333333%;
}
.col-lg-push-3 {
left: 25%;
}
.col-lg-push-2 {
left: 16.66666667%;
}
.col-lg-push-1 {
left: 8.33333333%;
}
.col-lg-push-0 {
left: auto;
}
.col-lg-offset-12 {
margin-left: 100%;
}
.col-lg-offset-11 {
margin-left: 91.66666667%;
}
.col-lg-offset-10 {
margin-left: 83.33333333%;
}
.col-lg-offset-9 {
margin-left: 75%;
}
.col-lg-offset-8 {
margin-left: 66.66666667%;
}
.col-lg-offset-7 {
margin-left: 58.33333333%;
}
.col-lg-offset-6 {
margin-left: 50%;
}
.col-lg-offset-5 {
margin-left: 41.66666667%;
}
.col-lg-offset-4 {
margin-left: 33.33333333%;
}
.col-lg-offset-3 {
margin-left: 25%;
}
.col-lg-offset-2 {
margin-left: 16.66666667%;
}
.col-lg-offset-1 {
margin-left: 8.33333333%;
}
.col-lg-offset-0 {
margin-left: 0%;
}
}
table {
background-color: transparent;
}
caption {
padding-top: 8px;
padding-bottom: 8px;
color: #777777;
text-align: left;
}
th {
text-align: left;
}
.table {
width: 100%;
max-width: 100%;
margin-bottom: 26px;
}
.table > thead > tr > th,
.table > tbody > tr > th,
.table > tfoot > tr > th,
.table > thead > tr > td,
.table > tbody > tr > td,
.table > tfoot > tr > td {
padding: 8px;
line-height: 1.625;
vertical-align: top;
border-top: 1px solid #dddddd;
}
.table > thead > tr > th {
vertical-align: bottom;
border-bottom: 2px solid #dddddd;
}
.table > caption + thead > tr:first-child > th,
.table > colgroup + thead > tr:first-child > th,
.table > thead:first-child > tr:first-child > th,
.table > caption + thead > tr:first-child > td,
.table > colgroup + thead > tr:first-child > td,
.table > thead:first-child > tr:first-child > td {
border-top: 0;
}
.table > tbody + tbody {
border-top: 2px solid #dddddd;
}
.table .table {
background-color: #ffffff;
}
.table-condensed > thead > tr > th,
.table-condensed > tbody > tr > th,
.table-condensed > tfoot > tr > th,
.table-condensed > thead > tr > td,
.table-condensed > tbody > tr > td,
.table-condensed > tfoot > tr > td {
padding: 5px;
}
.table-bordered {
border: 1px solid #dddddd;
}
.table-bordered > thead > tr > th,
.table-bordered > tbody > tr > th,
.table-bordered > tfoot > tr > th,
.table-bordered > thead > tr > td,
.table-bordered > tbody > tr > td,
.table-bordered > tfoot > tr > td {
border: 1px solid #dddddd;
}
.table-bordered > thead > tr > th,
.table-bordered > thead > tr > td {
border-bottom-width: 2px;
}
.table-striped > tbody > tr:nth-of-type(odd) {
background-color: #f9f9f9;
}
.table-hover > tbody > tr:hover {
background-color: #f5f5f5;
}
table col[class*="col-"] {
position: static;
float: none;
display: table-column;
}
table td[class*="col-"],
table th[class*="col-"] {
position: static;
float: none;
display: table-cell;
}
.table > thead > tr > td.active,
.table > tbody > tr > td.active,
.table > tfoot > tr > td.active,
.table > thead > tr > th.active,
.table > tbody > tr > th.active,
.table > tfoot > tr > th.active,
.table > thead > tr.active > td,
.table > tbody > tr.active > td,
.table > tfoot > tr.active > td,
.table > thead > tr.active > th,
.table > tbody > tr.active > th,
.table > tfoot > tr.active > th {
background-color: #f5f5f5;
}
.table-hover > tbody > tr > td.active:hover,
.table-hover > tbody > tr > th.active:hover,
.table-hover > tbody > tr.active:hover > td,
.table-hover > tbody > tr:hover > .active,
.table-hover > tbody > tr.active:hover > th {
background-color: #e8e8e8;
}
.table > thead > tr > td.success,
.table > tbody > tr > td.success,
.table > tfoot > tr > td.success,
.table > thead > tr > th.success,
.table > tbody > tr > th.success,
.table > tfoot > tr > th.success,
.table > thead > tr.success > td,
.table > tbody > tr.success > td,
.table > tfoot > tr.success > td,
.table > thead > tr.success > th,
.table > tbody > tr.success > th,
.table > tfoot > tr.success > th {
background-color: #dff0d8;
}
.table-hover > tbody > tr > td.success:hover,
.table-hover > tbody > tr > th.success:hover,
.table-hover > tbody > tr.success:hover > td,
.table-hover > tbody > tr:hover > .success,
.table-hover > tbody > tr.success:hover > th {
background-color: #d0e9c6;
}
.table > thead > tr > td.info,
.table > tbody > tr > td.info,
.table > tfoot > tr > td.info,
.table > thead > tr > th.info,
.table > tbody > tr > th.info,
.table > tfoot > tr > th.info,
.table > thead > tr.info > td,
.table > tbody > tr.info > td,
.table > tfoot > tr.info > td,
.table > thead > tr.info > th,
.table > tbody > tr.info > th,
.table > tfoot > tr.info > th {
background-color: #d9edf7;
}
.table-hover > tbody > tr > td.info:hover,
.table-hover > tbody > tr > th.info:hover,
.table-hover > tbody > tr.info:hover > td,
.table-hover > tbody > tr:hover > .info,
.table-hover > tbody > tr.info:hover > th {
background-color: #c4e3f3;
}
.table > thead > tr > td.warning,
.table > tbody > tr > td.warning,
.table > tfoot > tr > td.warning,
.table > thead > tr > th.warning,
.table > tbody > tr > th.warning,
.table > tfoot > tr > th.warning,
.table > thead > tr.warning > td,
.table > tbody > tr.warning > td,
.table > tfoot > tr.warning > td,
.table > thead > tr.warning > th,
.table > tbody > tr.warning > th,
.table > tfoot > tr.warning > th {
background-color: #fcf8e3;
}
.table-hover > tbody > tr > td.warning:hover,
.table-hover > tbody > tr > th.warning:hover,
.table-hover > tbody > tr.warning:hover > td,
.table-hover > tbody > tr:hover > .warning,
.table-hover > tbody > tr.warning:hover > th {
background-color: #faf2cc;
}
.table > thead > tr > td.danger,
.table > tbody > tr > td.danger,
.table > tfoot > tr > td.danger,
.table > thead > tr > th.danger,
.table > tbody > tr > th.danger,
.table > tfoot > tr > th.danger,
.table > thead > tr.danger > td,
.table > tbody > tr.danger > td,
.table > tfoot > tr.danger > td,
.table > thead > tr.danger > th,
.table > tbody > tr.danger > th,
.table > tfoot > tr.danger > th {
background-color: #f2dede;
}
.table-hover > tbody > tr > td.danger:hover,
.table-hover > tbody > tr > th.danger:hover,
.table-hover > tbody > tr.danger:hover > td,
.table-hover > tbody > tr:hover > .danger,
.table-hover > tbody > tr.danger:hover > th {
background-color: #ebcccc;
}
.table-responsive {
overflow-x: auto;
min-height: 0.01%;
}
@media screen and (max-width: 767px) {
.table-responsive {
width: 100%;
margin-bottom: 19.5px;
overflow-y: hidden;
-ms-overflow-style: -ms-autohiding-scrollbar;
border: 1px solid #dddddd;
}
.table-responsive > .table {
margin-bottom: 0;
}
.table-responsive > .table > thead > tr > th,
.table-responsive > .table > tbody > tr > th,
.table-responsive > .table > tfoot > tr > th,
.table-responsive > .table > thead > tr > td,
.table-responsive > .table > tbody > tr > td,
.table-responsive > .table > tfoot > tr > td {
white-space: nowrap;
}
.table-responsive > .table-bordered {
border: 0;
}
.table-responsive > .table-bordered > thead > tr > th:first-child,
.table-responsive > .table-bordered > tbody > tr > th:first-child,
.table-responsive > .table-bordered > tfoot > tr > th:first-child,
.table-responsive > .table-bordered > thead > tr > td:first-child,
.table-responsive > .table-bordered > tbody > tr > td:first-child,
.table-responsive > .table-bordered > tfoot > tr > td:first-child {
border-left: 0;
}
.table-responsive > .table-bordered > thead > tr > th:last-child,
.table-responsive > .table-bordered > tbody > tr > th:last-child,
.table-responsive > .table-bordered > tfoot > tr > th:last-child,
.table-responsive > .table-bordered > thead > tr > td:last-child,
.table-responsive > .table-bordered > tbody > tr > td:last-child,
.table-responsive > .table-bordered > tfoot > tr > td:last-child {
border-right: 0;
}
.table-responsive > .table-bordered > tbody > tr:last-child > th,
.table-responsive > .table-bordered > tfoot > tr:last-child > th,
.table-responsive > .table-bordered > tbody > tr:last-child > td,
.table-responsive > .table-bordered > tfoot > tr:last-child > td {
border-bottom: 0;
}
}
fieldset {
padding: 0;
margin: 0;
border: 0;
min-width: 0;
}
legend {
display: block;
width: 100%;
padding: 0;
margin-bottom: 26px;
font-size: 24px;
line-height: inherit;
color: #333333;
border: 0;
border-bottom: 1px solid #e5e5e5;
}
label {
display: inline-block;
max-width: 100%;
margin-bottom: 5px;
font-weight: bold;
}
input[type="search"] {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
input[type="radio"],
input[type="checkbox"] {
margin: 4px 0 0;
margin-top: 1px \9;
line-height: normal;
}
input[type="file"] {
display: block;
}
input[type="range"] {
display: block;
width: 100%;
}
select[multiple],
select[size] {
height: auto;
}
input[type="file"]:focus,
input[type="radio"]:focus,
input[type="checkbox"]:focus {
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
output {
display: block;
padding-top: 7px;
font-size: 16px;
line-height: 1.625;
color: #555555;
}
.form-control {
display: block;
width: 100%;
height: 40px;
padding: 6px 12px;
font-size: 16px;
line-height: 1.625;
color: #555555;
background-color: #f2f2f2;
background-image: none;
border: 1px solid transparent;
border-radius: 3px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}
.form-control:focus {
border-color: #66afe9;
outline: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
}
.form-control::-moz-placeholder {
color: #999999;
opacity: 1;
}
.form-control:-ms-input-placeholder {
color: #999999;
}
.form-control::-webkit-input-placeholder {
color: #999999;
}
.form-control::-ms-expand {
border: 0;
background-color: transparent;
}
.form-control[disabled],
.form-control[readonly],
fieldset[disabled] .form-control {
background-color: #eeeeee;
opacity: 1;
}
.form-control[disabled],
fieldset[disabled] .form-control {
cursor: not-allowed;
}
textarea.form-control {
height: auto;
}
input[type="search"] {
-webkit-appearance: none;
}
@media screen and (-webkit-min-device-pixel-ratio: 0) {
input[type="date"].form-control,
input[type="time"].form-control,
input[type="datetime-local"].form-control,
input[type="month"].form-control {
line-height: 40px;
}
input[type="date"].input-sm,
input[type="time"].input-sm,
input[type="datetime-local"].input-sm,
input[type="month"].input-sm,
.input-group-sm input[type="date"],
.input-group-sm input[type="time"],
.input-group-sm input[type="datetime-local"],
.input-group-sm input[type="month"] {
line-height: 28px;
}
input[type="date"].input-lg,
input[type="time"].input-lg,
input[type="datetime-local"].input-lg,
input[type="month"].input-lg,
.input-group-lg input[type="date"],
.input-group-lg input[type="time"],
.input-group-lg input[type="datetime-local"],
.input-group-lg input[type="month"] {
line-height: 49px;
}
}
.form-group {
margin-bottom: 15px;
}
.radio,
.checkbox {
position: relative;
display: block;
margin-top: 10px;
margin-bottom: 10px;
}
.radio label,
.checkbox label {
min-height: 26px;
padding-left: 20px;
margin-bottom: 0;
font-weight: normal;
cursor: pointer;
}
.radio input[type="radio"],
.radio-inline input[type="radio"],
.checkbox input[type="checkbox"],
.checkbox-inline input[type="checkbox"] {
position: absolute;
margin-left: -20px;
margin-top: 4px \9;
}
.radio + .radio,
.checkbox + .checkbox {
margin-top: -5px;
}
.radio-inline,
.checkbox-inline {
position: relative;
display: inline-block;
padding-left: 20px;
margin-bottom: 0;
vertical-align: middle;
font-weight: normal;
cursor: pointer;
}
.radio-inline + .radio-inline,
.checkbox-inline + .checkbox-inline {
margin-top: 0;
margin-left: 10px;
}
input[type="radio"][disabled],
input[type="checkbox"][disabled],
input[type="radio"].disabled,
input[type="checkbox"].disabled,
fieldset[disabled] input[type="radio"],
fieldset[disabled] input[type="checkbox"] {
cursor: not-allowed;
}
.radio-inline.disabled,
.checkbox-inline.disabled,
fieldset[disabled] .radio-inline,
fieldset[disabled] .checkbox-inline {
cursor: not-allowed;
}
.radio.disabled label,
.checkbox.disabled label,
fieldset[disabled] .radio label,
fieldset[disabled] .checkbox label {
cursor: not-allowed;
}
.form-control-static {
padding-top: 7px;
padding-bottom: 7px;
margin-bottom: 0;
min-height: 42px;
}
.form-control-static.input-lg,
.form-control-static.input-sm {
padding-left: 0;
padding-right: 0;
}
.input-sm {
height: 28px;
padding: 5px 10px;
font-size: 11px;
line-height: 1.5;
border-radius: 3px;
}
select.input-sm {
height: 28px;
line-height: 28px;
}
textarea.input-sm,
select[multiple].input-sm {
height: auto;
}
.form-group-sm .form-control {
height: 28px;
padding: 5px 10px;
font-size: 11px;
line-height: 1.5;
border-radius: 3px;
}
.form-group-sm select.form-control {
height: 28px;
line-height: 28px;
}
.form-group-sm textarea.form-control,
.form-group-sm select[multiple].form-control {
height: auto;
}
.form-group-sm .form-control-static {
height: 28px;
min-height: 37px;
padding: 6px 10px;
font-size: 11px;
line-height: 1.5;
}
.input-lg {
height: 49px;
padding: 10px 16px;
font-size: 20px;
line-height: 1.3333333;
border-radius: 6px;
}
select.input-lg {
height: 49px;
line-height: 49px;
}
textarea.input-lg,
select[multiple].input-lg {
height: auto;
}
.form-group-lg .form-control {
height: 49px;
padding: 10px 16px;
font-size: 20px;
line-height: 1.3333333;
border-radius: 6px;
}
.form-group-lg select.form-control {
height: 49px;
line-height: 49px;
}
.form-group-lg textarea.form-control,
.form-group-lg select[multiple].form-control {
height: auto;
}
.form-group-lg .form-control-static {
height: 49px;
min-height: 46px;
padding: 11px 16px;
font-size: 20px;
line-height: 1.3333333;
}
.has-feedback {
position: relative;
}
.has-feedback .form-control {
padding-right: 50px;
}
.form-control-feedback {
position: absolute;
top: 0;
right: 0;
z-index: 2;
display: block;
width: 40px;
height: 40px;
line-height: 40px;
text-align: center;
pointer-events: none;
}
.input-lg + .form-control-feedback,
.input-group-lg + .form-control-feedback,
.form-group-lg .form-control + .form-control-feedback {
width: 49px;
height: 49px;
line-height: 49px;
}
.input-sm + .form-control-feedback,
.input-group-sm + .form-control-feedback,
.form-group-sm .form-control + .form-control-feedback {
width: 28px;
height: 28px;
line-height: 28px;
}
.has-success .help-block,
.has-success .control-label,
.has-success .radio,
.has-success .checkbox,
.has-success .radio-inline,
.has-success .checkbox-inline,
.has-success.radio label,
.has-success.checkbox label,
.has-success.radio-inline label,
.has-success.checkbox-inline label {
color: #3c763d;
}
.has-success .form-control {
border-color: #3c763d;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.has-success .form-control:focus {
border-color: #2b542c;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #67b168;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #67b168;
}
.has-success .input-group-addon {
color: #3c763d;
border-color: #3c763d;
background-color: #dff0d8;
}
.has-success .form-control-feedback {
color: #3c763d;
}
.has-warning .help-block,
.has-warning .control-label,
.has-warning .radio,
.has-warning .checkbox,
.has-warning .radio-inline,
.has-warning .checkbox-inline,
.has-warning.radio label,
.has-warning.checkbox label,
.has-warning.radio-inline label,
.has-warning.checkbox-inline label {
color: #8a6d3b;
}
.has-warning .form-control {
border-color: #8a6d3b;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.has-warning .form-control:focus {
border-color: #66512c;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #c0a16b;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #c0a16b;
}
.has-warning .input-group-addon {
color: #8a6d3b;
border-color: #8a6d3b;
background-color: #fcf8e3;
}
.has-warning .form-control-feedback {
color: #8a6d3b;
}
.has-error .help-block,
.has-error .control-label,
.has-error .radio,
.has-error .checkbox,
.has-error .radio-inline,
.has-error .checkbox-inline,
.has-error.radio label,
.has-error.checkbox label,
.has-error.radio-inline label,
.has-error.checkbox-inline label {
color: #a94442;
}
.has-error .form-control {
border-color: #a94442;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.has-error .form-control:focus {
border-color: #843534;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #ce8483;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #ce8483;
}
.has-error .input-group-addon {
color: #a94442;
border-color: #a94442;
background-color: #f2dede;
}
.has-error .form-control-feedback {
color: #a94442;
}
.has-feedback label ~ .form-control-feedback {
top: 31px;
}
.has-feedback label.sr-only ~ .form-control-feedback {
top: 0;
}
.help-block {
display: block;
margin-top: 5px;
margin-bottom: 10px;
color: #0061d2;
}
@media (min-width: 768px) {
.form-inline .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .form-control {
display: inline-block;
width: auto;
vertical-align: middle;
}
.form-inline .form-control-static {
display: inline-block;
}
.form-inline .input-group {
display: inline-table;
vertical-align: middle;
}
.form-inline .input-group .input-group-addon,
.form-inline .input-group .input-group-btn,
.form-inline .input-group .form-control {
width: auto;
}
.form-inline .input-group > .form-control {
width: 100%;
}
.form-inline .control-label {
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .radio,
.form-inline .checkbox {
display: inline-block;
margin-top: 0;
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .radio label,
.form-inline .checkbox label {
padding-left: 0;
}
.form-inline .radio input[type="radio"],
.form-inline .checkbox input[type="checkbox"] {
position: relative;
margin-left: 0;
}
.form-inline .has-feedback .form-control-feedback {
top: 0;
}
}
.form-horizontal .radio,
.form-horizontal .checkbox,
.form-horizontal .radio-inline,
.form-horizontal .checkbox-inline {
margin-top: 0;
margin-bottom: 0;
padding-top: 7px;
}
.form-horizontal .radio,
.form-horizontal .checkbox {
min-height: 33px;
}
.form-horizontal .form-group {
margin-left: -15px;
margin-right: -15px;
}
@media (min-width: 768px) {
.form-horizontal .control-label {
text-align: right;
margin-bottom: 0;
padding-top: 7px;
}
}
.form-horizontal .has-feedback .form-control-feedback {
right: 15px;
}
@media (min-width: 768px) {
.form-horizontal .form-group-lg .control-label {
padding-top: 11px;
font-size: 20px;
}
}
@media (min-width: 768px) {
.form-horizontal .form-group-sm .control-label {
padding-top: 6px;
font-size: 11px;
}
}
.btn {
display: inline-block;
margin-bottom: 0;
font-weight: normal;
text-align: center;
vertical-align: middle;
-ms-touch-action: manipulation;
touch-action: manipulation;
cursor: pointer;
background-image: none;
border: 1px solid transparent;
white-space: nowrap;
padding: 6px 12px;
font-size: 16px;
line-height: 1.625;
border-radius: 3px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.btn:focus,
.btn:active:focus,
.btn.active:focus,
.btn.focus,
.btn:active.focus,
.btn.active.focus {
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
.btn:hover,
.btn:focus,
.btn.focus {
color: #002652;
text-decoration: none;
}
.btn:active,
.btn.active {
outline: 0;
background-image: none;
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
}
.btn.disabled,
.btn[disabled],
fieldset[disabled] .btn {
cursor: not-allowed;
opacity: 0.65;
filter: alpha(opacity=65);
-webkit-box-shadow: none;
box-shadow: none;
}
a.btn.disabled,
fieldset[disabled] a.btn {
pointer-events: none;
}
.btn-default {
color: #002652;
background-color: #d9d9d9;
border-color: #d9d9d9;
}
.btn-default:focus,
.btn-default.focus {
color: #002652;
background-color: #c0c0c0;
border-color: #999999;
}
.btn-default:hover {
color: #002652;
background-color: #c0c0c0;
border-color: #bababa;
}
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
color: #002652;
background-color: #c0c0c0;
border-color: #bababa;
}
.btn-default:active:hover,
.btn-default.active:hover,
.open > .dropdown-toggle.btn-default:hover,
.btn-default:active:focus,
.btn-default.active:focus,
.open > .dropdown-toggle.btn-default:focus,
.btn-default:active.focus,
.btn-default.active.focus,
.open > .dropdown-toggle.btn-default.focus {
color: #002652;
background-color: #aeaeae;
border-color: #999999;
}
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
background-image: none;
}
.btn-default.disabled:hover,
.btn-default[disabled]:hover,
fieldset[disabled] .btn-default:hover,
.btn-default.disabled:focus,
.btn-default[disabled]:focus,
fieldset[disabled] .btn-default:focus,
.btn-default.disabled.focus,
.btn-default[disabled].focus,
fieldset[disabled] .btn-default.focus {
background-color: #d9d9d9;
border-color: #d9d9d9;
}
.btn-default .badge {
color: #d9d9d9;
background-color: #002652;
}
.btn-primary {
color: #ffffff;
background-color: #009dd3;
border-color: #009dd3;
}
.btn-primary:focus,
.btn-primary.focus {
color: #ffffff;
background-color: #0077a0;
border-color: #003e53;
}
.btn-primary:hover {
color: #ffffff;
background-color: #0077a0;
border-color: #006f96;
}
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
color: #ffffff;
background-color: #0077a0;
border-color: #006f96;
}
.btn-primary:active:hover,
.btn-primary.active:hover,
.open > .dropdown-toggle.btn-primary:hover,
.btn-primary:active:focus,
.btn-primary.active:focus,
.open > .dropdown-toggle.btn-primary:focus,
.btn-primary:active.focus,
.btn-primary.active.focus,
.open > .dropdown-toggle.btn-primary.focus {
color: #ffffff;
background-color: #005c7c;
border-color: #003e53;
}
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
background-image: none;
}
.btn-primary.disabled:hover,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary:hover,
.btn-primary.disabled:focus,
.btn-primary[disabled]:focus,
fieldset[disabled] .btn-primary:focus,
.btn-primary.disabled.focus,
.btn-primary[disabled].focus,
fieldset[disabled] .btn-primary.focus {
background-color: #009dd3;
border-color: #009dd3;
}
.btn-primary .badge {
color: #009dd3;
background-color: #ffffff;
}
.btn-success {
color: #ffffff;
background-color: #6b9c4e;
border-color: transparent;
}
.btn-success:focus,
.btn-success.focus {
color: #ffffff;
background-color: #547a3d;
border-color: rgba(0, 0, 0, 0);
}
.btn-success:hover {
color: #ffffff;
background-color: #547a3d;
border-color: rgba(0, 0, 0, 0);
}
.btn-success:active,
.btn-success.active,
.open > .dropdown-toggle.btn-success {
color: #ffffff;
background-color: #547a3d;
border-color: rgba(0, 0, 0, 0);
}
.btn-success:active:hover,
.btn-success.active:hover,
.open > .dropdown-toggle.btn-success:hover,
.btn-success:active:focus,
.btn-success.active:focus,
.open > .dropdown-toggle.btn-success:focus,
.btn-success:active.focus,
.btn-success.active.focus,
.open > .dropdown-toggle.btn-success.focus {
color: #ffffff;
background-color: #436231;
border-color: rgba(0, 0, 0, 0);
}
.btn-success:active,
.btn-success.active,
.open > .dropdown-toggle.btn-success {
background-image: none;
}
.btn-success.disabled:hover,
.btn-success[disabled]:hover,
fieldset[disabled] .btn-success:hover,
.btn-success.disabled:focus,
.btn-success[disabled]:focus,
fieldset[disabled] .btn-success:focus,
.btn-success.disabled.focus,
.btn-success[disabled].focus,
fieldset[disabled] .btn-success.focus {
background-color: #6b9c4e;
border-color: transparent;
}
.btn-success .badge {
color: #6b9c4e;
background-color: #ffffff;
}
.btn-info {
color: #ffffff;
background-color: #5bc0de;
border-color: #46b8da;
}
.btn-info:focus,
.btn-info.focus {
color: #ffffff;
background-color: #31b0d5;
border-color: #1b6d85;
}
.btn-info:hover {
color: #ffffff;
background-color: #31b0d5;
border-color: #269abc;
}
.btn-info:active,
.btn-info.active,
.open > .dropdown-toggle.btn-info {
color: #ffffff;
background-color: #31b0d5;
border-color: #269abc;
}
.btn-info:active:hover,
.btn-info.active:hover,
.open > .dropdown-toggle.btn-info:hover,
.btn-info:active:focus,
.btn-info.active:focus,
.open > .dropdown-toggle.btn-info:focus,
.btn-info:active.focus,
.btn-info.active.focus,
.open > .dropdown-toggle.btn-info.focus {
color: #ffffff;
background-color: #269abc;
border-color: #1b6d85;
}
.btn-info:active,
.btn-info.active,
.open > .dropdown-toggle.btn-info {
background-image: none;
}
.btn-info.disabled:hover,
.btn-info[disabled]:hover,
fieldset[disabled] .btn-info:hover,
.btn-info.disabled:focus,
.btn-info[disabled]:focus,
fieldset[disabled] .btn-info:focus,
.btn-info.disabled.focus,
.btn-info[disabled].focus,
fieldset[disabled] .btn-info.focus {
background-color: #5bc0de;
border-color: #46b8da;
}
.btn-info .badge {
color: #5bc0de;
background-color: #ffffff;
}
.btn-warning {
color: #ffffff;
background-color: #f0ad4e;
border-color: #eea236;
}
.btn-warning:focus,
.btn-warning.focus {
color: #ffffff;
background-color: #ec971f;
border-color: #985f0d;
}
.btn-warning:hover {
color: #ffffff;
background-color: #ec971f;
border-color: #d58512;
}
.btn-warning:active,
.btn-warning.active,
.open > .dropdown-toggle.btn-warning {
color: #ffffff;
background-color: #ec971f;
border-color: #d58512;
}
.btn-warning:active:hover,
.btn-warning.active:hover,
.open > .dropdown-toggle.btn-warning:hover,
.btn-warning:active:focus,
.btn-warning.active:focus,
.open > .dropdown-toggle.btn-warning:focus,
.btn-warning:active.focus,
.btn-warning.active.focus,
.open > .dropdown-toggle.btn-warning.focus {
color: #ffffff;
background-color: #d58512;
border-color: #985f0d;
}
.btn-warning:active,
.btn-warning.active,
.open > .dropdown-toggle.btn-warning {
background-image: none;
}
.btn-warning.disabled:hover,
.btn-warning[disabled]:hover,
fieldset[disabled] .btn-warning:hover,
.btn-warning.disabled:focus,
.btn-warning[disabled]:focus,
fieldset[disabled] .btn-warning:focus,
.btn-warning.disabled.focus,
.btn-warning[disabled].focus,
fieldset[disabled] .btn-warning.focus {
background-color: #f0ad4e;
border-color: #eea236;
}
.btn-warning .badge {
color: #f0ad4e;
background-color: #ffffff;
}
.btn-danger {
color: #ffffff;
background-color: #d9534f;
border-color: #d43f3a;
}
.btn-danger:focus,
.btn-danger.focus {
color: #ffffff;
background-color: #c9302c;
border-color: #761c19;
}
.btn-danger:hover {
color: #ffffff;
background-color: #c9302c;
border-color: #ac2925;
}
.btn-danger:active,
.btn-danger.active,
.open > .dropdown-toggle.btn-danger {
color: #ffffff;
background-color: #c9302c;
border-color: #ac2925;
}
.btn-danger:active:hover,
.btn-danger.active:hover,
.open > .dropdown-toggle.btn-danger:hover,
.btn-danger:active:focus,
.btn-danger.active:focus,
.open > .dropdown-toggle.btn-danger:focus,
.btn-danger:active.focus,
.btn-danger.active.focus,
.open > .dropdown-toggle.btn-danger.focus {
color: #ffffff;
background-color: #ac2925;
border-color: #761c19;
}
.btn-danger:active,
.btn-danger.active,
.open > .dropdown-toggle.btn-danger {
background-image: none;
}
.btn-danger.disabled:hover,
.btn-danger[disabled]:hover,
fieldset[disabled] .btn-danger:hover,
.btn-danger.disabled:focus,
.btn-danger[disabled]:focus,
fieldset[disabled] .btn-danger:focus,
.btn-danger.disabled.focus,
.btn-danger[disabled].focus,
fieldset[disabled] .btn-danger.focus {
background-color: #d9534f;
border-color: #d43f3a;
}
.btn-danger .badge {
color: #d9534f;
background-color: #ffffff;
}
.btn-link {
color: #009dd3;
font-weight: normal;
border-radius: 0;
}
.btn-link,
.btn-link:active,
.btn-link.active,
.btn-link[disabled],
fieldset[disabled] .btn-link {
background-color: transparent;
-webkit-box-shadow: none;
box-shadow: none;
}
.btn-link,
.btn-link:hover,
.btn-link:focus,
.btn-link:active {
border-color: transparent;
}
.btn-link:hover,
.btn-link:focus {
color: #006486;
text-decoration: underline;
background-color: transparent;
}
.btn-link[disabled]:hover,
fieldset[disabled] .btn-link:hover,
.btn-link[disabled]:focus,
fieldset[disabled] .btn-link:focus {
color: #777777;
text-decoration: none;
}
.btn-lg,
.btn-group-lg > .btn {
padding: 10px 16px;
font-size: 20px;
line-height: 1.3333333;
border-radius: 6px;
}
.btn-sm,
.btn-group-sm > .btn {
padding: 5px 10px;
font-size: 11px;
line-height: 1.5;
border-radius: 3px;
}
.btn-xs,
.btn-group-xs > .btn {
padding: 1px 5px;
font-size: 11px;
line-height: 1.5;
border-radius: 3px;
}
.btn-block {
display: block;
width: 100%;
}
.btn-block + .btn-block {
margin-top: 5px;
}
input[type="submit"].btn-block,
input[type="reset"].btn-block,
input[type="button"].btn-block {
width: 100%;
}
.fade {
opacity: 0;
-webkit-transition: opacity 0.15s linear;
-o-transition: opacity 0.15s linear;
transition: opacity 0.15s linear;
}
.fade.in {
opacity: 1;
}
.collapse {
display: none;
}
.collapse.in {
display: block;
}
tr.collapse.in {
display: table-row;
}
tbody.collapse.in {
display: table-row-group;
}
.collapsing {
position: relative;
height: 0;
overflow: hidden;
-webkit-transition-property: height, visibility;
-o-transition-property: height, visibility;
transition-property: height, visibility;
-webkit-transition-duration: 0.35s;
-o-transition-duration: 0.35s;
transition-duration: 0.35s;
-webkit-transition-timing-function: ease;
-o-transition-timing-function: ease;
transition-timing-function: ease;
}
.caret {
display: inline-block;
width: 0;
height: 0;
margin-left: 2px;
vertical-align: middle;
border-top: 4px dashed;
border-top: 4px solid \9;
border-right: 4px solid transparent;
border-left: 4px solid transparent;
}
.dropup,
.dropdown {
position: relative;
}
.dropdown-toggle:focus {
outline: 0;
}
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
display: none;
float: left;
min-width: 160px;
padding: 5px 0;
margin: 2px 0 0;
list-style: none;
font-size: 16px;
text-align: left;
background-color: #f2f2f2;
border: 1px solid transparent;
border-radius: 3px;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
-webkit-background-clip: padding-box;
background-clip: padding-box;
}
.dropdown-menu.pull-right {
right: 0;
left: auto;
}
.dropdown-menu .divider {
height: 1px;
margin: 12px 0;
overflow: hidden;
background-color: #e5e5e5;
}
.dropdown-menu > li > a {
display: block;
padding: 3px 20px;
clear: both;
font-weight: normal;
line-height: 1.625;
color: #333333;
white-space: nowrap;
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
text-decoration: none;
color: #262626;
background-color: #f5f5f5;
}
.dropdown-menu > .active > a,
.dropdown-menu > .active > a:hover,
.dropdown-menu > .active > a:focus {
color: #ffffff;
text-decoration: none;
outline: 0;
background-color: #009dd3;
}
.dropdown-menu > .disabled > a,
.dropdown-menu > .disabled > a:hover,
.dropdown-menu > .disabled > a:focus {
color: #777777;
}
.dropdown-menu > .disabled > a:hover,
.dropdown-menu > .disabled > a:focus {
text-decoration: none;
background-color: transparent;
background-image: none;
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
cursor: not-allowed;
}
.open > .dropdown-menu {
display: block;
}
.open > a {
outline: 0;
}
.dropdown-menu-right {
left: auto;
right: 0;
}
.dropdown-menu-left {
left: 0;
right: auto;
}
.dropdown-header {
display: block;
padding: 3px 20px;
font-size: 11px;
line-height: 1.625;
color: #777777;
white-space: nowrap;
}
.dropdown-backdrop {
position: fixed;
left: 0;
right: 0;
bottom: 0;
top: 0;
z-index: 990;
}
.pull-right > .dropdown-menu {
right: 0;
left: auto;
}
.dropup .caret,
.navbar-fixed-bottom .dropdown .caret {
border-top: 0;
border-bottom: 4px dashed;
border-bottom: 4px solid \9;
content: "";
}
.dropup .dropdown-menu,
.navbar-fixed-bottom .dropdown .dropdown-menu {
top: auto;
bottom: 100%;
margin-bottom: 2px;
}
@media (min-width: 768px) {
.navbar-right .dropdown-menu {
left: auto;
right: 0;
}
.navbar-right .dropdown-menu-left {
left: 0;
right: auto;
}
}
.btn-group,
.btn-group-vertical {
position: relative;
display: inline-block;
vertical-align: middle;
}
.btn-group > .btn,
.btn-group-vertical > .btn {
position: relative;
float: left;
}
.btn-group > .btn:hover,
.btn-group-vertical > .btn:hover,
.btn-group > .btn:focus,
.btn-group-vertical > .btn:focus,
.btn-group > .btn:active,
.btn-group-vertical > .btn:active,
.btn-group > .btn.active,
.btn-group-vertical > .btn.active {
z-index: 2;
}
.btn-group .btn + .btn,
.btn-group .btn + .btn-group,
.btn-group .btn-group + .btn,
.btn-group .btn-group + .btn-group {
margin-left: -1px;
}
.btn-toolbar {
margin-left: -5px;
}
.btn-toolbar .btn,
.btn-toolbar .btn-group,
.btn-toolbar .input-group {
float: left;
}
.btn-toolbar > .btn,
.btn-toolbar > .btn-group,
.btn-toolbar > .input-group {
margin-left: 5px;
}
.btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {
border-radius: 0;
}
.btn-group > .btn:first-child {
margin-left: 0;
}
.btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) {
border-bottom-right-radius: 0;
border-top-right-radius: 0;
}
.btn-group > .btn:last-child:not(:first-child),
.btn-group > .dropdown-toggle:not(:first-child) {
border-bottom-left-radius: 0;
border-top-left-radius: 0;
}
.btn-group > .btn-group {
float: left;
}
.btn-group > .btn-group:not(:first-child):not(:last-child) > .btn {
border-radius: 0;
}
.btn-group > .btn-group:first-child:not(:last-child) > .btn:last-child,
.btn-group > .btn-group:first-child:not(:last-child) > .dropdown-toggle {
border-bottom-right-radius: 0;
border-top-right-radius: 0;
}
.btn-group > .btn-group:last-child:not(:first-child) > .btn:first-child {
border-bottom-left-radius: 0;
border-top-left-radius: 0;
}
.btn-group .dropdown-toggle:active,
.btn-group.open .dropdown-toggle {
outline: 0;
}
.btn-group > .btn + .dropdown-toggle {
padding-left: 8px;
padding-right: 8px;
}
.btn-group > .btn-lg + .dropdown-toggle {
padding-left: 12px;
padding-right: 12px;
}
.btn-group.open .dropdown-toggle {
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
}
.btn-group.open .dropdown-toggle.btn-link {
-webkit-box-shadow: none;
box-shadow: none;
}
.btn .caret {
margin-left: 0;
}
.btn-lg .caret {
border-width: 5px 5px 0;
border-bottom-width: 0;
}
.dropup .btn-lg .caret {
border-width: 0 5px 5px;
}
.btn-group-vertical > .btn,
.btn-group-vertical > .btn-group,
.btn-group-vertical > .btn-group > .btn {
display: block;
float: none;
width: 100%;
max-width: 100%;
}
.btn-group-vertical > .btn-group > .btn {
float: none;
}
.btn-group-vertical > .btn + .btn,
.btn-group-vertical > .btn + .btn-group,
.btn-group-vertical > .btn-group + .btn,
.btn-group-vertical > .btn-group + .btn-group {
margin-top: -1px;
margin-left: 0;
}
.btn-group-vertical > .btn:not(:first-child):not(:last-child) {
border-radius: 0;
}
.btn-group-vertical > .btn:first-child:not(:last-child) {
border-top-right-radius: 3px;
border-top-left-radius: 3px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group-vertical > .btn:last-child:not(:first-child) {
border-top-right-radius: 0;
border-top-left-radius: 0;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn {
border-radius: 0;
}
.btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child,
.btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle {
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child {
border-top-right-radius: 0;
border-top-left-radius: 0;
}
.btn-group-justified {
display: table;
width: 100%;
table-layout: fixed;
border-collapse: separate;
}
.btn-group-justified > .btn,
.btn-group-justified > .btn-group {
float: none;
display: table-cell;
width: 1%;
}
.btn-group-justified > .btn-group .btn {
width: 100%;
}
.btn-group-justified > .btn-group .dropdown-menu {
left: auto;
}
[data-toggle="buttons"] > .btn input[type="radio"],
[data-toggle="buttons"] > .btn-group > .btn input[type="radio"],
[data-toggle="buttons"] > .btn input[type="checkbox"],
[data-toggle="buttons"] > .btn-group > .btn input[type="checkbox"] {
position: absolute;
clip: rect(0, 0, 0, 0);
pointer-events: none;
}
.input-group {
position: relative;
display: table;
border-collapse: separate;
}
.input-group[class*="col-"] {
float: none;
padding-left: 0;
padding-right: 0;
}
.input-group .form-control {
position: relative;
z-index: 2;
float: left;
width: 100%;
margin-bottom: 0;
}
.input-group .form-control:focus {
z-index: 3;
}
.input-group-lg > .form-control,
.input-group-lg > .input-group-addon,
.input-group-lg > .input-group-btn > .btn {
height: 49px;
padding: 10px 16px;
font-size: 20px;
line-height: 1.3333333;
border-radius: 6px;
}
select.input-group-lg > .form-control,
select.input-group-lg > .input-group-addon,
select.input-group-lg > .input-group-btn > .btn {
height: 49px;
line-height: 49px;
}
textarea.input-group-lg > .form-control,
textarea.input-group-lg > .input-group-addon,
textarea.input-group-lg > .input-group-btn > .btn,
select[multiple].input-group-lg > .form-control,
select[multiple].input-group-lg > .input-group-addon,
select[multiple].input-group-lg > .input-group-btn > .btn {
height: auto;
}
.input-group-sm > .form-control,
.input-group-sm > .input-group-addon,
.input-group-sm > .input-group-btn > .btn {
height: 28px;
padding: 5px 10px;
font-size: 11px;
line-height: 1.5;
border-radius: 3px;
}
select.input-group-sm > .form-control,
select.input-group-sm > .input-group-addon,
select.input-group-sm > .input-group-btn > .btn {
height: 28px;
line-height: 28px;
}
textarea.input-group-sm > .form-control,
textarea.input-group-sm > .input-group-addon,
textarea.input-group-sm > .input-group-btn > .btn,
select[multiple].input-group-sm > .form-control,
select[multiple].input-group-sm > .input-group-addon,
select[multiple].input-group-sm > .input-group-btn > .btn {
height: auto;
}
.input-group-addon,
.input-group-btn,
.input-group .form-control {
display: table-cell;
}
.input-group-addon:not(:first-child):not(:last-child),
.input-group-btn:not(:first-child):not(:last-child),
.input-group .form-control:not(:first-child):not(:last-child) {
border-radius: 0;
}
.input-group-addon,
.input-group-btn {
width: 1%;
white-space: nowrap;
vertical-align: middle;
}
.input-group-addon {
padding: 6px 12px;
font-size: 16px;
font-weight: normal;
line-height: 1;
color: #555555;
text-align: center;
background-color: #eeeeee;
border: 1px solid transparent;
border-radius: 3px;
}
.input-group-addon.input-sm {
padding: 5px 10px;
font-size: 11px;
border-radius: 3px;
}
.input-group-addon.input-lg {
padding: 10px 16px;
font-size: 20px;
border-radius: 6px;
}
.input-group-addon input[type="radio"],
.input-group-addon input[type="checkbox"] {
margin-top: 0;
}
.input-group .form-control:first-child,
.input-group-addon:first-child,
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .btn-group > .btn,
.input-group-btn:first-child > .dropdown-toggle,
.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle),
.input-group-btn:last-child > .btn-group:not(:last-child) > .btn {
border-bottom-right-radius: 0;
border-top-right-radius: 0;
}
.input-group-addon:first-child {
border-right: 0;
}
.input-group .form-control:last-child,
.input-group-addon:last-child,
.input-group-btn:last-child > .btn,
.input-group-btn:last-child > .btn-group > .btn,
.input-group-btn:last-child > .dropdown-toggle,
.input-group-btn:first-child > .btn:not(:first-child),
.input-group-btn:first-child > .btn-group:not(:first-child) > .btn {
border-bottom-left-radius: 0;
border-top-left-radius: 0;
}
.input-group-addon:last-child {
border-left: 0;
}
.input-group-btn {
position: relative;
font-size: 0;
white-space: nowrap;
}
.input-group-btn > .btn {
position: relative;
}
.input-group-btn > .btn + .btn {
margin-left: -1px;
}
.input-group-btn > .btn:hover,
.input-group-btn > .btn:focus,
.input-group-btn > .btn:active {
z-index: 2;
}
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .btn-group {
margin-right: -1px;
}
.input-group-btn:last-child > .btn,
.input-group-btn:last-child > .btn-group {
z-index: 2;
margin-left: -1px;
}
.nav {
margin-bottom: 0;
padding-left: 0;
list-style: none;
}
.nav > li {
position: relative;
display: block;
}
.nav > li > a {
position: relative;
display: block;
padding: 10px 15px;
}
.nav > li > a:hover,
.nav > li > a:focus {
text-decoration: none;
background-color: #eeeeee;
}
.nav > li.disabled > a {
color: #777777;
}
.nav > li.disabled > a:hover,
.nav > li.disabled > a:focus {
color: #777777;
text-decoration: none;
background-color: transparent;
cursor: not-allowed;
}
.nav .open > a,
.nav .open > a:hover,
.nav .open > a:focus {
background-color: #eeeeee;
border-color: #009dd3;
}
.nav .nav-divider {
height: 1px;
margin: 12px 0;
overflow: hidden;
background-color: #e5e5e5;
}
.nav > li > a > img {
max-width: none;
}
.nav-tabs {
border-bottom: 1px solid #dddddd;
}
.nav-tabs > li {
float: left;
margin-bottom: -1px;
}
.nav-tabs > li > a {
margin-right: 2px;
line-height: 1.625;
border: 1px solid transparent;
border-radius: 3px 3px 0 0;
}
.nav-tabs > li > a:hover {
border-color: #eeeeee #eeeeee #dddddd;
}
.nav-tabs > li.active > a,
.nav-tabs > li.active > a:hover,
.nav-tabs > li.active > a:focus {
color: #555555;
background-color: #ffffff;
border: 1px solid #dddddd;
border-bottom-color: transparent;
cursor: default;
}
.nav-tabs.nav-justified {
width: 100%;
border-bottom: 0;
}
.nav-tabs.nav-justified > li {
float: none;
}
.nav-tabs.nav-justified > li > a {
text-align: center;
margin-bottom: 5px;
}
.nav-tabs.nav-justified > .dropdown .dropdown-menu {
top: auto;
left: auto;
}
@media (min-width: 768px) {
.nav-tabs.nav-justified > li {
display: table-cell;
width: 1%;
}
.nav-tabs.nav-justified > li > a {
margin-bottom: 0;
}
}
.nav-tabs.nav-justified > li > a {
margin-right: 0;
border-radius: 3px;
}
.nav-tabs.nav-justified > .active > a,
.nav-tabs.nav-justified > .active > a:hover,
.nav-tabs.nav-justified > .active > a:focus {
border: 1px solid #dddddd;
}
@media (min-width: 768px) {
.nav-tabs.nav-justified > li > a {
border-bottom: 1px solid #dddddd;
border-radius: 3px 3px 0 0;
}
.nav-tabs.nav-justified > .active > a,
.nav-tabs.nav-justified > .active > a:hover,
.nav-tabs.nav-justified > .active > a:focus {
border-bottom-color: #ffffff;
}
}
.nav-pills > li {
float: left;
}
.nav-pills > li > a {
border-radius: 3px;
}
.nav-pills > li + li {
margin-left: 2px;
}
.nav-pills > li.active > a,
.nav-pills > li.active > a:hover,
.nav-pills > li.active > a:focus {
color: #ffffff;
background-color: #002652;
}
.nav-stacked > li {
float: none;
}
.nav-stacked > li + li {
margin-top: 2px;
margin-left: 0;
}
.nav-justified {
width: 100%;
}
.nav-justified > li {
float: none;
}
.nav-justified > li > a {
text-align: center;
margin-bottom: 5px;
}
.nav-justified > .dropdown .dropdown-menu {
top: auto;
left: auto;
}
@media (min-width: 768px) {
.nav-justified > li {
display: table-cell;
width: 1%;
}
.nav-justified > li > a {
margin-bottom: 0;
}
}
.nav-tabs-justified {
border-bottom: 0;
}
.nav-tabs-justified > li > a {
margin-right: 0;
border-radius: 3px;
}
.nav-tabs-justified > .active > a,
.nav-tabs-justified > .active > a:hover,
.nav-tabs-justified > .active > a:focus {
border: 1px solid #dddddd;
}
@media (min-width: 768px) {
.nav-tabs-justified > li > a {
border-bottom: 1px solid #dddddd;
border-radius: 3px 3px 0 0;
}
.nav-tabs-justified > .active > a,
.nav-tabs-justified > .active > a:hover,
.nav-tabs-justified > .active > a:focus {
border-bottom-color: #ffffff;
}
}
.tab-content > .tab-pane {
display: none;
}
.tab-content > .active {
display: block;
}
.nav-tabs .dropdown-menu {
margin-top: -1px;
border-top-right-radius: 0;
border-top-left-radius: 0;
}
.navbar {
position: relative;
min-height: 50px;
margin-bottom: 26px;
border: 1px solid transparent;
}
@media (min-width: 768px) {
.navbar {
border-radius: 3px;
}
}
@media (min-width: 768px) {
.navbar-header {
float: left;
}
}
.navbar-collapse {
overflow-x: visible;
padding-right: 15px;
padding-left: 15px;
border-top: 1px solid transparent;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);
-webkit-overflow-scrolling: touch;
}
.navbar-collapse.in {
overflow-y: auto;
}
@media (min-width: 768px) {
.navbar-collapse {
width: auto;
border-top: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.navbar-collapse.collapse {
display: block !important;
height: auto !important;
padding-bottom: 0;
overflow: visible !important;
}
.navbar-collapse.in {
overflow-y: visible;
}
.navbar-fixed-top .navbar-collapse,
.navbar-static-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
padding-left: 0;
padding-right: 0;
}
}
.navbar-fixed-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
max-height: 340px;
}
@media (max-device-width: 480px) and (orientation: landscape) {
.navbar-fixed-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
max-height: 200px;
}
}
.container > .navbar-header,
.container-fluid > .navbar-header,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
margin-right: -15px;
margin-left: -15px;
}
@media (min-width: 768px) {
.container > .navbar-header,
.container-fluid > .navbar-header,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
margin-right: 0;
margin-left: 0;
}
}
.navbar-static-top {
z-index: 1000;
border-width: 0 0 1px;
}
@media (min-width: 768px) {
.navbar-static-top {
border-radius: 0;
}
}
.navbar-fixed-top,
.navbar-fixed-bottom {
position: fixed;
right: 0;
left: 0;
z-index: 1030;
}
@media (min-width: 768px) {
.navbar-fixed-top,
.navbar-fixed-bottom {
border-radius: 0;
}
}
.navbar-fixed-top {
top: 0;
border-width: 0 0 1px;
}
.navbar-fixed-bottom {
bottom: 0;
margin-bottom: 0;
border-width: 1px 0 0;
}
.navbar-brand {
float: left;
padding: 12px 15px;
font-size: 20px;
line-height: 26px;
height: 50px;
}
.navbar-brand:hover,
.navbar-brand:focus {
text-decoration: none;
}
.navbar-brand > img {
display: block;
}
@media (min-width: 768px) {
.navbar > .container .navbar-brand,
.navbar > .container-fluid .navbar-brand {
margin-left: -15px;
}
}
.navbar-toggle {
position: relative;
float: right;
margin-right: 15px;
padding: 9px 10px;
margin-top: 8px;
margin-bottom: 8px;
background-color: transparent;
background-image: none;
border: 1px solid transparent;
border-radius: 3px;
}
.navbar-toggle:focus {
outline: 0;
}
.navbar-toggle .icon-bar {
display: block;
width: 22px;
height: 2px;
border-radius: 1px;
}
.navbar-toggle .icon-bar + .icon-bar {
margin-top: 4px;
}
@media (min-width: 768px) {
.navbar-toggle {
display: none;
}
}
.navbar-nav {
margin: 6px -15px;
}
.navbar-nav > li > a {
padding-top: 10px;
padding-bottom: 10px;
line-height: 26px;
}
@media (max-width: 767px) {
.navbar-nav .open .dropdown-menu {
position: static;
float: none;
width: auto;
margin-top: 0;
background-color: transparent;
border: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.navbar-nav .open .dropdown-menu > li > a,
.navbar-nav .open .dropdown-menu .dropdown-header {
padding: 5px 15px 5px 25px;
}
.navbar-nav .open .dropdown-menu > li > a {
line-height: 26px;
}
.navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-nav .open .dropdown-menu > li > a:focus {
background-image: none;
}
}
@media (min-width: 768px) {
.navbar-nav {
float: left;
margin: 0;
}
.navbar-nav > li {
float: left;
}
.navbar-nav > li > a {
padding-top: 12px;
padding-bottom: 12px;
}
}
.navbar-form {
margin-left: -15px;
margin-right: -15px;
padding: 10px 15px;
border-top: 1px solid transparent;
border-bottom: 1px solid transparent;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);
margin-top: 5px;
margin-bottom: 5px;
}
@media (min-width: 768px) {
.navbar-form .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .form-control {
display: inline-block;
width: auto;
vertical-align: middle;
}
.navbar-form .form-control-static {
display: inline-block;
}
.navbar-form .input-group {
display: inline-table;
vertical-align: middle;
}
.navbar-form .input-group .input-group-addon,
.navbar-form .input-group .input-group-btn,
.navbar-form .input-group .form-control {
width: auto;
}
.navbar-form .input-group > .form-control {
width: 100%;
}
.navbar-form .control-label {
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .radio,
.navbar-form .checkbox {
display: inline-block;
margin-top: 0;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .radio label,
.navbar-form .checkbox label {
padding-left: 0;
}
.navbar-form .radio input[type="radio"],
.navbar-form .checkbox input[type="checkbox"] {
position: relative;
margin-left: 0;
}
.navbar-form .has-feedback .form-control-feedback {
top: 0;
}
}
@media (max-width: 767px) {
.navbar-form .form-group {
margin-bottom: 5px;
}
.navbar-form .form-group:last-child {
margin-bottom: 0;
}
}
@media (min-width: 768px) {
.navbar-form {
width: auto;
border: 0;
margin-left: 0;
margin-right: 0;
padding-top: 0;
padding-bottom: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
}
.navbar-nav > li > .dropdown-menu {
margin-top: 0;
border-top-right-radius: 0;
border-top-left-radius: 0;
}
.navbar-fixed-bottom .navbar-nav > li > .dropdown-menu {
margin-bottom: 0;
border-top-right-radius: 3px;
border-top-left-radius: 3px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.navbar-btn {
margin-top: 5px;
margin-bottom: 5px;
}
.navbar-btn.btn-sm {
margin-top: 11px;
margin-bottom: 11px;
}
.navbar-btn.btn-xs {
margin-top: 14px;
margin-bottom: 14px;
}
.navbar-text {
margin-top: 12px;
margin-bottom: 12px;
}
@media (min-width: 768px) {
.navbar-text {
float: left;
margin-left: 15px;
margin-right: 15px;
}
}
@media (min-width: 768px) {
.navbar-left {
float: left !important;
}
.navbar-right {
float: right !important;
margin-right: -15px;
}
.navbar-right ~ .navbar-right {
margin-right: 0;
}
}
.navbar-default {
background-color: #f8f8f8;
border-color: #e7e7e7;
}
.navbar-default .navbar-brand {
color: #777777;
}
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
color: #5e5e5e;
background-color: transparent;
}
.navbar-default .navbar-text {
color: #777777;
}
.navbar-default .navbar-nav > li > a {
color: #777777;
}
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
color: #333333;
background-color: transparent;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
color: #555555;
background-color: #e7e7e7;
}
.navbar-default .navbar-nav > .disabled > a,
.navbar-default .navbar-nav > .disabled > a:hover,
.navbar-default .navbar-nav > .disabled > a:focus {
color: #cccccc;
background-color: transparent;
}
.navbar-default .navbar-toggle {
border-color: #dddddd;
}
.navbar-default .navbar-toggle:hover,
.navbar-default .navbar-toggle:focus {
background-color: #dddddd;
}
.navbar-default .navbar-toggle .icon-bar {
background-color: #888888;
}
.navbar-default .navbar-collapse,
.navbar-default .navbar-form {
border-color: #e7e7e7;
}
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .open > a:hover,
.navbar-default .navbar-nav > .open > a:focus {
background-color: #e7e7e7;
color: #555555;
}
@media (max-width: 767px) {
.navbar-default .navbar-nav .open .dropdown-menu > li > a {
color: #777777;
}
.navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
color: #333333;
background-color: transparent;
}
.navbar-default .navbar-nav .open .dropdown-menu > .active > a,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #555555;
background-color: #e7e7e7;
}
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #cccccc;
background-color: transparent;
}
}
.navbar-default .navbar-link {
color: #777777;
}
.navbar-default .navbar-link:hover {
color: #333333;
}
.navbar-default .btn-link {
color: #777777;
}
.navbar-default .btn-link:hover,
.navbar-default .btn-link:focus {
color: #333333;
}
.navbar-default .btn-link[disabled]:hover,
fieldset[disabled] .navbar-default .btn-link:hover,
.navbar-default .btn-link[disabled]:focus,
fieldset[disabled] .navbar-default .btn-link:focus {
color: #cccccc;
}
.navbar-inverse {
background-color: #222222;
border-color: #080808;
}
.navbar-inverse .navbar-brand {
color: #9d9d9d;
}
.navbar-inverse .navbar-brand:hover,
.navbar-inverse .navbar-brand:focus {
color: #ffffff;
background-color: transparent;
}
.navbar-inverse .navbar-text {
color: #9d9d9d;
}
.navbar-inverse .navbar-nav > li > a {
color: #9d9d9d;
}
.navbar-inverse .navbar-nav > li > a:hover,
.navbar-inverse .navbar-nav > li > a:focus {
color: #ffffff;
background-color: transparent;
}
.navbar-inverse .navbar-nav > .active > a,
.navbar-inverse .navbar-nav > .active > a:hover,
.navbar-inverse .navbar-nav > .active > a:focus {
color: #ffffff;
background-color: #080808;
}
.navbar-inverse .navbar-nav > .disabled > a,
.navbar-inverse .navbar-nav > .disabled > a:hover,
.navbar-inverse .navbar-nav > .disabled > a:focus {
color: #444444;
background-color: transparent;
}
.navbar-inverse .navbar-toggle {
border-color: #333333;
}
.navbar-inverse .navbar-toggle:hover,
.navbar-inverse .navbar-toggle:focus {
background-color: #333333;
}
.navbar-inverse .navbar-toggle .icon-bar {
background-color: #ffffff;
}
.navbar-inverse .navbar-collapse,
.navbar-inverse .navbar-form {
border-color: #101010;
}
.navbar-inverse .navbar-nav > .open > a,
.navbar-inverse .navbar-nav > .open > a:hover,
.navbar-inverse .navbar-nav > .open > a:focus {
background-color: #080808;
color: #ffffff;
}
@media (max-width: 767px) {
.navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header {
border-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu .divider {
background-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a {
color: #9d9d9d;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus {
color: #ffffff;
background-color: transparent;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a,
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #ffffff;
background-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #444444;
background-color: transparent;
}
}
.navbar-inverse .navbar-link {
color: #9d9d9d;
}
.navbar-inverse .navbar-link:hover {
color: #ffffff;
}
.navbar-inverse .btn-link {
color: #9d9d9d;
}
.navbar-inverse .btn-link:hover,
.navbar-inverse .btn-link:focus {
color: #ffffff;
}
.navbar-inverse .btn-link[disabled]:hover,
fieldset[disabled] .navbar-inverse .btn-link:hover,
.navbar-inverse .btn-link[disabled]:focus,
fieldset[disabled] .navbar-inverse .btn-link:focus {
color: #444444;
}
.breadcrumb {
padding: 8px 15px;
margin-bottom: 26px;
list-style: none;
background-color: #f5f5f5;
border-radius: 3px;
}
.breadcrumb > li {
display: inline-block;
}
.breadcrumb > li + li:before {
content: "/\00a0";
padding: 0 5px;
color: #cccccc;
}
.breadcrumb > .active {
color: #777777;
}
.pagination {
display: inline-block;
padding-left: 0;
margin: 26px 0;
border-radius: 3px;
}
.pagination > li {
display: inline;
}
.pagination > li > a,
.pagination > li > span {
position: relative;
float: left;
padding: 6px 12px;
line-height: 1.625;
text-decoration: none;
color: #009dd3;
background-color: #ffffff;
border: 1px solid #dddddd;
margin-left: -1px;
}
.pagination > li:first-child > a,
.pagination > li:first-child > span {
margin-left: 0;
border-bottom-left-radius: 3px;
border-top-left-radius: 3px;
}
.pagination > li:last-child > a,
.pagination > li:last-child > span {
border-bottom-right-radius: 3px;
border-top-right-radius: 3px;
}
.pagination > li > a:hover,
.pagination > li > span:hover,
.pagination > li > a:focus,
.pagination > li > span:focus {
z-index: 2;
color: #006486;
background-color: #eeeeee;
border-color: #dddddd;
}
.pagination > .active > a,
.pagination > .active > span,
.pagination > .active > a:hover,
.pagination > .active > span:hover,
.pagination > .active > a:focus,
.pagination > .active > span:focus {
z-index: 3;
color: #ffffff;
background-color: #009dd3;
border-color: #009dd3;
cursor: default;
}
.pagination > .disabled > span,
.pagination > .disabled > span:hover,
.pagination > .disabled > span:focus,
.pagination > .disabled > a,
.pagination > .disabled > a:hover,
.pagination > .disabled > a:focus {
color: #777777;
background-color: #ffffff;
border-color: #dddddd;
cursor: not-allowed;
}
.pagination-lg > li > a,
.pagination-lg > li > span {
padding: 10px 16px;
font-size: 20px;
line-height: 1.3333333;
}
.pagination-lg > li:first-child > a,
.pagination-lg > li:first-child > span {
border-bottom-left-radius: 6px;
border-top-left-radius: 6px;
}
.pagination-lg > li:last-child > a,
.pagination-lg > li:last-child > span {
border-bottom-right-radius: 6px;
border-top-right-radius: 6px;
}
.pagination-sm > li > a,
.pagination-sm > li > span {
padding: 5px 10px;
font-size: 11px;
line-height: 1.5;
}
.pagination-sm > li:first-child > a,
.pagination-sm > li:first-child > span {
border-bottom-left-radius: 3px;
border-top-left-radius: 3px;
}
.pagination-sm > li:last-child > a,
.pagination-sm > li:last-child > span {
border-bottom-right-radius: 3px;
border-top-right-radius: 3px;
}
.pager {
padding-left: 0;
margin: 26px 0;
list-style: none;
text-align: center;
}
.pager li {
display: inline;
}
.pager li > a,
.pager li > span {
display: inline-block;
padding: 5px 14px;
background-color: #ffffff;
border: 1px solid #dddddd;
border-radius: 15px;
}
.pager li > a:hover,
.pager li > a:focus {
text-decoration: none;
background-color: #eeeeee;
}
.pager .next > a,
.pager .next > span {
float: right;
}
.pager .previous > a,
.pager .previous > span {
float: left;
}
.pager .disabled > a,
.pager .disabled > a:hover,
.pager .disabled > a:focus,
.pager .disabled > span {
color: #777777;
background-color: #ffffff;
cursor: not-allowed;
}
.label {
display: inline;
padding: .2em .6em .3em;
font-size: 75%;
font-weight: bold;
line-height: 1;
color: #ffffff;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
border-radius: .25em;
}
a.label:hover,
a.label:focus {
color: #ffffff;
text-decoration: none;
cursor: pointer;
}
.label:empty {
display: none;
}
.btn .label {
position: relative;
top: -1px;
}
.label-default {
background-color: #777777;
}
.label-default[href]:hover,
.label-default[href]:focus {
background-color: #5e5e5e;
}
.label-primary {
background-color: #009dd3;
}
.label-primary[href]:hover,
.label-primary[href]:focus {
background-color: #0077a0;
}
.label-success {
background-color: #5cb85c;
}
.label-success[href]:hover,
.label-success[href]:focus {
background-color: #449d44;
}
.label-info {
background-color: #5bc0de;
}
.label-info[href]:hover,
.label-info[href]:focus {
background-color: #31b0d5;
}
.label-warning {
background-color: #f0ad4e;
}
.label-warning[href]:hover,
.label-warning[href]:focus {
background-color: #ec971f;
}
.label-danger {
background-color: #d9534f;
}
.label-danger[href]:hover,
.label-danger[href]:focus {
background-color: #c9302c;
}
.badge {
display: inline-block;
min-width: 10px;
padding: 3px 7px;
font-size: 11px;
font-weight: bold;
color: #ffffff;
line-height: 1;
vertical-align: middle;
white-space: nowrap;
text-align: center;
background-color: #777777;
border-radius: 10px;
}
.badge:empty {
display: none;
}
.btn .badge {
position: relative;
top: -1px;
}
.btn-xs .badge,
.btn-group-xs > .btn .badge {
top: 0;
padding: 1px 5px;
}
a.badge:hover,
a.badge:focus {
color: #ffffff;
text-decoration: none;
cursor: pointer;
}
.list-group-item.active > .badge,
.nav-pills > .active > a > .badge {
color: #009dd3;
background-color: #ffffff;
}
.list-group-item > .badge {
float: right;
}
.list-group-item > .badge + .badge {
margin-right: 5px;
}
.nav-pills > li > a > .badge {
margin-left: 3px;
}
.jumbotron {
padding-top: 30px;
padding-bottom: 30px;
margin-bottom: 30px;
color: inherit;
background-color: #eeeeee;
}
.jumbotron h1,
.jumbotron .h1 {
color: inherit;
}
.jumbotron p {
margin-bottom: 15px;
font-size: 24px;
font-weight: 200;
}
.jumbotron > hr {
border-top-color: #d5d5d5;
}
.container .jumbotron,
.container-fluid .jumbotron {
border-radius: 6px;
padding-left: 15px;
padding-right: 15px;
}
.jumbotron .container {
max-width: 100%;
}
@media screen and (min-width: 768px) {
.jumbotron {
padding-top: 48px;
padding-bottom: 48px;
}
.container .jumbotron,
.container-fluid .jumbotron {
padding-left: 60px;
padding-right: 60px;
}
.jumbotron h1,
.jumbotron .h1 {
font-size: 72px;
}
}
.thumbnail {
display: block;
padding: 4px;
margin-bottom: 26px;
line-height: 1.625;
background-color: #ffffff;
border: 1px solid #dddddd;
border-radius: 3px;
-webkit-transition: border 0.2s ease-in-out;
-o-transition: border 0.2s ease-in-out;
transition: border 0.2s ease-in-out;
}
.thumbnail > img,
.thumbnail a > img {
margin-left: auto;
margin-right: auto;
}
a.thumbnail:hover,
a.thumbnail:focus,
a.thumbnail.active {
border-color: #009dd3;
}
.thumbnail .caption {
padding: 9px;
color: #002652;
}
.alert {
padding: 15px;
margin-bottom: 26px;
border: 1px solid transparent;
border-radius: 3px;
}
.alert h4 {
margin-top: 0;
color: inherit;
}
.alert .alert-link {
font-weight: bold;
}
.alert > p,
.alert > ul {
margin-bottom: 0;
}
.alert > p + p {
margin-top: 5px;
}
.alert-dismissable,
.alert-dismissible {
padding-right: 35px;
}
.alert-dismissable .close,
.alert-dismissible .close {
position: relative;
top: -2px;
right: -21px;
color: inherit;
}
.alert-success {
background-color: #dff0d8;
border-color: #d6e9c6;
color: #3c763d;
}
.alert-success hr {
border-top-color: #c9e2b3;
}
.alert-success .alert-link {
color: #2b542c;
}
.alert-info {
background-color: #d9edf7;
border-color: #bce8f1;
color: #31708f;
}
.alert-info hr {
border-top-color: #a6e1ec;
}
.alert-info .alert-link {
color: #245269;
}
.alert-warning {
background-color: #fcf8e3;
border-color: #faebcc;
color: #8a6d3b;
}
.alert-warning hr {
border-top-color: #f7e1b5;
}
.alert-warning .alert-link {
color: #66512c;
}
.alert-danger {
background-color: #f2dede;
border-color: #ebccd1;
color: #a94442;
}
.alert-danger hr {
border-top-color: #e4b9c0;
}
.alert-danger .alert-link {
color: #843534;
}
@-webkit-keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
@-o-keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
@keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
.progress {
overflow: hidden;
height: 26px;
margin-bottom: 26px;
background-color: #f5f5f5;
border-radius: 3px;
-webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
}
.progress-bar {
float: left;
width: 0%;
height: 100%;
font-size: 11px;
line-height: 26px;
color: #ffffff;
text-align: center;
background-color: #009dd3;
-webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);
-webkit-transition: width 0.6s ease;
-o-transition: width 0.6s ease;
transition: width 0.6s ease;
}
.progress-striped .progress-bar,
.progress-bar-striped {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-webkit-background-size: 40px 40px;
background-size: 40px 40px;
}
.progress.active .progress-bar,
.progress-bar.active {
-webkit-animation: progress-bar-stripes 2s linear infinite;
-o-animation: progress-bar-stripes 2s linear infinite;
animation: progress-bar-stripes 2s linear infinite;
}
.progress-bar-success {
background-color: #5cb85c;
}
.progress-striped .progress-bar-success {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
}
.progress-bar-info {
background-color: #5bc0de;
}
.progress-striped .progress-bar-info {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
}
.progress-bar-warning {
background-color: #f0ad4e;
}
.progress-striped .progress-bar-warning {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
}
.progress-bar-danger {
background-color: #d9534f;
}
.progress-striped .progress-bar-danger {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
}
.media {
margin-top: 15px;
}
.media:first-child {
margin-top: 0;
}
.media,
.media-body {
zoom: 1;
overflow: hidden;
}
.media-body {
width: 10000px;
}
.media-object {
display: block;
}
.media-object.img-thumbnail {
max-width: none;
}
.media-right,
.media > .pull-right {
padding-left: 10px;
}
.media-left,
.media > .pull-left {
padding-right: 10px;
}
.media-left,
.media-right,
.media-body {
display: table-cell;
vertical-align: top;
}
.media-middle {
vertical-align: middle;
}
.media-bottom {
vertical-align: bottom;
}
.media-heading {
margin-top: 0;
margin-bottom: 5px;
}
.media-list {
padding-left: 0;
list-style: none;
}
.list-group {
margin-bottom: 20px;
padding-left: 0;
}
.list-group-item {
position: relative;
display: block;
padding: 10px 15px;
margin-bottom: -1px;
background-color: #ffffff;
border: 1px solid #dddddd;
}
.list-group-item:first-child {
border-top-right-radius: 3px;
border-top-left-radius: 3px;
}
.list-group-item:last-child {
margin-bottom: 0;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
a.list-group-item,
button.list-group-item {
color: #555555;
}
a.list-group-item .list-group-item-heading,
button.list-group-item .list-group-item-heading {
color: #333333;
}
a.list-group-item:hover,
button.list-group-item:hover,
a.list-group-item:focus,
button.list-group-item:focus {
text-decoration: none;
color: #555555;
background-color: #f5f5f5;
}
button.list-group-item {
width: 100%;
text-align: left;
}
.list-group-item.disabled,
.list-group-item.disabled:hover,
.list-group-item.disabled:focus {
background-color: #eeeeee;
color: #777777;
cursor: not-allowed;
}
.list-group-item.disabled .list-group-item-heading,
.list-group-item.disabled:hover .list-group-item-heading,
.list-group-item.disabled:focus .list-group-item-heading {
color: inherit;
}
.list-group-item.disabled .list-group-item-text,
.list-group-item.disabled:hover .list-group-item-text,
.list-group-item.disabled:focus .list-group-item-text {
color: #777777;
}
.list-group-item.active,
.list-group-item.active:hover,
.list-group-item.active:focus {
z-index: 2;
color: #ffffff;
background-color: #009dd3;
border-color: #009dd3;
}
.list-group-item.active .list-group-item-heading,
.list-group-item.active:hover .list-group-item-heading,
.list-group-item.active:focus .list-group-item-heading,
.list-group-item.active .list-group-item-heading > small,
.list-group-item.active:hover .list-group-item-heading > small,
.list-group-item.active:focus .list-group-item-heading > small,
.list-group-item.active .list-group-item-heading > .small,
.list-group-item.active:hover .list-group-item-heading > .small,
.list-group-item.active:focus .list-group-item-heading > .small {
color: inherit;
}
.list-group-item.active .list-group-item-text,
.list-group-item.active:hover .list-group-item-text,
.list-group-item.active:focus .list-group-item-text {
color: #a0e7ff;
}
.list-group-item-success {
color: #3c763d;
background-color: #dff0d8;
}
a.list-group-item-success,
button.list-group-item-success {
color: #3c763d;
}
a.list-group-item-success .list-group-item-heading,
button.list-group-item-success .list-group-item-heading {
color: inherit;
}
a.list-group-item-success:hover,
button.list-group-item-success:hover,
a.list-group-item-success:focus,
button.list-group-item-success:focus {
color: #3c763d;
background-color: #d0e9c6;
}
a.list-group-item-success.active,
button.list-group-item-success.active,
a.list-group-item-success.active:hover,
button.list-group-item-success.active:hover,
a.list-group-item-success.active:focus,
button.list-group-item-success.active:focus {
color: #fff;
background-color: #3c763d;
border-color: #3c763d;
}
.list-group-item-info {
color: #31708f;
background-color: #d9edf7;
}
a.list-group-item-info,
button.list-group-item-info {
color: #31708f;
}
a.list-group-item-info .list-group-item-heading,
button.list-group-item-info .list-group-item-heading {
color: inherit;
}
a.list-group-item-info:hover,
button.list-group-item-info:hover,
a.list-group-item-info:focus,
button.list-group-item-info:focus {
color: #31708f;
background-color: #c4e3f3;
}
a.list-group-item-info.active,
button.list-group-item-info.active,
a.list-group-item-info.active:hover,
button.list-group-item-info.active:hover,
a.list-group-item-info.active:focus,
button.list-group-item-info.active:focus {
color: #fff;
background-color: #31708f;
border-color: #31708f;
}
.list-group-item-warning {
color: #8a6d3b;
background-color: #fcf8e3;
}
a.list-group-item-warning,
button.list-group-item-warning {
color: #8a6d3b;
}
a.list-group-item-warning .list-group-item-heading,
button.list-group-item-warning .list-group-item-heading {
color: inherit;
}
a.list-group-item-warning:hover,
button.list-group-item-warning:hover,
a.list-group-item-warning:focus,
button.list-group-item-warning:focus {
color: #8a6d3b;
background-color: #faf2cc;
}
a.list-group-item-warning.active,
button.list-group-item-warning.active,
a.list-group-item-warning.active:hover,
button.list-group-item-warning.active:hover,
a.list-group-item-warning.active:focus,
button.list-group-item-warning.active:focus {
color: #fff;
background-color: #8a6d3b;
border-color: #8a6d3b;
}
.list-group-item-danger {
color: #a94442;
background-color: #f2dede;
}
a.list-group-item-danger,
button.list-group-item-danger {
color: #a94442;
}
a.list-group-item-danger .list-group-item-heading,
button.list-group-item-danger .list-group-item-heading {
color: inherit;
}
a.list-group-item-danger:hover,
button.list-group-item-danger:hover,
a.list-group-item-danger:focus,
button.list-group-item-danger:focus {
color: #a94442;
background-color: #ebcccc;
}
a.list-group-item-danger.active,
button.list-group-item-danger.active,
a.list-group-item-danger.active:hover,
button.list-group-item-danger.active:hover,
a.list-group-item-danger.active:focus,
button.list-group-item-danger.active:focus {
color: #fff;
background-color: #a94442;
border-color: #a94442;
}
.list-group-item-heading {
margin-top: 0;
margin-bottom: 5px;
}
.list-group-item-text {
margin-bottom: 0;
line-height: 1.3;
}
.panel {
margin-bottom: 26px;
background-color: #ffffff;
border: 1px solid transparent;
border-radius: 3px;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
}
.panel-body {
padding: 15px;
}
.panel-heading {
padding: 10px 15px;
border-bottom: 1px solid transparent;
border-top-right-radius: 2px;
border-top-left-radius: 2px;
}
.panel-heading > .dropdown .dropdown-toggle {
color: inherit;
}
.panel-title {
margin-top: 0;
margin-bottom: 0;
font-size: 18px;
color: inherit;
}
.panel-title > a,
.panel-title > small,
.panel-title > .small,
.panel-title > small > a,
.panel-title > .small > a {
color: inherit;
}
.panel-footer {
padding: 10px 15px;
background-color: #f5f5f5;
border-top: 1px solid #dddddd;
border-bottom-right-radius: 2px;
border-bottom-left-radius: 2px;
}
.panel > .list-group,
.panel > .panel-collapse > .list-group {
margin-bottom: 0;
}
.panel > .list-group .list-group-item,
.panel > .panel-collapse > .list-group .list-group-item {
border-width: 1px 0;
border-radius: 0;
}
.panel > .list-group:first-child .list-group-item:first-child,
.panel > .panel-collapse > .list-group:first-child .list-group-item:first-child {
border-top: 0;
border-top-right-radius: 2px;
border-top-left-radius: 2px;
}
.panel > .list-group:last-child .list-group-item:last-child,
.panel > .panel-collapse > .list-group:last-child .list-group-item:last-child {
border-bottom: 0;
border-bottom-right-radius: 2px;
border-bottom-left-radius: 2px;
}
.panel > .panel-heading + .panel-collapse > .list-group .list-group-item:first-child {
border-top-right-radius: 0;
border-top-left-radius: 0;
}
.panel-heading + .list-group .list-group-item:first-child {
border-top-width: 0;
}
.list-group + .panel-footer {
border-top-width: 0;
}
.panel > .table,
.panel > .table-responsive > .table,
.panel > .panel-collapse > .table {
margin-bottom: 0;
}
.panel > .table caption,
.panel > .table-responsive > .table caption,
.panel > .panel-collapse > .table caption {
padding-left: 15px;
padding-right: 15px;
}
.panel > .table:first-child,
.panel > .table-responsive:first-child > .table:first-child {
border-top-right-radius: 2px;
border-top-left-radius: 2px;
}
.panel > .table:first-child > thead:first-child > tr:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child {
border-top-left-radius: 2px;
border-top-right-radius: 2px;
}
.panel > .table:first-child > thead:first-child > tr:first-child td:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child td:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:first-child,
.panel > .table:first-child > thead:first-child > tr:first-child th:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child th:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:first-child {
border-top-left-radius: 2px;
}
.panel > .table:first-child > thead:first-child > tr:first-child td:last-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:last-child,
.panel > .table:first-child > tbody:first-child > tr:first-child td:last-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:last-child,
.panel > .table:first-child > thead:first-child > tr:first-child th:last-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:last-child,
.panel > .table:first-child > tbody:first-child > tr:first-child th:last-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:last-child {
border-top-right-radius: 2px;
}
.panel > .table:last-child,
.panel > .table-responsive:last-child > .table:last-child {
border-bottom-right-radius: 2px;
border-bottom-left-radius: 2px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child {
border-bottom-left-radius: 2px;
border-bottom-right-radius: 2px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child td:first-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:first-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
.panel > .table:last-child > tbody:last-child > tr:last-child th:first-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:first-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child th:first-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:first-child {
border-bottom-left-radius: 2px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child td:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
.panel > .table:last-child > tbody:last-child > tr:last-child th:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child th:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:last-child {
border-bottom-right-radius: 2px;
}
.panel > .panel-body + .table,
.panel > .panel-body + .table-responsive,
.panel > .table + .panel-body,
.panel > .table-responsive + .panel-body {
border-top: 1px solid #dddddd;
}
.panel > .table > tbody:first-child > tr:first-child th,
.panel > .table > tbody:first-child > tr:first-child td {
border-top: 0;
}
.panel > .table-bordered,
.panel > .table-responsive > .table-bordered {
border: 0;
}
.panel > .table-bordered > thead > tr > th:first-child,
.panel > .table-responsive > .table-bordered > thead > tr > th:first-child,
.panel > .table-bordered > tbody > tr > th:first-child,
.panel > .table-responsive > .table-bordered > tbody > tr > th:first-child,
.panel > .table-bordered > tfoot > tr > th:first-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > th:first-child,
.panel > .table-bordered > thead > tr > td:first-child,
.panel > .table-responsive > .table-bordered > thead > tr > td:first-child,
.panel > .table-bordered > tbody > tr > td:first-child,
.panel > .table-responsive > .table-bordered > tbody > tr > td:first-child,
.panel > .table-bordered > tfoot > tr > td:first-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > td:first-child {
border-left: 0;
}
.panel > .table-bordered > thead > tr > th:last-child,
.panel > .table-responsive > .table-bordered > thead > tr > th:last-child,
.panel > .table-bordered > tbody > tr > th:last-child,
.panel > .table-responsive > .table-bordered > tbody > tr > th:last-child,
.panel > .table-bordered > tfoot > tr > th:last-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > th:last-child,
.panel > .table-bordered > thead > tr > td:last-child,
.panel > .table-responsive > .table-bordered > thead > tr > td:last-child,
.panel > .table-bordered > tbody > tr > td:last-child,
.panel > .table-responsive > .table-bordered > tbody > tr > td:last-child,
.panel > .table-bordered > tfoot > tr > td:last-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > td:last-child {
border-right: 0;
}
.panel > .table-bordered > thead > tr:first-child > td,
.panel > .table-responsive > .table-bordered > thead > tr:first-child > td,
.panel > .table-bordered > tbody > tr:first-child > td,
.panel > .table-responsive > .table-bordered > tbody > tr:first-child > td,
.panel > .table-bordered > thead > tr:first-child > th,
.panel > .table-responsive > .table-bordered > thead > tr:first-child > th,
.panel > .table-bordered > tbody > tr:first-child > th,
.panel > .table-responsive > .table-bordered > tbody > tr:first-child > th {
border-bottom: 0;
}
.panel > .table-bordered > tbody > tr:last-child > td,
.panel > .table-responsive > .table-bordered > tbody > tr:last-child > td,
.panel > .table-bordered > tfoot > tr:last-child > td,
.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > td,
.panel > .table-bordered > tbody > tr:last-child > th,
.panel > .table-responsive > .table-bordered > tbody > tr:last-child > th,
.panel > .table-bordered > tfoot > tr:last-child > th,
.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > th {
border-bottom: 0;
}
.panel > .table-responsive {
border: 0;
margin-bottom: 0;
}
.panel-group {
margin-bottom: 26px;
}
.panel-group .panel {
margin-bottom: 0;
border-radius: 3px;
}
.panel-group .panel + .panel {
margin-top: 5px;
}
.panel-group .panel-heading {
border-bottom: 0;
}
.panel-group .panel-heading + .panel-collapse > .panel-body,
.panel-group .panel-heading + .panel-collapse > .list-group {
border-top: 1px solid #dddddd;
}
.panel-group .panel-footer {
border-top: 0;
}
.panel-group .panel-footer + .panel-collapse .panel-body {
border-bottom: 1px solid #dddddd;
}
.panel-default {
border-color: #dddddd;
}
.panel-default > .panel-heading {
color: #333333;
background-color: #f5f5f5;
border-color: #dddddd;
}
.panel-default > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #dddddd;
}
.panel-default > .panel-heading .badge {
color: #f5f5f5;
background-color: #333333;
}
.panel-default > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #dddddd;
}
.panel-primary {
border-color: #009dd3;
}
.panel-primary > .panel-heading {
color: #ffffff;
background-color: #009dd3;
border-color: #009dd3;
}
.panel-primary > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #009dd3;
}
.panel-primary > .panel-heading .badge {
color: #009dd3;
background-color: #ffffff;
}
.panel-primary > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #009dd3;
}
.panel-success {
border-color: #d6e9c6;
}
.panel-success > .panel-heading {
color: #3c763d;
background-color: #dff0d8;
border-color: #d6e9c6;
}
.panel-success > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #d6e9c6;
}
.panel-success > .panel-heading .badge {
color: #dff0d8;
background-color: #3c763d;
}
.panel-success > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #d6e9c6;
}
.panel-info {
border-color: #bce8f1;
}
.panel-info > .panel-heading {
color: #31708f;
background-color: #d9edf7;
border-color: #bce8f1;
}
.panel-info > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #bce8f1;
}
.panel-info > .panel-heading .badge {
color: #d9edf7;
background-color: #31708f;
}
.panel-info > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #bce8f1;
}
.panel-warning {
border-color: #faebcc;
}
.panel-warning > .panel-heading {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #faebcc;
}
.panel-warning > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #faebcc;
}
.panel-warning > .panel-heading .badge {
color: #fcf8e3;
background-color: #8a6d3b;
}
.panel-warning > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #faebcc;
}
.panel-danger {
border-color: #ebccd1;
}
.panel-danger > .panel-heading {
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;
}
.panel-danger > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #ebccd1;
}
.panel-danger > .panel-heading .badge {
color: #f2dede;
background-color: #a94442;
}
.panel-danger > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #ebccd1;
}
.embed-responsive {
position: relative;
display: block;
height: 0;
padding: 0;
overflow: hidden;
}
.embed-responsive .embed-responsive-item,
.embed-responsive iframe,
.embed-responsive embed,
.embed-responsive object,
.embed-responsive video {
position: absolute;
top: 0;
left: 0;
bottom: 0;
height: 100%;
width: 100%;
border: 0;
}
.embed-responsive-16by9 {
padding-bottom: 56.25%;
}
.embed-responsive-4by3 {
padding-bottom: 75%;
}
.well {
min-height: 20px;
padding: 19px;
margin-bottom: 20px;
background-color: #f5f5f5;
border: 1px solid #e3e3e3;
border-radius: 3px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
}
.well blockquote {
border-color: #ddd;
border-color: rgba(0, 0, 0, 0.15);
}
.well-lg {
padding: 24px;
border-radius: 6px;
}
.well-sm {
padding: 9px;
border-radius: 3px;
}
.close {
float: right;
font-size: 24px;
font-weight: bold;
line-height: 1;
color: #000000;
text-shadow: 0 1px 0 #ffffff;
opacity: 0.2;
filter: alpha(opacity=20);
}
.close:hover,
.close:focus {
color: #000000;
text-decoration: none;
cursor: pointer;
opacity: 0.5;
filter: alpha(opacity=50);
}
button.close {
padding: 0;
cursor: pointer;
background: transparent;
border: 0;
-webkit-appearance: none;
}
.modal-open {
overflow: hidden;
}
.modal {
display: none;
overflow: hidden;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1050;
-webkit-overflow-scrolling: touch;
outline: 0;
}
.modal.fade .modal-dialog {
-webkit-transform: translate(0, -25%);
-ms-transform: translate(0, -25%);
-o-transform: translate(0, -25%);
transform: translate(0, -25%);
-webkit-transition: -webkit-transform 0.3s ease-out;
-o-transition: -o-transform 0.3s ease-out;
transition: transform 0.3s ease-out;
}
.modal.in .modal-dialog {
-webkit-transform: translate(0, 0);
-ms-transform: translate(0, 0);
-o-transform: translate(0, 0);
transform: translate(0, 0);
}
.modal-open .modal {
overflow-x: hidden;
overflow-y: auto;
}
.modal-dialog {
position: relative;
width: auto;
margin: 10px;
}
.modal-content {
position: relative;
background-color: #ffffff;
border: 1px solid #999999;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 6px;
-webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
-webkit-background-clip: padding-box;
background-clip: padding-box;
outline: 0;
}
.modal-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1040;
background-color: #000000;
}
.modal-backdrop.fade {
opacity: 0;
filter: alpha(opacity=0);
}
.modal-backdrop.in {
opacity: 0.5;
filter: alpha(opacity=50);
}
.modal-header {
padding: 15px;
border-bottom: 1px solid #e5e5e5;
}
.modal-header .close {
margin-top: -2px;
}
.modal-title {
margin: 0;
line-height: 1.625;
}
.modal-body {
position: relative;
padding: 15px;
}
.modal-footer {
padding: 15px;
text-align: right;
border-top: 1px solid #e5e5e5;
}
.modal-footer .btn + .btn {
margin-left: 5px;
margin-bottom: 0;
}
.modal-footer .btn-group .btn + .btn {
margin-left: -1px;
}
.modal-footer .btn-block + .btn-block {
margin-left: 0;
}
.modal-scrollbar-measure {
position: absolute;
top: -9999px;
width: 50px;
height: 50px;
overflow: scroll;
}
@media (min-width: 768px) {
.modal-dialog {
width: 600px;
margin: 30px auto;
}
.modal-content {
-webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
}
.modal-sm {
width: 300px;
}
}
@media (min-width: 992px) {
.modal-lg {
width: 900px;
}
}
.tooltip {
position: absolute;
z-index: 1070;
display: block;
font-family: "FranklinGothic-Book", Helvetica, Arial, sans-serif;
font-style: normal;
font-weight: normal;
letter-spacing: normal;
line-break: auto;
line-height: 1.625;
text-align: left;
text-align: start;
text-decoration: none;
text-shadow: none;
text-transform: none;
white-space: normal;
word-break: normal;
word-spacing: normal;
word-wrap: normal;
font-size: 11px;
opacity: 0;
filter: alpha(opacity=0);
}
.tooltip.in {
opacity: 0.9;
filter: alpha(opacity=90);
}
.tooltip.top {
margin-top: -3px;
padding: 5px 0;
}
.tooltip.right {
margin-left: 3px;
padding: 0 5px;
}
.tooltip.bottom {
margin-top: 3px;
padding: 5px 0;
}
.tooltip.left {
margin-left: -3px;
padding: 0 5px;
}
.tooltip-inner {
max-width: 200px;
padding: 3px 8px;
color: #ffffff;
text-align: center;
background-color: #000000;
border-radius: 3px;
}
.tooltip-arrow {
position: absolute;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
.tooltip.top .tooltip-arrow {
bottom: 0;
left: 50%;
margin-left: -5px;
border-width: 5px 5px 0;
border-top-color: #000000;
}
.tooltip.top-left .tooltip-arrow {
bottom: 0;
right: 5px;
margin-bottom: -5px;
border-width: 5px 5px 0;
border-top-color: #000000;
}
.tooltip.top-right .tooltip-arrow {
bottom: 0;
left: 5px;
margin-bottom: -5px;
border-width: 5px 5px 0;
border-top-color: #000000;
}
.tooltip.right .tooltip-arrow {
top: 50%;
left: 0;
margin-top: -5px;
border-width: 5px 5px 5px 0;
border-right-color: #000000;
}
.tooltip.left .tooltip-arrow {
top: 50%;
right: 0;
margin-top: -5px;
border-width: 5px 0 5px 5px;
border-left-color: #000000;
}
.tooltip.bottom .tooltip-arrow {
top: 0;
left: 50%;
margin-left: -5px;
border-width: 0 5px 5px;
border-bottom-color: #000000;
}
.tooltip.bottom-left .tooltip-arrow {
top: 0;
right: 5px;
margin-top: -5px;
border-width: 0 5px 5px;
border-bottom-color: #000000;
}
.tooltip.bottom-right .tooltip-arrow {
top: 0;
left: 5px;
margin-top: -5px;
border-width: 0 5px 5px;
border-bottom-color: #000000;
}
.popover {
position: absolute;
top: 0;
left: 0;
z-index: 1060;
display: none;
max-width: 276px;
padding: 1px;
font-family: "FranklinGothic-Book", Helvetica, Arial, sans-serif;
font-style: normal;
font-weight: normal;
letter-spacing: normal;
line-break: auto;
line-height: 1.625;
text-align: left;
text-align: start;
text-decoration: none;
text-shadow: none;
text-transform: none;
white-space: normal;
word-break: normal;
word-spacing: normal;
word-wrap: normal;
font-size: 16px;
background-color: #ffffff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #cccccc;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 6px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
}
.popover.top {
margin-top: -10px;
}
.popover.right {
margin-left: 10px;
}
.popover.bottom {
margin-top: 10px;
}
.popover.left {
margin-left: -10px;
}
.popover-title {
margin: 0;
padding: 8px 14px;
font-size: 16px;
background-color: #f7f7f7;
border-bottom: 1px solid #ebebeb;
border-radius: 5px 5px 0 0;
}
.popover-content {
padding: 9px 14px;
}
.popover > .arrow,
.popover > .arrow:after {
position: absolute;
display: block;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
.popover > .arrow {
border-width: 11px;
}
.popover > .arrow:after {
border-width: 10px;
content: "";
}
.popover.top > .arrow {
left: 50%;
margin-left: -11px;
border-bottom-width: 0;
border-top-color: #999999;
border-top-color: rgba(0, 0, 0, 0.25);
bottom: -11px;
}
.popover.top > .arrow:after {
content: " ";
bottom: 1px;
margin-left: -10px;
border-bottom-width: 0;
border-top-color: #ffffff;
}
.popover.right > .arrow {
top: 50%;
left: -11px;
margin-top: -11px;
border-left-width: 0;
border-right-color: #999999;
border-right-color: rgba(0, 0, 0, 0.25);
}
.popover.right > .arrow:after {
content: " ";
left: 1px;
bottom: -10px;
border-left-width: 0;
border-right-color: #ffffff;
}
.popover.bottom > .arrow {
left: 50%;
margin-left: -11px;
border-top-width: 0;
border-bottom-color: #999999;
border-bottom-color: rgba(0, 0, 0, 0.25);
top: -11px;
}
.popover.bottom > .arrow:after {
content: " ";
top: 1px;
margin-left: -10px;
border-top-width: 0;
border-bottom-color: #ffffff;
}
.popover.left > .arrow {
top: 50%;
right: -11px;
margin-top: -11px;
border-right-width: 0;
border-left-color: #999999;
border-left-color: rgba(0, 0, 0, 0.25);
}
.popover.left > .arrow:after {
content: " ";
right: 1px;
border-right-width: 0;
border-left-color: #ffffff;
bottom: -10px;
}
.carousel {
position: relative;
}
.carousel-inner {
position: relative;
overflow: hidden;
width: 100%;
}
.carousel-inner > .item {
display: none;
position: relative;
-webkit-transition: 0.6s ease-in-out left;
-o-transition: 0.6s ease-in-out left;
transition: 0.6s ease-in-out left;
}
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
line-height: 1;
}
@media all and (transform-3d), (-webkit-transform-3d) {
.carousel-inner > .item {
-webkit-transition: -webkit-transform 0.6s ease-in-out;
-o-transition: -o-transform 0.6s ease-in-out;
transition: transform 0.6s ease-in-out;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
-webkit-perspective: 1000px;
perspective: 1000px;
}
.carousel-inner > .item.next,
.carousel-inner > .item.active.right {
-webkit-transform: translate3d(100%, 0, 0);
transform: translate3d(100%, 0, 0);
left: 0;
}
.carousel-inner > .item.prev,
.carousel-inner > .item.active.left {
-webkit-transform: translate3d(-100%, 0, 0);
transform: translate3d(-100%, 0, 0);
left: 0;
}
.carousel-inner > .item.next.left,
.carousel-inner > .item.prev.right,
.carousel-inner > .item.active {
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
left: 0;
}
}
.carousel-inner > .active,
.carousel-inner > .next,
.carousel-inner > .prev {
display: block;
}
.carousel-inner > .active {
left: 0;
}
.carousel-inner > .next,
.carousel-inner > .prev {
position: absolute;
top: 0;
width: 100%;
}
.carousel-inner > .next {
left: 100%;
}
.carousel-inner > .prev {
left: -100%;
}
.carousel-inner > .next.left,
.carousel-inner > .prev.right {
left: 0;
}
.carousel-inner > .active.left {
left: -100%;
}
.carousel-inner > .active.right {
left: 100%;
}
.carousel-control {
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 15%;
opacity: 0.5;
filter: alpha(opacity=50);
font-size: 20px;
color: #ffffff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
background-color: rgba(0, 0, 0, 0);
}
.carousel-control.left {
background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0.0001) 100%);
background-image: -o-linear-gradient(left, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0.0001) 100%);
background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, 0.5)), to(rgba(0, 0, 0, 0.0001)));
background-image: linear-gradient(to right, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0.0001) 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
}
.carousel-control.right {
left: auto;
right: 0;
background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, 0.0001) 0%, rgba(0, 0, 0, 0.5) 100%);
background-image: -o-linear-gradient(left, rgba(0, 0, 0, 0.0001) 0%, rgba(0, 0, 0, 0.5) 100%);
background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, 0.0001)), to(rgba(0, 0, 0, 0.5)));
background-image: linear-gradient(to right, rgba(0, 0, 0, 0.0001) 0%, rgba(0, 0, 0, 0.5) 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
}
.carousel-control:hover,
.carousel-control:focus {
outline: 0;
color: #ffffff;
text-decoration: none;
opacity: 0.9;
filter: alpha(opacity=90);
}
.carousel-control .icon-prev,
.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right {
position: absolute;
top: 50%;
margin-top: -10px;
z-index: 5;
display: inline-block;
}
.carousel-control .icon-prev,
.carousel-control .glyphicon-chevron-left {
left: 50%;
margin-left: -10px;
}
.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-right {
right: 50%;
margin-right: -10px;
}
.carousel-control .icon-prev,
.carousel-control .icon-next {
width: 20px;
height: 20px;
line-height: 1;
font-family: serif;
}
.carousel-control .icon-prev:before {
content: '\2039';
}
.carousel-control .icon-next:before {
content: '\203a';
}
.carousel-indicators {
position: absolute;
bottom: 10px;
left: 50%;
z-index: 15;
width: 60%;
margin-left: -30%;
padding-left: 0;
list-style: none;
text-align: center;
}
.carousel-indicators li {
display: inline-block;
width: 10px;
height: 10px;
margin: 1px;
text-indent: -999px;
border: 1px solid #ffffff;
border-radius: 10px;
cursor: pointer;
background-color: #000 \9;
background-color: rgba(0, 0, 0, 0);
}
.carousel-indicators .active {
margin: 0;
width: 12px;
height: 12px;
background-color: #ffffff;
}
.carousel-caption {
position: absolute;
left: 15%;
right: 15%;
bottom: 20px;
z-index: 10;
padding-top: 20px;
padding-bottom: 20px;
color: #ffffff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
}
.carousel-caption .btn {
text-shadow: none;
}
@media screen and (min-width: 768px) {
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right,
.carousel-control .icon-prev,
.carousel-control .icon-next {
width: 30px;
height: 30px;
margin-top: -10px;
font-size: 30px;
}
.carousel-control .glyphicon-chevron-left,
.carousel-control .icon-prev {
margin-left: -10px;
}
.carousel-control .glyphicon-chevron-right,
.carousel-control .icon-next {
margin-right: -10px;
}
.carousel-caption {
left: 20%;
right: 20%;
padding-bottom: 30px;
}
.carousel-indicators {
bottom: 20px;
}
}
.clearfix:before,
.clearfix:after,
.dl-horizontal dd:before,
.dl-horizontal dd:after,
.container:before,
.container:after,
.container-fluid:before,
.container-fluid:after,
.row:before,
.row:after,
.form-horizontal .form-group:before,
.form-horizontal .form-group:after,
.btn-toolbar:before,
.btn-toolbar:after,
.btn-group-vertical > .btn-group:before,
.btn-group-vertical > .btn-group:after,
.nav:before,
.nav:after,
.navbar:before,
.navbar:after,
.navbar-header:before,
.navbar-header:after,
.navbar-collapse:before,
.navbar-collapse:after,
.pager:before,
.pager:after,
.panel-body:before,
.panel-body:after,
.modal-header:before,
.modal-header:after,
.modal-footer:before,
.modal-footer:after {
content: " ";
display: table;
}
.clearfix:after,
.dl-horizontal dd:after,
.container:after,
.container-fluid:after,
.row:after,
.form-horizontal .form-group:after,
.btn-toolbar:after,
.btn-group-vertical > .btn-group:after,
.nav:after,
.navbar:after,
.navbar-header:after,
.navbar-collapse:after,
.pager:after,
.panel-body:after,
.modal-header:after,
.modal-footer:after {
clear: both;
}
.center-block {
display: block;
margin-left: auto;
margin-right: auto;
}
.pull-right {
float: right !important;
}
.pull-left {
float: left !important;
}
.hide {
display: none !important;
}
.show {
display: block !important;
}
.invisible {
visibility: hidden;
}
.text-hide {
font: 0/0 a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0;
}
.hidden {
display: none !important;
}
.affix {
position: fixed;
}
@-ms-viewport {
width: device-width;
}
.visible-xs,
.visible-sm,
.visible-md,
.visible-lg {
display: none !important;
}
.visible-xs-block,
.visible-xs-inline,
.visible-xs-inline-block,
.visible-sm-block,
.visible-sm-inline,
.visible-sm-inline-block,
.visible-md-block,
.visible-md-inline,
.visible-md-inline-block,
.visible-lg-block,
.visible-lg-inline,
.visible-lg-inline-block {
display: none !important;
}
@media (max-width: 767px) {
.visible-xs {
display: block !important;
}
table.visible-xs {
display: table !important;
}
tr.visible-xs {
display: table-row !important;
}
th.visible-xs,
td.visible-xs {
display: table-cell !important;
}
}
@media (max-width: 767px) {
.visible-xs-block {
display: block !important;
}
}
@media (max-width: 767px) {
.visible-xs-inline {
display: inline !important;
}
}
@media (max-width: 767px) {
.visible-xs-inline-block {
display: inline-block !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm {
display: block !important;
}
table.visible-sm {
display: table !important;
}
tr.visible-sm {
display: table-row !important;
}
th.visible-sm,
td.visible-sm {
display: table-cell !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-block {
display: block !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-inline {
display: inline !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-inline-block {
display: inline-block !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md {
display: block !important;
}
table.visible-md {
display: table !important;
}
tr.visible-md {
display: table-row !important;
}
th.visible-md,
td.visible-md {
display: table-cell !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-block {
display: block !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-inline {
display: inline !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-inline-block {
display: inline-block !important;
}
}
@media (min-width: 1200px) {
.visible-lg {
display: block !important;
}
table.visible-lg {
display: table !important;
}
tr.visible-lg {
display: table-row !important;
}
th.visible-lg,
td.visible-lg {
display: table-cell !important;
}
}
@media (min-width: 1200px) {
.visible-lg-block {
display: block !important;
}
}
@media (min-width: 1200px) {
.visible-lg-inline {
display: inline !important;
}
}
@media (min-width: 1200px) {
.visible-lg-inline-block {
display: inline-block !important;
}
}
@media (max-width: 767px) {
.hidden-xs {
display: none !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.hidden-sm {
display: none !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.hidden-md {
display: none !important;
}
}
@media (min-width: 1200px) {
.hidden-lg {
display: none !important;
}
}
.visible-print {
display: none !important;
}
@media print {
.visible-print {
display: block !important;
}
table.visible-print {
display: table !important;
}
tr.visible-print {
display: table-row !important;
}
th.visible-print,
td.visible-print {
display: table-cell !important;
}
}
.visible-print-block {
display: none !important;
}
@media print {
.visible-print-block {
display: block !important;
}
}
.visible-print-inline {
display: none !important;
}
@media print {
.visible-print-inline {
display: inline !important;
}
}
.visible-print-inline-block {
display: none !important;
}
@media print {
.visible-print-inline-block {
display: inline-block !important;
}
}
@media print {
.hidden-print {
display: none !important;
}
}
| apache-2.0 |
jeffvance/origin | pkg/build/admission/defaults/api/v1/types.go | 1882 | package v1
import (
kapi "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/unversioned"
buildapi "github.com/openshift/origin/pkg/build/api/v1"
)
// BuildDefaultsConfig controls the default information for Builds
type BuildDefaultsConfig struct {
unversioned.TypeMeta `json:",inline"`
// gitHTTPProxy is the location of the HTTPProxy for Git source
GitHTTPProxy string `json:"gitHTTPProxy,omitempty"`
// gitHTTPSProxy is the location of the HTTPSProxy for Git source
GitHTTPSProxy string `json:"gitHTTPSProxy,omitempty"`
// gitNoProxy is the list of domains for which the proxy should not be used
GitNoProxy string `json:"gitNoProxy,omitempty"`
// env is a set of default environment variables that will be applied to the
// build if the specified variables do not exist on the build
Env []kapi.EnvVar `json:"env,omitempty"`
// sourceStrategyDefaults are default values that apply to builds using the
// source strategy.
SourceStrategyDefaults *SourceStrategyDefaultsConfig `json:"sourceStrategyDefaults,omitempty"`
// imageLabels is a list of docker labels that are applied to the resulting image.
// User can override a default label by providing a label with the same name in their
// Build/BuildConfig.
ImageLabels []buildapi.ImageLabel `json:"imageLabels,omitempty"`
// nodeSelector is a selector which must be true for the build pod to fit on a node
NodeSelector map[string]string `json:"nodeSelector,omitempty"`
// annotations are annotations that will be added to the build pod
Annotations map[string]string `json:"annotations,omitempty"`
}
// SourceStrategyDefaultsConfig contains values that apply to builds using the
// source strategy.
type SourceStrategyDefaultsConfig struct {
// incremental indicates if s2i build strategies should perform an incremental
// build or not
Incremental *bool `json:"incremental,omitempty"`
}
| apache-2.0 |
AndroidX/androidx | room/integration-tests/testapp/src/androidTest/java/androidx/room/integration/testapp/test/RawQueryTest.java | 11077 | /*
* Copyright 2018 The Android Open Source Project
*
* 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 androidx.room.integration.testapp.test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static java.util.Collections.emptyList;
import androidx.arch.core.executor.testing.CountingTaskExecutorRule;
import androidx.lifecycle.LiveData;
import androidx.room.integration.testapp.dao.RawDao;
import androidx.room.integration.testapp.vo.NameAndLastName;
import androidx.room.integration.testapp.vo.Pet;
import androidx.room.integration.testapp.vo.User;
import androidx.room.integration.testapp.vo.UserAndAllPets;
import androidx.room.integration.testapp.vo.UserAndPet;
import androidx.sqlite.db.SimpleSQLiteQuery;
import androidx.sqlite.db.SupportSQLiteQuery;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@SmallTest
@RunWith(AndroidJUnit4.class)
public class RawQueryTest extends TestDatabaseTest {
@Rule
public CountingTaskExecutorRule mExecutorRule = new CountingTaskExecutorRule();
@Test
public void entity_null() {
User user = mRawDao.getUser(new SimpleSQLiteQuery("SELECT * FROM User WHERE mId = 0"));
assertThat(user, is(nullValue()));
}
@Test
public void entity_one() {
User expected = TestUtil.createUser(3);
mUserDao.insert(expected);
User received = mRawDao.getUser(new SimpleSQLiteQuery("SELECT * FROM User WHERE mId = ?",
new Object[]{3}));
assertThat(received, is(expected));
}
@Test
public void entity_list() {
List<User> expected = TestUtil.createUsersList(1, 2, 3, 4);
mUserDao.insertAll(expected.toArray(new User[4]));
List<User> received = mRawDao.getUserList(
new SimpleSQLiteQuery("SELECT * FROM User ORDER BY mId ASC"));
assertThat(received, is(expected));
}
@Test
public void entity_liveData_string() throws TimeoutException, InterruptedException {
SupportSQLiteQuery query = new SimpleSQLiteQuery(
"SELECT * FROM User WHERE mId = ?",
new Object[]{3}
);
liveDataTest(mRawDao.getUserLiveData(query));
}
@Test
public void entity_liveData_supportQuery() throws TimeoutException, InterruptedException {
liveDataTest(mRawDao.getUserLiveData(
new SimpleSQLiteQuery("SELECT * FROM User WHERE mId = ?", new Object[]{3})));
}
private void liveDataTest(
final LiveData<User> liveData) throws TimeoutException, InterruptedException {
InstrumentationRegistry.getInstrumentation().runOnMainSync(
() -> liveData.observeForever(user -> { }));
drain();
assertThat(liveData.getValue(), is(nullValue()));
User user = TestUtil.createUser(3);
mUserDao.insert(user);
drain();
assertThat(liveData.getValue(), is(user));
user.setLastName("cxZ");
mUserDao.insertOrReplace(user);
drain();
assertThat(liveData.getValue(), is(user));
}
@Test
public void entity_supportSql() {
User user = TestUtil.createUser(3);
mUserDao.insert(user);
SimpleSQLiteQuery query = new SimpleSQLiteQuery("SELECT * FROM User WHERE mId = ?",
new Object[]{3});
User received = mRawDao.getUser(query);
assertThat(received, is(user));
}
@Test
public void embedded() {
User user = TestUtil.createUser(3);
Pet[] pets = TestUtil.createPetsForUser(3, 1, 1);
mUserDao.insert(user);
mPetDao.insertAll(pets);
UserAndPet received = mRawDao.getUserAndPet(new SimpleSQLiteQuery(
"SELECT * FROM User, Pet WHERE User.mId = Pet.mUserId LIMIT 1"));
assertThat(received.getUser(), is(user));
assertThat(received.getPet(), is(pets[0]));
}
@Test
public void relation() {
User user = TestUtil.createUser(3);
mUserDao.insert(user);
Pet[] pets = TestUtil.createPetsForUser(3, 1, 10);
mPetDao.insertAll(pets);
UserAndAllPets result = mRawDao
.getUserAndAllPets(new SimpleSQLiteQuery("SELECT * FROM User WHERE mId = ?",
new Object[]{3}));
assertThat(result.user, is(user));
assertThat(result.pets, is(Arrays.asList(pets)));
}
@Test
public void pojo() {
User user = TestUtil.createUser(3);
mUserDao.insert(user);
NameAndLastName result =
mRawDao.getUserNameAndLastName(new SimpleSQLiteQuery("SELECT * FROM User"));
assertThat(result, is(new NameAndLastName(user.getName(), user.getLastName())));
}
@Test
public void pojo_supportSql() {
User user = TestUtil.createUser(3);
mUserDao.insert(user);
NameAndLastName result =
mRawDao.getUserNameAndLastNameWithObserved(new SimpleSQLiteQuery(
"SELECT * FROM User WHERE mId = ?",
new Object[]{3}
));
assertThat(result, is(new NameAndLastName(user.getName(), user.getLastName())));
}
@Test
public void pojo_typeConverter() {
User user = TestUtil.createUser(3);
mUserDao.insert(user);
RawDao.UserNameAndBirthday result = mRawDao.getUserAndBirthday(
new SimpleSQLiteQuery("SELECT mName, mBirthday FROM user LIMIT 1"));
assertThat(result.name, is(user.getName()));
assertThat(result.birthday, is(user.getBirthday()));
}
@Test
public void embedded_nullField() {
User user = TestUtil.createUser(3);
Pet[] pets = TestUtil.createPetsForUser(3, 1, 1);
mUserDao.insert(user);
mPetDao.insertAll(pets);
UserAndPet received = mRawDao.getUserAndPet(
new SimpleSQLiteQuery("SELECT * FROM User LIMIT 1"));
assertThat(received.getUser(), is(user));
assertThat(received.getPet(), is(nullValue()));
}
@Test
public void embedded_list() {
User[] users = TestUtil.createUsersArray(3, 5);
Pet[] pets = TestUtil.createPetsForUser(3, 1, 2);
mUserDao.insertAll(users);
mPetDao.insertAll(pets);
List<UserAndPet> received = mRawDao.getUserAndPetList(
new SimpleSQLiteQuery(
"SELECT * FROM User LEFT JOIN Pet ON (User.mId = Pet.mUserId)"
+ " ORDER BY mId ASC, mPetId ASC"));
assertThat(received.size(), is(3));
// row 0
assertThat(received.get(0).getUser(), is(users[0]));
assertThat(received.get(0).getPet(), is(pets[0]));
// row 1
assertThat(received.get(1).getUser(), is(users[0]));
assertThat(received.get(1).getPet(), is(pets[1]));
// row 2
assertThat(received.get(2).getUser(), is(users[1]));
assertThat(received.get(2).getPet(), is(nullValue()));
}
@Test
public void count() {
mUserDao.insertAll(TestUtil.createUsersArray(3, 5, 7, 10));
int count = mRawDao.count(new SimpleSQLiteQuery("SELECT COUNT(*) FROM User"));
assertThat(count, is(4));
}
@Test
public void embedded_liveData() throws TimeoutException, InterruptedException {
LiveData<List<UserAndPet>> liveData = mRawDao.getUserAndPetListObservable(
new SimpleSQLiteQuery("SELECT * FROM User LEFT JOIN Pet ON (User.mId = Pet.mUserId)"
+ " ORDER BY mId ASC, mPetId ASC"));
InstrumentationRegistry.getInstrumentation().runOnMainSync(
() -> liveData.observeForever(user -> {
})
);
drain();
assertThat(liveData.getValue(), is(emptyList()));
User[] users = TestUtil.createUsersArray(3, 5);
Pet[] pets = TestUtil.createPetsForUser(3, 1, 2);
mUserDao.insertAll(users);
drain();
List<UserAndPet> justUsers = liveData.getValue();
//noinspection ConstantConditions
assertThat(justUsers.size(), is(2));
assertThat(justUsers.get(0).getUser(), is(users[0]));
assertThat(justUsers.get(1).getUser(), is(users[1]));
assertThat(justUsers.get(0).getPet(), is(nullValue()));
assertThat(justUsers.get(1).getPet(), is(nullValue()));
mPetDao.insertAll(pets);
drain();
List<UserAndPet> allItems = liveData.getValue();
//noinspection ConstantConditions
assertThat(allItems.size(), is(3));
// row 0
assertThat(allItems.get(0).getUser(), is(users[0]));
assertThat(allItems.get(0).getPet(), is(pets[0]));
// row 1
assertThat(allItems.get(1).getUser(), is(users[0]));
assertThat(allItems.get(1).getPet(), is(pets[1]));
// row 2
assertThat(allItems.get(2).getUser(), is(users[1]));
assertThat(allItems.get(2).getPet(), is(nullValue()));
mDatabase.clearAllTables();
drain();
assertThat(liveData.getValue(), is(emptyList()));
}
@SuppressWarnings("ConstantConditions")
@Test
public void relation_liveData() throws TimeoutException, InterruptedException {
LiveData<UserAndAllPets> liveData = mRawDao
.getUserAndAllPetsObservable(
new SimpleSQLiteQuery("SELECT * FROM User WHERE mId = ?",
new Object[]{3}));
InstrumentationRegistry.getInstrumentation().runOnMainSync(
() -> liveData.observeForever(user -> {
})
);
drain();
User user = TestUtil.createUser(3);
mUserDao.insert(user);
drain();
assertThat(liveData.getValue().user, is(user));
assertThat(liveData.getValue().pets, is(emptyList()));
Pet[] pets = TestUtil.createPetsForUser(3, 1, 5);
mPetDao.insertAll(pets);
drain();
assertThat(liveData.getValue().user, is(user));
assertThat(liveData.getValue().pets, is(Arrays.asList(pets)));
}
private void drain() throws TimeoutException, InterruptedException {
mExecutorRule.drainTasks(1, TimeUnit.MINUTES);
}
}
| apache-2.0 |
minggLu/bigtop | bigtop_toolchain/bin/puppetize.sh | 2534 | #!/bin/bash
# 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.
# Use /etc/os-release to determine Linux Distro
if [ -f /etc/os-release ]; then
. /etc/os-release
else
if [ -f /etc/redhat-release ]; then
if grep "CentOS release 6" /etc/redhat-release >/dev/null ; then
ID=centos
VERSION_ID=6
fi
else
echo "Unknown Linux Distribution."
exit 1
fi
fi
case ${ID}-${VERSION_ID} in
fedora-20*)
# Work around issue in fedora:20 docker image
yum -y install yum-utils; yum-config-manager --enable updates-testing
rpm -ivh https://yum.puppetlabs.com/puppetlabs-release-fedora-20.noarch.rpm
yum update
yum -y install hostname curl sudo unzip wget puppet
;;
ubuntu-14.04)
# BIGTOP-2003. A workaround to install newer hiera to get rid of hiera 1.3.0 bug.
apt-get -y install wget
wget -O /tmp/puppetlabs-release-trusty.deb https://apt.puppetlabs.com/puppetlabs-release-trusty.deb && dpkg -i /tmp/puppetlabs-release-trusty.deb
rm -f /tmp/puppetlabs-release-trusty.deb
apt-get update
apt-get -y install curl sudo unzip puppet software-properties-common
;;
ubuntu-15*)
apt-get update
apt-get -y install curl sudo unzip wget puppet software-properties-common
;;
debian-8*)
apt-get update
apt-get -y install curl sudo unzip wget puppet
;;
opensuse-13.2)
zypper --gpg-auto-import-keys install -y curl sudo unzip wget puppet suse-release ca-certificates-mozilla net-tools tar
;;
centos-6*)
rpm -ivh http://yum.puppetlabs.com/puppetlabs-release-el-6.noarch.rpm
yum -y install curl sudo unzip wget puppet tar
;;
centos-7*)
rpm -ivh http://yum.puppetlabs.com/puppetlabs-release-el-7.noarch.rpm
yum -y install hostname curl sudo unzip wget puppet
;;
*)
echo "Unsupported OS ${ID}-${VERSION_ID}."
exit 1
esac
| apache-2.0 |
OSBI/oodt | workflow/src/main/java/org/apache/oodt/cas/workflow/engine/ThreadPoolWorkflowEngine.java | 15482 | /**
* 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.oodt.cas.workflow.engine;
//OODT imports
import org.apache.oodt.cas.metadata.Metadata;
import org.apache.oodt.cas.resource.system.XmlRpcResourceManagerClient;
import org.apache.oodt.cas.workflow.structs.Workflow;
import org.apache.oodt.cas.workflow.structs.WorkflowInstance;
import org.apache.oodt.cas.workflow.structs.WorkflowStatus;
import org.apache.oodt.cas.workflow.structs.WorkflowTask;
import org.apache.oodt.cas.workflow.structs.exceptions.EngineException;
import org.apache.oodt.cas.workflow.structs.exceptions.InstanceRepositoryException;
import org.apache.oodt.cas.workflow.engine.IterativeWorkflowProcessorThread;
import org.apache.oodt.cas.workflow.instrepo.WorkflowInstanceRepository;
import org.apache.oodt.commons.util.DateConvert;
//JDK imports
import java.net.URL;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
//java.util.concurrent imports
import EDU.oswego.cs.dl.util.concurrent.BoundedBuffer;
import EDU.oswego.cs.dl.util.concurrent.Channel;
import EDU.oswego.cs.dl.util.concurrent.LinkedQueue;
import EDU.oswego.cs.dl.util.concurrent.PooledExecutor;
/**
*
* The ThreadPooling portion of the WorkflowEngine. This class is meant to be an
* extension point for WorkflowEngines that want to implement ThreadPooling.
* This WorkflowEngine provides everything needed to manage a ThreadPool using
* Doug Lea's wonderful java.util.concurrent package that made it into JDK5.
*
* @author mattmann
* @version $Revsion$
*
*/
public class ThreadPoolWorkflowEngine implements WorkflowEngine, WorkflowStatus {
/* our thread pool */
private PooledExecutor pool = null;
/* our worker thread hash mapping worker threads to workflow instance ids */
private HashMap workerMap = null;
/* our log stream */
private static final Logger LOG = Logger
.getLogger(ThreadPoolWorkflowEngine.class.getName());
/* our instance repository */
private WorkflowInstanceRepository instRep = null;
/* our resource manager client */
private XmlRpcResourceManagerClient rClient = null;
/* the URL pointer to the parent Workflow Manager */
private URL wmgrUrl = null;
/**
* Default Constructor.
*
* @param instRep
* The WorkflowInstanceRepository to be used by this engine.
* @param queueSize
* The size of the queue that the workflow engine should use
* (irrelevant if unlimitedQueue is set to true)
* @param maxPoolSize
* The minimum thread pool size.
* @param minPoolSize
* The maximum thread pool size.
* @param threadKeepAliveTime
* The amount of minutes that each thread in the pool should be kept
* alive.
* @param unlimitedQueue
* Whether or not to use a queue whose bounds are dictated by the
* physical memory of the underlying hardware.
* @param resUrl
* A URL pointer to a resource manager. If this is set Tasks will be
* wrapped as Resource Manager {@link Job}s and sent through the
* Resource Manager. If this parameter is not set, local execution
* (the default) will be used
*/
public ThreadPoolWorkflowEngine(WorkflowInstanceRepository instRep,
int queueSize, int maxPoolSize, int minPoolSize,
long threadKeepAliveTime, boolean unlimitedQueue, URL resUrl) {
this.instRep = instRep;
Channel c = null;
if (unlimitedQueue) {
c = new LinkedQueue();
} else {
c = new BoundedBuffer(queueSize);
}
pool = new PooledExecutor(c, maxPoolSize);
pool.setMinimumPoolSize(minPoolSize);
pool.setKeepAliveTime(1000 * 60 * threadKeepAliveTime);
workerMap = new HashMap();
if (resUrl != null)
rClient = new XmlRpcResourceManagerClient(resUrl);
}
/*
* (non-Javadoc)
*
* @see
* org.apache.oodt.cas.workflow.engine.WorkflowEngine#pauseWorkflowInstance
* (java.lang.String)
*/
public synchronized void pauseWorkflowInstance(String workflowInstId) {
// okay, try and look up that worker thread in our hash map
IterativeWorkflowProcessorThread worker = (IterativeWorkflowProcessorThread) workerMap
.get(workflowInstId);
if (worker == null) {
LOG.log(Level.WARNING,
"WorkflowEngine: Attempt to pause workflow instance id: "
+ workflowInstId
+ ", however, this engine is not tracking its execution");
return;
}
// otherwise, all good
worker.pause();
}
/*
* (non-Javadoc)
*
* @see
* org.apache.oodt.cas.workflow.engine.WorkflowEngine#resumeWorkflowInstance
* (java.lang.String)
*/
public synchronized void resumeWorkflowInstance(String workflowInstId) {
// okay, try and look up that worker thread in our hash map
IterativeWorkflowProcessorThread worker = (IterativeWorkflowProcessorThread) workerMap
.get(workflowInstId);
if (worker == null) {
LOG.log(Level.WARNING,
"WorkflowEngine: Attempt to resume workflow instance id: "
+ workflowInstId + ", however, this engine is "
+ "not tracking its execution");
return;
}
// also check to make sure that the worker is currently paused
// only can resume WorkflowInstances that are paused, right?
if (!worker.isPaused()) {
LOG.log(Level.WARNING,
"WorkflowEngine: Attempt to resume a workflow that "
+ "isn't paused currently: instance id: " + workflowInstId);
return;
}
// okay, all good
worker.resume();
}
/*
* (non-Javadoc)
*
* @see
* org.apache.oodt.cas.workflow.engine.WorkflowEngine#startWorkflow(org.apache
* .oodt.cas.workflow.structs.Workflow, org.apache.oodt.cas.metadata.Metadata)
*/
public synchronized WorkflowInstance startWorkflow(Workflow workflow,
Metadata metadata) throws EngineException {
// to start the workflow, we create a default workflow instance
// populate it
// persist it
// add it to the worker map
// start it
WorkflowInstance wInst = new WorkflowInstance();
wInst.setWorkflow(workflow);
wInst.setCurrentTaskId(((WorkflowTask) workflow.getTasks().get(0))
.getTaskId());
wInst.setSharedContext(metadata);
wInst.setStatus(CREATED);
persistWorkflowInstance(wInst);
IterativeWorkflowProcessorThread worker = new IterativeWorkflowProcessorThread(
wInst, instRep, this.wmgrUrl);
worker.setRClient(rClient);
workerMap.put(wInst.getId(), worker);
wInst.setStatus(QUEUED);
persistWorkflowInstance(wInst);
try {
pool.execute(worker);
} catch (InterruptedException e) {
throw new EngineException(e);
}
return wInst;
}
/*
* (non-Javadoc)
*
* @see
* org.apache.oodt.cas.workflow.engine.WorkflowEngine#getInstanceRepository()
*/
public WorkflowInstanceRepository getInstanceRepository() {
return this.instRep;
}
/*
* (non-Javadoc)
*
* @see
* org.apache.oodt.cas.workflow.engine.WorkflowEngine#updateMetadata(java.
* lang.String, org.apache.oodt.cas.metadata.Metadata)
*/
public synchronized boolean updateMetadata(String workflowInstId, Metadata met) {
// okay, try and look up that worker thread in our hash map
IterativeWorkflowProcessorThread worker = (IterativeWorkflowProcessorThread) workerMap
.get(workflowInstId);
if (worker == null) {
LOG.log(Level.WARNING,
"WorkflowEngine: Attempt to update metadata context "
+ "for workflow instance id: " + workflowInstId
+ ", however, this engine is " + "not tracking its execution");
return false;
}
worker.getWorkflowInstance().setSharedContext(met);
try {
persistWorkflowInstance(worker.getWorkflowInstance());
} catch (Exception e) {
LOG.log(
Level.WARNING,
"Exception persisting workflow instance: ["
+ worker.getWorkflowInstance().getId() + "]: Message: "
+ e.getMessage());
return false;
}
return true;
}
/*
* (non-Javadoc)
*
* @see
* org.apache.oodt.cas.workflow.engine.WorkflowEngine#setWorkflowManagerUrl
* (java.net.URL)
*/
public void setWorkflowManagerUrl(URL url) {
this.wmgrUrl = url;
}
/*
* (non-Javadoc)
*
* @see
* org.apache.oodt.cas.workflow.engine.WorkflowEngine#stopWorkflow(java.lang
* .String)
*/
public synchronized void stopWorkflow(String workflowInstId) {
// okay, try and look up that worker thread in our hash map
IterativeWorkflowProcessorThread worker = (IterativeWorkflowProcessorThread) workerMap
.get(workflowInstId);
if (worker == null) {
LOG.log(Level.WARNING,
"WorkflowEngine: Attempt to stop workflow instance id: "
+ workflowInstId + ", however, this engine is "
+ "not tracking its execution");
return;
}
worker.stop();
}
/*
* (non-Javadoc)
*
* @see org.apache.oodt.cas.workflow.engine.WorkflowEngine#
* getCurrentTaskWallClockMinutes(java.lang.String)
*/
public double getCurrentTaskWallClockMinutes(String workflowInstId) {
// get the workflow instance that we're talking about
WorkflowInstance inst = safeGetWorkflowInstanceById(workflowInstId);
return getCurrentTaskWallClockMinutes(inst);
}
/*
* (non-Javadoc)
*
* @see
* org.apache.oodt.cas.workflow.engine.WorkflowEngine#getWorkflowInstanceMetadata
* (java.lang.String)
*/
public Metadata getWorkflowInstanceMetadata(String workflowInstId) {
// okay, try and look up that worker thread in our hash map
IterativeWorkflowProcessorThread worker = (IterativeWorkflowProcessorThread) workerMap
.get(workflowInstId);
if (worker == null) {
// try and get the metadata
// from the workflow instance repository (as it was persisted)
try {
WorkflowInstance inst = instRep.getWorkflowInstanceById(workflowInstId);
return inst.getSharedContext();
} catch (InstanceRepositoryException e) {
LOG.log(Level.FINEST, "WorkflowEngine: Attempt to get metadata "
+ "for workflow instance id: " + workflowInstId
+ ", however, this engine is "
+ "not tracking its execution and the id: [" + workflowInstId
+ "] " + "was never persisted to " + "the instance repository");
e.printStackTrace();
return new Metadata();
}
}
return worker.getWorkflowInstance().getSharedContext();
}
/*
* (non-Javadoc)
*
* @see
* org.apache.oodt.cas.workflow.engine.WorkflowEngine#getWallClockMinutes(
* java.lang.String)
*/
public double getWallClockMinutes(String workflowInstId) {
// get the workflow instance that we're talking about
WorkflowInstance inst = safeGetWorkflowInstanceById(workflowInstId);
return getWallClockMinutes(inst);
}
protected static double getWallClockMinutes(WorkflowInstance inst) {
if (inst == null) {
return 0.0;
}
Date currentDateOrStopTime = (inst.getEndDateTimeIsoStr() != null
&& !inst.getEndDateTimeIsoStr().equals("") && !inst
.getEndDateTimeIsoStr().equals("null")) ? safeDateConvert(inst
.getEndDateTimeIsoStr()) : new Date();
Date workflowStartDateTime = null;
if (inst.getStartDateTimeIsoStr() == null
|| (inst.getStartDateTimeIsoStr() != null && (inst
.getStartDateTimeIsoStr().equals("") || inst
.getStartDateTimeIsoStr().equals("null")))) {
return 0.0;
}
try {
workflowStartDateTime = DateConvert.isoParse(inst
.getStartDateTimeIsoStr());
} catch (ParseException e) {
return 0.0;
}
long diffMs = currentDateOrStopTime.getTime()
- workflowStartDateTime.getTime();
double diffSecs = (diffMs * 1.0 / 1000.0);
double diffMins = diffSecs / 60.0;
return diffMins;
}
protected static double getCurrentTaskWallClockMinutes(WorkflowInstance inst) {
if (inst == null) {
return 0.0;
}
Date currentDateOrStopTime = (inst.getCurrentTaskEndDateTimeIsoStr() != null
&& !inst.getCurrentTaskEndDateTimeIsoStr().equals("") && !inst
.getCurrentTaskEndDateTimeIsoStr().equals("null")) ? safeDateConvert(inst
.getCurrentTaskEndDateTimeIsoStr()) : new Date();
Date workflowTaskStartDateTime = null;
if (inst.getCurrentTaskStartDateTimeIsoStr() == null
|| (inst.getCurrentTaskStartDateTimeIsoStr() != null && (inst
.getCurrentTaskStartDateTimeIsoStr().equals("") || inst
.getCurrentTaskStartDateTimeIsoStr().equals("null")))) {
return 0.0;
}
try {
workflowTaskStartDateTime = DateConvert.isoParse(inst
.getCurrentTaskStartDateTimeIsoStr());
} catch (ParseException e) {
return 0.0;
}
// should never be in this state, so return 0
if (workflowTaskStartDateTime.after(currentDateOrStopTime)) {
LOG.log(
Level.WARNING,
"Start date time: ["
+ DateConvert.isoFormat(workflowTaskStartDateTime)
+ " of workflow inst [" + inst.getId() + "] is AFTER "
+ "End date time: ["
+ DateConvert.isoFormat(currentDateOrStopTime)
+ "] of workflow inst.");
return 0.0;
}
long diffMs = currentDateOrStopTime.getTime()
- workflowTaskStartDateTime.getTime();
double diffSecs = (diffMs * 1.0 / 1000.0);
double diffMins = diffSecs / 60.0;
return diffMins;
}
private synchronized void persistWorkflowInstance(WorkflowInstance wInst)
throws EngineException {
try {
if (wInst.getId() == null
|| (wInst.getId() != null && wInst.getId().equals(""))) {
// we have to persist it by adding it
// rather than updating it
instRep.addWorkflowInstance(wInst);
} else {
// persist by update
instRep.updateWorkflowInstance(wInst);
}
} catch (InstanceRepositoryException e) {
e.printStackTrace();
throw new EngineException(e.getMessage());
}
}
private WorkflowInstance safeGetWorkflowInstanceById(String workflowInstId) {
try {
return instRep.getWorkflowInstanceById(workflowInstId);
} catch (Exception e) {
return null;
}
}
private static Date safeDateConvert(String isoTimeStr) {
try {
return DateConvert.isoParse(isoTimeStr);
} catch (Exception ignore) {
ignore.printStackTrace();
return null;
}
}
} | apache-2.0 |
google/nearby-connections | connections/clients/windows/core_adapter.h | 13399 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef LOCATION_NEARBY_CONNECTIONS_WINDOWS_CORE_ADAPTER_H_
#define LOCATION_NEARBY_CONNECTIONS_WINDOWS_CORE_ADAPTER_H_
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
// todo(jfcarroll) This cannot remain. It exposes stuff the client doesn't need.
#include "connections/advertising_options.h"
#include "connections/connection_options.h"
#include "connections/discovery_options.h"
#include "connections/implementation/offline_service_controller.h"
#define DLL_EXPORT extern "C" __declspec(dllexport)
namespace location {
namespace nearby {
namespace connections {
class Core;
class ServiceControllerRouter;
namespace windows {
// Initizlizes a Core instance, providing the ServiceController factory from
// app side. If no factory is provided, it will initialize a new
// factory creating OffilineServiceController.
// Returns the instance handle to c# client.
DLL_EXPORT connections::Core *__stdcall InitCoreWithServiceControllerFactory(
std::function<connections::ServiceController *()> factory = []() {
return new connections::OfflineServiceController;
});
// Initializes a default Core instance.
// Returns the instance handle to c# client.
DLL_EXPORT Core *__stdcall InitCore(ServiceControllerRouter *router);
// Closes the core with stopping all endpoints, then free the memory.
DLL_EXPORT void __stdcall CloseCore(Core *pCore);
// Starts advertising an endpoint for a local app.
//
// service_id - An identifier to advertise your app to other endpoints.
// This can be an arbitrary string, so long as it uniquely
// identifies your service. A good default is to use your
// app's package name.
// advertising_options - The options for advertising.
// info - Connection parameters:
// > name - A human readable name for this endpoint, to appear on
// other devices.
// > listener - A callback notified when remote endpoints request a
// connection to this endpoint.
// callback - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK if advertising started successfully.
// Status::STATUS_ALREADY_ADVERTISING if the app is already advertising.
// Status::STATUS_OUT_OF_ORDER_API_CALL if the app is currently
// connected to remote endpoints; call StopAllEndpoints first.
DLL_EXPORT void __stdcall StartAdvertising(
Core *pCore, const char *service_id, AdvertisingOptions advertising_options,
connections::ConnectionRequestInfo info, ResultCallback callback);
// Stops advertising a local endpoint. Should be called after calling
// StartAdvertising, as soon as the application no longer needs to advertise
// itself or goes inactive. Payloads can still be sent to connected
// endpoints after advertising ends.
//
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK if none of the above errors occurred.
DLL_EXPORT void __stdcall StopAdvertising(Core *pCore, ResultCallback callback);
// Starts discovery for remote endpoints with the specified service ID.
//
// service_id - The ID for the service to be discovered, as specified in
// the corresponding call to StartAdvertising.
// listener - A callback notified when a remote endpoint is discovered.
// discovery_options - The options for discovery.
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK if discovery started successfully.
// Status::STATUS_ALREADY_DISCOVERING if the app is already
// discovering the specified service.
// Status::STATUS_OUT_OF_ORDER_API_CALL if the app is currently
// connected to remote endpoints; call StopAllEndpoints first.
DLL_EXPORT void __stdcall StartDiscovery(Core *pCore, const char *service_id,
DiscoveryOptions discovery_options,
DiscoveryListener listener,
ResultCallback callback);
// Stops discovery for remote endpoints, after a previous call to
// StartDiscovery, when the client no longer needs to discover endpoints or
// goes inactive. Payloads can still be sent to connected endpoints after
// discovery ends.
//
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK if none of the above errors occurred.
DLL_EXPORT void __stdcall StopDiscovery(connections::Core *pCore,
connections::ResultCallback callback);
// Invokes the discovery callback from a previous call to StartDiscovery()
// with the given endpoint info. The previous call to StartDiscovery() must
// have been passed ConnectionOptions with is_out_of_band_connection == true.
//
// service_id - The ID for the service to be discovered, as
// specified in the corresponding call to
// StartDiscovery().
// metadata - Metadata used in order to inject the endpoint.
// result_cb - to access the status of the operation when
// available.
// Possible status codes include:
// Status::kSuccess if endpoint injection was attempted.
// Status::kError if endpoint_id, endpoint_info, or
// remote_bluetooth_mac_address are malformed.
// Status::kOutOfOrderApiCall if the app is not discovering.
DLL_EXPORT void __stdcall InjectEndpoint(Core *pCore, char *service_id,
OutOfBandConnectionMetadata metadata,
ResultCallback callback);
// Sends a request to connect to a remote endpoint.
//
// endpoint_id - The identifier for the remote endpoint to which a
// connection request will be sent. Should match the value
// provided in a call to
// DiscoveryListener::endpoint_found_cb()
// info - Connection parameters:
// > name - A human readable name for the local endpoint, to appear on
// the remote endpoint.
// > listener - A callback notified when the remote endpoint sends a
// response to the connection request.
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK if the connection request was sent.
// Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT if the app already
// has a connection to the specified endpoint.
// Status::STATUS_RADIO_ERROR if we failed to connect because of an
// issue with Bluetooth/WiFi.
// Status::STATUS_ERROR if we failed to connect for any other reason.
DLL_EXPORT void __stdcall RequestConnection(
Core *pCore, const char *endpoint_id, ConnectionRequestInfo info,
ConnectionOptions connection_options, ResultCallback callback);
// Accepts a connection to a remote endpoint. This method must be called
// before Payloads can be exchanged with the remote endpoint.
//
// endpoint_id - The identifier for the remote endpoint. Should match the
// value provided in a call to
// ConnectionListener::onConnectionInitiated.
// listener - A callback for payloads exchanged with the remote endpoint.
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK if the connection request was accepted.
// Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT if the app already.
// has a connection to the specified endpoint.
DLL_EXPORT void __stdcall AcceptConnection(Core *pCore, const char *endpoint_id,
PayloadListener listener,
ResultCallback callback);
// Rejects a connection to a remote endpoint.
//
// endpoint_id - The identifier for the remote endpoint. Should match the
// value provided in a call to
// ConnectionListener::onConnectionInitiated().
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK} if the connection request was rejected.
// Status::STATUS_ALREADY_CONNECTED_TO_ENDPOINT} if the app already
// has a connection to the specified endpoint.
DLL_EXPORT void __stdcall RejectConnection(Core *pCore, const char *endpoint_id,
ResultCallback callback);
// Sends a Payload to a remote endpoint. Payloads can only be sent to remote
// endpoints once a notice of connection acceptance has been delivered via
// ConnectionListener::onConnectionResult().
//
// endpoint_ids - Array of remote endpoint identifiers for the to which the
// payload should be sent.
// payload - The Payload to be sent.
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OUT_OF_ORDER_API_CALL if the device has not first
// performed advertisement or discovery (to set the Strategy.)
// Status::STATUS_ENDPOINT_UNKNOWN if there's no active (or pending)
// connection to the remote endpoint.
// Status::STATUS_OK if none of the above errors occurred. Note that this
// indicates that Nearby Connections will attempt to send the Payload,
// but not that the send has successfully completed yet. Errors might
// still occur during transmission (and at different times for
// different endpoints), and will be delivered via
// PayloadCallback#onPayloadTransferUpdate.
DLL_EXPORT void __stdcall SendPayload(
Core *pCore, absl::Span<const std::string> endpoint_ids, Payload payload,
ResultCallback callback);
// Cancels a Payload currently in-flight to or from remote endpoint(s).
//
// payload_id - The identifier for the Payload to be canceled.
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK if none of the above errors occurred.
DLL_EXPORT void __stdcall CancelPayload(Core *pCore, int64_t payload_id,
ResultCallback callback);
// Disconnects from a remote endpoint. {@link Payload}s can no longer be sent
// to or received from the endpoint after this method is called.
//
// endpoint_id - The identifier for the remote endpoint to disconnect from.
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK - finished successfully.
DLL_EXPORT void __stdcall DisconnectFromEndpoint(Core *pCore, char *endpoint_id,
ResultCallback callback);
// Disconnects from, and removes all traces of, all connected and/or
// discovered endpoints. This call is expected to be preceded by a call to
// StopAdvertising or StartDiscovery as needed. After calling
// StopAllEndpoints, no further operations with remote endpoints will be
// possible until a new call to one of StartAdvertising() or StartDiscovery().
//
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK - finished successfully.
DLL_EXPORT void __stdcall StopAllEndpoints(Core *pCore,
ResultCallback callback);
// Sends a request to initiate connection bandwidth upgrade.
//
// endpoint_id - The identifier for the remote endpoint which will be
// switching to a higher connection data rate and possibly
// different wireless protocol. On success, calls
// ConnectionListener::bandwidth_changed_cb().
// result_cb - to access the status of the operation when available.
// Possible status codes include:
// Status::STATUS_OK - finished successfully.
DLL_EXPORT void __stdcall InitiateBandwidthUpgrade(Core *pCore,
char *endpoint_id,
ResultCallback callback);
// Gets the local endpoint generated by Nearby Connections.
DLL_EXPORT const char *__stdcall GetLocalEndpointId(Core *pCore);
// Initializes a default ServiceControllerRouter instance.
// Returns the instance handle to c# client.
DLL_EXPORT ServiceControllerRouter *__stdcall InitServiceControllerRouter();
// Close a ServiceControllerRouter instance.
DLL_EXPORT void __stdcall CloseServiceControllerRouter(
ServiceControllerRouter *pRouter);
} // namespace windows
} // namespace connections
} // namespace nearby
} // namespace location
#endif // LOCATION_NEARBY_CONNECTIONS_WINDOWS_CORE_ADAPTER_H_
| apache-2.0 |
OLIMEX/DIY-LAPTOP | SOFTWARE/A64-TERES/linux-a64/drivers/soc/allwinner/pm/standby/Makefile | 1793 | #makefile for standby.bin
always := standby.code
targets := standby.elf
GCOV_PROFILE=no
#use "-Os" flags.
#Don't use "-O2" flags.
KBUILD_CFLAGS := -g -c -nostdlib -march=armv7-a -D__LINUX_ARM_ARCH__=7 -marm -fno-unwind-tables -fno-asynchronous-unwind-tables -mlittle-endian -O2 -mno-unaligned-access
#Include the cur dir.
KBUILD_CPPFLAGS += -I.
LD_FLAGS = -static
LIBS =
INCLUDE = -I. \
-I$(KDIR)/include \
-I$(KDIR)/drivers/soc/allwinner/standby/include \
-I$(KDIR)/drivers/soc/allwinner/pm
subdir- += brom
$(obj)/brom.o : $(obj)/brom/resumes.code FORCE
obj-y += brom.o
standby-y := common.o \
standby_twi.o \
power/axp152_power.o \
power/axp192_power.o \
power/standby_power.o \
standby_clock.o \
standby_debug.o \
standby_divlib.o \
./../mem_divlibc.o \
./../mem_clk.o \
./../mem_timing.o \
./../mem_serial.o \
./../mem_printk.o \
main.o
standby-y := $(addprefix $(obj)/,$(standby-y))
$(obj)/standby.code: $(obj)/standby.elf FORCE
$(Q)$(CROSS_COMPILE)objcopy -O binary $(obj)/standby.elf $(obj)/standby.code
#$(call if_changed,objcopy)
rm -rf *.o $(obj)/./*.o
$(obj)/standby.elf: $(obj)/standby.xn $(standby-y)
$(Q)$(CROSS_COMPILE)ld -T $(obj)/standby.xn $(LD_FLAGS) $(LIBS) -EL $(standby-y) -o $(obj)/standby.elf -Map $(obj)/standby.map
$(Q)$(CROSS_COMPILE)objdump -D $(obj)/standby.elf > $(obj)/standby.lst
#$(call if_changed,ld)
$(obj)/brom/resumes.code: FORCE
$(Q)$(MAKE) $(build)=$(obj)/brom
clean-files += standby.code standby.elf
| apache-2.0 |
google/gemmlowp | test/test.cc | 75539 | // Copyright 2015 The Gemmlowp Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "test.h"
#include <array>
#include <cstdint>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#ifdef __APPLE__
#include <TargetConditionals.h>
#endif
#include "../eight_bit_int_gemm/eight_bit_int_gemm.h"
#include "../internal/kernel_reference.h"
#include "test_data.h"
namespace gemmlowp {
void ReferenceEightBitIntGemm(bool transpose_a, bool transpose_b,
bool transpose_c, int m, int n, int k,
const std::uint8_t* a, std::int32_t a_offset,
int lda, const std::uint8_t* b,
std::int32_t b_offset, int ldb, std::uint8_t* c,
std::int32_t c_offset, std::int32_t c_mult_int,
std::int32_t c_shift, int ldc) {
ScopedProfilingLabel("ReferenceEightBitIntGemm");
assert((c_shift >= 0) && (c_shift <= 32));
assert(a != nullptr);
assert(b != nullptr);
assert(c != nullptr);
int a_i_stride;
int a_l_stride;
if (transpose_a) {
a_i_stride = lda;
a_l_stride = 1;
} else {
a_i_stride = 1;
a_l_stride = lda;
}
int b_j_stride;
int b_l_stride;
if (transpose_b) {
b_j_stride = 1;
b_l_stride = ldb;
} else {
b_j_stride = ldb;
b_l_stride = 1;
}
int c_i_stride;
int c_j_stride;
if (transpose_c) {
c_i_stride = ldc;
c_j_stride = 1;
} else {
c_i_stride = 1;
c_j_stride = ldc;
}
int i, j, l;
const std::int32_t kRoundingTerm = (c_shift < 1) ? 0 : (1 << (c_shift - 1));
for (j = 0; j < n; j++) {
for (i = 0; i < m; i++) {
std::int32_t total = 0;
for (l = 0; l < k; l++) {
const int a_index = i * a_i_stride + l * a_l_stride;
const std::uint8_t a_as_byte = a[a_index];
const std::int32_t a_as_int =
static_cast<std::int32_t>(a_as_byte) + a_offset;
const int b_index = j * b_j_stride + l * b_l_stride;
const std::uint8_t b_as_byte = b[b_index];
const std::int32_t b_as_int =
static_cast<std::int32_t>(b_as_byte) + b_offset;
const std::int32_t mult_as_int = a_as_int * b_as_int;
total += mult_as_int;
}
std::int32_t output =
(((total + c_offset) * c_mult_int) + kRoundingTerm) >> c_shift;
if (output > 255) {
output = 255;
}
if (output < 0) {
output = 0;
}
const int c_index = i * c_i_stride + j * c_j_stride;
c[c_index] = static_cast<std::uint8_t>(output);
}
}
}
typedef VectorMap<const std::int32_t, VectorShape::Col> OffsetColMap;
typedef VectorMap<const std::int32_t, VectorShape::Row> OffsetRowMap;
typedef VectorDup<const std::int32_t, VectorShape::Col> OffsetColDup;
typedef VectorDup<const std::int32_t, VectorShape::Row> OffsetRowDup;
// *GemmWrapper's allow to wrap various Gemm functions in a uniform
// interface, so we can use the same testing code to test all of them
template <typename Kernel, typename Scalar, typename tBitDepthParams>
struct SingleThreadGemmWrapper {
typedef tBitDepthParams BitDepthParams;
static const char* Name() {
static char buf[256];
snprintf(buf, sizeof(buf), "SingleThreadGemm, Kernel: %s", Kernel().Name());
return buf;
}
typedef SingleThreadGemmContext Context;
template <MapOrder LhsOrder, MapOrder RhsOrder, MapOrder ResultOrder>
static bool Gemm(Context* context,
const MatrixMap<const Scalar, LhsOrder>& lhs,
const MatrixMap<const Scalar, RhsOrder>& rhs,
MatrixMap<Scalar, ResultOrder>* result, int lhs_offset,
int rhs_offset, int result_offset, int result_mult_int,
int result_shift) {
ScopedProfilingLabel("SingleThreadGemmWrapper::Gemm");
const int rows = lhs.rows();
const int cols = rhs.cols();
if (rows < cols) {
// SingleThreadGemm is never called with rows < cols.
// That case is handled earlier.
return false;
}
const OffsetColDup lhs_offset_vector(lhs_offset, rows);
const OffsetRowDup rhs_offset_vector(rhs_offset, cols);
SingleThreadGemm<typename Kernel::Format, Scalar, Scalar, BitDepthParams,
LhsOrder, RhsOrder, ResultOrder, OffsetColDup,
OffsetRowDup>(
context, Kernel(), lhs, rhs, result, lhs_offset_vector,
rhs_offset_vector,
MakeStandardOutputPipeline(result_offset, result_mult_int,
result_shift));
return true;
}
};
template <typename Kernel, typename Scalar, typename tBitDepthParams>
struct MultiThreadGemmWrapper {
typedef tBitDepthParams BitDepthParams;
static const char* Name() {
static char buf[256];
snprintf(buf, sizeof(buf), "MultiThreadGemm, Kernel: %s", Kernel().Name());
return buf;
}
typedef MultiThreadGemmContext Context;
template <MapOrder LhsOrder, MapOrder RhsOrder, MapOrder ResultOrder>
static bool Gemm(Context* context,
const MatrixMap<const Scalar, LhsOrder>& lhs,
const MatrixMap<const Scalar, RhsOrder>& rhs,
MatrixMap<Scalar, ResultOrder>* result, int lhs_offset,
int rhs_offset, int result_offset, int result_mult_int,
int result_shift) {
ScopedProfilingLabel("MultiThreadGemmWrapper::Gemm");
context->set_max_num_threads(0);
const int rows = lhs.rows();
const int cols = rhs.cols();
if (rows < cols) {
// SingleThreadGemm is never called with rows < cols.
// That case is handled earlier.
return false;
}
const OffsetColDup lhs_offset_vector(lhs_offset, rows);
const OffsetRowDup rhs_offset_vector(rhs_offset, cols);
MultiThreadGemm<typename Kernel::Format, Scalar, Scalar, BitDepthParams,
LhsOrder, RhsOrder, ResultOrder, OffsetColDup,
OffsetRowDup>(
context, Kernel(), lhs, rhs, result, lhs_offset_vector,
rhs_offset_vector,
MakeStandardOutputPipeline(result_offset, result_mult_int,
result_shift));
return true;
}
};
template <typename Scalar, typename tBitDepthParams>
struct PublicGemmWrapper {
typedef tBitDepthParams BitDepthParams;
static const char* Name() { return "public Gemm"; }
typedef GemmContext Context;
template <MapOrder LhsOrder, MapOrder RhsOrder, MapOrder ResultOrder>
static bool Gemm(Context* context,
const MatrixMap<const Scalar, LhsOrder>& lhs,
const MatrixMap<const Scalar, RhsOrder>& rhs,
MatrixMap<Scalar, ResultOrder>* result, int lhs_offset,
int rhs_offset, int result_offset, int result_mult_int,
int result_shift) {
ScopedProfilingLabel("PublicGemmWrapper::Gemm");
gemmlowp::Gemm<std::uint8_t, BitDepthParams, LhsOrder, RhsOrder,
ResultOrder>(context, lhs, rhs, result, lhs_offset,
rhs_offset, result_offset, result_mult_int,
result_shift);
return true;
}
};
template <eight_bit_int_gemm::BitDepthSetting BitDepth>
struct BitDepthParamsForSettings {};
template <>
struct BitDepthParamsForSettings<eight_bit_int_gemm::BitDepthSetting::A8B8>
: DefaultL8R8BitDepthParams {};
template <>
struct BitDepthParamsForSettings<eight_bit_int_gemm::BitDepthSetting::A5B7>
: DefaultL7R5BitDepthParams {};
template <typename Scalar, eight_bit_int_gemm::BitDepthSetting BitDepth>
struct EightBitIntGemmWrapper {
typedef BitDepthParamsForSettings<BitDepth> BitDepthParams;
static const char* Name() { return "EightBitIntGemm"; }
typedef void Context;
template <MapOrder LhsOrder, MapOrder RhsOrder, MapOrder ResultOrder>
static bool Gemm(Context*, const MatrixMap<const Scalar, LhsOrder>& lhs,
const MatrixMap<const Scalar, RhsOrder>& rhs,
MatrixMap<Scalar, ResultOrder>* result, int lhs_offset,
int rhs_offset, int result_offset, int result_mult_int,
int result_shift) {
ScopedProfilingLabel("EightBitIntGemmWrapper::Gemm");
const bool transpose_c = ResultOrder == MapOrder::RowMajor;
const bool transpose_a = LhsOrder == MapOrder::RowMajor;
const bool transpose_b = RhsOrder == MapOrder::RowMajor;
eight_bit_int_gemm::EightBitIntGemm(
transpose_a, transpose_b, transpose_c, lhs.rows(), rhs.cols(),
lhs.cols(), lhs.data(), lhs_offset, lhs.stride(), rhs.data(),
rhs_offset, rhs.stride(), result->data(), result_offset,
result_mult_int, result_shift, result->stride(), BitDepth);
return true;
}
};
template <typename Scalar>
struct ReferenceEightBitIntGemmWrapper {
typedef DefaultL8R8BitDepthParams BitDepthParams;
static const char* Name() { return "ReferenceEightBitIntGemm"; }
template <MapOrder LhsOrder, MapOrder RhsOrder, MapOrder ResultOrder>
static bool Gemm(bool transpose_a, bool transpose_b, bool transpose_c,
const MatrixMap<const Scalar, LhsOrder>& lhs,
const MatrixMap<const Scalar, RhsOrder>& rhs,
MatrixMap<Scalar, ResultOrder>* result, int lhs_offset,
int rhs_offset, int result_offset, int result_mult_int,
int result_shift) {
ScopedProfilingLabel("ReferenceEightBitIntGemmWrapper::Gemm");
ReferenceEightBitIntGemm(transpose_a, transpose_b, transpose_c, lhs.rows(),
rhs.cols(), lhs.cols(), lhs.data(), lhs_offset,
lhs.stride(), rhs.data(), rhs_offset, rhs.stride(),
result->data(), result_offset, result_mult_int,
result_shift, result->stride());
return true;
}
};
const char* OrderName(MapOrder order) {
return order == MapOrder::ColMajor ? "ColMajor" : "RowMajor";
}
struct ResultStats {
ResultStats()
: count(0),
med_val(0),
mean_signed_diff(0),
med_signed_diff(0),
med_unsigned_diff(0),
max_unsigned_diff(0) {}
int count;
int med_val;
float mean_signed_diff;
int med_signed_diff;
int med_unsigned_diff;
int max_unsigned_diff;
std::vector<int> count_diff_by_pot_slice;
};
void GetResultStats(const std::uint8_t* actual, const std::uint8_t* expected,
size_t count, ResultStats* stats) {
ScopedProfilingLabel("GetResultStats");
std::vector<std::uint8_t> results;
std::vector<std::int16_t> signed_diffs;
std::vector<std::uint8_t> unsigned_diffs;
std::int64_t signed_diffs_sum = 0;
for (size_t i = 0; i < count; i++) {
results.push_back(actual[i]);
std::int16_t signed_diff = actual[i] - expected[i];
signed_diffs.push_back(signed_diff);
unsigned_diffs.push_back(std::abs(signed_diff));
signed_diffs_sum += signed_diff;
}
std::sort(results.begin(), results.end());
std::sort(signed_diffs.begin(), signed_diffs.end());
std::sort(unsigned_diffs.begin(), unsigned_diffs.end());
const size_t middle = count / 2;
stats->count = count;
stats->med_val = results[middle];
stats->mean_signed_diff = float(signed_diffs_sum) / count;
stats->med_signed_diff = signed_diffs[middle];
stats->med_unsigned_diff = unsigned_diffs[middle];
stats->max_unsigned_diff = unsigned_diffs.back();
// Size 9 for 9 different POT values: 2^0, ..., 2^8
stats->count_diff_by_pot_slice.resize(9);
auto cur = unsigned_diffs.begin();
size_t checksum = 0;
for (int exponent = 0; exponent < 9; exponent++) {
int pot = 1 << exponent;
auto next = std::lower_bound(cur, unsigned_diffs.end(), pot);
checksum += stats->count_diff_by_pot_slice[exponent] = next - cur;
cur = next;
}
assert(checksum == count);
}
struct ResultStatsBounds {
ResultStatsBounds()
: mean_signed_diff(0),
med_signed_diff(0),
med_unsigned_diff(0),
max_unsigned_diff(0) {}
float mean_signed_diff;
int med_signed_diff;
int med_unsigned_diff;
int max_unsigned_diff;
};
bool CheckResultStatsBounds(const ResultStats& stats,
const ResultStatsBounds& bounds) {
return stats.max_unsigned_diff <= bounds.max_unsigned_diff &&
stats.med_unsigned_diff <= bounds.med_unsigned_diff &&
std::abs(stats.med_signed_diff) <= bounds.med_signed_diff &&
std::abs(stats.mean_signed_diff) <= bounds.mean_signed_diff;
}
void ReportResultStats(const ResultStats& stats,
const ResultStatsBounds& bounds) {
printf(" number of matrix entries: %d\n", stats.count);
printf(" median value: %d\n", stats.med_val);
printf(" median unsigned diff: %d (tolerating %d)\n",
stats.med_unsigned_diff, bounds.med_unsigned_diff);
printf(" max unsigned diff: %d (tolerating %d)\n", stats.max_unsigned_diff,
bounds.max_unsigned_diff);
printf(" median signed diff: %d (tolerating %d)\n", stats.med_signed_diff,
bounds.med_signed_diff);
printf(" mean signed diff: %.3g (tolerating %.3g)\n",
stats.mean_signed_diff, bounds.mean_signed_diff);
printf("No error: %.2f %% of entries\n",
100.f * stats.count_diff_by_pot_slice[0] / stats.count);
for (int exponent = 1; exponent < 9; exponent++) {
printf("Error in %d..%d range: %.2f %% of entries\n", 1 << (exponent - 1),
(1 << exponent) - 1,
100.f * stats.count_diff_by_pot_slice[exponent] / stats.count);
}
}
// Our approach to choosing result_shift values for testing, is bisection.
// This function takes an interval, [result_shift_min .. result_shift_max].
// If too much saturation occurred in either direction, it bisects accordingly,
// recursing until the interval contains only one value.
// The primary reason why we prefer this over computing optimal shift values,
// is that we actually want to exercise some saturation, as there is nontrivial
// code handling that in gemmlowp.
// Secondarily, this is faster than computing optimal shifts, since in 90% of
// cases the first-tried shift value 16 turns out to be good enough.
template <typename GemmWrapper, typename LhsType, typename RhsType,
typename ResultType>
void test_gemm_impl(typename GemmWrapper::Context* context, const LhsType& lhs,
const RhsType& rhs, ResultType* result, int lhs_offset,
int rhs_offset, int result_offset, int result_mult_int,
int result_shift_min, int result_shift_max) {
const int rows = lhs.rows();
const int cols = rhs.cols();
Check(lhs.cols() == rhs.rows());
const int depth = lhs.cols();
const int result_shift = (result_shift_min + result_shift_max) / 2;
if (!GemmWrapper::Gemm(context, lhs.const_map(), rhs.const_map(),
&result->map(), lhs_offset, rhs_offset, result_offset,
result_mult_int, result_shift)) {
// Internal GEMM functions are not required to handle all cases
// (e.g. rows < cols) as these are supposed to have been handled
// ahead of them. Their test wrappers return false in that case.
return;
}
typedef typename ResultType::Scalar Scalar;
static const MapOrder kLhsOrder = LhsType::kOrder;
static const MapOrder kRhsOrder = RhsType::kOrder;
static const MapOrder kResultOrder = ResultType::kOrder;
ResultType ref_result(rows, cols);
const bool transpose_c = kResultOrder == MapOrder::RowMajor;
const bool transpose_a = kLhsOrder == MapOrder::RowMajor;
const bool transpose_b = kRhsOrder == MapOrder::RowMajor;
ReferenceEightBitIntGemmWrapper<Scalar>::Gemm(
transpose_a, transpose_b, transpose_c, lhs.const_map(), rhs.const_map(),
&ref_result.map(), lhs_offset, rhs_offset, result_offset, result_mult_int,
result_shift);
typedef typename GemmWrapper::BitDepthParams BitDepthParams;
ResultStats stats;
GetResultStats(result->data(), ref_result.data(), rows * cols, &stats);
// Adjust shifts until we get meaningful results
int new_result_shift_min = result_shift_min;
int new_result_shift_max = result_shift_max;
bool retry = false;
if (stats.med_val < 32) {
new_result_shift_max = (result_shift_min + result_shift_max) / 2;
retry = true;
}
if (stats.med_val > 224) {
new_result_shift_min = (result_shift_min + result_shift_max) / 2;
retry = true;
}
if (retry) {
if (result_shift_min != result_shift_max) {
test_gemm_impl<GemmWrapper>(context, lhs, rhs, result, lhs_offset,
rhs_offset, result_offset, result_mult_int,
new_result_shift_min, new_result_shift_max);
}
return;
}
ResultStatsBounds bounds;
// Check results
const bool good = CheckResultStatsBounds(stats, bounds);
printf(
"%s: %dx%dx%d %s x %s -> %s, %s, offsets %d/%d/%d, mult %d, shift %d\n",
good ? "PASS" : "FAIL", rows, depth, cols, OrderName(kLhsOrder),
OrderName(kRhsOrder), OrderName(kResultOrder), GemmWrapper::Name(),
lhs_offset, rhs_offset, result_offset, result_mult_int, result_shift);
if (!good) {
ReportResultStats(stats, bounds);
int bad_coeffs_printed = 0;
for (int c = 0; c < result->cols() && bad_coeffs_printed < 200; c++) {
for (int r = 0; r < result->rows() && bad_coeffs_printed < 200; r++) {
if (ref_result(r, c) != (*result)(r, c)) {
printf("bad coeff: at (%d, %d), expected %d, got %d\n", r, c,
ref_result(r, c), (*result)(r, c));
bad_coeffs_printed++;
}
}
}
}
Check(good);
}
template <typename GemmWrapper, typename LhsType, typename RhsType,
typename ResultType>
void test_gemm(typename GemmWrapper::Context* context, const LhsType& lhs,
const RhsType& rhs, ResultType* result, int lhs_offset,
int rhs_offset, int result_offset, int result_mult_int) {
test_gemm_impl<GemmWrapper>(context, lhs, rhs, result, lhs_offset, rhs_offset,
result_offset, result_mult_int, 0, 32);
}
enum class WhatParamsToTest {
All,
OnlyGenericCase,
};
template <typename GemmWrapper, MapOrder LhsOrder, MapOrder RhsOrder,
MapOrder ResultOrder>
void test_gemm(typename GemmWrapper::Context* context, int rows, int depth,
int cols, WhatParamsToTest params_to_test) {
typedef std::uint8_t Scalar;
typedef Matrix<Scalar, LhsOrder> LhsType;
using BitDepthParams = typename GemmWrapper::BitDepthParams;
LhsType lhs(rows, depth);
MakeRandom<typename BitDepthParams::LhsRange>(&lhs);
typedef Matrix<Scalar, RhsOrder> RhsType;
RhsType rhs(depth, cols);
MakeRandom<typename BitDepthParams::RhsRange>(&rhs);
typedef Matrix<Scalar, ResultOrder> ResultType;
ResultType result(rows, cols);
MakeZero(&result);
if (params_to_test == WhatParamsToTest::All) {
test_gemm<GemmWrapper>(context, lhs, rhs, &result, 0, 0, 0, 1);
test_gemm<GemmWrapper>(context, lhs, rhs, &result, 10, 0, 0, 1);
test_gemm<GemmWrapper>(context, lhs, rhs, &result, 0, 10, 0, 1);
test_gemm<GemmWrapper>(context, lhs, rhs, &result, 0, 0, 10, 1);
test_gemm<GemmWrapper>(context, lhs, rhs, &result, 0, 0, 0, 10);
test_gemm<GemmWrapper>(context, lhs, rhs, &result, 10, 10, 10, 10);
test_gemm<GemmWrapper>(context, lhs, rhs, &result, 256, 1, 17, 4);
}
test_gemm<GemmWrapper>(context, lhs, rhs, &result, -75, -91, 74980, 123);
}
enum class WhatOrdersToTest { All, OnlyRCC };
template <typename GemmWrapper>
void test_gemm(typename GemmWrapper::Context* context, int rows, int depth,
int cols, WhatParamsToTest params_to_test,
WhatOrdersToTest orders_to_test) {
#define GEMMLOWP_ONE_TEST(LhsOrder, RhsOrder, ResultOrder) \
do { \
test_gemm<GemmWrapper, MapOrder::LhsOrder, MapOrder::RhsOrder, \
MapOrder::ResultOrder>(context, rows, depth, cols, \
params_to_test); \
} while (false)
if (orders_to_test == WhatOrdersToTest::All) {
GEMMLOWP_ONE_TEST(ColMajor, ColMajor, ColMajor);
GEMMLOWP_ONE_TEST(RowMajor, ColMajor, ColMajor);
GEMMLOWP_ONE_TEST(ColMajor, RowMajor, ColMajor);
GEMMLOWP_ONE_TEST(RowMajor, RowMajor, ColMajor);
GEMMLOWP_ONE_TEST(ColMajor, ColMajor, RowMajor);
GEMMLOWP_ONE_TEST(RowMajor, ColMajor, RowMajor);
GEMMLOWP_ONE_TEST(ColMajor, RowMajor, RowMajor);
GEMMLOWP_ONE_TEST(RowMajor, RowMajor, RowMajor);
} else {
GEMMLOWP_ONE_TEST(RowMajor, ColMajor, ColMajor);
}
#undef GEMMLOWP_ONE_TEST
}
template <typename Kernel>
void test_gemm_kernel(MultiThreadGemmContext* context) {
typedef MultiThreadGemmWrapper<Kernel, std::uint8_t,
DefaultL8R8BitDepthParams>
GemmWrapper;
test_gemm<GemmWrapper>(context, 1, 1, 1, WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 2, 2, 2, WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 3, 3, 3, WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 4, 4, 4, WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 5, 5, 5, WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 9, 11, 13, WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 50, 50, 50, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 200, 200, 200,
WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::All);
test_gemm<GemmWrapper>(context, 50, 5000, 50,
WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::OnlyRCC);
}
template <typename GemmWrapper>
void test_gemm(typename GemmWrapper::Context* context) {
test_gemm<GemmWrapper>(context, 1, 1, 1, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 2, 1, 1, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 1, 2, 1, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 1, 1, 2, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 2, 2, 2, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 3, 3, 3, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 4, 4, 4, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 5, 5, 5, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 6, 6, 6, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 3, 5, 7, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 7, 3, 5, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 5, 7, 3, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 8, 8, 8, WhatParamsToTest::All,
WhatOrdersToTest::All);
test_gemm<GemmWrapper>(context, 16, 16, 16, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 32, 32, 32, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 64, 64, 64, WhatParamsToTest::All,
WhatOrdersToTest::All);
test_gemm<GemmWrapper>(context, 128, 128, 128, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 16, 17, 16, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 37, 55, 73, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 57, 87, 117, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 93, 83, 73, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 109, 89, 99, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 78, 101, 82, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 512, 512, 512,
WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 1024, 1024, 1024,
WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 567, 2345, 123,
WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 100, 5000, 100,
WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 1, 1, 1000, WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 1000, 1, 1, WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 1, 1000, 1, WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 1, 1000, 1000,
WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 1000, 1, 1000,
WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 1000, 1000, 1,
WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 777, 3456, 1,
WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 4567, 555, 1,
WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::OnlyRCC);
// Test all storage orders
test_gemm<GemmWrapper>(context, 70, 90, 110, WhatParamsToTest::All,
WhatOrdersToTest::All);
test_gemm<GemmWrapper>(context, 300, 400, 500,
WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::All);
}
template <typename GemmWrapper>
void test_gemv(typename GemmWrapper::Context* context) {
test_gemm<GemmWrapper>(context, 2, 2, 1, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 3, 3, 1, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 4, 4, 1, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 5, 5, 1, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 6, 6, 1, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 3, 5, 1, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 7, 3, 1, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 5, 7, 1, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 8, 8, 1, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 32, 32, 1, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 128, 128, 1, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
test_gemm<GemmWrapper>(context, 321, 123, 1, WhatParamsToTest::All,
WhatOrdersToTest::OnlyRCC);
// Test all storage orders
test_gemm<GemmWrapper>(context, 70, 90, 1, WhatParamsToTest::All,
WhatOrdersToTest::All);
test_gemm<GemmWrapper>(context, 300, 400, 1,
WhatParamsToTest::OnlyGenericCase,
WhatOrdersToTest::All);
}
const char* GetBitDepthName(eight_bit_int_gemm::BitDepthSetting b) {
switch (b) {
case eight_bit_int_gemm::BitDepthSetting::A8B8:
return "Lhs: 8 bit, Rhs: 8 bit";
case eight_bit_int_gemm::BitDepthSetting::A5B7:
return "(legacy, no longer requantizing) Lhs: 7 bit, Rhs: 5 bit";
default:
abort();
return nullptr;
}
}
// Runs a small set of hand-picked data for per-channel quantized data.
// This test case comes from a set of 2 2x2 convolution filters run over a 3x3
// image.
void TestWithSmallDataPerChannelQuantization() {
const int m = 2;
const int n = 9;
const int k = 12;
// 12 x 2, columnwise.
const std::uint8_t a_data[] = {0, 0, 0, 0, 0, 0, 0, 0,
0, 255, 255, 255, 64, 64, 64, 64,
64, 64, 0, 0, 0, 255, 255, 255};
const int lda = k;
int a_offset[] = {0, -64};
MatrixMap<const std::uint8_t, MapOrder::RowMajor> lhs(a_data, m, k, lda);
const OffsetColMap lhs_offset(a_offset, m);
// 12 x 9, columnwise.
const std::uint8_t b_data[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 0, 0,
0, 0, 0, 0, 255, 255, 255, 0, 0, 0, 0, 0, 0, 127,
127, 127, 0, 0, 0, 127, 127, 127, 0, 0, 0, 255, 255, 255,
0, 0, 0, 0, 0, 0, 255, 255, 255, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 127, 127, 127, 0, 0, 0, 127,
127, 127, 0, 0, 0, 0, 0, 0, 127, 127, 127, 127, 127, 127,
0, 0, 0, 0, 0, 0, 127, 127, 127, 127, 127, 127, 0, 0,
0, 127, 127, 127, 127, 127, 127, 127, 127, 127};
const int ldb = k;
int b_offset = -127;
MatrixMap<const std::uint8_t, MapOrder::ColMajor> rhs(b_data, k, n, ldb);
const OffsetRowDup rhs_offset(b_offset, rhs.cols());
// 2 x 9, columnwise.
const std::uint8_t expected_c_data[] = {255, 255, 0, 0, 127, 159,
0, 64, 0, 64, 127, 159,
127, 127, 127, 127, 127, 127};
const int ldc = m;
int c_offset[] = {97155, 97346};
int c_mult_int[] = {2741, 2741};
const int c_shift = 21;
const int c_count = m * n;
std::unique_ptr<std::uint8_t[]> output_data(new std::uint8_t[c_count]);
MatrixMap<std::uint8_t, MapOrder::ColMajor> result(output_data.get(), m, n,
ldc);
const OffsetColMap result_offset(c_offset, m);
const OffsetColMap result_mult_int(c_mult_int, m);
const int result_shift = c_shift;
GemmContext gemm_context;
auto output_pipeline = MakeStandardOutputPipeline<VectorShape::Col>(
result_offset, result_mult_int, result_shift);
GemmWithOutputPipelinePC<std::uint8_t, std::uint8_t,
DefaultL8R8BitDepthParams>(
&gemm_context, lhs, rhs, &result, lhs_offset, rhs_offset,
output_pipeline);
ResultStats stats;
GetResultStats(output_data.get(), expected_c_data, c_count, &stats);
ResultStatsBounds bounds;
const bool good = CheckResultStatsBounds(stats, bounds);
printf("TestWithSmallDataPerChannelQuantization: %s\n",
good ? "PASS" : "FAIL");
ReportResultStats(stats, bounds);
Check(good);
}
// Runs a larger set of hand-picked data for per-channel quantized data.
// This test case comes from a set of 22 3x3 convolution filters run over a 5x5
// image. Right now, I have 7 different filters and 15 copies of the first
// filter to make sure NEON code path that processes 16 rows at a time is
// covered.
void TestWithLargeDataPerChannelQuantization() {
const int m = 22;
const int n = 25;
const int k = 27;
// 27 x 22, column-wise.
const std::uint8_t a_data[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 127, 127, 127, 255, 255, 255, 127, 127, 127,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 127, 127, 127,
0, 0, 0, 0, 0, 0, 255, 255, 255, 0, 0, 0, 0, 0, 0,
127, 127, 127, 0, 0, 0, 51, 51, 51, 51, 51, 51, 51, 51, 51,
0, 0, 0, 255, 255, 255, 0, 0, 0, 51, 51, 51, 51, 51, 51,
51, 51, 51, 51, 51, 51, 0, 0, 0, 51, 51, 51, 51, 51, 51,
255, 255, 255, 51, 51, 51, 51, 51, 51, 0, 0, 0, 51, 51, 51,
0, 0, 0, 64, 64, 64, 0, 0, 0, 64, 64, 64, 255, 255, 255,
64, 64, 64, 0, 0, 0, 64, 64, 64, 0, 0, 0, 36, 36, 36,
0, 0, 0, 36, 36, 36, 0, 0, 0, 255, 255, 255, 0, 0, 0,
36, 36, 36, 0, 0, 0, 36, 36, 36, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 255, 255, 255, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 255, 255, 255, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 255, 255, 255, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
};
const int lda = k;
int a_offset[] = {0, 0, 0, -51, -51, 0, -36, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
MatrixMap<const std::uint8_t, MapOrder::RowMajor> lhs(a_data, m, k, lda);
const OffsetColMap lhs_offset(a_offset, m);
// 27 x 25, column-wise.
const std::uint8_t b_data[] = {
127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 119, 119,
119, 119, 119, 119, 127, 127, 127, 119, 119, 119, 119, 119, 119, 127,
127, 127, 127, 127, 127, 127, 127, 127, 119, 119, 119, 119, 119, 119,
119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 127, 127,
127, 127, 127, 127, 127, 127, 127, 119, 119, 119, 119, 119, 119, 119,
119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 127, 127, 127,
127, 127, 127, 127, 127, 127, 119, 119, 119, 119, 119, 119, 119, 119,
119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 127, 127, 127, 127,
127, 127, 127, 127, 127, 119, 119, 119, 119, 119, 119, 127, 127, 127,
119, 119, 119, 119, 119, 119, 127, 127, 127, 127, 127, 127, 119, 119,
119, 119, 119, 119, 127, 127, 127, 119, 119, 119, 119, 119, 119, 127,
127, 127, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,
119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,
119, 119, 119, 119, 136, 136, 136, 119, 119, 119, 119, 119, 119, 119,
119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,
136, 136, 136, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,
119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 136, 136, 136, 119,
119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 127, 127, 127,
119, 119, 119, 119, 119, 119, 127, 127, 127, 119, 119, 119, 119, 119,
119, 127, 127, 127, 127, 127, 127, 119, 119, 119, 119, 119, 119, 127,
127, 127, 119, 119, 119, 119, 119, 119, 127, 127, 127, 119, 119, 119,
119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,
119, 119, 119, 119, 136, 136, 136, 119, 119, 119, 119, 119, 119, 119,
119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,
136, 136, 136, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,
119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 136, 136, 136, 119,
119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,
119, 119, 119, 119, 119, 119, 127, 127, 127, 119, 119, 119, 119, 119,
119, 127, 127, 127, 119, 119, 119, 119, 119, 119, 127, 127, 127, 127,
127, 127, 119, 119, 119, 119, 119, 119, 127, 127, 127, 119, 119, 119,
119, 119, 119, 127, 127, 127, 119, 119, 119, 119, 119, 119, 119, 119,
119, 119, 119, 119, 136, 136, 136, 119, 119, 119, 119, 119, 119, 119,
119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,
136, 136, 136, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,
119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 136, 136, 136, 119,
119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,
119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119,
119, 127, 127, 127, 119, 119, 119, 119, 119, 119, 127, 127, 127, 119,
119, 119, 119, 119, 119, 127, 127, 127, 127, 127, 127, 119, 119, 119,
119, 119, 119, 127, 127, 127, 119, 119, 119, 119, 119, 119, 127, 127,
127, 127, 127, 127, 127, 127, 127, 119, 119, 119, 119, 119, 119, 119,
119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 127, 127, 127,
127, 127, 127, 127, 127, 127, 119, 119, 119, 119, 119, 119, 119, 119,
119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 127, 127, 127, 127,
127, 127, 127, 127, 127, 119, 119, 119, 119, 119, 119, 119, 119, 119,
119, 119, 119, 119, 119, 119, 119, 119, 119, 127, 127, 127, 127, 127,
127, 127, 127, 127, 119, 119, 119, 119, 119, 119, 127, 127, 127, 119,
119, 119, 119, 119, 119, 127, 127, 127, 127, 127, 127, 127, 127, 127,
127, 127, 127};
const int ldb = k;
int b_offset = -127;
MatrixMap<const std::uint8_t, MapOrder::ColMajor> rhs(b_data, k, n, ldb);
const OffsetRowDup rhs_offset(b_offset, rhs.cols());
// 22 x 25, column-wise.
const std::uint8_t expected_c_data[] = {
7, 37, 37, 67, 67, 39, 79, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 37, 87, 67, 23, 91, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 37, 87, 67, 23, 91, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 37, 87, 67, 23, 91, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 37,
37, 67, 67, 39, 79, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 37, 7, 67, 87, 23, 91, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
87, 87, 7, 103, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 71, 87, 45, 41, 77, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 87,
87, 7, 103, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 37, 7, 67, 87, 23, 91, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 37, 7, 67, 87,
23, 91, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 71, 7, 45, 87, 41, 77, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 255, 135, 135, 255, 255, 143,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 7, 71, 7, 45, 87, 41, 77, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 37, 7, 67, 87, 23, 91,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 37, 7, 67, 87, 23, 91, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 87, 87, 7, 103, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 71, 87, 45, 41, 77, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 87, 87, 7, 103, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 37,
7, 67, 87, 23, 91, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 37, 37, 67, 67, 39, 79, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 37,
87, 67, 23, 91, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 37, 87, 67, 23, 91, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 37, 87,
67, 23, 91, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 37, 37, 67, 67, 39, 79, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111,
111, 111, 111, 111, 111, 111, 111, 111, 111,
};
const int ldc = m;
int c_offset[] = {
6477, 12954, 12954, 7793, 7793, 12954, 9282, 6477, 6477, 6477, 6477,
6477, 6477, 6477, 6477, 6477, 6477, 6477, 6477, 6477, 6477, 6477,
};
int c_mult_int[] = {
41121, 20560, 20560, 34267, 34267, 21937, 28784, 41121,
41121, 41121, 41121, 41121, 41121, 41121, 41121, 41121,
41121, 41121, 41121, 41121, 41121, 41121,
};
const int c_shift = 21;
const int c_count = m * n;
std::unique_ptr<std::uint8_t[]> output_data(new std::uint8_t[c_count]);
MatrixMap<std::uint8_t, MapOrder::ColMajor> result(output_data.get(), m, n,
ldc);
const OffsetColMap result_offset(c_offset, m);
const OffsetColMap result_mult_int(c_mult_int, m);
const int result_shift = c_shift;
GemmContext gemm_context;
auto output_pipeline = MakeStandardOutputPipeline<VectorShape::Col>(
result_offset, result_mult_int, result_shift);
GemmWithOutputPipelinePC<std::uint8_t, std::uint8_t,
DefaultL8R8BitDepthParams>(
&gemm_context, lhs, rhs, &result, lhs_offset, rhs_offset,
output_pipeline);
ResultStats stats;
GetResultStats(output_data.get(), expected_c_data, c_count, &stats);
ResultStatsBounds bounds;
const bool good = CheckResultStatsBounds(stats, bounds);
printf("TestWithLargeDataPerChannelQuantization: %s\n",
good ? "PASS" : "FAIL");
ReportResultStats(stats, bounds);
Check(good);
}
// Multithreading only activates when the result has more than 16 rows, and also
// (result rows) * (result cols) * depth >= 2 x 65 x 1024. Size was selected
// to run in 3 threads.
//
// Based on the following floating point data:
// LHS: all zeros except 10.0, 20.0 at the beginning of first 16 rows;
// 1.0, 2.0 at the beginning of next 16 rows; 0.1, 0.2 in next 16 rows;
// 0.01, 0.02 in last 16 rows.
// RHS: all zeros except 1.0 in (0, 0) and 2.0 in (1, 0).
// Varying boundaries were used for each 16 rows block of LHS, to test for
// correct indexing into offsets.
// Expected result: all zeros, except 50.0 at the beginning of first 16 rows;
// 5.0 at the beginning of next 16 rows; 0.5 in next 16 rows; 0.05 in last
// 16 rows.
void TestMultithreadedPerChannelQuantization() {
const int m = 64;
const int n = 20;
const int k = 160;
// LHS, m x k.
const std::array<std::int32_t, 4> lhs_offsets_terse{{
0, -51, -85, -109,
}};
assert(lhs_offsets_terse.size() * 16 == m);
const std::array<std::uint8_t, 4> lhs_first_el{{
128, 153, 170, 182,
}};
assert(lhs_first_el.size() * 16 == m);
// lhs_first_el at (i, 0) and 255 at (i, 1), other values are all -offset.
std::vector<std::uint8_t> a_data(m * k, 0);
for (int i = 0; i < m; ++i) {
a_data[i * k] = lhs_first_el[i / 16];
a_data[i * k + 1] = 255;
for (int j = 2; j < k; ++j) {
a_data[i * k + j] = std::uint8_t(-lhs_offsets_terse[i / 16]);
}
}
const int lda = k;
// Given values at [i / 16].
std::vector<std::int32_t> a_offset(m, 0);
for (int i = 0; i < m; ++i) {
a_offset[i] = lhs_offsets_terse[i / 16];
}
MatrixMap<const std::uint8_t, MapOrder::RowMajor> lhs(&a_data[0], m, k, lda);
const OffsetColMap lhs_offset(&a_offset[0], m);
// RHS, k x n.
// All zeros, except 128 at (0, 0) and 255 at (1, 0).
std::vector<std::uint8_t> b_data(k * n, 0);
b_data[0] = 128;
b_data[1] = 255;
const int ldb = k;
std::int32_t b_offset = 0;
MatrixMap<const std::uint8_t, MapOrder::ColMajor> rhs(&b_data[0], k, n, ldb);
const OffsetRowDup rhs_offset(b_offset, rhs.cols());
// Result, m x n.
// All zeros, except given values at (i / 16, 0).
const std::array<std::uint8_t, 4> expected_c_terse{{
142, 159, 182, 213,
}};
assert(expected_c_terse.size() * 16 == m);
std::vector<std::uint8_t> expected_c_data(m * n, 0);
for (int i = 0; i < m; ++i) {
expected_c_data[i] = expected_c_terse[i / 16];
}
const int ldc = m;
// All zeros.
std::vector<std::int32_t> c_offset(m, 0);
// Given values at [i / 16].
const std::array<std::int32_t, 4> c_mult_int_terse{{
3655, 5140, 7049, 9595,
}};
assert(c_mult_int_terse.size() * 16 == m);
std::vector<std::int32_t> c_mult_int(m);
for (int i = 0; i < m; ++i) {
c_mult_int[i] = c_mult_int_terse[i / 16];
}
const int c_shift = 21;
const int c_count = m * n;
std::unique_ptr<std::uint8_t[]> output_data(new std::uint8_t[c_count]);
MatrixMap<std::uint8_t, MapOrder::ColMajor> result(output_data.get(), m, n,
ldc);
const OffsetColMap result_offset(&c_offset[0], m);
const OffsetColMap result_mult_int(&c_mult_int[0], m);
const int result_shift = c_shift;
GemmContext gemm_context;
auto output_pipeline = MakeStandardOutputPipeline<VectorShape::Col>(
result_offset, result_mult_int, result_shift);
GemmWithOutputPipelinePC<std::uint8_t, std::uint8_t,
DefaultL8R8BitDepthParams>(
&gemm_context, lhs, rhs, &result, lhs_offset, rhs_offset,
output_pipeline);
ResultStats stats;
GetResultStats(output_data.get(), &expected_c_data[0], c_count, &stats);
ResultStatsBounds bounds;
const bool good = CheckResultStatsBounds(stats, bounds);
printf("TestMultithreadedPerChannelQuantization: %s\n",
good ? "PASS" : "FAIL");
ReportResultStats(stats, bounds);
Check(good);
}
// Runs a small set of hand-calculated data through the implementation.
void TestWithSmallData() {
const int m = 4;
const int n = 2;
const int k = 3;
// Matrix A (LHS) is:
// | 7 | 10 | 13 | 16 |
// | 8 | 11 | 14 | 17 |
// | 9 | 12 | 15 | 18 |
const std::uint8_t a_data[] = {7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18};
// Matrix B (RHS) is:
// | 1 | 3 | 5 |
// | 2 | 4 | 6 |
const std::uint8_t b_data[] = {1, 2, 3, 4, 5, 6};
// Here are the results we expect, from hand calculations:
// (1 * 7) + (3 * 8) + (5 * 9) = 76
// (2 * 7) + (4 * 8) + (6 * 9) = 100
// (1 * 10) + (3 * 11) + (5 * 12) = 103
// (2 * 10) + (4 * 11) + (6 * 12) = 136
// (1 * 13) + (3 * 14) + (5 * 15) = 130
// (2 * 13) + (4 * 14) + (6 * 15) = 172
// (1 * 16) + (3 * 17) + (5 * 18) = 157
// (2 * 16) + (4 * 17) + (6 * 18) = 208
// That means matrix C should be:
// | 76 | 103 | 130 | 157 |
// | 100 | 136 | 172 | 208 |
const std::uint8_t expected_data[] = {76, 100, 103, 136, 130, 172, 157, 208};
const int c_count = m * n;
std::unique_ptr<std::uint8_t[]> output_data(new std::uint8_t[c_count]);
const bool is_a_transposed = true;
const bool is_b_transposed = true;
const bool is_c_transposed = true;
const int lda = k;
const int ldb = n;
const int ldc = n;
const int a_offset = 0;
const int b_offset = 0;
const int c_offset = 0;
const int c_mult = 1;
const int c_shift = 0;
gemmlowp::eight_bit_int_gemm::EightBitIntGemm(
is_a_transposed, is_b_transposed, is_c_transposed, m, n, k, a_data,
a_offset, lda, b_data, b_offset, ldb, output_data.get(), c_offset, c_mult,
c_shift, ldc, eight_bit_int_gemm::BitDepthSetting::A8B8);
ResultStats stats;
GetResultStats(output_data.get(), expected_data, c_count, &stats);
ResultStatsBounds bounds;
const bool good = CheckResultStatsBounds(stats, bounds);
printf("TestWithSmallData: %s\n", good ? "PASS" : "FAIL");
ReportResultStats(stats, bounds);
Check(good);
}
// This is the most realistic test of how we'll be using the low-precision GEMM
// function in applications. It takes in large input matrices that have been
// captured from an actual neural network run.
void TestWithRealData(eight_bit_int_gemm::BitDepthSetting BitDepth,
int tolerance_median, int tolerance_max) {
std::unique_ptr<std::uint8_t[]> output_data(
new std::uint8_t[test_data::c_count]);
gemmlowp::eight_bit_int_gemm::EightBitIntGemm(
test_data::is_a_transposed, test_data::is_b_transposed,
test_data::is_c_transposed, test_data::m, test_data::n, test_data::k,
test_data::a_data, test_data::a_offset, test_data::k, test_data::b_data,
test_data::b_offset, test_data::k, output_data.get(), test_data::c_offset,
test_data::c_mult_int, test_data::c_shift, test_data::m, BitDepth);
ResultStats stats;
GetResultStats(output_data.get(), test_data::expected_c_data,
test_data::c_count, &stats);
ResultStatsBounds bounds;
if (BitDepth == eight_bit_int_gemm::BitDepthSetting::A5B7) {
bounds.med_unsigned_diff = tolerance_median;
bounds.max_unsigned_diff = tolerance_max;
bounds.med_signed_diff = 0;
bounds.mean_signed_diff = 0.2f;
}
const bool good = CheckResultStatsBounds(stats, bounds);
printf("TestWithRealData: %s with %s\n", good ? "PASS" : "FAIL",
GetBitDepthName(BitDepth));
ReportResultStats(stats, bounds);
Check(good);
}
template <typename BitDepthParams, MapOrder ResultOrder>
void TestOutputStages(int rows, int depth, int cols, int result_offset,
int result_mult_int, int result_shift) {
Matrix<std::uint8_t, MapOrder::RowMajor> lhs(rows, depth);
Matrix<std::uint8_t, MapOrder::ColMajor> rhs(depth, cols);
Matrix<std::int32_t, ResultOrder> result_raw_int32(rows, cols);
MakeRandom<typename BitDepthParams::LhsRange>(&lhs);
MakeRandom<typename BitDepthParams::RhsRange>(&rhs);
const int lhs_offset = 12;
const int rhs_offset = -34;
// Test an empty pipeline, i.e. returning raw int32 accumulators.
auto empty_pipeline = std::make_tuple();
GemmContext context;
GemmWithOutputPipeline<std::uint8_t, std::int32_t, DefaultL8R8BitDepthParams>(
&context, lhs.const_map(), rhs.const_map(), &result_raw_int32, lhs_offset,
rhs_offset, empty_pipeline);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
std::int32_t expected = 0;
for (int d = 0; d < depth; d++) {
std::int32_t lhs_val =
static_cast<std::int32_t>(lhs(r, d)) + lhs_offset;
std::int32_t rhs_val =
static_cast<std::int32_t>(rhs(d, c)) + rhs_offset;
expected += lhs_val * rhs_val;
}
Check(expected == result_raw_int32(r, c));
}
}
// Test a pipeline with only the quantize-down stage, still returning
// unclamped (but scaled) int32's
OutputStageQuantizeDownInt32ToUint8Scale quantize_down_stage;
quantize_down_stage.result_offset = result_offset;
quantize_down_stage.result_mult_int = result_mult_int;
quantize_down_stage.result_shift = result_shift;
auto quantize_down_pipeline = std::make_tuple(quantize_down_stage);
Matrix<std::int32_t, ResultOrder> result_quantized_down_int32(rows, cols);
GemmWithOutputPipeline<std::uint8_t, std::int32_t, DefaultL8R8BitDepthParams>(
&context, lhs.const_map(), rhs.const_map(), &result_quantized_down_int32,
lhs_offset, rhs_offset, quantize_down_pipeline);
std::int64_t sum = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
std::int32_t raw = result_raw_int32(r, c);
std::int32_t expected = RoundingDivideByPOT(
(raw + result_offset) * result_mult_int, result_shift);
Check(expected == result_quantized_down_int32(r, c));
sum += expected;
}
}
std::int64_t avg = sum / (rows * cols);
// Test that the average quantized-down value falls reasonably in the
// middle of the [0..255] range. Otherwise, the multiplier / shift need to be
// adjusted.
Check(avg >= 64 && avg <= 192);
// Test the familiar default pipeline consisting of quantize-down and
// clamp-and-cast-to-uint8.
OutputStageSaturatingCastToUint8 saturating_cast_stage;
auto quantize_down_and_saturating_cast_pipeline =
std::make_tuple(quantize_down_stage, saturating_cast_stage);
Matrix<std::uint8_t, ResultOrder> result_quantized_down_saturated_uint8(rows,
cols);
GemmWithOutputPipeline<std::uint8_t, std::uint8_t, DefaultL8R8BitDepthParams>(
&context, lhs.const_map(), rhs.const_map(),
&result_quantized_down_saturated_uint8, lhs_offset, rhs_offset,
quantize_down_and_saturating_cast_pipeline);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
std::int32_t quantized = result_quantized_down_int32(r, c);
std::uint8_t expected = std::min(std::max(quantized, 0), 255);
Check(expected == result_quantized_down_saturated_uint8(r, c));
}
}
// Test a variant of the familiar default pipeline consisting of quantize-down
// and clamp-and-cast-to-int16.
OutputStageSaturatingCastToInt16 saturating_cast_int16_stage;
auto quantize_down_and_saturating_cast_int16_pipeline =
std::make_tuple(quantize_down_stage, saturating_cast_int16_stage);
Matrix<std::int16_t, ResultOrder> result_quantized_down_saturated_int16(rows,
cols);
GemmWithOutputPipeline<std::uint8_t, std::int16_t, DefaultL8R8BitDepthParams>(
&context, lhs.const_map(), rhs.const_map(),
&result_quantized_down_saturated_int16, lhs_offset, rhs_offset,
quantize_down_and_saturating_cast_int16_pipeline);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
std::int32_t quantized = result_quantized_down_int32(r, c);
std::int16_t expected = std::min(std::max(quantized, -32768), 32767);
Check(expected == result_quantized_down_saturated_int16(r, c));
}
}
#ifdef GEMMLOWP_MSA
// Test a pipeline consisting of quantize-down and truncating-cast-to-uint8.
OutputStageTruncatingCastToUint8 truncating_cast_stage;
auto quantize_down_and_truncating_cast_pipeline =
std::make_tuple(quantize_down_stage, truncating_cast_stage);
Matrix<std::uint8_t, ResultOrder> result_quantized_down_truncated_uint8(
rows, cols);
GemmWithOutputPipeline<std::uint8_t, std::uint8_t, DefaultL8R8BitDepthParams>(
&context, lhs.const_map(), rhs.const_map(),
&result_quantized_down_truncated_uint8, lhs_offset, rhs_offset,
quantize_down_and_truncating_cast_pipeline);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
std::int32_t quantized = result_quantized_down_int32(r, c);
std::uint8_t expected = quantized & 255;
Check(expected == result_quantized_down_truncated_uint8(r, c));
}
}
#endif
// Test a bias-addition with row-vector
std::vector<std::int32_t> row_vector_data(cols);
std::uniform_int_distribution<std::int32_t> uniform_minus_500_plus_500(-500,
500);
for (int i = 0; i < cols; i++) {
row_vector_data[i] = uniform_minus_500_plus_500(RandomEngine());
}
typedef VectorMap<std::int32_t, VectorShape::Row> RowVectorMap;
RowVectorMap row_vector_map(row_vector_data.data(), cols);
OutputStageBiasAddition<RowVectorMap> row_bias_addition_stage;
row_bias_addition_stage.bias_vector = row_vector_map;
auto row_bias_addition_pipeline = std::make_tuple(row_bias_addition_stage);
Matrix<std::int32_t, ResultOrder> result_of_row_bias_addition(rows, cols);
GemmWithOutputPipeline<std::uint8_t, std::int32_t, DefaultL8R8BitDepthParams>(
&context, lhs.const_map(), rhs.const_map(), &result_of_row_bias_addition,
lhs_offset, rhs_offset, row_bias_addition_pipeline);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
std::int32_t expected = result_raw_int32(r, c) + row_vector_data[c];
Check(expected == result_of_row_bias_addition(r, c));
}
}
// Test a bias-addition with column-vector
std::vector<std::int32_t> col_vector_data(rows);
for (int i = 0; i < rows; i++) {
col_vector_data[i] = uniform_minus_500_plus_500(RandomEngine());
}
typedef VectorMap<std::int32_t, VectorShape::Col> ColVectorMap;
ColVectorMap col_vector_map(col_vector_data.data(), rows);
OutputStageBiasAddition<ColVectorMap> col_bias_addition_stage;
col_bias_addition_stage.bias_vector = col_vector_map;
auto col_bias_addition_pipeline = std::make_tuple(col_bias_addition_stage);
Matrix<std::int32_t, ResultOrder> result_of_col_bias_addition(rows, cols);
GemmWithOutputPipeline<std::uint8_t, std::int32_t, DefaultL8R8BitDepthParams>(
&context, lhs.const_map(), rhs.const_map(), &result_of_col_bias_addition,
lhs_offset, rhs_offset, col_bias_addition_pipeline);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
std::int32_t expected = result_raw_int32(r, c) + col_vector_data[r];
Check(expected == result_of_col_bias_addition(r, c));
}
}
// Test a clamp
OutputStageClamp clamp_stage;
// Determine min and max of raw int32 accumulators
std::int32_t raw_min = std::numeric_limits<std::int32_t>::max();
std::int32_t raw_max = std::numeric_limits<std::int32_t>::min();
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
raw_min = std::min(raw_min, result_raw_int32(r, c));
raw_max = std::max(raw_max, result_raw_int32(r, c));
}
}
// Pick some interesting clamp min/max bounds
clamp_stage.min = static_cast<std::int32_t>(raw_min * 0.7 + raw_max * 0.3);
clamp_stage.max = static_cast<std::int32_t>(raw_min * 0.3 + raw_max * 0.7);
assert(raw_min <= clamp_stage.min && clamp_stage.min <= clamp_stage.max &&
clamp_stage.max <= raw_max);
auto clamp_pipeline = std::make_tuple(clamp_stage);
Matrix<std::int32_t, ResultOrder> result_clamped(rows, cols);
GemmWithOutputPipeline<std::uint8_t, std::int32_t, DefaultL8R8BitDepthParams>(
&context, lhs.const_map(), rhs.const_map(), &result_clamped, lhs_offset,
rhs_offset, clamp_pipeline);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
std::int32_t raw = result_raw_int32(r, c);
std::int32_t expected =
std::min(std::max(raw, clamp_stage.min), clamp_stage.max);
Check(expected == result_clamped(r, c));
}
}
// Test tanh
OutputStageTanh tanh_stage;
const std::int32_t real_zero_as_int32 = (raw_max + raw_min) / 2;
const std::int32_t real_amplitude_as_int32 = (raw_max - raw_min) / 16;
tanh_stage.real_zero_as_int32 = real_zero_as_int32;
tanh_stage.real_amplitude_as_int32 = real_amplitude_as_int32;
auto tanh_pipeline = std::make_tuple(tanh_stage);
Matrix<std::int32_t, ResultOrder> result_tanh(rows, cols);
GemmWithOutputPipeline<std::uint8_t, std::int32_t, DefaultL8R8BitDepthParams>(
&context, lhs.const_map(), rhs.const_map(), &result_tanh, lhs_offset,
rhs_offset, tanh_pipeline);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
std::int32_t raw = result_raw_int32(r, c);
double real_input =
double(raw - real_zero_as_int32) / real_amplitude_as_int32;
double expected = std::tanh(real_input);
std::int32_t actual_int32 = result_tanh(r, c);
double actual =
double(actual_int32 - real_zero_as_int32) / real_amplitude_as_int32;
Check(std::abs(expected - actual) < 2e-4);
}
}
// Test a pipeline with bias and clamp
auto bias_clamp_pipeline =
std::make_tuple(col_bias_addition_stage, clamp_stage);
Matrix<std::int32_t, ResultOrder> result_biased_clamped(rows, cols);
GemmWithOutputPipeline<std::uint8_t, std::int32_t, DefaultL8R8BitDepthParams>(
&context, lhs.const_map(), rhs.const_map(), &result_biased_clamped,
lhs_offset, rhs_offset, bias_clamp_pipeline);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
std::int32_t raw = result_raw_int32(r, c);
std::int32_t biased = raw + col_vector_data[r];
std::int32_t expected =
std::min(std::max(biased, clamp_stage.min), clamp_stage.max);
Check(expected == result_biased_clamped(r, c));
}
}
// Test a full pipeline with bias and clamp and quantization down to 8bit
// result
auto bias_clamp_quantize_cast_pipeline =
std::make_tuple(col_bias_addition_stage, clamp_stage, quantize_down_stage,
saturating_cast_stage);
Matrix<std::uint8_t, ResultOrder> result_biased_clamped_quantized_casted(
rows, cols);
GemmWithOutputPipeline<std::uint8_t, std::uint8_t, DefaultL8R8BitDepthParams>(
&context, lhs.const_map(), rhs.const_map(),
&result_biased_clamped_quantized_casted, lhs_offset, rhs_offset,
bias_clamp_quantize_cast_pipeline);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
std::int32_t quantized = RoundingDivideByPOT(
(result_biased_clamped(r, c) + result_offset) * result_mult_int,
result_shift);
std::uint8_t expected = std::min(std::max(quantized, 0), 255);
Check(expected == result_biased_clamped_quantized_casted(r, c));
}
}
// Test a pipeline with the fixed-point-multiplier variant stage for the
// quantizing down of 32bit accumulators.
//
// First, figure appropriate fixedpoint multiplier and shift values.
std::int32_t result_fixedpoint_multiplier = result_mult_int;
std::int32_t result_fixedpoint_shift = result_shift;
Check(result_mult_int > 0);
Check(result_shift > 0);
result_fixedpoint_multiplier = result_mult_int;
result_fixedpoint_shift = result_shift - 31;
while (result_fixedpoint_multiplier < (1 << 30)) {
result_fixedpoint_multiplier <<= 1;
result_fixedpoint_shift++;
}
Check(result_fixedpoint_shift >= 0);
// Now test OutputStageQuantizeDownInt32ByFixedPoint
OutputStageQuantizeDownInt32ByFixedPoint
quantize_down_by_fixedpoint_stage;
quantize_down_by_fixedpoint_stage.result_offset_after_shift =
static_cast<std::int32_t>(
round(static_cast<double>(result_offset * result_mult_int) /
(1 << result_shift)));
quantize_down_by_fixedpoint_stage.result_fixedpoint_multiplier =
result_fixedpoint_multiplier;
quantize_down_by_fixedpoint_stage.result_shift = result_fixedpoint_shift;
auto quantize_down_by_fixedpoint_pipeline =
std::make_tuple(quantize_down_by_fixedpoint_stage);
Matrix<std::int32_t, ResultOrder> result_quantized_down_by_fixedpoint_int32(
rows, cols);
GemmWithOutputPipeline<std::uint8_t, std::int32_t, DefaultL8R8BitDepthParams>(
&context, lhs.const_map(), rhs.const_map(),
&result_quantized_down_by_fixedpoint_int32, lhs_offset, rhs_offset,
quantize_down_by_fixedpoint_pipeline);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
const std::int32_t actual =
result_quantized_down_by_fixedpoint_int32(r, c);
const std::int32_t raw = result_raw_int32(r, c);
const std::int32_t expected =
quantize_down_by_fixedpoint_stage.result_offset_after_shift +
RoundingDivideByPOT(SaturatingRoundingDoublingHighMul(
raw, result_fixedpoint_multiplier),
result_fixedpoint_shift);
Check(actual == expected);
}
}
// Test OutputStageScaleInt32ByFixedPointAndExponent
for (int exponent = -2; exponent <= 2; exponent++) {
OutputStageScaleInt32ByFixedPointAndExponent
scale_by_fixedpoint_and_exponent_stage;
scale_by_fixedpoint_and_exponent_stage.result_offset_after_shift =
static_cast<std::int32_t>(round(static_cast<double>(
result_offset * result_mult_int * std::pow(2.0, exponent))));
scale_by_fixedpoint_and_exponent_stage.result_fixedpoint_multiplier =
result_fixedpoint_multiplier;
scale_by_fixedpoint_and_exponent_stage.result_exponent = exponent;
auto scale_by_fixedpoint_and_exponent_pipeline =
std::make_tuple(scale_by_fixedpoint_and_exponent_stage);
Matrix<std::int32_t, ResultOrder>
result_scaled_by_fixedpoint_and_exponent_int32(rows, cols);
GemmWithOutputPipeline<std::uint8_t, std::int32_t,
DefaultL8R8BitDepthParams>(
&context, lhs.const_map(), rhs.const_map(),
&result_scaled_by_fixedpoint_and_exponent_int32, lhs_offset, rhs_offset,
scale_by_fixedpoint_and_exponent_pipeline);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
const std::int32_t actual =
result_scaled_by_fixedpoint_and_exponent_int32(r, c);
const std::int32_t raw = result_raw_int32(r, c);
int left_shift = std::max(0, exponent);
int right_shift = std::max(0, -exponent);
const std::int32_t expected =
scale_by_fixedpoint_and_exponent_stage.result_offset_after_shift +
RoundingDivideByPOT(
SaturatingRoundingDoublingHighMul((1 << left_shift) * raw,
result_fixedpoint_multiplier),
right_shift);
Check(actual == expected);
}
}
}
// Test the variant of the familiar default pipeline consisting of
// quantize-down and
// clamp-and-cast-to-uint8, where we used fixedpoint multipliers for the
// downscaling.
auto quantize_down_by_fixedpoint_and_saturating_cast_pipeline =
std::make_tuple(quantize_down_by_fixedpoint_stage, saturating_cast_stage);
Matrix<std::uint8_t, ResultOrder>
result_quantized_down_by_fixedpoint_saturated_uint8(rows, cols);
GemmWithOutputPipeline<std::uint8_t, std::uint8_t, DefaultL8R8BitDepthParams>(
&context, lhs.const_map(), rhs.const_map(),
&result_quantized_down_by_fixedpoint_saturated_uint8, lhs_offset,
rhs_offset, quantize_down_by_fixedpoint_and_saturating_cast_pipeline);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
std::int32_t quantized = result_quantized_down_by_fixedpoint_int32(r, c);
std::uint8_t expected = std::min(std::max(quantized, 0), 255);
Check(expected ==
result_quantized_down_by_fixedpoint_saturated_uint8(r, c));
}
}
printf("TestOutputStages: PASS with ResultOrder=%s\n",
OrderName(ResultOrder));
}
#ifndef GEMMLOWP_SKIP_EXHAUSTIVE_TESTS
template <typename BitDepthParams>
void TestExhaustively() {
GemmContext context;
// Test the internal GEMM interfaces
test_gemm<
SingleThreadGemmWrapper<DefaultKernel<BitDepthParams>,
std::uint8_t, BitDepthParams>>(&context);
test_gemm<
MultiThreadGemmWrapper<DefaultKernel<BitDepthParams>,
std::uint8_t, BitDepthParams>>(&context);
// Test the public GEMM interfaces
test_gemm<PublicGemmWrapper<std::uint8_t, BitDepthParams>>(&context);
// Test GEMV cases (internal interfaces)
test_gemv<
SingleThreadGemmWrapper<DefaultKernel<BitDepthParams>,
std::uint8_t, BitDepthParams>>(&context);
test_gemv<
MultiThreadGemmWrapper<DefaultKernel<BitDepthParams>,
std::uint8_t, BitDepthParams>>(&context);
// Test GEMV cases (public interfaces)
test_gemv<PublicGemmWrapper<std::uint8_t, BitDepthParams>>(&context);
}
template <eight_bit_int_gemm::BitDepthSetting BitDepthSetting>
void TestExhaustivelyEightBitIntGemm() {
GemmContext context;
test_gemv<EightBitIntGemmWrapper<std::uint8_t, BitDepthSetting>>(&context);
test_gemv<EightBitIntGemmWrapper<std::uint8_t, BitDepthSetting>>(&context);
test_gemm<EightBitIntGemmWrapper<std::uint8_t, BitDepthSetting>>(&context);
}
void TestKernels() {
GemmContext context;
// Test specific kernels with various different formats,
// to exercises corner cases especially in the packing code.
test_gemm_kernel<
ReferenceKernel<KernelFormat<KernelSideFormat<CellFormat<1, 1>, 1>,
KernelSideFormat<CellFormat<1, 1>, 1>>>>(
&context);
test_gemm_kernel<
ReferenceKernel<KernelFormat<KernelSideFormat<CellFormat<4, 2>, 1>,
KernelSideFormat<CellFormat<4, 2>, 2>>>>(
&context);
test_gemm_kernel<
ReferenceKernel<KernelFormat<KernelSideFormat<CellFormat<4, 2>, 4>,
KernelSideFormat<CellFormat<4, 2>, 5>>>>(
&context);
test_gemm_kernel<ReferenceKernel<KernelFormat<
KernelSideFormat<CellFormat<3, 4, CellOrder::DepthMajor>, 2>,
KernelSideFormat<CellFormat<5, 4, CellOrder::DepthMajor>, 3>>>>(&context);
test_gemm_kernel<ReferenceKernel<KernelFormat<
KernelSideFormat<CellFormat<3, 4, CellOrder::WidthMajor>, 2>,
KernelSideFormat<CellFormat<5, 4, CellOrder::WidthMajor>, 3>>>>(&context);
test_gemm_kernel<ReferenceKernel<KernelFormat<
KernelSideFormat<CellFormat<5, 2, CellOrder::WidthMajor>, 3>,
KernelSideFormat<CellFormat<4, 2, CellOrder::DepthMajor>, 2>>>>(&context);
test_gemm_kernel<ReferenceKernel<KernelFormat<
KernelSideFormat<CellFormat<5, 2, CellOrder::DepthMajor>, 3>,
KernelSideFormat<CellFormat<4, 2, CellOrder::WidthMajor>, 2>>>>(&context);
test_gemm_kernel<ReferenceKernel<KernelFormat<
KernelSideFormat<CellFormat<8, 8, CellOrder::Diagonal>, 2>,
KernelSideFormat<CellFormat<3, 8, CellOrder::WidthMajor>, 1>>>>(&context);
test_gemm_kernel<ReferenceKernel<KernelFormat<
KernelSideFormat<CellFormat<1, 4, CellOrder::DepthMajor>, 1>,
KernelSideFormat<CellFormat<4, 4, CellOrder::Diagonal>, 1>>>>(&context);
}
#endif // not GEMMLOWP_SKIP_EXHAUSTIVE_TESTS
template <typename BitDepthParams>
void TestOutputStages() {
// Test non-default output pipelines with various combinations of
// output stages.
TestOutputStages<BitDepthParams, MapOrder::RowMajor>(63, 10, 127, 5, 17, 14);
TestOutputStages<BitDepthParams, MapOrder::ColMajor>(63, 10, 127, 5, 17, 14);
TestOutputStages<BitDepthParams, MapOrder::RowMajor>(630, 10, 1270, 5, 17,
14);
TestOutputStages<BitDepthParams, MapOrder::ColMajor>(630, 10, 1270, 5, 17,
14);
}
void test() {
#ifdef GEMMLOWP_TEST_PROFILE
RegisterCurrentThreadForProfiling();
StartProfiling();
#endif
// Run a first quick test against hand-calculated data.
TestWithSmallData();
#ifndef GEMMLOWP_SKIP_EXHAUSTIVE_TESTS
TestExhaustively<DefaultL8R8BitDepthParams>();
TestExhaustively<L8R8WithLhsNonzeroBitDepthParams>();
TestExhaustively<DefaultL7R5BitDepthParams>(); // legacy, same as L8R8
TestExhaustivelyEightBitIntGemm<eight_bit_int_gemm::BitDepthSetting::A8B8>();
TestExhaustivelyEightBitIntGemm<eight_bit_int_gemm::BitDepthSetting::A5B7>();
TestKernels();
#endif
// Run against actual data from a network evaluation.
TestWithRealData(eight_bit_int_gemm::BitDepthSetting::A8B8, 0, 0);
TestWithRealData(eight_bit_int_gemm::BitDepthSetting::A5B7, 2, 10);
// Test non-default output pipelines with various combinations of
// output stages.
TestOutputStages<DefaultL8R8BitDepthParams>();
TestOutputStages<L8R8WithLhsNonzeroBitDepthParams>();
// Test per channel quantization.
TestWithSmallDataPerChannelQuantization();
TestWithLargeDataPerChannelQuantization();
TestMultithreadedPerChannelQuantization();
#ifdef GEMMLOWP_TEST_PROFILE
FinishProfiling();
#endif
std::cerr << "All tests passed." << std::endl;
// We have been testing the eight_bit_int_gemm, so we should free its
// persistent
// resources now to avoid having leak-checking tools report leaks.
eight_bit_int_gemm::FreePersistentResources();
}
} // end namespace gemmlowp
// For iOS, we need to define our own main(), so skip it here.
#if !(defined(__APPLE__) && (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR))
int main() { gemmlowp::test(); }
#endif
| apache-2.0 |
juniorug/vidacon | js/myMail/classes/libs/InlineStyle.php | 53238 | <?php
/*
* InlineStyle MIT License
*
* Copyright (c) 2010 Christiaan Baartse
*
* 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.
*/
/**
* Parses a html file and applies all embedded and external stylesheets inline
*
* @author Christiaan Baartse <[email protected]>
* @copyright 2010 Christiaan Baartse
*/
class InlineStyle
{
/**
* @var DOMDocument the HTML as DOMDocument
*/
protected $_dom;
/**
* @var CSSQuery instance to use css based selectors on our DOMDocument
*/
protected $_cssquery;
/**
* Prepare all the necessary objects
*
* @param string $html
*/
public function __construct($html, $encoding = 'UTF-8') {
if(!class_exists("CSSQuery")) {
throw new Exception(
"InlineStyle needs the CSSQuery class");
}
$html = htmlspecialchars_decode(htmlentities((string) $html, ENT_NOQUOTES, $encoding), ENT_NOQUOTES);
$this->_dom = new DOMDocument();
$this->_dom->formatOutput = true;
$this->_dom->preserveWhitespace = false;
if(file_exists($html)) {
$this->_dom->loadHTMLFile($html);
}
else {
$this->_dom->loadHTML($html);
}
$this->_cssquery = new CSSQuery($this->_dom);
}
/**
* Applies one or more stylesheets to the current document
*
* @param string $stylesheet
* @return InlineStyle self
*/
public function applyStylesheet($stylesheet) {
$stylesheet = (array) $stylesheet;
foreach($stylesheet as $ss) {
foreach($this->parseStylesheet($ss) as $arr) {
list($selector, $style) = $arr;
$this->applyRule($selector, $style);
}
}
return $this;
}
/**
* Applies a style rule on the document
* @param string $selector
* @param string $style
* @return InlineStyle self
*/
public function applyRule($selector, $style) {
$selector = trim(trim($selector), ",");
if($selector) {
$nodes = array();
foreach(explode(",", $selector) as $sel) {
if(false === stripos($sel, ":hover") &&
false === stripos($sel, ":active") &&
false === stripos($sel, ":link") &&
false === stripos($sel, ":visited")) {
$nodes = array_merge($nodes, $this->_cssquery->query($sel));
}
}
$style = $this->_styleToArray($style);
foreach($nodes as $node) {
$current = $node->hasAttribute("style") ?
$this->_styleToArray($node->getAttribute("style")) :
array();
$current = $this->_mergeStyles($current, $style);
$st = array();
foreach($current as $prop => $val) {
$st[] = "{$prop}:{$val}";
}
$node->setAttribute("style", implode(";", $st));
}
}
return $this;
}
/**
* Returns the DOMDocument as html
*
* @return string the HTML
*/
public function getHTML()
{
return $this->_dom->saveHTML();
}
/**
* Recursively extracts the stylesheet nodes from the DOMNode
* @param DOMNode $node leave empty to extract from the whole document
* @return array the extracted stylesheets
*/
public function extractStylesheets(DOMNode $node = null, $base = "")
{
if(null === $node) {
$node = $this->_dom;
}
$stylesheets = array();
if(strtolower($node->nodeName) === "style") {
$stylesheets[] = $node->nodeValue;
$node->parentNode->removeChild($node);
}
else if(strtolower($node->nodeName) === "link") {
if($node->hasAttribute("href")) {
$href = $node->getAttribute("href");
if($base && false === strpos($href, "://")) {
$href = "{$base}/{$href}";
}
$ext = @file_get_contents($href);
if($ext) {
$stylesheets[] = $ext;
$node->parentNode->removeChild($node);
}
}
}
if($node->hasChildNodes()) {
foreach($node->childNodes as $child) {
$stylesheets = array_merge($stylesheets,
$this->extractStylesheets($child, $base));
}
}
return $stylesheets;
}
/**
* Parses a stylesheet to selectors and properties
* @param string $stylesheet
* @return array
*/
public function parseStylesheet($stylesheet) {
$parsed = array();
$stylesheet = $this->_stripStylesheet($stylesheet);
$stylesheet = trim(trim($stylesheet), "}");
foreach(explode("}", $stylesheet) as $rule) {
list($selector, $style) = explode("{", $rule, 2);
$parsed[] = array(trim($selector), trim(trim($style), ";"));
}
return $parsed;
}
/**
* Parses style properties to a array which can be merged by mergeStyles()
* @param string $style
* @return array
*/
protected function _styleToArray($style) {
$styles = array();
$style = trim(trim($style), ";");
if($style) {
foreach(explode(";",$style) as $props) {
$props = trim(trim($props), ";");
preg_match('#^([-a-z0-9]+):(.*)$#i', $props, $matches);
list($match, $prop, $val) = $matches;
$styles[$prop] = $val;
}
}
return $styles;
}
/**
* Merges two sets of style properties taking !important into account
* @param array $styleA
* @param array $styleB
* @return array
*/
protected function _mergeStyles(array $styleA, array $styleB) {
foreach($styleB as $prop => $val) {
if(!isset($styleA[$prop]) ||
substr(str_replace(" ", "", strtolower($styleA[$prop])), -10) !==
"!important") {
$styleA[$prop] = $val;
}
}
return $styleA;
}
protected function _stripStylesheet($s)
{
$s = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!','', $s);
$s = str_replace(array("\r\n","\r","\n","\t",' ',' ',' '),'',$s);
$s = str_replace('{ ', '{', $s);
$s = str_replace(' }', '}', $s);
$s = str_replace('; ', ';', $s);
return $s;
}
}
/**
* This file has had some love from Christiaan Baartse <[email protected]>
*
* This package contains one class for using Cascading Style Sheet
* selectors to retrieve elements from a DOMDocument object similarly
* to DOMXPath does with XPath selectors
*
* PHP version 5
*
* @category HTML
* @package CSSQuery
* @author Sam Shull <[email protected]>
* @copyright Copyright (c) 2009 Sam Shull <[email protected]>
* @license <http://www.opensource.org/licenses/mit-license.html>
* @version 1.4
*
* 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.
*
* CHANGES:
* 06-08-2009 - added normalize-space function to CSSQuery::className
* and removed unecessary sprintf(s) in favor of " strings
* and fixed runtime pass-by-reference errors
* 07-14-2009 - added references and type hinting to many of the functions
* in order to improve performance a little
* 07-25-2009 - added support for class (.) and id (#) as filters (div#id.class)
* 08-05-2009 - corrected my horrible typing errors
* changed the attribute filter handling to match the entire operator
*/
/**
* Perform a CSS query on a DOMDocument using DOMXPath
*
* <code>
* $doc = new DOMDocument();
* $doc->loadHTML('<html><body><p>hello world</p></body></html>');
* $css = new CSSQuery($doc);
* print count( $css->query("p:contains('hello world')") );
* </code>
*
*
* @category HTML
* @package CSSQuery
* @author Sam Shull <[email protected]>
* @copyright Copyright (c) 2009 Sam Shull <[email protected]>
* @license <http://www.opensource.org/licenses/mit-license.html>
* @version Release: @package_version@
* @link
* @since Class available since Release 1.0
*/
class CSSQuery
{
/**
* This PCRE string matches one valid css selector at a time
*
* @const string
*/
const CHUNKER = '/^\s*([#\.>~\+:\[,]?)\s*(\*|[^\*#\.>~\+:\[\]\)\(\s,]*)/';
/**
* This PCRE string matches one psuedo css selector at a time
*
* @const string
*/
const PSUEDO = '/^\s*:([\w\-]+)\s*(\(\s*([^\(\)]*(\([^\(\)]*\))?)?\s*\))?\s*/';
/**
* This PCRE string matches one css attribute selector at a time
*
* @const string
*/
const ATTRIBUTES = '/\[@?([\w\-]+(\|[\w\-]+)?)\s*((\S*=)\s*([\'"]?)(?(5)([^\\5]*)\\5|([^\]]+)))?\s*\]/i';
/**
* An array of functions representing psuedo selectors
*
* @access public
*
* @staticvar array
*/
public static $filters;
/**
* An array of functions representing attribute selectors
*
* @access public
*
* @staticvar array
*/
public static $attributeFilters;
/**
* An instance of DOMXPath for finding the information on the document
*
* @access public
*
* @var DOMXPath
*/
public $xpath;
/**
* The document that the queries will originate from
*
* @access public
*
* @var DOMDocument
*/
public $document;
/**
* Initialize the object - opens a new DOMXPath
*
* @access public
*
* @param DOMDocument $document
*/
public function __construct (DOMDocument &$document)
{
$this->xpath = new DOMXPath($document);
$this->document =& $document;
}
/**
* register a namespace
*
* @access public
*
* @param string $prefix
* @param string $URI
*
* @returns boolean
*/
public function registerNamespace ($prefix, $URI)
{
return $this->xpath->registerNamespace($prefix, $URI);
}
/**
* Get an array of DOMNodes that match a CSS query expression
*
* @access public
*
* @param string $expression
* @param mixed $context - a DOMNode or an array of DOMNodes
*
* @returns array
*/
public function query ($expression, $context=null)
{
$original_context = func_num_args() < 3 ? $context : func_get_arg(2);
$current = $context instanceof DOMNode ? array($context) : self::makeArray($context);
$new = array();
$m = array('');
if ($expression && preg_match(self::CHUNKER, $expression, $m))
{
//replace a pipe with a semi-colon in a selector
//for namespace uses
$m[2] = $m[2] ? str_replace('|', ':', $m[2]) : '*';
switch ($m[1])
{
case ',':
{
$new = $this->query(ltrim(substr($expression, strpos($expression, $m[1]) + 1)), array(), $original_context);
$new = array_merge($current, $new);
return self::unique($new);
}
//#id
case '#':
{
$new = $this->id($m[2], $current);
break;
}
//.class
case '.':
{
$new = $this->className($m[2], $current);
break;
}
// > child
case '>':
{
$new = $this->children($m[2], $current);
break;
}
// + adjacent sibling
case '+':
{
$new = $this->adjacentSibling($m[2],$current);
break;
}
// ~ general sibling
case '~':
{
$new = $this->generalSibling($m[2], $current);
break;
}
//:psuedo-filter
case ':':
{
if ($m[2] == 'root')
{
$new = array($this->document->documentElement);
}
//a psuedo selector is a filter
elseif (preg_match(self::PSUEDO, $expression, $n))
{
if ($n[1] && isset(self::$filters[$n[1]]) && is_callable(self::$filters[$n[1]]))
{
if (!$current)
{
$current = $this->xpath->query('//*');
$current = self::makeArray($current);
}
$i = 0;
foreach ($current as $elem)
{
if ($item = call_user_func(self::$filters[$n[1]], $elem, $i++, $n, $current, $this))
{
if ($item instanceof DOMNode)
{
if (self::inArray($item, $new) < 0)
{
$new[] = $item;
}
}
//usually boolean
elseif (is_scalar($item))
{
if ($item)
{
$new[] = $elem;
}
}
else
{
$new = array_merge($new, self::makeArray($item));
$new = self::unique($new);
}
}
}
}
else
{
throw new Exception("Unknown psuedo-filter: {$m[2]}, in {$expression}");
}
//set this for the substr
$m[0] = $n[0];
}
else
{
throw new Exception("Unknown use of semi-colon: {$m[2]}, in {$expression}");
}
break;
}
//[attribute="value"] filter
case '[':
{
if (preg_match(self::ATTRIBUTES, $expression, $n))
{
//change a pipe to a semi-colon for namespace purposes
$n[1] = str_replace('|', ':', $n[1]);
if (!isset($n[4]) || !$n[4])
{
$n[4] = '';
$n[6] = null;
}
if (!isset(self::$attributeFilters[$n[4]]) || !is_callable(self::$attributeFilters[$n[4]]))
{
//print_r($n);
//thrown if there is no viable attributeFilter function for the given operator
throw new Exception("Unknown attribute filter: {$n[4]}");
}
if (!$current)
{
$current = $this->xpath->query('//*');
$current = self::makeArray($current);
}
foreach ($current as $elem)
{
if (true === call_user_func(self::$attributeFilters[$n[4]], $elem, $n[1], $n[6], $n, $current))
{
$new[] = $elem;
}
}
//set this for the substr
$m[0] = $n[0];
}
else
{
//only thrown if query is malformed
throw new Exception("Unidentified use of '[' in {$m[0]}");
}
break;
}
//just a tag - i.e. any descendant of the current context
default:
{
$new = $this->tag($m[2], $current);
break;
}
}
//check for # or . as filter
$exp = substr($expression, strlen($m[0]));
while ($exp && ($exp[0] == "." || $exp[0] == "#"))
{
if (preg_match(self::CHUNKER, $exp, $m))
{
$expression = $exp;
$new = $m[1] == "."
? $this->className($m[2], $new, true)
: $this->id($m[2], $new, true);
$exp = substr($expression, strlen($m[0]));
}
}
}
return (strlen($m[0]) < strlen($expression) && !empty($new))
//return strlen($m[0]) < strlen($expression)
? $this->query(substr($expression, strlen($m[0])), $new, $original_context)
: self::unique($new);
}
/**
* get an element by its id attribute
*
* @access public
*
* @param string $id
* @param array $context
*
* @returns array
*/
public function id (&$id, array &$context=array(), $filter=false)
{
$new = array();
//if a context is present - div#id should act like a filter
if ($filter || $context)
{
foreach ($context as $elem)
{
if ($elem instanceof DOMElement && $elem->hasAttribute('id') && $elem->getAttribute('id') == $id)
{
$new[] = $elem;
}
}
}
elseif (($items = $this->xpath->query("//*[@id='{$id}']")) && $items->length > 0)
{
foreach ($items as $item)
{
$new[] = $item;
}
}
return $new;
}
/**
* get an element by its class attribute
*
* @access public
*
* @param string $id
* @param array $context
*
* @returns array
*/
public function className (&$className, array &$context=array(), $filter=false)
{
$new = array();
if ($filter && $context)
{
$regex = '/\s+' . preg_quote($className, '/') . '\s+/';
foreach ($context as $elem)
{
if ($elem->hasAttribute('class') && preg_match($regex, " {$elem->getAttribute('class')} "))
{
$new[] = $elem;
}
}
}
//if there is a context for the query
elseif ($context)
{
//06-08-2009 - added normalize-space function, http://westhoffswelt.de/blog/0036_xpath_to_select_html_by_class.html
$query = "./descendant::*[ @class and contains( concat(' ', normalize-space(@class), ' '), ' {$className} ') ]";
foreach ($context as $elem)
{
if (
($items = $this->xpath->query($query, $elem)) &&
$items->length > 0
)
{
foreach ($items as $item)
{
$new[] = $item;
}
}
}
}
//otherwise select any element in the document that matches the selector
elseif (($items = $this->xpath->query("//*[ @class and contains( concat(' ', normalize-space(@class), ' '), ' {$className} ') ]")) && $items->length > 0)
{
foreach ($items as $item)
{
$new[] = $item;
}
}
return $new;
}
/**
* get the children elements
*
* @access public
*
* @param string $tag
* @param array $context
*
* @returns array
*/
public function children (&$tag='*', array &$context=array())
{
$new = array();
$query = "./{$tag}";
//if there is a context for the query
if ($context)
{
foreach ($context as $elem)
{
if (($items = $this->xpath->query($query, $elem)) && $items->length > 0)
{
foreach ($items as $item)
{
$new[] = $item;
}
}
}
}
//otherwise select any element in the document that matches the selector
elseif (($items = $this->xpath->query($query, $this->document->documentElement)) && $items->length > 0)
{
foreach ($items as $item)
{
$new[] = $item;
}
}
return $new;
}
/**
* get the adjacent sibling elements
*
* @access public
*
* @param string $tag
* @param array $context
*
* @returns array
*/
public function adjacentSibling (&$tag='*', array &$context=array())
{
$new = array();
$tag = strtolower($tag);
//if there is a context for the query
if ($context)
{
foreach ($context as $elem)
{
if ($tag == '*' || strtolower($elem->nextSibling->nodeName) == $tag)
{
$new[] = $elem->nextSibling;
}
}
}
return $new;
}
/**
* get the all sibling elements
*
* @access public
*
* @param string $tag
* @param array $context
*
* @returns array
*/
public function generalSibling (&$tag='*', array &$context=array())
{
$new = array();
//if there is a context for the query
if ($context)
{
$query = "./following-sibling::{$tag} | ./preceding-sibling::{$tag}";
foreach ($context as $elem)
{
if (($items = $this->xpath->query($query, $elem)) && $items->length > 0)
{
foreach ($items as $item)
{
$new[] = $item;
}
}
}
}
return $new;
}
/**
* get the all descendant elements
*
* @access public
*
* @param string $tag
* @param array $context
*
* @returns array
*/
public function tag (&$tag='*', array &$context=array())
{
$new = array();
//get all the descendants with the given tagName
if ($context)
{
$query = "./descendant::{$tag}";
foreach ($context as $elem)
{
if ($items = $this->xpath->query($query, $elem))
{
foreach ($items as $item)
{
$new[] = $item;
}
}
}
}
//get all elements with the given tagName
else
{
if ($items = $this->xpath->query("//{$tag}"))
{
foreach ($items as $item)
{
$new[] = $item;
}
}
}
return $new;
}
/**
* A utility function for calculating nth-* style psuedo selectors
*
* @static
* @access public
*
* @param DOMNode $context - the element whose position is being calculated
* @param string $func - the name of the psuedo function that is being calculated for
* @param string $expr - the string argument for the selector
* @param DOMXPath $xpath - an existing xpath instance for the document that the context belong to
*
* @returns boolean
*/
public static function nthChild (DOMNode &$context, $func, $expr, DOMXPath &$xpath)
{
//remove all the whitespace
$expr = preg_replace('/\s+/', '', trim(strtolower($expr)));
//all
if ($expr == 'n' || $expr == 'n+0' || $expr == '1n+0' || $expr == '1n')
{
return true;
}
//the direction we will look for siblings
$DIR = (stristr($func, 'last') ? 'following' : 'preceding');
//do a tagName check?
$type = stristr($func, 'type') ? '[local-name()=name(.)]' : '';
//the position of this node
$count = $xpath->evaluate("count( {$DIR}-sibling::*{$type} ) + 1", $context);
//odd
if($expr == 'odd' || $expr == '2n+1')
{
return $count % 2 != 0;
}
//even
elseif($expr == 'even' || $expr == '2n' || $expr == '2n+0')
{
return $count > 0 && $count % 2 == 0;
}
//a particular position
elseif(preg_match('/^([\+\-]?\d+)$/i', $expr, $mat))
{
$d = (stristr($func, 'last') ? -1 : 1) * intval($mat[1]);
$r = $xpath->query(sprintf('../%s', $type ? $context->tagName : '*'), $context);
return $r && $r->length >= abs($d) && ($d > 0 ? $r->item($d - 1)->isSameNode($context) : $r->item($r->length + $d)->isSameNode($context));
}
//grouped after a particular position
elseif(preg_match('/^([\+\-]?\d*)?n([\+\-]\d+)?/i', $expr, $mat))
{
$a = (isset($mat[2]) && $mat[2] ? intval($mat[2]) : 0);
$b = (isset($mat[2]) && $mat[2] ? intval($mat[2]) : 1);
return ($a == 0 && $count == $b) ||
($a > 0 && $count >= $b && ($count - $b) % $a == 0) ||
($a < 0 && $count <= $b && (($b - $count) % ($a * -1)) == 0);
}
return false;
}
/**
* A utility function for filtering inputs of a specific type
*
* @static
* @access public
*
* @param mixed $elem
* @param string $type
*
* @returns boolean
*/
public static function inputFilter (&$elem, $type)
{
$t = trim(strtolower($type));
//gotta be a -DOMNode- DOMElement
return $elem instanceof DOMElement &&
//with the tagName input
strtolower($elem->tagName) == 'input' &&
(
($t == 'text' && !$elem->hasAttribute('type')) ||
($t == 'button' && strtolower($e->tagName) == "button") ||
(
//and the attribute type
$elem->hasAttribute('type') &&
//the attribute type should match the given variable type case insensitive
trim(strtolower($elem->getAttribute('type'))) == $t
)
);
}
/**
* A utility function for making an iterable object into an array
*
* @static
* @access public
*
* @param array|Traversable $arr
*
* @return array
*/
public static function makeArray (&$arr)
{
if (is_array($arr))
{
return array_values($arr);
}
$ret = array();
if ($arr)
{
foreach ($arr as $elem)
{
$ret[count($ret)] = $elem;
}
}
return $ret;
}
/**
* A utility function for stripping duplicate elements from an array
* works on DOMNodes
*
* @static
* @access public
*
* @param array|Traversable $arr
*
* @returns array
*/
public static function unique (&$arr)
{
//first step make sure all the elements are unique
$new = array();
foreach ($arr as $current)
{
if (
//if the new array is empty
//just put the element in the array
empty($new) ||
(
//if it is not an instance of a DOMNode
//no need to check for isSameNode
!($current instanceof DOMNode) &&
!in_array($current, $new)
) ||
//do DOMNode test on array
self::inArray($current, $new) < 0
)
{
$new[] = $current;
}
}
return $new;
}
/**
* A utility function for determining the position of an element in an array
* works on DOMNodes, returns -1 on failure
*
* @static
* @access public
*
* @param mixed $elem
* @param array|Traversable $arr
*
* @returns integer
*/
public static function inArray (DOMNode $elem, $arr)
{
$i = 0;
foreach ($arr as $current)
{
//if it is an identical object or a DOMElement that represents the same node
if ($current === $elem || ($current instanceof DOMNode && $current->isSameNode($elem)))
{
return $i;
}
$i += 1;
}
return -1;
}
/**
* A utility function for filtering elements from an array or array-like object
*
* @static
* @access public
*
* @param mixed $elem
* @param array|Traversable $arr
*
* @returns array
*/
public static function filter ($array, $func)
{
$ret = array();
if (!is_callable($func))
{
return $array;
}
foreach ($array as $n => $v)
{
if (false !== call_user_func($func, $v, $n, $array, $this))
{
$ret[] = $v;
}
}
return $ret;
}
/**
* A static function designed to make it easier to get the info
*
* @static
* @access public
*
* @param string $query
* @param mixed $context
* @param array|Traversable $ret - passed by reference
*
* @return array
*/
public static function find ($query, $context, $ret=null)
{
$new = array();
//query using DOMDocument
if ($context instanceof DOMDocument)
{
$css = new self($context);
$new = $css->query($query);
}
elseif ($context instanceof DOMNodeList)
{
if ($context->length)
{
$css = new self($context->item(0)->ownerDocument);
$new = $css->query($query, $context);
}
}
//should be an array if it isn't a DOMNode
//in which case the first element should be a DOMNode
//representing the desired context
elseif (!($context instanceof DOMNode) && count($context))
{
$css = new self($context[0]->ownerDocument);
$new = $css->query($query, $context);
}
//otherwise use the ownerDocument and the context as the context of the query
else
{
$css = new self($context->ownerDocument);
$new = $css->query($query, $context);
}
//if there is a place to store the newly selected elements
if ($ret)
{
//append the newly selected elements to the given array|object
//or if it is an instance of ArrayAccess just push it on to the object
if (is_array($ret))
{
$new = array_merge($ret, $new);
$new = self::unique($new);
$ret = $new;
}
elseif (is_object($ret))
{
if ($ret instanceof ArrayAccess)
{
foreach ($new as $elem)
{
$ret[count($ret)] = $elem;
}
}
//appending elements to a DOMDocumentFragment is a fast way to move them around
elseif ($ret instanceof DOMDocumentFragment)
{
foreach ($new as $elem)
{
//appendChild, but don't forget to verify same document
$ret->appendChild( !$ret->ownerDocument->isSameNode($elem->ownerDocument)
? $ret->ownerDocument->importNode($elem, true)
: $elem);
}
}
//otherwise we need to find a method to use to attach the elements
elseif (($m = method_exists($ret, 'push')) || method_exists($ret, 'add'))
{
$method = $m ? 'push' : 'add';
foreach ($new as $elem)
{
$ret->$method($elem);
}
}
elseif (($m = method_exists($ret, 'concat')) || method_exists($ret, 'concatenate'))
{
$method = $m ? 'concat' : 'concatenate';
$ret->$method($new);
}
}
//this will save the selected elements into a string
elseif (is_string($ret))
{
foreach ($new as $elem)
{
$ret .= $elem->ownerDocument->saveXML($elem);
}
}
}
return $new;
}
}
/**
* this creates the default filters array on the CSSQuery object
*
* <code>
* //prototype function (DOMNode $element, integer $i, array $matches, array $context, CSSQuery $cssQuery);
* CSSQuery::$filters['myfilter'] = create_function('', '');
*
* </code>
*/
CSSQuery::$filters = new RecursiveArrayIterator(array(
//CSS3 selectors
'first-child' => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', 'return !$e->isSameNode($e->ownerDocument->documentElement) &&
$c->xpath->query("../*[position()=1]", $e)->item(0)->isSameNode($e);'),
'last-child' => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', 'return !$e->isSameNode($e->ownerDocument->documentElement) &&
$c->xpath->query("../*[last()]", $e)->item(0)->isSameNode($e);'),
'only-child' => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', 'return !$e->isSameNode($e->ownerDocument->documentElement) &&
$e->parentNode->getElementsByTagName("*")->length == 1;'),
'checked' => create_function('DOMNode $e', 'return strtolower($e->tagName) == "input" && $e->hasAttribute("checked");'),
'disabled' => create_function('DOMNode $e', 'return $e->hasAttribute("disabled") &&
stristr("|input|textarea|select|button|", "|".$e->tagName."|") !== false;'),
'enabled' => create_function('DOMNode $e', 'return !$e->hasAttribute("disabled") &&
stristr("|input|textarea|select|button|", "|".$e->tagName . "|") !== false &&
(!$e->hasAttribute("type") || strtolower($e->getAttribute("type")) != "hidden");'),
//nth child selectors
"nth-child" => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', 'return CSSQuery::nthChild($e, "nth-child", $m[3], $c->xpath);'),
"nth-last-child" => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', 'return CSSQuery::nthChild($e, "nth-last-child", $m[3], $c->xpath);'),
"nth-of-type" => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', 'return CSSQuery::nthChild($e, "nth-of-type", $m[3], $c->xpath);'),
"nth-last-of-type" => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', 'return CSSQuery::nthChild($e, "nth-last-of-type", $m[3], $c->xpath);'),
"first-of-type" => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', 'return call_user_func(CSSQuery::$filters["nth-of-type"], $e, $i, array(0,1,1,1), $a, $c);'),
"last-of-type" => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', 'return call_user_func(CSSQuery::$filters["nth-last-of-type"],$e, $i, array(0,1,1,1), $a, $c);'),
"only-of-type" => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', 'return call_user_func(CSSQuery::$filters["first-of-type"], $e, $i, $m, $a, $c) &&
call_user_func(CSSQuery::$filters["last-of-type"], $e, $i, $m, $a, $c);'),
//closest thing to the lang filter
"lang" => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', 'return $c->xpath->evaluate(
sprintf(
"count(./ancestor-or-self::*[@lang and (@lang =".
" \"%s\" or substring(@lang, 1, %u)=\"%s-\")])",
$m[3],
strlen($m[3]) + 1,
$m[3]
),
$e
) > 0;'),
//negation filter
"not" => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', 'return CSSQuery::inArray($e, $c->query(trim($m[3]))) == -1;'),
//element has no child nodes
"empty" => create_function('DOMNode $e', 'return !$e->hasChildNodes();'),
//element has child nodes that are elements
"parent" => create_function('DOMNode $e', 'return ($n = $e->getElementsByTagName("*")) && $n->length > 0;'),
//get the parent node of the current element
"parent-node" => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', '//if there is no filter just return the first parentNode
if (!$m || !isset($m[3]) || !trim($m[3])) return $e->parentNode;
//otherwise if the filter is more than a tagName
return preg_match("/^(\*|\w+)([^\w]+.+)/", trim($m[3]), $n)
? CSSQuery::find(trim($n[2]), $c->xpath->query("./ancestor::{$n[1]}", $e))
//if the filter is only a tagName save the trouble
: $c->xpath->query(sprintf("./ancestor::%s", trim($m[3])), $e);'),
//get the ancestors of the current element
"parents" => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', '$r = $c->xpath->query("./ancestor::*", $e);
return $m && isset($m[3]) && trim($m[3]) ? CSSQuery::find(trim($m[3]), $r) : $r;'),
//the element has nextSiblings
"next-sibling" => create_function('DOMNode $e', 'return ($n = $e->parentNode->getElementsByTagName("*"))
&& !$n->item($n->length-1)->isSameNode($e);'),
//the element has previousSiblings
"previous-sibling" => create_function('DOMNode $e', 'return !$e->parentNode->getElementsByTagName("*")->item(0)->isSameNode($e);'),
//get the previousSiblings of the current element
"previous-siblings" => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', '$r = $c->xpath->query("./preceding-sibling::*", $e);
return $m && isset($m[3]) && trim($m[3]) ? CSSQuery::find(trim($m[3]), $r) : $r;'),
//get the nextSiblings of the current element
"next-siblings" => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', '$r = $c->xpath->query("./following-sibling::*", $e);
return $m && isset($m[3]) && trim($m[3]) ? CSSQuery::find(trim($m[3]), $r) : $r;'),
//get all the siblings of the current element
"siblings" => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', '$r = $c->xpath->query("./preceding-sibling::* | ./following-sibling::*", $e);
return $m && isset($m[3]) && trim($m[3]) ? CSSQuery::find(trim($m[3]), $r) : $r;'),
//select the header elements
"header" => create_function('DOMNode $e', 'return (bool)preg_match("/^h[1-6]$/i", $e->tagName);'),
//form element selectors
"selected" => create_function('DOMNode $e', 'return $e->hasAttribute("selected");'),
//any element that would be considered input based on tagName
"input" => create_function('DOMNode $e', 'return stristr("|input|textarea|select|button|", "|" . $e->tagName . "|") !== false;'),
//any input element and type
"radio" => create_function('DOMNode $e', 'return CSSQuery::inputFilter($e, "radio");'),
"checkbox" => create_function('DOMNode $e', 'return CSSQuery::inputFilter($e, "checkbox");'),
"file" => create_function('DOMNode $e', 'return CSSQuery::inputFilter($e, "file");'),
"password" => create_function('DOMNode $e', 'return CSSQuery::inputFilter($e, "password");'),
"submit" => create_function('DOMNode $e', 'return CSSQuery::inputFilter($e, "submit");'),
"image" => create_function('DOMNode $e', 'return CSSQuery::inputFilter($e, "image");'),
"reset" => create_function('DOMNode $e', 'return CSSQuery::inputFilter($e, "reset");'),
"button" => create_function('DOMNode $e', 'return CSSQuery::inputFilter($e, "button");'),
"text" => create_function('DOMNode $e', 'return CSSQuery::inputFilter($e, "text");'),
//limiting filter
"has" => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', 'return count($c->query($m[3], $e)) > 0;'),
//text limiting filter
"contains" => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', 'return strstr($e->textContent,
preg_replace("/^\s*([\'\"])(.*)\\\\1\s*$/", "\\\\2", $m[3]));'),
"Contains" => create_function('DOMNode $e,$i,$m,$a,CSSQuery $c', 'return stristr($e->textContent,
preg_replace("/^\s*([\'\"])(.*)\\\\1\s*$/", "\\\\2", $m[3]));'),
//positional selectors for the current node-set
"first" => create_function('DOMNode $e,$i', 'return $i === 0;'),
"last" => create_function('DOMNode $e,$i,$m,$a', 'return $i === (count($a) - 1);'),
"lt" => create_function('DOMNode $e,$i,$m', 'return $i < $m[3];'),
"gt" => create_function('DOMNode $e,$i,$m', 'return $i > $m[3];'),
"eq" => create_function('DOMNode $e,$i,$m', 'return $i === intval($m[3]);'),
//works like nth-child on the currently selected node-set
"nth" => create_function('DOMNode $e,$i,$m', '$expr = preg_replace("/\s+/", "", strtolower(trim($m[3])));
//these selectors select all so dont waste time figuring them out
if ($expr == "n" || $expr == "n+0" || $expr == "1n+0" || $expr == "1n")
{
return true;
}
//even numbered elements
elseif ($expr == "even" || $expr == "2n" || $expr == "2n+0")
{
return $i % 2 == 0;
}
//odd numbered elements
elseif ($expr == "odd" || $expr == "2n+1")
{
return $i % 2 != 0;
}
//positional - a negative position is not supported
elseif (preg_match("/^([\+\-]?\d+)$/i", $expr, $mat))
{
return $i == intval($mat[1]);
}
//grouped according to a position
elseif (preg_match("/^([\+\-]?\d*)?n([\+\-]\d+)?/i", $expr, $mat))
{
$a = (isset($mat[2]) && $mat[2] ? intval($mat[2]) : 0);
$b = (isset($mat[2]) && $mat[2] ? intval($mat[2]) : 1);
return ($a == 0 && $i == $b) ||
($a > 0 && $i >= $b && ($i - $b) % $a == 0) ||
($a < 0 && $i <= $b && (($b - $i) % ($a * -1)) == 0);
}
return false;
'),
), 2);
/**
* create a default array of attribute filters
*
* <code>
* //prototype function (DOMNode $element, string $attributeName, string $value = '', array $matches, array $context=array());
* CSSQuery::$attributeFilters['>'] = create_function('', '');
*
* </code>
*/
CSSQuery::$attributeFilters = new RecursiveArrayIterator(array(
//hasAttribute and/or attribute == value
"" => create_function('$e,$a,$v=null', 'return $e->hasAttribute($a);'),
//hasAttribute and/or attribute == value
"=" => create_function('$e,$a,$v=null', 'return $e->hasAttribute($a) && $e->getAttribute($a) == $v;'),
//!hasAttribute or attribute != value
"!=" => create_function('$e,$a,$v', 'return !$e->hasAttribute($a) || $e->getAttribute($a) != $v;'),
//hasAttribute and the attribute begins with value
"^=" => create_function('$e,$a,$v', 'return $e->hasAttribute($a) && substr($e->getAttribute($a), 0, strlen($v)) == $v;'),
//hasAttribute and the attribute ends with value
'$=' => create_function('$e,$a,$v', 'return $e->hasAttribute($a) && substr($e->getAttribute($a), -strlen($v)) == $v;'),
//hasAttribute and the attribute begins with value . -
"|=" => create_function('$e,$a,$v', 'return $e->hasAttribute($a) && substr($e->getAttribute($a), 0, strlen($v) + 1) == $v."-";'),
//hasAttribute and attribute contains value
"*=" => create_function('$e,$a,$v', 'return $e->hasAttribute($a) && strstr($e->getAttribute($a), $v);'),
//special
//hasAttribute and attribute contains value - case insensitive
"%=" => create_function('$e,$a,$v', 'return $e->hasAttribute($a) && stristr($e->getAttribute($a), $v);'),
//hasAttribute and the attrributes value matches the given PCRE pattern
"@=" => create_function('$e,$a,$v', 'return $e->hasAttribute($a) && preg_match($v, $e->getAttribute($a));'),
), 2);
?> | apache-2.0 |
hnafar/IronJS | Src/Tests/ietestcenter/chapter15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-45.js | 2309 | /// Copyright (c) 2009 Microsoft Corporation
///
/// Redistribution and use in source and binary forms, with or without modification, are permitted provided
/// that the following conditions are met:
/// * Redistributions of source code must retain the above copyright notice, this list of conditions and
/// the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
/// the following disclaimer in the documentation and/or other materials provided with the distribution.
/// * Neither the name of Microsoft nor the names of its contributors may be used to
/// endorse or promote products derived from this software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
/// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
/// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
/// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
/// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
/// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
/// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
ES5Harness.registerTest({
id: "15.2.3.6-4-45",
path: "TestCases/chapter15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-45.js",
description: "Object.defineProperty - 'O' is the global object that uses Object's [[GetOwnProperty]] method to access the 'name' property (8.12.9 step 1)",
test: function testcase() {
try {
Object.defineProperty(fnGlobalObject(), "foo", {
value: 12,
configurable: true
});
return dataPropertyAttributesAreCorrect(fnGlobalObject(), "foo", 12, false, false, true);
} finally {
delete fnGlobalObject().foo;
}
},
precondition: function prereq() {
return fnExists(Object.defineProperty);
}
});
| apache-2.0 |
googlefonts/TachyFont | run_time/src/gae_server/www/js/tachyfont/work_queue.js | 5429 | 'use strict';
/**
* @license
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
goog.provide('tachyfont.WorkQueue');
goog.require('goog.Promise');
goog.require('tachyfont.Reporter');
/**
* This class manages work queues.
* @param {string} name An identifier useful for error reports.
* @constructor @struct @final
*/
tachyfont.WorkQueue = function(name) {
/** @private @const {string} */
this.name_ = name;
/** @private {!Array<!tachyfont.WorkQueue.Task>} */
this.queue_ = [];
};
/**
* Adds a task.
* @param {function(?)} taskFunction The function to call.
* @param {*} data The data to pass to the function.
* @param {string} fontId An identifier useful for error messages.
* @param {number=} opt_watchDogTime Option watch dog time.
* @return {!tachyfont.WorkQueue.Task} A task object.
*/
tachyfont.WorkQueue.prototype.addTask = function(
taskFunction, data, fontId, opt_watchDogTime) {
var task = new tachyfont.WorkQueue.Task(
taskFunction, data, fontId, opt_watchDogTime);
this.queue_.push(task);
if (this.queue_.length == 1) {
this.runNextTask();
}
return task;
};
/**
* Runs a task.
*/
tachyfont.WorkQueue.prototype.runNextTask = function() {
if (this.queue_.length < 1) {
return;
}
var task = this.queue_[0];
task.run().thenAlways(
/** @this {tachyfont.WorkQueue} */
function() {
this.queue_.shift();
this.runNextTask();
},
this);
};
/**
* Gets the queue length.
* @return {number}
*/
tachyfont.WorkQueue.prototype.getLength = function() {
return this.queue_.length;
};
/**
* Enum for error values.
* @enum {string}
*/
// LINT.IfChange
tachyfont.WorkQueue.Error = {
FILE_ID: 'EWQ',
WATCH_DOG_TIMER: '01',
END: '00'
};
// LINT.ThenChange(//depot/google3/\
// java/com/google/i18n/tachyfont/boq/gen204/error-reports.properties)
/**
* The error reporter for this file.
* @param {string} errNum The error number;
* @param {string} errId Identifies the error.
* @param {*} errInfo The error object;
*/
tachyfont.WorkQueue.reportError = function(errNum, errId, errInfo) {
tachyfont.Reporter.reportError(
tachyfont.WorkQueue.Error.FILE_ID + errNum, errId, errInfo);
};
/**
* Gets the work queue name
* @return {string}
*/
tachyfont.WorkQueue.prototype.getName = function() {
return this.name_;
};
/**
* A class that holds a task.
* @param {function(?)} taskFunction The function to call.
* @param {*} data The data to pass to the function.
* @param {string} fontId An indentifer for error reporting.
* @param {number=} opt_watchDogTime Option watch dog time.
* @constructor @struct @final
*/
tachyfont.WorkQueue.Task = function(
taskFunction, data, fontId, opt_watchDogTime) {
var resolver;
/** @private {function(?)} */
this.function_ = taskFunction;
/** @private {*} */
this.data_ = data;
/** @private {string} */
this.fontId_ = fontId;
/** @private {!goog.Promise<?,?>} */
this.result_ = new goog.Promise(function(resolve, reject) { //
resolver = resolve;
});
/** @private {function(*=)} */
this.resolver_ = resolver;
/** @private {?number} */
this.timeoutId_ = null;
/** @private {number} */
this.watchDogTime_ =
opt_watchDogTime || tachyfont.WorkQueue.Task.WATCH_DOG_TIME;
};
/**
* The time in milliseconds to wait before reporting that a running task did not
* complete.
* @type {number}
*/
tachyfont.WorkQueue.Task.WATCH_DOG_TIME = 10 * 60 * 1000;
/**
* Gets the task result promise (may be unresolved).
* @return {!goog.Promise<?,?>}
*/
tachyfont.WorkQueue.Task.prototype.getResult = function() {
return this.result_;
};
/**
* Resolves the task result promise.
* @param {*} result The result of the function. May be any value including a
* resolved/rejected promise.
* @return {!goog.Promise<?,?>}
* @private
*/
tachyfont.WorkQueue.Task.prototype.resolve_ = function(result) {
this.resolver_(result);
return this.result_;
};
/**
* Runs the task.
* @return {*}
*/
tachyfont.WorkQueue.Task.prototype.run = function() {
this.startWatchDogTimer_();
var result;
try {
result = this.function_(this.data_);
} catch (e) {
result = goog.Promise.reject(e);
}
this.result_.thenAlways(function() { //
this.stopWatchDogTimer_();
}.bind(this));
return this.resolve_(result);
};
/**
* Starts the watch dog timer.
* @return {*}
* @private
*/
tachyfont.WorkQueue.Task.prototype.startWatchDogTimer_ = function() {
this.timeoutId_ = setTimeout(function() {
this.timeoutId_ = null;
tachyfont.WorkQueue.reportError(
tachyfont.WorkQueue.Error.WATCH_DOG_TIMER, this.fontId_, '');
}.bind(this), this.watchDogTime_);
};
/**
* Stops the watch dog timer.
* @private
*/
tachyfont.WorkQueue.Task.prototype.stopWatchDogTimer_ = function() {
if (this.timeoutId_) {
clearTimeout(this.timeoutId_);
}
this.timeoutId_ = null;
};
| apache-2.0 |
peter-gergely-horvath/kylo | core/operational-metadata/operational-metadata-jpa/src/main/java/com/thinkbiganalytics/metadata/jpa/app/JpaKyloVersionProvider.java | 3679 | package com.thinkbiganalytics.metadata.jpa.app;
/*-
* #%L
* thinkbig-operational-metadata-jpa
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* 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.
* #L%
*/
import com.thinkbiganalytics.KyloVersionUtil;
import com.thinkbiganalytics.KyloVersion;
import com.thinkbiganalytics.metadata.api.app.KyloVersionProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Properties;
import javax.annotation.PostConstruct;
/**
* Provider for accessing and updating the Kylo version
*/
public class JpaKyloVersionProvider implements KyloVersionProvider {
private static final Logger log = LoggerFactory.getLogger(JpaKyloVersionProvider.class);
private static final Sort SORT_ORDER = new Sort(new Sort.Order(Direction.DESC, "majorVersion"),
new Sort.Order(Direction.DESC, "minorVersion"),
new Sort.Order(Direction.DESC, "pointVersion"),
new Sort.Order(Direction.DESC, "tag") );
private KyloVersionRepository kyloVersionRepository;
private String currentVersion;
private String buildTimestamp;
@Autowired
public JpaKyloVersionProvider(KyloVersionRepository kyloVersionRepository) {
this.kyloVersionRepository = kyloVersionRepository;
}
@Override
public boolean isUpToDate() {
KyloVersion buildVer = KyloVersionUtil.getBuildVersion();
KyloVersion currentVer = getCurrentVersion();
return currentVer != null && buildVer.matches(currentVer.getMajorVersion(),
currentVer.getMinorVersion(),
currentVer.getPointVersion());
}
@Override
public KyloVersion getCurrentVersion() {
List<JpaKyloVersion> versions = kyloVersionRepository.findAll(SORT_ORDER);
if (versions != null && !versions.isEmpty()) {
return versions.get(0);
}
return null;
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.metadata.api.app.KyloVersionProvider#setCurrentVersion(com.thinkbiganalytics.KyloVersion)
*/
@Override
public void setCurrentVersion(KyloVersion version) {
JpaKyloVersion update = new JpaKyloVersion(version.getMajorVersion(),
version.getMinorVersion(),
version.getPointVersion(),
version.getTag());
kyloVersionRepository.save(update);
}
@Override
public KyloVersion getBuildVersion() {
return KyloVersionUtil.getBuildVersion();
}
@PostConstruct
private void init() {
getBuildVersion();
}
}
| apache-2.0 |
Tycheo/coffeemud | com/planet_ink/coffee_mud/Abilities/Spells/Spell_ArcaneMark.java | 3763 | package com.planet_ink.coffee_mud.Abilities.Spells;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2003-2015 Bo Zimmerman
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.
*/
@SuppressWarnings("rawtypes")
public class Spell_ArcaneMark extends Spell
{
@Override public String ID() { return "Spell_ArcaneMark"; }
private final static String localizedName = CMLib.lang().L("Arcane Mark");
@Override public String name() { return localizedName; }
@Override public int abstractQuality(){ return Ability.QUALITY_INDIFFERENT;}
@Override protected int canAffectCode(){return 0;}
@Override protected int canTargetCode(){return CAN_ITEMS;}
@Override public int classificationCode(){ return Ability.ACODE_SPELL|Ability.DOMAIN_ALTERATION;}
@Override
public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
{
if(commands.size()<2)
{
mob.tell(L("You must specify what object you want the spell cast on, and the message you wish the object have marked upon it. "));
return false;
}
final Physical target=mob.location().fetchFromMOBRoomFavorsItems(mob,null,((String)commands.elementAt(0)),Wearable.FILTER_UNWORNONLY);
if((target==null)||(!CMLib.flags().canBeSeenBy(target,mob)))
{
mob.tell(L("You don't see '@x1' here.",((String)commands.elementAt(0))));
return false;
}
if((!(target instanceof Item))||(!target.isGeneric()))
{
mob.tell(L("You can't can't cast this on @x1.",target.name(mob)));
return false;
}
final String message=CMParms.combine(commands,1);
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),L("^S<S-NAME> invoke(s) a spell upon <T-NAMESELF>.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
if(target.description().indexOf("Some markings on it say")>=0)
target.setDescription(L("@x1 Some other markings say `@x2`.",target.description(),message));
else
target.setDescription(L("@x1 Some markings on it say `@x2`.",target.description(),message));
}
}
else
beneficialWordsFizzle(mob,target,L("<S-NAME> attempt(s) to invoke a spell upon <T-NAMESELF>, but the spell fizzles."));
// return whether it worked
return success;
}
}
| apache-2.0 |
creatorlxd/Space | Source/GameEngine/ThirdParty/FX11/inc/d3dx11effect.h | 54214 | //--------------------------------------------------------------------------------------
// File: D3DX11Effect.h
//
// Direct3D 11 Effect Types & APIs Header
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// http://go.microsoft.com/fwlink/p/?LinkId=271568
//--------------------------------------------------------------------------------------
#pragma once
#define D3DX11_EFFECTS_VERSION 1119
#if defined(_XBOX_ONE) && defined(_TITLE)
#include <d3d11_x.h>
#define DCOMMON_H_INCLUDED
#define NO_D3D11_DEBUG_NAME
#else
#include <d3d11_1.h>
#include <d3d11shader.h>
#endif
#pragma comment( lib, "d3dcompiler.lib" )
#pragma comment( lib, "dxguid.lib" )
#include <stdint.h>
//////////////////////////////////////////////////////////////////////////////
// File contents:
//
// 1) Stateblock enums, structs, interfaces, flat APIs
// 2) Effect enums, structs, interfaces, flat APIs
//////////////////////////////////////////////////////////////////////////////
#ifndef D3DX11_BYTES_FROM_BITS
#define D3DX11_BYTES_FROM_BITS(x) (((x) + 7) / 8)
#endif // D3DX11_BYTES_FROM_BITS
#ifndef D3DERR_INVALIDCALL
#define D3DERR_INVALIDCALL MAKE_HRESULT( 1, 0x876, 2156 )
#endif
struct D3DX11_STATE_BLOCK_MASK
{
uint8_t VS;
uint8_t VSSamplers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT)];
uint8_t VSShaderResources[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)];
uint8_t VSConstantBuffers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT)];
uint8_t VSInterfaces[D3DX11_BYTES_FROM_BITS(D3D11_SHADER_MAX_INTERFACES)];
uint8_t HS;
uint8_t HSSamplers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT)];
uint8_t HSShaderResources[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)];
uint8_t HSConstantBuffers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT)];
uint8_t HSInterfaces[D3DX11_BYTES_FROM_BITS(D3D11_SHADER_MAX_INTERFACES)];
uint8_t DS;
uint8_t DSSamplers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT)];
uint8_t DSShaderResources[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)];
uint8_t DSConstantBuffers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT)];
uint8_t DSInterfaces[D3DX11_BYTES_FROM_BITS(D3D11_SHADER_MAX_INTERFACES)];
uint8_t GS;
uint8_t GSSamplers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT)];
uint8_t GSShaderResources[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)];
uint8_t GSConstantBuffers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT)];
uint8_t GSInterfaces[D3DX11_BYTES_FROM_BITS(D3D11_SHADER_MAX_INTERFACES)];
uint8_t PS;
uint8_t PSSamplers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT)];
uint8_t PSShaderResources[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)];
uint8_t PSConstantBuffers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT)];
uint8_t PSInterfaces[D3DX11_BYTES_FROM_BITS(D3D11_SHADER_MAX_INTERFACES)];
uint8_t PSUnorderedAccessViews;
uint8_t CS;
uint8_t CSSamplers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT)];
uint8_t CSShaderResources[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)];
uint8_t CSConstantBuffers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT)];
uint8_t CSInterfaces[D3DX11_BYTES_FROM_BITS(D3D11_SHADER_MAX_INTERFACES)];
uint8_t CSUnorderedAccessViews;
uint8_t IAVertexBuffers[D3DX11_BYTES_FROM_BITS(D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT)];
uint8_t IAIndexBuffer;
uint8_t IAInputLayout;
uint8_t IAPrimitiveTopology;
uint8_t OMRenderTargets;
uint8_t OMDepthStencilState;
uint8_t OMBlendState;
uint8_t RSViewports;
uint8_t RSScissorRects;
uint8_t RSRasterizerState;
uint8_t SOBuffers;
uint8_t Predication;
};
//----------------------------------------------------------------------------
// D3DX11_EFFECT flags:
// -------------------------------------
//
// These flags are passed in when creating an effect, and affect
// the runtime effect behavior:
//
// (Currently none)
//
//
// These flags are set by the effect runtime:
//
// D3DX11_EFFECT_OPTIMIZED
// This effect has been optimized. Reflection functions that rely on
// names/semantics/strings should fail. This is set when Optimize() is
// called, but CEffect::IsOptimized() should be used to test for this.
//
// D3DX11_EFFECT_CLONE
// This effect is a clone of another effect. Single CBs will never be
// updated when internal variable values are changed.
// This flag is not set when the D3DX11_EFFECT_CLONE_FORCE_NONSINGLE flag
// is used in cloning.
//
//----------------------------------------------------------------------------
#define D3DX11_EFFECT_OPTIMIZED (1 << 21)
#define D3DX11_EFFECT_CLONE (1 << 22)
// Mask of valid D3DCOMPILE_EFFECT flags for D3DX11CreateEffect*
#define D3DX11_EFFECT_RUNTIME_VALID_FLAGS (0)
//----------------------------------------------------------------------------
// D3DX11_EFFECT_VARIABLE flags:
// ----------------------------
//
// These flags describe an effect variable (global or annotation),
// and are returned in D3DX11_EFFECT_VARIABLE_DESC::Flags.
//
// D3DX11_EFFECT_VARIABLE_ANNOTATION
// Indicates that this is an annotation on a technique, pass, or global
// variable. Otherwise, this is a global variable. Annotations cannot
// be shared.
//
// D3DX11_EFFECT_VARIABLE_EXPLICIT_BIND_POINT
// Indicates that the variable has been explicitly bound using the
// register keyword.
//----------------------------------------------------------------------------
#define D3DX11_EFFECT_VARIABLE_ANNOTATION (1 << 1)
#define D3DX11_EFFECT_VARIABLE_EXPLICIT_BIND_POINT (1 << 2)
//----------------------------------------------------------------------------
// D3DX11_EFFECT_CLONE flags:
// ----------------------------
//
// These flags modify the effect cloning process and are passed into Clone.
//
// D3DX11_EFFECT_CLONE_FORCE_NONSINGLE
// Ignore all "single" qualifiers on cbuffers. All cbuffers will have their
// own ID3D11Buffer's created in the cloned effect.
//----------------------------------------------------------------------------
#define D3DX11_EFFECT_CLONE_FORCE_NONSINGLE (1 << 0)
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectType //////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------
// D3DX11_EFFECT_TYPE_DESC:
//
// Retrieved by ID3DX11EffectType::GetDesc()
//----------------------------------------------------------------------------
struct D3DX11_EFFECT_TYPE_DESC
{
LPCSTR TypeName; // Name of the type
// (e.g. "float4" or "MyStruct")
D3D_SHADER_VARIABLE_CLASS Class; // (e.g. scalar, vector, object, etc.)
D3D_SHADER_VARIABLE_TYPE Type; // (e.g. float, texture, vertexshader, etc.)
uint32_t Elements; // Number of elements in this type
// (0 if not an array)
uint32_t Members; // Number of members
// (0 if not a structure)
uint32_t Rows; // Number of rows in this type
// (0 if not a numeric primitive)
uint32_t Columns; // Number of columns in this type
// (0 if not a numeric primitive)
uint32_t PackedSize; // Number of bytes required to represent
// this data type, when tightly packed
uint32_t UnpackedSize; // Number of bytes occupied by this data
// type, when laid out in a constant buffer
uint32_t Stride; // Number of bytes to seek between elements,
// when laid out in a constant buffer
};
typedef interface ID3DX11EffectType ID3DX11EffectType;
typedef interface ID3DX11EffectType *LPD3D11EFFECTTYPE;
// {4250D721-D5E5-491F-B62B-587C43186285}
DEFINE_GUID(IID_ID3DX11EffectType,
0x4250d721, 0xd5e5, 0x491f, 0xb6, 0x2b, 0x58, 0x7c, 0x43, 0x18, 0x62, 0x85);
#undef INTERFACE
#define INTERFACE ID3DX11EffectType
DECLARE_INTERFACE_(ID3DX11EffectType, IUnknown)
{
// IUnknown
// ID3DX11EffectType
STDMETHOD_(bool, IsValid)(THIS) PURE;
STDMETHOD(GetDesc)(THIS_ _Out_ D3DX11_EFFECT_TYPE_DESC *pDesc) PURE;
STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByIndex)(THIS_ _In_ uint32_t Index) PURE;
STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByName)(THIS_ _In_z_ LPCSTR Name) PURE;
STDMETHOD_(ID3DX11EffectType*, GetMemberTypeBySemantic)(THIS_ _In_z_ LPCSTR Semantic) PURE;
STDMETHOD_(LPCSTR, GetMemberName)(THIS_ _In_ uint32_t Index) PURE;
STDMETHOD_(LPCSTR, GetMemberSemantic)(THIS_ _In_ uint32_t Index) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectVariable //////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------
// D3DX11_EFFECT_VARIABLE_DESC:
//
// Retrieved by ID3DX11EffectVariable::GetDesc()
//----------------------------------------------------------------------------
struct D3DX11_EFFECT_VARIABLE_DESC
{
LPCSTR Name; // Name of this variable, annotation,
// or structure member
LPCSTR Semantic; // Semantic string of this variable
// or structure member (nullptr for
// annotations or if not present)
uint32_t Flags; // D3DX11_EFFECT_VARIABLE_* flags
uint32_t Annotations; // Number of annotations on this variable
// (always 0 for annotations)
uint32_t BufferOffset; // Offset into containing cbuffer or tbuffer
// (always 0 for annotations or variables
// not in constant buffers)
uint32_t ExplicitBindPoint; // Used if the variable has been explicitly bound
// using the register keyword. Check Flags for
// D3DX11_EFFECT_VARIABLE_EXPLICIT_BIND_POINT;
};
typedef interface ID3DX11EffectVariable ID3DX11EffectVariable;
typedef interface ID3DX11EffectVariable *LPD3D11EFFECTVARIABLE;
// {036A777D-B56E-4B25-B313-CC3DDAB71873}
DEFINE_GUID(IID_ID3DX11EffectVariable,
0x036a777d, 0xb56e, 0x4b25, 0xb3, 0x13, 0xcc, 0x3d, 0xda, 0xb7, 0x18, 0x73);
#undef INTERFACE
#define INTERFACE ID3DX11EffectVariable
// Forward defines
typedef interface ID3DX11EffectScalarVariable ID3DX11EffectScalarVariable;
typedef interface ID3DX11EffectVectorVariable ID3DX11EffectVectorVariable;
typedef interface ID3DX11EffectMatrixVariable ID3DX11EffectMatrixVariable;
typedef interface ID3DX11EffectStringVariable ID3DX11EffectStringVariable;
typedef interface ID3DX11EffectClassInstanceVariable ID3DX11EffectClassInstanceVariable;
typedef interface ID3DX11EffectInterfaceVariable ID3DX11EffectInterfaceVariable;
typedef interface ID3DX11EffectShaderResourceVariable ID3DX11EffectShaderResourceVariable;
typedef interface ID3DX11EffectUnorderedAccessViewVariable ID3DX11EffectUnorderedAccessViewVariable;
typedef interface ID3DX11EffectRenderTargetViewVariable ID3DX11EffectRenderTargetViewVariable;
typedef interface ID3DX11EffectDepthStencilViewVariable ID3DX11EffectDepthStencilViewVariable;
typedef interface ID3DX11EffectConstantBuffer ID3DX11EffectConstantBuffer;
typedef interface ID3DX11EffectShaderVariable ID3DX11EffectShaderVariable;
typedef interface ID3DX11EffectBlendVariable ID3DX11EffectBlendVariable;
typedef interface ID3DX11EffectDepthStencilVariable ID3DX11EffectDepthStencilVariable;
typedef interface ID3DX11EffectRasterizerVariable ID3DX11EffectRasterizerVariable;
typedef interface ID3DX11EffectSamplerVariable ID3DX11EffectSamplerVariable;
DECLARE_INTERFACE_(ID3DX11EffectVariable, IUnknown)
{
// IUnknown
// ID3DX11EffectVariable
STDMETHOD_(bool, IsValid)(THIS) PURE;
STDMETHOD_(ID3DX11EffectType*, GetType)(THIS) PURE;
STDMETHOD(GetDesc)(THIS_ _Out_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) PURE;
STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ _In_ uint32_t Index) PURE;
STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ _In_z_ LPCSTR Name) PURE;
STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(THIS_ _In_ uint32_t Index) PURE;
STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(THIS_ _In_z_ LPCSTR Name) PURE;
STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(THIS_ _In_z_ LPCSTR Semantic) PURE;
STDMETHOD_(ID3DX11EffectVariable*, GetElement)(THIS_ _In_ uint32_t Index) PURE;
STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(THIS) PURE;
STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(THIS) PURE;
STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(THIS) PURE;
STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(THIS) PURE;
STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(THIS) PURE;
STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(THIS) PURE;
STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(THIS) PURE;
STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)(THIS) PURE;
STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(THIS) PURE;
STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(THIS) PURE;
STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(THIS) PURE;
STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(THIS) PURE;
STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(THIS) PURE;
STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(THIS) PURE;
STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(THIS) PURE;
STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(THIS) PURE;
STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(THIS) PURE;
STDMETHOD(SetRawValue)(THIS_ _In_reads_bytes_(ByteCount) const void *pData, _In_ uint32_t ByteOffset, _In_ uint32_t ByteCount) PURE;
STDMETHOD(GetRawValue)(THIS_ _Out_writes_bytes_(ByteCount) void *pData, _In_ uint32_t ByteOffset, _In_ uint32_t ByteCount) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectScalarVariable ////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
typedef interface ID3DX11EffectScalarVariable ID3DX11EffectScalarVariable;
typedef interface ID3DX11EffectScalarVariable *LPD3D11EFFECTSCALARVARIABLE;
// {921EF2E5-A65D-4E92-9FC6-4E9CC09A4ADE}
DEFINE_GUID(IID_ID3DX11EffectScalarVariable,
0x921ef2e5, 0xa65d, 0x4e92, 0x9f, 0xc6, 0x4e, 0x9c, 0xc0, 0x9a, 0x4a, 0xde);
#undef INTERFACE
#define INTERFACE ID3DX11EffectScalarVariable
DECLARE_INTERFACE_(ID3DX11EffectScalarVariable, ID3DX11EffectVariable)
{
// IUnknown
// ID3DX11EffectVariable
// ID3DX11EffectScalarVariable
STDMETHOD(SetFloat)(THIS_ _In_ const float Value) PURE;
STDMETHOD(GetFloat)(THIS_ _Out_ float *pValue) PURE;
STDMETHOD(SetFloatArray)(THIS_ _In_reads_(Count) const float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
STDMETHOD(GetFloatArray)(THIS_ _Out_writes_(Count) float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
STDMETHOD(SetInt)(THIS_ _In_ const int Value) PURE;
STDMETHOD(GetInt)(THIS_ _Out_ int *pValue) PURE;
STDMETHOD(SetIntArray)(THIS_ _In_reads_(Count) const int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
STDMETHOD(GetIntArray)(THIS_ _Out_writes_(Count) int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
STDMETHOD(SetBool)(THIS_ _In_ const bool Value) PURE;
STDMETHOD(GetBool)(THIS_ _Out_ bool *pValue) PURE;
STDMETHOD(SetBoolArray)(THIS_ _In_reads_(Count) const bool *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
STDMETHOD(GetBoolArray)(THIS_ _Out_writes_(Count) bool *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectVectorVariable ////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
typedef interface ID3DX11EffectVectorVariable ID3DX11EffectVectorVariable;
typedef interface ID3DX11EffectVectorVariable *LPD3D11EFFECTVECTORVARIABLE;
// {5E785D4A-D87B-48D8-B6E6-0F8CA7E7467A}
DEFINE_GUID(IID_ID3DX11EffectVectorVariable,
0x5e785d4a, 0xd87b, 0x48d8, 0xb6, 0xe6, 0x0f, 0x8c, 0xa7, 0xe7, 0x46, 0x7a);
#undef INTERFACE
#define INTERFACE ID3DX11EffectVectorVariable
DECLARE_INTERFACE_(ID3DX11EffectVectorVariable, ID3DX11EffectVariable)
{
// IUnknown
// ID3DX11EffectVariable
// ID3DX11EffectVectorVariable
STDMETHOD(SetBoolVector) (THIS_ _In_reads_(4) const bool *pData) PURE;
STDMETHOD(SetIntVector) (THIS_ _In_reads_(4) const int *pData) PURE;
STDMETHOD(SetFloatVector)(THIS_ _In_reads_(4) const float *pData) PURE;
STDMETHOD(GetBoolVector) (THIS_ _Out_writes_(4) bool *pData) PURE;
STDMETHOD(GetIntVector) (THIS_ _Out_writes_(4) int *pData) PURE;
STDMETHOD(GetFloatVector)(THIS_ _Out_writes_(4) float *pData) PURE;
STDMETHOD(SetBoolVectorArray) (THIS_ _In_reads_(Count*4) const bool *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
STDMETHOD(SetIntVectorArray) (THIS_ _In_reads_(Count*4) const int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
STDMETHOD(SetFloatVectorArray)(THIS_ _In_reads_(Count*4) const float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
STDMETHOD(GetBoolVectorArray) (THIS_ _Out_writes_(Count*4) bool *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
STDMETHOD(GetIntVectorArray) (THIS_ _Out_writes_(Count*4) int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
STDMETHOD(GetFloatVectorArray)(THIS_ _Out_writes_(Count*4) float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectMatrixVariable ////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
typedef interface ID3DX11EffectMatrixVariable ID3DX11EffectMatrixVariable;
typedef interface ID3DX11EffectMatrixVariable *LPD3D11EFFECTMATRIXVARIABLE;
// {E1096CF4-C027-419A-8D86-D29173DC803E}
DEFINE_GUID(IID_ID3DX11EffectMatrixVariable,
0xe1096cf4, 0xc027, 0x419a, 0x8d, 0x86, 0xd2, 0x91, 0x73, 0xdc, 0x80, 0x3e);
#undef INTERFACE
#define INTERFACE ID3DX11EffectMatrixVariable
DECLARE_INTERFACE_(ID3DX11EffectMatrixVariable, ID3DX11EffectVariable)
{
// IUnknown
// ID3DX11EffectVariable
// ID3DX11EffectMatrixVariable
STDMETHOD(SetMatrix)(THIS_ _In_reads_(16) const float *pData) PURE;
STDMETHOD(GetMatrix)(THIS_ _Out_writes_(16) float *pData) PURE;
STDMETHOD(SetMatrixArray)(THIS_ _In_reads_(Count*16) const float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
STDMETHOD(GetMatrixArray)(THIS_ _Out_writes_(Count*16) float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
STDMETHOD(SetMatrixPointerArray)(_In_reads_(Count*16) const float **ppData, uint32_t Offset, uint32_t Count) PURE;
STDMETHOD(GetMatrixPointerArray)(_Out_writes_(Count*16) float **ppData, uint32_t Offset, uint32_t Count) PURE;
STDMETHOD(SetMatrixTranspose)(THIS_ _In_reads_(16) const float *pData) PURE;
STDMETHOD(GetMatrixTranspose)(THIS_ _Out_writes_(16) float *pData) PURE;
STDMETHOD(SetMatrixTransposeArray)(THIS_ _In_reads_(Count*16) const float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
STDMETHOD(GetMatrixTransposeArray)(THIS_ _Out_writes_(Count*16) float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
STDMETHOD(SetMatrixTransposePointerArray)(_In_reads_(Count*16) const float **ppData, uint32_t Offset, uint32_t Count) PURE;
STDMETHOD(GetMatrixTransposePointerArray)(_Out_writes_(Count*16) float **ppData, uint32_t Offset, uint32_t Count) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectStringVariable ////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
typedef interface ID3DX11EffectStringVariable ID3DX11EffectStringVariable;
typedef interface ID3DX11EffectStringVariable *LPD3D11EFFECTSTRINGVARIABLE;
// {F355C818-01BE-4653-A7CC-60FFFEDDC76D}
DEFINE_GUID(IID_ID3DX11EffectStringVariable,
0xf355c818, 0x01be, 0x4653, 0xa7, 0xcc, 0x60, 0xff, 0xfe, 0xdd, 0xc7, 0x6d);
#undef INTERFACE
#define INTERFACE ID3DX11EffectStringVariable
DECLARE_INTERFACE_(ID3DX11EffectStringVariable, ID3DX11EffectVariable)
{
// IUnknown
// ID3DX11EffectVariable
// ID3DX11EffectStringVariable
STDMETHOD(GetString)(THIS_ _Outptr_result_z_ LPCSTR *ppString) PURE;
STDMETHOD(GetStringArray)(THIS_ _Out_writes_(Count) LPCSTR *ppStrings, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectClassInstanceVariable ////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
typedef interface ID3DX11EffectClassInstanceVariable ID3DX11EffectClassInstanceVariable;
typedef interface ID3DX11EffectClassInstanceVariable *LPD3D11EFFECTCLASSINSTANCEVARIABLE;
// {926A8053-2A39-4DB4-9BDE-CF649ADEBDC1}
DEFINE_GUID(IID_ID3DX11EffectClassInstanceVariable,
0x926a8053, 0x2a39, 0x4db4, 0x9b, 0xde, 0xcf, 0x64, 0x9a, 0xde, 0xbd, 0xc1);
#undef INTERFACE
#define INTERFACE ID3DX11EffectClassInstanceVariable
DECLARE_INTERFACE_(ID3DX11EffectClassInstanceVariable, ID3DX11EffectVariable)
{
// IUnknown
// ID3DX11EffectVariable
// ID3DX11EffectClassInstanceVariable
STDMETHOD(GetClassInstance)(_Outptr_ ID3D11ClassInstance** ppClassInstance) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectInterfaceVariable ////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
typedef interface ID3DX11EffectInterfaceVariable ID3DX11EffectInterfaceVariable;
typedef interface ID3DX11EffectInterfaceVariable *LPD3D11EFFECTINTERFACEVARIABLE;
// {516C8CD8-1C80-40A4-B19B-0688792F11A5}
DEFINE_GUID(IID_ID3DX11EffectInterfaceVariable,
0x516c8cd8, 0x1c80, 0x40a4, 0xb1, 0x9b, 0x06, 0x88, 0x79, 0x2f, 0x11, 0xa5);
#undef INTERFACE
#define INTERFACE ID3DX11EffectInterfaceVariable
DECLARE_INTERFACE_(ID3DX11EffectInterfaceVariable, ID3DX11EffectVariable)
{
// IUnknown
// ID3DX11EffectVariable
// ID3DX11EffectInterfaceVariable
STDMETHOD(SetClassInstance)(_In_ ID3DX11EffectClassInstanceVariable *pEffectClassInstance) PURE;
STDMETHOD(GetClassInstance)(_Outptr_ ID3DX11EffectClassInstanceVariable **ppEffectClassInstance) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectShaderResourceVariable ////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
typedef interface ID3DX11EffectShaderResourceVariable ID3DX11EffectShaderResourceVariable;
typedef interface ID3DX11EffectShaderResourceVariable *LPD3D11EFFECTSHADERRESOURCEVARIABLE;
// {350DB233-BBE0-485C-9BFE-C0026B844F89}
DEFINE_GUID(IID_ID3DX11EffectShaderResourceVariable,
0x350db233, 0xbbe0, 0x485c, 0x9b, 0xfe, 0xc0, 0x02, 0x6b, 0x84, 0x4f, 0x89);
#undef INTERFACE
#define INTERFACE ID3DX11EffectShaderResourceVariable
DECLARE_INTERFACE_(ID3DX11EffectShaderResourceVariable, ID3DX11EffectVariable)
{
// IUnknown
// ID3DX11EffectVariable
// ID3DX11EffectShaderResourceVariable
STDMETHOD(SetResource)(THIS_ _In_ ID3D11ShaderResourceView *pResource) PURE;
STDMETHOD(GetResource)(THIS_ _Outptr_ ID3D11ShaderResourceView **ppResource) PURE;
STDMETHOD(SetResourceArray)(THIS_ _In_reads_(Count) ID3D11ShaderResourceView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
STDMETHOD(GetResourceArray)(THIS_ _Out_writes_(Count) ID3D11ShaderResourceView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectUnorderedAccessViewVariable ////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
typedef interface ID3DX11EffectUnorderedAccessViewVariable ID3DX11EffectUnorderedAccessViewVariable;
typedef interface ID3DX11EffectUnorderedAccessViewVariable *LPD3D11EFFECTUNORDEREDACCESSVIEWVARIABLE;
// {79B4AC8C-870A-47D2-B05A-8BD5CC3EE6C9}
DEFINE_GUID(IID_ID3DX11EffectUnorderedAccessViewVariable,
0x79b4ac8c, 0x870a, 0x47d2, 0xb0, 0x5a, 0x8b, 0xd5, 0xcc, 0x3e, 0xe6, 0xc9);
#undef INTERFACE
#define INTERFACE ID3DX11EffectUnorderedAccessViewVariable
DECLARE_INTERFACE_(ID3DX11EffectUnorderedAccessViewVariable, ID3DX11EffectVariable)
{
// IUnknown
// ID3DX11EffectVariable
// ID3DX11EffectUnorderedAccessViewVariable
STDMETHOD(SetUnorderedAccessView)(THIS_ _In_ ID3D11UnorderedAccessView *pResource) PURE;
STDMETHOD(GetUnorderedAccessView)(THIS_ _Outptr_ ID3D11UnorderedAccessView **ppResource) PURE;
STDMETHOD(SetUnorderedAccessViewArray)(THIS_ _In_reads_(Count) ID3D11UnorderedAccessView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
STDMETHOD(GetUnorderedAccessViewArray)(THIS_ _Out_writes_(Count) ID3D11UnorderedAccessView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectRenderTargetViewVariable //////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
typedef interface ID3DX11EffectRenderTargetViewVariable ID3DX11EffectRenderTargetViewVariable;
typedef interface ID3DX11EffectRenderTargetViewVariable *LPD3D11EFFECTRENDERTARGETVIEWVARIABLE;
// {D5066909-F40C-43F8-9DB5-057C2A208552}
DEFINE_GUID(IID_ID3DX11EffectRenderTargetViewVariable,
0xd5066909, 0xf40c, 0x43f8, 0x9d, 0xb5, 0x05, 0x7c, 0x2a, 0x20, 0x85, 0x52);
#undef INTERFACE
#define INTERFACE ID3DX11EffectRenderTargetViewVariable
DECLARE_INTERFACE_(ID3DX11EffectRenderTargetViewVariable, ID3DX11EffectVariable)
{
// IUnknown
// ID3DX11EffectVariable
// ID3DX11EffectRenderTargetViewVariable
STDMETHOD(SetRenderTarget)(THIS_ _In_ ID3D11RenderTargetView *pResource) PURE;
STDMETHOD(GetRenderTarget)(THIS_ _Outptr_ ID3D11RenderTargetView **ppResource) PURE;
STDMETHOD(SetRenderTargetArray)(THIS_ _In_reads_(Count) ID3D11RenderTargetView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
STDMETHOD(GetRenderTargetArray)(THIS_ _Out_writes_(Count) ID3D11RenderTargetView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectDepthStencilViewVariable //////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
typedef interface ID3DX11EffectDepthStencilViewVariable ID3DX11EffectDepthStencilViewVariable;
typedef interface ID3DX11EffectDepthStencilViewVariable *LPD3D11EFFECTDEPTHSTENCILVIEWVARIABLE;
// {33C648AC-2E9E-4A2E-9CD6-DE31ACC5B347}
DEFINE_GUID(IID_ID3DX11EffectDepthStencilViewVariable,
0x33c648ac, 0x2e9e, 0x4a2e, 0x9c, 0xd6, 0xde, 0x31, 0xac, 0xc5, 0xb3, 0x47);
#undef INTERFACE
#define INTERFACE ID3DX11EffectDepthStencilViewVariable
DECLARE_INTERFACE_(ID3DX11EffectDepthStencilViewVariable, ID3DX11EffectVariable)
{
// IUnknown
// ID3DX11EffectVariable
// ID3DX11EffectDepthStencilViewVariable
STDMETHOD(SetDepthStencil)(THIS_ _In_ ID3D11DepthStencilView *pResource) PURE;
STDMETHOD(GetDepthStencil)(THIS_ _Outptr_ ID3D11DepthStencilView **ppResource) PURE;
STDMETHOD(SetDepthStencilArray)(THIS_ _In_reads_(Count) ID3D11DepthStencilView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
STDMETHOD(GetDepthStencilArray)(THIS_ _Out_writes_(Count) ID3D11DepthStencilView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectConstantBuffer ////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
typedef interface ID3DX11EffectConstantBuffer ID3DX11EffectConstantBuffer;
typedef interface ID3DX11EffectConstantBuffer *LPD3D11EFFECTCONSTANTBUFFER;
// {2CB6C733-82D2-4000-B3DA-6219D9A99BF2}
DEFINE_GUID(IID_ID3DX11EffectConstantBuffer,
0x2cb6c733, 0x82d2, 0x4000, 0xb3, 0xda, 0x62, 0x19, 0xd9, 0xa9, 0x9b, 0xf2);
#undef INTERFACE
#define INTERFACE ID3DX11EffectConstantBuffer
DECLARE_INTERFACE_(ID3DX11EffectConstantBuffer, ID3DX11EffectVariable)
{
// IUnknown
// ID3DX11EffectVariable
// ID3DX11EffectConstantBuffer
STDMETHOD(SetConstantBuffer)(THIS_ _In_ ID3D11Buffer *pConstantBuffer) PURE;
STDMETHOD(UndoSetConstantBuffer)(THIS) PURE;
STDMETHOD(GetConstantBuffer)(THIS_ _Outptr_ ID3D11Buffer **ppConstantBuffer) PURE;
STDMETHOD(SetTextureBuffer)(THIS_ _In_ ID3D11ShaderResourceView *pTextureBuffer) PURE;
STDMETHOD(UndoSetTextureBuffer)(THIS) PURE;
STDMETHOD(GetTextureBuffer)(THIS_ _Outptr_ ID3D11ShaderResourceView **ppTextureBuffer) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectShaderVariable ////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------
// D3DX11_EFFECT_SHADER_DESC:
//
// Retrieved by ID3DX11EffectShaderVariable::GetShaderDesc()
//----------------------------------------------------------------------------
struct D3DX11_EFFECT_SHADER_DESC
{
const uint8_t *pInputSignature; // Passed into CreateInputLayout,
// valid on VS and GS only
bool IsInline; // Is this an anonymous shader variable
// resulting from an inline shader assignment?
// -- The following fields are not valid after Optimize() --
const uint8_t *pBytecode; // Shader bytecode
uint32_t BytecodeLength;
LPCSTR SODecls[D3D11_SO_STREAM_COUNT]; // Stream out declaration string (for GS with SO)
uint32_t RasterizedStream;
uint32_t NumInputSignatureEntries; // Number of entries in the input signature
uint32_t NumOutputSignatureEntries; // Number of entries in the output signature
uint32_t NumPatchConstantSignatureEntries; // Number of entries in the patch constant signature
};
typedef interface ID3DX11EffectShaderVariable ID3DX11EffectShaderVariable;
typedef interface ID3DX11EffectShaderVariable *LPD3D11EFFECTSHADERVARIABLE;
// {7508B344-020A-4EC7-9118-62CDD36C88D7}
DEFINE_GUID(IID_ID3DX11EffectShaderVariable,
0x7508b344, 0x020a, 0x4ec7, 0x91, 0x18, 0x62, 0xcd, 0xd3, 0x6c, 0x88, 0xd7);
#undef INTERFACE
#define INTERFACE ID3DX11EffectShaderVariable
DECLARE_INTERFACE_(ID3DX11EffectShaderVariable, ID3DX11EffectVariable)
{
// IUnknown
// ID3DX11EffectVariable
// ID3DX11EffectShaderVariable
STDMETHOD(GetShaderDesc)(THIS_ _In_ uint32_t ShaderIndex, _Out_ D3DX11_EFFECT_SHADER_DESC *pDesc) PURE;
STDMETHOD(GetVertexShader)(THIS_ _In_ uint32_t ShaderIndex, _Outptr_ ID3D11VertexShader **ppVS) PURE;
STDMETHOD(GetGeometryShader)(THIS_ _In_ uint32_t ShaderIndex, _Outptr_ ID3D11GeometryShader **ppGS) PURE;
STDMETHOD(GetPixelShader)(THIS_ _In_ uint32_t ShaderIndex, _Outptr_ ID3D11PixelShader **ppPS) PURE;
STDMETHOD(GetHullShader)(THIS_ _In_ uint32_t ShaderIndex, _Outptr_ ID3D11HullShader **ppHS) PURE;
STDMETHOD(GetDomainShader)(THIS_ _In_ uint32_t ShaderIndex, _Outptr_ ID3D11DomainShader **ppDS) PURE;
STDMETHOD(GetComputeShader)(THIS_ _In_ uint32_t ShaderIndex, _Outptr_ ID3D11ComputeShader **ppCS) PURE;
STDMETHOD(GetInputSignatureElementDesc)(THIS_ _In_ uint32_t ShaderIndex, _In_ uint32_t Element, _Out_ D3D11_SIGNATURE_PARAMETER_DESC *pDesc) PURE;
STDMETHOD(GetOutputSignatureElementDesc)(THIS_ _In_ uint32_t ShaderIndex, _In_ uint32_t Element, _Out_ D3D11_SIGNATURE_PARAMETER_DESC *pDesc) PURE;
STDMETHOD(GetPatchConstantSignatureElementDesc)(THIS_ _In_ uint32_t ShaderIndex, _In_ uint32_t Element, _Out_ D3D11_SIGNATURE_PARAMETER_DESC *pDesc) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectBlendVariable /////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
typedef interface ID3DX11EffectBlendVariable ID3DX11EffectBlendVariable;
typedef interface ID3DX11EffectBlendVariable *LPD3D11EFFECTBLENDVARIABLE;
// {D664F4D7-3B81-4805-B277-C1DF58C39F53}
DEFINE_GUID(IID_ID3DX11EffectBlendVariable,
0xd664f4d7, 0x3b81, 0x4805, 0xb2, 0x77, 0xc1, 0xdf, 0x58, 0xc3, 0x9f, 0x53);
#undef INTERFACE
#define INTERFACE ID3DX11EffectBlendVariable
DECLARE_INTERFACE_(ID3DX11EffectBlendVariable, ID3DX11EffectVariable)
{
// IUnknown
// ID3DX11EffectVariable
// ID3DX11EffectBlendVariable
STDMETHOD(GetBlendState)(THIS_ _In_ uint32_t Index, _Outptr_ ID3D11BlendState **ppState) PURE;
STDMETHOD(SetBlendState)(THIS_ _In_ uint32_t Index, _In_ ID3D11BlendState *pState) PURE;
STDMETHOD(UndoSetBlendState)(THIS_ _In_ uint32_t Index) PURE;
STDMETHOD(GetBackingStore)(THIS_ _In_ uint32_t Index, _Out_ D3D11_BLEND_DESC *pDesc) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectDepthStencilVariable //////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
typedef interface ID3DX11EffectDepthStencilVariable ID3DX11EffectDepthStencilVariable;
typedef interface ID3DX11EffectDepthStencilVariable *LPD3D11EFFECTDEPTHSTENCILVARIABLE;
// {69B5751B-61A5-48E5-BD41-D93988111563}
DEFINE_GUID(IID_ID3DX11EffectDepthStencilVariable,
0x69b5751b, 0x61a5, 0x48e5, 0xbd, 0x41, 0xd9, 0x39, 0x88, 0x11, 0x15, 0x63);
#undef INTERFACE
#define INTERFACE ID3DX11EffectDepthStencilVariable
DECLARE_INTERFACE_(ID3DX11EffectDepthStencilVariable, ID3DX11EffectVariable)
{
// IUnknown
// ID3DX11EffectVariable
// ID3DX11EffectDepthStencilVariable
STDMETHOD(GetDepthStencilState)(THIS_ _In_ uint32_t Index, _Outptr_ ID3D11DepthStencilState **ppState) PURE;
STDMETHOD(SetDepthStencilState)(THIS_ _In_ uint32_t Index, _In_ ID3D11DepthStencilState *pState) PURE;
STDMETHOD(UndoSetDepthStencilState)(THIS_ _In_ uint32_t Index) PURE;
STDMETHOD(GetBackingStore)(THIS_ _In_ uint32_t Index, _Out_ D3D11_DEPTH_STENCIL_DESC *pDesc) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectRasterizerVariable ////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
typedef interface ID3DX11EffectRasterizerVariable ID3DX11EffectRasterizerVariable;
typedef interface ID3DX11EffectRasterizerVariable *LPD3D11EFFECTRASTERIZERVARIABLE;
// {53A262F6-5F74-4151-A132-E3DD19A62C9D}
DEFINE_GUID(IID_ID3DX11EffectRasterizerVariable,
0x53a262f6, 0x5f74, 0x4151, 0xa1, 0x32, 0xe3, 0xdd, 0x19, 0xa6, 0x2c, 0x9d);
#undef INTERFACE
#define INTERFACE ID3DX11EffectRasterizerVariable
DECLARE_INTERFACE_(ID3DX11EffectRasterizerVariable, ID3DX11EffectVariable)
{
// IUnknown
// ID3DX11EffectVariable
// ID3DX11EffectRasterizerVariable
STDMETHOD(GetRasterizerState)(THIS_ _In_ uint32_t Index, _Outptr_ ID3D11RasterizerState **ppState) PURE;
STDMETHOD(SetRasterizerState)(THIS_ _In_ uint32_t Index, _In_ ID3D11RasterizerState *pState) PURE;
STDMETHOD(UndoSetRasterizerState)(THIS_ _In_ uint32_t Index) PURE;
STDMETHOD(GetBackingStore)(THIS_ _In_ uint32_t Index, _Out_ D3D11_RASTERIZER_DESC *pDesc) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectSamplerVariable ///////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
typedef interface ID3DX11EffectSamplerVariable ID3DX11EffectSamplerVariable;
typedef interface ID3DX11EffectSamplerVariable *LPD3D11EFFECTSAMPLERVARIABLE;
// {C6402E55-1095-4D95-8931-F92660513DD9}
DEFINE_GUID(IID_ID3DX11EffectSamplerVariable,
0xc6402e55, 0x1095, 0x4d95, 0x89, 0x31, 0xf9, 0x26, 0x60, 0x51, 0x3d, 0xd9);
#undef INTERFACE
#define INTERFACE ID3DX11EffectSamplerVariable
DECLARE_INTERFACE_(ID3DX11EffectSamplerVariable, ID3DX11EffectVariable)
{
// IUnknown
// ID3DX11EffectVariable
// ID3DX11EffectSamplerVariable
STDMETHOD(GetSampler)(THIS_ _In_ uint32_t Index, _Outptr_ ID3D11SamplerState **ppSampler) PURE;
STDMETHOD(SetSampler)(THIS_ _In_ uint32_t Index, _In_ ID3D11SamplerState *pSampler) PURE;
STDMETHOD(UndoSetSampler)(THIS_ _In_ uint32_t Index) PURE;
STDMETHOD(GetBackingStore)(THIS_ _In_ uint32_t Index, _Out_ D3D11_SAMPLER_DESC *pDesc) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectPass //////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------
// D3DX11_PASS_DESC:
//
// Retrieved by ID3DX11EffectPass::GetDesc()
//----------------------------------------------------------------------------
struct D3DX11_PASS_DESC
{
LPCSTR Name; // Name of this pass (nullptr if not anonymous)
uint32_t Annotations; // Number of annotations on this pass
uint8_t *pIAInputSignature; // Signature from VS or GS (if there is no VS)
// or nullptr if neither exists
size_t IAInputSignatureSize; // Singature size in bytes
uint32_t StencilRef; // Specified in SetDepthStencilState()
uint32_t SampleMask; // Specified in SetBlendState()
FLOAT BlendFactor[4]; // Specified in SetBlendState()
};
//----------------------------------------------------------------------------
// D3DX11_PASS_SHADER_DESC:
//
// Retrieved by ID3DX11EffectPass::Get**ShaderDesc()
//----------------------------------------------------------------------------
struct D3DX11_PASS_SHADER_DESC
{
ID3DX11EffectShaderVariable *pShaderVariable; // The variable that this shader came from.
// If this is an inline shader assignment,
// the returned interface will be an
// anonymous shader variable, which is
// not retrievable any other way. It's
// name in the variable description will
// be "$Anonymous".
// If there is no assignment of this type in
// the pass block, pShaderVariable != nullptr,
// but pShaderVariable->IsValid() == false.
uint32_t ShaderIndex; // The element of pShaderVariable (if an array)
// or 0 if not applicable
};
typedef interface ID3DX11EffectPass ID3DX11EffectPass;
typedef interface ID3DX11EffectPass *LPD3D11EFFECTPASS;
// {3437CEC4-4AC1-4D87-8916-F4BD5A41380C}
DEFINE_GUID(IID_ID3DX11EffectPass,
0x3437cec4, 0x4ac1, 0x4d87, 0x89, 0x16, 0xf4, 0xbd, 0x5a, 0x41, 0x38, 0x0c);
#undef INTERFACE
#define INTERFACE ID3DX11EffectPass
DECLARE_INTERFACE_(ID3DX11EffectPass, IUnknown)
{
// IUnknown
// ID3DX11EffectPass
STDMETHOD_(bool, IsValid)(THIS) PURE;
STDMETHOD(GetDesc)(THIS_ _Out_ D3DX11_PASS_DESC *pDesc) PURE;
STDMETHOD(GetVertexShaderDesc)(THIS_ _Out_ D3DX11_PASS_SHADER_DESC *pDesc) PURE;
STDMETHOD(GetGeometryShaderDesc)(THIS_ _Out_ D3DX11_PASS_SHADER_DESC *pDesc) PURE;
STDMETHOD(GetPixelShaderDesc)(THIS_ _Out_ D3DX11_PASS_SHADER_DESC *pDesc) PURE;
STDMETHOD(GetHullShaderDesc)(THIS_ _Out_ D3DX11_PASS_SHADER_DESC *pDesc) PURE;
STDMETHOD(GetDomainShaderDesc)(THIS_ _Out_ D3DX11_PASS_SHADER_DESC *pDesc) PURE;
STDMETHOD(GetComputeShaderDesc)(THIS_ _Out_ D3DX11_PASS_SHADER_DESC *pDesc) PURE;
STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ _In_ uint32_t Index) PURE;
STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ _In_z_ LPCSTR Name) PURE;
STDMETHOD(Apply)(THIS_ _In_ uint32_t Flags, _In_ ID3D11DeviceContext* pContext) PURE;
STDMETHOD(ComputeStateBlockMask)(THIS_ _Inout_ D3DX11_STATE_BLOCK_MASK *pStateBlockMask) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectTechnique /////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------
// D3DX11_TECHNIQUE_DESC:
//
// Retrieved by ID3DX11EffectTechnique::GetDesc()
//----------------------------------------------------------------------------
struct D3DX11_TECHNIQUE_DESC
{
LPCSTR Name; // Name of this technique (nullptr if not anonymous)
uint32_t Passes; // Number of passes contained within
uint32_t Annotations; // Number of annotations on this technique
};
typedef interface ID3DX11EffectTechnique ID3DX11EffectTechnique;
typedef interface ID3DX11EffectTechnique *LPD3D11EFFECTTECHNIQUE;
// {51198831-1F1D-4F47-BD76-41CB0835B1DE}
DEFINE_GUID(IID_ID3DX11EffectTechnique,
0x51198831, 0x1f1d, 0x4f47, 0xbd, 0x76, 0x41, 0xcb, 0x08, 0x35, 0xb1, 0xde);
#undef INTERFACE
#define INTERFACE ID3DX11EffectTechnique
DECLARE_INTERFACE_(ID3DX11EffectTechnique, IUnknown)
{
// IUnknown
// ID3DX11EffectTechnique
STDMETHOD_(bool, IsValid)(THIS) PURE;
STDMETHOD(GetDesc)(THIS_ _Out_ D3DX11_TECHNIQUE_DESC *pDesc) PURE;
STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ _In_ uint32_t Index) PURE;
STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ _In_z_ LPCSTR Name) PURE;
STDMETHOD_(ID3DX11EffectPass*, GetPassByIndex)(THIS_ _In_ uint32_t Index) PURE;
STDMETHOD_(ID3DX11EffectPass*, GetPassByName)(THIS_ _In_z_ LPCSTR Name) PURE;
STDMETHOD(ComputeStateBlockMask)(THIS_ _Inout_ D3DX11_STATE_BLOCK_MASK *pStateBlockMask) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11EffectTechnique /////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------
// D3DX11_GROUP_DESC:
//
// Retrieved by ID3DX11EffectTechnique::GetDesc()
//----------------------------------------------------------------------------
struct D3DX11_GROUP_DESC
{
LPCSTR Name; // Name of this group (only nullptr if global)
uint32_t Techniques; // Number of techniques contained within
uint32_t Annotations; // Number of annotations on this group
};
typedef interface ID3DX11EffectGroup ID3DX11EffectGroup;
typedef interface ID3DX11EffectGroup *LPD3D11EFFECTGROUP;
// {03074acf-97de-485f-b201-cb775264afd6}
DEFINE_GUID(IID_ID3DX11EffectGroup,
0x03074acf, 0x97de, 0x485f, 0xb2, 0x01, 0xcb, 0x77, 0x52, 0x64, 0xaf, 0xd6);
#undef INTERFACE
#define INTERFACE ID3DX11EffectGroup
DECLARE_INTERFACE_(ID3DX11EffectGroup, IUnknown)
{
// IUnknown
// ID3DX11EffectGroup
STDMETHOD_(bool, IsValid)(THIS) PURE;
STDMETHOD(GetDesc)(THIS_ _Out_ D3DX11_GROUP_DESC *pDesc) PURE;
STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ _In_ uint32_t Index) PURE;
STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ _In_z_ LPCSTR Name) PURE;
STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByIndex)(THIS_ _In_ uint32_t Index) PURE;
STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByName)(THIS_ _In_z_ LPCSTR Name) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// ID3DX11Effect //////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------
// D3DX11_EFFECT_DESC:
//
// Retrieved by ID3DX11Effect::GetDesc()
//----------------------------------------------------------------------------
struct D3DX11_EFFECT_DESC
{
uint32_t ConstantBuffers; // Number of constant buffers in this effect
uint32_t GlobalVariables; // Number of global variables in this effect
uint32_t InterfaceVariables; // Number of global interfaces in this effect
uint32_t Techniques; // Number of techniques in this effect
uint32_t Groups; // Number of groups in this effect
};
typedef interface ID3DX11Effect ID3DX11Effect;
typedef interface ID3DX11Effect *LPD3D11EFFECT;
// {FA61CA24-E4BA-4262-9DB8-B132E8CAE319}
DEFINE_GUID(IID_ID3DX11Effect,
0xfa61ca24, 0xe4ba, 0x4262, 0x9d, 0xb8, 0xb1, 0x32, 0xe8, 0xca, 0xe3, 0x19);
#undef INTERFACE
#define INTERFACE ID3DX11Effect
DECLARE_INTERFACE_(ID3DX11Effect, IUnknown)
{
// IUnknown
// ID3DX11Effect
STDMETHOD_(bool, IsValid)(THIS) PURE;
STDMETHOD(GetDevice)(THIS_ _Outptr_ ID3D11Device** ppDevice) PURE;
STDMETHOD(GetDesc)(THIS_ _Out_ D3DX11_EFFECT_DESC *pDesc) PURE;
STDMETHOD_(ID3DX11EffectConstantBuffer*, GetConstantBufferByIndex)(THIS_ _In_ uint32_t Index) PURE;
STDMETHOD_(ID3DX11EffectConstantBuffer*, GetConstantBufferByName)(THIS_ _In_z_ LPCSTR Name) PURE;
STDMETHOD_(ID3DX11EffectVariable*, GetVariableByIndex)(THIS_ _In_ uint32_t Index) PURE;
STDMETHOD_(ID3DX11EffectVariable*, GetVariableByName)(THIS_ _In_z_ LPCSTR Name) PURE;
STDMETHOD_(ID3DX11EffectVariable*, GetVariableBySemantic)(THIS_ _In_z_ LPCSTR Semantic) PURE;
STDMETHOD_(ID3DX11EffectGroup*, GetGroupByIndex)(THIS_ _In_ uint32_t Index) PURE;
STDMETHOD_(ID3DX11EffectGroup*, GetGroupByName)(THIS_ _In_z_ LPCSTR Name) PURE;
STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByIndex)(THIS_ _In_ uint32_t Index) PURE;
STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByName)(THIS_ _In_z_ LPCSTR Name) PURE;
STDMETHOD_(ID3D11ClassLinkage*, GetClassLinkage)(THIS) PURE;
STDMETHOD(CloneEffect)(THIS_ _In_ uint32_t Flags, _Outptr_ ID3DX11Effect** ppClonedEffect ) PURE;
STDMETHOD(Optimize)(THIS) PURE;
STDMETHOD_(bool, IsOptimized)(THIS) PURE;
};
//////////////////////////////////////////////////////////////////////////////
// APIs //////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
//----------------------------------------------------------------------------
// D3DX11CreateEffectFromMemory
//
// Creates an effect instance from a compiled effect in memory
//
// Parameters:
//
// [in]
//
// pData
// Blob of compiled effect data
// DataLength
// Length of the data blob
// FXFlags
// Flags pertaining to Effect creation
// pDevice
// Pointer to the D3D11 device on which to create Effect resources
// srcName [optional]
// ASCII string to use for debug object naming
//
// [out]
//
// ppEffect
// Address of the newly created Effect interface
//
//----------------------------------------------------------------------------
HRESULT WINAPI D3DX11CreateEffectFromMemory( _In_reads_bytes_(DataLength) LPCVOID pData,
_In_ SIZE_T DataLength,
_In_ UINT FXFlags,
_In_ ID3D11Device *pDevice,
_Outptr_ ID3DX11Effect **ppEffect,
_In_opt_z_ LPCSTR srcName = nullptr );
//----------------------------------------------------------------------------
// D3DX11CreateEffectFromFile
//
// Creates an effect instance from a compiled effect data file
//
// Parameters:
//
// [in]
//
// pFileName
// Compiled effect file
// FXFlags
// Flags pertaining to Effect creation
// pDevice
// Pointer to the D3D11 device on which to create Effect resources
//
// [out]
//
// ppEffect
// Address of the newly created Effect interface
//
//----------------------------------------------------------------------------
HRESULT WINAPI D3DX11CreateEffectFromFile( _In_z_ LPCWSTR pFileName,
_In_ UINT FXFlags,
_In_ ID3D11Device *pDevice,
_Outptr_ ID3DX11Effect **ppEffect );
//----------------------------------------------------------------------------
// D3DX11CompileEffectFromMemory
//
// Complies an effect shader source file in memory and then creates an effect instance
//
// Parameters:
//
// [in]
//
// pData
// Pointer to FX shader as an ASCII string
// DataLength
// Length of the FX shader ASCII string
// srcName [optional]
// ASCII string to use for debug object naming
// pDefines [optional]
// A NULL-terminated array of shader macros
// pInclude [optional]
// A pointer to an include interface
// HLSLFlags
// HLSL compile options (see D3DCOMPILE flags)
// FXFlags
// Flags pertaining to Effect compilation (see D3DCOMPILE_EFFECT flags)
// pDevice
// Pointer to the D3D11 device on which to create Effect resources
//
// [out]
//
// ppEffect
// Address of the newly created Effect interface
//
//----------------------------------------------------------------------------
HRESULT D3DX11CompileEffectFromMemory( _In_reads_bytes_(DataLength) LPCVOID pData,
_In_ SIZE_T DataLength,
_In_opt_z_ LPCSTR srcName,
_In_opt_ const D3D_SHADER_MACRO *pDefines,
_In_opt_ ID3DInclude *pInclude,
_In_ UINT HLSLFlags,
_In_ UINT FXFlags,
_In_ ID3D11Device *pDevice,
_Out_ ID3DX11Effect **ppEffect,
_Outptr_opt_result_maybenull_ ID3DBlob **ppErrors );
//----------------------------------------------------------------------------
// D3DX11CompileEffectFromFile
//
// Complies an effect shader source file and then creates an effect instance
//
// Parameters:
//
// [in]
//
// pFileName
// FX shader source file
// pDefines [optional]
// A NULL-terminated array of shader macros
// pInclude [optional]
// A pointer to an include interface
// HLSLFlags
// HLSL compile options (see D3DCOMPILE flags)
// FXFlags
// Flags pertaining to Effect compilation (see D3DCOMPILE_EFFECT flags)
// pDevice
// Pointer to the D3D11 device on which to create Effect resources
//
// [out]
//
// ppEffect
// Address of the newly created Effect interface
//
//----------------------------------------------------------------------------
HRESULT D3DX11CompileEffectFromFile( _In_z_ LPCWSTR pFileName,
_In_opt_ const D3D_SHADER_MACRO *pDefines,
_In_opt_ ID3DInclude *pInclude,
_In_ UINT HLSLFlags,
_In_ UINT FXFlags,
_In_ ID3D11Device *pDevice,
_Out_ ID3DX11Effect **ppEffect,
_Outptr_opt_result_maybenull_ ID3DBlob **ppErrors );
#ifdef __cplusplus
}
#endif //__cplusplus
| apache-2.0 |
yifan-gu/go-oidc | oidc/util.go | 1643 | package oidc
import (
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/coreos/go-oidc/jose"
)
func ParseTokenFromRequest(r *http.Request) (token jose.JWT, err error) {
ah := r.Header.Get("Authorization")
if ah == "" {
err = errors.New("missing Authorization header")
return
}
if len(ah) <= 6 || strings.ToUpper(ah[0:6]) != "BEARER" {
err = errors.New("should be a bearer token")
return
}
return jose.ParseJWT(ah[7:])
}
func NewClaims(iss, sub, aud string, iat, exp time.Time) jose.Claims {
return jose.Claims{
// required
"iss": iss,
"sub": sub,
"aud": aud,
"iat": float64(iat.Unix()),
"exp": float64(exp.Unix()),
}
}
func GenClientID(hostport string) (string, error) {
b, err := randBytes(32)
if err != nil {
return "", err
}
var host string
if strings.Contains(hostport, ":") {
host, _, err = net.SplitHostPort(hostport)
if err != nil {
return "", err
}
} else {
host = hostport
}
return fmt.Sprintf("%s@%s", base64.URLEncoding.EncodeToString(b), host), nil
}
func randBytes(n int) ([]byte, error) {
b := make([]byte, n)
got, err := rand.Read(b)
if err != nil {
return nil, err
} else if n != got {
return nil, errors.New("unable to generate enough random data")
}
return b, nil
}
// urlEqual checks two urls for equality using only the host and path portions.
func urlEqual(url1, url2 string) bool {
u1, err := url.Parse(url1)
if err != nil {
return false
}
u2, err := url.Parse(url2)
if err != nil {
return false
}
return strings.ToLower(u1.Host+u1.Path) == strings.ToLower(u2.Host+u2.Path)
}
| apache-2.0 |
WebDeltaSync/WebR2sync_plus | node_modules/ali-oss/lib/sts.js | 4037 | 'use strict';
var debug = require('debug')('ali-oss:sts');
var crypto = require('crypto');
var querystring = require('querystring');
var copy = require('copy-to');
var AgentKeepalive = require('agentkeepalive');
var is = require('is-type-of');
var ms = require('humanize-ms');
var urllib = require('urllib');
var globalHttpAgent = new AgentKeepalive();
module.exports = STS;
function STS(options) {
if (!(this instanceof STS)) {
return new STS(options);
}
if (!options
|| !options.accessKeyId
|| !options.accessKeySecret) {
throw new Error('require accessKeyId, accessKeySecret');
}
this.options = {
endpoint: options.endpoint || 'https://sts.aliyuncs.com',
format: 'JSON',
apiVersion: '2015-04-01',
sigMethod: 'HMAC-SHA1',
sigVersion: '1.0',
timeout: '60s'
};
copy(options).to(this.options);
// support custom agent and urllib client
if (this.options.urllib) {
this.urllib = this.options.urllib;
} else {
this.urllib = urllib;
this.agent = this.options.agent || globalHttpAgent;
}
};
var proto = STS.prototype;
/**
* STS opertaions
*/
proto.assumeRole = function* assumeRole(role, policy, expiration, session, options) {
var opts = this.options;
var params = {
'Action': 'AssumeRole',
'RoleArn': role,
'RoleSessionName': session || 'app',
'DurationSeconds': expiration || 3600,
'Format': opts.format,
'Version': opts.apiVersion,
'AccessKeyId': opts.accessKeyId,
'SignatureMethod': opts.sigMethod,
'SignatureVersion': opts.sigVersion,
'SignatureNonce': Math.random(),
'Timestamp': new Date().toISOString()
};
if (policy) {
var policyStr;
if (is.string(policy)) {
try {
policyStr = JSON.stringify(JSON.parse(policy));
} catch (err) {
throw new Error('Policy string is not a valid JSON: ' + err.message);
}
} else {
policyStr = JSON.stringify(policy);
}
params.Policy = policyStr;
}
var signature = this._getSignature('POST', params, opts.accessKeySecret);
params.Signature = signature;
var reqUrl = opts.endpoint;
var reqParams = {
agent: this.agent,
timeout: ms(options && options.timeout || opts.timeout),
method: 'POST',
content: querystring.stringify(params),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
ctx: options && options.ctx,
};
var result = yield this.urllib.request(reqUrl, reqParams);
debug('response %s %s, got %s, headers: %j',
reqParams.method, reqUrl, result.status, result.headers);
if (Math.floor(result.status / 100) !== 2) {
var err = yield this._requestError(result);
err.params = reqParams;
throw err;
}
result.data = JSON.parse(result.data);
return {
res: result.res,
credentials: result.data.Credentials
};
};
proto._requestError = function* _requestError(result) {
var err = new Error();
err.status = result.status;
try {
var resp = yield JSON.parse(result.data) || {};
err.code = resp.Code;
err.message = resp.Code + ': ' + resp.Message;
err.requestId = resp.RequestId;
} catch (e) {
err.message = 'UnknownError: ' + String(result.data);
}
return err;
};
proto._getSignature = function _getSignature(method, params, key) {
var that = this;
var canoQuery = Object.keys(params).sort().map(function (key) {
return that._escape(key) + '=' + that._escape(params[key])
}).join('&');
var stringToSign =
method.toUpperCase() +
'&' + this._escape('/') +
'&' + this._escape(canoQuery);
debug('string to sign: %s', stringToSign);
var signature = crypto.createHmac('sha1', key + '&');
signature = signature.update(stringToSign).digest('base64');
debug('signature: %s', signature);
return signature;
};
/**
* Since `encodeURIComponent` doesn't encode '*', which causes
* 'SignatureDoesNotMatch'. We need do it ourselves.
*/
proto._escape = function _escape(str) {
return encodeURIComponent(str).replace(/\*/g, '%2A');
};
| apache-2.0 |
mafulafunk/wicket | wicket-user-guide/examples/MarkupInheritanceExample/src/main/java/org/wicketTutorial/HomePage.java | 1308 | /**
* 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.wicketTutorial;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.WebPage;
public class HomePage extends WebPage {
private static final long serialVersionUID = 1L;
public HomePage(final PageParameters parameters) {
super(parameters);
add(new Label("version", getApplication().getFrameworkSettings().getVersion()));
// TODO Add your page's components here
}
}
| apache-2.0 |
pcmoritz/arrow | java/vector/src/main/java/org/apache/arrow/vector/complex/impl/ComplexWriterImpl.java | 5289 | /*
* 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.arrow.vector.complex.impl;
import org.apache.arrow.util.Preconditions;
import org.apache.arrow.vector.complex.ListVector;
import org.apache.arrow.vector.complex.NonNullableStructVector;
import org.apache.arrow.vector.complex.StateTool;
import org.apache.arrow.vector.complex.StructVector;
import org.apache.arrow.vector.complex.writer.BaseWriter.ComplexWriter;
import org.apache.arrow.vector.types.pojo.Field;
public class ComplexWriterImpl extends AbstractFieldWriter implements ComplexWriter {
private NullableStructWriter structRoot;
private UnionListWriter listRoot;
private final NonNullableStructVector container;
Mode mode = Mode.INIT;
private final String name;
private final boolean unionEnabled;
private final NullableStructWriterFactory nullableStructWriterFactory;
private enum Mode { INIT, STRUCT, LIST }
public ComplexWriterImpl(
String name,
NonNullableStructVector container,
boolean unionEnabled,
boolean caseSensitive) {
this.name = name;
this.container = container;
this.unionEnabled = unionEnabled;
nullableStructWriterFactory = caseSensitive ?
NullableStructWriterFactory.getNullableCaseSensitiveStructWriterFactoryInstance() :
NullableStructWriterFactory.getNullableStructWriterFactoryInstance();
}
public ComplexWriterImpl(String name, NonNullableStructVector container, boolean unionEnabled) {
this(name, container, unionEnabled, false);
}
public ComplexWriterImpl(String name, NonNullableStructVector container) {
this(name, container, false);
}
@Override
public Field getField() {
return container.getField();
}
@Override
public int getValueCapacity() {
return container.getValueCapacity();
}
private void check(Mode... modes) {
StateTool.check(mode, modes);
}
@Override
public void reset() {
setPosition(0);
}
@Override
public void close() throws Exception {
clear();
structRoot.close();
if (listRoot != null) {
listRoot.close();
}
}
@Override
public void clear() {
switch (mode) {
case STRUCT:
structRoot.clear();
break;
case LIST:
listRoot.clear();
break;
default:
break;
}
}
@Override
public void setValueCount(int count) {
switch (mode) {
case STRUCT:
structRoot.setValueCount(count);
break;
case LIST:
listRoot.setValueCount(count);
break;
default:
break;
}
}
@Override
public void setPosition(int index) {
super.setPosition(index);
switch (mode) {
case STRUCT:
structRoot.setPosition(index);
break;
case LIST:
listRoot.setPosition(index);
break;
default:
break;
}
}
public StructWriter directStruct() {
Preconditions.checkArgument(name == null);
switch (mode) {
case INIT:
structRoot = nullableStructWriterFactory.build((StructVector) container);
structRoot.setPosition(idx());
mode = Mode.STRUCT;
break;
case STRUCT:
break;
default:
check(Mode.INIT, Mode.STRUCT);
}
return structRoot;
}
@Override
public StructWriter rootAsStruct() {
switch (mode) {
case INIT:
// TODO allow dictionaries in complex types
StructVector struct = container.addOrGetStruct(name);
structRoot = nullableStructWriterFactory.build(struct);
structRoot.setPosition(idx());
mode = Mode.STRUCT;
break;
case STRUCT:
break;
default:
check(Mode.INIT, Mode.STRUCT);
}
return structRoot;
}
@Override
public void allocate() {
if (structRoot != null) {
structRoot.allocate();
} else if (listRoot != null) {
listRoot.allocate();
}
}
@Override
public ListWriter rootAsList() {
switch (mode) {
case INIT:
int vectorCount = container.size();
// TODO allow dictionaries in complex types
ListVector listVector = container.addOrGetList(name);
if (container.size() > vectorCount) {
listVector.allocateNew();
}
listRoot = new UnionListWriter(listVector, nullableStructWriterFactory);
listRoot.setPosition(idx());
mode = Mode.LIST;
break;
case LIST:
break;
default:
check(Mode.INIT, Mode.STRUCT);
}
return listRoot;
}
}
| apache-2.0 |
dcbw/kubernetes | test/e2e/service.go | 63318 | /*
Copyright 2014 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package e2e
import (
"fmt"
"io/ioutil"
"math/rand"
"net"
"net/http"
"sort"
"strconv"
"strings"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/errors"
client "k8s.io/kubernetes/pkg/client/unversioned"
"k8s.io/kubernetes/pkg/labels"
"k8s.io/kubernetes/pkg/types"
"k8s.io/kubernetes/pkg/util"
"k8s.io/kubernetes/pkg/util/intstr"
utilnet "k8s.io/kubernetes/pkg/util/net"
"k8s.io/kubernetes/pkg/util/sets"
"k8s.io/kubernetes/pkg/util/wait"
)
// Maximum time a kube-proxy daemon on a node is allowed to not
// notice a Service update, such as type=NodePort.
// TODO: This timeout should be O(10s), observed values are O(1m), 5m is very
// liberal. Fix tracked in #20567.
const kubeProxyLagTimeout = 5 * time.Minute
// Maximum time a load balancer is allowed to not respond after creation.
const loadBalancerLagTimeout = 2 * time.Minute
// How long to wait for a load balancer to be created/modified.
//TODO: once support ticket 21807001 is resolved, reduce this timeout back to something reasonable
const loadBalancerCreateTimeout = 20 * time.Minute
// This should match whatever the default/configured range is
var ServiceNodePortRange = utilnet.PortRange{Base: 30000, Size: 2768}
var _ = Describe("Services", func() {
f := NewFramework("services")
var c *client.Client
var extraNamespaces []string
BeforeEach(func() {
var err error
c, err = loadClient()
Expect(err).NotTo(HaveOccurred())
})
AfterEach(func() {
if testContext.DeleteNamespace {
for _, ns := range extraNamespaces {
By(fmt.Sprintf("Destroying namespace %v", ns))
if err := deleteNS(c, ns, 5*time.Minute /* namespace deletion timeout */); err != nil {
Failf("Couldn't delete namespace %s: %s", ns, err)
}
}
extraNamespaces = nil
} else {
Logf("Found DeleteNamespace=false, skipping namespace deletion!")
}
})
// TODO: We get coverage of TCP/UDP and multi-port services through the DNS test. We should have a simpler test for multi-port TCP here.
It("should provide secure master service [Conformance]", func() {
_, err := c.Services(api.NamespaceDefault).Get("kubernetes")
Expect(err).NotTo(HaveOccurred())
})
It("should serve a basic endpoint from pods [Conformance]", func() {
// TODO: use the ServiceTestJig here
serviceName := "endpoint-test2"
ns := f.Namespace.Name
labels := map[string]string{
"foo": "bar",
"baz": "blah",
}
By("creating service " + serviceName + " in namespace " + ns)
defer func() {
err := c.Services(ns).Delete(serviceName)
Expect(err).NotTo(HaveOccurred())
}()
service := &api.Service{
ObjectMeta: api.ObjectMeta{
Name: serviceName,
},
Spec: api.ServiceSpec{
Selector: labels,
Ports: []api.ServicePort{{
Port: 80,
TargetPort: intstr.FromInt(80),
}},
},
}
_, err := c.Services(ns).Create(service)
Expect(err).NotTo(HaveOccurred())
validateEndpointsOrFail(c, ns, serviceName, PortsByPodName{})
names := map[string]bool{}
defer func() {
for name := range names {
err := c.Pods(ns).Delete(name, nil)
Expect(err).NotTo(HaveOccurred())
}
}()
name1 := "pod1"
name2 := "pod2"
createPodOrFail(c, ns, name1, labels, []api.ContainerPort{{ContainerPort: 80}})
names[name1] = true
validateEndpointsOrFail(c, ns, serviceName, PortsByPodName{name1: {80}})
createPodOrFail(c, ns, name2, labels, []api.ContainerPort{{ContainerPort: 80}})
names[name2] = true
validateEndpointsOrFail(c, ns, serviceName, PortsByPodName{name1: {80}, name2: {80}})
deletePodOrFail(c, ns, name1)
delete(names, name1)
validateEndpointsOrFail(c, ns, serviceName, PortsByPodName{name2: {80}})
deletePodOrFail(c, ns, name2)
delete(names, name2)
validateEndpointsOrFail(c, ns, serviceName, PortsByPodName{})
})
It("should serve multiport endpoints from pods [Conformance]", func() {
// TODO: use the ServiceTestJig here
// repacking functionality is intentionally not tested here - it's better to test it in an integration test.
serviceName := "multi-endpoint-test"
ns := f.Namespace.Name
defer func() {
err := c.Services(ns).Delete(serviceName)
Expect(err).NotTo(HaveOccurred())
}()
labels := map[string]string{"foo": "bar"}
svc1port := "svc1"
svc2port := "svc2"
By("creating service " + serviceName + " in namespace " + ns)
service := &api.Service{
ObjectMeta: api.ObjectMeta{
Name: serviceName,
},
Spec: api.ServiceSpec{
Selector: labels,
Ports: []api.ServicePort{
{
Name: "portname1",
Port: 80,
TargetPort: intstr.FromString(svc1port),
},
{
Name: "portname2",
Port: 81,
TargetPort: intstr.FromString(svc2port),
},
},
},
}
_, err := c.Services(ns).Create(service)
Expect(err).NotTo(HaveOccurred())
port1 := 100
port2 := 101
validateEndpointsOrFail(c, ns, serviceName, PortsByPodName{})
names := map[string]bool{}
defer func() {
for name := range names {
err := c.Pods(ns).Delete(name, nil)
Expect(err).NotTo(HaveOccurred())
}
}()
containerPorts1 := []api.ContainerPort{
{
Name: svc1port,
ContainerPort: port1,
},
}
containerPorts2 := []api.ContainerPort{
{
Name: svc2port,
ContainerPort: port2,
},
}
podname1 := "pod1"
podname2 := "pod2"
createPodOrFail(c, ns, podname1, labels, containerPorts1)
names[podname1] = true
validateEndpointsOrFail(c, ns, serviceName, PortsByPodName{podname1: {port1}})
createPodOrFail(c, ns, podname2, labels, containerPorts2)
names[podname2] = true
validateEndpointsOrFail(c, ns, serviceName, PortsByPodName{podname1: {port1}, podname2: {port2}})
deletePodOrFail(c, ns, podname1)
delete(names, podname1)
validateEndpointsOrFail(c, ns, serviceName, PortsByPodName{podname2: {port2}})
deletePodOrFail(c, ns, podname2)
delete(names, podname2)
validateEndpointsOrFail(c, ns, serviceName, PortsByPodName{})
})
It("should be able to up and down services", func() {
// TODO: use the ServiceTestJig here
// this test uses NodeSSHHosts that does not work if a Node only reports LegacyHostIP
SkipUnlessProviderIs(providersWithSSH...)
ns := f.Namespace.Name
numPods, servicePort := 3, 80
By("creating service1 in namespace " + ns)
podNames1, svc1IP, err := startServeHostnameService(c, ns, "service1", servicePort, numPods)
Expect(err).NotTo(HaveOccurred())
By("creating service2 in namespace " + ns)
podNames2, svc2IP, err := startServeHostnameService(c, ns, "service2", servicePort, numPods)
Expect(err).NotTo(HaveOccurred())
hosts, err := NodeSSHHosts(c)
Expect(err).NotTo(HaveOccurred())
if len(hosts) == 0 {
Failf("No ssh-able nodes")
}
host := hosts[0]
By("verifying service1 is up")
expectNoError(verifyServeHostnameServiceUp(c, ns, host, podNames1, svc1IP, servicePort))
By("verifying service2 is up")
expectNoError(verifyServeHostnameServiceUp(c, ns, host, podNames2, svc2IP, servicePort))
// Stop service 1 and make sure it is gone.
By("stopping service1")
expectNoError(stopServeHostnameService(c, ns, "service1"))
By("verifying service1 is not up")
expectNoError(verifyServeHostnameServiceDown(c, host, svc1IP, servicePort))
By("verifying service2 is still up")
expectNoError(verifyServeHostnameServiceUp(c, ns, host, podNames2, svc2IP, servicePort))
// Start another service and verify both are up.
By("creating service3 in namespace " + ns)
podNames3, svc3IP, err := startServeHostnameService(c, ns, "service3", servicePort, numPods)
Expect(err).NotTo(HaveOccurred())
if svc2IP == svc3IP {
Failf("service IPs conflict: %v", svc2IP)
}
By("verifying service2 is still up")
expectNoError(verifyServeHostnameServiceUp(c, ns, host, podNames2, svc2IP, servicePort))
By("verifying service3 is up")
expectNoError(verifyServeHostnameServiceUp(c, ns, host, podNames3, svc3IP, servicePort))
})
It("should work after restarting kube-proxy [Disruptive]", func() {
// TODO: use the ServiceTestJig here
SkipUnlessProviderIs("gce", "gke")
ns := f.Namespace.Name
numPods, servicePort := 3, 80
svc1 := "service1"
svc2 := "service2"
defer func() { expectNoError(stopServeHostnameService(c, ns, svc1)) }()
podNames1, svc1IP, err := startServeHostnameService(c, ns, svc1, servicePort, numPods)
Expect(err).NotTo(HaveOccurred())
defer func() { expectNoError(stopServeHostnameService(c, ns, svc2)) }()
podNames2, svc2IP, err := startServeHostnameService(c, ns, svc2, servicePort, numPods)
Expect(err).NotTo(HaveOccurred())
if svc1IP == svc2IP {
Failf("VIPs conflict: %v", svc1IP)
}
hosts, err := NodeSSHHosts(c)
Expect(err).NotTo(HaveOccurred())
if len(hosts) == 0 {
Failf("No ssh-able nodes")
}
host := hosts[0]
expectNoError(verifyServeHostnameServiceUp(c, ns, host, podNames1, svc1IP, servicePort))
expectNoError(verifyServeHostnameServiceUp(c, ns, host, podNames2, svc2IP, servicePort))
By("Restarting kube-proxy")
if err := restartKubeProxy(host); err != nil {
Failf("error restarting kube-proxy: %v", err)
}
expectNoError(verifyServeHostnameServiceUp(c, ns, host, podNames1, svc1IP, servicePort))
expectNoError(verifyServeHostnameServiceUp(c, ns, host, podNames2, svc2IP, servicePort))
By("Removing iptable rules")
result, err := SSH(`
sudo iptables -t nat -F KUBE-SERVICES || true;
sudo iptables -t nat -F KUBE-PORTALS-HOST || true;
sudo iptables -t nat -F KUBE-PORTALS-CONTAINER || true`, host, testContext.Provider)
if err != nil || result.Code != 0 {
LogSSHResult(result)
Failf("couldn't remove iptable rules: %v", err)
}
expectNoError(verifyServeHostnameServiceUp(c, ns, host, podNames1, svc1IP, servicePort))
expectNoError(verifyServeHostnameServiceUp(c, ns, host, podNames2, svc2IP, servicePort))
})
It("should work after restarting apiserver [Disruptive]", func() {
// TODO: use the ServiceTestJig here
// TODO: restartApiserver doesn't work in GKE - fix it and reenable this test.
SkipUnlessProviderIs("gce")
ns := f.Namespace.Name
numPods, servicePort := 3, 80
defer func() { expectNoError(stopServeHostnameService(c, ns, "service1")) }()
podNames1, svc1IP, err := startServeHostnameService(c, ns, "service1", servicePort, numPods)
Expect(err).NotTo(HaveOccurred())
hosts, err := NodeSSHHosts(c)
Expect(err).NotTo(HaveOccurred())
if len(hosts) == 0 {
Failf("No ssh-able nodes")
}
host := hosts[0]
expectNoError(verifyServeHostnameServiceUp(c, ns, host, podNames1, svc1IP, servicePort))
// Restart apiserver
if err := restartApiserver(); err != nil {
Failf("error restarting apiserver: %v", err)
}
if err := waitForApiserverUp(c); err != nil {
Failf("error while waiting for apiserver up: %v", err)
}
expectNoError(verifyServeHostnameServiceUp(c, ns, host, podNames1, svc1IP, servicePort))
// Create a new service and check if it's not reusing IP.
defer func() { expectNoError(stopServeHostnameService(c, ns, "service2")) }()
podNames2, svc2IP, err := startServeHostnameService(c, ns, "service2", servicePort, numPods)
Expect(err).NotTo(HaveOccurred())
if svc1IP == svc2IP {
Failf("VIPs conflict: %v", svc1IP)
}
expectNoError(verifyServeHostnameServiceUp(c, ns, host, podNames1, svc1IP, servicePort))
expectNoError(verifyServeHostnameServiceUp(c, ns, host, podNames2, svc2IP, servicePort))
})
// TODO: Run this test against the userspace proxy and nodes
// configured with a default deny firewall to validate that the
// proxy whitelists NodePort traffic.
It("should be able to create a functioning NodePort service", func() {
serviceName := "nodeport-test"
ns := f.Namespace.Name
jig := NewServiceTestJig(c, serviceName)
nodeIP := pickNodeIP(jig.Client) // for later
By("creating service " + serviceName + " with type=NodePort in namespace " + ns)
service := jig.CreateTCPServiceOrFail(ns, func(svc *api.Service) {
svc.Spec.Type = api.ServiceTypeNodePort
})
jig.SanityCheckService(service, api.ServiceTypeNodePort)
nodePort := service.Spec.Ports[0].NodePort
By("creating pod to be part of service " + serviceName)
jig.RunOrFail(ns, nil)
By("hitting the pod through the service's NodePort")
jig.TestReachableHTTP(nodeIP, nodePort, kubeProxyLagTimeout)
By("verifying the node port is locked")
hostExec := LaunchHostExecPod(f.Client, f.Namespace.Name, "hostexec")
// Even if the node-ip:node-port check above passed, this hostexec pod
// might fall on a node with a laggy kube-proxy.
cmd := fmt.Sprintf(`for i in $(seq 1 300); do if ss -ant46 'sport = :%d' | grep ^LISTEN; then exit 0; fi; sleep 1; done; exit 1`, nodePort)
stdout, err := RunHostCmd(hostExec.Namespace, hostExec.Name, cmd)
if err != nil {
Failf("expected node port %d to be in use, stdout: %v", nodePort, stdout)
}
})
It("should be able to change the type and ports of a service", func() {
// requires cloud load-balancer support
SkipUnlessProviderIs("gce", "gke", "aws")
// This test is more monolithic than we'd like because LB turnup can be
// very slow, so we lumped all the tests into one LB lifecycle.
serviceName := "mutability-test"
ns1 := f.Namespace.Name // LB1 in ns1 on TCP
Logf("namespace for TCP test: %s", ns1)
By("creating a second namespace")
namespacePtr, err := createTestingNS("services", c, nil)
Expect(err).NotTo(HaveOccurred())
ns2 := namespacePtr.Name // LB2 in ns2 on UDP
Logf("namespace for UDP test: %s", ns2)
extraNamespaces = append(extraNamespaces, ns2)
jig := NewServiceTestJig(c, serviceName)
nodeIP := pickNodeIP(jig.Client) // for later
// Test TCP and UDP Services. Services with the same name in different
// namespaces should get different node ports and load balancers.
By("creating a TCP service " + serviceName + " with type=ClusterIP in namespace " + ns1)
tcpService := jig.CreateTCPServiceOrFail(ns1, nil)
jig.SanityCheckService(tcpService, api.ServiceTypeClusterIP)
By("creating a UDP service " + serviceName + " with type=ClusterIP in namespace " + ns2)
udpService := jig.CreateUDPServiceOrFail(ns2, nil)
jig.SanityCheckService(udpService, api.ServiceTypeClusterIP)
By("verifying that TCP and UDP use the same port")
if tcpService.Spec.Ports[0].Port != udpService.Spec.Ports[0].Port {
Failf("expected to use the same port for TCP and UDP")
}
svcPort := tcpService.Spec.Ports[0].Port
Logf("service port (TCP and UDP): %d", svcPort)
By("creating a pod to be part of the TCP service " + serviceName)
jig.RunOrFail(ns1, nil)
By("creating a pod to be part of the UDP service " + serviceName)
jig.RunOrFail(ns2, nil)
// Change the services to NodePort.
By("changing the TCP service " + serviceName + " to type=NodePort")
tcpService = jig.UpdateServiceOrFail(ns1, tcpService.Name, func(s *api.Service) {
s.Spec.Type = api.ServiceTypeNodePort
})
jig.SanityCheckService(tcpService, api.ServiceTypeNodePort)
tcpNodePort := tcpService.Spec.Ports[0].NodePort
Logf("TCP node port: %d", tcpNodePort)
By("changing the UDP service " + serviceName + " to type=NodePort")
udpService = jig.UpdateServiceOrFail(ns2, udpService.Name, func(s *api.Service) {
s.Spec.Type = api.ServiceTypeNodePort
})
jig.SanityCheckService(udpService, api.ServiceTypeNodePort)
udpNodePort := udpService.Spec.Ports[0].NodePort
Logf("UDP node port: %d", udpNodePort)
By("hitting the TCP service's NodePort")
jig.TestReachableHTTP(nodeIP, tcpNodePort, kubeProxyLagTimeout)
By("hitting the UDP service's NodePort")
jig.TestReachableUDP(nodeIP, udpNodePort, kubeProxyLagTimeout)
// Change the services to LoadBalancer.
requestedIP := ""
if providerIs("gce", "gke") {
By("creating a static load balancer IP")
rand.Seed(time.Now().UTC().UnixNano())
staticIPName := fmt.Sprintf("e2e-external-lb-test-%d", rand.Intn(65535))
requestedIP, err = createGCEStaticIP(staticIPName)
Expect(err).NotTo(HaveOccurred())
defer func() {
// Release GCE static IP - this is not kube-managed and will not be automatically released.
deleteGCEStaticIP(staticIPName)
}()
Logf("Allocated static load balancer IP: %s", requestedIP)
}
By("changing the TCP service " + serviceName + " to type=LoadBalancer")
tcpService = jig.UpdateServiceOrFail(ns1, tcpService.Name, func(s *api.Service) {
s.Spec.LoadBalancerIP = requestedIP // will be "" if not applicable
s.Spec.Type = api.ServiceTypeLoadBalancer
})
By("changing the UDP service " + serviceName + " to type=LoadBalancer")
udpService = jig.UpdateServiceOrFail(ns2, udpService.Name, func(s *api.Service) {
s.Spec.Type = api.ServiceTypeLoadBalancer
})
By("waiting for the TCP service " + serviceName + " to have a load balancer")
// Wait for the load balancer to be created asynchronously
tcpService = jig.WaitForLoadBalancerOrFail(ns1, tcpService.Name)
jig.SanityCheckService(tcpService, api.ServiceTypeLoadBalancer)
if tcpService.Spec.Ports[0].NodePort != tcpNodePort {
Failf("TCP Spec.Ports[0].NodePort changed (%d -> %d) when not expected", tcpNodePort, tcpService.Spec.Ports[0].NodePort)
}
if requestedIP != "" && getIngressPoint(&tcpService.Status.LoadBalancer.Ingress[0]) != requestedIP {
Failf("unexpected TCP Status.LoadBalancer.Ingress (expected %s, got %s)", requestedIP, getIngressPoint(&tcpService.Status.LoadBalancer.Ingress[0]))
}
tcpIngressIP := getIngressPoint(&tcpService.Status.LoadBalancer.Ingress[0])
Logf("TCP load balancer: %s", tcpIngressIP)
By("waiting for the UDP service " + serviceName + " to have a load balancer")
// 2nd one should be faster since they ran in parallel.
udpService = jig.WaitForLoadBalancerOrFail(ns2, udpService.Name)
jig.SanityCheckService(udpService, api.ServiceTypeLoadBalancer)
if udpService.Spec.Ports[0].NodePort != udpNodePort {
Failf("UDP Spec.Ports[0].NodePort changed (%d -> %d) when not expected", udpNodePort, udpService.Spec.Ports[0].NodePort)
}
udpIngressIP := getIngressPoint(&udpService.Status.LoadBalancer.Ingress[0])
Logf("UDP load balancer: %s", tcpIngressIP)
By("verifying that TCP and UDP use different load balancers")
if tcpIngressIP == udpIngressIP {
Failf("Load balancers are not different: %s", getIngressPoint(&tcpService.Status.LoadBalancer.Ingress[0]))
}
By("hitting the TCP service's NodePort")
jig.TestReachableHTTP(nodeIP, tcpNodePort, kubeProxyLagTimeout)
By("hitting the UDP service's NodePort")
jig.TestReachableUDP(nodeIP, udpNodePort, kubeProxyLagTimeout)
By("hitting the TCP service's LoadBalancer")
jig.TestReachableHTTP(tcpIngressIP, svcPort, loadBalancerLagTimeout)
By("hitting the UDP service's LoadBalancer")
jig.TestReachableUDP(udpIngressIP, svcPort, loadBalancerLagTimeout)
// Change the services' node ports.
By("changing the TCP service's " + serviceName + " NodePort")
tcpService = jig.ChangeServiceNodePortOrFail(ns1, tcpService.Name, tcpNodePort)
jig.SanityCheckService(tcpService, api.ServiceTypeLoadBalancer)
tcpNodePortOld := tcpNodePort
tcpNodePort = tcpService.Spec.Ports[0].NodePort
if tcpNodePort == tcpNodePortOld {
Failf("TCP Spec.Ports[0].NodePort (%d) did not change", tcpNodePort)
}
if getIngressPoint(&tcpService.Status.LoadBalancer.Ingress[0]) != tcpIngressIP {
Failf("TCP Status.LoadBalancer.Ingress changed (%s -> %s) when not expected", tcpIngressIP, getIngressPoint(&tcpService.Status.LoadBalancer.Ingress[0]))
}
Logf("TCP node port: %d", tcpNodePort)
By("changing the UDP service's " + serviceName + " NodePort")
udpService = jig.ChangeServiceNodePortOrFail(ns2, udpService.Name, udpNodePort)
jig.SanityCheckService(udpService, api.ServiceTypeLoadBalancer)
udpNodePortOld := udpNodePort
udpNodePort = udpService.Spec.Ports[0].NodePort
if udpNodePort == udpNodePortOld {
Failf("UDP Spec.Ports[0].NodePort (%d) did not change", udpNodePort)
}
if getIngressPoint(&udpService.Status.LoadBalancer.Ingress[0]) != udpIngressIP {
Failf("UDP Status.LoadBalancer.Ingress changed (%s -> %s) when not expected", udpIngressIP, getIngressPoint(&udpService.Status.LoadBalancer.Ingress[0]))
}
Logf("UDP node port: %d", udpNodePort)
By("hitting the TCP service's new NodePort")
jig.TestReachableHTTP(nodeIP, tcpNodePort, kubeProxyLagTimeout)
By("hitting the UDP service's new NodePort")
jig.TestReachableUDP(nodeIP, udpNodePort, kubeProxyLagTimeout)
By("checking the old TCP NodePort is closed")
jig.TestNotReachableHTTP(nodeIP, tcpNodePortOld, kubeProxyLagTimeout)
By("checking the old UDP NodePort is closed")
jig.TestNotReachableUDP(nodeIP, udpNodePortOld, kubeProxyLagTimeout)
By("hitting the TCP service's LoadBalancer")
jig.TestReachableHTTP(tcpIngressIP, svcPort, loadBalancerLagTimeout)
By("hitting the UDP service's LoadBalancer")
jig.TestReachableUDP(udpIngressIP, svcPort, loadBalancerLagTimeout)
// Change the services' main ports.
By("changing the TCP service's port")
tcpService = jig.UpdateServiceOrFail(ns1, tcpService.Name, func(s *api.Service) {
s.Spec.Ports[0].Port++
})
jig.SanityCheckService(tcpService, api.ServiceTypeLoadBalancer)
svcPortOld := svcPort
svcPort = tcpService.Spec.Ports[0].Port
if svcPort == svcPortOld {
Failf("TCP Spec.Ports[0].Port (%d) did not change", svcPort)
}
if tcpService.Spec.Ports[0].NodePort != tcpNodePort {
Failf("TCP Spec.Ports[0].NodePort (%d) changed", tcpService.Spec.Ports[0].NodePort)
}
if getIngressPoint(&tcpService.Status.LoadBalancer.Ingress[0]) != tcpIngressIP {
Failf("TCP Status.LoadBalancer.Ingress changed (%s -> %s) when not expected", tcpIngressIP, getIngressPoint(&tcpService.Status.LoadBalancer.Ingress[0]))
}
Logf("service port (TCP and UDP): %d", svcPort)
By("changing the UDP service's port")
udpService = jig.UpdateServiceOrFail(ns2, udpService.Name, func(s *api.Service) {
s.Spec.Ports[0].Port++
})
jig.SanityCheckService(udpService, api.ServiceTypeLoadBalancer)
if udpService.Spec.Ports[0].Port != svcPort {
Failf("UDP Spec.Ports[0].Port (%d) did not change", udpService.Spec.Ports[0].Port)
}
if udpService.Spec.Ports[0].NodePort != udpNodePort {
Failf("UDP Spec.Ports[0].NodePort (%d) changed", udpService.Spec.Ports[0].NodePort)
}
if getIngressPoint(&udpService.Status.LoadBalancer.Ingress[0]) != udpIngressIP {
Failf("UDP Status.LoadBalancer.Ingress changed (%s -> %s) when not expected", udpIngressIP, getIngressPoint(&udpService.Status.LoadBalancer.Ingress[0]))
}
By("hitting the TCP service's NodePort")
jig.TestReachableHTTP(nodeIP, tcpNodePort, kubeProxyLagTimeout)
By("hitting the UDP service's NodePort")
jig.TestReachableUDP(nodeIP, udpNodePort, kubeProxyLagTimeout)
By("hitting the TCP service's LoadBalancer")
jig.TestReachableHTTP(tcpIngressIP, svcPort, loadBalancerCreateTimeout) // this may actually recreate the LB
By("hitting the UDP service's LoadBalancer")
jig.TestReachableUDP(udpIngressIP, svcPort, loadBalancerCreateTimeout) // this may actually recreate the LB)
// Change the services back to ClusterIP.
By("changing TCP service " + serviceName + " back to type=ClusterIP")
tcpService = jig.UpdateServiceOrFail(ns1, tcpService.Name, func(s *api.Service) {
s.Spec.Type = api.ServiceTypeClusterIP
s.Spec.Ports[0].NodePort = 0
})
// Wait for the load balancer to be destroyed asynchronously
tcpService = jig.WaitForLoadBalancerDestroyOrFail(ns1, tcpService.Name, tcpIngressIP, svcPort)
jig.SanityCheckService(tcpService, api.ServiceTypeClusterIP)
By("changing UDP service " + serviceName + " back to type=ClusterIP")
udpService = jig.UpdateServiceOrFail(ns2, udpService.Name, func(s *api.Service) {
s.Spec.Type = api.ServiceTypeClusterIP
s.Spec.Ports[0].NodePort = 0
})
// Wait for the load balancer to be destroyed asynchronously
udpService = jig.WaitForLoadBalancerDestroyOrFail(ns2, udpService.Name, udpIngressIP, svcPort)
jig.SanityCheckService(udpService, api.ServiceTypeClusterIP)
By("checking the TCP NodePort is closed")
jig.TestNotReachableHTTP(nodeIP, tcpNodePort, kubeProxyLagTimeout)
By("checking the UDP NodePort is closed")
jig.TestNotReachableUDP(nodeIP, udpNodePort, kubeProxyLagTimeout)
By("checking the TCP LoadBalancer is closed")
jig.TestNotReachableHTTP(tcpIngressIP, svcPort, loadBalancerLagTimeout)
By("checking the UDP LoadBalancer is closed")
jig.TestNotReachableUDP(udpIngressIP, svcPort, loadBalancerLagTimeout)
})
It("should prevent NodePort collisions", func() {
// TODO: use the ServiceTestJig here
baseName := "nodeport-collision-"
serviceName1 := baseName + "1"
serviceName2 := baseName + "2"
ns := f.Namespace.Name
t := NewServerTest(c, ns, serviceName1)
defer func() {
defer GinkgoRecover()
errs := t.Cleanup()
if len(errs) != 0 {
Failf("errors in cleanup: %v", errs)
}
}()
By("creating service " + serviceName1 + " with type NodePort in namespace " + ns)
service := t.BuildServiceSpec()
service.Spec.Type = api.ServiceTypeNodePort
result, err := t.CreateService(service)
Expect(err).NotTo(HaveOccurred())
if result.Spec.Type != api.ServiceTypeNodePort {
Failf("got unexpected Spec.Type for new service: %v", result)
}
if len(result.Spec.Ports) != 1 {
Failf("got unexpected len(Spec.Ports) for new service: %v", result)
}
port := result.Spec.Ports[0]
if port.NodePort == 0 {
Failf("got unexpected Spec.Ports[0].nodePort for new service: %v", result)
}
By("creating service " + serviceName2 + " with conflicting NodePort")
service2 := t.BuildServiceSpec()
service2.Name = serviceName2
service2.Spec.Type = api.ServiceTypeNodePort
service2.Spec.Ports[0].NodePort = port.NodePort
result2, err := t.CreateService(service2)
if err == nil {
Failf("Created service with conflicting NodePort: %v", result2)
}
expectedErr := fmt.Sprintf("%d.*port is already allocated", port.NodePort)
Expect(fmt.Sprintf("%v", err)).To(MatchRegexp(expectedErr))
By("deleting service " + serviceName1 + " to release NodePort")
err = t.DeleteService(serviceName1)
Expect(err).NotTo(HaveOccurred())
By("creating service " + serviceName2 + " with no-longer-conflicting NodePort")
_, err = t.CreateService(service2)
Expect(err).NotTo(HaveOccurred())
})
It("should check NodePort out-of-range", func() {
// TODO: use the ServiceTestJig here
serviceName := "nodeport-range-test"
ns := f.Namespace.Name
t := NewServerTest(c, ns, serviceName)
defer func() {
defer GinkgoRecover()
errs := t.Cleanup()
if len(errs) != 0 {
Failf("errors in cleanup: %v", errs)
}
}()
service := t.BuildServiceSpec()
service.Spec.Type = api.ServiceTypeNodePort
By("creating service " + serviceName + " with type NodePort in namespace " + ns)
service, err := t.CreateService(service)
Expect(err).NotTo(HaveOccurred())
if service.Spec.Type != api.ServiceTypeNodePort {
Failf("got unexpected Spec.Type for new service: %v", service)
}
if len(service.Spec.Ports) != 1 {
Failf("got unexpected len(Spec.Ports) for new service: %v", service)
}
port := service.Spec.Ports[0]
if port.NodePort == 0 {
Failf("got unexpected Spec.Ports[0].nodePort for new service: %v", service)
}
if !ServiceNodePortRange.Contains(port.NodePort) {
Failf("got unexpected (out-of-range) port for new service: %v", service)
}
outOfRangeNodePort := 0
for {
outOfRangeNodePort = 1 + rand.Intn(65535)
if !ServiceNodePortRange.Contains(outOfRangeNodePort) {
break
}
}
By(fmt.Sprintf("changing service "+serviceName+" to out-of-range NodePort %d", outOfRangeNodePort))
result, err := updateService(c, ns, serviceName, func(s *api.Service) {
s.Spec.Ports[0].NodePort = outOfRangeNodePort
})
if err == nil {
Failf("failed to prevent update of service with out-of-range NodePort: %v", result)
}
expectedErr := fmt.Sprintf("%d.*port is not in the valid range", outOfRangeNodePort)
Expect(fmt.Sprintf("%v", err)).To(MatchRegexp(expectedErr))
By("deleting original service " + serviceName)
err = t.DeleteService(serviceName)
Expect(err).NotTo(HaveOccurred())
By(fmt.Sprintf("creating service "+serviceName+" with out-of-range NodePort %d", outOfRangeNodePort))
service = t.BuildServiceSpec()
service.Spec.Type = api.ServiceTypeNodePort
service.Spec.Ports[0].NodePort = outOfRangeNodePort
service, err = t.CreateService(service)
if err == nil {
Failf("failed to prevent create of service with out-of-range NodePort (%d): %v", outOfRangeNodePort, service)
}
Expect(fmt.Sprintf("%v", err)).To(MatchRegexp(expectedErr))
})
It("should release NodePorts on delete", func() {
// TODO: use the ServiceTestJig here
serviceName := "nodeport-reuse"
ns := f.Namespace.Name
t := NewServerTest(c, ns, serviceName)
defer func() {
defer GinkgoRecover()
errs := t.Cleanup()
if len(errs) != 0 {
Failf("errors in cleanup: %v", errs)
}
}()
service := t.BuildServiceSpec()
service.Spec.Type = api.ServiceTypeNodePort
By("creating service " + serviceName + " with type NodePort in namespace " + ns)
service, err := t.CreateService(service)
Expect(err).NotTo(HaveOccurred())
if service.Spec.Type != api.ServiceTypeNodePort {
Failf("got unexpected Spec.Type for new service: %v", service)
}
if len(service.Spec.Ports) != 1 {
Failf("got unexpected len(Spec.Ports) for new service: %v", service)
}
port := service.Spec.Ports[0]
if port.NodePort == 0 {
Failf("got unexpected Spec.Ports[0].nodePort for new service: %v", service)
}
if !ServiceNodePortRange.Contains(port.NodePort) {
Failf("got unexpected (out-of-range) port for new service: %v", service)
}
nodePort := port.NodePort
By("deleting original service " + serviceName)
err = t.DeleteService(serviceName)
Expect(err).NotTo(HaveOccurred())
hostExec := LaunchHostExecPod(f.Client, f.Namespace.Name, "hostexec")
cmd := fmt.Sprintf(`! ss -ant46 'sport = :%d' | tail -n +2 | grep LISTEN`, nodePort)
var stdout string
if pollErr := wait.PollImmediate(poll, kubeProxyLagTimeout, func() (bool, error) {
var err error
stdout, err = RunHostCmd(hostExec.Namespace, hostExec.Name, cmd)
if err != nil {
Logf("expected node port (%d) to not be in use, stdout: %v", nodePort, stdout)
return false, nil
}
return true, nil
}); pollErr != nil {
Failf("expected node port (%d) to not be in use in %v, stdout: %v", nodePort, kubeProxyLagTimeout, stdout)
}
By(fmt.Sprintf("creating service "+serviceName+" with same NodePort %d", nodePort))
service = t.BuildServiceSpec()
service.Spec.Type = api.ServiceTypeNodePort
service.Spec.Ports[0].NodePort = nodePort
service, err = t.CreateService(service)
Expect(err).NotTo(HaveOccurred())
})
})
// updateService fetches a service, calls the update function on it,
// and then attempts to send the updated service. It retries up to 2
// times in the face of timeouts and conflicts.
func updateService(c *client.Client, namespace, serviceName string, update func(*api.Service)) (*api.Service, error) {
var service *api.Service
var err error
for i := 0; i < 3; i++ {
service, err = c.Services(namespace).Get(serviceName)
if err != nil {
return service, err
}
update(service)
service, err = c.Services(namespace).Update(service)
if !errors.IsConflict(err) && !errors.IsServerTimeout(err) {
return service, err
}
}
return service, err
}
func getContainerPortsByPodUID(endpoints *api.Endpoints) PortsByPodUID {
m := PortsByPodUID{}
for _, ss := range endpoints.Subsets {
for _, port := range ss.Ports {
for _, addr := range ss.Addresses {
containerPort := port.Port
hostPort := port.Port
// use endpoint annotations to recover the container port in a Mesos setup
// compare contrib/mesos/pkg/service/endpoints_controller.syncService
key := fmt.Sprintf("k8s.mesosphere.io/containerPort_%s_%s_%d", port.Protocol, addr.IP, hostPort)
mesosContainerPortString := endpoints.Annotations[key]
if mesosContainerPortString != "" {
var err error
containerPort, err = strconv.Atoi(mesosContainerPortString)
if err != nil {
continue
}
Logf("Mapped mesos host port %d to container port %d via annotation %s=%s", hostPort, containerPort, key, mesosContainerPortString)
}
// Logf("Found pod %v, host port %d and container port %d", addr.TargetRef.UID, hostPort, containerPort)
if _, ok := m[addr.TargetRef.UID]; !ok {
m[addr.TargetRef.UID] = make([]int, 0)
}
m[addr.TargetRef.UID] = append(m[addr.TargetRef.UID], containerPort)
}
}
}
return m
}
type PortsByPodName map[string][]int
type PortsByPodUID map[types.UID][]int
func translatePodNameToUIDOrFail(c *client.Client, ns string, expectedEndpoints PortsByPodName) PortsByPodUID {
portsByUID := make(PortsByPodUID)
for name, portList := range expectedEndpoints {
pod, err := c.Pods(ns).Get(name)
if err != nil {
Failf("failed to get pod %s, that's pretty weird. validation failed: %s", name, err)
}
portsByUID[pod.ObjectMeta.UID] = portList
}
// Logf("successfully translated pod names to UIDs: %v -> %v on namespace %s", expectedEndpoints, portsByUID, ns)
return portsByUID
}
func validatePortsOrFail(endpoints PortsByPodUID, expectedEndpoints PortsByPodUID) {
if len(endpoints) != len(expectedEndpoints) {
// should not happen because we check this condition before
Failf("invalid number of endpoints got %v, expected %v", endpoints, expectedEndpoints)
}
for podUID := range expectedEndpoints {
if _, ok := endpoints[podUID]; !ok {
Failf("endpoint %v not found", podUID)
}
if len(endpoints[podUID]) != len(expectedEndpoints[podUID]) {
Failf("invalid list of ports for uid %v. Got %v, expected %v", podUID, endpoints[podUID], expectedEndpoints[podUID])
}
sort.Ints(endpoints[podUID])
sort.Ints(expectedEndpoints[podUID])
for index := range endpoints[podUID] {
if endpoints[podUID][index] != expectedEndpoints[podUID][index] {
Failf("invalid list of ports for uid %v. Got %v, expected %v", podUID, endpoints[podUID], expectedEndpoints[podUID])
}
}
}
}
func validateEndpointsOrFail(c *client.Client, namespace, serviceName string, expectedEndpoints PortsByPodName) {
By(fmt.Sprintf("waiting up to %v for service %s in namespace %s to expose endpoints %v", serviceStartTimeout, serviceName, namespace, expectedEndpoints))
i := 1
for start := time.Now(); time.Since(start) < serviceStartTimeout; time.Sleep(1 * time.Second) {
endpoints, err := c.Endpoints(namespace).Get(serviceName)
if err != nil {
Logf("Get endpoints failed (%v elapsed, ignoring for 5s): %v", time.Since(start), err)
continue
}
// Logf("Found endpoints %v", endpoints)
portsByPodUID := getContainerPortsByPodUID(endpoints)
// Logf("Found port by pod UID %v", portsByPodUID)
expectedPortsByPodUID := translatePodNameToUIDOrFail(c, namespace, expectedEndpoints)
if len(portsByPodUID) == len(expectedEndpoints) {
validatePortsOrFail(portsByPodUID, expectedPortsByPodUID)
Logf("successfully validated that service %s in namespace %s exposes endpoints %v (%v elapsed)",
serviceName, namespace, expectedEndpoints, time.Since(start))
return
}
if i%5 == 0 {
Logf("Unexpected endpoints: found %v, expected %v (%v elapsed, will retry)", portsByPodUID, expectedEndpoints, time.Since(start))
}
i++
}
if pods, err := c.Pods(api.NamespaceAll).List(api.ListOptions{}); err == nil {
for _, pod := range pods.Items {
Logf("Pod %s\t%s\t%s\t%s", pod.Namespace, pod.Name, pod.Spec.NodeName, pod.DeletionTimestamp)
}
} else {
Logf("Can't list pod debug info: %v", err)
}
Failf("Timed out waiting for service %s in namespace %s to expose endpoints %v (%v elapsed)", serviceName, namespace, expectedEndpoints, serviceStartTimeout)
}
// createExecPodOrFail creates a simple busybox pod in a sleep loop used as a
// vessel for kubectl exec commands.
func createExecPodOrFail(c *client.Client, ns, name string) {
Logf("Creating new exec pod")
immediate := int64(0)
pod := &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: name,
Namespace: ns,
},
Spec: api.PodSpec{
TerminationGracePeriodSeconds: &immediate,
Containers: []api.Container{
{
Name: "exec",
Image: "gcr.io/google_containers/busybox",
Command: []string{"sh", "-c", "while true; do sleep 5; done"},
},
},
},
}
_, err := c.Pods(ns).Create(pod)
Expect(err).NotTo(HaveOccurred())
err = wait.PollImmediate(poll, 5*time.Minute, func() (bool, error) {
retrievedPod, err := c.Pods(pod.Namespace).Get(pod.Name)
if err != nil {
return false, nil
}
return retrievedPod.Status.Phase == api.PodRunning, nil
})
Expect(err).NotTo(HaveOccurred())
}
func createPodOrFail(c *client.Client, ns, name string, labels map[string]string, containerPorts []api.ContainerPort) {
By(fmt.Sprintf("creating pod %s in namespace %s", name, ns))
pod := &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: name,
Labels: labels,
},
Spec: api.PodSpec{
Containers: []api.Container{
{
Name: "test",
Image: "gcr.io/google_containers/pause:2.0",
Ports: containerPorts,
},
},
},
}
_, err := c.Pods(ns).Create(pod)
Expect(err).NotTo(HaveOccurred())
}
func deletePodOrFail(c *client.Client, ns, name string) {
By(fmt.Sprintf("deleting pod %s in namespace %s", name, ns))
err := c.Pods(ns).Delete(name, nil)
Expect(err).NotTo(HaveOccurred())
}
func collectAddresses(nodes *api.NodeList, addressType api.NodeAddressType) []string {
ips := []string{}
for i := range nodes.Items {
item := &nodes.Items[i]
for j := range item.Status.Addresses {
nodeAddress := &item.Status.Addresses[j]
if nodeAddress.Type == addressType {
ips = append(ips, nodeAddress.Address)
}
}
}
return ips
}
func getNodePublicIps(c *client.Client) ([]string, error) {
nodes := ListSchedulableNodesOrDie(c)
ips := collectAddresses(nodes, api.NodeExternalIP)
if len(ips) == 0 {
ips = collectAddresses(nodes, api.NodeLegacyHostIP)
}
return ips, nil
}
func pickNodeIP(c *client.Client) string {
publicIps, err := getNodePublicIps(c)
Expect(err).NotTo(HaveOccurred())
if len(publicIps) == 0 {
Failf("got unexpected number (%d) of public IPs", len(publicIps))
}
ip := publicIps[0]
return ip
}
func testReachableHTTP(ip string, port int, request string, expect string) (bool, error) {
url := fmt.Sprintf("http://%s:%d%s", ip, port, request)
if ip == "" {
Failf("Got empty IP for reachability check (%s)", url)
return false, nil
}
if port == 0 {
Failf("Got port==0 for reachability check (%s)", url)
return false, nil
}
Logf("Testing HTTP reachability of %v", url)
resp, err := httpGetNoConnectionPool(url)
if err != nil {
Logf("Got error testing for reachability of %s: %v", url, err)
return false, nil
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
Logf("Got error reading response from %s: %v", url, err)
return false, nil
}
if resp.StatusCode != 200 {
return false, fmt.Errorf("received non-success return status %q trying to access %s; got body: %s", resp.Status, url, string(body))
}
if !strings.Contains(string(body), expect) {
return false, fmt.Errorf("received response body without expected substring %q: %s", expect, string(body))
}
Logf("Successfully reached %v", url)
return true, nil
}
func testNotReachableHTTP(ip string, port int) (bool, error) {
url := fmt.Sprintf("http://%s:%d", ip, port)
if ip == "" {
Failf("Got empty IP for non-reachability check (%s)", url)
return false, nil
}
if port == 0 {
Failf("Got port==0 for non-reachability check (%s)", url)
return false, nil
}
Logf("Testing HTTP non-reachability of %v", url)
resp, err := httpGetNoConnectionPool(url)
if err != nil {
Logf("Confirmed that %s is not reachable", url)
return true, nil
}
resp.Body.Close()
return false, nil
}
func testReachableUDP(ip string, port int, request string, expect string) (bool, error) {
uri := fmt.Sprintf("udp://%s:%d", ip, port)
if ip == "" {
Failf("Got empty IP for reachability check (%s)", uri)
return false, nil
}
if port == 0 {
Failf("Got port==0 for reachability check (%s)", uri)
return false, nil
}
Logf("Testing UDP reachability of %v", uri)
con, err := net.Dial("udp", ip+":"+strconv.Itoa(port))
if err != nil {
return false, fmt.Errorf("Failed to dial %s:%d: %v", ip, port, err)
}
_, err = con.Write([]byte(fmt.Sprintf("%s\n", request)))
if err != nil {
return false, fmt.Errorf("Failed to send request: %v", err)
}
var buf []byte = make([]byte, len(expect)+1)
err = con.SetDeadline(time.Now().Add(3 * time.Second))
if err != nil {
return false, fmt.Errorf("Failed to set deadline: %v", err)
}
_, err = con.Read(buf)
if err != nil {
return false, nil
}
if !strings.Contains(string(buf), expect) {
return false, fmt.Errorf("Failed to retrieve %q, got %q", expect, string(buf))
}
Logf("Successfully reached %v", uri)
return true, nil
}
func testNotReachableUDP(ip string, port int, request string) (bool, error) {
uri := fmt.Sprintf("udp://%s:%d", ip, port)
if ip == "" {
Failf("Got empty IP for reachability check (%s)", uri)
return false, nil
}
if port == 0 {
Failf("Got port==0 for reachability check (%s)", uri)
return false, nil
}
Logf("Testing UDP non-reachability of %v", uri)
con, err := net.Dial("udp", ip+":"+strconv.Itoa(port))
if err != nil {
Logf("Confirmed that %s is not reachable", uri)
return true, nil
}
_, err = con.Write([]byte(fmt.Sprintf("%s\n", request)))
if err != nil {
Logf("Confirmed that %s is not reachable", uri)
return true, nil
}
var buf []byte = make([]byte, 1)
err = con.SetDeadline(time.Now().Add(3 * time.Second))
if err != nil {
return false, fmt.Errorf("Failed to set deadline: %v", err)
}
_, err = con.Read(buf)
if err != nil {
Logf("Confirmed that %s is not reachable", uri)
return true, nil
}
return false, nil
}
// Creates a replication controller that serves its hostname and a service on top of it.
func startServeHostnameService(c *client.Client, ns, name string, port, replicas int) ([]string, string, error) {
podNames := make([]string, replicas)
By("creating service " + name + " in namespace " + ns)
_, err := c.Services(ns).Create(&api.Service{
ObjectMeta: api.ObjectMeta{
Name: name,
},
Spec: api.ServiceSpec{
Ports: []api.ServicePort{{
Port: port,
TargetPort: intstr.FromInt(9376),
Protocol: "TCP",
}},
Selector: map[string]string{
"name": name,
},
},
})
if err != nil {
return podNames, "", err
}
var createdPods []*api.Pod
maxContainerFailures := 0
config := RCConfig{
Client: c,
Image: "gcr.io/google_containers/serve_hostname:1.1",
Name: name,
Namespace: ns,
PollInterval: 3 * time.Second,
Timeout: podReadyBeforeTimeout,
Replicas: replicas,
CreatedPods: &createdPods,
MaxContainerFailures: &maxContainerFailures,
}
err = RunRC(config)
if err != nil {
return podNames, "", err
}
if len(createdPods) != replicas {
return podNames, "", fmt.Errorf("Incorrect number of running pods: %v", len(createdPods))
}
for i := range createdPods {
podNames[i] = createdPods[i].ObjectMeta.Name
}
sort.StringSlice(podNames).Sort()
service, err := c.Services(ns).Get(name)
if err != nil {
return podNames, "", err
}
if service.Spec.ClusterIP == "" {
return podNames, "", fmt.Errorf("Service IP is blank for %v", name)
}
serviceIP := service.Spec.ClusterIP
return podNames, serviceIP, nil
}
func stopServeHostnameService(c *client.Client, ns, name string) error {
if err := DeleteRC(c, ns, name); err != nil {
return err
}
if err := c.Services(ns).Delete(name); err != nil {
return err
}
return nil
}
// verifyServeHostnameServiceUp wgets the given serviceIP:servicePort from the
// given host and from within a pod. The host is expected to be an SSH-able node
// in the cluster. Each pod in the service is expected to echo its name. These
// names are compared with the given expectedPods list after a sort | uniq.
func verifyServeHostnameServiceUp(c *client.Client, ns, host string, expectedPods []string, serviceIP string, servicePort int) error {
execPodName := "execpod"
createExecPodOrFail(c, ns, execPodName)
defer func() {
deletePodOrFail(c, ns, execPodName)
}()
// Loop a bunch of times - the proxy is randomized, so we want a good
// chance of hitting each backend at least once.
buildCommand := func(wget string) string {
return fmt.Sprintf("for i in $(seq 1 %d); do %s http://%s:%d 2>&1 || true; echo; done",
50*len(expectedPods), wget, serviceIP, servicePort)
}
commands := []func() string{
// verify service from node
func() string {
cmd := "set -e; " + buildCommand("wget -q --timeout=0.2 --tries=1 -O -")
Logf("Executing cmd %q on host %v", cmd, host)
result, err := SSH(cmd, host, testContext.Provider)
if err != nil || result.Code != 0 {
LogSSHResult(result)
Logf("error while SSH-ing to node: %v", err)
}
return result.Stdout
},
// verify service from pod
func() string {
cmd := buildCommand("wget -q -T 1 -O -")
Logf("Executing cmd %q in pod %v/%v", cmd, ns, execPodName)
// TODO: Use exec-over-http via the netexec pod instead of kubectl exec.
output, err := RunHostCmd(ns, execPodName, cmd)
if err != nil {
Logf("error while kubectl execing %q in pod %v/%v: %v\nOutput: %v", cmd, ns, execPodName, err, output)
}
return output
},
}
sort.StringSlice(expectedPods).Sort()
By(fmt.Sprintf("verifying service has %d reachable backends", len(expectedPods)))
for _, cmdFunc := range commands {
passed := false
gotPods := []string{}
// Retry cmdFunc for a while
for start := time.Now(); time.Since(start) < time.Minute; time.Sleep(5 * time.Second) {
pods := strings.Split(strings.TrimSpace(cmdFunc()), "\n")
// Uniq pods before the sort because inserting them into a set
// (which is implemented using dicts) can re-order them.
gotPods = sets.NewString(pods...).List()
if api.Semantic.DeepEqual(gotPods, expectedPods) {
passed = true
break
}
Logf("Waiting for expected pods for %s: %v, got: %v", serviceIP, expectedPods, gotPods)
}
if !passed {
return fmt.Errorf("service verification failed for: %s, expected %v, got %v", serviceIP, expectedPods, gotPods)
}
}
return nil
}
func verifyServeHostnameServiceDown(c *client.Client, host string, serviceIP string, servicePort int) error {
command := fmt.Sprintf(
"curl -s --connect-timeout 2 http://%s:%d && exit 99", serviceIP, servicePort)
for start := time.Now(); time.Since(start) < time.Minute; time.Sleep(5 * time.Second) {
result, err := SSH(command, host, testContext.Provider)
if err != nil {
LogSSHResult(result)
Logf("error while SSH-ing to node: %v", err)
}
if result.Code != 99 {
return nil
}
Logf("service still alive - still waiting")
}
return fmt.Errorf("waiting for service to be down timed out")
}
// Does an HTTP GET, but does not reuse TCP connections
// This masks problems where the iptables rule has changed, but we don't see it
// This is intended for relatively quick requests (status checks), so we set a short (5 seconds) timeout
func httpGetNoConnectionPool(url string) (*http.Response, error) {
tr := &http.Transport{
DisableKeepAlives: true,
}
client := &http.Client{
Transport: tr,
Timeout: 5 * time.Second,
}
return client.Get(url)
}
// A test jig to help testing.
type ServiceTestJig struct {
ID string
Name string
Client *client.Client
Labels map[string]string
}
// NewServiceTestJig allocates and inits a new ServiceTestJig.
func NewServiceTestJig(client *client.Client, name string) *ServiceTestJig {
j := &ServiceTestJig{}
j.Client = client
j.Name = name
j.ID = j.Name + "-" + string(util.NewUUID())
j.Labels = map[string]string{"testid": j.ID}
return j
}
// newServiceTemplate returns the default api.Service template for this jig, but
// does not actually create the Service. The default Service has the same name
// as the jig and exposes port 80.
func (j *ServiceTestJig) newServiceTemplate(namespace string, proto api.Protocol) *api.Service {
service := &api.Service{
ObjectMeta: api.ObjectMeta{
Namespace: namespace,
Name: j.Name,
Labels: j.Labels,
},
Spec: api.ServiceSpec{
Selector: j.Labels,
Ports: []api.ServicePort{
{
Protocol: proto,
Port: 80,
},
},
},
}
return service
}
// CreateTCPServiceOrFail creates a new TCP Service based on the jig's
// defaults. Callers can provide a function to tweak the Service object before
// it is created.
func (j *ServiceTestJig) CreateTCPServiceOrFail(namespace string, tweak func(svc *api.Service)) *api.Service {
svc := j.newServiceTemplate(namespace, api.ProtocolTCP)
if tweak != nil {
tweak(svc)
}
result, err := j.Client.Services(namespace).Create(svc)
if err != nil {
Failf("Failed to create TCP Service %q: %v", svc.Name, err)
}
return result
}
// CreateUDPServiceOrFail creates a new UDP Service based on the jig's
// defaults. Callers can provide a function to tweak the Service object before
// it is created.
func (j *ServiceTestJig) CreateUDPServiceOrFail(namespace string, tweak func(svc *api.Service)) *api.Service {
svc := j.newServiceTemplate(namespace, api.ProtocolUDP)
if tweak != nil {
tweak(svc)
}
result, err := j.Client.Services(namespace).Create(svc)
if err != nil {
Failf("Failed to create UDP Service %q: %v", svc.Name, err)
}
return result
}
func (j *ServiceTestJig) SanityCheckService(svc *api.Service, svcType api.ServiceType) {
if svc.Spec.Type != svcType {
Failf("unexpected Spec.Type (%s) for service, expected %s", svc.Spec.Type, svcType)
}
expectNodePorts := false
if svcType != api.ServiceTypeClusterIP {
expectNodePorts = true
}
for i, port := range svc.Spec.Ports {
hasNodePort := (port.NodePort != 0)
if hasNodePort != expectNodePorts {
Failf("unexpected Spec.Ports[%d].NodePort (%d) for service", i, port.NodePort)
}
if hasNodePort {
if !ServiceNodePortRange.Contains(port.NodePort) {
Failf("out-of-range nodePort (%d) for service", port.NodePort)
}
}
}
expectIngress := false
if svcType == api.ServiceTypeLoadBalancer {
expectIngress = true
}
hasIngress := len(svc.Status.LoadBalancer.Ingress) != 0
if hasIngress != expectIngress {
Failf("unexpected number of Status.LoadBalancer.Ingress (%d) for service", len(svc.Status.LoadBalancer.Ingress))
}
if hasIngress {
for i, ing := range svc.Status.LoadBalancer.Ingress {
if ing.IP == "" && ing.Hostname == "" {
Failf("unexpected Status.LoadBalancer.Ingress[%d] for service: %#v", i, ing)
}
}
}
}
// UpdateService fetches a service, calls the update function on it, and
// then attempts to send the updated service. It tries up to 3 times in the
// face of timeouts and conflicts.
func (j *ServiceTestJig) UpdateService(namespace, name string, update func(*api.Service)) (*api.Service, error) {
for i := 0; i < 3; i++ {
service, err := j.Client.Services(namespace).Get(name)
if err != nil {
return nil, fmt.Errorf("Failed to get Service %q: %v", name, err)
}
update(service)
service, err = j.Client.Services(namespace).Update(service)
if err == nil {
return service, nil
}
if !errors.IsConflict(err) && !errors.IsServerTimeout(err) {
return nil, fmt.Errorf("Failed to update Service %q: %v", name, err)
}
}
return nil, fmt.Errorf("Too many retries updating Service %q", name)
}
// UpdateServiceOrFail fetches a service, calls the update function on it, and
// then attempts to send the updated service. It tries up to 3 times in the
// face of timeouts and conflicts.
func (j *ServiceTestJig) UpdateServiceOrFail(namespace, name string, update func(*api.Service)) *api.Service {
svc, err := j.UpdateService(namespace, name, update)
if err != nil {
Failf(err.Error())
}
return svc
}
func (j *ServiceTestJig) ChangeServiceNodePortOrFail(namespace, name string, initial int) *api.Service {
var err error
var service *api.Service
for i := 1; i < ServiceNodePortRange.Size; i++ {
offs1 := initial - ServiceNodePortRange.Base
offs2 := (offs1 + i) % ServiceNodePortRange.Size
newPort := ServiceNodePortRange.Base + offs2
service, err = j.UpdateService(namespace, name, func(s *api.Service) {
s.Spec.Ports[0].NodePort = newPort
})
if err != nil && strings.Contains(err.Error(), "provided port is already allocated") {
Logf("tried nodePort %d, but it is in use, will try another", newPort)
continue
}
// Otherwise err was nil or err was a real error
break
}
if err != nil {
Failf("Could not change the nodePort: %v", err)
}
return service
}
func (j *ServiceTestJig) WaitForLoadBalancerOrFail(namespace, name string) *api.Service {
var service *api.Service
Logf("Waiting up to %v for service %q to have a LoadBalancer", loadBalancerCreateTimeout, name)
pollFunc := func() (bool, error) {
svc, err := j.Client.Services(namespace).Get(name)
if err != nil {
return false, err
}
if len(svc.Status.LoadBalancer.Ingress) > 0 {
service = svc
return true, nil
}
return false, nil
}
if err := wait.PollImmediate(poll, loadBalancerCreateTimeout, pollFunc); err != nil {
Failf("Timeout waiting for service %q to have a load balancer", name)
}
return service
}
func (j *ServiceTestJig) WaitForLoadBalancerDestroyOrFail(namespace, name string, ip string, port int) *api.Service {
// TODO: once support ticket 21807001 is resolved, reduce this timeout back to something reasonable
defer func() {
if err := EnsureLoadBalancerResourcesDeleted(ip, strconv.Itoa(port)); err != nil {
Logf("Failed to delete cloud resources for service: %s %d (%v)", ip, port, err)
}
}()
var service *api.Service
Logf("Waiting up to %v for service %q to have no LoadBalancer", loadBalancerCreateTimeout, name)
pollFunc := func() (bool, error) {
svc, err := j.Client.Services(namespace).Get(name)
if err != nil {
return false, err
}
if len(svc.Status.LoadBalancer.Ingress) == 0 {
service = svc
return true, nil
}
return false, nil
}
if err := wait.PollImmediate(poll, loadBalancerCreateTimeout, pollFunc); err != nil {
Failf("Timeout waiting for service %q to have no load balancer", name)
}
return service
}
func (j *ServiceTestJig) TestReachableHTTP(host string, port int, timeout time.Duration) {
if err := wait.PollImmediate(poll, timeout, func() (bool, error) { return testReachableHTTP(host, port, "/echo?msg=hello", "hello") }); err != nil {
Failf("Could not reach HTTP service through %v:%v after %v: %v", host, port, timeout, err)
}
}
func (j *ServiceTestJig) TestNotReachableHTTP(host string, port int, timeout time.Duration) {
if err := wait.PollImmediate(poll, timeout, func() (bool, error) { return testNotReachableHTTP(host, port) }); err != nil {
Failf("Could still reach HTTP service through %v:%v after %v: %v", host, port, timeout, err)
}
}
func (j *ServiceTestJig) TestReachableUDP(host string, port int, timeout time.Duration) {
if err := wait.PollImmediate(poll, timeout, func() (bool, error) { return testReachableUDP(host, port, "echo hello", "hello") }); err != nil {
Failf("Could not reach UDP service through %v:%v after %v: %v", host, port, timeout, err)
}
}
func (j *ServiceTestJig) TestNotReachableUDP(host string, port int, timeout time.Duration) {
if err := wait.PollImmediate(poll, timeout, func() (bool, error) { return testNotReachableUDP(host, port, "echo hello") }); err != nil {
Failf("Could still reach UDP service through %v:%v after %v: %v", host, port, timeout, err)
}
}
func getIngressPoint(ing *api.LoadBalancerIngress) string {
host := ing.IP
if host == "" {
host = ing.Hostname
}
return host
}
// newRCTemplate returns the default api.ReplicationController object for
// this jig, but does not actually create the RC. The default RC has the same
// name as the jig and runs the "netexec" container.
func (j *ServiceTestJig) newRCTemplate(namespace string) *api.ReplicationController {
rc := &api.ReplicationController{
ObjectMeta: api.ObjectMeta{
Namespace: namespace,
Name: j.Name,
Labels: j.Labels,
},
Spec: api.ReplicationControllerSpec{
Replicas: 1,
Selector: j.Labels,
Template: &api.PodTemplateSpec{
ObjectMeta: api.ObjectMeta{
Labels: j.Labels,
},
Spec: api.PodSpec{
Containers: []api.Container{
{
Name: "netexec",
Image: "gcr.io/google_containers/netexec:1.4",
Args: []string{"--http-port=80", "--udp-port=80"},
ReadinessProbe: &api.Probe{
PeriodSeconds: 3,
Handler: api.Handler{
HTTPGet: &api.HTTPGetAction{
Port: intstr.FromInt(80),
Path: "/hostName",
},
},
},
},
},
TerminationGracePeriodSeconds: new(int64),
},
},
},
}
return rc
}
// RunOrFail creates a ReplicationController and Pod(s) and waits for the
// Pod(s) to be running. Callers can provide a function to tweak the RC object
// before it is created.
func (j *ServiceTestJig) RunOrFail(namespace string, tweak func(rc *api.ReplicationController)) *api.ReplicationController {
rc := j.newRCTemplate(namespace)
if tweak != nil {
tweak(rc)
}
result, err := j.Client.ReplicationControllers(namespace).Create(rc)
if err != nil {
Failf("Failed to created RC %q: %v", rc.Name, err)
}
pods, err := j.waitForPodsCreated(namespace, rc.Spec.Replicas)
if err != nil {
Failf("Failed to create pods: %v", err)
}
if err := j.waitForPodsReady(namespace, pods); err != nil {
Failf("Failed waiting for pods to be running: %v", err)
}
return result
}
func (j *ServiceTestJig) waitForPodsCreated(namespace string, replicas int) ([]string, error) {
timeout := 2 * time.Minute
// List the pods, making sure we observe all the replicas.
label := labels.SelectorFromSet(labels.Set(j.Labels))
Logf("Waiting up to %v for %d pods to be created", timeout, replicas)
for start := time.Now(); time.Since(start) < timeout; time.Sleep(2 * time.Second) {
options := api.ListOptions{LabelSelector: label}
pods, err := j.Client.Pods(namespace).List(options)
if err != nil {
return nil, err
}
found := []string{}
for _, pod := range pods.Items {
if pod.DeletionTimestamp != nil {
continue
}
found = append(found, pod.Name)
}
if len(found) == replicas {
Logf("Found all %d pods", replicas)
return found, nil
}
Logf("Found %d/%d pods - will retry", len(found), replicas)
}
return nil, fmt.Errorf("Timeout waiting for %d pods to be created", replicas)
}
func (j *ServiceTestJig) waitForPodsReady(namespace string, pods []string) error {
timeout := 2 * time.Minute
if !checkPodsRunningReady(j.Client, namespace, pods, timeout) {
return fmt.Errorf("Timeout waiting for %d pods to be ready")
}
return nil
}
// Simple helper class to avoid too much boilerplate in tests
type ServiceTestFixture struct {
ServiceName string
Namespace string
Client *client.Client
TestId string
Labels map[string]string
rcs map[string]bool
services map[string]bool
name string
image string
}
func NewServerTest(client *client.Client, namespace string, serviceName string) *ServiceTestFixture {
t := &ServiceTestFixture{}
t.Client = client
t.Namespace = namespace
t.ServiceName = serviceName
t.TestId = t.ServiceName + "-" + string(util.NewUUID())
t.Labels = map[string]string{
"testid": t.TestId,
}
t.rcs = make(map[string]bool)
t.services = make(map[string]bool)
t.name = "webserver"
t.image = "gcr.io/google_containers/test-webserver"
return t
}
// Build default config for a service (which can then be changed)
func (t *ServiceTestFixture) BuildServiceSpec() *api.Service {
service := &api.Service{
ObjectMeta: api.ObjectMeta{
Name: t.ServiceName,
Namespace: t.Namespace,
},
Spec: api.ServiceSpec{
Selector: t.Labels,
Ports: []api.ServicePort{{
Port: 80,
TargetPort: intstr.FromInt(80),
}},
},
}
return service
}
// CreateWebserverRC creates rc-backed pods with the well-known webserver
// configuration and records it for cleanup.
func (t *ServiceTestFixture) CreateWebserverRC(replicas int) *api.ReplicationController {
rcSpec := rcByNamePort(t.name, replicas, t.image, 80, api.ProtocolTCP, t.Labels)
rcAct, err := t.createRC(rcSpec)
if err != nil {
Failf("Failed to create rc %s: %v", rcSpec.Name, err)
}
if err := verifyPods(t.Client, t.Namespace, t.name, false, replicas); err != nil {
Failf("Failed to create %d pods with name %s: %v", replicas, t.name, err)
}
return rcAct
}
// createRC creates a replication controller and records it for cleanup.
func (t *ServiceTestFixture) createRC(rc *api.ReplicationController) (*api.ReplicationController, error) {
rc, err := t.Client.ReplicationControllers(t.Namespace).Create(rc)
if err == nil {
t.rcs[rc.Name] = true
}
return rc, err
}
// Create a service, and record it for cleanup
func (t *ServiceTestFixture) CreateService(service *api.Service) (*api.Service, error) {
result, err := t.Client.Services(t.Namespace).Create(service)
if err == nil {
t.services[service.Name] = true
}
return result, err
}
// Delete a service, and remove it from the cleanup list
func (t *ServiceTestFixture) DeleteService(serviceName string) error {
err := t.Client.Services(t.Namespace).Delete(serviceName)
if err == nil {
delete(t.services, serviceName)
}
return err
}
func (t *ServiceTestFixture) Cleanup() []error {
var errs []error
for rcName := range t.rcs {
By("stopping RC " + rcName + " in namespace " + t.Namespace)
// First, resize the RC to 0.
old, err := t.Client.ReplicationControllers(t.Namespace).Get(rcName)
if err != nil {
errs = append(errs, err)
}
old.Spec.Replicas = 0
if _, err := t.Client.ReplicationControllers(t.Namespace).Update(old); err != nil {
errs = append(errs, err)
}
// TODO(mikedanese): Wait.
// Then, delete the RC altogether.
if err := t.Client.ReplicationControllers(t.Namespace).Delete(rcName); err != nil {
errs = append(errs, err)
}
}
for serviceName := range t.services {
By("deleting service " + serviceName + " in namespace " + t.Namespace)
err := t.Client.Services(t.Namespace).Delete(serviceName)
if err != nil {
errs = append(errs, err)
}
}
return errs
}
| apache-2.0 |
fgdorais/lean | src/library/vm/optimize.cpp | 2195 | /*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "library/vm/vm.h"
namespace lean {
static void del_instr_at(unsigned pc, buffer<vm_instr> & code) {
code.erase(pc);
// we must adjust pc of other instructions
for (unsigned i = 0; i < code.size(); i++) {
vm_instr & c = code[i];
for (unsigned j = 0; j < c.get_num_pcs(); j++) {
if (c.get_pc(j) > pc)
c.set_pc(j, c.get_pc(j) - 1);
}
}
}
typedef rb_tree<unsigned, unsigned_cmp> addr_set;
/* Collect addresses in addr_set that are goto/branching targets */
static void collect_targets(buffer<vm_instr> & code, addr_set & r) {
for (auto c : code) {
for (unsigned j = 0; j < c.get_num_pcs(); j++)
r.insert(c.get_pc(j));
}
}
/**
\brief Applies the following transformation
...
pc: drop n
pc+1: drop m
...
===>
...
pc: drop n+m
... */
static void compress_drop_drop(buffer<vm_instr> & code) {
if (code.empty()) return;
addr_set targets;
collect_targets(code, targets);
unsigned i = code.size() - 1;
while (i > 0) {
--i;
if (code[i].op() == opcode::Drop &&
code[i+1].op() == opcode::Drop &&
/* If i+1 is a goto/branch target, then we should not merge the two Drops */
!targets.contains(i+1)) {
code[i] = mk_drop_instr(code[i].get_num() + code[i+1].get_num());
del_instr_at(i+1, code);
}
}
}
/**
\brief Applies the following transformation
pc_1 : goto pc_2
...
pc_2 : ret
===>
pc_1 : ret
...
pc_2 : ret */
static void compress_goto_ret(buffer<vm_instr> & code) {
unsigned i = code.size();
while (i > 0) {
--i;
if (code[i].op() == opcode::Goto) {
unsigned pc = code[i].get_goto_pc();
if (code[pc].op() == opcode::Ret) {
code[i] = mk_ret_instr();
}
}
}
}
void optimize(environment const &, buffer<vm_instr> & code) {
compress_goto_ret(code);
compress_drop_drop(code);
}
}
| apache-2.0 |
damienmg/bazel | src/tools/android/java/com/google/devtools/build/android/desugar/DefaultMethodClassFixer.java | 24887 | // Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.android.desugar;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.collect.ImmutableList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
/**
* Fixer of classes that extend interfaces with default methods to declare any missing methods
* explicitly and call the corresponding companion method generated by {@link InterfaceDesugaring}.
*/
public class DefaultMethodClassFixer extends ClassVisitor {
private final ClassReaderFactory classpath;
private final ClassReaderFactory bootclasspath;
private final ClassLoader targetLoader;
private final DependencyCollector depsCollector;
private final HashSet<String> instanceMethods = new HashSet<>();
private boolean isInterface;
private String internalName;
private ImmutableList<String> directInterfaces;
private String superName;
/** This method node caches <clinit>, and flushes out in {@code visitEnd()}; */
private MethodNode clInitMethodNode;
public DefaultMethodClassFixer(
ClassVisitor dest,
ClassReaderFactory classpath,
DependencyCollector depsCollector,
ClassReaderFactory bootclasspath,
ClassLoader targetLoader) {
super(Opcodes.ASM5, dest);
this.classpath = classpath;
this.bootclasspath = bootclasspath;
this.targetLoader = targetLoader;
this.depsCollector = depsCollector;
}
@Override
public void visit(
int version,
int access,
String name,
String signature,
String superName,
String[] interfaces) {
checkState(this.directInterfaces == null);
isInterface = BitFlags.isSet(access, Opcodes.ACC_INTERFACE);
internalName = name;
checkArgument(
superName != null || "java/lang/Object".equals(name), // ASM promises this
"Type without superclass: %s",
name);
this.directInterfaces = ImmutableList.copyOf(interfaces);
this.superName = superName;
super.visit(version, access, name, signature, superName, interfaces);
}
@Override
public void visitEnd() {
if (!isInterface && defaultMethodsDefined(directInterfaces)) {
// Inherited methods take precedence over default methods, so visit all superclasses and
// figure out what methods they declare before stubbing in any missing default methods.
recordInheritedMethods();
stubMissingDefaultAndBridgeMethods();
// Check whether there are interfaces with default methods and <clinit>. If yes, the following
// method call will return a list of interface fields to access in the <clinit> to trigger
// the initialization of these interfaces.
ImmutableList<String> companionsToTriggerInterfaceClinit =
collectOrderedCompanionsToTriggerInterfaceClinit(directInterfaces);
if (!companionsToTriggerInterfaceClinit.isEmpty()) {
if (clInitMethodNode == null) {
clInitMethodNode = new MethodNode(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null);
}
desugarClinitToTriggerInterfaceInitializers(companionsToTriggerInterfaceClinit);
}
}
if (clInitMethodNode != null && super.cv != null) { // Write <clinit> to the chained visitor.
clInitMethodNode.accept(super.cv);
}
super.visitEnd();
}
private boolean isClinitAlreadyDesugared(
ImmutableList<String> companionsToAccessToTriggerInterfaceClinit) {
InsnList instructions = clInitMethodNode.instructions;
if (instructions.size() <= companionsToAccessToTriggerInterfaceClinit.size()) {
// The <clinit> must end with RETURN, so if the instruction count is less than or equal to
// the companion class count, this <clinit> has not been desugared.
return false;
}
Iterator<AbstractInsnNode> iterator = instructions.iterator();
for (String companion : companionsToAccessToTriggerInterfaceClinit) {
if (!iterator.hasNext()) {
return false;
}
AbstractInsnNode first = iterator.next();
if (!(first instanceof MethodInsnNode)) {
return false;
}
MethodInsnNode methodInsnNode = (MethodInsnNode) first;
if (methodInsnNode.getOpcode() != Opcodes.INVOKESTATIC
|| !methodInsnNode.owner.equals(companion)
|| !methodInsnNode.name.equals(
InterfaceDesugaring.COMPANION_METHOD_TO_TRIGGER_INTERFACE_CLINIT_NAME)) {
return false;
}
checkState(
methodInsnNode.desc.equals(
InterfaceDesugaring.COMPANION_METHOD_TO_TRIGGER_INTERFACE_CLINIT_DESC),
"Inconsistent method desc: %s vs %s",
methodInsnNode.desc,
InterfaceDesugaring.COMPANION_METHOD_TO_TRIGGER_INTERFACE_CLINIT_DESC);
if (!iterator.hasNext()) {
return false;
}
AbstractInsnNode second = iterator.next();
if (second.getOpcode() != Opcodes.POP) {
return false;
}
}
return true;
}
private void desugarClinitToTriggerInterfaceInitializers(
ImmutableList<String> companionsToTriggerInterfaceClinit) {
if (isClinitAlreadyDesugared(companionsToTriggerInterfaceClinit)) {
return;
}
InsnList desugarInsts = new InsnList();
for (String companionClass : companionsToTriggerInterfaceClinit) {
desugarInsts.add(
new MethodInsnNode(
Opcodes.INVOKESTATIC,
companionClass,
InterfaceDesugaring.COMPANION_METHOD_TO_TRIGGER_INTERFACE_CLINIT_NAME,
InterfaceDesugaring.COMPANION_METHOD_TO_TRIGGER_INTERFACE_CLINIT_DESC,
false));
}
if (clInitMethodNode.instructions.size() == 0) {
clInitMethodNode.instructions.insert(new InsnNode(Opcodes.RETURN));
}
clInitMethodNode.instructions.insertBefore(
clInitMethodNode.instructions.getFirst(), desugarInsts);
}
@Override
public MethodVisitor visitMethod(
int access, String name, String desc, String signature, String[] exceptions) {
// Keep track of instance methods implemented in this class for later.
if (!isInterface) {
recordIfInstanceMethod(access, name, desc);
}
if ("<clinit>".equals(name)) {
checkState(clInitMethodNode == null, "This class fixer has been used. ");
clInitMethodNode = new MethodNode(access, name, desc, signature, exceptions);
return clInitMethodNode;
}
return super.visitMethod(access, name, desc, signature, exceptions);
}
private void stubMissingDefaultAndBridgeMethods() {
TreeSet<Class<?>> allInterfaces = new TreeSet<>(InterfaceComparator.INSTANCE);
for (String direct : directInterfaces) {
// Loading ensures all transitively implemented interfaces can be loaded, which is necessary
// to produce correct default method stubs in all cases. We could do without classloading but
// it's convenient to rely on Class.isAssignableFrom to compute subtype relationships, and
// we'd still have to insist that all transitively implemented interfaces can be loaded.
// We don't load the visited class, however, in case it's a generated lambda class.
Class<?> itf = loadFromInternal(direct);
collectInterfaces(itf, allInterfaces);
}
Class<?> superclass = loadFromInternal(superName);
for (Class<?> interfaceToVisit : allInterfaces) {
// if J extends I, J is allowed to redefine I's default methods. The comparator we used
// above makes sure we visit J before I in that case so we can use J's definition.
if (superclass != null && interfaceToVisit.isAssignableFrom(superclass)) {
// superclass already implements this interface, so we must skip it. The superclass will
// be similarly rewritten or comes from the bootclasspath; either way we don't need to and
// shouldn't stub default methods for this interface.
continue;
}
stubMissingDefaultAndBridgeMethods(interfaceToVisit.getName().replace('.', '/'));
}
}
private Class<?> loadFromInternal(String internalName) {
try {
return targetLoader.loadClass(internalName.replace('/', '.'));
} catch (ClassNotFoundException e) {
throw new IllegalStateException(
"Couldn't load " + internalName + ", is the classpath complete?", e);
}
}
private void collectInterfaces(Class<?> itf, Set<Class<?>> dest) {
checkArgument(itf.isInterface());
if (!dest.add(itf)) {
return;
}
for (Class<?> implemented : itf.getInterfaces()) {
collectInterfaces(implemented, dest);
}
}
private void recordInheritedMethods() {
InstanceMethodRecorder recorder = new InstanceMethodRecorder();
String internalName = superName;
while (internalName != null) {
ClassReader bytecode = bootclasspath.readIfKnown(internalName);
if (bytecode == null) {
bytecode =
checkNotNull(
classpath.readIfKnown(internalName), "Superclass not found: %s", internalName);
}
bytecode.accept(recorder, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG);
internalName = bytecode.getSuperName();
}
}
private void recordIfInstanceMethod(int access, String name, String desc) {
if (BitFlags.noneSet(access, Opcodes.ACC_STATIC)) {
// Record all declared instance methods, including abstract, bridge, and native methods, as
// they all take precedence over default methods.
instanceMethods.add(name + ":" + desc);
}
}
/**
* Starting from the given interfaces, this method scans the interface hierarchy, finds the
* interfaces that have default methods and <clinit>, and returns the companion class names of
* these interfaces.
*
* <p>Note that the returned companion classes are ordered in the order of the interface
* initialization, which is consistent with the JVM behavior. For example, "class A implements I1,
* I2", the returned list would be [I1$$CC, I2$$CC], not [I2$$CC, I1$$CC].
*/
private ImmutableList<String> collectOrderedCompanionsToTriggerInterfaceClinit(
ImmutableList<String> interfaces) {
ImmutableList.Builder<String> companionCollector = ImmutableList.builder();
HashSet<String> visitedInterfaces = new HashSet<>();
for (String anInterface : interfaces) {
collectOrderedCompanionsToTriggerInterfaceClinit(
anInterface, visitedInterfaces, companionCollector);
}
return companionCollector.build();
}
private void collectOrderedCompanionsToTriggerInterfaceClinit(
String anInterface,
HashSet<String> visitedInterfaces,
ImmutableList.Builder<String> companionCollector) {
if (!visitedInterfaces.add(anInterface)) {
return;
}
ClassReader bytecode = classpath.readIfKnown(anInterface);
if (bytecode == null || bootclasspath.isKnown(anInterface)) {
return;
}
String[] parentInterfaces = bytecode.getInterfaces();
if (parentInterfaces != null && parentInterfaces.length > 0) {
for (String parentInterface : parentInterfaces) {
collectOrderedCompanionsToTriggerInterfaceClinit(
parentInterface, visitedInterfaces, companionCollector);
}
}
InterfaceInitializationNecessityDetector necessityDetector =
new InterfaceInitializationNecessityDetector(bytecode.getClassName());
bytecode.accept(necessityDetector, ClassReader.SKIP_DEBUG);
if (necessityDetector.needsToInitialize()) {
// If we need to initialize this interface, we initialize its companion class, and its
// companion class will initialize the interface then. This desigin decision is made to avoid
// access issue, e.g., package-private interfaces.
companionCollector.add(InterfaceDesugaring.getCompanionClassName(anInterface));
}
}
/**
* Recursively searches the given interfaces for default methods not implemented by this class
* directly. If this method returns true we need to think about stubbing missing default methods.
*/
private boolean defaultMethodsDefined(ImmutableList<String> interfaces) {
for (String implemented : interfaces) {
if (bootclasspath.isKnown(implemented)) {
continue;
}
ClassReader bytecode = classpath.readIfKnown(implemented);
if (bytecode == null) {
// Interface isn't on the classpath, which indicates incomplete classpaths. Record missing
// dependency so we can check it later. If we don't check then we may get runtime failures
// or wrong behavior from default methods that should've been stubbed in.
// TODO(kmb): Print a warning so people can start fixing their deps?
depsCollector.missingImplementedInterface(internalName, implemented);
} else {
// Class in classpath and bootclasspath is a bad idea but in any event, assume the
// bootclasspath will take precedence like in a classloader.
// We can skip code attributes as we just need to find default methods to stub.
DefaultMethodFinder finder = new DefaultMethodFinder();
bytecode.accept(finder, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG);
if (finder.foundDefaultMethods()) {
return true;
}
}
}
return false;
}
/** Returns {@code true} for non-bridge default methods not in {@link #instanceMethods}. */
private boolean shouldStubAsDefaultMethod(int access, String name, String desc) {
// Ignore private methods, which technically aren't default methods and can only be called from
// other methods defined in the interface. This also ignores lambda body methods, which is fine
// as we don't want or need to stub those. Also ignore bridge methods as javac adds them to
// concrete classes as needed anyway and we handle them separately for generated lambda classes.
// Note that an exception is that, if a bridge method is for a default interface method, javac
// will NOT generate the bridge method in the implementing class. So we need extra logic to
// handle these bridge methods.
return isNonBridgeDefaultMethod(access) && !instanceMethods.contains(name + ":" + desc);
}
private static boolean isNonBridgeDefaultMethod(int access) {
return BitFlags.noneSet(
access,
Opcodes.ACC_ABSTRACT | Opcodes.ACC_STATIC | Opcodes.ACC_BRIDGE | Opcodes.ACC_PRIVATE);
}
/**
* Check whether an interface method is a bridge method for a default interface method. This type
* of bridge methods is special, as they are not put in the implementing classes by javac.
*/
private boolean shouldStubAsBridgeDefaultMethod(int access, String name, String desc) {
return BitFlags.isSet(access, Opcodes.ACC_BRIDGE | Opcodes.ACC_PUBLIC)
&& BitFlags.noneSet(access, Opcodes.ACC_ABSTRACT | Opcodes.ACC_STATIC)
&& !instanceMethods.contains(name + ":" + desc);
}
private void stubMissingDefaultAndBridgeMethods(String implemented) {
if (bootclasspath.isKnown(implemented)) {
// Default methods on the bootclasspath will be available at runtime, so just ignore them.
return;
}
ClassReader bytecode =
checkNotNull(
classpath.readIfKnown(implemented),
"Couldn't find interface %s implemented by %s",
implemented,
internalName);
bytecode.accept(new DefaultMethodStubber(), ClassReader.SKIP_DEBUG);
}
/**
* Visitor for interfaces that produces delegates in the class visited by the outer {@link
* DefaultMethodClassFixer} for every default method encountered.
*/
private class DefaultMethodStubber extends ClassVisitor {
private String stubbedInterfaceName;
public DefaultMethodStubber() {
super(Opcodes.ASM5);
}
@Override
public void visit(
int version,
int access,
String name,
String signature,
String superName,
String[] interfaces) {
checkArgument(BitFlags.isSet(access, Opcodes.ACC_INTERFACE));
checkState(stubbedInterfaceName == null);
stubbedInterfaceName = name;
}
@Override
public MethodVisitor visitMethod(
int access, String name, String desc, String signature, String[] exceptions) {
if (shouldStubAsDefaultMethod(access, name, desc)) {
// Remember we stubbed this method in case it's also defined by subsequently visited
// interfaces. javac would force the method to be defined explicitly if there any two
// definitions conflict, but see stubMissingDefaultMethods() for how we deal with default
// methods redefined in interfaces extending another.
recordIfInstanceMethod(access, name, desc);
depsCollector.assumeCompanionClass(
internalName, InterfaceDesugaring.getCompanionClassName(stubbedInterfaceName));
// Add this method to the class we're desugaring and stub in a body to call the default
// implementation in the interface's companion class. ijar omits these methods when setting
// ACC_SYNTHETIC modifier, so don't.
// Signatures can be wrong, e.g., when type variables are introduced, instantiated, or
// refined in the class we're processing, so drop them.
MethodVisitor stubMethod =
DefaultMethodClassFixer.this.visitMethod(access, name, desc, (String) null, exceptions);
int slot = 0;
stubMethod.visitVarInsn(Opcodes.ALOAD, slot++); // load the receiver
Type neededType = Type.getMethodType(desc);
for (Type arg : neededType.getArgumentTypes()) {
stubMethod.visitVarInsn(arg.getOpcode(Opcodes.ILOAD), slot);
slot += arg.getSize();
}
stubMethod.visitMethodInsn(
Opcodes.INVOKESTATIC,
InterfaceDesugaring.getCompanionClassName(stubbedInterfaceName),
name,
InterfaceDesugaring.companionDefaultMethodDescriptor(stubbedInterfaceName, desc),
/*itf*/ false);
stubMethod.visitInsn(neededType.getReturnType().getOpcode(Opcodes.IRETURN));
stubMethod.visitMaxs(0, 0); // rely on class writer to compute these
stubMethod.visitEnd();
return null;
} else if (shouldStubAsBridgeDefaultMethod(access, name, desc)) {
recordIfInstanceMethod(access, name, desc);
// For bridges we just copy their bodies instead of going through the companion class.
// Meanwhile, we also need to desugar the copied method bodies, so that any calls to
// interface methods are correctly handled.
return new InterfaceDesugaring.InterfaceInvocationRewriter(
DefaultMethodClassFixer.this.visitMethod(access, name, desc, (String) null, exceptions),
stubbedInterfaceName,
bootclasspath,
depsCollector,
internalName);
} else {
return null; // we don't care about the actual code in these methods
}
}
}
/**
* Visitor for interfaces that recursively searches interfaces for default method declarations.
*/
private class DefaultMethodFinder extends ClassVisitor {
@SuppressWarnings("hiding")
private ImmutableList<String> interfaces;
private boolean found;
public DefaultMethodFinder() {
super(Opcodes.ASM5);
}
@Override
public void visit(
int version,
int access,
String name,
String signature,
String superName,
String[] interfaces) {
checkArgument(BitFlags.isSet(access, Opcodes.ACC_INTERFACE));
checkState(this.interfaces == null);
this.interfaces = ImmutableList.copyOf(interfaces);
}
public boolean foundDefaultMethods() {
return found;
}
@Override
public void visitEnd() {
if (!found) {
found = defaultMethodsDefined(this.interfaces);
}
}
@Override
public MethodVisitor visitMethod(
int access, String name, String desc, String signature, String[] exceptions) {
if (!found && shouldStubAsDefaultMethod(access, name, desc)) {
// Found a default method we're not ignoring (instanceMethods at this point contains methods
// the top-level visited class implements itself).
found = true;
}
return null; // we don't care about the actual code in these methods
}
}
private class InstanceMethodRecorder extends ClassVisitor {
public InstanceMethodRecorder() {
super(Opcodes.ASM5);
}
@Override
public void visit(
int version,
int access,
String name,
String signature,
String superName,
String[] interfaces) {
checkArgument(BitFlags.noneSet(access, Opcodes.ACC_INTERFACE));
super.visit(version, access, name, signature, superName, interfaces);
}
@Override
public MethodVisitor visitMethod(
int access, String name, String desc, String signature, String[] exceptions) {
recordIfInstanceMethod(access, name, desc);
return null;
}
}
/**
* Detector to determine whether an interface needs to be initialized when it is loaded.
*
* <p>If the interface has a default method, and its <clinit> initializes any of its fields, then
* this interface needs to be initialized.
*/
private static class InterfaceInitializationNecessityDetector extends ClassVisitor {
private final String internalName;
private boolean hasFieldInitializedInClinit;
private boolean hasDefaultMethods;
public InterfaceInitializationNecessityDetector(String internalName) {
super(Opcodes.ASM5);
this.internalName = internalName;
}
public boolean needsToInitialize() {
return hasDefaultMethods && hasFieldInitializedInClinit;
}
@Override
public void visit(
int version,
int access,
String name,
String signature,
String superName,
String[] interfaces) {
super.visit(version, access, name, signature, superName, interfaces);
checkState(
internalName.equals(name),
"Inconsistent internal names: expected=%s, real=%s",
internalName,
name);
checkArgument(
BitFlags.isSet(access, Opcodes.ACC_INTERFACE),
"This class visitor is only used for interfaces.");
}
@Override
public MethodVisitor visitMethod(
int access, String name, String desc, String signature, String[] exceptions) {
if (!hasDefaultMethods) {
hasDefaultMethods = isNonBridgeDefaultMethod(access);
}
if ("<clinit>".equals(name)) {
return new MethodVisitor(Opcodes.ASM5) {
@Override
public void visitFieldInsn(int opcode, String owner, String name, String desc) {
if (opcode == Opcodes.PUTSTATIC && internalName.equals(owner)) {
hasFieldInitializedInClinit = true;
}
}
};
}
return null; // Do not care about the code.
}
}
/** Comparator for interfaces that compares by whether interfaces extend one another. */
enum InterfaceComparator implements Comparator<Class<?>> {
INSTANCE;
@Override
public int compare(Class<?> o1, Class<?> o2) {
checkArgument(o1.isInterface());
checkArgument(o2.isInterface());
if (o1 == o2) {
return 0;
}
if (o1.isAssignableFrom(o2)) { // o1 is supertype of o2
return 1; // we want o1 to come after o2
}
if (o2.isAssignableFrom(o1)) { // o2 is supertype of o1
return -1; // we want o2 to come after o1
}
// o1 and o2 aren't comparable so arbitrarily impose lexicographical ordering
return o1.getName().compareTo(o2.getName());
}
}
}
| apache-2.0 |
NixaSoftware/CVis | venv/bin/libs/log/doc/html/boost/log/add_common_attributes.html | 4543 | <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function add_common_attributes</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Log v2">
<link rel="up" href="../../utilities.html#header.boost.log.utility.setup.common_attributes_hpp" title="Header <boost/log/utility/setup/common_attributes.hpp>">
<link rel="prev" href="make_attr_orde_idp28286312.html" title="Function template make_attr_ordering">
<link rel="next" href="add_console_lo_idp28294808.html" title="Function template add_console_log">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr><td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td></tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="make_attr_orde_idp28286312.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../utilities.html#header.boost.log.utility.setup.common_attributes_hpp"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="add_console_lo_idp28294808.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.log.add_common_attributes"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Function add_common_attributes</span></h2>
<p>boost::log::add_common_attributes — Simple attribute initialization routine. </p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../utilities.html#header.boost.log.utility.setup.common_attributes_hpp" title="Header <boost/log/utility/setup/common_attributes.hpp>">boost/log/utility/setup/common_attributes.hpp</a>>
</span>
<span class="keyword">void</span> <span class="identifier">add_common_attributes</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp69195736"></a><h2>Description</h2>
<p>The function adds commonly used attributes to the logging system. Specifically, the following attributes are registered globally:</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem"><p>LineID - logging records counter with value type <code class="computeroutput">unsigned int</code> </p></li>
<li class="listitem"><p>TimeStamp - local time generator with value type <code class="computeroutput">boost::posix_time::ptime</code> </p></li>
<li class="listitem"><p>ProcessID - current process identifier with value type <code class="computeroutput">attributes::current_process_id::value_type</code> </p></li>
<li class="listitem"><p>ThreadID - in multithreaded builds, current thread identifier with value type <code class="computeroutput">attributes::current_thread_id::value_type</code> </p></li>
</ul></div>
<p>
</p>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2007-2013 Andrey Semashev<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>).
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="make_attr_orde_idp28286312.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../utilities.html#header.boost.log.utility.setup.common_attributes_hpp"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="add_console_lo_idp28294808.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| apache-2.0 |
christ66/jenkins-artifactory-plugin | src/main/java/org/jfrog/hudson/util/CredentialManager.java | 3973 | /*
* Copyright (C) 2010 JFrog 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.
*/
package org.jfrog.hudson.util;
import org.apache.commons.lang.StringUtils;
import org.jfrog.hudson.ArtifactoryServer;
import org.jfrog.hudson.DeployerOverrider;
import org.jfrog.hudson.ResolverOverrider;
import org.jfrog.hudson.util.plugins.PluginsUtils;
/**
* A utility class the helps find the preferred credentials to use out of each setting and server
*
* @author Noam Y. Tenne
*/
public abstract class CredentialManager {
private CredentialManager() {
}
/**
* Decides and returns the preferred deployment credentials to use from this builder settings and selected server
*
* @param deployerOverrider Deploy-overriding capable builder
* @param server Selected Artifactory server
* @return Preferred deployment credentials
*/
public static Credentials getPreferredDeployer(DeployerOverrider deployerOverrider, ArtifactoryServer server) {
if (deployerOverrider.isOverridingDefaultDeployer()) {
String credentialsId = deployerOverrider.getDeployerCredentialsId();
return PluginsUtils.credentialsLookup(credentialsId);
}
if (server != null) {
Credentials deployerCredentials = server.getDeployerCredentials();
if (deployerCredentials != null) {
return deployerCredentials;
}
}
return new Credentials(null, null);
}
public static Credentials getPreferredDeployer(String credentialsId, ArtifactoryServer server) {
String username;
String password;
if(StringUtils.isBlank(credentialsId)) {
Credentials deployedCredentials = server.getDeployerCredentials();
username = deployedCredentials.getUsername();
password = deployedCredentials.getPassword();
}
else {
return PluginsUtils.credentialsLookup(credentialsId);
}
return new Credentials(username, password);
}
/**
* Decides and returns the preferred resolver credentials to use from this builder settings and selected server
* Override priority:
* 1) Job override resolver
* 2) Plugin manage override resolver
* 3) Plugin manage general
* @param resolverOverrider Resolve-overriding capable builder
* @param server Selected Artifactory server
* @return Preferred resolver credentials
*/
public static Credentials getPreferredResolver(ResolverOverrider resolverOverrider, ArtifactoryServer server) {
if (resolverOverrider != null && resolverOverrider.isOverridingDefaultResolver()) {
String credentialsId = resolverOverrider.getResolverCredentialsId();
return PluginsUtils.credentialsLookup(credentialsId);
}
return server.getResolvingCredentials();
}
public static Credentials getPreferredResolver(String credentialsId, ArtifactoryServer server) {
String username;
String password;
if(StringUtils.isBlank(credentialsId)) {
Credentials deployedCredentials = server.getResolvingCredentials();
username = deployedCredentials.getUsername();
password = deployedCredentials.getPassword();
}
else {
return PluginsUtils.credentialsLookup(credentialsId);
}
return new Credentials(username, password);
}
}
| apache-2.0 |
tilmannOSG/jerryscript | tests/jerry-test-suite/15/15.08/15.08.02/15.08.02.05/15.08.02.05-010.js | 653 | // Copyright 2014 Samsung Electronics Co., 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.
assert(Math.atan2(+0, -Infinity) === Math.PI);
| apache-2.0 |
awslabs/aws-sdk-cpp | aws-cpp-sdk-dms/include/aws/dms/model/StopReplicationTaskResult.h | 1986 | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/dms/DatabaseMigrationService_EXPORTS.h>
#include <aws/dms/model/ReplicationTask.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace DatabaseMigrationService
{
namespace Model
{
/**
* <p/><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/StopReplicationTaskResponse">AWS
* API Reference</a></p>
*/
class AWS_DATABASEMIGRATIONSERVICE_API StopReplicationTaskResult
{
public:
StopReplicationTaskResult();
StopReplicationTaskResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
StopReplicationTaskResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The replication task stopped.</p>
*/
inline const ReplicationTask& GetReplicationTask() const{ return m_replicationTask; }
/**
* <p>The replication task stopped.</p>
*/
inline void SetReplicationTask(const ReplicationTask& value) { m_replicationTask = value; }
/**
* <p>The replication task stopped.</p>
*/
inline void SetReplicationTask(ReplicationTask&& value) { m_replicationTask = std::move(value); }
/**
* <p>The replication task stopped.</p>
*/
inline StopReplicationTaskResult& WithReplicationTask(const ReplicationTask& value) { SetReplicationTask(value); return *this;}
/**
* <p>The replication task stopped.</p>
*/
inline StopReplicationTaskResult& WithReplicationTask(ReplicationTask&& value) { SetReplicationTask(std::move(value)); return *this;}
private:
ReplicationTask m_replicationTask;
};
} // namespace Model
} // namespace DatabaseMigrationService
} // namespace Aws
| apache-2.0 |
rahmalik/trafficserver | iocore/eventsystem/UnixEThread.cc | 9183 | /** @file
A brief file description
@section license License
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.
*/
//////////////////////////////////////////////////////////////////////
//
// The EThread Class
//
/////////////////////////////////////////////////////////////////////
#include "P_EventSystem.h"
#if HAVE_EVENTFD
#include <sys/eventfd.h>
#endif
struct AIOCallback;
#define MAX_HEARTBEATS_MISSED 10
#define NO_HEARTBEAT -1
#define THREAD_MAX_HEARTBEAT_MSECONDS 60
volatile bool shutdown_event_system = false;
EThread::EThread()
{
memset(thread_private, 0, PER_THREAD_DATA);
}
EThread::EThread(ThreadType att, int anid) : id(anid), tt(att)
{
ethreads_to_be_signalled = (EThread **)ats_malloc(MAX_EVENT_THREADS * sizeof(EThread *));
memset(ethreads_to_be_signalled, 0, MAX_EVENT_THREADS * sizeof(EThread *));
memset(thread_private, 0, PER_THREAD_DATA);
#if HAVE_EVENTFD
evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
if (evfd < 0) {
if (errno == EINVAL) { // flags invalid for kernel <= 2.6.26
evfd = eventfd(0, 0);
if (evfd < 0) {
Fatal("EThread::EThread: %d=eventfd(0,0),errno(%d)", evfd, errno);
}
} else {
Fatal("EThread::EThread: %d=eventfd(0,EFD_NONBLOCK | EFD_CLOEXEC),errno(%d)", evfd, errno);
}
}
#elif TS_USE_PORT
/* Solaris ports requires no crutches to do cross thread signaling.
* We'll just port_send the event straight over the port.
*/
#else
ink_release_assert(pipe(evpipe) >= 0);
fcntl(evpipe[0], F_SETFD, FD_CLOEXEC);
fcntl(evpipe[0], F_SETFL, O_NONBLOCK);
fcntl(evpipe[1], F_SETFD, FD_CLOEXEC);
fcntl(evpipe[1], F_SETFL, O_NONBLOCK);
#endif
}
EThread::EThread(ThreadType att, Event *e) : tt(att), start_event(e)
{
ink_assert(att == DEDICATED);
memset(thread_private, 0, PER_THREAD_DATA);
}
// Provide a destructor so that SDK functions which create and destroy
// threads won't have to deal with EThread memory deallocation.
EThread::~EThread()
{
if (n_ethreads_to_be_signalled > 0) {
flush_signals(this);
}
ats_free(ethreads_to_be_signalled);
// TODO: This can't be deleted ....
// delete[]l1_hash;
}
bool
EThread::is_event_type(EventType et)
{
return (event_types & (1 << static_cast<int>(et))) != 0;
}
void
EThread::set_event_type(EventType et)
{
event_types |= (1 << static_cast<int>(et));
}
void
EThread::process_event(Event *e, int calling_code)
{
ink_assert((!e->in_the_prot_queue && !e->in_the_priority_queue));
MUTEX_TRY_LOCK_FOR(lock, e->mutex, this, e->continuation);
if (!lock.is_locked()) {
e->timeout_at = cur_time + DELAY_FOR_RETRY;
EventQueueExternal.enqueue_local(e);
} else {
if (e->cancelled) {
free_event(e);
return;
}
Continuation *c_temp = e->continuation;
e->continuation->handleEvent(calling_code, e);
ink_assert(!e->in_the_priority_queue);
ink_assert(c_temp == e->continuation);
MUTEX_RELEASE(lock);
if (e->period) {
if (!e->in_the_prot_queue && !e->in_the_priority_queue) {
if (e->period < 0) {
e->timeout_at = e->period;
} else {
this->get_hrtime_updated();
e->timeout_at = cur_time + e->period;
if (e->timeout_at < cur_time) {
e->timeout_at = cur_time;
}
}
EventQueueExternal.enqueue_local(e);
}
} else if (!e->in_the_prot_queue && !e->in_the_priority_queue) {
free_event(e);
}
}
}
//
// void EThread::execute()
//
// Execute loops forever on:
// Find the earliest event.
// Sleep until the event time or until an earlier event is inserted
// When its time for the event, try to get the appropriate continuation
// lock. If successful, call the continuation, otherwise put the event back
// into the queue.
//
void
EThread::execute()
{
// Do the start event first.
// coverity[lock]
if (start_event) {
MUTEX_TAKE_LOCK_FOR(start_event->mutex, this, start_event->continuation);
start_event->continuation->handleEvent(EVENT_IMMEDIATE, start_event);
MUTEX_UNTAKE_LOCK(start_event->mutex, this);
free_event(start_event);
start_event = nullptr;
}
switch (tt) {
case REGULAR: {
Event *e;
Que(Event, link) NegativeQueue;
ink_hrtime next_time = 0;
// give priority to immediate events
for (;;) {
if (unlikely(shutdown_event_system == true)) {
return;
}
// execute all the available external events that have
// already been dequeued
cur_time = Thread::get_hrtime_updated();
while ((e = EventQueueExternal.dequeue_local())) {
if (e->cancelled) {
free_event(e);
} else if (!e->timeout_at) { // IMMEDIATE
ink_assert(e->period == 0);
process_event(e, e->callback_event);
} else if (e->timeout_at > 0) { // INTERVAL
EventQueue.enqueue(e, cur_time);
} else { // NEGATIVE
Event *p = nullptr;
Event *a = NegativeQueue.head;
while (a && a->timeout_at > e->timeout_at) {
p = a;
a = a->link.next;
}
if (!a) {
NegativeQueue.enqueue(e);
} else {
NegativeQueue.insert(e, p);
}
}
}
bool done_one;
do {
done_one = false;
// execute all the eligible internal events
EventQueue.check_ready(cur_time, this);
while ((e = EventQueue.dequeue_ready(cur_time))) {
ink_assert(e);
ink_assert(e->timeout_at > 0);
if (e->cancelled) {
free_event(e);
} else {
done_one = true;
process_event(e, e->callback_event);
}
}
} while (done_one);
// execute any negative (poll) events
if (NegativeQueue.head) {
if (n_ethreads_to_be_signalled) {
flush_signals(this);
}
// dequeue all the external events and put them in a local
// queue. If there are no external events available, don't
// do a cond_timedwait.
if (!INK_ATOMICLIST_EMPTY(EventQueueExternal.al)) {
EventQueueExternal.dequeue_timed(cur_time, next_time, false);
}
while ((e = EventQueueExternal.dequeue_local())) {
if (!e->timeout_at) {
process_event(e, e->callback_event);
} else {
if (e->cancelled) {
free_event(e);
} else {
// If its a negative event, it must be a result of
// a negative event, which has been turned into a
// timed-event (because of a missed lock), executed
// before the poll. So, it must
// be executed in this round (because you can't have
// more than one poll between two executions of a
// negative event)
if (e->timeout_at < 0) {
Event *p = nullptr;
Event *a = NegativeQueue.head;
while (a && a->timeout_at > e->timeout_at) {
p = a;
a = a->link.next;
}
if (!a) {
NegativeQueue.enqueue(e);
} else {
NegativeQueue.insert(e, p);
}
} else {
EventQueue.enqueue(e, cur_time);
}
}
}
}
// execute poll events
while ((e = NegativeQueue.dequeue())) {
process_event(e, EVENT_POLL);
}
if (!INK_ATOMICLIST_EMPTY(EventQueueExternal.al)) {
EventQueueExternal.dequeue_timed(cur_time, next_time, false);
}
} else { // Means there are no negative events
next_time = EventQueue.earliest_timeout();
ink_hrtime sleep_time = next_time - cur_time;
if (sleep_time > THREAD_MAX_HEARTBEAT_MSECONDS * HRTIME_MSECOND) {
next_time = cur_time + THREAD_MAX_HEARTBEAT_MSECONDS * HRTIME_MSECOND;
}
// dequeue all the external events and put them in a local
// queue. If there are no external events available, do a
// cond_timedwait.
if (n_ethreads_to_be_signalled) {
flush_signals(this);
}
EventQueueExternal.dequeue_timed(cur_time, next_time, true);
}
}
}
case DEDICATED: {
break;
}
default:
ink_assert(!"bad case value (execute)");
break;
} /* End switch */
// coverity[missing_unlock]
}
| apache-2.0 |
shakamunyi/mesos | src/log/tool/benchmark.cpp | 7142 | // 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.
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <mesos/log/log.hpp>
#include <process/clock.hpp>
#include <process/future.hpp>
#include <process/process.hpp>
#include <process/time.hpp>
#include <stout/bytes.hpp>
#include <stout/error.hpp>
#include <stout/foreach.hpp>
#include <stout/os.hpp>
#include <stout/stopwatch.hpp>
#include <stout/strings.hpp>
#include <stout/os/read.hpp>
#include "log/tool/initialize.hpp"
#include "log/tool/benchmark.hpp"
#include "logging/logging.hpp"
using namespace process;
using std::cout;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::string;
using std::vector;
using mesos::log::Log;
namespace mesos {
namespace internal {
namespace log {
namespace tool {
Benchmark::Flags::Flags()
{
add(&Flags::quorum,
"quorum",
"Quorum size");
add(&Flags::path,
"path",
"Path to the log");
add(&Flags::servers,
"servers",
"ZooKeeper servers");
add(&Flags::znode,
"znode",
"ZooKeeper znode");
add(&Flags::input,
"input",
"Path to the input trace file. Each line in the trace file\n"
"specifies the size of the append (e.g. 100B, 2MB, etc.)");
add(&Flags::output,
"output",
"Path to the output file");
add(&Flags::type,
"type",
"Type of data to be written (zero, one, random)\n"
" zero: all bits are 0\n"
" one: all bits are 1\n"
" random: all bits are randomly chosen\n",
"random");
add(&Flags::initialize,
"initialize",
"Whether to initialize the log",
true);
}
Try<Nothing> Benchmark::execute(int argc, char** argv)
{
flags.setUsageMessage(
"Usage: " + name() + " [options]\n"
"\n"
"This command is used to do performance test on the\n"
"replicated log. It takes a trace file of write sizes\n"
"and replay that trace to measure the latency of each\n"
"write. The data to be written for each write can be\n"
"specified using the --type flag.\n"
"\n");
// Configure the tool by parsing command line arguments.
if (argc > 0 && argv != nullptr) {
Try<flags::Warnings> load = flags.load(None(), argc, argv);
if (load.isError()) {
return Error(flags.usage(load.error()));
}
if (flags.help) {
return Error(flags.usage());
}
process::initialize();
logging::initialize(argv[0], false, flags);
// Log any flag warnings (after logging is initialized).
foreach (const flags::Warning& warning, load->warnings) {
LOG(WARNING) << warning.message;
}
}
if (flags.quorum.isNone()) {
return Error(flags.usage("Missing required option --quorum"));
}
if (flags.path.isNone()) {
return Error(flags.usage("Missing required option --path"));
}
if (flags.servers.isNone()) {
return Error(flags.usage("Missing required option --servers"));
}
if (flags.znode.isNone()) {
return Error(flags.usage("Missing required option --znode"));
}
if (flags.input.isNone()) {
return Error(flags.usage("Missing required option --input"));
}
if (flags.output.isNone()) {
return Error(flags.usage("Missing required option --output"));
}
// Initialize the log.
if (flags.initialize) {
Initialize initialize;
initialize.flags.path = flags.path;
Try<Nothing> execution = initialize.execute();
if (execution.isError()) {
return Error(execution.error());
}
}
// Create the log.
Log log(
flags.quorum.get(),
flags.path.get(),
flags.servers.get(),
Seconds(10),
flags.znode.get());
// Create the log writer.
Log::Writer writer(&log);
Future<Option<Log::Position>> position = writer.start();
if (!position.await(Seconds(15))) {
return Error("Failed to start a log writer: timed out");
} else if (!position.isReady()) {
return Error("Failed to start a log writer: " +
(position.isFailed()
? position.failure()
: "Discarded future"));
}
// Statistics to output.
vector<Bytes> sizes;
vector<Duration> durations;
vector<Time> timestamps;
// Read sizes from the input trace file.
ifstream input(flags.input.get().c_str());
if (!input.is_open()) {
return Error("Failed to open the trace file " + flags.input.get());
}
string line;
while (getline(input, line)) {
Try<Bytes> size = Bytes::parse(strings::trim(line));
if (size.isError()) {
return Error("Failed to parse the trace file: " + size.error());
}
sizes.push_back(size.get());
}
input.close();
// Generate the data to be written.
vector<string> data;
for (size_t i = 0; i < sizes.size(); i++) {
if (flags.type == "one") {
data.push_back(string(sizes[i].bytes(), static_cast<char>(0xff)));
} else if (flags.type == "random") {
data.push_back(string(sizes[i].bytes(), os::random() % 256));
} else {
data.push_back(string(sizes[i].bytes(), 0));
}
}
Stopwatch stopwatch;
stopwatch.start();
for (size_t i = 0; i < sizes.size(); i++) {
Stopwatch stopwatch;
stopwatch.start();
position = writer.append(data[i]);
if (!position.await(Seconds(10))) {
return Error("Failed to append: timed out");
} else if (!position.isReady()) {
return Error("Failed to append: " +
(position.isFailed()
? position.failure()
: "Discarded future"));
} else if (position.get().isNone()) {
return Error("Failed to append: exclusive write promise lost");
}
durations.push_back(stopwatch.elapsed());
timestamps.push_back(Clock::now());
}
cout << "Total number of appends: " << sizes.size() << endl;
cout << "Total time used: " << stopwatch.elapsed() << endl;
// Ouput statistics.
ofstream output(flags.output.get().c_str());
if (!output.is_open()) {
return Error("Failed to open the output file " + flags.output.get());
}
for (size_t i = 0; i < sizes.size(); i++) {
output << timestamps[i]
<< " Appended " << sizes[i].bytes() << " bytes"
<< " in " << durations[i].ms() << " ms" << endl;
}
return Nothing();
}
} // namespace tool {
} // namespace log {
} // namespace internal {
} // namespace mesos {
| apache-2.0 |
SiddharthChatrolaMs/azure-sdk-for-net | src/SDKs/Automation/Management.Automation/Generated/Models/ConnectionTypeAssociationProperty.cs | 1705 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Automation.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Automation;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// The connection type property associated with the entity.
/// </summary>
public partial class ConnectionTypeAssociationProperty
{
/// <summary>
/// Initializes a new instance of the ConnectionTypeAssociationProperty
/// class.
/// </summary>
public ConnectionTypeAssociationProperty()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ConnectionTypeAssociationProperty
/// class.
/// </summary>
/// <param name="name">Gets or sets the name of the connection
/// type.</param>
public ConnectionTypeAssociationProperty(string name = default(string))
{
Name = name;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the name of the connection type.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
}
}
| apache-2.0 |
dkhwangbo/druid | processing/src/test/java/org/apache/druid/query/groupby/epinephelinae/BufferArrayGrouperTest.java | 3937 | /*
* 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.druid.query.groupby.epinephelinae;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.primitives.Ints;
import org.apache.druid.common.config.NullHandling;
import org.apache.druid.data.input.MapBasedRow;
import org.apache.druid.query.aggregation.AggregatorFactory;
import org.apache.druid.query.aggregation.CountAggregatorFactory;
import org.apache.druid.query.aggregation.LongSumAggregatorFactory;
import org.apache.druid.query.groupby.epinephelinae.Grouper.Entry;
import org.junit.Assert;
import org.junit.Test;
import java.nio.ByteBuffer;
import java.util.Comparator;
import java.util.List;
public class BufferArrayGrouperTest
{
@Test
public void testAggregate()
{
final TestColumnSelectorFactory columnSelectorFactory = GrouperTestUtil.newColumnSelectorFactory();
final IntGrouper grouper = newGrouper(columnSelectorFactory, 1024);
columnSelectorFactory.setRow(new MapBasedRow(0, ImmutableMap.of("value", 10L)));
grouper.aggregate(12);
grouper.aggregate(6);
grouper.aggregate(10);
grouper.aggregate(6);
grouper.aggregate(12);
grouper.aggregate(6);
final List<Entry<Integer>> expected = ImmutableList.of(
new Grouper.Entry<>(6, new Object[]{30L, 3L}),
new Grouper.Entry<>(10, new Object[]{10L, 1L}),
new Grouper.Entry<>(12, new Object[]{20L, 2L})
);
final List<Entry<Integer>> unsortedEntries = Lists.newArrayList(grouper.iterator(false));
Assert.assertEquals(
expected,
Ordering.from((Comparator<Entry<Integer>>) (o1, o2) -> Ints.compare(o1.getKey(), o2.getKey()))
.sortedCopy(unsortedEntries)
);
}
private BufferArrayGrouper newGrouper(
TestColumnSelectorFactory columnSelectorFactory,
int bufferSize
)
{
final ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
final BufferArrayGrouper grouper = new BufferArrayGrouper(
Suppliers.ofInstance(buffer),
columnSelectorFactory,
new AggregatorFactory[]{
new LongSumAggregatorFactory("valueSum", "value"),
new CountAggregatorFactory("count")
},
1000
);
grouper.init();
return grouper;
}
@Test
public void testRequiredBufferCapacity()
{
int[] cardinalityArray = new int[]{1, 10, Integer.MAX_VALUE - 1};
AggregatorFactory[] aggregatorFactories = new AggregatorFactory[]{
new LongSumAggregatorFactory("sum", "sum")
};
long[] requiredSizes;
if (NullHandling.sqlCompatible()) {
// We need additional size to store nullability information.
requiredSizes = new long[]{19, 101, 19058917368L};
} else {
requiredSizes = new long[]{17, 90, 16911433721L};
}
for (int i = 0; i < cardinalityArray.length; i++) {
Assert.assertEquals(requiredSizes[i], BufferArrayGrouper.requiredBufferCapacity(
cardinalityArray[i],
aggregatorFactories
));
}
}
}
| apache-2.0 |
cosmoharrigan/rl-viz | projects/rlVizLibJava/src/rlVizLib/visualization/AgentOnValueFunctionVizComponent.java | 3132 | /*
Copyright 2007 Brian Tanner
[email protected]
http://brian.tannerpages.com
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 rlVizLib.visualization;
import java.util.Observable;
import rlVizLib.visualization.interfaces.AgentOnValueFunctionDataProvider;
import rlVizLib.utilities.UtilityShop;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.util.Observer;
import org.rlcommunity.rlglue.codec.types.Reward_observation_action_terminal;
import rlVizLib.general.TinyGlue;
import rlVizLib.visualization.interfaces.GlueStateProvider;
public class AgentOnValueFunctionVizComponent implements SelfUpdatingVizComponent, Observer {
private VizComponentChangeListener theChangeListener;
private AgentOnValueFunctionDataProvider dataProvider;
private boolean enabled = true;
public AgentOnValueFunctionVizComponent(AgentOnValueFunctionDataProvider dataProvider, TinyGlue theGlueState) {
this.dataProvider = dataProvider;
theGlueState.addObserver(this);
}
public void setEnabled(boolean newEnableValue) {
if (newEnableValue == false && this.enabled) {
disable();
}
if (newEnableValue == true && !this.enabled) {
enable();
}
}
private void disable() {
enabled = false;
theChangeListener.vizComponentChanged(this);
}
private void enable() {
enabled = true;
}
public void render(Graphics2D g) {
if (!enabled) {
Color myClearColor = new Color(0.0f, 0.0f, 0.0f, 0.0f);
g.setColor(myClearColor);
g.setBackground(myClearColor);
g.clearRect(0, 0, 1, 1);
return;
}
dataProvider.updateAgentState();
g.setColor(Color.BLUE);
double transX = UtilityShop.normalizeValue(dataProvider.getCurrentStateInDimension(0),
dataProvider.getMinValueForDim(0),
dataProvider.getMaxValueForDim(0));
double transY = UtilityShop.normalizeValue(dataProvider.getCurrentStateInDimension(1),
dataProvider.getMinValueForDim(1),
dataProvider.getMaxValueForDim(1));
Rectangle2D agentRect = new Rectangle2D.Double(transX-.01, transY-.01, .02, .02);
g.fill(agentRect);
}
public void setVizComponentChangeListener(VizComponentChangeListener theChangeListener) {
this.theChangeListener = theChangeListener;
}
public void update(Observable o, Object theEvent) {
if (theChangeListener != null) {
theChangeListener.vizComponentChanged(this);
}
}
}
| apache-2.0 |
tascape/th-junit4 | src/main/java/junit/runner/Version.java | 279 | package junit.runner;
/**
* This class defines the current version of JUnit
*/
public class Version {
private Version() {
// don't instantiate
}
public static String id() {
return "4.12";
}
public static void main(String[] args) {
System.out.println(id());
}
}
| apache-2.0 |
arostm/mbed-os | drivers/BusInOut.h | 4420 | /* mbed Microcontroller Library
* Copyright (c) 2006-2013 ARM Limited
*
* 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.
*/
#ifndef MBED_BUSINOUT_H
#define MBED_BUSINOUT_H
#include "drivers/DigitalInOut.h"
#include "platform/PlatformMutex.h"
namespace mbed {
/** \addtogroup drivers */
/** A digital input output bus, used for setting the state of a collection of pins
*
* @note Synchronization level: Thread safe
* @ingroup drivers
*/
class BusInOut {
public:
/** Create an BusInOut, connected to the specified pins
*
* @param p0 DigitalInOut pin to connect to bus bit
* @param p1 DigitalInOut pin to connect to bus bit
* @param p2 DigitalInOut pin to connect to bus bit
* @param p3 DigitalInOut pin to connect to bus bit
* @param p4 DigitalInOut pin to connect to bus bit
* @param p5 DigitalInOut pin to connect to bus bit
* @param p6 DigitalInOut pin to connect to bus bit
* @param p7 DigitalInOut pin to connect to bus bit
* @param p8 DigitalInOut pin to connect to bus bit
* @param p9 DigitalInOut pin to connect to bus bit
* @param p10 DigitalInOut pin to connect to bus bit
* @param p11 DigitalInOut pin to connect to bus bit
* @param p12 DigitalInOut pin to connect to bus bit
* @param p13 DigitalInOut pin to connect to bus bit
* @param p14 DigitalInOut pin to connect to bus bit
* @param p15 DigitalInOut pin to connect to bus bit
*
* @note
* It is only required to specify as many pin variables as is required
* for the bus; the rest will default to NC (not connected)
*/
BusInOut(PinName p0, PinName p1 = NC, PinName p2 = NC, PinName p3 = NC,
PinName p4 = NC, PinName p5 = NC, PinName p6 = NC, PinName p7 = NC,
PinName p8 = NC, PinName p9 = NC, PinName p10 = NC, PinName p11 = NC,
PinName p12 = NC, PinName p13 = NC, PinName p14 = NC, PinName p15 = NC);
/** Create an BusInOut, connected to the specified pins
*
* @param pins An array of pins to construct a BusInOut from
*/
BusInOut(PinName pins[16]);
virtual ~BusInOut();
/* Group: Access Methods */
/** Write the value to the output bus
*
* @param value An integer specifying a bit to write for every corresponding DigitalInOut pin
*/
void write(int value);
/** Read the value currently output on the bus
*
* @returns
* An integer with each bit corresponding to associated DigitalInOut pin setting
*/
int read();
/** Set as an output
*/
void output();
/** Set as an input
*/
void input();
/** Set the input pin mode
*
* @param pull PullUp, PullDown, PullNone
*/
void mode(PinMode pull);
/** Binary mask of bus pins connected to actual pins (not NC pins)
* If bus pin is in NC state make corresponding bit will be cleared (set to 0), else bit will be set to 1
*
* @returns
* Binary mask of connected pins
*/
int mask() {
// No lock needed since _nc_mask is not modified outside the constructor
return _nc_mask;
}
/** A shorthand for write()
*/
BusInOut& operator= (int v);
BusInOut& operator= (BusInOut& rhs);
/** Access to particular bit in random-iterator fashion
*/
DigitalInOut& operator[] (int index);
/** A shorthand for read()
*/
operator int();
protected:
virtual void lock();
virtual void unlock();
DigitalInOut* _pin[16];
/* Mask of bus's NC pins
* If bit[n] is set to 1 - pin is connected
* if bit[n] is cleared - pin is not connected (NC)
*/
int _nc_mask;
PlatformMutex _mutex;
/* disallow copy constructor and assignment operators */
private:
BusInOut(const BusInOut&);
BusInOut & operator = (const BusInOut&);
};
} // namespace mbed
#endif
| apache-2.0 |
jt70471/aws-sdk-cpp | aws-cpp-sdk-importexport/source/model/GetStatusResult.cpp | 5140 | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/importexport/model/GetStatusResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <utility>
using namespace Aws::ImportExport::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::Logging;
using namespace Aws::Utils;
using namespace Aws;
GetStatusResult::GetStatusResult() :
m_jobType(JobType::NOT_SET),
m_errorCount(0)
{
}
GetStatusResult::GetStatusResult(const Aws::AmazonWebServiceResult<XmlDocument>& result) :
m_jobType(JobType::NOT_SET),
m_errorCount(0)
{
*this = result;
}
GetStatusResult& GetStatusResult::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
const XmlDocument& xmlDocument = result.GetPayload();
XmlNode rootNode = xmlDocument.GetRootElement();
XmlNode resultNode = rootNode;
if (!rootNode.IsNull() && (rootNode.GetName() != "GetStatusResult"))
{
resultNode = rootNode.FirstChild("GetStatusResult");
}
if(!resultNode.IsNull())
{
XmlNode jobIdNode = resultNode.FirstChild("JobId");
if(!jobIdNode.IsNull())
{
m_jobId = Aws::Utils::Xml::DecodeEscapedXmlText(jobIdNode.GetText());
}
XmlNode jobTypeNode = resultNode.FirstChild("JobType");
if(!jobTypeNode.IsNull())
{
m_jobType = JobTypeMapper::GetJobTypeForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(jobTypeNode.GetText()).c_str()).c_str());
}
XmlNode locationCodeNode = resultNode.FirstChild("LocationCode");
if(!locationCodeNode.IsNull())
{
m_locationCode = Aws::Utils::Xml::DecodeEscapedXmlText(locationCodeNode.GetText());
}
XmlNode locationMessageNode = resultNode.FirstChild("LocationMessage");
if(!locationMessageNode.IsNull())
{
m_locationMessage = Aws::Utils::Xml::DecodeEscapedXmlText(locationMessageNode.GetText());
}
XmlNode progressCodeNode = resultNode.FirstChild("ProgressCode");
if(!progressCodeNode.IsNull())
{
m_progressCode = Aws::Utils::Xml::DecodeEscapedXmlText(progressCodeNode.GetText());
}
XmlNode progressMessageNode = resultNode.FirstChild("ProgressMessage");
if(!progressMessageNode.IsNull())
{
m_progressMessage = Aws::Utils::Xml::DecodeEscapedXmlText(progressMessageNode.GetText());
}
XmlNode carrierNode = resultNode.FirstChild("Carrier");
if(!carrierNode.IsNull())
{
m_carrier = Aws::Utils::Xml::DecodeEscapedXmlText(carrierNode.GetText());
}
XmlNode trackingNumberNode = resultNode.FirstChild("TrackingNumber");
if(!trackingNumberNode.IsNull())
{
m_trackingNumber = Aws::Utils::Xml::DecodeEscapedXmlText(trackingNumberNode.GetText());
}
XmlNode logBucketNode = resultNode.FirstChild("LogBucket");
if(!logBucketNode.IsNull())
{
m_logBucket = Aws::Utils::Xml::DecodeEscapedXmlText(logBucketNode.GetText());
}
XmlNode logKeyNode = resultNode.FirstChild("LogKey");
if(!logKeyNode.IsNull())
{
m_logKey = Aws::Utils::Xml::DecodeEscapedXmlText(logKeyNode.GetText());
}
XmlNode errorCountNode = resultNode.FirstChild("ErrorCount");
if(!errorCountNode.IsNull())
{
m_errorCount = StringUtils::ConvertToInt32(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(errorCountNode.GetText()).c_str()).c_str());
}
XmlNode signatureNode = resultNode.FirstChild("Signature");
if(!signatureNode.IsNull())
{
m_signature = Aws::Utils::Xml::DecodeEscapedXmlText(signatureNode.GetText());
}
XmlNode signatureFileContentsNode = resultNode.FirstChild("SignatureFileContents");
if(!signatureFileContentsNode.IsNull())
{
m_signatureFileContents = Aws::Utils::Xml::DecodeEscapedXmlText(signatureFileContentsNode.GetText());
}
XmlNode currentManifestNode = resultNode.FirstChild("CurrentManifest");
if(!currentManifestNode.IsNull())
{
m_currentManifest = Aws::Utils::Xml::DecodeEscapedXmlText(currentManifestNode.GetText());
}
XmlNode creationDateNode = resultNode.FirstChild("CreationDate");
if(!creationDateNode.IsNull())
{
m_creationDate = DateTime(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(creationDateNode.GetText()).c_str()).c_str(), DateFormat::ISO_8601);
}
XmlNode artifactListNode = resultNode.FirstChild("ArtifactList");
if(!artifactListNode.IsNull())
{
XmlNode artifactListMember = artifactListNode.FirstChild("member");
while(!artifactListMember.IsNull())
{
m_artifactList.push_back(artifactListMember);
artifactListMember = artifactListMember.NextNode("member");
}
}
}
if (!rootNode.IsNull()) {
XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata");
m_responseMetadata = responseMetadataNode;
AWS_LOGSTREAM_DEBUG("Aws::ImportExport::Model::GetStatusResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() );
}
return *this;
}
| apache-2.0 |
jt70471/aws-sdk-cpp | aws-cpp-sdk-ebs/include/aws/ebs/model/ValidationException.h | 3057 | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/ebs/EBS_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/ebs/model/ValidationExceptionReason.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace EBS
{
namespace Model
{
/**
* <p>The input fails to satisfy the constraints of the EBS direct
* APIs.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/ebs-2019-11-02/ValidationException">AWS
* API Reference</a></p>
*/
class AWS_EBS_API ValidationException
{
public:
ValidationException();
ValidationException(Aws::Utils::Json::JsonView jsonValue);
ValidationException& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
inline const Aws::String& GetMessage() const{ return m_message; }
inline bool MessageHasBeenSet() const { return m_messageHasBeenSet; }
inline void SetMessage(const Aws::String& value) { m_messageHasBeenSet = true; m_message = value; }
inline void SetMessage(Aws::String&& value) { m_messageHasBeenSet = true; m_message = std::move(value); }
inline void SetMessage(const char* value) { m_messageHasBeenSet = true; m_message.assign(value); }
inline ValidationException& WithMessage(const Aws::String& value) { SetMessage(value); return *this;}
inline ValidationException& WithMessage(Aws::String&& value) { SetMessage(std::move(value)); return *this;}
inline ValidationException& WithMessage(const char* value) { SetMessage(value); return *this;}
/**
* <p>The reason for the validation exception.</p>
*/
inline const ValidationExceptionReason& GetReason() const{ return m_reason; }
/**
* <p>The reason for the validation exception.</p>
*/
inline bool ReasonHasBeenSet() const { return m_reasonHasBeenSet; }
/**
* <p>The reason for the validation exception.</p>
*/
inline void SetReason(const ValidationExceptionReason& value) { m_reasonHasBeenSet = true; m_reason = value; }
/**
* <p>The reason for the validation exception.</p>
*/
inline void SetReason(ValidationExceptionReason&& value) { m_reasonHasBeenSet = true; m_reason = std::move(value); }
/**
* <p>The reason for the validation exception.</p>
*/
inline ValidationException& WithReason(const ValidationExceptionReason& value) { SetReason(value); return *this;}
/**
* <p>The reason for the validation exception.</p>
*/
inline ValidationException& WithReason(ValidationExceptionReason&& value) { SetReason(std::move(value)); return *this;}
private:
Aws::String m_message;
bool m_messageHasBeenSet;
ValidationExceptionReason m_reason;
bool m_reasonHasBeenSet;
};
} // namespace Model
} // namespace EBS
} // namespace Aws
| apache-2.0 |
rafd123/aws-sdk-net | sdk/src/Services/S3/Custom/Model/Internal/MarshallTransformations/PutACLRequestMarshaller.cs | 8804 | /*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System.IO;
using System.Xml;
using System.Text;
using Amazon.S3.Util;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using System.Globalization;
using Amazon.Util;
#pragma warning disable 1591
namespace Amazon.S3.Model.Internal.MarshallTransformations
{
/// <summary>
/// Put Object Acl Request Marshaller
/// </summary>
public class PutACLRequestMarshaller : IMarshaller<IRequest, PutACLRequest> ,IMarshaller<IRequest,Amazon.Runtime.AmazonWebServiceRequest>
{
public IRequest Marshall(Amazon.Runtime.AmazonWebServiceRequest input)
{
return this.Marshall((PutACLRequest)input);
}
public IRequest Marshall(PutACLRequest putObjectAclRequest)
{
IRequest request = new DefaultRequest(putObjectAclRequest, "AmazonS3");
request.HttpMethod = "PUT";
if (putObjectAclRequest.IsSetCannedACL())
request.Headers.Add(HeaderKeys.XAmzAclHeader, S3Transforms.ToStringValue(putObjectAclRequest.CannedACL));
// if we are putting the acl onto the bucket, the keyname component will collapse to empty string
request.ResourcePath = string.Format(CultureInfo.InvariantCulture, "/{0}/{1}",
S3Transforms.ToStringValue(putObjectAclRequest.BucketName),
S3Transforms.ToStringValue(putObjectAclRequest.Key));
request.AddSubResource("acl");
if (putObjectAclRequest.IsSetVersionId())
request.AddSubResource("versionId", S3Transforms.ToStringValue(putObjectAclRequest.VersionId));
var stringWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
using (
var xmlWriter = XmlWriter.Create(stringWriter,
new XmlWriterSettings()
{
Encoding = Encoding.UTF8,
OmitXmlDeclaration = true
}))
{
var accessControlPolicyAccessControlPolicy = putObjectAclRequest.AccessControlList;
if (accessControlPolicyAccessControlPolicy != null)
{
xmlWriter.WriteStartElement("AccessControlPolicy", "");
var accessControlPolicyAccessControlPolicygrantsList = accessControlPolicyAccessControlPolicy.Grants;
if (accessControlPolicyAccessControlPolicygrantsList != null &&
accessControlPolicyAccessControlPolicygrantsList.Count > 0)
{
xmlWriter.WriteStartElement("AccessControlList", "");
foreach (
var accessControlPolicyAccessControlPolicygrantsListValue in
accessControlPolicyAccessControlPolicygrantsList)
{
xmlWriter.WriteStartElement("Grant", "");
if (accessControlPolicyAccessControlPolicygrantsListValue != null)
{
var granteeGrantee = accessControlPolicyAccessControlPolicygrantsListValue.Grantee;
if (granteeGrantee != null)
{
xmlWriter.WriteStartElement("Grantee", "");
if (granteeGrantee.IsSetType())
{
xmlWriter.WriteAttributeString("xsi", "type",
"http://www.w3.org/2001/XMLSchema-instance",
granteeGrantee.Type.ToString());
}
if (granteeGrantee.IsSetDisplayName())
{
xmlWriter.WriteElementString("DisplayName", "",
S3Transforms.ToXmlStringValue(
granteeGrantee.DisplayName));
}
if (granteeGrantee.IsSetEmailAddress())
{
xmlWriter.WriteElementString("EmailAddress", "",
S3Transforms.ToXmlStringValue(
granteeGrantee.EmailAddress));
}
if (granteeGrantee.IsSetCanonicalUser())
{
xmlWriter.WriteElementString("ID", "",
S3Transforms.ToXmlStringValue(
granteeGrantee.CanonicalUser));
}
if (granteeGrantee.IsSetURI())
{
xmlWriter.WriteElementString("URI", "",
S3Transforms.ToXmlStringValue(
granteeGrantee.URI));
}
xmlWriter.WriteEndElement();
}
if (accessControlPolicyAccessControlPolicygrantsListValue.IsSetPermission())
{
xmlWriter.WriteElementString("Permission", "",
S3Transforms.ToXmlStringValue(
accessControlPolicyAccessControlPolicygrantsListValue
.Permission));
}
}
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
var ownerOwner = accessControlPolicyAccessControlPolicy.Owner;
if (ownerOwner != null)
{
xmlWriter.WriteStartElement("Owner", "");
if (ownerOwner.IsSetDisplayName())
{
xmlWriter.WriteElementString("DisplayName", "",
S3Transforms.ToXmlStringValue(ownerOwner.DisplayName));
}
if (ownerOwner.IsSetId())
{
xmlWriter.WriteElementString("ID", "", S3Transforms.ToXmlStringValue(ownerOwner.Id));
}
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
}
try
{
var content = stringWriter.ToString();
request.Content = Encoding.UTF8.GetBytes(content);
request.Headers[HeaderKeys.ContentTypeHeader] = "application/xml";
string checksum = AmazonS3Util.GenerateChecksumForContent(content, true);
request.Headers[HeaderKeys.ContentMD5Header] = checksum;
}
catch (EncoderFallbackException e)
{
throw new AmazonServiceException("Unable to marshall request to XML", e);
}
return request;
}
}
}
| apache-2.0 |
nat2013/netty | codec-http2/src/main/java/io/netty/handler/codec/http2/Http2Connection.java | 10653 | /*
* Copyright 2014 The Netty Project
*
* The Netty Project 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 io.netty.handler.codec.http2;
import java.util.Collection;
/**
* Manager for the state of an HTTP/2 connection with the remote end-point.
*/
public interface Http2Connection {
/**
* Listener for life-cycle events for streams in this connection.
*/
interface Listener {
/**
* Notifies the listener that the given stream was added to the connection. This stream may
* not yet be active (i.e. open/half-closed).
*/
void streamAdded(Http2Stream stream);
/**
* Notifies the listener that the given stream was made active (i.e. open in at least one
* direction).
*/
void streamActive(Http2Stream stream);
/**
* Notifies the listener that the given stream is now half-closed. The stream can be
* inspected to determine which side is closed.
*/
void streamHalfClosed(Http2Stream stream);
/**
* Notifies the listener that the given stream is now closed in both directions.
*/
void streamInactive(Http2Stream stream);
/**
* Notifies the listener that the given stream has now been removed from the connection and
* will no longer be returned via {@link Http2Connection#stream(int)}. The connection may
* maintain inactive streams for some time before removing them.
*/
void streamRemoved(Http2Stream stream);
/**
* Notifies the listener that a priority tree parent change has occurred. This method will be invoked
* in a top down order relative to the priority tree. This method will also be invoked after all tree
* structure changes have been made and the tree is in steady state relative to the priority change
* which caused the tree structure to change.
* @param stream The stream which had a parent change (new parent and children will be steady state)
* @param oldParent The old parent which {@code stream} used to be a child of (may be {@code null})
*/
void priorityTreeParentChanged(Http2Stream stream, Http2Stream oldParent);
/**
* Notifies the listener that a parent dependency is about to change
* This is called while the tree is being restructured and so the tree
* structure is not necessarily steady state.
* @param stream The stream which the parent is about to change to {@code newParent}
* @param newParent The stream which will be the parent of {@code stream}
*/
void priorityTreeParentChanging(Http2Stream stream, Http2Stream newParent);
/**
* Notifies the listener that the weight has changed for {@code stream}
* @param stream The stream which the weight has changed
* @param oldWeight The old weight for {@code stream}
*/
void onWeightChanged(Http2Stream stream, short oldWeight);
/**
* Called when a GO_AWAY frame has either been sent or received for the connection.
*/
void goingAway();
}
/**
* A view of the connection from one endpoint (local or remote).
*/
interface Endpoint<F extends Http2FlowController> {
/**
* Returns the next valid streamId for this endpoint. If negative, the stream IDs are
* exhausted for this endpoint an no further streams may be created.
*/
int nextStreamId();
/**
* Indicates whether the given streamId is from the set of IDs used by this endpoint to
* create new streams.
*/
boolean createdStreamId(int streamId);
/**
* Indicates whether or not this endpoint is currently accepting new streams. This will be
* be false if {@link #numActiveStreams()} + 1 >= {@link #maxStreams()} or if the stream IDs
* for this endpoint have been exhausted (i.e. {@link #nextStreamId()} < 0).
*/
boolean acceptingNewStreams();
/**
* Creates a stream initiated by this endpoint. This could fail for the following reasons:
* <ul>
* <li>The requested stream ID is not the next sequential ID for this endpoint.</li>
* <li>The stream already exists.</li>
* <li>The number of concurrent streams is above the allowed threshold for this endpoint.</li>
* <li>The connection is marked as going away.</li>
* </ul>
* <p>
* The caller is expected to {@link Http2Stream#open()} the stream.
* @param streamId The ID of the stream
* @see Http2Stream#open()
* @see Http2Stream#open(boolean)
*/
Http2Stream createStream(int streamId) throws Http2Exception;
/**
* Creates a push stream in the reserved state for this endpoint and notifies all listeners.
* This could fail for the following reasons:
* <ul>
* <li>Server push is not allowed to the opposite endpoint.</li>
* <li>The requested stream ID is not the next sequential stream ID for this endpoint.</li>
* <li>The number of concurrent streams is above the allowed threshold for this endpoint.</li>
* <li>The connection is marked as going away.</li>
* <li>The parent stream ID does not exist or is not open from the side sending the push
* promise.</li>
* <li>Could not set a valid priority for the new stream.</li>
* </ul>
*
* @param streamId the ID of the push stream
* @param parent the parent stream used to initiate the push stream.
*/
Http2Stream reservePushStream(int streamId, Http2Stream parent) throws Http2Exception;
/**
* Indicates whether or not this endpoint is the server-side of the connection.
*/
boolean isServer();
/**
* Sets whether server push is allowed to this endpoint.
*/
void allowPushTo(boolean allow);
/**
* Gets whether or not server push is allowed to this endpoint. This is always false
* for a server endpoint.
*/
boolean allowPushTo();
/**
* Gets the number of currently active streams that were created by this endpoint.
*/
int numActiveStreams();
/**
* Gets the maximum number of concurrent streams allowed by this endpoint.
*/
int maxStreams();
/**
* Sets the maximum number of concurrent streams allowed by this endpoint.
*/
void maxStreams(int maxStreams);
/**
* Gets the ID of the stream last successfully created by this endpoint.
*/
int lastStreamCreated();
/**
* Gets the last stream created by this endpoint that is "known" by the opposite endpoint.
* If a GOAWAY was received for this endpoint, this will be the last stream ID from the
* GOAWAY frame. Otherwise, this will be same as {@link #lastStreamCreated()}.
*/
int lastKnownStream();
/**
* Gets the flow controller for this endpoint.
*/
F flowController();
/**
* Sets the flow controller for this endpoint.
*/
void flowController(F flowController);
/**
* Gets the {@link Endpoint} opposite this one.
*/
Endpoint<? extends Http2FlowController> opposite();
}
/**
* Adds a listener of stream life-cycle events. Adding the same listener multiple times has no effect.
*/
void addListener(Listener listener);
/**
* Removes a listener of stream life-cycle events.
*/
void removeListener(Listener listener);
/**
* Attempts to get the stream for the given ID. If it doesn't exist, throws.
*/
Http2Stream requireStream(int streamId) throws Http2Exception;
/**
* Gets the stream if it exists. If not, returns {@code null}.
*/
Http2Stream stream(int streamId);
/**
* Gets the stream object representing the connection, itself (i.e. stream zero). This object
* always exists.
*/
Http2Stream connectionStream();
/**
* Gets the number of streams that are currently either open or half-closed.
*/
int numActiveStreams();
/**
* Gets all streams that are currently either open or half-closed. The returned collection is
* sorted by priority.
*/
Collection<Http2Stream> activeStreams();
/**
* Indicates whether or not the local endpoint for this connection is the server.
*/
boolean isServer();
/**
* Gets a view of this connection from the local {@link Endpoint}.
*/
Endpoint<Http2LocalFlowController> local();
/**
* Creates a new stream initiated by the local endpoint
* @see Endpoint#createStream(int)
*/
Http2Stream createLocalStream(int streamId) throws Http2Exception;
/**
* Gets a view of this connection from the remote {@link Endpoint}.
*/
Endpoint<Http2RemoteFlowController> remote();
/**
* Creates a new stream initiated by the remote endpoint.
* @see Endpoint#createStream(int)
*/
Http2Stream createRemoteStream(int streamId) throws Http2Exception;
/**
* Indicates whether or not a {@code GOAWAY} was received from the remote endpoint.
*/
boolean goAwayReceived();
/**
* Indicates that a {@code GOAWAY} was received from the remote endpoint and sets the last known stream.
*/
void goAwayReceived(int lastKnownStream);
/**
* Indicates whether or not a {@code GOAWAY} was sent to the remote endpoint.
*/
boolean goAwaySent();
/**
* Indicates that a {@code GOAWAY} was sent to the remote endpoint and sets the last known stream.
*/
void goAwaySent(int lastKnownStream);
/**
* Indicates whether or not either endpoint has received a GOAWAY.
*/
boolean isGoAway();
}
| apache-2.0 |
diorcety/intellij-community | platform/util/src/com/intellij/util/io/IOUtil.java | 7277 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* 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.intellij.util.io;
import com.intellij.openapi.util.ThreadLocalCachedValue;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.util.SystemProperties;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.io.*;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
public class IOUtil {
public static final boolean ourByteBuffersUseNativeByteOrder = SystemProperties.getBooleanProperty("idea.bytebuffers.use.native.byte.order", true);
private static final int STRING_HEADER_SIZE = 1;
private static final int STRING_LENGTH_THRESHOLD = 255;
@NonNls private static final String LONGER_THAN_64K_MARKER = "LONGER_THAN_64K";
private IOUtil() {}
public static String readString(@NotNull DataInput stream) throws IOException {
int length = stream.readInt();
if (length == -1) return null;
if (length == 0) return "";
byte[] bytes = new byte[length*2];
stream.readFully(bytes);
return new String(bytes, 0, length*2, CharsetToolkit.UTF_16BE_CHARSET);
}
public static void writeString(String s, @NotNull DataOutput stream) throws IOException {
if (s == null) {
stream.writeInt(-1);
return;
}
stream.writeInt(s.length());
if (s.isEmpty()) {
return;
}
char[] chars = s.toCharArray();
byte[] bytes = new byte[chars.length * 2];
for (int i = 0, i2 = 0; i < chars.length; i++, i2 += 2) {
char aChar = chars[i];
bytes[i2] = (byte)(aChar >>> 8 & 0xFF);
bytes[i2 + 1] = (byte)(aChar & 0xFF);
}
stream.write(bytes);
}
public static void writeUTFTruncated(@NotNull DataOutput stream, @NotNull String text) throws IOException {
// we should not compare number of symbols to 65635 -> it is number of bytes what should be compared
// ? 4 bytes per symbol - rough estimation
if (text.length() > 16383) {
stream.writeUTF(text.substring(0, 16383));
}
else {
stream.writeUTF(text);
}
}
private static final ThreadLocalCachedValue<byte[]> ourReadWriteBuffersCache = new ThreadLocalCachedValue<byte[]>() {
@Override
protected byte[] create() {
return allocReadWriteUTFBuffer();
}
};
public static void writeUTF(@NotNull DataOutput storage, @NotNull final String value) throws IOException {
writeUTFFast(ourReadWriteBuffersCache.getValue(), storage, value);
}
public static String readUTF(@NotNull DataInput storage) throws IOException {
return readUTFFast(ourReadWriteBuffersCache.getValue(), storage);
}
@NotNull
public static byte[] allocReadWriteUTFBuffer() {
return new byte[STRING_LENGTH_THRESHOLD + STRING_HEADER_SIZE];
}
public static void writeUTFFast(@NotNull byte[] buffer, @NotNull DataOutput storage, @NotNull final String value) throws IOException {
int len = value.length();
if (len < STRING_LENGTH_THRESHOLD) {
buffer[0] = (byte)len;
boolean isAscii = true;
for (int i = 0; i < len; i++) {
char c = value.charAt(i);
if (c >= 128) {
isAscii = false;
break;
}
buffer[i + STRING_HEADER_SIZE] = (byte)c;
}
if (isAscii) {
storage.write(buffer, 0, len + STRING_HEADER_SIZE);
return;
}
}
storage.writeByte((byte)0xFF);
try {
storage.writeUTF(value);
}
catch (UTFDataFormatException e) {
storage.writeUTF(LONGER_THAN_64K_MARKER);
writeString(value, storage);
}
}
public static final Charset US_ASCII = Charset.forName("US-ASCII");
private static final ThreadLocalCachedValue<char[]> spareBufferLocal = new ThreadLocalCachedValue<char[]>() {
@Override
protected char[] create() {
return new char[STRING_LENGTH_THRESHOLD];
}
};
public static String readUTFFast(@NotNull byte[] buffer, @NotNull DataInput storage) throws IOException {
int len = 0xFF & (int)storage.readByte();
if (len == 0xFF) {
String result = storage.readUTF();
if (LONGER_THAN_64K_MARKER.equals(result)) {
return readString(storage);
}
return result;
}
if (len == 0) return "";
storage.readFully(buffer, 0, len);
char[] chars = spareBufferLocal.getValue();
for(int i = 0; i < len; ++i) chars[i] = (char)(buffer[i] &0xFF);
return new String(chars, 0, len);
}
public static boolean isAscii(@NotNull String str) {
for (int i = 0, length = str.length(); i < length; ++ i) {
if (str.charAt(i) >= 128) return false;
}
return true;
}
public static boolean isAscii(char c) {
return c < 128;
}
public static boolean deleteAllFilesStartingWith(@NotNull File file) {
final String baseName = file.getName();
File parentFile = file.getParentFile();
final File[] files = parentFile != null ? parentFile.listFiles(new FileFilter() {
@Override
public boolean accept(final File pathname) {
return pathname.getName().startsWith(baseName);
}
}): null;
boolean ok = true;
if (files != null) {
for (File f : files) {
ok &= FileUtil.delete(f);
}
}
return ok;
}
public static void syncStream(OutputStream stream) throws IOException {
stream.flush();
try {
Field outField = FilterOutputStream.class.getDeclaredField("out");
outField.setAccessible(true);
while (stream instanceof FilterOutputStream) {
Object o = outField.get(stream);
if (o instanceof OutputStream) {
stream = (OutputStream)o;
} else {
break;
}
}
if (stream instanceof FileOutputStream) {
((FileOutputStream)stream).getFD().sync();
}
}
catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static <T> T openCleanOrResetBroken(@NotNull ThrowableComputable<T, IOException> factoryComputable, final File file) throws IOException {
return openCleanOrResetBroken(factoryComputable, new Runnable() {
@Override
public void run() {
deleteAllFilesStartingWith(file);
}
});
}
public static <T> T openCleanOrResetBroken(@NotNull ThrowableComputable<T, IOException> factoryComputable, Runnable cleanupCallback) throws IOException {
for(int i = 0; i < 2; ++i) {
try {
return factoryComputable.compute();
} catch (IOException ex) {
if (i == 1) throw ex;
cleanupCallback.run();
}
}
return null;
}
}
| apache-2.0 |
mc-server/MCServer | src/Mobs/AggressiveMonster.h | 898 |
#pragma once
#include "Monster.h"
class cAggressiveMonster:
public cMonster
{
using Super = cMonster;
public:
cAggressiveMonster(
const AString & a_ConfigName,
eMonsterType a_MobType,
const AString & a_SoundHurt,
const AString & a_SoundDeath,
const AString & a_SoundAmbient,
float a_Width,
float a_Height
);
virtual void Tick (std::chrono::milliseconds a_Dt, cChunk & a_Chunk) override;
virtual void InStateChasing(std::chrono::milliseconds a_Dt, cChunk & a_Chunk) override;
virtual void EventSeePlayer(cPlayer * a_Player, cChunk & a_Chunk) override;
/** Try to perform attack
returns true if attack was deemed successful (hit player, fired projectile, creeper exploded, etc.) even if it didn't actually do damage
return false if e.g. the mob is still in cooldown from a previous attack */
virtual bool Attack(std::chrono::milliseconds a_Dt);
} ;
| apache-2.0 |
google/aistreams | third_party/gstreamer/plugins/elements/gstfilesrc.c | 17608 | /* GStreamer
* Copyright (C) 1999,2000 Erik Walthinsen <[email protected]>
* 2000,2005 Wim Taymans <[email protected]>
*
* gstfilesrc.c:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library 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.
*/
/**
* SECTION:element-filesrc
* @title: filesrc
* @see_also: #GstFileSrc
*
* Read data from a file in the local file system.
*
* ## Example launch line
* |[
* gst-launch-1.0 filesrc location=song.ogg ! decodebin ! audioconvert ! audioresample ! autoaudiosink
* ]| Play song.ogg audio file which must be in the current working directory.
*
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <gst/gst.h>
#include "gstfilesrc.h"
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef G_OS_WIN32
#include <io.h> /* lseek, open, close, read */
/* On win32, stat* default to 32 bit; we need the 64-bit
* variants, so explicitly define it that way. */
#undef stat
#define stat __stat64
#undef fstat
#define fstat _fstat64
#undef lseek
#define lseek _lseeki64
#undef off_t
#define off_t guint64
/* Prevent stat.h from defining the stat* functions as
* _stat*, since we're explicitly overriding that */
#undef _INC_STAT_INL
#endif
#include <fcntl.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef __BIONIC__ /* Android */
#if defined(__ANDROID_API__) && __ANDROID_API__ >= 21
#undef fstat
#define fstat fstat64
#endif
#endif
#include <errno.h>
#include <string.h>
#include "../../gst/gst-i18n-lib.h"
static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS_ANY);
#ifndef S_ISREG
#define S_ISREG(mode) ((mode)&_S_IFREG)
#endif
#ifndef S_ISDIR
#define S_ISDIR(mode) ((mode)&_S_IFDIR)
#endif
#ifndef S_ISSOCK
#define S_ISSOCK(x) (0)
#endif
#ifndef O_BINARY
#define O_BINARY (0)
#endif
/* Copy of glib's g_open due to win32 libc/cross-DLL brokenness: we can't
* use the 'file descriptor' opened in glib (and returned from this function)
* in this library, as they may have unrelated C runtimes. */
static int
gst_open (const gchar * filename, int flags, int mode)
{
#ifdef G_OS_WIN32
wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
int retval;
int save_errno;
if (wfilename == NULL) {
errno = EINVAL;
return -1;
}
retval = _wopen (wfilename, flags, mode);
save_errno = errno;
g_free (wfilename);
errno = save_errno;
return retval;
#elif defined (__BIONIC__)
return open (filename, flags | O_LARGEFILE, mode);
#else
return open (filename, flags, mode);
#endif
}
GST_DEBUG_CATEGORY_STATIC (gst_file_src_debug);
#define GST_CAT_DEFAULT gst_file_src_debug
/* FileSrc signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
#define DEFAULT_BLOCKSIZE 4*1024
enum
{
PROP_0,
PROP_LOCATION
};
static void gst_file_src_finalize (GObject * object);
static void gst_file_src_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_file_src_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_file_src_start (GstBaseSrc * basesrc);
static gboolean gst_file_src_stop (GstBaseSrc * basesrc);
static gboolean gst_file_src_is_seekable (GstBaseSrc * src);
static gboolean gst_file_src_get_size (GstBaseSrc * src, guint64 * size);
static GstFlowReturn gst_file_src_fill (GstBaseSrc * src, guint64 offset,
guint length, GstBuffer * buf);
static void gst_file_src_uri_handler_init (gpointer g_iface,
gpointer iface_data);
#define _do_init \
G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_file_src_uri_handler_init); \
GST_DEBUG_CATEGORY_INIT (gst_file_src_debug, "filesrc", 0, "filesrc element");
#define gst_file_src_parent_class parent_class
G_DEFINE_TYPE_WITH_CODE (GstFileSrc, gst_file_src, GST_TYPE_BASE_SRC, _do_init);
static void
gst_file_src_class_init (GstFileSrcClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
GstBaseSrcClass *gstbasesrc_class;
gobject_class = G_OBJECT_CLASS (klass);
gstelement_class = GST_ELEMENT_CLASS (klass);
gstbasesrc_class = GST_BASE_SRC_CLASS (klass);
gobject_class->set_property = gst_file_src_set_property;
gobject_class->get_property = gst_file_src_get_property;
g_object_class_install_property (gobject_class, PROP_LOCATION,
g_param_spec_string ("location", "File Location",
"Location of the file to read", NULL,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
GST_PARAM_MUTABLE_READY));
gobject_class->finalize = gst_file_src_finalize;
gst_element_class_set_static_metadata (gstelement_class,
"File Source",
"Source/File",
"Read from arbitrary point in a file",
"Erik Walthinsen <[email protected]>");
gst_element_class_add_static_pad_template (gstelement_class, &srctemplate);
gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_file_src_start);
gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_file_src_stop);
gstbasesrc_class->is_seekable = GST_DEBUG_FUNCPTR (gst_file_src_is_seekable);
gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR (gst_file_src_get_size);
gstbasesrc_class->fill = GST_DEBUG_FUNCPTR (gst_file_src_fill);
if (sizeof (off_t) < 8) {
GST_LOG ("No large file support, sizeof (off_t) = %" G_GSIZE_FORMAT "!",
sizeof (off_t));
}
}
static void
gst_file_src_init (GstFileSrc * src)
{
src->filename = NULL;
src->fd = 0;
src->uri = NULL;
src->is_regular = FALSE;
gst_base_src_set_blocksize (GST_BASE_SRC (src), DEFAULT_BLOCKSIZE);
}
static void
gst_file_src_finalize (GObject * object)
{
GstFileSrc *src;
src = GST_FILE_SRC (object);
g_free (src->filename);
g_free (src->uri);
G_OBJECT_CLASS (parent_class)->finalize (object);
}
static gboolean
gst_file_src_set_location (GstFileSrc * src, const gchar * location,
GError ** err)
{
GstState state;
/* the element must be stopped in order to do this */
GST_OBJECT_LOCK (src);
state = GST_STATE (src);
if (state != GST_STATE_READY && state != GST_STATE_NULL)
goto wrong_state;
GST_OBJECT_UNLOCK (src);
g_free (src->filename);
g_free (src->uri);
/* clear the filename if we get a NULL */
if (location == NULL) {
src->filename = NULL;
src->uri = NULL;
} else {
/* we store the filename as received by the application. On Windows this
* should be UTF8 */
src->filename = g_strdup (location);
src->uri = gst_filename_to_uri (location, NULL);
GST_INFO ("filename : %s", src->filename);
GST_INFO ("uri : %s", src->uri);
}
g_object_notify (G_OBJECT (src), "location");
/* FIXME 2.0: notify "uri" property once there is one */
return TRUE;
/* ERROR */
wrong_state:
{
g_warning ("Changing the `location' property on filesrc when a file is "
"open is not supported.");
if (err)
g_set_error (err, GST_URI_ERROR, GST_URI_ERROR_BAD_STATE,
"Changing the `location' property on filesrc when a file is "
"open is not supported.");
GST_OBJECT_UNLOCK (src);
return FALSE;
}
}
static void
gst_file_src_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
GstFileSrc *src;
g_return_if_fail (GST_IS_FILE_SRC (object));
src = GST_FILE_SRC (object);
switch (prop_id) {
case PROP_LOCATION:
gst_file_src_set_location (src, g_value_get_string (value), NULL);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_file_src_get_property (GObject * object, guint prop_id, GValue * value,
GParamSpec * pspec)
{
GstFileSrc *src;
g_return_if_fail (GST_IS_FILE_SRC (object));
src = GST_FILE_SRC (object);
switch (prop_id) {
case PROP_LOCATION:
g_value_set_string (value, src->filename);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/***
* read code below
* that is to say, you shouldn't read the code below, but the code that reads
* stuff is below. Well, you shouldn't not read the code below, feel free
* to read it of course. It's just that "read code below" is a pretty crappy
* documentation string because it sounds like we're expecting you to read
* the code to understand what it does, which, while true, is really not
* the sort of attitude we want to be advertising. No sir.
*
*/
static GstFlowReturn
gst_file_src_fill (GstBaseSrc * basesrc, guint64 offset, guint length,
GstBuffer * buf)
{
GstFileSrc *src;
guint to_read, bytes_read;
int ret;
GstMapInfo info;
guint8 *data;
src = GST_FILE_SRC_CAST (basesrc);
if (G_UNLIKELY (offset != -1 && src->read_position != offset)) {
off_t res;
res = lseek (src->fd, offset, SEEK_SET);
if (G_UNLIKELY (res < 0 || res != offset))
goto seek_failed;
src->read_position = offset;
}
if (!gst_buffer_map (buf, &info, GST_MAP_WRITE))
goto buffer_write_fail;
data = info.data;
bytes_read = 0;
to_read = length;
while (to_read > 0) {
GST_LOG_OBJECT (src, "Reading %d bytes at offset 0x%" G_GINT64_MODIFIER "x",
to_read, offset + bytes_read);
errno = 0;
ret = read (src->fd, data + bytes_read, to_read);
if (G_UNLIKELY (ret < 0)) {
if (errno == EAGAIN || errno == EINTR)
continue;
goto could_not_read;
}
/* files should eos if they read 0 and more was requested */
if (G_UNLIKELY (ret == 0)) {
/* .. but first we should return any remaining data */
if (bytes_read > 0)
break;
goto eos;
}
to_read -= ret;
bytes_read += ret;
src->read_position += ret;
}
gst_buffer_unmap (buf, &info);
if (bytes_read != length)
gst_buffer_resize (buf, 0, bytes_read);
GST_BUFFER_OFFSET (buf) = offset;
GST_BUFFER_OFFSET_END (buf) = offset + bytes_read;
return GST_FLOW_OK;
/* ERROR */
seek_failed:
{
GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM);
return GST_FLOW_ERROR;
}
could_not_read:
{
GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM);
gst_buffer_unmap (buf, &info);
gst_buffer_resize (buf, 0, 0);
return GST_FLOW_ERROR;
}
eos:
{
GST_DEBUG ("EOS");
gst_buffer_unmap (buf, &info);
gst_buffer_resize (buf, 0, 0);
return GST_FLOW_EOS;
}
buffer_write_fail:
{
GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL), ("Can't write to buffer"));
return GST_FLOW_ERROR;
}
}
static gboolean
gst_file_src_is_seekable (GstBaseSrc * basesrc)
{
GstFileSrc *src = GST_FILE_SRC (basesrc);
return src->seekable;
}
static gboolean
gst_file_src_get_size (GstBaseSrc * basesrc, guint64 * size)
{
struct stat stat_results;
GstFileSrc *src;
src = GST_FILE_SRC (basesrc);
if (!src->seekable) {
/* If it isn't seekable, we won't know the length (but fstat will still
* succeed, and wrongly say our length is zero. */
return FALSE;
}
if (fstat (src->fd, &stat_results) < 0)
goto could_not_stat;
*size = stat_results.st_size;
return TRUE;
/* ERROR */
could_not_stat:
{
return FALSE;
}
}
/* open the file, necessary to go to READY state */
static gboolean
gst_file_src_start (GstBaseSrc * basesrc)
{
GstFileSrc *src = GST_FILE_SRC (basesrc);
struct stat stat_results;
if (src->filename == NULL || src->filename[0] == '\0')
goto no_filename;
GST_INFO_OBJECT (src, "opening file %s", src->filename);
/* open the file */
src->fd = gst_open (src->filename, O_RDONLY | O_BINARY, 0);
if (src->fd < 0)
goto open_failed;
/* check if it is a regular file, otherwise bail out */
if (fstat (src->fd, &stat_results) < 0)
goto no_stat;
if (S_ISDIR (stat_results.st_mode))
goto was_directory;
if (S_ISSOCK (stat_results.st_mode))
goto was_socket;
src->read_position = 0;
/* record if it's a regular (hence seekable and lengthable) file */
if (S_ISREG (stat_results.st_mode))
src->is_regular = TRUE;
/* We need to check if the underlying file is seekable. */
{
off_t res = lseek (src->fd, 0, SEEK_END);
if (res < 0) {
GST_LOG_OBJECT (src, "disabling seeking, lseek failed: %s",
g_strerror (errno));
src->seekable = FALSE;
} else {
res = lseek (src->fd, 0, SEEK_SET);
if (res < 0) {
/* We really don't like not being able to go back to 0 */
src->seekable = FALSE;
goto lseek_wonky;
}
src->seekable = TRUE;
}
}
/* We can only really do seeking on regular files - for other file types, we
* don't know their length, so seeking isn't useful/meaningful */
src->seekable = src->seekable && src->is_regular;
gst_base_src_set_dynamic_size (basesrc, src->seekable);
return TRUE;
/* ERROR */
no_filename:
{
GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND,
(_("No file name specified for reading.")), (NULL));
goto error_exit;
}
open_failed:
{
switch (errno) {
case ENOENT:
GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
("No such file \"%s\"", src->filename));
break;
default:
GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
(_("Could not open file \"%s\" for reading."), src->filename),
GST_ERROR_SYSTEM);
break;
}
goto error_exit;
}
no_stat:
{
GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
(_("Could not get info on \"%s\"."), src->filename), (NULL));
goto error_close;
}
was_directory:
{
GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
(_("\"%s\" is a directory."), src->filename), (NULL));
goto error_close;
}
was_socket:
{
GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
(_("File \"%s\" is a socket."), src->filename), (NULL));
goto error_close;
}
lseek_wonky:
{
GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
("Could not seek back to zero after seek test in file \"%s\"",
src->filename));
goto error_close;
}
error_close:
close (src->fd);
error_exit:
return FALSE;
}
/* unmap and close the file */
static gboolean
gst_file_src_stop (GstBaseSrc * basesrc)
{
GstFileSrc *src = GST_FILE_SRC (basesrc);
/* close the file */
close (src->fd);
/* zero out a lot of our state */
src->fd = 0;
src->is_regular = FALSE;
return TRUE;
}
/*** GSTURIHANDLER INTERFACE *************************************************/
static GstURIType
gst_file_src_uri_get_type (GType type)
{
return GST_URI_SRC;
}
static const gchar *const *
gst_file_src_uri_get_protocols (GType type)
{
static const gchar *protocols[] = { "file", NULL };
return protocols;
}
static gchar *
gst_file_src_uri_get_uri (GstURIHandler * handler)
{
GstFileSrc *src = GST_FILE_SRC (handler);
/* FIXME: make thread-safe */
return g_strdup (src->uri);
}
static gboolean
gst_file_src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
GError ** err)
{
gchar *location, *hostname = NULL;
gboolean ret = FALSE;
GstFileSrc *src = GST_FILE_SRC (handler);
if (strcmp (uri, "file://") == 0) {
/* Special case for "file://" as this is used by some applications
* to test with gst_element_make_from_uri if there's an element
* that supports the URI protocol. */
gst_file_src_set_location (src, NULL, NULL);
return TRUE;
}
location = g_filename_from_uri (uri, &hostname, err);
if (!location || (err != NULL && *err != NULL)) {
GST_WARNING_OBJECT (src, "Invalid URI '%s' for filesrc: %s", uri,
(err != NULL && *err != NULL) ? (*err)->message : "unknown error");
goto beach;
}
if ((hostname) && (strcmp (hostname, "localhost"))) {
/* Only 'localhost' is permitted */
GST_WARNING_OBJECT (src, "Invalid hostname '%s' for filesrc", hostname);
g_set_error (err, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
"File URI with invalid hostname '%s'", hostname);
goto beach;
}
#ifdef G_OS_WIN32
/* Unfortunately, g_filename_from_uri() doesn't handle some UNC paths
* correctly on windows, it leaves them with an extra backslash
* at the start if they're of the mozilla-style file://///host/path/file
* form. Correct this.
*/
if (location[0] == '\\' && location[1] == '\\' && location[2] == '\\')
memmove (location, location + 1, strlen (location + 1) + 1);
#endif
ret = gst_file_src_set_location (src, location, err);
beach:
if (location)
g_free (location);
if (hostname)
g_free (hostname);
return ret;
}
static void
gst_file_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
{
GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
iface->get_type = gst_file_src_uri_get_type;
iface->get_protocols = gst_file_src_uri_get_protocols;
iface->get_uri = gst_file_src_uri_get_uri;
iface->set_uri = gst_file_src_uri_set_uri;
}
| apache-2.0 |
svn2github/pixels | src/main/java/com/jhlabs/image/BlockFilter.java | 3064 | /*
Copyright 2006 Jerry Huxtable
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.jhlabs.image;
import java.awt.*;
import java.awt.image.*;
/**
* A Filter to pixellate images.
*/
public class BlockFilter extends AbstractBufferedImageOp {
private int blockSize = 2;
/**
* Construct a BlockFilter.
*/
public BlockFilter() {
}
/**
* Construct a BlockFilter.
* @param blockSize the number of pixels along each block edge
*/
public BlockFilter( int blockSize ) {
this.blockSize = blockSize;
}
/**
* Set the pixel block size.
* @param blockSize the number of pixels along each block edge
* @min-value 1
* @max-value 100+
* @see #getBlockSize
*/
public void setBlockSize(int blockSize) {
this.blockSize = blockSize;
}
/**
* Get the pixel block size.
* @return the number of pixels along each block edge
* @see #setBlockSize
*/
public int getBlockSize() {
return blockSize;
}
public BufferedImage filter( BufferedImage src, BufferedImage dst ) {
int width = src.getWidth();
int height = src.getHeight();
int type = src.getType();
WritableRaster srcRaster = src.getRaster();
if ( dst == null )
dst = createCompatibleDestImage( src, null );
int[] pixels = new int[blockSize * blockSize];
for ( int y = 0; y < height; y += blockSize ) {
for ( int x = 0; x < width; x += blockSize ) {
int w = Math.min( blockSize, width-x );
int h = Math.min( blockSize, height-y );
int t = w*h;
getRGB( src, x, y, w, h, pixels );
int r = 0, g = 0, b = 0;
int argb;
int i = 0;
for ( int by = 0; by < h; by++ ) {
for ( int bx = 0; bx < w; bx++ ) {
argb = pixels[i];
r += (argb >> 16) & 0xff;
g += (argb >> 8) & 0xff;
b += argb & 0xff;
i++;
}
}
argb = ((r/t) << 16) | ((g/t) << 8) | (b/t);
i = 0;
for ( int by = 0; by < h; by++ ) {
for ( int bx = 0; bx < w; bx++ ) {
pixels[i] = (pixels[i] & 0xff000000) | argb;
i++;
}
}
setRGB( dst, x, y, w, h, pixels );
}
}
return dst;
}
public String toString() {
return "Pixellate/Mosaic...";
}
}
| apache-2.0 |
Distrotech/fop | src/java/org/apache/fop/pdf/PDFName.java | 3799 | /*
* 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.
*/
/* $Id$ */
package org.apache.fop.pdf;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.io.output.CountingOutputStream;
/**
* Class representing a PDF name object.
*/
public class PDFName extends PDFObject {
private String name;
/**
* Creates a new PDF name object.
* @param name the name value
*/
public PDFName(String name) {
super();
this.name = escapeName(name);
}
private static final String ESCAPED_NAME_CHARS = "/()<>[]%#";
/**
* Escapes a PDF name. It adds the leading slash and escapes characters as necessary.
* @param name the name
* @return the escaped name
*/
static String escapeName(String name) {
StringBuilder sb = new StringBuilder(Math.min(16, name.length() + 4));
boolean skipFirst = false;
sb.append('/');
if (name.startsWith("/")) {
skipFirst = true;
}
for (int i = (skipFirst ? 1 : 0), c = name.length(); i < c; i++) {
char ch = name.charAt(i);
if (ch < 33 || ch > 126 || ESCAPED_NAME_CHARS.indexOf(ch) >= 0) {
sb.append('#');
toHex(ch, sb);
} else {
sb.append(ch);
}
}
return sb.toString();
}
private static final char[] DIGITS
= {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
private static void toHex(char ch, StringBuilder sb) {
if (ch >= 256) {
throw new IllegalArgumentException(
"Only 8-bit characters allowed by this implementation");
}
sb.append(DIGITS[ch >>> 4 & 0x0F]);
sb.append(DIGITS[ch & 0x0F]);
}
/** {@inheritDoc} */
@Override
public String toString() {
return this.name;
}
/**
* Returns the name without the leading slash.
* @return the name without the leading slash
*/
public String getName() {
return this.name.substring(1);
}
/** {@inheritDoc} */
public boolean equals(Object obj) {
if (!(obj instanceof PDFName)) {
return false;
}
PDFName other = (PDFName)obj;
return this.name.equals(other.name);
}
/** {@inheritDoc} */
public int hashCode() {
return name.hashCode();
}
@Override
public int output(OutputStream stream) throws IOException {
CountingOutputStream cout = new CountingOutputStream(stream);
StringBuilder textBuffer = new StringBuilder(64);
textBuffer.append(toString());
PDFDocument.flushTextBuffer(textBuffer, cout);
return cout.getCount();
}
@Override
public void outputInline(OutputStream out, StringBuilder textBuffer) throws IOException {
if (hasObjectNumber()) {
textBuffer.append(referencePDF());
} else {
textBuffer.append(toString());
}
}
}
| apache-2.0 |
elizabethso/sdcct | sdcct-core/src/main/java/gov/hhs/onc/sdcct/ws/impl/SdcctConduitSelector.java | 455 | package gov.hhs.onc.sdcct.ws.impl;
import gov.hhs.onc.sdcct.logging.impl.TxTaskExecutor;
import org.apache.cxf.endpoint.DeferredConduitSelector;
public class SdcctConduitSelector extends DeferredConduitSelector {
private TxTaskExecutor taskExec;
public SdcctConduitSelector(TxTaskExecutor taskExec) {
super();
this.taskExec = taskExec;
}
public TxTaskExecutor getTaskExecutor() {
return this.taskExec;
}
}
| apache-2.0 |
symplified/Symplified.Auth | lib/mono/mcs/class/System.Security/System.Security.Cryptography.Xml/CipherReference.cs | 2802 | //
// CipherReference.cs - CipherReference implementation for XML Encryption
// http://www.w3.org/2001/04/xmlenc#sec-CipherReference
//
// Author:
// Tim Coleman ([email protected])
//
// Copyright (C) Tim Coleman, 2004
//
// 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.
//
#if NET_2_0
using System.Xml;
namespace System.Security.Cryptography.Xml {
public sealed class CipherReference : EncryptedReference {
#region Constructors
public CipherReference ()
: base ()
{
}
public CipherReference (string uri)
: base (uri)
{
}
public CipherReference (string uri, TransformChain tc)
: base (uri, tc)
{
}
#endregion // Constructors
#region Methods
public override XmlElement GetXml ()
{
return GetXml (new XmlDocument ());
}
internal override XmlElement GetXml (XmlDocument document)
{
XmlElement xel = document.CreateElement (XmlEncryption.ElementNames.CipherReference, EncryptedXml.XmlEncNamespaceUrl);
xel.SetAttribute (XmlEncryption.AttributeNames.URI, Uri);
if (TransformChain != null && TransformChain.Count > 0) {
XmlElement xtr = document.CreateElement (XmlEncryption.ElementNames.Transforms, EncryptedXml.XmlEncNamespaceUrl);
foreach (Transform t in TransformChain)
xtr.AppendChild (document.ImportNode (t.GetXml (), true));
xel.AppendChild (xtr);
}
return xel;
}
public override void LoadXml (XmlElement value)
{
if (value == null)
throw new ArgumentNullException ("value");
if ((value.LocalName != XmlEncryption.ElementNames.CipherReference) || (value.NamespaceURI != EncryptedXml.XmlEncNamespaceUrl))
throw new CryptographicException ("Malformed CipherReference element.");
base.LoadXml (value);
}
#endregion // Methods
}
}
#endif
| apache-2.0 |
cshannon/activemq-artemis | docs/user-manual/en/configuration-index.md | 37772 | Configuration Reference
=======================
This section is a quick index for looking up configuration. Click on the
element name to go to the specific chapter.
Server Configuration
====================
broker.xml
--------------------------
This is the main core server configuration file which contains to elements
'core' and 'jms'.
The 'core' element contains the main server configuration while the 'jms'
element is used by the server side JMS service to load JMS Queues, Topics
# System properties
It is possible to use System properties to replace some of the configuration properties. If you define a System property starting with "brokerconfig." that will be passed along to Bean Utils and the configuration would be replaced.
To define global-max-size=1000000 using a system property you would have to define this property, for example through java arguments:
```
java -Dbrokerconfig.globalMaxSize=1000000
```
You can also change the prefix through the broker.xml by setting:
```
<system-property-prefix>yourprefix</system-property-prefix>
```
This is to help you customize artemis on embedded systems.
# The core configuration
This describes the root of the XML configuration. You will see here also multiple sub-types listed.
For example on the main config you will have bridges and at the [list of bridge](#bridge-type) type we will describe the properties for that configuration.
Name | Description
:--- | :---
[acceptors](configuring-transports.md "Understanding Acceptors") | a list of remoting acceptors
[acceptors.acceptor](configuring-transports.md "Understanding Acceptors") | Each acceptor is composed for just an URL
[address-settings](address-model.md "Configuring Addresses and Queues Via Address Settings") | [a list of address-setting](#address-setting-type)
[allow-failback](ha.md "Failing Back to live Server") | Should stop backup on live restart. default true
[async-connection-execution-enabled](connection-ttl.md "Configuring Asynchronous Connection Execution") | If False delivery would be always asynchronous. default true
[bindings-directory](persistence.md "Configuring the bindings journal") | The folder in use for the bindings folder
[bridges](core-bridges.md "Core Bridges") | [a list of bridge](#bridge-type)
[broadcast-groups](clusters.md "Clusters") | [a list of broadcast-group](#broadcast-group-type)
[configuration-file-refresh-period](config-reload.md) | The frequency in milliseconds the configuration file is checked for changes (default 5000)
[check-for-live-server](ha.md) | Used for a live server to verify if there are other nodes with the same ID on the topology
[cluster-connections](clusters.md "Clusters") | [a list of cluster-connection](#cluster-connection-type)
[cluster-password](clusters.md "Clusters") | Cluster password. It applies to all cluster configurations.
[cluster-user](clusters.md "Clusters") | Cluster username. It applies to all cluster configurations.
[connection-ttl-override](connection-ttl.md) | if set, this will override how long (in ms) to keep a connection alive without receiving a ping. -1 disables this setting. Default -1
[connection-ttl-check-period](connection-ttl.md) | how often (in ms) to check connections for ttl violation. Default 2000
[connectors.connector](configuring-transports.md "Understanding Connectors") | The URL for the connector. This is a list
[create-bindings-dir](persistence.md "Configuring the bindings journal") | true means that the server will create the bindings directory on start up. Default=true
[create-journal-dir](persistence.md) | true means that the journal directory will be created. Default=true
[discovery-groups](clusters.md "Clusters") | [a list of discovery-group](#discovery-group-type)
[disk-scan-period](paging.md#max-disk-usage) | The interval where the disk is scanned for percentual usage. Default=5000 ms.
[diverts](diverts.md "Diverting and Splitting Message Flows") | [a list of diverts to use](#divert-type)
[global-max-size](paging.md#global-max-size) | The amount in bytes before all addresses are considered full. Default is half of the memory used by the JVM (-Xmx argument).
[graceful-shutdown-enabled](graceful-shutdown.md "Graceful Server Shutdown") | true means that graceful shutdown is enabled. Default=true
[graceful-shutdown-timeout](graceful-shutdown.md "Graceful Server Shutdown") | Timeout on waitin for clients to disconnect before server shutdown. Default=-1
[grouping-handler](message-grouping.md "Message Grouping") | Message Group configuration
[id-cache-size](duplicate-detection.md "Configuring the Duplicate ID Cache") | The duplicate detection circular cache size. Default=20000
[jmx-domain](management.md "Configuring JMX") | the JMX domain used to registered MBeans in the MBeanServer. Default=org.apache.activemq
[jmx-management-enabled](management.md "Configuring JMX") | true means that the management API is available via JMX. Default=true
[journal-buffer-size](persistence.md) | The size of the internal buffer on the journal in KB. Default=490 KiB
[journal-buffer-timeout](persistence.md) | The Flush timeout for the journal buffer
[journal-compact-min-files](persistence.md) | The minimal number of data files before we can start compacting. Setting this to 0 means compacting is disabled. Default=10
[journal-compact-percentage](persistence.md) | The percentage of live data on which we consider compacting the journal. Default=30
[journal-directory](persistence.md) | the directory to store the journal files in. Default=data/journal
[journal-file-size](persistence.md) | the size (in bytes) of each journal file. Default=10485760 (10 MB)
[journal-max-io](persistence.md#configuring.message.journal.journal-max-io) | the maximum number of write requests that can be in the AIO queue at any one time. Default is 500 for AIO and 1 for NIO, ignored for MAPPED.
[journal-min-files](persistence.md#configuring.message.journal.journal-min-files) | how many journal files to pre-create. Default=2
[journal-pool-files](persistence.md#configuring.message.journal.journal-pool-files) | The upper theshold of the journal file pool,-1 (default) means no Limit. The system will create as many files as needed however when reclaiming files it will shrink back to the `journal-pool-files`
[journal-sync-non-transactional](persistence.md) | if true wait for non transaction data to be synced to the journal before returning response to client. Default=true
[journal-sync-transactional](persistence.md) | if true wait for transaction data to be synchronized to the journal before returning response to client. Default=true
[journal-type](persistence.md) | the type of journal to use. Default=ASYNCIO
[journal-datasync](persistence.md) | It will use msync/fsync on journal operations. Default=true.
[large-messages-directory](large-messages.md "Configuring the server") | the directory to store large messages. Default=data/largemessages
[management-address](management.md "Configuring Core Management") | the name of the management address to send management messages to. It is prefixed with "jms.queue" so that JMS clients can send messages to it. Default=jms.queue.activemq.management
[management-notification-address](management.md "Configuring The Core Management Notification Address") | the name of the address that consumers bind to receive management notifications. Default=activemq.notifications
[mask-password](configuration-index.md "Using Masked Passwords in Configuration Files") | This option controls whether passwords in server configuration need be masked. If set to "true" the passwords are masked. Default=false
[max-saved-replicated-journals-size](ha.md#data-replication) | This specifies how many times a replicated backup server can restart after moving its files on start. Once there are this number of backup journal files the server will stop permanently after if fails back. -1 Means no Limit, 0 don't keep a copy at all, Default=2
[max-disk-usage](paging.md#max-disk-usage) | The max percentage of data we should use from disks. The System will block while the disk is full. Default=100
[memory-measure-interval](perf-tuning.md) | frequency to sample JVM memory in ms (or -1 to disable memory sampling). Default=-1
[memory-warning-threshold](perf-tuning.md) | Percentage of available memory which will trigger a warning log. Default=25
[message-counter-enabled](management.md "Configuring Message Counters") | true means that message counters are enabled. Default=false
[message-counter-max-day-history](management.md "Configuring Message Counters") | how many days to keep message counter history. Default=10 (days)
[message-counter-sample-period](management.md "Configuring Message Counters") | the sample period (in ms) to use for message counters. Default=10000
[message-expiry-scan-period](message-expiry.md "Configuring The Expiry Reaper Thread") | how often (in ms) to scan for expired messages. Default=30000
[message-expiry-thread-priority](message-expiry.md "Configuring The Expiry Reaper Thread") | the priority of the thread expiring messages. Default=3
[page-max-concurrent-io](paging.md "Paging Mode") | The max number of concurrent reads allowed on paging. Default=5
[paging-directory](paging.md "Configuration") | the directory to store paged messages in. Default=data/paging
[persist-delivery-count-before-delivery](undelivered-messages.md "Delivery Count Persistence") | True means that the delivery count is persisted before delivery. False means that this only happens after a message has been cancelled. Default=false
[persistence-enabled](persistence.md "Configuring ActiveMQ Artemis for Zero Persistence") | true means that the server will use the file based journal for persistence. Default=true
[persist-id-cache](duplicate-detection.md "Configuring the Duplicate ID Cache") | true means that ID's are persisted to the journal. Default=true
[queues](address-model.md "Predefined Queues") | [a list of queue to be created](#queue-type)
[remoting-incoming-interceptors](intercepting-operations.md "Intercepting Operations") | A list of interceptor
[resolveProtocols]() | Use [ServiceLoader](http://docs.oracle.com/javase/tutorial/ext/basics/spi.html) to load protocol modules. Default=true
[scheduled-thread-pool-max-size](thread-pooling.md#server.scheduled.thread.pool "Server Scheduled Thread Pool")| Maximum number of threads to use for the scheduled thread pool. Default=5
[security-enabled](security.md "Security") | true means that security is enabled. Default=true
[security-invalidation-interval](security.md "Security") | how long (in ms) to wait before invalidating the security cache. Default=10000
system-property-prefix | Prefix for replacing configuration settings using Bean Utils.
[populate-validated-user](security.md "Security") | whether or not to add the name of the validated user to the messages that user sends. Default=false
[security-settings](security.md "Role based security for addresses") | [a list of security-setting](#security-setting-type)
[thread-pool-max-size](thread-pooling.md "Server Scheduled Thread Pool") | Maximum number of threads to use for the thread pool. -1 means 'no limits'.. Default=30
[transaction-timeout](transaction-config.md "Resource Manager Configuration") | how long (in ms) before a transaction can be removed from the resource manager after create time. Default=300000
[transaction-timeout-scan-period](transaction-config.md "Resource Manager Configuration") | how often (in ms) to scan for timeout transactions. Default=1000
[wild-card-routing-enabled](wildcard-routing.md "Routing Messages With Wild Cards") | true means that the server supports wild card routing. Default=true
[network-check-NIC](network-isolation.md) | The network internet card to be used on InetAddress.isReacheable
[network-check-URL](network-isolation.md) | The list of http URIs to be used to validate the network
[network-check-list](network-isolation.md) | The list of pings to be used on ping or InetAddress.isReacheable
[network-check-ping-command](network-isolation.md) | The command used to oping IPV4 addresses
[network-check-ping6-command](network-isolation.md) | The command used to oping IPV6 addresses
#address-setting type
Name | Description
:--- | :---
[match ](address-model.md "Configuring Queues Via Address Settings") | The filter to apply to the setting
[dead-letter-address](undelivered-messages.md "Configuring Dead Letter Addresses") | dead letter address
[expiry-address](message-expiry.md "Configuring Expiry Addresses") | expired messages address
[expiry-delay](address-model.md "Configuring Queues Via Address Settings") | expiration time override, -1 don't override with default=-1
[redelivery-delay](undelivered-messages.md "Configuring Delayed Redelivery") | time to redeliver a message (in ms) with default=0
[redelivery-delay-multiplier](address-model.md "Configuring Queues Via Address Settings") | multiplier to apply to the "redelivery-delay"
[max-redelivery-delay](address-model.md "Configuring Queues Via Address Settings") | Max value for the redelivery-delay
[max-delivery-attempts](undelivered-messages.md "Configuring Dead Letter Addresses") | Number of retries before dead letter address, default=10
[max-size-bytes](paging.md "Paging") | Limit before paging. -1 = infinite
[page-size-bytes](paging.md "Paging") | Size of each file on page, default=10485760
[page-max-cache-size](paging.md "Paging") | Maximum number of files cached from paging default=5
[address-full-policy](address-model.md "Configuring Queues Via Address Settings") | Model to chose after queue full
[message-counter-history-day-limit](address-model.md "Configuring Queues Via Address Settings") | Days to keep in history
[last-value-queue](last-value-queues.md "Last-Value Queues") | Queue is a last value queue, default=false
[redistribution-delay](clusters.md "Clusters") | Timeout before redistributing values after no consumers. default=-1
[send-to-dla-on-no-route](address-model.md "Configuring Queues Via Address Settings") | Forward messages to DLA when no queues subscribing. default=false
#bridge type
Name | Description
:--- | :---
[name ](core-bridges.md "Core Bridges") | unique name
[queue-name](core-bridges.md "Core Bridges") | name of queue that this bridge consumes from
[forwarding-address](core-bridges.md "Core Bridges") | address to forward to. If omitted original address is used
[ha](core-bridges.md "Core Bridges") | whether this bridge supports fail-over
[filter](core-bridges.md "Core Bridges") | optional core filter expression
[transformer-class-name](core-bridges.md "Core Bridges") | optional name of transformer class
[min-large-message-size](core-bridges.md "Core Bridges") | Limit before message is considered large. default 100KB
[check-period](connection-ttl.md "Detecting Dead Connections") | [TTL](http://en.wikipedia.org/wiki/Time_to_live "Time to Live") check period for the bridge. -1 means disabled. default 30000 (ms)
[connection-ttl](connection-ttl.md "Detecting Dead Connections") | [TTL](http://en.wikipedia.org/wiki/Time_to_live "Time to Live") for the Bridge. This should be greater than the ping period. default 60000 (ms)
[retry-interval](core-bridges.md "Core Bridges") | period (in ms) between successive retries. default 2000
[retry-interval-multiplier](core-bridges.md "Core Bridges") | multiplier to apply to successive retry intervals. default 1
[max-retry-interval](core-bridges.md "Core Bridges") | Limit to the retry-interval growth. default 2000
[reconnect-attempts](core-bridges.md "Core Bridges") | maximum number of retry attempts, -1 means 'no limits'. default -1
[use-duplicate-detection](core-bridges.md "Core Bridges") | forward duplicate detection headers?. default true
[confirmation-window-size](core-bridges.md "Core Bridges") | number of bytes before confirmations are sent. default 1MB
[producer-window-size](core-bridges.md "Core Bridges") | Producer flow control size on the bridge. Default -1 (disabled)
[user](core-bridges.md "Core Bridges") | Username for the bridge, the default is the cluster username
[password](core-bridges.md "Core Bridges") | Password for the bridge, default is the cluster password
[reconnect-attempts-same-node](core-bridges.md "Core Bridges") | Number of retries before trying another node. default 10
# broadcast-group type
Name | Type
:--- | :---
[name ](clusters.md "Clusters") | unique name
[local-bind-address](clusters.md "Clusters") | local bind address that the datagram socket is bound to
[local-bind-port](clusters.md "Clusters") | local port to which the datagram socket is bound to
[group-address](clusters.md "Clusters") | multicast address to which the data will be broadcast
[group-port](clusters.md "Clusters") | UDP port number used for broadcasting
[broadcast-period](clusters.md "Clusters") | period in milliseconds between consecutive broadcasts. default 2000
[jgroups-file](clusters.md) | Name of JGroups configuration file
[jgroups-channel](clusters.md) | Name of JGroups Channel
[connector-ref](clusters.md "Clusters") |
#cluster-connection type
Name | Description
:--- | :---
[name](clusters.md "Clusters") | unique name
[address](clusters.md "Clusters") | name of the address this cluster connection applies to
[connector-ref](clusters.md "Clusters") | Name of the connector reference to use.
[check-period](connection-ttl.md "Detecting Dead Connections") | The period (in milliseconds) used to check if the cluster connection has failed to receive pings from another server with default = 30000
[connection-ttl](connection-ttl.md "Detecting Dead Connections") | Timeout for TTL. Default 60000
[min-large-message-size](large-messages.md "Large Messages") | Messages larger than this are considered large-messages, default=100KB
[call-timeout](clusters.md "Clusters") | Time(ms) before giving up on blocked calls. Default=30000
[retry-interval](clusters.md "Clusters") | period (in ms) between successive retries. Default=500
[retry-interval-multiplier](clusters.md "Clusters") | multiplier to apply to the retry-interval. Default=1
[max-retry-interval](clusters.md "Clusters") | Maximum value for retry-interval. Default=2000
[reconnect-attempts](clusters.md "Clusters") | How many attempts should be made to reconnect after failure. Default=-1
[use-duplicate-detection](clusters.md "Clusters") | should duplicate detection headers be inserted in forwarded messages?. Default=true
[message-load-balancing](clusters.md "Clusters") | how should messages be load balanced? Default=OFF
[max-hops](clusters.md "Clusters") | maximum number of hops cluster topology is propagated. Default=1
[confirmation-window-size](client-reconnection.md "Client Reconnection and Session Reattachment")| The size (in bytes) of the window used for confirming data from the server connected to. Default 1048576
[producer-window-size](clusters.md "Clusters") | Flow Control for the Cluster connection bridge. Default -1 (disabled)
[call-failover-timeout](clusters.md "Configuring Cluster Connections") | How long to wait for a reply if in the middle of a fail-over. -1 means wait forever. Default -1
[notification-interval](clusters.md "Clusters") | how often the cluster connection will notify the cluster of its existence right after joining the cluster. Default 1000
[notification-attempts](clusters.md "Clusters") | how many times this cluster connection will notify the cluster of its existence right after joining the cluster Default 2
#discovery-group type
Name | Description
:--- | :---
[name](clusters.md "Clusters") | unique name
[group-address](clusters.md "Clusters") | Multicast IP address of the group to listen on
[group-port](clusters.md "Clusters") | UDP port number of the multi cast group
[jgroups-file](clusters.md) | Name of a JGroups configuration file. If specified, the server uses JGroups for discovery.
[jgroups-channel](clusters.md) | Name of a JGroups Channel. If specified, the server uses the named channel for discovery.
[refresh-timeout]() | Period the discovery group waits after receiving the last broadcast from a particular server before removing that servers connector pair entry from its list. Default=10000
[local-bind-address](clusters.md "Clusters") | local bind address that the datagram socket is bound to
[local-bind-port](clusters.md "Clusters") | local port to which the datagram socket is bound to. Default=-1
[initial-wait-timeout]() | time to wait for an initial broadcast to give us at least one node in the cluster. Default=10000
#divert type
Name | Description
:--- | :---
[name](diverts.md "Diverting and Splitting Message Flows") | unique name
[transformer-class-name](diverts.md "Diverting and Splitting Message Flows") | an optional class name of a transformer
[exclusive](diverts.md "Diverting and Splitting Message Flows") | whether this is an exclusive divert. Default=false
[routing-name](diverts.md "Diverting and Splitting Message Flows") | the routing name for the divert
[address](diverts.md "Diverting and Splitting Message Flows") | the address this divert will divert from
[forwarding-address](diverts.md "Diverting and Splitting Message Flows") | the forwarding address for the divert
[filter](diverts.md "Diverting and Splitting Message Flows")| optional core filter expression
#queue type
Name | Description
:--- | :---
[name ](address-model.md "Predefined Queues") | unique name
[address](address-model.md "Predefined Queues") | address for the queue
[filter](address-model.md "Predefined Queues") | optional core filter expression
[durable](address-model.md "Predefined Queues") | whether the queue is durable (persistent). Default=true
#security-setting type
Name | Description
:--- | :---
[match ](security.md "Role based security for addresses") | [address expression](wildcard-syntax.md)
[permission](security.md "Role based security for addresses") |
[permission.type ](security.md "Role based security for addresses") | the type of permission
[permission.roles ](security.md "Role based security for addresses") | a comma-separated list of roles to apply the permission to
----------------------------
##The jms configuration
Name | Type | Description
:--- | :--- | :---
[queue](using-jms.md "JMS Server Configuration") | Queue | a queue
[queue.name (attribute)](using-jms.md "JMS Server Configuration") | String | unique name of the queue
[queue.durable](using-jms.md "JMS Server Configuration") | Boolean | is the queue durable?. Default=true
[queue.filter](using-jms.md "JMS Server Configuration") | String | optional filter expression for the queue
[topic](using-jms.md "JMS Server Configuration") | Topic | a topic
[topic.name (attribute)](using-jms.md "JMS Server Configuration") | String | unique name of the topic
Using Masked Passwords in Configuration Files
---------------------------------------------
By default all passwords in Apache ActiveMQ Artemis server's configuration files are in
plain text form. This usually poses no security issues as those files
should be well protected from unauthorized accessing. However, in some
circumstances a user doesn't want to expose its passwords to more eyes
than necessary.
Apache ActiveMQ Artemis can be configured to use 'masked' passwords in its
configuration files. A masked password is an obscure string
representation of a real password. To mask a password a user will use an
'encoder'. The encoder takes in the real password and outputs the masked
version. A user can then replace the real password in the configuration
files with the new masked password. When Apache ActiveMQ Artemis loads a masked
password, it uses a suitable 'decoder' to decode it into real password.
Apache ActiveMQ Artemis provides a default password encoder and decoder. Optionally
users can use or implement their own encoder and decoder for masking the
passwords.
### Password Masking in Server Configuration File
#### The password masking property
The server configuration file has a property that defines the default
masking behaviors over the entire file scope.
`mask-password`: this boolean type property indicates if a password
should be masked or not. Set it to "true" if you want your passwords
masked. The default value is "false".
#### Specific masking behaviors
##### cluster-password
The nature of the value of cluster-password is subject to the value of
property 'mask-password'. If it is true the cluster-password is masked.
##### Passwords in connectors and acceptors
In the server configuration, Connectors and Acceptors sometimes needs to
specify passwords. For example if a users wants to use an SSL-enabled
NettyAcceptor, it can specify a key-store-password and a
trust-store-password. Because Acceptors and Connectors are pluggable
implementations, each transport will have different password masking
needs.
When a Connector or Acceptor configuration is initialised, Apache ActiveMQ Artemis will
add the "mask-password" and "password-codec" values to the Connector or
Acceptors params using the keys `activemq.usemaskedpassword` and
`activemq.passwordcodec` respectively. The Netty and InVM
implementations will use these as needed and any other implementations
will have access to these to use if they so wish.
##### Passwords in Core Bridge configurations
Core Bridges are configured in the server configuration file and so the
masking of its 'password' properties follows the same rules as that of
'cluster-password'.
#### Examples
The following table summarizes the relations among the above-mentioned
properties
mask-password | cluster-password | acceptor/connector passwords | bridge password
:------------- | :---------------- | :--------------------------- | :---------------
absent | plain text | plain text | plain text
false | plain text | plain text | plain text
true | masked | masked | masked
Examples
Note: In the following examples if related attributed or properties are
absent, it means they are not specified in the configure file.
example 1
```xml
<cluster-password>bbc</cluster-password>
```
This indicates the cluster password is a plain text value ("bbc").
example 2
```xml
<mask-password>true</mask-password>
<cluster-password>80cf731af62c290</cluster-password>
```
This indicates the cluster password is a masked value and Apache ActiveMQ Artemis will
use its built-in decoder to decode it. All other passwords in the
configuration file, Connectors, Acceptors and Bridges, will also use
masked passwords.
### JMS Bridge password masking
The JMS Bridges are configured and deployed as separate beans so they
need separate configuration to control the password masking. A JMS
Bridge has two password parameters in its constructor, SourcePassword
and TargetPassword. It uses the following two optional properties to
control their masking:
`useMaskedPassword` -- If set to "true" the passwords are masked.
Default is false.
`passwordCodec` -- Class name and its parameters for the Decoder used to
decode the masked password. Ignored if `useMaskedPassword` is false. The
format of this property is a full qualified class name optionally
followed by key/value pairs, separated by semi-colons. For example:
```xml
<property name="useMaskedPassword">true</property>
<property name="passwordCodec">com.foo.FooDecoder;key=value</property>
```
Apache ActiveMQ Artemis will load this property and initialize the class with a
parameter map containing the "key"-\>"value" pair. If `passwordCodec` is
not specified, the built-in decoder is used.
### Masking passwords in ActiveMQ Artemis ResourceAdapters and MDB activation configurations
Both ra.xml and MDB activation configuration have a 'password' property
that can be masked. They are controlled by the following two optional
Resource Adapter properties in ra.xml:
`UseMaskedPassword` -- If setting to "true" the passwords are masked.
Default is false.
`PasswordCodec` -- Class name and its parameters for the Decoder used to
decode the masked password. Ignored if UseMaskedPassword is false. The
format of this property is a full qualified class name optionally
followed by key/value pairs. It is the same format as that for JMS
Bridges. Example:
```xml
<config-property>
<config-property-name>UseMaskedPassword</config-property-name>
<config-property-type>boolean</config-property-type>
<config-property-value>true</config-property-value>
</config-property>
<config-property>
<config-property-name>PasswordCodec</config-property-name>
<config-property-type>java.lang.String</config-property-type>
<config-property-value>com.foo.ADecoder;key=helloworld</config-property-value>
</config-property>
```
With this configuration, both passwords in ra.xml and all of its MDBs
will have to be in masked form.
### Masking passwords in artemis-users.properties
Apache ActiveMQ Artemis's built-in security manager uses plain properties files
where the user passwords are specified in hash forms by default.
Please use Artemis CLI command to add a password. For example
```sh
./artemis user add --username guest --password guest --role admin
```
### Choosing a decoder for password masking
As described in the previous sections, all password masking requires a
decoder. A decoder uses an algorithm to convert a masked password into
its original clear text form in order to be used in various security
operations. The algorithm used for decoding must match that for
encoding. Otherwise the decoding may not be successful.
For user's convenience Apache ActiveMQ Artemis provides a default built-in Decoder.
However a user can if they so wish implement their own.
#### The built-in Decoder
Whenever no decoder is specified in the configuration file, the built-in
decoder is used. The class name for the built-in decoder is
org.apache.activemq.artemis.utils.DefaultSensitiveStringCodec. It has both
encoding and decoding capabilities. It uses java.crypto.Cipher utilities
to encrypt (encode) a plaintext password and decrypt a mask string using
same algorithm. Using this decoder/encoder is pretty straightforward. To
get a mask for a password, just run the main class at org.apache.activemq.artemis.utils.DefaultSensitiveStringCodec.
An easy way to do it is through activemq-tools-<VERSION>-jar-with-dependencies.jar since it has all the dependencies:
```sh
java -cp artemis-tools-1.0.0-jar-with-dependencies.jar org.apache.activemq.artemis.utils.DefaultSensitiveStringCodec "your plaintext password"
```
If you don't want to use the jar-with-dependencies, make sure the classpath is correct. You'll get something like
```
Encoded password: 80cf731af62c290
```
Just copy "80cf731af62c290" and replace your plaintext password with it.
#### Using a different decoder
It is possible to use a different decoder rather than the built-in one.
Simply make sure the decoder is in Apache ActiveMQ Artemis's classpath and configure
the server to use it as follows:
```xml
<password-codec>com.foo.SomeDecoder;key1=value1;key2=value2</password-codec>
```
If your decoder needs params passed to it you can do this via key/value
pairs when configuring. For instance if your decoder needs say a
"key-location" parameter, you can define like so:
```xml
<password-codec>com.foo.NewDecoder;key-location=/some/url/to/keyfile</password-codec>
```
Then configure your cluster-password like this:
```xml
<mask-password>true</mask-password>
<cluster-password>masked_password</cluster-password>
```
When Apache ActiveMQ Artemis reads the cluster-password it will initialize the
NewDecoder and use it to decode "mask\_password". It also process all
passwords using the new defined decoder.
#### Implementing your own codecs
To use a different decoder than the built-in one, you either pick one
from existing libraries or you implement it yourself. All decoders must
implement the `org.apache.activemq.artemis.utils.SensitiveDataCodec<T>`
interface:
``` java
public interface SensitiveDataCodec<T>
{
T decode(Object mask) throws Exception;
void init(Map<String, String> params);
}
```
This is a generic type interface but normally for a password you just
need String type. So a new decoder would be defined like
```java
public class MyNewDecoder implements SensitiveDataCodec<String>
{
public String decode(Object mask) throws Exception
{
//decode the mask into clear text password
return "the password";
}
public void init(Map<String, String> params)
{
//initialization done here. It is called right after the decoder has been created.
}
}
```
Last but not least, once you get your own decoder, please add it to the
classpath. Otherwise Apache ActiveMQ Artemis will fail to load it!
| apache-2.0 |
Jun1113/MapReduce-Example | docs/api/org/apache/hadoop/io/compress/bzip2/package-tree.html | 9144 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_26) on Tue Feb 14 08:16:36 UTC 2012 -->
<TITLE>
org.apache.hadoop.io.compress.bzip2 Class Hierarchy (Hadoop 1.0.1 API)
</TITLE>
<META NAME="date" CONTENT="2012-02-14">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.apache.hadoop.io.compress.bzip2 Class Hierarchy (Hadoop 1.0.1 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../org/apache/hadoop/io/compress/package-tree.html"><B>PREV</B></A>
<A HREF="../../../../../../org/apache/hadoop/io/compress/zlib/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/hadoop/io/compress/bzip2/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
Hierarchy For Package org.apache.hadoop.io.compress.bzip2
</H2>
</CENTER>
<DL>
<DT><B>Package Hierarchies:</B><DD><A HREF="../../../../../../overview-tree.html">All Packages</A></DL>
<HR>
<H2>
Class Hierarchy
</H2>
<UL>
<LI TYPE="circle">java.lang.<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><B>Object</B></A><UL>
<LI TYPE="circle">org.apache.hadoop.io.compress.bzip2.<A HREF="../../../../../../org/apache/hadoop/io/compress/bzip2/BZip2DummyCompressor.html" title="class in org.apache.hadoop.io.compress.bzip2"><B>BZip2DummyCompressor</B></A> (implements org.apache.hadoop.io.compress.<A HREF="../../../../../../org/apache/hadoop/io/compress/Compressor.html" title="interface in org.apache.hadoop.io.compress">Compressor</A>)
<LI TYPE="circle">org.apache.hadoop.io.compress.bzip2.<A HREF="../../../../../../org/apache/hadoop/io/compress/bzip2/BZip2DummyDecompressor.html" title="class in org.apache.hadoop.io.compress.bzip2"><B>BZip2DummyDecompressor</B></A> (implements org.apache.hadoop.io.compress.<A HREF="../../../../../../org/apache/hadoop/io/compress/Decompressor.html" title="interface in org.apache.hadoop.io.compress">Decompressor</A>)
<LI TYPE="circle">java.io.<A HREF="http://java.sun.com/javase/6/docs/api/java/io/InputStream.html?is-external=true" title="class or interface in java.io"><B>InputStream</B></A> (implements java.io.<A HREF="http://java.sun.com/javase/6/docs/api/java/io/Closeable.html?is-external=true" title="class or interface in java.io">Closeable</A>)
<UL>
<LI TYPE="circle">org.apache.hadoop.io.compress.bzip2.<A HREF="../../../../../../org/apache/hadoop/io/compress/bzip2/CBZip2InputStream.html" title="class in org.apache.hadoop.io.compress.bzip2"><B>CBZip2InputStream</B></A> (implements org.apache.hadoop.io.compress.bzip2.<A HREF="../../../../../../org/apache/hadoop/io/compress/bzip2/BZip2Constants.html" title="interface in org.apache.hadoop.io.compress.bzip2">BZip2Constants</A>)
</UL>
<LI TYPE="circle">java.io.<A HREF="http://java.sun.com/javase/6/docs/api/java/io/OutputStream.html?is-external=true" title="class or interface in java.io"><B>OutputStream</B></A> (implements java.io.<A HREF="http://java.sun.com/javase/6/docs/api/java/io/Closeable.html?is-external=true" title="class or interface in java.io">Closeable</A>, java.io.<A HREF="http://java.sun.com/javase/6/docs/api/java/io/Flushable.html?is-external=true" title="class or interface in java.io">Flushable</A>)
<UL>
<LI TYPE="circle">org.apache.hadoop.io.compress.bzip2.<A HREF="../../../../../../org/apache/hadoop/io/compress/bzip2/CBZip2OutputStream.html" title="class in org.apache.hadoop.io.compress.bzip2"><B>CBZip2OutputStream</B></A> (implements org.apache.hadoop.io.compress.bzip2.<A HREF="../../../../../../org/apache/hadoop/io/compress/bzip2/BZip2Constants.html" title="interface in org.apache.hadoop.io.compress.bzip2">BZip2Constants</A>)
</UL>
</UL>
</UL>
<H2>
Interface Hierarchy
</H2>
<UL>
<LI TYPE="circle">org.apache.hadoop.io.compress.bzip2.<A HREF="../../../../../../org/apache/hadoop/io/compress/bzip2/BZip2Constants.html" title="interface in org.apache.hadoop.io.compress.bzip2"><B>BZip2Constants</B></A></UL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../org/apache/hadoop/io/compress/package-tree.html"><B>PREV</B></A>
<A HREF="../../../../../../org/apache/hadoop/io/compress/zlib/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/hadoop/io/compress/bzip2/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2009 The Apache Software Foundation
</BODY>
</HTML>
| apache-2.0 |
apache/curator | curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ModelStage.java | 5444 | /**
* 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.curator.x.async.modeled.details;
import org.apache.curator.x.async.AsyncStage;
import org.apache.zookeeper.WatchedEvent;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Executor;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
class ModelStage<T> extends CompletableFuture<T> implements AsyncStage<T>
{
private final CompletionStage<WatchedEvent> event;
static <U> ModelStage<U> make()
{
return new ModelStage<>(null);
}
static <U> ModelStage<U> make(CompletionStage<WatchedEvent> event)
{
return new ModelStage<>(event);
}
static <U> ModelStage<U> completed(U value)
{
ModelStage<U> stage = new ModelStage<>(null);
stage.complete(value);
return stage;
}
static <U> ModelStage<U> exceptionally(Exception e)
{
ModelStage<U> stage = new ModelStage<>(null);
stage.completeExceptionally(e);
return stage;
}
static <U> ModelStage<U> async(Executor executor)
{
return new AsyncModelStage<>(executor);
}
static <U> ModelStage<U> asyncCompleted(U value, Executor executor)
{
ModelStage<U> stage = new AsyncModelStage<>(executor);
stage.complete(value);
return stage;
}
static <U> ModelStage<U> asyncExceptionally(Exception e, Executor executor)
{
ModelStage<U> stage = new AsyncModelStage<>(executor);
stage.completeExceptionally(e);
return stage;
}
@Override
public CompletionStage<WatchedEvent> event()
{
return event;
}
private ModelStage(CompletionStage<WatchedEvent> event)
{
this.event = event;
}
private static class AsyncModelStage<U> extends ModelStage<U>
{
private final Executor executor;
public AsyncModelStage(Executor executor)
{
super(null);
this.executor = executor;
}
@Override
public <U1> CompletableFuture<U1> thenApplyAsync(Function<? super U, ? extends U1> fn)
{
return super.thenApplyAsync(fn, executor);
}
@Override
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super U> action)
{
return super.thenAcceptAsync(action, executor);
}
@Override
public CompletableFuture<Void> thenRunAsync(Runnable action)
{
return super.thenRunAsync(action, executor);
}
@Override
public <U1, V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U1> other, BiFunction<? super U, ? super U1, ? extends V> fn)
{
return super.thenCombineAsync(other, fn, executor);
}
@Override
public <U1> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U1> other, BiConsumer<? super U, ? super U1> action)
{
return super.thenAcceptBothAsync(other, action, executor);
}
@Override
public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action)
{
return super.runAfterBothAsync(other, action, executor);
}
@Override
public <U1> CompletableFuture<U1> applyToEitherAsync(CompletionStage<? extends U> other, Function<? super U, U1> fn)
{
return super.applyToEitherAsync(other, fn, executor);
}
@Override
public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends U> other, Consumer<? super U> action)
{
return super.acceptEitherAsync(other, action, executor);
}
@Override
public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other, Runnable action)
{
return super.runAfterEitherAsync(other, action, executor);
}
@Override
public <U1> CompletableFuture<U1> thenComposeAsync(Function<? super U, ? extends CompletionStage<U1>> fn)
{
return super.thenComposeAsync(fn, executor);
}
@Override
public CompletableFuture<U> whenCompleteAsync(BiConsumer<? super U, ? super Throwable> action)
{
return super.whenCompleteAsync(action, executor);
}
@Override
public <U1> CompletableFuture<U1> handleAsync(BiFunction<? super U, Throwable, ? extends U1> fn)
{
return super.handleAsync(fn, executor);
}
}
}
| apache-2.0 |
googleapis/google-cloud-php-storage | tests/System/ManageBucketsTest.php | 9520 | <?php
/**
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Cloud\Storage\Tests\System;
use Google\Cloud\Core\Exception\BadRequestException;
use Google\Cloud\Storage\Bucket;
/**
* @group storage
* @group storage-bucket
*/
class ManageBucketsTest extends StorageTestCase
{
public function testListsBuckets()
{
$foundBuckets = [];
$bucketsToCreate = [
uniqid(self::TESTING_PREFIX),
uniqid(self::TESTING_PREFIX)
];
foreach ($bucketsToCreate as $bucketToCreate) {
self::createBucket(self::$client, $bucketToCreate);
}
$buckets = self::$client->buckets(['prefix' => self::TESTING_PREFIX]);
foreach ($buckets as $bucket) {
foreach ($bucketsToCreate as $key => $bucketToCreate) {
if ($bucket->name() === $bucketToCreate) {
$foundBuckets[$key] = $bucket->name();
}
}
}
$this->assertEquals($bucketsToCreate, $foundBuckets);
}
public function testCreatesBucket()
{
$name = uniqid(self::TESTING_PREFIX);
$options = [
'location' => 'ASIA',
'storageClass' => 'NEARLINE',
'versioning' => [
'enabled' => true
]
];
$this->assertFalse(self::$client->bucket($name)->exists());
$bucket = self::createBucket(self::$client, $name, $options);
$this->assertTrue(self::$client->bucket($name)->exists());
$this->assertEquals($name, $bucket->name());
$this->assertEquals($options['location'], $bucket->info()['location']);
$this->assertEquals($options['storageClass'], $bucket->info()['storageClass']);
$this->assertEquals($options['versioning'], $bucket->info()['versioning']);
$this->assertEquals('multi-region', $bucket->info()['locationType']);
}
public function testUpdateBucket()
{
$options = [
'website' => [
'mainPageSuffix' => 'index.html',
'notFoundPage' => '404.html'
]
];
$info = self::$bucket->update($options);
$this->assertEquals($options['website'], $info['website']);
}
/**
* @group storage-bucket-lifecycle
* @dataProvider lifecycleRules
*/
public function testCreateBucketWithLifecycleDeleteRule(array $rule, $isError = false)
{
if ($isError) {
$this->setExpectedException(BadRequestException::class);
}
$lifecycle = Bucket::lifecycle();
$lifecycle->addDeleteRule($rule);
$bucket = self::createBucket(self::$client, uniqid(self::TESTING_PREFIX), [
'lifecycle' => $lifecycle
]);
$this->assertEquals($lifecycle->toArray(), $bucket->info()['lifecycle']);
}
/**
* @group storage-bucket-lifecycle
* @dataProvider lifecycleRules
*/
public function testUpdateBucketWithLifecycleDeleteRule(array $rule, $isError = false)
{
if ($isError) {
$this->setExpectedException(BadRequestException::class);
}
$lifecycle = Bucket::lifecycle();
$lifecycle->addDeleteRule($rule);
$bucket = self::createBucket(self::$client, uniqid(self::TESTING_PREFIX));
$this->assertArrayNotHasKey('lifecycle', $bucket->info());
$bucket->update([
'lifecycle' => $lifecycle
]);
$this->assertEquals($lifecycle->toArray(), $bucket->info()['lifecycle']);
}
public function lifecycleRules()
{
return [
[['age' => 1000]],
[['daysSinceNoncurrentTime' => 25]],
[['daysSinceNoncurrentTime' => -5], true], // error case
[['daysSinceNoncurrentTime' => -5], true], // error case
[['noncurrentTimeBefore' => (new \DateTime)->format("Y-m-d")]],
[['noncurrentTimeBefore' => new \DateTime]],
[['noncurrentTimeBefore' => 'this is not a timestamp'], true], // error case
[['customTimeBefore' => (new \DateTime)->format("Y-m-d")]],
[['customTimeBefore' => new \DateTime]],
[['customTimeBefore' => 'this is not a timestamp'], true], // error case
];
}
/**
* @group storage-bucket-lifecycle
*/
public function testUpdateAndClearLifecycle()
{
$lifecycle = self::$bucket->currentLifecycle()
->addDeleteRule([
'age' => 500
]);
$info = self::$bucket->update(['lifecycle' => $lifecycle]);
$this->assertEquals($lifecycle->toArray(), $info['lifecycle']);
$lifecycle = self::$bucket->currentLifecycle()
->clearRules('Delete');
$info = self::$bucket->update(['lifecycle' => $lifecycle]);
$this->assertEmpty($lifecycle->toArray());
$this->assertArrayNotHasKey('lifecycle', $info);
}
public function testReloadBucket()
{
$this->assertEquals('storage#bucket', self::$bucket->reload()['kind']);
}
/**
* @group storageiam
*/
public function testIam()
{
$iam = self::$bucket->iam();
$policy = $iam->policy();
// pop the version off the resourceId to make the assertion below more robust.
$resourceId = explode('#', $policy['resourceId'])[0];
$bucketName = self::$bucket->name();
$this->assertEquals($resourceId, sprintf('projects/_/buckets/%s', $bucketName));
$role = 'roles/storage.admin';
$policy['bindings'][] = [
'role' => $role,
'members' => ['projectOwner:gcloud-php-integration-tests']
];
$iam->setPolicy($policy);
$policy = $iam->reload();
$newBinding = array_filter($policy['bindings'], function ($binding) use ($role) {
return ($binding['role'] === $role);
});
$this->assertCount(1, $newBinding);
$permissions = ['storage.buckets.get'];
$test = $iam->testPermissions($permissions);
$this->assertEquals($permissions, $test);
}
public function testLabels()
{
$bucket = self::$bucket;
$bucket->update([
'labels' => [
'foo' => 'bar'
]
]);
$bucket->reload();
$this->assertEquals($bucket->info()['labels']['foo'], 'bar');
$bucket->update([
'labels' => [
'foo' => 'bat'
]
]);
$bucket->reload();
$this->assertEquals($bucket->info()['labels']['foo'], 'bat');
$bucket->update([
'labels' => [
'foo' => null
]
]);
$bucket->reload();
$this->assertFalse(isset($bucket->info()['labels']['foo']));
}
/**
* @group storage-bucket-location
* @dataProvider locationTypes
*/
public function testBucketLocationType($storageClass, $location, $expectedLocationType, $updateStorageClass)
{
$bucketName = uniqid(self::TESTING_PREFIX);
$bucket = self::createBucket(self::$client, $bucketName, [
'storageClass' => $storageClass,
'location' => $location,
'retentionPolicy' => [
'retentionPeriod' => 1
]
]);
// Test create bucket response
$this->assertEquals($expectedLocationType, $bucket->info()['locationType']);
// Test get bucket response
$this->assertEquals($expectedLocationType, $bucket->reload()['locationType']);
// Test update bucket.
$bucket->update(['storageClass' => $updateStorageClass]);
$bucket->update(['storageClass' => $storageClass]);
$this->assertEquals($expectedLocationType, $bucket->info()['locationType']);
// Test list bucket response
$buckets = iterator_to_array(self::$client->buckets());
$listBucketBucket = current(array_filter($buckets, function ($bucket) use ($bucketName) {
return $bucket->name() === $bucketName;
}));
$this->assertEquals($expectedLocationType, $listBucketBucket->info()['locationType']);
// Test lock retention policy response
$bucket->lockRetentionPolicy();
$this->assertEquals($expectedLocationType, $bucket->info()['locationType']);
}
public function locationTypes()
{
return [
[
'STANDARD',
'us',
'multi-region',
'NEARLINE'
], [
'STANDARD',
'us-central1',
'region',
'NEARLINE'
], [
'COLDLINE',
'nam4',
'dual-region',
'STANDARD'
], [
'ARCHIVE',
'nam4',
'dual-region',
'STANDARD'
]
];
}
}
| apache-2.0 |
jdamick/denominator | core/src/test/java/denominator/DenominatorTest.java | 2477 | package denominator;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import dagger.ObjectGraph;
import denominator.mock.MockProvider;
import static org.assertj.core.api.Assertions.assertThat;
public class DenominatorTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void niceMessageWhenProviderNotFound() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("provider foo not in set of configured providers: [mock]");
Denominator.create("foo");
}
@Test
public void illegalArgumentWhenMissingModule() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("NoModuleProvider should have a static inner class named Module");
Denominator.create(new NoModuleProvider());
}
@Test
public void illegalArgumentWhenCtorHasArgs() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Module has a no-args constructor");
Denominator.create(new WrongCtorModuleProvider());
}
@Test
public void providerBindsProperly() {
Provider provider = Denominator.create(new FooProvider()).provider();
assertThat(provider).isEqualTo(new FooProvider());
}
@Test
@Deprecated
public void providerReturnsSameInstance() {
FooProvider provider = new FooProvider();
DNSApiManager
mgr =
ObjectGraph.create(Denominator.provider(provider), new FooProvider.Module()).get(
DNSApiManager.class);
assertThat(mgr.provider()).isSameAs(provider);
}
@Test
public void anonymousProviderPermitted() {
Provider provider = Denominator.create(new FooProvider() {
@Override
public String name() {
return "bar";
}
@Override
public String url() {
return "http://bar";
}
}).provider();
assertThat(provider.name()).isEqualTo("bar");
assertThat(provider.url()).isEqualTo("http://bar");
}
static class NoModuleProvider extends BasicProvider {
}
static class WrongCtorModuleProvider extends BasicProvider {
@dagger.Module(injects = DNSApiManager.class, includes = MockProvider.Module.class, complete = false)
static class Module {
Module(String name) {
}
}
}
static class FooProvider extends BasicProvider {
@dagger.Module(injects = DNSApiManager.class, includes = MockProvider.Module.class, complete = false)
static class Module {
}
}
}
| apache-2.0 |
jayantgolhar/Hadoop-0.21.0 | mapred/docs/api/org/apache/hadoop/examples/dancing/class-use/DistributedPentomino.PentMap.html | 6311 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_14) on Tue Aug 17 01:07:09 EDT 2010 -->
<TITLE>
Uses of Class org.apache.hadoop.examples.dancing.DistributedPentomino.PentMap (Hadoop-Mapred 0.21.0 API)
</TITLE>
<META NAME="date" CONTENT="2010-08-17">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.examples.dancing.DistributedPentomino.PentMap (Hadoop-Mapred 0.21.0 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/examples/dancing/DistributedPentomino.PentMap.html" title="class in org.apache.hadoop.examples.dancing"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/hadoop/examples/dancing//class-useDistributedPentomino.PentMap.html" target="_top"><B>FRAMES</B></A>
<A HREF="DistributedPentomino.PentMap.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.hadoop.examples.dancing.DistributedPentomino.PentMap</B></H2>
</CENTER>
No usage of org.apache.hadoop.examples.dancing.DistributedPentomino.PentMap
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/examples/dancing/DistributedPentomino.PentMap.html" title="class in org.apache.hadoop.examples.dancing"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/hadoop/examples/dancing//class-useDistributedPentomino.PentMap.html" target="_top"><B>FRAMES</B></A>
<A HREF="DistributedPentomino.PentMap.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2009 The Apache Software Foundation
</BODY>
</HTML>
| apache-2.0 |
jt70471/aws-sdk-cpp | aws-cpp-sdk-marketplace-entitlement/include/aws/marketplace-entitlement/model/Entitlement.h | 13956 | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/marketplace-entitlement/MarketplaceEntitlementService_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/marketplace-entitlement/model/EntitlementValue.h>
#include <aws/core/utils/DateTime.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace MarketplaceEntitlementService
{
namespace Model
{
/**
* <p>An entitlement represents capacity in a product owned by the customer. For
* example, a customer might own some number of users or seats in an SaaS
* application or some amount of data capacity in a multi-tenant
* database.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/entitlement.marketplace-2017-01-11/Entitlement">AWS
* API Reference</a></p>
*/
class AWS_MARKETPLACEENTITLEMENTSERVICE_API Entitlement
{
public:
Entitlement();
Entitlement(Aws::Utils::Json::JsonView jsonValue);
Entitlement& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The product code for which the given entitlement applies. Product codes are
* provided by AWS Marketplace when the product listing is created.</p>
*/
inline const Aws::String& GetProductCode() const{ return m_productCode; }
/**
* <p>The product code for which the given entitlement applies. Product codes are
* provided by AWS Marketplace when the product listing is created.</p>
*/
inline bool ProductCodeHasBeenSet() const { return m_productCodeHasBeenSet; }
/**
* <p>The product code for which the given entitlement applies. Product codes are
* provided by AWS Marketplace when the product listing is created.</p>
*/
inline void SetProductCode(const Aws::String& value) { m_productCodeHasBeenSet = true; m_productCode = value; }
/**
* <p>The product code for which the given entitlement applies. Product codes are
* provided by AWS Marketplace when the product listing is created.</p>
*/
inline void SetProductCode(Aws::String&& value) { m_productCodeHasBeenSet = true; m_productCode = std::move(value); }
/**
* <p>The product code for which the given entitlement applies. Product codes are
* provided by AWS Marketplace when the product listing is created.</p>
*/
inline void SetProductCode(const char* value) { m_productCodeHasBeenSet = true; m_productCode.assign(value); }
/**
* <p>The product code for which the given entitlement applies. Product codes are
* provided by AWS Marketplace when the product listing is created.</p>
*/
inline Entitlement& WithProductCode(const Aws::String& value) { SetProductCode(value); return *this;}
/**
* <p>The product code for which the given entitlement applies. Product codes are
* provided by AWS Marketplace when the product listing is created.</p>
*/
inline Entitlement& WithProductCode(Aws::String&& value) { SetProductCode(std::move(value)); return *this;}
/**
* <p>The product code for which the given entitlement applies. Product codes are
* provided by AWS Marketplace when the product listing is created.</p>
*/
inline Entitlement& WithProductCode(const char* value) { SetProductCode(value); return *this;}
/**
* <p>The dimension for which the given entitlement applies. Dimensions represent
* categories of capacity in a product and are specified when the product is listed
* in AWS Marketplace.</p>
*/
inline const Aws::String& GetDimension() const{ return m_dimension; }
/**
* <p>The dimension for which the given entitlement applies. Dimensions represent
* categories of capacity in a product and are specified when the product is listed
* in AWS Marketplace.</p>
*/
inline bool DimensionHasBeenSet() const { return m_dimensionHasBeenSet; }
/**
* <p>The dimension for which the given entitlement applies. Dimensions represent
* categories of capacity in a product and are specified when the product is listed
* in AWS Marketplace.</p>
*/
inline void SetDimension(const Aws::String& value) { m_dimensionHasBeenSet = true; m_dimension = value; }
/**
* <p>The dimension for which the given entitlement applies. Dimensions represent
* categories of capacity in a product and are specified when the product is listed
* in AWS Marketplace.</p>
*/
inline void SetDimension(Aws::String&& value) { m_dimensionHasBeenSet = true; m_dimension = std::move(value); }
/**
* <p>The dimension for which the given entitlement applies. Dimensions represent
* categories of capacity in a product and are specified when the product is listed
* in AWS Marketplace.</p>
*/
inline void SetDimension(const char* value) { m_dimensionHasBeenSet = true; m_dimension.assign(value); }
/**
* <p>The dimension for which the given entitlement applies. Dimensions represent
* categories of capacity in a product and are specified when the product is listed
* in AWS Marketplace.</p>
*/
inline Entitlement& WithDimension(const Aws::String& value) { SetDimension(value); return *this;}
/**
* <p>The dimension for which the given entitlement applies. Dimensions represent
* categories of capacity in a product and are specified when the product is listed
* in AWS Marketplace.</p>
*/
inline Entitlement& WithDimension(Aws::String&& value) { SetDimension(std::move(value)); return *this;}
/**
* <p>The dimension for which the given entitlement applies. Dimensions represent
* categories of capacity in a product and are specified when the product is listed
* in AWS Marketplace.</p>
*/
inline Entitlement& WithDimension(const char* value) { SetDimension(value); return *this;}
/**
* <p>The customer identifier is a handle to each unique customer in an
* application. Customer identifiers are obtained through the ResolveCustomer
* operation in AWS Marketplace Metering Service.</p>
*/
inline const Aws::String& GetCustomerIdentifier() const{ return m_customerIdentifier; }
/**
* <p>The customer identifier is a handle to each unique customer in an
* application. Customer identifiers are obtained through the ResolveCustomer
* operation in AWS Marketplace Metering Service.</p>
*/
inline bool CustomerIdentifierHasBeenSet() const { return m_customerIdentifierHasBeenSet; }
/**
* <p>The customer identifier is a handle to each unique customer in an
* application. Customer identifiers are obtained through the ResolveCustomer
* operation in AWS Marketplace Metering Service.</p>
*/
inline void SetCustomerIdentifier(const Aws::String& value) { m_customerIdentifierHasBeenSet = true; m_customerIdentifier = value; }
/**
* <p>The customer identifier is a handle to each unique customer in an
* application. Customer identifiers are obtained through the ResolveCustomer
* operation in AWS Marketplace Metering Service.</p>
*/
inline void SetCustomerIdentifier(Aws::String&& value) { m_customerIdentifierHasBeenSet = true; m_customerIdentifier = std::move(value); }
/**
* <p>The customer identifier is a handle to each unique customer in an
* application. Customer identifiers are obtained through the ResolveCustomer
* operation in AWS Marketplace Metering Service.</p>
*/
inline void SetCustomerIdentifier(const char* value) { m_customerIdentifierHasBeenSet = true; m_customerIdentifier.assign(value); }
/**
* <p>The customer identifier is a handle to each unique customer in an
* application. Customer identifiers are obtained through the ResolveCustomer
* operation in AWS Marketplace Metering Service.</p>
*/
inline Entitlement& WithCustomerIdentifier(const Aws::String& value) { SetCustomerIdentifier(value); return *this;}
/**
* <p>The customer identifier is a handle to each unique customer in an
* application. Customer identifiers are obtained through the ResolveCustomer
* operation in AWS Marketplace Metering Service.</p>
*/
inline Entitlement& WithCustomerIdentifier(Aws::String&& value) { SetCustomerIdentifier(std::move(value)); return *this;}
/**
* <p>The customer identifier is a handle to each unique customer in an
* application. Customer identifiers are obtained through the ResolveCustomer
* operation in AWS Marketplace Metering Service.</p>
*/
inline Entitlement& WithCustomerIdentifier(const char* value) { SetCustomerIdentifier(value); return *this;}
/**
* <p>The EntitlementValue represents the amount of capacity that the customer is
* entitled to for the product.</p>
*/
inline const EntitlementValue& GetValue() const{ return m_value; }
/**
* <p>The EntitlementValue represents the amount of capacity that the customer is
* entitled to for the product.</p>
*/
inline bool ValueHasBeenSet() const { return m_valueHasBeenSet; }
/**
* <p>The EntitlementValue represents the amount of capacity that the customer is
* entitled to for the product.</p>
*/
inline void SetValue(const EntitlementValue& value) { m_valueHasBeenSet = true; m_value = value; }
/**
* <p>The EntitlementValue represents the amount of capacity that the customer is
* entitled to for the product.</p>
*/
inline void SetValue(EntitlementValue&& value) { m_valueHasBeenSet = true; m_value = std::move(value); }
/**
* <p>The EntitlementValue represents the amount of capacity that the customer is
* entitled to for the product.</p>
*/
inline Entitlement& WithValue(const EntitlementValue& value) { SetValue(value); return *this;}
/**
* <p>The EntitlementValue represents the amount of capacity that the customer is
* entitled to for the product.</p>
*/
inline Entitlement& WithValue(EntitlementValue&& value) { SetValue(std::move(value)); return *this;}
/**
* <p>The expiration date represents the minimum date through which this
* entitlement is expected to remain valid. For contractual products listed on AWS
* Marketplace, the expiration date is the date at which the customer will renew or
* cancel their contract. Customers who are opting to renew their contract will
* still have entitlements with an expiration date.</p>
*/
inline const Aws::Utils::DateTime& GetExpirationDate() const{ return m_expirationDate; }
/**
* <p>The expiration date represents the minimum date through which this
* entitlement is expected to remain valid. For contractual products listed on AWS
* Marketplace, the expiration date is the date at which the customer will renew or
* cancel their contract. Customers who are opting to renew their contract will
* still have entitlements with an expiration date.</p>
*/
inline bool ExpirationDateHasBeenSet() const { return m_expirationDateHasBeenSet; }
/**
* <p>The expiration date represents the minimum date through which this
* entitlement is expected to remain valid. For contractual products listed on AWS
* Marketplace, the expiration date is the date at which the customer will renew or
* cancel their contract. Customers who are opting to renew their contract will
* still have entitlements with an expiration date.</p>
*/
inline void SetExpirationDate(const Aws::Utils::DateTime& value) { m_expirationDateHasBeenSet = true; m_expirationDate = value; }
/**
* <p>The expiration date represents the minimum date through which this
* entitlement is expected to remain valid. For contractual products listed on AWS
* Marketplace, the expiration date is the date at which the customer will renew or
* cancel their contract. Customers who are opting to renew their contract will
* still have entitlements with an expiration date.</p>
*/
inline void SetExpirationDate(Aws::Utils::DateTime&& value) { m_expirationDateHasBeenSet = true; m_expirationDate = std::move(value); }
/**
* <p>The expiration date represents the minimum date through which this
* entitlement is expected to remain valid. For contractual products listed on AWS
* Marketplace, the expiration date is the date at which the customer will renew or
* cancel their contract. Customers who are opting to renew their contract will
* still have entitlements with an expiration date.</p>
*/
inline Entitlement& WithExpirationDate(const Aws::Utils::DateTime& value) { SetExpirationDate(value); return *this;}
/**
* <p>The expiration date represents the minimum date through which this
* entitlement is expected to remain valid. For contractual products listed on AWS
* Marketplace, the expiration date is the date at which the customer will renew or
* cancel their contract. Customers who are opting to renew their contract will
* still have entitlements with an expiration date.</p>
*/
inline Entitlement& WithExpirationDate(Aws::Utils::DateTime&& value) { SetExpirationDate(std::move(value)); return *this;}
private:
Aws::String m_productCode;
bool m_productCodeHasBeenSet;
Aws::String m_dimension;
bool m_dimensionHasBeenSet;
Aws::String m_customerIdentifier;
bool m_customerIdentifierHasBeenSet;
EntitlementValue m_value;
bool m_valueHasBeenSet;
Aws::Utils::DateTime m_expirationDate;
bool m_expirationDateHasBeenSet;
};
} // namespace Model
} // namespace MarketplaceEntitlementService
} // namespace Aws
| apache-2.0 |
floodlight/loxigen-artifacts | openflowj/gen-src/main/java/org/projectfloodlight/openflow/protocol/ver15/OFGroupModVer15.java | 3873 | // Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_virtual_class.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver15;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import io.netty.buffer.ByteBuf;
abstract class OFGroupModVer15 {
// version: 1.5
final static byte WIRE_VERSION = 6;
final static int MINIMUM_LENGTH = 24;
public final static OFGroupModVer15.Reader READER = new Reader();
static class Reader implements OFMessageReader<OFGroupMod> {
@Override
public OFGroupMod readFrom(ByteBuf bb) throws OFParseError {
if(bb.readableBytes() < MINIMUM_LENGTH)
return null;
int start = bb.readerIndex();
// fixed value property version == 6
byte version = bb.readByte();
if(version != (byte) 0x6)
throw new OFParseError("Wrong version: Expected=OFVersion.OF_15(6), got="+version);
// fixed value property type == 15
byte type = bb.readByte();
if(type != (byte) 0xf)
throw new OFParseError("Wrong type: Expected=OFType.GROUP_MOD(15), got="+type);
int length = U16.f(bb.readShort());
if(length < MINIMUM_LENGTH)
throw new OFParseError("Wrong length: Expected to be >= " + MINIMUM_LENGTH + ", was: " + length);
U32.f(bb.readInt());
short command = bb.readShort();
bb.readerIndex(start);
switch(command) {
case (short) 0x0:
// discriminator value OFGroupModCommand.ADD=0 for class OFGroupAddVer15
return OFGroupAddVer15.READER.readFrom(bb);
case (short) 0x2:
// discriminator value OFGroupModCommand.DELETE=2 for class OFGroupDeleteVer15
return OFGroupDeleteVer15.READER.readFrom(bb);
case (short) 0x1:
// discriminator value OFGroupModCommand.MODIFY=1 for class OFGroupModifyVer15
return OFGroupModifyVer15.READER.readFrom(bb);
case (short) 0x3:
// discriminator value OFGroupModCommand.INSERT_BUCKET=3 for class OFGroupInsertBucketVer15
return OFGroupInsertBucketVer15.READER.readFrom(bb);
case (short) 0x5:
// discriminator value OFGroupModCommand.REMOVE_BUCKET=5 for class OFGroupRemoveBucketVer15
return OFGroupRemoveBucketVer15.READER.readFrom(bb);
default:
throw new OFParseError("Unknown value for discriminator command of class OFGroupModVer15: " + command);
}
}
}
}
| apache-2.0 |
liuyuanyuan/dbeaver | plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/registry/formatter/DataFormatterProfile.java | 8702 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2019 Serge Rider ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.registry.formatter;
import org.jkiss.dbeaver.model.data.DBDDataFormatter;
import org.jkiss.dbeaver.model.data.DBDDataFormatterProfile;
import org.jkiss.dbeaver.model.impl.preferences.SimplePreferenceStore;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceListener;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore;
import org.jkiss.dbeaver.model.preferences.DBPPropertyDescriptor;
import org.jkiss.dbeaver.model.struct.DBSTypedObject;
import org.jkiss.dbeaver.utils.PrefUtils;
import org.jkiss.utils.CommonUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* DataFormatterProfile
*/
public class DataFormatterProfile implements DBDDataFormatterProfile, DBPPreferenceListener {
private static final String PROP_LANGUAGE = "dataformat.profile.language"; //$NON-NLS-1$
private static final String PROP_COUNTRY = "dataformat.profile.country"; //$NON-NLS-1$
private static final String PROP_VARIANT = "dataformat.profile.variant"; //$NON-NLS-1$
public static final String DATAFORMAT_PREFIX = "dataformat."; //$NON-NLS-1$
public static final String DATAFORMAT_TYPE_PREFIX = DATAFORMAT_PREFIX + "type."; //$NON-NLS-1$
private DBPPreferenceStore store;
private String name;
private Locale locale;
public DataFormatterProfile(String profileName, DBPPreferenceStore store)
{
this.name = profileName;
this.store = store;
loadProfile();
}
private void loadProfile()
{
{
String language = store.getString(PROP_LANGUAGE);
String country = store.getString(PROP_COUNTRY);
String variant = store.getString(PROP_VARIANT);
if (CommonUtils.isEmpty(language)) {
this.locale = Locale.getDefault();
} else if (CommonUtils.isEmpty(country)) {
this.locale = new Locale(language);
} else if (CommonUtils.isEmpty(variant)) {
this.locale = new Locale(language, country);
} else {
this.locale = new Locale(language, country, variant);
}
}
}
@Override
public void saveProfile() throws IOException
{
store.setValue(PROP_LANGUAGE, locale.getLanguage());
store.setValue(PROP_COUNTRY, locale.getCountry());
store.setValue(PROP_VARIANT, locale.getVariant());
PrefUtils.savePreferenceStore(store);
}
@Override
public DBPPreferenceStore getPreferenceStore()
{
return store;
}
@Override
public String getProfileName()
{
return name;
}
@Override
public void setProfileName(String name)
{
this.name = name;
}
@Override
public Locale getLocale()
{
return locale;
}
@Override
public void setLocale(Locale locale)
{
this.locale = locale;
}
@Override
public Map<Object, Object> getFormatterProperties(String typeId)
{
DataFormatterDescriptor formatter = DataFormatterRegistry.getInstance().getDataFormatter(typeId);
Map<Object, Object> defaultProperties = formatter.getSample().getDefaultProperties(locale);
Map<Object, Object> formatterProps = new HashMap<>();
for (DBPPropertyDescriptor prop : formatter.getProperties()) {
Object defaultValue = defaultProperties.get(prop.getId());
Object propValue = PrefUtils.getPreferenceValue(
store,
DATAFORMAT_TYPE_PREFIX + formatter.getId() + "." + prop.getId(), prop.getDataType());
if (propValue != null && !CommonUtils.equalObjects(defaultValue, propValue)) {
formatterProps.put(prop.getId(), propValue);
}
}
return formatterProps;
}
@Override
public void setFormatterProperties(String typeId, Map<Object, Object> formatterProps)
{
DataFormatterDescriptor formatter = DataFormatterRegistry.getInstance().getDataFormatter(typeId);
for (DBPPropertyDescriptor prop : formatter.getProperties()) {
Object propValue = formatterProps == null ? null : formatterProps.get(prop.getId());
if (propValue != null) {
PrefUtils.setPreferenceValue(store, DATAFORMAT_TYPE_PREFIX + formatter.getId() + "." + prop.getId(), propValue);
} else {
store.setToDefault(DATAFORMAT_TYPE_PREFIX + formatter.getId() + "." + prop.getId());
}
}
}
@Override
public boolean isOverridesParent()
{
if (store instanceof SimplePreferenceStore) {
SimplePreferenceStore prefStore = (SimplePreferenceStore) store;
if (prefStore.isSet(PROP_LANGUAGE) || prefStore.isSet(PROP_COUNTRY) || prefStore.isSet(PROP_VARIANT)) {
return true;
}
for (DataFormatterDescriptor formatter : DataFormatterRegistry.getInstance().getDataFormatters()) {
for (DBPPropertyDescriptor prop : formatter.getProperties()) {
if (prefStore.isSet(DATAFORMAT_TYPE_PREFIX + formatter.getId() + "." + prop.getId())) {
return true;
}
}
}
return false;
}
return true;
}
@Override
public void reset()
{
if (store instanceof SimplePreferenceStore) {
// Set all formatter properties to default
store.setToDefault(PROP_LANGUAGE);
store.setToDefault(PROP_COUNTRY);
store.setToDefault(PROP_VARIANT);
for (DataFormatterDescriptor formatter : DataFormatterRegistry.getInstance().getDataFormatters()) {
for (DBPPropertyDescriptor prop : formatter.getProperties()) {
store.setToDefault(DATAFORMAT_TYPE_PREFIX + formatter.getId() + "." + prop.getId());
}
}
}
loadProfile();
}
@Override
public DBDDataFormatter createFormatter(String typeId, DBSTypedObject type)
throws IllegalAccessException, InstantiationException, IllegalArgumentException
{
DataFormatterDescriptor descriptor = DataFormatterRegistry.getInstance().getDataFormatter(typeId);
if (descriptor == null) {
throw new IllegalArgumentException("Formatter '" + typeId + "' not found");
}
DBDDataFormatter formatter = descriptor.createFormatter();
Map<Object, Object> defProps = descriptor.getSample().getDefaultProperties(locale);
Map<Object, Object> props = getFormatterProperties(typeId);
Map<Object, Object> formatterProps = new HashMap<>();
if (defProps != null && !defProps.isEmpty()) {
formatterProps.putAll(defProps);
}
if (props != null && !props.isEmpty()) {
formatterProps.putAll(props);
}
formatter.init(type, locale, formatterProps);
return formatter;
}
public static void initDefaultPreferences(DBPPreferenceStore store, Locale locale)
{
for (DataFormatterDescriptor formatter : DataFormatterRegistry.getInstance().getDataFormatters()) {
Map<Object, Object> defaultProperties = formatter.getSample().getDefaultProperties(locale);
Map<Object, Object> formatterProps = new HashMap<>();
for (DBPPropertyDescriptor prop : formatter.getProperties()) {
Object defaultValue = defaultProperties.get(prop.getId());
if (defaultValue != null) {
PrefUtils.setPreferenceDefaultValue(store, DATAFORMAT_TYPE_PREFIX + formatter.getId() + "." + prop.getId(), defaultValue);
}
}
}
}
@Override
public void preferenceChange(PreferenceChangeEvent event) {
if (event.getProperty() != null && event.getProperty().startsWith(DATAFORMAT_PREFIX)) {
// Reload this profile
loadProfile();
}
}
}
| apache-2.0 |
MaxRau/CoffeeMud | com/planet_ink/coffee_mud/Races/GiantAmphibian.java | 2689 | package com.planet_ink.coffee_mud.Races;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2004-2015 Bo Zimmerman
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.
*/
public class GiantAmphibian extends GreatAmphibian
{
@Override public String ID(){ return "GiantAmphibian"; }
@Override public String name(){ return "Giant Amphibian"; }
@Override public int shortestMale(){return 50;}
@Override public int shortestFemale(){return 55;}
@Override public int heightVariance(){return 20;}
@Override public int lightestWeight(){return 1955;}
@Override public int weightVariance(){return 405;}
@Override public long forbiddenWornBits(){return ~(Wearable.WORN_EYES);}
@Override public String racialCategory(){return "Amphibian";}
protected static Vector<RawMaterial> resources=new Vector<RawMaterial>();
@Override
public List<RawMaterial> myResources()
{
synchronized(resources)
{
if(resources.size()==0)
{
for(int i=0;i<25;i++)
resources.addElement(makeResource
("some "+name().toLowerCase(),RawMaterial.RESOURCE_FISH));
for(int i=0;i<15;i++)
resources.addElement(makeResource
("a "+name().toLowerCase()+" hide",RawMaterial.RESOURCE_HIDE));
resources.addElement(makeResource
("some "+name().toLowerCase()+" blood",RawMaterial.RESOURCE_BLOOD));
}
}
return resources;
}
}
| apache-2.0 |
subaan/display | app/controllers/catalog/platforms_controller.rb | 991 | class Catalog::PlatformsController < Base::PlatformsController
before_filter :find_catalog_and_platform
def index
@platforms = Cms::Relation.all(:params => {:ciId => @catalog.ciId,
:direction => 'from',
:targetClassName => 'catalog.Platform',
:relatioShortnName => 'ComposedOf'}).map(&:toCi)
render :json => @platforms
end
private
def find_catalog_and_platform
@catalog = Cms::Ci.locate(params[:catalog_id], catalogs_ns_path, 'account.Design') ||
Cms::Ci.locate(params[:catalog_id], private_catalogs_ns_path, 'account.Design')
platform_id = params[:id]
if platform_id.present?
@platform = Cms::Ci.locate(platform_id, catalog_ns_path(@catalog), 'catalog.Platform')
@platform = nil if @platform && @platform.ciClassName != 'catalog.Platform'
end
end
end
| apache-2.0 |
adragomir/dcos-commons | sdk/scheduler/src/main/java/com/mesosphere/sdk/specification/yaml/RawPort.java | 682 | package com.mesosphere.sdk.specification.yaml;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Raw YAML port.
*/
public class RawPort {
private final Integer port;
private final String envKey;
private final RawVip vip;
private RawPort(
@JsonProperty("port") Integer port,
@JsonProperty("env-key") String envKey,
@JsonProperty("vip") RawVip vip) {
this.port = port;
this.envKey = envKey;
this.vip = vip;
}
public Integer getPort() {
return port;
}
public String getEnvKey() {
return envKey;
}
public RawVip getVip() {
return vip;
}
}
| apache-2.0 |
barakb/gigaspaces-wiki-jekyll | xap101adm/visualizing-cluster-groups-and-members---gigaspaces-browser.markdown | 2305 | ---
layout: post101
title: Groups and Members
categories: XAP101ADM
parent: cluster-view---gigaspaces-browser.html
weight: 400
---
{% summary %}Viewing clustered groups, clustered spaces and URLs, and accessing information views for a clustered space.{% endsummary %}
When you click the cluster node in the Cluster Tree, the visual display area shows groups as gray ovals, while the information panel shows the names and URLs of members.
# Visualizing Cluster Groups
Groups are structures within a cluster that define the relationship between spaces. A group may have one or more of the following attributes: replication, failover and load-balancing. For two spaces to maintain a replication link, for example, both must belong to a replication group. A cluster must have at least one group, and spaces may not belong to more than one group.
Each group shown in the visual display area has two lines of text. The first line is the group's name (or the beginning of the name, followed by an ellipsis). The second line shows the group's attributes, using abbreviations denoted in the legend.
You can move the groups around by clicking and dragging them; this has no effect on the cluster configuration. Double-clicking a group has the same effect as clicking its name in the **Cluster Tree**.
# Viewing Clustered Spaces and URLs
When the cluster node is selected, the information panel shows the names of all cluster members, their direct URLs and Primary/Backup indication.
# Accessing Information Views for a Clustered Space
A space has five information views, which appear under the space node in the Grid Tree. To access these views, right-click the space you want to view in the Cluster view's visual display:
{% indent %}

{% endindent %}
From the context menu, select one of the options to access one of the space information views:
- [Query view](./gigaspaces-browser-query-view.html)
- [Statistics view](./gigaspaces-browser-statistics-view.html)
- [Benchmark view](./gigaspaces-browser-benchmark-view.html)
- [Transactions view](./gigaspaces-browser-transaction-view.html)
- [Date Types](./gigaspaces-browser-data-types-view.html)
| apache-2.0 |
gomex/devopsdays-web | content/events/2019-raleigh/speakers/ricardo-green.md | 796 | +++
Title = "Ricardo Green"
Twitter = "RicardoWins"
image = "ricardo-green.png"
type = "speaker"
linktitle = "ricardo-green"
+++
Ricardo Green is a cloud technology evangelist and senior solutions architect with Fugue. Prior to joining Fugue, he worked in the cloud business unit of a major telecommunications company serving as a managed hosting and cloud computing specialist. He later served as a solutions architect, supporting the company's managed services offerings on AWS. Ricardo has been in the cloud and managed hosting space for more than 10 years, with the last six focused on cloud architecture. Ricardo has multiple AWS certifications and brings his passion for cloud technology to Fugue where he supports efforts in increasing the adoption of Fugue in enterprise organizations.
| apache-2.0 |
linzhaoming/origin | vendor/github.com/Azure/azure-sdk-for-go/services/cognitiveservices/v1.0/customimagesearch/client.go | 1734 | // Package customimagesearch implements the Azure ARM Customimagesearch service API version 1.0.
//
// The Bing Custom Image Search API lets you send an image search query to Bing and get back image search results
// customized to meet your custom search definition.
package customimagesearch
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
)
const (
// DefaultBaseURI is the default URI used for the service Customimagesearch
DefaultBaseURI = "https://api.cognitive.microsoft.com/bingcustomsearch/v7.0"
)
// BaseClient is the base client for Customimagesearch.
type BaseClient struct {
autorest.Client
BaseURI string
}
// New creates an instance of the BaseClient client.
func New() BaseClient {
return NewWithBaseURI(DefaultBaseURI)
}
// NewWithBaseURI creates an instance of the BaseClient client.
func NewWithBaseURI(baseURI string) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
}
}
| apache-2.0 |
aidanhs/blockade | blockade/tests/__init__.py | 731 | #
# Copyright (C) 2014 Dell, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import sys
PYTHON26 = sys.version_info < (2, 7)
if PYTHON26:
import unittest2 as unittest
else:
import unittest
__all__ = ['unittest']
| apache-2.0 |
tboyce021/home-assistant | tests/components/fan/test_init.py | 781 | """Tests for fan platforms."""
import pytest
from homeassistant.components.fan import FanEntity
class BaseFan(FanEntity):
"""Implementation of the abstract FanEntity."""
def __init__(self):
"""Initialize the fan."""
def test_fanentity():
"""Test fan entity methods."""
fan = BaseFan()
assert fan.state == "off"
assert len(fan.speed_list) == 0
assert fan.supported_features == 0
assert fan.capability_attributes == {}
# Test set_speed not required
with pytest.raises(NotImplementedError):
fan.oscillate(True)
with pytest.raises(NotImplementedError):
fan.set_speed("slow")
with pytest.raises(NotImplementedError):
fan.turn_on()
with pytest.raises(NotImplementedError):
fan.turn_off()
| apache-2.0 |
thrust/thrust | thrust/detail/complex/arithmetic.h | 7395 | /*
* Copyright 2008-2013 NVIDIA Corporation
* Copyright 2013 Filipe RNC Maia
*
* 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 <thrust/complex.h>
#include <cfloat>
#include <cmath>
#include <thrust/detail/complex/c99math.h>
namespace thrust
{
/* --- Binary Arithmetic Operators --- */
template <typename T0, typename T1>
__host__ __device__
complex<typename detail::promoted_numerical_type<T0, T1>::type>
operator+(const complex<T0>& x, const complex<T1>& y)
{
typedef typename detail::promoted_numerical_type<T0, T1>::type T;
return complex<T>(x.real() + y.real(), x.imag() + y.imag());
}
template <typename T0, typename T1>
__host__ __device__
complex<typename detail::promoted_numerical_type<T0, T1>::type>
operator+(const complex<T0>& x, const T1& y)
{
typedef typename detail::promoted_numerical_type<T0, T1>::type T;
return complex<T>(x.real() + y, x.imag());
}
template <typename T0, typename T1>
__host__ __device__
complex<typename detail::promoted_numerical_type<T0, T1>::type>
operator+(const T0& x, const complex<T1>& y)
{
typedef typename detail::promoted_numerical_type<T0, T1>::type T;
return complex<T>(x + y.real(), y.imag());
}
template <typename T0, typename T1>
__host__ __device__
complex<typename detail::promoted_numerical_type<T0, T1>::type>
operator-(const complex<T0>& x, const complex<T1>& y)
{
typedef typename detail::promoted_numerical_type<T0, T1>::type T;
return complex<T>(x.real() - y.real(), x.imag() - y.imag());
}
template <typename T0, typename T1>
__host__ __device__
complex<typename detail::promoted_numerical_type<T0, T1>::type>
operator-(const complex<T0>& x, const T1& y)
{
typedef typename detail::promoted_numerical_type<T0, T1>::type T;
return complex<T>(x.real() - y, x.imag());
}
template <typename T0, typename T1>
__host__ __device__
complex<typename detail::promoted_numerical_type<T0, T1>::type>
operator-(const T0& x, const complex<T1>& y)
{
typedef typename detail::promoted_numerical_type<T0, T1>::type T;
return complex<T>(x - y.real(), -y.imag());
}
template <typename T0, typename T1>
__host__ __device__
complex<typename detail::promoted_numerical_type<T0, T1>::type>
operator*(const complex<T0>& x, const complex<T1>& y)
{
typedef typename detail::promoted_numerical_type<T0, T1>::type T;
return complex<T>( x.real() * y.real() - x.imag() * y.imag()
, x.real() * y.imag() + x.imag() * y.real());
}
template <typename T0, typename T1>
__host__ __device__
complex<typename detail::promoted_numerical_type<T0, T1>::type>
operator*(const complex<T0>& x, const T1& y)
{
typedef typename detail::promoted_numerical_type<T0, T1>::type T;
return complex<T>(x.real() * y, x.imag() * y);
}
template <typename T0, typename T1>
__host__ __device__
complex<typename detail::promoted_numerical_type<T0, T1>::type>
operator*(const T0& x, const complex<T1>& y)
{
typedef typename detail::promoted_numerical_type<T0, T1>::type T;
return complex<T>(x * y.real(), x * y.imag());
}
template <typename T0, typename T1>
__host__ __device__
complex<typename detail::promoted_numerical_type<T0, T1>::type>
operator/(const complex<T0>& x, const complex<T1>& y)
{
typedef typename detail::promoted_numerical_type<T0, T1>::type T;
// Find `abs` by ADL.
using std::abs;
T s = abs(y.real()) + abs(y.imag());
T oos = T(1.0) / s;
T ars = x.real() * oos;
T ais = x.imag() * oos;
T brs = y.real() * oos;
T bis = y.imag() * oos;
s = (brs * brs) + (bis * bis);
oos = T(1.0) / s;
complex<T> quot( ((ars * brs) + (ais * bis)) * oos
, ((ais * brs) - (ars * bis)) * oos);
return quot;
}
template <typename T0, typename T1>
__host__ __device__
complex<typename detail::promoted_numerical_type<T0, T1>::type>
operator/(const complex<T0>& x, const T1& y)
{
typedef typename detail::promoted_numerical_type<T0, T1>::type T;
return complex<T>(x.real() / y, x.imag() / y);
}
template <typename T0, typename T1>
__host__ __device__
complex<typename detail::promoted_numerical_type<T0, T1>::type>
operator/(const T0& x, const complex<T1>& y)
{
typedef typename detail::promoted_numerical_type<T0, T1>::type T;
return complex<T>(x) / y;
}
/* --- Unary Arithmetic Operators --- */
template <typename T>
__host__ __device__
complex<T> operator+(const complex<T>& y)
{
return y;
}
template <typename T>
__host__ __device__
complex<T> operator-(const complex<T>& y)
{
return y * -T(1);
}
/* --- Other Basic Arithmetic Functions --- */
// As std::hypot is only C++11 we have to use the C interface
template <typename T>
__host__ __device__
T abs(const complex<T>& z)
{
return hypot(z.real(), z.imag());
}
// XXX Why are we specializing here?
namespace detail {
namespace complex {
__host__ __device__
inline float abs(const thrust::complex<float>& z)
{
return hypotf(z.real(),z.imag());
}
__host__ __device__
inline double abs(const thrust::complex<double>& z)
{
return hypot(z.real(),z.imag());
}
} // end namespace complex
} // end namespace detail
template <>
__host__ __device__
inline float abs(const complex<float>& z)
{
return detail::complex::abs(z);
}
template <>
__host__ __device__
inline double abs(const complex<double>& z)
{
return detail::complex::abs(z);
}
template <typename T>
__host__ __device__
T arg(const complex<T>& z)
{
// Find `atan2` by ADL.
using std::atan2;
return atan2(z.imag(), z.real());
}
template <typename T>
__host__ __device__
complex<T> conj(const complex<T>& z)
{
return complex<T>(z.real(), -z.imag());
}
template <typename T>
__host__ __device__
T norm(const complex<T>& z)
{
return z.real() * z.real() + z.imag() * z.imag();
}
// XXX Why specialize these, we could just rely on ADL.
template <>
__host__ __device__
inline float norm(const complex<float>& z)
{
// Find `abs` and `sqrt` by ADL.
using std::abs;
using std::sqrt;
if (abs(z.real()) < sqrt(FLT_MIN) && abs(z.imag()) < sqrt(FLT_MIN))
{
float a = z.real() * 4.0f;
float b = z.imag() * 4.0f;
return (a * a + b * b) / 16.0f;
}
return z.real() * z.real() + z.imag() * z.imag();
}
template <>
__host__ __device__
inline double norm(const complex<double>& z)
{
// Find `abs` and `sqrt` by ADL.
using std::abs;
using std::sqrt;
if (abs(z.real()) < sqrt(DBL_MIN) && abs(z.imag()) < sqrt(DBL_MIN))
{
double a = z.real() * 4.0;
double b = z.imag() * 4.0;
return (a * a + b * b) / 16.0;
}
return z.real() * z.real() + z.imag() * z.imag();
}
template <typename T0, typename T1>
__host__ __device__
complex<typename detail::promoted_numerical_type<T0, T1>::type>
polar(const T0& m, const T1& theta)
{
typedef typename detail::promoted_numerical_type<T0, T1>::type T;
// Find `cos` and `sin` by ADL.
using std::cos;
using std::sin;
return complex<T>(m * cos(theta), m * sin(theta));
}
} // end namespace thrust
| apache-2.0 |
hnafar/IronJS | Src/Tests/ietestcenter/chapter15/15.10/15.10.4/15.10.4.1-2.js | 2097 | /// Copyright (c) 2009 Microsoft Corporation
///
/// Redistribution and use in source and binary forms, with or without modification, are permitted provided
/// that the following conditions are met:
/// * Redistributions of source code must retain the above copyright notice, this list of conditions and
/// the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
/// the following disclaimer in the documentation and/or other materials provided with the distribution.
/// * Neither the name of Microsoft nor the names of its contributors may be used to
/// endorse or promote products derived from this software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
/// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
/// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
/// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
/// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
/// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
/// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
ES5Harness.registerTest({
id: "15.10.4.1-2",
path: "TestCases/chapter15/15.10/15.10.4/15.10.4.1-2.js",
description: "RegExp - the thrown error is SyntaxError instead of RegExpError when the characters of 'P' do not have the syntactic form Pattern",
test: function testcase() {
try {
var regExpObj = new RegExp('\\');
return false;
} catch (e) {
return e instanceof SyntaxError;
}
},
precondition: function prereq() {
return true;
}
});
| apache-2.0 |
leafclick/intellij-community | plugins/textmate/lib/bundles/git/src/statusbar.ts | 5303 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Disposable, Command, EventEmitter, Event, workspace, Uri } from 'vscode';
import { Repository, Operation } from './repository';
import { anyEvent, dispose, filterEvent } from './util';
import * as nls from 'vscode-nls';
import { Branch } from './api/git';
const localize = nls.loadMessageBundle();
class CheckoutStatusBar {
private _onDidChange = new EventEmitter<void>();
get onDidChange(): Event<void> { return this._onDidChange.event; }
private disposables: Disposable[] = [];
constructor(private repository: Repository) {
repository.onDidRunGitStatus(this._onDidChange.fire, this._onDidChange, this.disposables);
}
get command(): Command | undefined {
const rebasing = !!this.repository.rebaseCommit;
const title = `$(git-branch) ${this.repository.headLabel}${rebasing ? ` (${localize('rebasing', 'Rebasing')})` : ''}`;
return {
command: 'git.checkout',
tooltip: `${this.repository.headLabel}`,
title,
arguments: [this.repository.sourceControl]
};
}
dispose(): void {
this.disposables.forEach(d => d.dispose());
}
}
interface SyncStatusBarState {
enabled: boolean;
isSyncRunning: boolean;
hasRemotes: boolean;
HEAD: Branch | undefined;
}
class SyncStatusBar {
private static StartState: SyncStatusBarState = {
enabled: true,
isSyncRunning: false,
hasRemotes: false,
HEAD: undefined
};
private _onDidChange = new EventEmitter<void>();
get onDidChange(): Event<void> { return this._onDidChange.event; }
private disposables: Disposable[] = [];
private _state: SyncStatusBarState = SyncStatusBar.StartState;
private get state() { return this._state; }
private set state(state: SyncStatusBarState) {
this._state = state;
this._onDidChange.fire();
}
constructor(private repository: Repository) {
repository.onDidRunGitStatus(this.onModelChange, this, this.disposables);
repository.onDidChangeOperations(this.onOperationsChange, this, this.disposables);
const onEnablementChange = filterEvent(workspace.onDidChangeConfiguration, e => e.affectsConfiguration('git.enableStatusBarSync'));
onEnablementChange(this.updateEnablement, this, this.disposables);
this.updateEnablement();
this._onDidChange.fire();
}
private updateEnablement(): void {
const config = workspace.getConfiguration('git', Uri.file(this.repository.root));
const enabled = config.get<boolean>('enableStatusBarSync', true);
this.state = { ... this.state, enabled };
}
private onOperationsChange(): void {
const isSyncRunning = this.repository.operations.isRunning(Operation.Sync) ||
this.repository.operations.isRunning(Operation.Push) ||
this.repository.operations.isRunning(Operation.Pull);
this.state = { ...this.state, isSyncRunning };
}
private onModelChange(): void {
this.state = {
...this.state,
hasRemotes: this.repository.remotes.length > 0,
HEAD: this.repository.HEAD
};
}
get command(): Command | undefined {
if (!this.state.enabled || !this.state.hasRemotes) {
return undefined;
}
const HEAD = this.state.HEAD;
let icon = '$(sync)';
let text = '';
let command = '';
let tooltip = '';
if (HEAD && HEAD.name && HEAD.commit) {
if (HEAD.upstream) {
if (HEAD.ahead || HEAD.behind) {
text += this.repository.syncLabel;
}
const config = workspace.getConfiguration('git', Uri.file(this.repository.root));
const rebaseWhenSync = config.get<string>('rebaseWhenSync');
command = rebaseWhenSync ? 'git.syncRebase' : 'git.sync';
tooltip = localize('sync changes', "Synchronize Changes");
} else {
icon = '$(cloud-upload)';
command = 'git.publish';
tooltip = localize('publish changes', "Publish Changes");
}
} else {
command = '';
tooltip = '';
}
if (this.state.isSyncRunning) {
icon = '$(sync~spin)';
command = '';
tooltip = localize('syncing changes', "Synchronizing Changes...");
}
return {
command,
title: [icon, text].join(' ').trim(),
tooltip,
arguments: [this.repository.sourceControl]
};
}
dispose(): void {
this.disposables.forEach(d => d.dispose());
}
}
export class StatusBarCommands {
private syncStatusBar: SyncStatusBar;
private checkoutStatusBar: CheckoutStatusBar;
private disposables: Disposable[] = [];
constructor(repository: Repository) {
this.syncStatusBar = new SyncStatusBar(repository);
this.checkoutStatusBar = new CheckoutStatusBar(repository);
}
get onDidChange(): Event<void> {
return anyEvent(
this.syncStatusBar.onDidChange,
this.checkoutStatusBar.onDidChange
);
}
get commands(): Command[] {
const result: Command[] = [];
const checkout = this.checkoutStatusBar.command;
if (checkout) {
result.push(checkout);
}
const sync = this.syncStatusBar.command;
if (sync) {
result.push(sync);
}
return result;
}
dispose(): void {
this.syncStatusBar.dispose();
this.checkoutStatusBar.dispose();
this.disposables = dispose(this.disposables);
}
}
| apache-2.0 |
davinwang/caffe2 | docker/ubuntu-16.04-cpu-minimal/Dockerfile | 1104 | FROM ubuntu:16.04
LABEL maintainer="[email protected]"
# caffe2 install with cpu support
########## REQUIRED DEPENDENCIES ################
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential \
cmake \
curl \
git \
libgoogle-glog-dev \
libprotobuf-dev \
python-pip \
protobuf-compiler \
python-dev \
&& rm -rf /var/lib/apt/lists/*
# Don't use deb package because trusty's pip is too old for --no-cache-dir
RUN curl -O https://bootstrap.pypa.io/get-pip.py \
&& python get-pip.py \
&& rm get-pip.py
RUN pip install --no-cache-dir --upgrade pip setuptools wheel
RUN pip install --no-cache-dir future hypothesis numpy protobuf six
########## INSTALLATION STEPS ###################
RUN git clone --branch v0.8.1 --recursive https://github.com/caffe2/caffe2.git
RUN cd caffe2 && mkdir build && cd build \
&& cmake .. \
-DUSE_CUDA=OFF \
-DUSE_NNPACK=OFF \
-DUSE_ROCKSDB=OFF \
&& make -j"$(nproc)" install \
&& ldconfig \
&& make clean \
&& cd .. \
&& rm -rf build
ENV PYTHONPATH /usr/local
| apache-2.0 |
charliemblack/geode | geode-core/src/test/java/org/apache/geode/distributed/LocatorLauncherIntegrationTestCase.java | 5865 | /*
* 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.geode.distributed;
import static java.util.concurrent.TimeUnit.MINUTES;
import static org.apache.geode.distributed.AbstractLauncher.Status.STOPPED;
import static org.apache.geode.distributed.ConfigurationProperties.CLUSTER_CONFIGURATION_DIR;
import static org.apache.geode.distributed.ConfigurationProperties.DISABLE_AUTO_RECONNECT;
import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL;
import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
import static org.apache.geode.distributed.internal.ClusterConfigurationService.CLUSTER_CONFIG_DISK_DIR_PREFIX;
import static org.apache.geode.distributed.internal.DistributionConfig.GEMFIRE_PREFIX;
import static org.apache.geode.internal.AvailablePortHelper.getRandomAvailableTCPPorts;
import static org.apache.geode.internal.DistributionLocator.TEST_OVERRIDE_DEFAULT_PORT_PROPERTY;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.ErrorCollector;
import org.apache.geode.distributed.AbstractLauncher.Status;
import org.apache.geode.distributed.LocatorLauncher.Builder;
import org.apache.geode.distributed.LocatorLauncher.LocatorState;
import org.apache.geode.internal.process.ProcessType;
/**
* Abstract base class for integration tests of {@link LocatorLauncher}.
*
* @since GemFire 8.0
*/
public abstract class LocatorLauncherIntegrationTestCase extends LauncherIntegrationTestCase {
protected volatile int defaultLocatorPort;
protected volatile int nonDefaultLocatorPort;
protected volatile LocatorLauncher launcher;
private volatile File clusterConfigDirectory;
@Rule
public ErrorCollector errorCollector = new ErrorCollector();
@Before
public void setUpAbstractLocatorLauncherIntegrationTestCase() throws Exception {
System.setProperty(GEMFIRE_PREFIX + MCAST_PORT, Integer.toString(0));
clusterConfigDirectory =
temporaryFolder.newFolder(CLUSTER_CONFIG_DISK_DIR_PREFIX + getUniqueName());
int[] ports = getRandomAvailableTCPPorts(2);
defaultLocatorPort = ports[0];
nonDefaultLocatorPort = ports[1];
System.setProperty(TEST_OVERRIDE_DEFAULT_PORT_PROPERTY, String.valueOf(defaultLocatorPort));
}
@After
public void tearDownAbstractLocatorLauncherIntegrationTestCase() throws Exception {
if (launcher != null) {
launcher.stop();
}
}
@Override
protected ProcessType getProcessType() {
return ProcessType.LOCATOR;
}
@Override
protected void givenEmptyWorkingDirectory() {
File[] files = getWorkingDirectory().listFiles();
assertThat(files).hasSize(1);
assertThat(files[0]).isDirectory().isEqualTo(getClusterConfigDirectory());
}
protected LocatorLauncher givenLocatorLauncher() {
return givenLocatorLauncher(newBuilder());
}
private LocatorLauncher givenLocatorLauncher(final Builder builder) {
return builder.build();
}
protected LocatorLauncher givenRunningLocator() {
return givenRunningLocator(newBuilder());
}
protected LocatorLauncher givenRunningLocator(final Builder builder) {
return awaitStart(builder);
}
protected LocatorLauncher awaitStart(final LocatorLauncher launcher) {
await().atMost(2, MINUTES).until(() -> assertThat(isLauncherOnline()).isTrue());
return launcher;
}
protected Locator getLocator() {
return launcher.getLocator();
}
/**
* Returns a new Builder with helpful defaults for safe testing. If you need a Builder in a test
* without any of these defaults then simply use {@code new Builder()} instead.
*/
protected Builder newBuilder() {
return new Builder().setMemberName(getUniqueName()).setRedirectOutput(true)
.setWorkingDirectory(getWorkingDirectoryPath())
.set(CLUSTER_CONFIGURATION_DIR, getClusterConfigDirectoryPath())
.set(DISABLE_AUTO_RECONNECT, "true").set(LOG_LEVEL, "config").set(MCAST_PORT, "0");
}
protected LocatorLauncher startLocator() {
return awaitStart(newBuilder());
}
protected LocatorLauncher startLocator(final Builder builder) {
return awaitStart(builder);
}
protected void stopLocator() {
assertThat(launcher.stop().getStatus()).isEqualTo(STOPPED);
}
private LocatorLauncher awaitStart(final Builder builder) {
launcher = builder.build();
assertThat(launcher.start().getStatus()).isEqualTo(Status.ONLINE);
return awaitStart(launcher);
}
private File getClusterConfigDirectory() {
return clusterConfigDirectory;
}
private String getClusterConfigDirectoryPath() {
try {
return clusterConfigDirectory.getCanonicalPath();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private boolean isLauncherOnline() {
LocatorState locatorState = launcher.status();
assertNotNull(locatorState);
return Status.ONLINE.equals(locatorState.getStatus());
}
}
| apache-2.0 |
gomex/devopsdays-web | content/events/2019-ghent/program/sasha-rosenbaum.md | 1072 | +++
Talk_date = ""
Talk_start_time = ""
Talk_end_time = ""
Title = "Admitting that hard problems are hard"
Type = "talk"
Speakers = ["sasha-rosenbaum"]
+++
In my 14 years in the industry, I watched the technology landscape become more and more complex, with new tools and methodologies emerging and fading away every year. Yet I see "thought leaders" get up on stage every day, promising they can teach you the 3 easy steps to:
- Achieve full software testability (a subset of the Halting Problem, which is undecidable)
- Remediate 20 years of legacy code
- Migrate your entire data center to the cloud
- Adopt the new architectural pattern that is going to solve all of your problems
Beyond fostering imposter syndrome and burnout, this isn't good for business. In a room full of people embarrassed to admit that the emperor has no clothes, decisions are made without exploring their full implications.
In this talk, we will discuss why we should get better at admitting that hard problems are hard, and how this approach can help us build more resilient companies.
| apache-2.0 |
xiaoxq/apollo | modules/planning/open_space/trajectory_smoother/distance_approach_interface.h | 4825 | /******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*
* @file
*/
#pragma once
#include <adolc/adolc.h>
#include <adolc/adolc_openmp.h>
#include <adolc/adolc_sparse.h>
#include <adolc/adouble.h>
#include <omp.h>
#include <coin/IpTNLP.hpp>
#include <coin/IpTypes.hpp>
#include "Eigen/Dense"
#include "cyber/common/log.h"
#include "cyber/common/macros.h"
#include "modules/common/configs/proto/vehicle_config.pb.h"
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/util/util.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/proto/planner_open_space_config.pb.h"
#define tag_f 1
#define tag_g 2
#define tag_L 3
#define HPOFF 30
namespace apollo {
namespace planning {
class DistanceApproachInterface : public Ipopt::TNLP {
public:
virtual ~DistanceApproachInterface() = default;
/** Method to return some info about the nlp */
virtual bool get_nlp_info(int& n, int& m, int& nnz_jac_g, // NOLINT
int& nnz_h_lag, // NOLINT
IndexStyleEnum& index_style) = 0; // NOLINT
/** Method to return the bounds for my problem */
virtual bool get_bounds_info(int n, double* x_l, double* x_u, int m,
double* g_l, double* g_u) = 0;
/** Method to return the starting point for the algorithm */
virtual bool get_starting_point(int n, bool init_x, double* x, bool init_z,
double* z_L, double* z_U, int m,
bool init_lambda, double* lambda) = 0;
/** Method to return the objective value */
virtual bool eval_f(int n, const double* x, bool new_x, // NOLINT
double& obj_value) = 0; // NOLINT
/** Method to return the gradient of the objective */
virtual bool eval_grad_f(int n, const double* x, bool new_x,
double* grad_f) = 0;
/** Method to return the constraint residuals */
virtual bool eval_g(int n, const double* x, bool new_x, int m, double* g) = 0;
/** Check unfeasible constraints for further study**/
virtual bool check_g(int n, const double* x, int m, const double* g) = 0;
/** Method to return:
* 1) The structure of the jacobian (if "values" is nullptr)
* 2) The values of the jacobian (if "values" is not nullptr)
*/
virtual bool eval_jac_g(int n, const double* x, bool new_x, int m,
int nele_jac, int* iRow, int* jCol,
double* values) = 0;
// sequential implementation to jac_g
virtual bool eval_jac_g_ser(int n, const double* x, bool new_x, int m,
int nele_jac, int* iRow, int* jCol,
double* values) = 0;
/** Method to return:
* 1) The structure of the hessian of the lagrangian (if "values" is
* nullptr) 2) The values of the hessian of the lagrangian (if "values" is not
* nullptr)
*/
virtual bool eval_h(int n, const double* x, bool new_x, double obj_factor,
int m, const double* lambda, bool new_lambda,
int nele_hess, int* iRow, int* jCol, double* values) = 0;
/** @name Solution Methods */
/** This method is called when the algorithm is complete so the TNLP can
* store/write the solution */
virtual void finalize_solution(Ipopt::SolverReturn status, int n,
const double* x, const double* z_L,
const double* z_U, int m, const double* g,
const double* lambda, double obj_value,
const Ipopt::IpoptData* ip_data,
Ipopt::IpoptCalculatedQuantities* ip_cq) = 0;
virtual void get_optimization_results(
Eigen::MatrixXd* state_result, Eigen::MatrixXd* control_result,
Eigen::MatrixXd* time_result, Eigen::MatrixXd* dual_l_result,
Eigen::MatrixXd* dual_n_result) const = 0;
};
} // namespace planning
} // namespace apollo
| apache-2.0 |
massakam/pulsar | site2/website/versioned_docs/version-2.6.0/getting-started-standalone.md | 10786 | ---
id: version-2.6.0-standalone
title: Set up a standalone Pulsar locally
sidebar_label: Run Pulsar locally
original_id: standalone
---
For local development and testing, you can run Pulsar in standalone mode on your machine. The standalone mode includes a Pulsar broker, the necessary ZooKeeper and BookKeeper components running inside of a single Java Virtual Machine (JVM) process.
> #### Pulsar in production?
> If you're looking to run a full production Pulsar installation, see the [Deploying a Pulsar instance](deploy-bare-metal.md) guide.
## Install Pulsar standalone
This tutorial guides you through every step of the installation process.
### System requirements
Currently, Pulsar is available for 64-bit **macOS**, **Linux**, and **Windows**. To use Pulsar, you need to install 64-bit JRE/JDK 8 or later versions.
> #### Tip
> By default, Pulsar allocates 2G JVM heap memory to start. It can be changed in `conf/pulsar_env.sh` file under `PULSAR_MEM`. This is extra options passed into JVM.
### Install Pulsar using binary release
To get started with Pulsar, download a binary tarball release in one of the following ways:
* download from the Apache mirror (<a href="pulsar:binary_release_url" download>Pulsar {{pulsar:version}} binary release</a>)
* download from the Pulsar [downloads page](pulsar:download_page_url)
* download from the Pulsar [releases page](https://github.com/apache/pulsar/releases/latest)
* use [wget](https://www.gnu.org/software/wget):
```shell
$ wget pulsar:binary_release_url
```
After you download the tarball, untar it and use the `cd` command to navigate to the resulting directory:
```bash
$ tar xvfz apache-pulsar-{{pulsar:version}}-bin.tar.gz
$ cd apache-pulsar-{{pulsar:version}}
```
#### What your package contains
The Pulsar binary package initially contains the following directories:
Directory | Contains
:---------|:--------
`bin` | Pulsar's command-line tools, such as [`pulsar`](reference-cli-tools.md#pulsar) and [`pulsar-admin`](https://pulsar.apache.org/tools/pulsar-admin/).
`conf` | Configuration files for Pulsar, including [broker configuration](reference-configuration.md#broker), [ZooKeeper configuration](reference-configuration.md#zookeeper), and more.
`examples` | A Java JAR file containing [Pulsar Functions](functions-overview.md) example.
`lib` | The [JAR](https://en.wikipedia.org/wiki/JAR_(file_format)) files used by Pulsar.
`licenses` | License files, in the`.txt` form, for various components of the Pulsar [codebase](https://github.com/apache/pulsar).
These directories are created once you begin running Pulsar.
Directory | Contains
:---------|:--------
`data` | The data storage directory used by ZooKeeper and BookKeeper.
`instances` | Artifacts created for [Pulsar Functions](functions-overview.md).
`logs` | Logs created by the installation.
> #### Tip
> If you want to use builtin connectors and tiered storage offloaders, you can install them according to the following instructions:
>
> * [Install builtin connectors (optional)](#install-builtin-connectors-optional)
> * [Install tiered storage offloaders (optional)](#install-tiered-storage-offloaders-optional)
>
> Otherwise, skip this step and perform the next step [Start Pulsar standalone](#start-pulsar-standalone). Pulsar can be successfully installed without installing bulitin connectors and tiered storage offloaders.
### Install builtin connectors (optional)
Since `2.1.0-incubating` release, Pulsar releases a separate binary distribution, containing all the `builtin` connectors.
To enable those `builtin` connectors, you can download the connectors tarball release in one of the following ways:
* download from the Apache mirror <a href="pulsar:connector_release_url" download>Pulsar IO Connectors {{pulsar:version}} release</a>
* download from the Pulsar [downloads page](pulsar:download_page_url)
* download from the Pulsar [releases page](https://github.com/apache/pulsar/releases/latest)
* use [wget](https://www.gnu.org/software/wget):
```shell
$ wget pulsar:connector_release_url/{connector}-{{pulsar:version}}.nar
```
After you download the nar file, copy the file to the `connectors` directory in the pulsar directory.
For example, if you download the `pulsar-io-aerospike-{{pulsar:version}}.nar` connector file, enter the following commands:
```bash
$ mkdir connectors
$ mv pulsar-io-aerospike-{{pulsar:version}}.nar connectors
$ ls connectors
pulsar-io-aerospike-{{pulsar:version}}.nar
...
```
> #### Note
>
> * If you are running Pulsar in a bare metal cluster, make sure `connectors` tarball is unzipped in every pulsar directory of the broker
> (or in every pulsar directory of function-worker if you are running a separate worker cluster for Pulsar Functions).
>
> * If you are [running Pulsar in Docker](getting-started-docker.md) or deploying Pulsar using a docker image (e.g. [K8S](deploy-kubernetes.md) or [DC/OS](https://dcos.io/)),
> you can use the `apachepulsar/pulsar-all` image instead of the `apachepulsar/pulsar` image. `apachepulsar/pulsar-all` image has already bundled [all builtin connectors](io-overview.md#working-with-connectors).
### Install tiered storage offloaders (optional)
> #### Tip
>
> Since `2.2.0` release, Pulsar releases a separate binary distribution, containing the tiered storage offloaders.
> To enable tiered storage feature, follow the instructions below; otherwise skip this section.
To get started with [tiered storage offloaders](concepts-tiered-storage.md), you need to download the offloaders tarball release on every broker node in one of the following ways:
* download from the Apache mirror <a href="pulsar:offloader_release_url" download>Pulsar Tiered Storage Offloaders {{pulsar:version}} release</a>
* download from the Pulsar [downloads page](pulsar:download_page_url)
* download from the Pulsar [releases page](https://github.com/apache/pulsar/releases/latest)
* use [wget](https://www.gnu.org/software/wget):
```shell
$ wget pulsar:offloader_release_url
```
After you download the tarball, untar the offloaders package and copy the offloaders as `offloaders`
in the pulsar directory:
```bash
$ tar xvfz apache-pulsar-offloaders-{{pulsar:version}}-bin.tar.gz
// you will find a directory named `apache-pulsar-offloaders-{{pulsar:version}}` in the pulsar directory
// then copy the offloaders
$ mv apache-pulsar-offloaders-{{pulsar:version}}/offloaders offloaders
$ ls offloaders
tiered-storage-jcloud-{{pulsar:version}}.nar
```
For more information on how to configure tiered storage, see [Tiered storage cookbook](cookbooks-tiered-storage.md).
> #### Note
>
> * If you are running Pulsar in a bare metal cluster, make sure that `offloaders` tarball is unzipped in every broker's pulsar directory.
>
> * If you are [running Pulsar in Docker](getting-started-docker.md) or deploying Pulsar using a docker image (e.g. [K8S](deploy-kubernetes.md) or [DC/OS](https://dcos.io/)),
> you can use the `apachepulsar/pulsar-all` image instead of the `apachepulsar/pulsar` image. `apachepulsar/pulsar-all` image has already bundled tiered storage offloaders.
## Start Pulsar standalone
Once you have an up-to-date local copy of the release, you can start a local cluster using the [`pulsar`](reference-cli-tools.md#pulsar) command, which is stored in the `bin` directory, and specifying that you want to start Pulsar in standalone mode.
```bash
$ bin/pulsar standalone
```
If you have started Pulsar successfully, you will see `INFO`-level log messages like this:
```bash
2017-06-01 14:46:29,192 - INFO - [main:WebSocketService@95] - Configuration Store cache started
2017-06-01 14:46:29,192 - INFO - [main:AuthenticationService@61] - Authentication is disabled
2017-06-01 14:46:29,192 - INFO - [main:WebSocketService@108] - Pulsar WebSocket Service started
```
> #### Tip
>
> * The service is running on your terminal, which is under your direct control. If you need to run other commands, open a new terminal window.
You can also run the service as a background process using the `pulsar-daemon start standalone` command. For more information, see [pulsar-daemon](https://pulsar.apache.org/docs/en/reference-cli-tools/#pulsar-daemon).
>
> * By default, there is no encryption, authentication, or authorization configured. Apache Pulsar can be accessed from remote server without any authorization. Please do check [Security Overview](security-overview.md) document to secure your deployment.
>
> * When you start a local standalone cluster, a `public/default` [namespace](concepts-messaging.md#namespaces) is created automatically. The namespace is used for development purposes. All Pulsar topics are managed within namespaces. For more information, see [Topics](concepts-messaging.md#topics).
## Use Pulsar standalone
Pulsar provides a CLI tool called [`pulsar-client`](reference-cli-tools.md#pulsar-client). The pulsar-client tool enables you to consume and produce messages to a Pulsar topic in a running cluster.
### Consume a message
The following command consumes a message with the subscription name `first-subscription` to the `my-topic` topic:
```bash
$ bin/pulsar-client consume my-topic -s "first-subscription"
```
If the message has been successfully consumed, you will see a confirmation like the following in the `pulsar-client` logs:
```
09:56:55.566 [pulsar-client-io-1-1] INFO org.apache.pulsar.client.impl.MultiTopicsConsumerImpl - [TopicsConsumerFakeTopicNamee2df9] [first-subscription] Success subscribe new topic my-topic in topics consumer, partitions: 4, allTopicPartitionsNumber: 4
```
> #### Tip
>
> As you have noticed that we do not explicitly create the `my-topic` topic, to which we consume the message. When you consume a message to a topic that does not yet exist, Pulsar creates that topic for you automatically. Producing a message to a topic that does not exist will automatically create that topic for you as well.
### Produce a message
The following command produces a message saying `hello-pulsar` to the `my-topic` topic:
```bash
$ bin/pulsar-client produce my-topic --messages "hello-pulsar"
```
If the message has been successfully published to the topic, you will see a confirmation like the following in the `pulsar-client` logs:
```
13:09:39.356 [main] INFO org.apache.pulsar.client.cli.PulsarClientTool - 1 messages successfully produced
```
## Stop Pulsar standalone
Press `Ctrl+C` to stop a local standalone Pulsar.
> #### Tip
>
> If the service runs as a background process using the `pulsar-daemon start standalone` command, then use the `pulsar-daemon stop standalone` command to stop the service.
>
> For more information, see [pulsar-daemon](https://pulsar.apache.org/docs/en/reference-cli-tools/#pulsar-daemon).
| apache-2.0 |
menglingwei/denverdino.github.io | docker-cloud/getting-started/deploy-app/2_set_up.md | 3234 | ---
description: Set up the application
keywords: Python, application, setup
redirect_from:
- /docker-cloud/getting-started/python/2_set_up/
- /docker-cloud/getting-started/golang/2_set_up/
title: Set up your environment
---
In this step you install the Docker Cloud CLI so interact with the service using your command shell. This tutorial uses CLI commands to complete actions.
## Install the Docker Cloud CLI
Install the docker-cloud CLI using the package manager for your system.
#### Install using a Docker container
If you have Docker Engine installed locally, you can simply run the following command regardless of which operating system you are using.
```
docker run dockercloud/cli -h
```
This runs a container that installs the docker-cloud CLI for you. Learn more about this container [here](https://github.com/docker/dockercloud-cli#docker-image).
#### Install for Linux or Windows
Open your shell or terminal application and execute the following command:
```bash
$ pip install docker-cloud
```
#### Install on macOS
We recommend installing Docker CLI for macOS using Homebrew. If you don't have `brew` installed, follow the instructions here: <a href="http://brew.sh" target="_blank">http://brew.sh</a>
Once Homebrew is installed, open Terminal and run the following command:
```bash
$ brew install docker-cloud
```
## Validate the CLI installation
Check that the CLI installed correctly, using the `docker-cloud -v` command. (This command is the same for every platform.)
```bash
$ docker-cloud -v
docker-cloud 1.0.0
```
You can now use the `docker-cloud` CLI commands from your shell.
The documentation for the Docker Cloud CLI tool and API [here](/apidocs/docker-cloud.md).
## Log in
Use the `login` CLI command to log in to Docker Cloud. Use the username and password you used when creating your Docker ID. If you use Docker Hub, you can use the same username and password you use to log in to Docker Hub.
```
$ docker login
Username: my-username
Password:
Login succeeded!
```
You must log in to continue this tutorial.
## Set your username as an environment variable
For simplicity in this tutorial, we use an environment variable for your Docker Cloud username. If you will be copying and pasting the tutorial commands, set the environment variable using the command below. (Change `my-username` to your username.)
If you don't want to do this, make sure you substitute your username for $DOCKER_ID_USER whenever you see it in the example commands.
```none
$ export DOCKER_ID_USER=my-username
```
**If you are running the tutorial with an organization's resources:**
By default, the `docker-cloud` CLI uses your default user namespace, meaning the
repositories, nodes, and services associated with your individual Docker ID
account name. To use the CLI to interact with objects that belong to an
[organization](../../orgs.md), prefix these commands with
`DOCKERCLOUD_NAMESPACE=my-organization`, or set this variable as in the example below.
```none
$ export `DOCKERCLOUD_NAMESPACE=my-organization`
```
See the [CLI documentation](../../installing-cli.md#use-the-docker-cloud-cli-with-an-organization) for more information.
Next up, we'll [Prepare the app](3_prepare_the_app.md).
| apache-2.0 |
awslabs/aws-sdk-cpp | aws-cpp-sdk-application-insights/include/aws/application-insights/model/ApplicationComponent.h | 12743 | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/application-insights/ApplicationInsights_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/application-insights/model/OsType.h>
#include <aws/application-insights/model/Tier.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace ApplicationInsights
{
namespace Model
{
/**
* <p>Describes a standalone resource or similarly grouped resources that the
* application is made up of.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/application-insights-2018-11-25/ApplicationComponent">AWS
* API Reference</a></p>
*/
class AWS_APPLICATIONINSIGHTS_API ApplicationComponent
{
public:
ApplicationComponent();
ApplicationComponent(Aws::Utils::Json::JsonView jsonValue);
ApplicationComponent& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The name of the component.</p>
*/
inline const Aws::String& GetComponentName() const{ return m_componentName; }
/**
* <p>The name of the component.</p>
*/
inline bool ComponentNameHasBeenSet() const { return m_componentNameHasBeenSet; }
/**
* <p>The name of the component.</p>
*/
inline void SetComponentName(const Aws::String& value) { m_componentNameHasBeenSet = true; m_componentName = value; }
/**
* <p>The name of the component.</p>
*/
inline void SetComponentName(Aws::String&& value) { m_componentNameHasBeenSet = true; m_componentName = std::move(value); }
/**
* <p>The name of the component.</p>
*/
inline void SetComponentName(const char* value) { m_componentNameHasBeenSet = true; m_componentName.assign(value); }
/**
* <p>The name of the component.</p>
*/
inline ApplicationComponent& WithComponentName(const Aws::String& value) { SetComponentName(value); return *this;}
/**
* <p>The name of the component.</p>
*/
inline ApplicationComponent& WithComponentName(Aws::String&& value) { SetComponentName(std::move(value)); return *this;}
/**
* <p>The name of the component.</p>
*/
inline ApplicationComponent& WithComponentName(const char* value) { SetComponentName(value); return *this;}
/**
* <p> If logging is supported for the resource type, indicates whether the
* component has configured logs to be monitored. </p>
*/
inline const Aws::String& GetComponentRemarks() const{ return m_componentRemarks; }
/**
* <p> If logging is supported for the resource type, indicates whether the
* component has configured logs to be monitored. </p>
*/
inline bool ComponentRemarksHasBeenSet() const { return m_componentRemarksHasBeenSet; }
/**
* <p> If logging is supported for the resource type, indicates whether the
* component has configured logs to be monitored. </p>
*/
inline void SetComponentRemarks(const Aws::String& value) { m_componentRemarksHasBeenSet = true; m_componentRemarks = value; }
/**
* <p> If logging is supported for the resource type, indicates whether the
* component has configured logs to be monitored. </p>
*/
inline void SetComponentRemarks(Aws::String&& value) { m_componentRemarksHasBeenSet = true; m_componentRemarks = std::move(value); }
/**
* <p> If logging is supported for the resource type, indicates whether the
* component has configured logs to be monitored. </p>
*/
inline void SetComponentRemarks(const char* value) { m_componentRemarksHasBeenSet = true; m_componentRemarks.assign(value); }
/**
* <p> If logging is supported for the resource type, indicates whether the
* component has configured logs to be monitored. </p>
*/
inline ApplicationComponent& WithComponentRemarks(const Aws::String& value) { SetComponentRemarks(value); return *this;}
/**
* <p> If logging is supported for the resource type, indicates whether the
* component has configured logs to be monitored. </p>
*/
inline ApplicationComponent& WithComponentRemarks(Aws::String&& value) { SetComponentRemarks(std::move(value)); return *this;}
/**
* <p> If logging is supported for the resource type, indicates whether the
* component has configured logs to be monitored. </p>
*/
inline ApplicationComponent& WithComponentRemarks(const char* value) { SetComponentRemarks(value); return *this;}
/**
* <p>The resource type. Supported resource types include EC2 instances, Auto
* Scaling group, Classic ELB, Application ELB, and SQS Queue.</p>
*/
inline const Aws::String& GetResourceType() const{ return m_resourceType; }
/**
* <p>The resource type. Supported resource types include EC2 instances, Auto
* Scaling group, Classic ELB, Application ELB, and SQS Queue.</p>
*/
inline bool ResourceTypeHasBeenSet() const { return m_resourceTypeHasBeenSet; }
/**
* <p>The resource type. Supported resource types include EC2 instances, Auto
* Scaling group, Classic ELB, Application ELB, and SQS Queue.</p>
*/
inline void SetResourceType(const Aws::String& value) { m_resourceTypeHasBeenSet = true; m_resourceType = value; }
/**
* <p>The resource type. Supported resource types include EC2 instances, Auto
* Scaling group, Classic ELB, Application ELB, and SQS Queue.</p>
*/
inline void SetResourceType(Aws::String&& value) { m_resourceTypeHasBeenSet = true; m_resourceType = std::move(value); }
/**
* <p>The resource type. Supported resource types include EC2 instances, Auto
* Scaling group, Classic ELB, Application ELB, and SQS Queue.</p>
*/
inline void SetResourceType(const char* value) { m_resourceTypeHasBeenSet = true; m_resourceType.assign(value); }
/**
* <p>The resource type. Supported resource types include EC2 instances, Auto
* Scaling group, Classic ELB, Application ELB, and SQS Queue.</p>
*/
inline ApplicationComponent& WithResourceType(const Aws::String& value) { SetResourceType(value); return *this;}
/**
* <p>The resource type. Supported resource types include EC2 instances, Auto
* Scaling group, Classic ELB, Application ELB, and SQS Queue.</p>
*/
inline ApplicationComponent& WithResourceType(Aws::String&& value) { SetResourceType(std::move(value)); return *this;}
/**
* <p>The resource type. Supported resource types include EC2 instances, Auto
* Scaling group, Classic ELB, Application ELB, and SQS Queue.</p>
*/
inline ApplicationComponent& WithResourceType(const char* value) { SetResourceType(value); return *this;}
/**
* <p> The operating system of the component. </p>
*/
inline const OsType& GetOsType() const{ return m_osType; }
/**
* <p> The operating system of the component. </p>
*/
inline bool OsTypeHasBeenSet() const { return m_osTypeHasBeenSet; }
/**
* <p> The operating system of the component. </p>
*/
inline void SetOsType(const OsType& value) { m_osTypeHasBeenSet = true; m_osType = value; }
/**
* <p> The operating system of the component. </p>
*/
inline void SetOsType(OsType&& value) { m_osTypeHasBeenSet = true; m_osType = std::move(value); }
/**
* <p> The operating system of the component. </p>
*/
inline ApplicationComponent& WithOsType(const OsType& value) { SetOsType(value); return *this;}
/**
* <p> The operating system of the component. </p>
*/
inline ApplicationComponent& WithOsType(OsType&& value) { SetOsType(std::move(value)); return *this;}
/**
* <p>The stack tier of the application component.</p>
*/
inline const Tier& GetTier() const{ return m_tier; }
/**
* <p>The stack tier of the application component.</p>
*/
inline bool TierHasBeenSet() const { return m_tierHasBeenSet; }
/**
* <p>The stack tier of the application component.</p>
*/
inline void SetTier(const Tier& value) { m_tierHasBeenSet = true; m_tier = value; }
/**
* <p>The stack tier of the application component.</p>
*/
inline void SetTier(Tier&& value) { m_tierHasBeenSet = true; m_tier = std::move(value); }
/**
* <p>The stack tier of the application component.</p>
*/
inline ApplicationComponent& WithTier(const Tier& value) { SetTier(value); return *this;}
/**
* <p>The stack tier of the application component.</p>
*/
inline ApplicationComponent& WithTier(Tier&& value) { SetTier(std::move(value)); return *this;}
/**
* <p>Indicates whether the application component is monitored. </p>
*/
inline bool GetMonitor() const{ return m_monitor; }
/**
* <p>Indicates whether the application component is monitored. </p>
*/
inline bool MonitorHasBeenSet() const { return m_monitorHasBeenSet; }
/**
* <p>Indicates whether the application component is monitored. </p>
*/
inline void SetMonitor(bool value) { m_monitorHasBeenSet = true; m_monitor = value; }
/**
* <p>Indicates whether the application component is monitored. </p>
*/
inline ApplicationComponent& WithMonitor(bool value) { SetMonitor(value); return *this;}
/**
* <p> Workloads detected in the application component. </p>
*/
inline const Aws::Map<Tier, Aws::Map<Aws::String, Aws::String>>& GetDetectedWorkload() const{ return m_detectedWorkload; }
/**
* <p> Workloads detected in the application component. </p>
*/
inline bool DetectedWorkloadHasBeenSet() const { return m_detectedWorkloadHasBeenSet; }
/**
* <p> Workloads detected in the application component. </p>
*/
inline void SetDetectedWorkload(const Aws::Map<Tier, Aws::Map<Aws::String, Aws::String>>& value) { m_detectedWorkloadHasBeenSet = true; m_detectedWorkload = value; }
/**
* <p> Workloads detected in the application component. </p>
*/
inline void SetDetectedWorkload(Aws::Map<Tier, Aws::Map<Aws::String, Aws::String>>&& value) { m_detectedWorkloadHasBeenSet = true; m_detectedWorkload = std::move(value); }
/**
* <p> Workloads detected in the application component. </p>
*/
inline ApplicationComponent& WithDetectedWorkload(const Aws::Map<Tier, Aws::Map<Aws::String, Aws::String>>& value) { SetDetectedWorkload(value); return *this;}
/**
* <p> Workloads detected in the application component. </p>
*/
inline ApplicationComponent& WithDetectedWorkload(Aws::Map<Tier, Aws::Map<Aws::String, Aws::String>>&& value) { SetDetectedWorkload(std::move(value)); return *this;}
/**
* <p> Workloads detected in the application component. </p>
*/
inline ApplicationComponent& AddDetectedWorkload(const Tier& key, const Aws::Map<Aws::String, Aws::String>& value) { m_detectedWorkloadHasBeenSet = true; m_detectedWorkload.emplace(key, value); return *this; }
/**
* <p> Workloads detected in the application component. </p>
*/
inline ApplicationComponent& AddDetectedWorkload(Tier&& key, const Aws::Map<Aws::String, Aws::String>& value) { m_detectedWorkloadHasBeenSet = true; m_detectedWorkload.emplace(std::move(key), value); return *this; }
/**
* <p> Workloads detected in the application component. </p>
*/
inline ApplicationComponent& AddDetectedWorkload(const Tier& key, Aws::Map<Aws::String, Aws::String>&& value) { m_detectedWorkloadHasBeenSet = true; m_detectedWorkload.emplace(key, std::move(value)); return *this; }
/**
* <p> Workloads detected in the application component. </p>
*/
inline ApplicationComponent& AddDetectedWorkload(Tier&& key, Aws::Map<Aws::String, Aws::String>&& value) { m_detectedWorkloadHasBeenSet = true; m_detectedWorkload.emplace(std::move(key), std::move(value)); return *this; }
private:
Aws::String m_componentName;
bool m_componentNameHasBeenSet;
Aws::String m_componentRemarks;
bool m_componentRemarksHasBeenSet;
Aws::String m_resourceType;
bool m_resourceTypeHasBeenSet;
OsType m_osType;
bool m_osTypeHasBeenSet;
Tier m_tier;
bool m_tierHasBeenSet;
bool m_monitor;
bool m_monitorHasBeenSet;
Aws::Map<Tier, Aws::Map<Aws::String, Aws::String>> m_detectedWorkload;
bool m_detectedWorkloadHasBeenSet;
};
} // namespace Model
} // namespace ApplicationInsights
} // namespace Aws
| apache-2.0 |
roberthafner/flowable-engine | modules/flowable5-engine/src/main/java/org/activiti5/engine/impl/json/JsonObjectConverter.java | 1184 | /* 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 org.activiti5.engine.impl.json;
import java.io.Reader;
import java.io.Writer;
import org.activiti5.engine.impl.util.json.JSONObject;
/**
* @author Tom Baeyens
*/
public abstract class JsonObjectConverter <T> {
public void toJson(T object, Writer writer) {
toJsonObject(object).write(writer);
}
public String toJson(T object) {
return toJsonObject(object).toString();
}
public String toJson(T object, int indentFactor) {
return toJsonObject(object).toString(indentFactor);
}
public abstract JSONObject toJsonObject(T object);
public abstract T toObject(Reader reader);
}
| apache-2.0 |
KrithikaGanesh/cmb | src/com/comcast/cns/controller/CNSRawMessageDeliveryPolicyPage.java | 5387 | /**
* Copyright 2012 Comcast Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.comcast.cns.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.amazonaws.services.sns.model.GetSubscriptionAttributesRequest;
import com.amazonaws.services.sns.model.GetSubscriptionAttributesResult;
import com.amazonaws.services.sns.model.SetSubscriptionAttributesRequest;
import com.comcast.cmb.common.controller.AdminServletBase;
import com.comcast.cmb.common.controller.CMBControllerServlet;
/**
* Admin page for editing subscription delivery policy
* @author tina, aseem, bwolf
*
*/
public class CNSRawMessageDeliveryPolicyPage extends AdminServletBase {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(CNSRawMessageDeliveryPolicyPage.class);
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (redirectUnauthenticatedUser(request, response)) {
return;
}
CMBControllerServlet.valueAccumulator.initializeAllCounters();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String subArn = request.getParameter("subscriptionArn");
String userId = request.getParameter("userId");
Map<?, ?> params = request.getParameterMap();
connect(request);
out.println("<html>");
simpleHeader(request, out, "Raw Message Delivery Policy");
if (params.containsKey("Update")) {
String rawMessageDeliveryParam = request.getParameter("rawmessage");
Boolean rawMessageDelivery = false;
if (rawMessageDeliveryParam.trim().length() > 0) {
rawMessageDelivery = Boolean.parseBoolean(rawMessageDeliveryParam.trim());
}
try {
SetSubscriptionAttributesRequest setSubscriptionAttributesRequest = new SetSubscriptionAttributesRequest(subArn, "RawMessageDelivery", rawMessageDelivery.toString());
sns.setSubscriptionAttributes(setSubscriptionAttributesRequest);
logger.debug("event=set_raw_message_delivery_policy sub_arn=" + subArn + " user_id= " + userId);
} catch (Exception ex) {
logger.error("event=set_raw_message_delivery_policy sub_arn=" + subArn + " user_id= " + userId, ex);
throw new ServletException(ex);
}
out.println("<body onload='javascript:window.opener.location.reload();window.close();'>");
} else {
Boolean rawMessageDelivery = false;
if (subArn != null) {
Map<String, String> attributes = null;
try {
GetSubscriptionAttributesRequest getSubscriptionAttributesRequest = new GetSubscriptionAttributesRequest(subArn);
GetSubscriptionAttributesResult getSubscriptionAttributesResult = sns.getSubscriptionAttributes(getSubscriptionAttributesRequest);
attributes = getSubscriptionAttributesResult.getAttributes();
String rawMessageDeliveryStr = attributes.get("RawMessageDelivery");
if(rawMessageDeliveryStr != null && !rawMessageDeliveryStr.isEmpty()){
rawMessageDelivery = Boolean.parseBoolean(rawMessageDeliveryStr);
}
} catch (Exception ex) {
logger.error("event=get_raw_message_delivery_attribute sub_arn=" + subArn + " user_id= " + userId, ex);
throw new ServletException(ex);
}
}
out.println("<body>");
out.println("<h1>Raw Message Delivery Policy</h1>");
out.println("<form action=\"/webui/cnsuser/subscription/rawmessagedeliverypolicy?subscriptionArn="+subArn+"\" method=POST>");
out.println("<input type='hidden' name='userId' value='"+ userId +"'>");
out.println("<table width='98%'");
out.println("<tr><td colspan=2><b><font color='orange'>Raw Message Delivery</font></b></td></tr>");
out.println("<tr><td ><input type='radio' name='rawmessage' value='true' " + (rawMessageDelivery?"checked='true'":"") + ">True</td>");
out.println("<td ><input type='radio' name='rawmessage' value='false' " + (rawMessageDelivery?"":"checked='true'") + ">False</td></tr>");
out.println("<tr><td> </td><td> </td></tr>");
out.println("<tr><td colspan=2><hr/></td></tr>");
out.println("<tr><td colspan=2 align=right><input type='button' onclick='window.close()' value='Cancel'><input type='submit' name='Update' value='Update'></td></tr></table></form>");
}
out.println("</body></html>");
CMBControllerServlet.valueAccumulator.deleteAllCounters();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| apache-2.0 |
fogbeam/cas_mirror | support/cas-server-support-oauth-core-api/src/main/java/org/apereo/cas/ticket/BaseTokenSigningAndEncryptionService.java | 5013 | package org.apereo.cas.ticket;
import org.apereo.cas.support.oauth.OAuth20Constants;
import org.apereo.cas.support.oauth.services.OAuthRegisteredService;
import org.apereo.cas.token.JwtBuilder;
import org.apereo.cas.util.EncodingUtils;
import com.nimbusds.jwt.JWTClaimsSet;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.jose4j.jwk.PublicJsonWebKey;
import org.jose4j.jwt.JwtClaims;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.HashMap;
import java.util.Objects;
import java.util.Optional;
/**
* This is {@link BaseTokenSigningAndEncryptionService}.
*
* @author Misagh Moayyed
* @since 6.0.0
*/
@Slf4j
@NoArgsConstructor(force = true)
@RequiredArgsConstructor(access = AccessLevel.PROTECTED)
@Getter
public abstract class BaseTokenSigningAndEncryptionService implements OAuth20TokenSigningAndEncryptionService {
private final String issuer;
/**
* Create json web encryption json web encryption.
*
* @param encryptionAlg the encryption alg
* @param encryptionEncoding the encryption encoding
* @param keyIdHeaderValue the key id header value
* @param publicKey the public key
* @param payload the payload
* @return the json web encryption
*/
@SneakyThrows
protected static String encryptToken(final String encryptionAlg,
final String encryptionEncoding,
final String keyIdHeaderValue,
final Key publicKey,
final String payload) {
return EncodingUtils.encryptValueAsJwt(publicKey, payload, encryptionAlg,
encryptionEncoding, keyIdHeaderValue, new HashMap<>(0));
}
@Override
@SneakyThrows
public JwtClaims decode(final String token, final Optional<OAuthRegisteredService> service) {
val jsonWebKey = getJsonWebKeySigningKey();
if (jsonWebKey.getPublicKey() == null) {
throw new IllegalArgumentException("JSON web key used to validate the id token signature has no associated public key");
}
val jwt = verifySignature(token, jsonWebKey);
if (jwt == null) {
throw new IllegalArgumentException("Unable to verify signature of the token using the JSON web key public key");
}
val result = new String(jwt, StandardCharsets.UTF_8);
val claims = JwtBuilder.parse(result);
if (StringUtils.isBlank(claims.getIssuer())) {
throw new IllegalArgumentException("Claims do not container an issuer");
}
validateIssuerClaim(claims);
if (StringUtils.isBlank(claims.getStringClaim(OAuth20Constants.CLIENT_ID))) {
throw new IllegalArgumentException("Claims do not contain a client id claim");
}
return JwtClaims.parse(claims.toString());
}
/**
* Validate issuer claim.
*
* @param claims the claims
*/
protected void validateIssuerClaim(final JWTClaimsSet claims) {
LOGGER.debug("Validating claims as [{}] with issuer [{}]", claims, claims.getIssuer());
val iss = determineIssuer(claims);
Objects.requireNonNull(iss, "Issuer cannot be null or undefined");
if (!claims.getIssuer().equalsIgnoreCase(iss)) {
throw new IllegalArgumentException("Issuer assigned to claims " + claims.getIssuer() + " does not match " + iss);
}
}
/**
* Determine issuer.
*
* @param claims the claims
* @return the string
*/
protected String determineIssuer(final JWTClaimsSet claims) {
return getIssuer();
}
/**
* Configure json web signature for id token signing.
*
* @param svc the svc
* @param claims the claims
* @param jsonWebKey the json web key
* @return the json web signature
*/
protected String signToken(final OAuthRegisteredService svc,
final JwtClaims claims,
final PublicJsonWebKey jsonWebKey) {
LOGGER.debug("Service [{}] is set to sign id tokens", svc.getServiceId());
return EncodingUtils.signJws(claims, jsonWebKey, getJsonWebKeySigningAlgorithm(svc), new HashMap<>(0));
}
/**
* Verify signature.
*
* @param token the token
* @param jsonWebKey the json web key
* @return the byte []
*/
protected byte[] verifySignature(final String token, final PublicJsonWebKey jsonWebKey) {
return EncodingUtils.verifyJwsSignature(jsonWebKey.getPublicKey(), token);
}
/**
* Gets signing key.
*
* @return the signing key
*/
protected abstract PublicJsonWebKey getJsonWebKeySigningKey();
}
| apache-2.0 |
chenc10/Spark-PAF | examples/src/main/java/org/apache/spark/examples/ml/JavaPolynomialExpansionExample.java | 2545 | /*
* 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.spark.examples.ml;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.SQLContext;
// $example on$
import java.util.Arrays;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.ml.feature.PolynomialExpansion;
import org.apache.spark.mllib.linalg.VectorUDT;
import org.apache.spark.mllib.linalg.Vectors;
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.RowFactory;
import org.apache.spark.sql.types.Metadata;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;
// $example off$
public class JavaPolynomialExpansionExample {
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JavaPolynomialExpansionExample");
JavaSparkContext jsc = new JavaSparkContext(conf);
SQLContext jsql = new SQLContext(jsc);
// $example on$
PolynomialExpansion polyExpansion = new PolynomialExpansion()
.setInputCol("features")
.setOutputCol("polyFeatures")
.setDegree(3);
JavaRDD<Row> data = jsc.parallelize(Arrays.asList(
RowFactory.create(Vectors.dense(-2.0, 2.3)),
RowFactory.create(Vectors.dense(0.0, 0.0)),
RowFactory.create(Vectors.dense(0.6, -1.1))
));
StructType schema = new StructType(new StructField[]{
new StructField("features", new VectorUDT(), false, Metadata.empty()),
});
DataFrame df = jsql.createDataFrame(data, schema);
DataFrame polyDF = polyExpansion.transform(df);
Row[] row = polyDF.select("polyFeatures").take(3);
for (Row r : row) {
System.out.println(r.get(0));
}
// $example off$
jsc.stop();
}
} | apache-2.0 |
grpc/grpc | src/core/ext/upbdefs-generated/envoy/extensions/transport_sockets/tls/v3/common.upbdefs.h | 3131 | /* This file was generated by upbc (the upb compiler) from the input
* file:
*
* envoy/extensions/transport_sockets/tls/v3/common.proto
*
* Do not edit -- your changes will be discarded when the file is
* regenerated. */
#ifndef ENVOY_EXTENSIONS_TRANSPORT_SOCKETS_TLS_V3_COMMON_PROTO_UPBDEFS_H_
#define ENVOY_EXTENSIONS_TRANSPORT_SOCKETS_TLS_V3_COMMON_PROTO_UPBDEFS_H_
#include "upb/def.h"
#include "upb/port_def.inc"
#ifdef __cplusplus
extern "C" {
#endif
#include "upb/def.h"
#include "upb/port_def.inc"
extern _upb_DefPool_Init envoy_extensions_transport_sockets_tls_v3_common_proto_upbdefinit;
UPB_INLINE const upb_MessageDef *envoy_extensions_transport_sockets_tls_v3_TlsParameters_getmsgdef(upb_DefPool *s) {
_upb_DefPool_LoadDefInit(s, &envoy_extensions_transport_sockets_tls_v3_common_proto_upbdefinit);
return upb_DefPool_FindMessageByName(s, "envoy.extensions.transport_sockets.tls.v3.TlsParameters");
}
UPB_INLINE const upb_MessageDef *envoy_extensions_transport_sockets_tls_v3_PrivateKeyProvider_getmsgdef(upb_DefPool *s) {
_upb_DefPool_LoadDefInit(s, &envoy_extensions_transport_sockets_tls_v3_common_proto_upbdefinit);
return upb_DefPool_FindMessageByName(s, "envoy.extensions.transport_sockets.tls.v3.PrivateKeyProvider");
}
UPB_INLINE const upb_MessageDef *envoy_extensions_transport_sockets_tls_v3_TlsCertificate_getmsgdef(upb_DefPool *s) {
_upb_DefPool_LoadDefInit(s, &envoy_extensions_transport_sockets_tls_v3_common_proto_upbdefinit);
return upb_DefPool_FindMessageByName(s, "envoy.extensions.transport_sockets.tls.v3.TlsCertificate");
}
UPB_INLINE const upb_MessageDef *envoy_extensions_transport_sockets_tls_v3_TlsSessionTicketKeys_getmsgdef(upb_DefPool *s) {
_upb_DefPool_LoadDefInit(s, &envoy_extensions_transport_sockets_tls_v3_common_proto_upbdefinit);
return upb_DefPool_FindMessageByName(s, "envoy.extensions.transport_sockets.tls.v3.TlsSessionTicketKeys");
}
UPB_INLINE const upb_MessageDef *envoy_extensions_transport_sockets_tls_v3_CertificateProviderPluginInstance_getmsgdef(upb_DefPool *s) {
_upb_DefPool_LoadDefInit(s, &envoy_extensions_transport_sockets_tls_v3_common_proto_upbdefinit);
return upb_DefPool_FindMessageByName(s, "envoy.extensions.transport_sockets.tls.v3.CertificateProviderPluginInstance");
}
UPB_INLINE const upb_MessageDef *envoy_extensions_transport_sockets_tls_v3_SubjectAltNameMatcher_getmsgdef(upb_DefPool *s) {
_upb_DefPool_LoadDefInit(s, &envoy_extensions_transport_sockets_tls_v3_common_proto_upbdefinit);
return upb_DefPool_FindMessageByName(s, "envoy.extensions.transport_sockets.tls.v3.SubjectAltNameMatcher");
}
UPB_INLINE const upb_MessageDef *envoy_extensions_transport_sockets_tls_v3_CertificateValidationContext_getmsgdef(upb_DefPool *s) {
_upb_DefPool_LoadDefInit(s, &envoy_extensions_transport_sockets_tls_v3_common_proto_upbdefinit);
return upb_DefPool_FindMessageByName(s, "envoy.extensions.transport_sockets.tls.v3.CertificateValidationContext");
}
#ifdef __cplusplus
} /* extern "C" */
#endif
#include "upb/port_undef.inc"
#endif /* ENVOY_EXTENSIONS_TRANSPORT_SOCKETS_TLS_V3_COMMON_PROTO_UPBDEFS_H_ */
| apache-2.0 |
nmldiegues/stibt | infinispan/core/src/test/java/org/infinispan/loaders/decorators/AsyncStoreTest.java | 24964 | /*
* JBoss, Home of Professional Open Source
* Copyright 2009 Red Hat Inc. and/or its affiliates and other
* contributors as indicated by the @author tags. All rights reserved.
* See the copyright.txt in the distribution for a full listing of
* individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.infinispan.loaders.decorators;
import org.infinispan.Cache;
import org.infinispan.CacheException;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.test.fwk.TestInternalCacheEntryFactory;
import org.infinispan.loaders.CacheLoaderConfig;
import org.infinispan.loaders.CacheLoaderException;
import org.infinispan.loaders.CacheLoaderMetadata;
import org.infinispan.loaders.CacheStore;
import org.infinispan.loaders.dummy.DummyInMemoryCacheStore;
import org.infinispan.loaders.modifications.Clear;
import org.infinispan.loaders.modifications.Modification;
import org.infinispan.loaders.modifications.Remove;
import org.infinispan.loaders.modifications.Store;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.CacheManagerCallable;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.transaction.xa.TransactionFactory;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import static org.infinispan.test.TestingUtil.k;
import static org.infinispan.test.TestingUtil.v;
@Test(groups = "unit", testName = "loaders.decorators.AsyncStoreTest", sequential=true)
public class AsyncStoreTest extends AbstractInfinispanTest {
private static final Log log = LogFactory.getLog(AsyncStoreTest.class);
AsyncStore store;
ExecutorService asyncExecutor;
DummyInMemoryCacheStore underlying;
AsyncStoreConfig asyncConfig;
DummyInMemoryCacheStore.Cfg dummyCfg;
@BeforeMethod
public void setUp() throws CacheLoaderException {
underlying = new DummyInMemoryCacheStore();
asyncConfig = new AsyncStoreConfig().threadPoolSize(10);
store = new AsyncStore(underlying, asyncConfig);
dummyCfg = new DummyInMemoryCacheStore.Cfg().storeName(AsyncStoreTest.class.getName());
store.init(dummyCfg, null, null);
store.start();
asyncExecutor = (ExecutorService) TestingUtil.extractField(store, "executor");
}
@AfterMethod(alwaysRun = true)
public void tearDown() throws CacheLoaderException {
if (store != null) store.stop();
}
@Test(timeOut=10000)
public void testPutRemove() throws Exception {
TestCacheManagerFactory.backgroundTestStarted(this);
final int number = 1000;
String key = "testPutRemove-k-";
String value = "testPutRemove-v-";
doTestPut(number, key, value);
doTestRemove(number, key);
}
@Test(timeOut=10000)
public void testPutClearPut() throws Exception {
TestCacheManagerFactory.backgroundTestStarted(this);
final int number = 1000;
String key = "testPutClearPut-k-";
String value = "testPutClearPut-v-";
doTestPut(number, key, value);
doTestClear(number, key);
value = "testPutClearPut-v[2]-";
doTestPut(number, key, value);
doTestRemove(number, key);
}
@Test(timeOut=10000)
public void testMultiplePutsOnSameKey() throws Exception {
TestCacheManagerFactory.backgroundTestStarted(this);
final int number = 1000;
String key = "testMultiplePutsOnSameKey-k";
String value = "testMultiplePutsOnSameKey-v-";
doTestSameKeyPut(number, key, value);
doTestSameKeyRemove(key);
}
@Test(timeOut=10000)
public void testRestrictionOnAddingToAsyncQueue() throws Exception {
TestCacheManagerFactory.backgroundTestStarted(this);
store.remove("blah");
final int number = 10;
String key = "testRestrictionOnAddingToAsyncQueue-k";
String value = "testRestrictionOnAddingToAsyncQueue-v-";
doTestPut(number, key, value);
// stop the cache store
store.stop();
try {
store.store(null);
assert false : "Should have restricted this entry from being made";
}
catch (CacheException expected) {
}
// clean up
store.start();
doTestRemove(number, key);
}
public void testThreadSafetyWritingDiffValuesForKey(Method m) throws Exception {
try {
final String key = "k1";
final CountDownLatch v1Latch = new CountDownLatch(1);
final CountDownLatch v2Latch = new CountDownLatch(1);
final CountDownLatch endLatch = new CountDownLatch(1);
DummyInMemoryCacheStore underlying = new DummyInMemoryCacheStore();
store = new MockAsyncStore(key, v1Latch, v2Latch, endLatch, underlying, asyncConfig);
dummyCfg = new DummyInMemoryCacheStore.Cfg();
dummyCfg.setStoreName(m.getName());
store.init(dummyCfg, null, null);
store.start();
store.store(TestInternalCacheEntryFactory.create(key, "v1"));
v2Latch.await();
store.store(TestInternalCacheEntryFactory.create(key, "v2"));
endLatch.await();
assert store.load(key).getValue().equals("v2");
} finally {
store.delegate.clear();
store.stop();
store = null;
}
}
public void testTransactionalModificationsHappenInDiffThread(Method m) throws Exception {
final int waitTimeout = 10;
final TimeUnit waitUnit = TimeUnit.SECONDS;
try {
final TransactionFactory gtf = new TransactionFactory();
gtf.init(false, false, true, false);
final String k1 = k(m, 1), k2 = k(m, 2), v1 = v(m, 1), v2 = v(m, 2);
final ConcurrentMap<Object, Modification> localMods = new ConcurrentHashMap<Object, Modification>();
final CyclicBarrier barrier = new CyclicBarrier(2);
DummyInMemoryCacheStore underlying = new DummyInMemoryCacheStore();
store = new AsyncStore(underlying, asyncConfig) {
@Override
protected void applyModificationsSync(List<Modification> mods) throws CacheLoaderException {
for (Modification mod : mods)
localMods.put(getKey(mod), mod);
super.applyModificationsSync(mods);
try {
barrier.await(waitTimeout, waitUnit);
} catch (TimeoutException e) {
assert false : "Timed out applying for modifications";
} catch (Exception e) {
throw new CacheLoaderException("Barrier failed", e);
}
}
private Object getKey(Modification modification) {
switch (modification.getType()) {
case STORE:
return ((Store) modification).getStoredEntry().getKey();
case REMOVE:
return ((Remove) modification).getKey();
default:
return null;
}
}
};
dummyCfg = new DummyInMemoryCacheStore.Cfg();
dummyCfg.setStoreName(m.getName());
store.init(dummyCfg, null, null);
store.start();
List<Modification> mods = new ArrayList<Modification>();
mods.add(new Store(TestInternalCacheEntryFactory.create(k1, v1)));
mods.add(new Store(TestInternalCacheEntryFactory.create(k2, v2)));
mods.add(new Remove(k1));
GlobalTransaction tx = gtf.newGlobalTransaction(null, false);
store.prepare(mods, tx, false);
assert 0 == localMods.size();
assert !store.containsKey(k1);
assert !store.containsKey(k2);
store.commit(tx);
barrier.await(waitTimeout, waitUnit); // Wait for store
barrier.await(waitTimeout, waitUnit); // Wait for remove
assert store.load(k2).getValue().equals(v2);
assert !store.containsKey(k1);
assert 2 == localMods.size();
assert new Remove(k1).equals(localMods.get(k1));
} finally {
store.delegate.clear();
store.stop();
store = null;
}
}
public void testTransactionalModificationsAreCoalesced(Method m) throws Exception {
final int waitTimeout = 10;
final TimeUnit waitUnit = TimeUnit.SECONDS;
try {
final TransactionFactory gtf = new TransactionFactory();
gtf.init(false, false, true, false);
final String k1 = k(m, 1), k2 = k(m, 2), k3 = k(m, 3), v1 = v(m, 1), v2 = v(m, 2), v3 = v(m, 3);
final AtomicInteger storeCount = new AtomicInteger();
final AtomicInteger removeCount = new AtomicInteger();
final AtomicInteger clearCount = new AtomicInteger();
final CyclicBarrier barrier = new CyclicBarrier(2);
DummyInMemoryCacheStore underlying = new DummyInMemoryCacheStore() {
@Override
public void store(InternalCacheEntry ed) {
super.store(ed);
storeCount.getAndIncrement();
}
@Override
public boolean remove(Object key) {
boolean ret = super.remove(key);
removeCount.getAndIncrement();
return ret;
}
@Override
public void clear() {
super.clear();
clearCount.getAndIncrement();
}
};
store = new AsyncStore(underlying, asyncConfig) {
@Override
protected void applyModificationsSync(List<Modification> mods)
throws CacheLoaderException {
super.applyModificationsSync(mods);
try {
log.tracef("Wait to apply modifications: %s", mods);
barrier.await(waitTimeout, waitUnit);
} catch (TimeoutException e) {
assert false : "Timed out applying for modifications";
} catch (Exception e) {
throw new CacheLoaderException("Barrier failed", e);
}
}
};
dummyCfg = new DummyInMemoryCacheStore.Cfg();
dummyCfg.setStoreName(m.getName());
store.init(dummyCfg, null, null);
store.start();
List<Modification> mods = new ArrayList<Modification>();
mods.add(new Store(TestInternalCacheEntryFactory.create(k1, v1)));
mods.add(new Store(TestInternalCacheEntryFactory.create(k1, v2)));
mods.add(new Store(TestInternalCacheEntryFactory.create(k2, v1)));
mods.add(new Store(TestInternalCacheEntryFactory.create(k2, v2)));
mods.add(new Remove(k1));
GlobalTransaction tx = gtf.newGlobalTransaction(null, false);
store.prepare(mods, tx, false);
Thread.sleep(200); //verify that work is not performed until commit
assert 0 == storeCount.get();
assert 0 == removeCount.get();
assert 0 == clearCount.get();
store.commit(tx);
log.tracef("Wait for modifications to be queued: %s", mods);
barrier.await(waitTimeout, waitUnit); // Wait for single store to be applied
barrier.await(waitTimeout, waitUnit); // Wait for single remove to be applied
assert 1 == storeCount.get() : "Store count was " + storeCount.get();
assert 1 == removeCount.get();
assert 0 == clearCount.get();
storeCount.set(0);
removeCount.set(0);
clearCount.set(0);
mods = new ArrayList<Modification>();
mods.add(new Store(TestInternalCacheEntryFactory.create(k1, v1)));
mods.add(new Remove(k1));
mods.add(new Clear());
mods.add(new Store(TestInternalCacheEntryFactory.create(k2, v2)));
mods.add(new Remove(k2));
tx = gtf.newGlobalTransaction(null, false);
store.prepare(mods, tx, false);
Thread.sleep(200); //verify that work is not performed until commit
assert 0 == storeCount.get();
assert 0 == removeCount.get();
assert 0 == clearCount.get();
store.commit(tx);
barrier.await(waitTimeout, waitUnit);
assert 0 == storeCount.get() : "Store count was " + storeCount.get();
assert 1 == removeCount.get();
assert 1 == clearCount.get();
storeCount.set(0);
removeCount.set(0);
clearCount.set(0);
mods = new ArrayList<Modification>();
mods.add(new Store(TestInternalCacheEntryFactory.create(k1, v1)));
mods.add(new Remove(k1));
mods.add(new Store(TestInternalCacheEntryFactory.create(k2, v2)));
mods.add(new Remove(k2));
mods.add(new Store(TestInternalCacheEntryFactory.create(k3, v3)));
tx = gtf.newGlobalTransaction(null, false);
store.prepare(mods, tx, false);
Thread.sleep(200);
assert 0 == storeCount.get();
assert 0 == removeCount.get();
assert 0 == clearCount.get();
store.commit(tx);
barrier.await(waitTimeout, waitUnit); // Wait for store to be applied
barrier.await(waitTimeout, waitUnit); // Wait for first removal to be applied
barrier.await(waitTimeout, waitUnit); // Wait for second removal to be applied
assert 1 == storeCount.get() : "Store count was " + storeCount.get();
assert 2 == removeCount.get();
assert 0 == clearCount.get();
storeCount.set(0);
removeCount.set(0);
clearCount.set(0);
mods = new ArrayList<Modification>();
mods.add(new Clear());
mods.add(new Remove(k1));
tx = gtf.newGlobalTransaction(null, false);
store.prepare(mods, tx, false);
Thread.sleep(200);
assert 0 == storeCount.get();
assert 0 == removeCount.get();
assert 0 == clearCount.get();
store.commit(tx);
barrier.await(waitTimeout, waitUnit);
assert 0 == storeCount.get() : "Store count was " + storeCount.get();
assert 1 == removeCount.get();
assert 1 == clearCount.get();
storeCount.set(0);
removeCount.set(0);
clearCount.set(0);
mods = new ArrayList<Modification>();
mods.add(new Clear());
mods.add(new Store(TestInternalCacheEntryFactory.create(k1, v1)));
tx = gtf.newGlobalTransaction(null, false);
store.prepare(mods, tx, false);
Thread.sleep(200);
assert 0 == storeCount.get();
assert 0 == removeCount.get();
assert 0 == clearCount.get();
store.commit(tx);
barrier.await(waitTimeout, waitUnit);
assert 1 == storeCount.get() : "Store count was " + storeCount.get();
assert 0 == removeCount.get();
assert 1 == clearCount.get();
} finally {
store.delegate.clear();
store.stop();
store = null;
}
}
private void doTestPut(int number, String key, String value) throws Exception {
for (int i = 0; i < number; i++) {
InternalCacheEntry cacheEntry = TestInternalCacheEntryFactory.create(key + i, value + i);
store.store(cacheEntry);
}
for (int i = 0; i < number; i++) {
InternalCacheEntry ice = store.load(key + i);
assert ice != null && (value + i).equals(ice.getValue());
}
}
private void doTestSameKeyPut(int number, String key, String value) throws Exception {
for (int i = 0; i < number; i++) {
store.store(TestInternalCacheEntryFactory.create(key, value + i));
}
InternalCacheEntry ice = store.load(key);
assert ice != null && (value + (number - 1)).equals(ice.getValue());
}
private void doTestRemove(int number, String key) throws Exception {
for (int i = 0; i < number; i++) store.remove(key + i);
for (int i = 0; i < number; i++) {
String loadKey = key + i;
assert store.load(loadKey) == null : loadKey + " still in store";
}
}
private void doTestSameKeyRemove(String key) throws Exception {
store.remove(key);
assert store.load(key) == null;
}
private void doTestClear(int number, String key) throws Exception {
store.clear();
for (int i = 0; i < number; i++) {
assert store.load(key + i) == null;
}
}
static class MockAsyncStore extends AsyncStore {
volatile boolean block = true;
final CountDownLatch v1Latch;
final CountDownLatch v2Latch;
final CountDownLatch endLatch;
final Object key;
MockAsyncStore(Object key, CountDownLatch v1Latch, CountDownLatch v2Latch, CountDownLatch endLatch,
CacheStore delegate, AsyncStoreConfig asyncStoreConfig) {
super(delegate, asyncStoreConfig);
this.v1Latch = v1Latch;
this.v2Latch = v2Latch;
this.endLatch = endLatch;
this.key = key;
}
@Override
protected void applyModificationsSync(List<Modification> mods) throws CacheLoaderException {
boolean keyFound = findModificationForKey(key, mods) != null;
if (keyFound && block) {
log.trace("Wait for v1 latch");
try {
v2Latch.countDown();
block = false;
v1Latch.await(2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
super.applyModificationsSync(mods);
} else if (keyFound && !block) {
log.trace("Do v2 modification and unleash v1 latch");
super.applyModificationsSync(mods);
v1Latch.countDown();
endLatch.countDown();
}
}
private Modification findModificationForKey(Object key, List<Modification> mods) {
for (Modification modification : mods) {
switch (modification.getType()) {
case STORE:
Store store = (Store) modification;
if (store.getStoredEntry().getKey().equals(key))
return store;
break;
case REMOVE:
Remove remove = (Remove) modification;
if (remove.getKey().equals(key))
return remove;
break;
default:
return null;
}
}
return null;
}
}
private final static ThreadLocal<LockableCacheStore> STORE = new ThreadLocal<LockableCacheStore>();
public static class LockableCacheStoreConfig extends DummyInMemoryCacheStore.Cfg {
private static final long serialVersionUID = 1L;
public LockableCacheStoreConfig() {
setCacheLoaderClassName(LockableCacheStore.class.getName());
}
}
@CacheLoaderMetadata(configurationClass = LockableCacheStoreConfig.class)
public static class LockableCacheStore extends DummyInMemoryCacheStore {
private final ReentrantLock lock = new ReentrantLock();
public LockableCacheStore() {
super();
STORE.set(this);
}
@Override
public Class<? extends CacheLoaderConfig> getConfigurationClass() {
return LockableCacheStoreConfig.class;
}
@Override
public void store(InternalCacheEntry ed) {
lock.lock();
try {
super.store(ed);
} finally {
lock.unlock();
}
}
@Override
public boolean remove(Object key) {
lock.lock();
try {
return super.remove(key);
} finally {
lock.unlock();
}
}
}
public void testModificationQueueSize(final Method m) throws Exception {
LockableCacheStore underlying = new LockableCacheStore();
asyncConfig.modificationQueueSize(10);
store = new AsyncStore(underlying, asyncConfig);
store.init(new LockableCacheStoreConfig(), null, null);
store.start();
try {
final CountDownLatch done = new CountDownLatch(1);
underlying.lock.lock();
try {
Thread t = new Thread() {
@Override
public void run() {
try {
for (int i = 0; i < 100; i++)
store.store(TestInternalCacheEntryFactory.create(k(m, i), v(m, i)));
} catch (Exception e) {
log.error("Error storing entry", e);
}
done.countDown();
}
};
t.start();
assert !done.await(1, TimeUnit.SECONDS) : "Background thread should have blocked after adding 10 entries";
} finally {
underlying.lock.unlock();
}
} finally {
store.stop();
}
}
private static abstract class OneEntryCacheManagerCallable extends CacheManagerCallable {
protected final Cache<String, String> cache;
protected final LockableCacheStore store;
private static ConfigurationBuilder config(boolean passivation) {
ConfigurationBuilder config = new ConfigurationBuilder();
config.eviction().maxEntries(1).loaders().passivation(passivation).addStore()
.cacheStore(new LockableCacheStore()).async().enable();
return config;
}
OneEntryCacheManagerCallable(boolean passivation) {
super(TestCacheManagerFactory.createCacheManager(config(passivation)));
cache = cm.getCache();
store = STORE.get();
}
}
public void testEndToEndPutPutPassivation() throws Exception {
doTestEndToEndPutPut(true);
}
public void testEndToEndPutPut() throws Exception {
doTestEndToEndPutPut(false);
}
private void doTestEndToEndPutPut(boolean passivation) throws Exception {
TestingUtil.withCacheManager(new OneEntryCacheManagerCallable(passivation) {
@Override
public void call() {
cache.put("X", "1");
cache.put("Y", "1"); // force eviction of "X"
// wait for X == 1 to appear in store
while (store.load("X") == null)
TestingUtil.sleepThread(10);
// simulate slow back end store
store.lock.lock();
try {
cache.put("X", "2");
cache.put("Y", "2"); // force eviction of "X"
assert "2".equals(cache.get("X")) : "cache must return X == 2";
} finally {
store.lock.unlock();
}
}
});
}
public void testEndToEndPutRemovePassivation() throws Exception {
doTestEndToEndPutRemove(true);
}
public void testEndToEndPutRemove() throws Exception {
doTestEndToEndPutRemove(false);
}
private void doTestEndToEndPutRemove(boolean passivation) throws Exception {
TestingUtil.withCacheManager(new OneEntryCacheManagerCallable(passivation) {
@Override
public void call() {
cache.put("X", "1");
cache.put("Y", "1"); // force eviction of "X"
// wait for "X" to appear in store
while (store.load("X") == null)
TestingUtil.sleepThread(10);
// simulate slow back end store
store.lock.lock();
try {
cache.remove("X");
assert null == cache.get("X") : "cache must return X == null";
} finally {
store.lock.unlock();
}
}
});
}
}
| apache-2.0 |
papicella/snappy-store | tests/core/src/main/java/versioning/newWan/WANConflictResolver.java | 2212 | /*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package versioning.newWan;
import versioning.VersionBB;
import newWan.WANOperationsClientBB;
import hydra.Log;
import com.gemstone.gemfire.LogWriter;
import com.gemstone.gemfire.cache.util.GatewayConflictHelper;
import com.gemstone.gemfire.cache.util.GatewayConflictResolver;
import com.gemstone.gemfire.cache.util.TimestampedEntryEvent;
import com.gemstone.gemfire.pdx.PdxInstance;
/**
* Custom wan conflict resolver
* @author rdiyewar
*
*/
public class WANConflictResolver implements GatewayConflictResolver {
LogWriter log = Log.getLogWriter();
WANOperationsClientBB bb = WANOperationsClientBB.getBB();
public void onEvent(TimestampedEntryEvent event, GatewayConflictHelper helper) {
bb.getSharedCounters().increment(WANOperationsClientBB.WanEventResolved);
log.info("WANConflictResolver: existing timestamp=" + event.getOldTimestamp() + " existing value=" + event.getOldValue()
+ "\n proposed timestamp=" + event.getNewTimestamp() + " proposed value=" + event.getNewValue());
// use the default timestamp and ID based resolution
if (event.getOldTimestamp() > event.getNewTimestamp()) {
log.info("New event is older, disallow the event " + event);
helper.disallowEvent();
}
if (event.getOldTimestamp() == event.getNewTimestamp()
&& event.getOldDistributedSystemID() > event.getNewDistributedSystemID()) {
log.info("Both event has same timestamp, but new event's ds id small. Thus dissallow the event " + event);
helper.disallowEvent();
}
}
}
| apache-2.0 |
dancollins/libnarm | vendor/STM32F0xx_StdPeriph_Lib_V1.3.1/Projects/STM32F0xx_StdPeriph_Examples/NVIC/NVIC_WFI_Mode/main.h | 1930 | /**
******************************************************************************
* @file NVIC/NVIC_WFI_Mode/main.h
* @author MCD Application Team
* @version V1.3.0
* @date 16-January-2014
* @brief Header for main.c module
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2014 STMicroelectronics</center></h2>
*
* Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2
*
* 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.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __MAIN_H
#define __MAIN_H
/* Includes ------------------------------------------------------------------*/
#include "stm32f0xx.h"
#ifdef USE_STM320518_EVAL
#include "stm320518_eval.h"
#else
#include "stm32072b_eval.h"
#endif /* USE_STM320518_EVAL */
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
#endif /* __MAIN_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| apache-2.0 |
jdel/clairctl | vendor/github.com/opencontainers/runtime-spec/Makefile | 3244 |
EPOCH_TEST_COMMIT := 78e6667ae2d67aad100b28ee9580b41b7a24e667
OUTPUT_DIRNAME ?= output/
DOC_FILENAME ?= oci-runtime-spec
DOCKER ?= $(shell command -v docker 2>/dev/null)
PANDOC ?= $(shell command -v pandoc 2>/dev/null)
ifeq "$(strip $(PANDOC))" ''
ifneq "$(strip $(DOCKER))" ''
PANDOC = $(DOCKER) run \
-it \
--rm \
-v $(shell pwd)/:/input/:ro \
-v $(shell pwd)/$(OUTPUT_DIRNAME)/:/$(OUTPUT_DIRNAME)/ \
-u $(shell id -u) \
vbatts/pandoc
PANDOC_SRC := /input/
PANDOC_DST := /
endif
endif
# These docs are in an order that determines how they show up in the PDF/HTML docs.
DOC_FILES := \
version.md \
README.md \
code-of-conduct.md \
principles.md \
style.md \
ROADMAP.md \
implementations.md \
project.md \
bundle.md \
runtime.md \
runtime-linux.md \
config.md \
config-linux.md \
config-solaris.md \
glossary.md
default: docs
.PHONY: docs
docs: $(OUTPUT_DIRNAME)/$(DOC_FILENAME).pdf $(OUTPUT_DIRNAME)/$(DOC_FILENAME).html
ifeq "$(strip $(PANDOC))" ''
$(OUTPUT_DIRNAME)/$(DOC_FILENAME).pdf $(OUTPUT_DIRNAME)/$(DOC_FILENAME).html:
$(error cannot build $@ without either pandoc or docker)
else
$(OUTPUT_DIRNAME)/$(DOC_FILENAME).pdf: $(DOC_FILES)
mkdir -p $(OUTPUT_DIRNAME)/ && \
$(PANDOC) -f markdown_github -t latex -o $(PANDOC_DST)$@ $(patsubst %,$(PANDOC_SRC)%,$(DOC_FILES))
$(OUTPUT_DIRNAME)/$(DOC_FILENAME).html: $(DOC_FILES)
mkdir -p $(OUTPUT_DIRNAME)/ && \
$(PANDOC) -f markdown_github -t html5 -o $(PANDOC_DST)$@ $(patsubst %,$(PANDOC_SRC)%,$(DOC_FILES))
endif
code-of-conduct.md:
curl -o $@ https://raw.githubusercontent.com/opencontainers/tob/d2f9d68c1332870e40693fe077d311e0742bc73d/code-of-conduct.md
version.md: ./specs-go/version.go
go run ./.tool/version-doc.go > $@
HOST_GOLANG_VERSION = $(shell go version | cut -d ' ' -f3 | cut -c 3-)
# this variable is used like a function. First arg is the minimum version, Second arg is the version to be checked.
ALLOWED_GO_VERSION = $(shell test '$(shell /bin/echo -e "$(1)\n$(2)" | sort -V | head -n1)' = '$(1)' && echo 'true')
.PHONY: test .govet .golint .gitvalidation
test: .govet .golint .gitvalidation
.govet:
go vet -x ./...
# `go get github.com/golang/lint/golint`
.golint:
ifeq ($(call ALLOWED_GO_VERSION,1.5,$(HOST_GOLANG_VERSION)),true)
@which golint > /dev/null 2>/dev/null || (echo "ERROR: golint not found. Consider 'make install.tools' target" && false)
golint ./...
endif
# When this is running in travis, it will only check the travis commit range
.gitvalidation:
@which git-validation > /dev/null 2>/dev/null || (echo "ERROR: git-validation not found. Consider 'make install.tools' target" && false)
ifeq ($(TRAVIS),true)
git-validation -q -run DCO,short-subject,dangling-whitespace
else
git-validation -v -run DCO,short-subject,dangling-whitespace -range $(EPOCH_TEST_COMMIT)..HEAD
endif
.PHONY: install.tools
install.tools: .install.golint .install.gitvalidation
# golint does not even build for <go1.5
.install.golint:
ifeq ($(call ALLOWED_GO_VERSION,1.5,$(HOST_GOLANG_VERSION)),true)
go get -u github.com/golang/lint/golint
endif
.install.gitvalidation:
go get -u github.com/vbatts/git-validation
.PHONY: clean
clean:
rm -rf $(OUTPUT_DIRNAME) *~
rm -f code-of-conduct.md version.md
| apache-2.0 |
lukecwik/incubator-beam | sdks/java/io/kinesis/src/main/java/org/apache/beam/sdk/io/kinesis/BasicKinesisProvider.java | 4391 | /*
* 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.beam.sdk.io.kinesis;
import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkArgument;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.cloudwatch.AmazonCloudWatch;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchClientBuilder;
import com.amazonaws.services.kinesis.AmazonKinesis;
import com.amazonaws.services.kinesis.AmazonKinesisClientBuilder;
import com.amazonaws.services.kinesis.producer.IKinesisProducer;
import com.amazonaws.services.kinesis.producer.KinesisProducer;
import com.amazonaws.services.kinesis.producer.KinesisProducerConfiguration;
import java.net.URI;
import org.checkerframework.checker.nullness.qual.Nullable;
/** Basic implementation of {@link AWSClientsProvider} used by default in {@link KinesisIO}. */
class BasicKinesisProvider implements AWSClientsProvider {
private final String accessKey;
private final String secretKey;
private final Regions region;
private final @Nullable String serviceEndpoint;
private final boolean verifyCertificate;
BasicKinesisProvider(
String accessKey,
String secretKey,
Regions region,
@Nullable String serviceEndpoint,
boolean verifyCertificate) {
checkArgument(accessKey != null, "accessKey can not be null");
checkArgument(secretKey != null, "secretKey can not be null");
checkArgument(region != null, "region can not be null");
this.accessKey = accessKey;
this.secretKey = secretKey;
this.region = region;
this.serviceEndpoint = serviceEndpoint;
this.verifyCertificate = verifyCertificate;
}
BasicKinesisProvider(
String accessKey, String secretKey, Regions region, @Nullable String serviceEndpoint) {
this(accessKey, secretKey, region, serviceEndpoint, true);
}
private AWSCredentialsProvider getCredentialsProvider() {
return new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey));
}
@Override
public AmazonKinesis getKinesisClient() {
AmazonKinesisClientBuilder clientBuilder =
AmazonKinesisClientBuilder.standard().withCredentials(getCredentialsProvider());
if (serviceEndpoint == null) {
clientBuilder.withRegion(region);
} else {
clientBuilder.withEndpointConfiguration(
new AwsClientBuilder.EndpointConfiguration(serviceEndpoint, region.getName()));
}
return clientBuilder.build();
}
@Override
public AmazonCloudWatch getCloudWatchClient() {
AmazonCloudWatchClientBuilder clientBuilder =
AmazonCloudWatchClientBuilder.standard().withCredentials(getCredentialsProvider());
if (serviceEndpoint == null) {
clientBuilder.withRegion(region);
} else {
clientBuilder.withEndpointConfiguration(
new AwsClientBuilder.EndpointConfiguration(serviceEndpoint, region.getName()));
}
return clientBuilder.build();
}
@Override
public IKinesisProducer createKinesisProducer(KinesisProducerConfiguration config) {
config.setRegion(region.getName());
config.setCredentialsProvider(getCredentialsProvider());
if (serviceEndpoint != null) {
URI uri = URI.create(serviceEndpoint);
config.setKinesisEndpoint(uri.getHost());
config.setKinesisPort(uri.getPort());
}
config.setVerifyCertificate(verifyCertificate);
return new KinesisProducer(config);
}
}
| apache-2.0 |
AdrienKuhn/hackazon | modules/vulninjection/classes/VulnModule/Vulnerability/CSRF.php | 695 | <?php
/**
* Created by IntelliJ IDEA.
* User: Nikolay Chervyakov
* Date: 02.12.2014
* Time: 18:21
*/
namespace VulnModule\Vulnerability;
use VulnModule\Vulnerability;
/**
* Class SQL
* @package VulnModule\Vulnerability
* @Vuln\Vulnerability(name="Cross-site request forgery", "A type of malicious exploit of a website whereby
* unauthorized commands are transmitted from a user that the website trusts. Unlike cross-site scripting (XSS),
* which exploits the trust a user has for a particular site, CSRF exploits the trust that a site has in a user's browser.")
*/
class CSRF extends Vulnerability
{
public static $targets = [self::TARGET_CONTEXT];
} | apache-2.0 |
Qi4j/qi4j-sdk | core/api/src/main/java/org/apache/polygene/api/service/qualifier/Available.java | 1786 | /*
* 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.polygene.api.service.qualifier;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.function.Predicate;
import org.apache.polygene.api.service.ServiceReference;
/**
* Filter services based on whether they are available or not.
*
* At an injection point you can do this:
*
* <pre><code>
* @Service @Available MyService service;
* </code></pre>
* to get only a service that is currently available.
*/
@Retention( RetentionPolicy.RUNTIME )
@Qualifier( Available.AvailableQualifier.class )
public @interface Available
{
/**
* Available Annotation Qualifier.
* See {@link Available}.
*/
final class AvailableQualifier
implements AnnotationQualifier<Available>
{
@Override
public <T> Predicate<ServiceReference<?>> qualifier( Available active )
{
return ServiceQualifier.whereAvailable();
}
}
}
| apache-2.0 |
dillia23/code-dot-org | pegasus/sites.v3/hourofcode.com/i18n/public/bg/promote/proclamation.md | 7354 | ---
title: <%= hoc_s(:title_proclamation) %>
layout: wide
nav: promote_nav
---
### По-долу е примерна резолюция в подкрепа на CSEW и нейните цели, които могат да бъдат използвани от държавните и местните законодатели.
[Къща, СЕНАТА, държава, област или град резолюция или ОБЯВЯВЛЕНИЕ ###] – като има предвид, че CSEW подчертава решаващата роля, която играят компютърните науки в развитието на нашето общество и как компютърните науки позволяват да се случват иновациите и създават икономически възможности;
[РЕЗОЛЮЦИЯ ###]
[DATE]
Като има предвид, че компютърните технологии са неразделна част от културата и трансформират начина, по който хората си взаимодействат и въздействат на света около тях;
Като има предвид, че компютърните науки променят индустрията, създават нови сфери в търговията, насърчават иновациите във всички области на науката, както и стимулират производителността в установените икономически сектори;
Като има предвид, че областта на компютърните науки укрепва сектора на информационните технологии на нашата икономика, която е значителен принос за Съединените щати и тяхната икономическа производителност;
Като има предвид, че компютърните науки са фундаментални за дигиталната ера;
Като има предвид, че сектора на информационните технологии е в уникалната позиция да помогне с икономическото възстановяване чрез научни изследвания и развитие на нови иновации;
Като има предвид, че перспективите за работни места, свързани с компютърните науки нарастват с едно за всеки две STEM работни места в страната;
Като има предвид, че предоставянето на учениците възможност да участват в дейности с висококачествени компютърни уроци им създава богати възможности и им създава умения за критично мислене, които ще им служат през целия живот;
Като има предвид, че всички ученици заслужават задълбочена подготовка в компютърните науки, включително достъп до квалифицирани преподаватели, технология, както и подходящи за възрастта учебна програма, означава, че трябва учениците да учат компютърни науки в началните и средните нива на образование;
Като има предвид, че в образованието по компютърни науки има предизвикателства, включително прибавяне компютърните науки към изискването за дипломиране, както и предоставяне на професионално развитие за преподавателите по компютърни науки;
Като има предвид, че участието в Часът на кодирането по време на CSEW може да служи за демистифициране на областта на компютърните науки и да насърчи повече студенти да продължат обучението си по компютърни науки;
Като има предвид, че областта на компютърни науки има значителни капиталови бариери, включително и привличане на повече участие на жените и слабо представените малцинства на всички нива и клонове;
Като има предвид, че Грейс Мъри Хопър, една от първите жени в областта на компютърните науки, инженер, пионер в програмирането и пионер в стандартите за компютърни системи, които стават основа за много подобрения в компютърните науки; и
Като се има предвид че седмицата на <%= campaign_date('start-long') %>, е в чест на рождения ден на Грейс Хопър, е определен като "Седмица на компютърните науки в образованието": сега, следователно, ще бъде
Решено, че [СЕНАТЪТ, областта, градът / училището]--
(1) подкрепя определянето на седмицата на компютърните науки в образованието (<%= campaign_date('full') %>);
(2) насърчава училища, педагози, родители и политици да участват в CSEW като дават възможност на своите студенти да участват в Часът на кодирането;
(3) насърчава училища, учители, изследователи, университети, бизнес лидери и политици да определят механизми, по които учители да получат професионално развитие за да осигурят устойчив обучителен опит по компютърни науки на всички образователни нива и насърчава учениците даизучат компютърните концепции и понятия;
(4) насърчава политиците да премахнат бариерите, които пречат на изискването компютърните курсове да носят кредитни точки по математика или наука при завършване;
(5) насърчава възможности, включително чрез съществуващи програми, за участие на жените и слабо представените малцинства в компютърните науки.
| apache-2.0 |
mboudreau/Alternator | src/test/java/com/michelboudreau/test/TestClassWithHashRangeKey.java | 1515 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.michelboudreau.test;
import com.amazonaws.services.dynamodb.datamodeling.DynamoDBAttribute;
import com.amazonaws.services.dynamodb.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodb.datamodeling.DynamoDBRangeKey;
import com.amazonaws.services.dynamodb.datamodeling.DynamoDBTable;
@DynamoDBTable(tableName = "mapper.TestClassWithRangeHashKey")
public class TestClassWithHashRangeKey
{
private String hashCode;
private String rangeCode;
private String stringData;
private int intData;
@DynamoDBHashKey(attributeName = "hashCode")
public final String getHashCode()
{
return hashCode;
}
public final void setHashCode(String hashCode)
{
this.hashCode = hashCode;
}
@DynamoDBRangeKey(attributeName = "rangeCode")
public final String getRangeCode()
{
return rangeCode;
}
public final void setRangeCode(String rangeCode)
{
this.rangeCode = rangeCode;
}
@DynamoDBAttribute(attributeName = "stringData")
public String getStringData()
{
return stringData;
}
public void setStringData(String stringData)
{
this.stringData = stringData;
}
@DynamoDBAttribute(attributeName = "intData")
public int getIntData()
{
return intData;
}
public void setIntData(int intData)
{
this.intData = intData;
}
}
| apache-2.0 |
datamountaineer/stream-reactor | kafka-connect-hive/src/test/scala/com/landoop/streamreactor/connect/hive/source/offset/MockOffsetStorageReader.scala | 803 | package com.landoop.streamreactor.connect.hive.source.offset
import java.util
import com.landoop.streamreactor.connect.hive.source.{SourceOffset, SourcePartition, fromSourceOffset, toSourcePartition}
import org.apache.kafka.connect.storage.OffsetStorageReader
import scala.collection.JavaConverters._
class MockOffsetStorageReader(map: Map[SourcePartition, SourceOffset]) extends OffsetStorageReader {
override def offsets[T](partitions: util.Collection[util.Map[String, T]]): util.Map[util.Map[String, T], util.Map[String, AnyRef]] = ???
override def offset[T](partition: util.Map[String, T]): util.Map[String, AnyRef] = {
val sourcePartition = toSourcePartition(partition.asScala.toMap.mapValues(_.toString))
map.get(sourcePartition).map(fromSourceOffset).map(_.asJava).orNull
}
}
| apache-2.0 |
dotty-staging/dotty | tests/neg/i10605.scala | 289 | def xa[A, B, X, Y](f: X => ((A, B) ?=> Y)) =
(z: X) => (a: A, b: B) => f(z)(using a, b)
def superxa1(using String, Int): Nothing = ???
def superxa2(using String, Int): Unit = ???
def main =
xa(Function.const(superxa1)(_: Int)) // error
xa(Function.const(superxa2)(_: Int)) // error | apache-2.0 |
nvoron23/socialite | src/socialite/collection/SLongIntHashMap.java | 886 | package socialite.collection;
import gnu.trove.map.hash.TLongIntHashMap;
public class SLongIntHashMap extends TLongIntHashMap {
long prevKey;
int prevVal;
public SLongIntHashMap(int initCapacity, float f, long noEntryKey, int noEntryValue) {
super(initCapacity, f, noEntryKey, noEntryValue);
prevKey = noEntryValue;
prevVal = noEntryValue;
}
@Override
public int get(long key) {
if (prevKey!=super.no_entry_key && key==prevKey) {
return prevVal;
}
prevKey = key;
prevVal = super.get(key);
return prevVal;
}
@Override
public int put(long key, int value) {
prevKey = key;
prevVal = value;
return super.put(key, value);
}
@Override
public int remove(long key) {
prevKey = super.no_entry_key;
prevVal = super.no_entry_value;
return super.remove(key);
}
@Override
public void clear() {
prevKey=super.no_entry_key;
super.clear();
}
}
| apache-2.0 |
joelaha/devopsdays-web | static/events/2015-newyork/proposals/AgentOfChange/index.html | 14772 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" >
<meta name="google-site-verification" content="GcrnbgZkRkwn51jQmX7QBaMKSymq1h-iG8G_xeILIkM" />
<title>Agent of Change? Here's Your Helmet.</title>
<meta name="author" content="Waldo Grunenwald" >
<link rel="alternate" type="application/rss+xml" title="devopsdays RSS Feed" href="http://www.devopsdays.org/feed/" >
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('jquery', '1.3.2');
</script>
<!---This is a combined jAmpersand, jqwindont , jPullquote -->
<script type="text/javascript" src="/js/devops.js"></script>
<!--- Blueprint CSS Framework Screen + Fancytype-Screen + jedi.css -->
<link rel="stylesheet" href="/css/devops.min.css" type="text/css" media="screen, projection">
<link rel="stylesheet" href="/css/blueprint/print.css" type="text/css" media="print">
<!--[if IE]>
<link rel="stylesheet" href="/css/blueprint/ie.css" type="text/css" media="screen, projection">
<![endif]-->
<!--
Customize the labels on the map
*References*
- http://code.google.com/apis/maps/documentation/javascript/maptypes.html#StyledMaps
- http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.1/examples/basic.html
-->
<link href="/css/googlemaps.css" rel="stylesheet">
</head>
<body onload="initialize()">
<div class="container ">
<div class="span-24 last" id="header">
<div class="span-16 first">
<img src="/images/devopsdays-banner.png" title="devopsdays banner" width="801" height="115" alt="devopdays banner" ><br>
</div>
<div class="span-8 last">
</div>
</div>
<div class="span-24 last">
<div id="headermenu">
<table >
<tr>
<td>
<a href="/"><img alt="home" title="home" src="/images/home.png"></a>
<a href="/">Home</a>
</td>
<td>
<a href="/contact/"><img alt="contact" title="contact" src="/images/contact.png"></a>
<a href="/contact/">Contact</a>
</td>
<td>
<a href="/events/"><img alt="events" title="events" src="/images/events.png"></a>
<a href="/events/">Events</a>
</td>
<td>
<a href="/presentations/"><img alt="presentations" title="presentations" src="/images/presentations.png"></a>
<a href="/presentations/">Presentations</a>
</td>
<td>
<a href="/blog/"><img alt="blog" title="blog" src="/images/blog.png"></a>
<a href="/blog/">Blog</a>
</td>
</tr>
</table>
</div>
</div>
<div class="span-24 last" id="header">
<div class="span-15 first">
<h1>Agent of Change? Here's Your Helmet. </h1>
</div>
<div class="span-8 last">
<div>
<a href="/feed"><img width="32px" height="32px" alt="rss" title="rss feed" src="/images/feed.png"></a>
<a href="http://www.twitter.com/devopsdays"><img width="32px" height="32px" alt="twitter" title="twitter" src="/images/twitter.png"></a>
<a href="http://groups.google.com/group/devopsdays"><img width="32px" height="32px" alt="mail" title="mailinglist" src="/images/email.png"></a>
<a href="http://www.facebook.com/group.php?gid=106761636771"><img width="32px" height="32px" alt="mail" title="facebook" src="/images/facebook.png"></a>
<a href="http://www.linkedin.com/groups?home=&gid=2445279"><img width="32px" height="32px" alt="mail" title="linkedin" src="/images/linkedin.png"></a>
</div>
</div>
</div>
<div class="span-15 ">
<div class="span-15 last ">
<p><strong>Abstract:</strong>
A company that wants help bootstrapping a DevOps culture shift may seem like an attractive move for someone who is looking to make a move? What's not to like? There seems to be a lot of these jobs now. It looks like a chance to make your name, and heavily influence a culture that wants to be influenced.</p>
<p>But this path is fraught with peril. Choosing the wrong company - especially as an Agent of Change - could harm your health and your career. In this talk, I will describe</p>
<ul>
<li>What problems do they want you to solve?</li>
<li>The ways that companies delude themselves.</li>
<li>The people that you'll meet.</li>
<li>The roadblocks that you'll encounter.</li>
<li>The questions that you should ask before deciding to take the job.</li>
</ul>
<p><strong>Speaker:</strong>
Waldo Grunenwald</p>
</div>
<div class="span-15 first last">
<script type="text/javascript">
// var disqus_developer = 1;
</script>
<div id="disqus_thread"></div>
<script type="text/javascript">
var disqus_shortname = 'devopsdays';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">blog comments powered by <span class="logo-disqus">Disqus</span></a>
<hr>
</div>
</div>
<div class="span-8 last">
<div class="span-8 last">
<div style="height:340px">
<a class="twitter-timeline" data-chrome="noheader nofooter" data-tweet-limit=2 data-dnt="true" href="https://twitter.com/devopsdaysmsp/lists/devopsdays" data-widget-id="720829916510466048">Tweets from devopsdays events</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
</div>
</div>
</div>
<div class="span-17 ">
<div style=" padding-top:18px;" class="span-7 last">
<h1>Past </h1>
</div>
<div class="span-17 ">
<div style="height:700px;" id="quicklinks">
<table>
<tr>
<div style="display:table-cell; vertical-align:top">
<div style="margin:1px;">
<strong>2009</strong><br/>
<a href="/events/2009-ghent/">Ghent 2009</a>
</div>
<br>
<div style="margin:1px;">
<strong>2010</strong><br/>
<a href="/events/2010-sydney/">Sydney 2010</a><br>
<a href="/events/2010-us/">Mountain View 2010</a><br>
<a href="/events/2010-europe/">Hamburg 2010</a><br>
<a href="/events/2010-brazil/">Sao Paulo 2010</a><br>
</div>
</div>
<div style="display:table-cell; vertical-align:top">
<div style="margin:1px;">
<strong>2011</strong><br/>
<a href="/events/2011-boston/">Boston 2011</a><br>
<a href="/events/2011-mountainview/">Mountain View 2011</a><br>
<a href="/events/2011-melbourne/">Melbourne 2011</a><br>
<a href="/events/2011-bangalore/">Bangalore 2011</a><br>
<a href="/events/2011-goteborg/">Göteborg 2011</a><br>
<a href="/events/2011-manila/">Manila 2011</a><br>
</div>
<br>
<div style="margin:1px;">
<strong>2012</strong><br/>
<a href="/events/2012-austin/">Austin 2012</a><br>
<a href="/events/2012-tokyo/">Tokyo 2012</a><br>
<a href="/events/2012-india/">Delhi 2012</a><br>
<a href="/events/2012-mountainview/">Mountain View 2012</a><br>
<a href="/events/2012-italy/">Rome 2012</a><br>
<a href="/events/2012-newyork/">New York 2012</a><br>
</div>
</div>
<div style="display:table-cell; vertical-align:top">
<div style="margin:1px;">
<strong>2013</strong><br/>
<a href="/events/2013-newzealand/">New Zealand 2013</a><br>
<a href="/events/2013-london-spring/">London 2013</a><br>
<a href="/events/2013-paris/">Paris 2013</a><br>
<a href="/events/2013-austin/">Austin 2013</a><br>
<a href="/events/2013-berlin/">Berlin 2013</a><br>
<a href="/events/2013-amsterdam/">Amsterdam 2013</a><br>
<a href="/events/2013-mountainview/">Silicon Valley 2013</a><br>
<a href="/events/2013-downunder">Downunder 2013</a><br>
<a href="/events/2013-india/">Bangalore 2013</a><br/>
<a href="/events/2013-london/">London Autumn 2013</a><br/>
<a href="/events/2013-barcelona/">Barcelona 2013</a><br/>
<a href="/events/2013-vancouver/">Vancouver 2013</a><br/>
<a href="/events/2013-portland/">Portland 2013</a><br/>
<a href="/events/2013-newyork/">New York 2013</a><br/>
<a href="/events/2013-atlanta/">Atlanta 2013</a><br/>
<a href="/events/2013-telaviv/">Tel Aviv 2013</a><br/>
<a href="/events/2013-tokyo/">Tokyo 2013</a><br/>
</div>
</div>
<div style="display:table-cell; vertical-align:top">
<div style="margin:1px;">
<strong>2014</strong><br/>
<a href="/events/2014-nairobi/">Nairobi 2014</a><br/>
<a href="/events/2014-ljubljana/">Ljubljana 2014</a><br/>
<a href="/events/2014-austin/">Austin 2014</a><br/>
<a href="/events/2014-pittsburgh/">Pittsburgh 2014</a><br/>
<a href="/events/2014-amsterdam/">Amsterdam 2014</a><br/>
<a href="/events/2014-siliconvalley/">Silicon Valley 2014</a><br/>
<a href="/events/2014-minneapolis/">Minneapolis 2014</a><br/>
<a href="/events/2014-brisbane/">Brisbane 2014</a><br/>
<a href="/events/2014-boston/">Boston 2014</a><br/>
<a href="/events/2014-toronto/">Toronto 2014</a><br/>
<a href="/events/2014-newyork/">New York 2014</a><br/>
<a href="/events/2014-warsaw/">Warsaw 2014</a><br/>
<a href="/events/2014-chicago/">Chicago 2014</a><br/>
<a href="/events/2014-berlin/">Berlin 2014</a><br/>
<a href="/events/2014-belgium/">Belgium 2014</a><br/>
<a href="/events/2014-helsinki/">Helsinki 2014</a><br/>
<a href="/events/2014-vancouver/">Vancouver 2014</a><br/>
<a href="/events/2014-telaviv/">Tel Aviv 2014</a><br/>
<a href="/events/2014-bangalore/">Bangalore 2014</a><br/>
</div>
</div>
<div style="display:table-cell; vertical-align:top">
<div style="margin:1px;">
<strong>2015</strong><br/>
<a href="/events/2015-ljubljana/">Ljubljana 2015</a><br/>
<a href="/events/2015-paris">Paris 2015</a><br/>
<a href="/events/2015-denver/">Denver 2015</a><br/>
<a href="/events/2015-newyork/">New York 2015</a><br/>
<a href="/events/2015-austin">Austin 2015</a><br/>
<a href="/events/2015-toronto">Toronto 2015</a><br/>
<a href="/events/2015-washington-dc/">Washington, DC 2015</a><br/>
<a href="/events/2015-amsterdam">Amsterdam 2015</a><br/>
<a href="/events/2015-minneapolis/">Minneapolis 2015</a><br/>
<a href="/events/2015-melbourne/">Melbourne 2015</a><br/>
<a href="/events/2015-pittsburgh/">Pittsburgh 2015</a><br/>
<a href="/events/2015-chicago/">Chicago 2015</a><br/>
<a href="/events/2015-bangalore/">Bangalore 2015</a><br/>
<a href="/events/2015-boston/">Boston 2015</a><br/>
<a href="/events/2015-telaviv/">Tel Aviv 2015</a><br/>
<a href="/events/2015-singapore/">Singapore 2015</a><br/>
<a href="/events/2015-berlin/">Berlin 2015</a><br/>
<a href="/events/2015-charlotte">Charlotte 2015</a><br/>
<a href="/events/2015-siliconvalley">Silicon Valley 2015</a><br/>
<a href="/events/2015-detroit">Detroit 2015</a><br/>
<a href="/events/2015-ohio/">Ohio 2015</a><br/>
<a href="/events/2015-warsaw/">Warsaw 2015</a><br/>
</div>
</div>
<div style="display:table-cell; vertical-align:top">
<div style="margin:1px;">
<strong>2016</strong><br/>
<a href="/events/2016-losangeles-1day/">Los Angeles (1 day)</a>
<a href="/events/2016-vancouver/">Vancouver</a><br/>
<a href="/events/2016-london/">London</a><br/>
<a href="/events/2016-denver/">Denver</a><br/>
<a href="/events/2016-atlanta/">Atlanta</a><br/>
</div>
</div>
</tr>
</table>
</div>
</div>
</div>
<div class="span-6 last ">
<div style=" padding-top:18px;" class="span-5 last">
<h1>Future </h1>
</div>
<div class="span-6 last">
<div style="height:700px;" id="quicklinks">
<table>
<tr>
<td>
<strong>2016</strong><br/>
<a href="/events/2016-austin/">Austin - May 2 & 3</a><br/>
<a href="/events/2016-kiel/">Kiel - May 12 & 13</a><br/>
<a href="/events/2016-seattle/">Seattle - May 12 & 13</a><br/>
<a href="/events/2016-toronto/">Toronto - May 26 & 27</a><br/>
<a href="/events/2016-istanbul/">Istanbul - Jun 3 & 4</a><br/>
<a href="/events/2016-washington-dc/">Washington, DC - Jun 8 & 9</a><br/>
<a href="/events/2016-saltlakecity/">Salt Lake City - Jun 14 & 15</a><br/>
<a href="/events/2016-siliconvalley/">Silicon Valley - June 24 & 25</a><br/>
<a href="/events/2016-amsterdam/">Amsterdam - Jun 29, 30 & Jul 1</a><br/>
<a href="/events/2016-minneapolis/">Minneapolis - Jul 20 & 21</a><br/>
<a href="/events/2016-portland/">Portland - Aug 9 & 10</a><br/>
<a href="/events/2016-boston/">Boston - Aug 25 & 26</a><br/>
<a href="/events/2016-chicago/">Chicago - Aug 30 & 31</a><br/>
<a href="/events/2016-oslo/">Oslo - Sep 5 & 6</a><br/>
<a href="/events/2016-dallas/">Dallas - Sep 15 & 16</a><br/>
<a href="/events/2016-newyork/">New York - Sep 23 & 24</a><br/>
<a href="/events/2016-boise/">Boise - Oct 7 & 8</a><br/>
<a href="/events/2016-singapore/">Singapore - Oct 8 & 9</a><br/>
<a href="/events/2016-detroit/">Detroit - Oct 12 & 13</a><br/>
<a href="/events/2016-kansascity/">Kansas City - Oct 20 & 21</a><br/>
<a href="/events/2016-philadelphia/">Philadelphia - Oct 26 & 27</a><br/>
<br/>
<strong>2016, Dates TBD</strong><br/>
<a href="/events/2016-ghent/">Ghent</a><br/>
<a href="/events/2016-raleigh/">Raleigh</a><br/>
<a href="/events/2016-newzealand/">New Zealand</a><br/>
<a href="/events/2016-ohio/">Ohio</a><br/>
<a href="/events/2016-nashville/">Nashville</a><br/>
<a href="/events/2016-madison/">Madison</a><br/>
<a href="/events/2016-capetown/">Cape Town</a><br/>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-9713393-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
| apache-2.0 |
apache/syncope | client/idrepo/console/src/main/java/org/apache/syncope/client/console/wicket/markup/html/form/XMLEditorPanel.java | 2701 | /*
* 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.syncope.client.console.wicket.markup.html.form;
import org.apache.syncope.client.console.panels.AbstractModalPanel;
import org.apache.syncope.client.console.wicket.markup.html.bootstrap.dialog.BaseModal;
import org.apache.wicket.PageReference;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.OnLoadHeaderItem;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.model.IModel;
public class XMLEditorPanel extends AbstractModalPanel<String> {
private static final long serialVersionUID = -5110368813584745668L;
private final IModel<String> content;
private final boolean readOnly;
public XMLEditorPanel(final IModel<String> content) {
this(null, content, false, null);
}
public XMLEditorPanel(
final BaseModal<String> modal,
final IModel<String> content,
final boolean readOnly,
final PageReference pageRef) {
super(modal, pageRef);
this.content = content;
this.readOnly = readOnly;
final TextArea<String> xmlEditorInfoDefArea = new TextArea<>("xmlEditorInfo", this.content);
xmlEditorInfoDefArea.setMarkupId("xmlEditorInfo").setOutputMarkupPlaceholderTag(true);
add(xmlEditorInfoDefArea);
}
@Override
public void renderHead(final IHeaderResponse response) {
super.renderHead(response);
response.render(OnLoadHeaderItem.forScript(
"CodeMirror.fromTextArea(document.getElementById('xmlEditorInfo'), {"
+ " readOnly: " + readOnly + ", "
+ " lineNumbers: true, "
+ " lineWrapping: true, "
+ " autoCloseTags: true, "
+ " mode: 'text/html', "
+ " autoRefresh: true"
+ "}).on('change', updateTextArea);"));
}
}
| apache-2.0 |
papicella/snappy-store | gemfirexd/core/src/main/java/com/pivotal/gemfirexd/internal/engine/management/AggregateStatementMXBean.java | 4681 | /*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package com.pivotal.gemfirexd.internal.engine.management;
/**
* This MBean provide different Statistics aggregate for StatementStats. It only
* provide details about query node.
*
* This MBean will show only rate between two sampling interval. Sampling
* interval being DistributionConfig.JMX_MANAGER_UPDATE_RATE_NAME.
* {jmx-manager-update-rate}. Default interval is 2 secs.
*
* e.g. if Sample:1{NumExecution = 2} & Sample:2 {NumExecution = 5} this MBean
* will show a value of 3 if queried after Sample :2 & before Sample:3
*
*
* @author rishim
*
*/
public interface AggregateStatementMXBean {
/**
* Number of times this statement is compiled (including recompilations)
* between two sampling interval.
*
*/
public long getNumTimesCompiled();
/**
* Number of times this statement is executed between two sampling interval.
*/
public long getNumExecution();
/**
* Statements that are actively being processed during the statistics snapshot
* between two sampling interval.
*/
public long getNumExecutionsInProgress();
/**
* Number of times global index lookup message exchanges occurred between two
* sampling interval.
*
*/
public long getNumTimesGlobalIndexLookup();
/**
* Number of rows modified by DML operation of insert/delete/update between
* two sampling interval.
*
*/
public long getNumRowsModified();
/**
* Time spent(in milliseconds) in parsing the query string between two
* sampling interval.
*
*/
public long getParseTime();
/**
* Time spent (in milliseconds) mapping this statement with database object's
* metadata (bind) between two sampling interval.
*
*/
public long getBindTime();
/**
* Time spent (in milliseconds) determining the best execution path for this
* statement (optimize) between two sampling interval.
*
*/
public long getOptimizeTime();
/**
* Time spent (in milliseconds) compiling details about routing information of
* query strings to data node(s) (processQueryInfo) between two sampling interval.
*
*/
public long getRoutingInfoTime();
/**
* Time spent (in milliseconds) to generate query execution plan definition
* (activation class) between two sampling interval.
*
*/
public long getGenerateTime();
/**
* Total compilation time (in milliseconds) of the statement on this node
* (prepMinion) between two sampling interval.
*
*/
public long getTotalCompilationTime();
/**
* Time spent (in nanoseconds) in creation of all the layers of query
* processing (ac.execute) between two sampling interval.
*
*/
public long getExecutionTime();
/**
* Time to apply (in nanoseconds) the projection and additional filters
* between two sampling interval.
*
*/
public long getProjectionTime();
/**
* Total execution time (in nanoseconds) taken to process the statement on
* this node (execute/open/next/close) between two sampling interval.
*
*/
public long getTotalExecutionTime();
/**
* Time taken (in nanoseconds) to modify rows by DML operation of
* insert/delete/update between two sampling interval.
*
*/
public long getRowsModificationTime();
/**
* Number of rows returned from remote nodes (ResultHolder/Get convertibles)
* between two sampling interval.
*
*/
public long getQNNumRowsSeen();
/**
* TCP send time (in nanoseconds) of all the messages including serialization
* time and queue wait time between two sampling interval.
*
*/
public long getQNMsgSendTime();
/**
* Serialization time (in nanoseconds) for all the messages while sending to
* remote node(s) between two sampling interval.
*
*/
public long getQNMsgSerTime();
/**
* Response message deserialization time (in nano seconds ) from remote
* node(s) excluding resultset deserialization between two sampling interval.
*
*/
public long getQNRespDeSerTime();
}
| apache-2.0 |
slozier/ironpython2 | Src/StdLib/Lib/test/inspect_fodder.py | 967 | # line 1
'A module docstring.'
import sys, inspect
# line 5
# line 7
def spam(a, b, c, d=3, (e, (f,))=(4, (5,)), *g, **h):
eggs(b + d, c + f)
# line 11
def eggs(x, y):
"A docstring."
global fr, st
fr = inspect.currentframe()
st = inspect.stack()
p = x
q = y // 0
# line 20
class StupidGit:
"""A longer,
indented
docstring."""
# line 27
def abuse(self, a, b, c):
"""Another
\tdocstring
containing
\ttabs
\t
"""
self.argue(a, b, c)
# line 40
def argue(self, a, b, c):
try:
spam(a, b, c)
except:
self.ex = sys.exc_info()
self.tr = inspect.trace()
# line 48
class MalodorousPervert(StupidGit):
pass
Tit = MalodorousPervert
class ParrotDroppings:
pass
class FesteringGob(MalodorousPervert, ParrotDroppings):
pass
currentframe = inspect.currentframe()
try:
raise Exception()
except:
tb = sys.exc_info()[2]
| apache-2.0 |
byronmccollum/rpc-openstack | maas/plugins/ceph_monitoring.py | 6319 | #!/usr/bin/env python
# Copyright 2015, Rackspace US, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import json
import maas_common
import subprocess
STATUSES = {'HEALTH_OK': 2, 'HEALTH_WARN': 1, 'HEALTH_ERR': 0}
def check_command(command):
output = subprocess.check_output(command, stderr=subprocess.STDOUT)
lines = output.strip().split('\n')
return json.loads(lines[-1])
def get_ceph_status(client, keyring, fmt='json'):
return check_command(('ceph', '--format', fmt, '--name', client,
'--keyring', keyring, 'status'))
def get_ceph_pg_dump_osds(client, keyring, fmt='json'):
return check_command(('ceph', '--format', fmt, '--name', client,
'--keyring', keyring, 'pg', 'dump', 'osds'))
def get_ceph_osd_dump(client, keyring, fmt='json'):
return check_command(('ceph', '--format', fmt, '--name', client,
'--keyring', keyring, 'osd', 'dump'))
def get_mon_statistics(client=None, keyring=None, host=None):
ceph_status = get_ceph_status(client=client, keyring=keyring)
mon = [m for m in ceph_status['monmap']['mons']
if m['name'] == host]
mon_in = mon[0]['rank'] in ceph_status['quorum']
maas_common.metric_bool('mon_in_quorum', mon_in)
health_status = 0
for each in ceph_status['health']['health']['health_services'][0]['mons']:
if each['name'] == host:
health_status = STATUSES[each['health']]
break
maas_common.metric('mon_health', 'uint32', health_status)
def get_osd_statistics(client=None, keyring=None, osd_ids=None):
osd_dump = get_ceph_osd_dump(client=client, keyring=keyring)
pg_osds_dump = get_ceph_pg_dump_osds(client=client, keyring=keyring)
for osd_id in osd_ids:
osd_ref = 'osd.%s' % osd_id
for _osd in osd_dump['osds']:
if _osd['osd'] == osd_id:
osd = _osd
break
else:
msg = 'The OSD ID %s does not exist.' % osd_id
raise maas_common.MaaSException(msg)
for key in ('up', 'in'):
name = '_'.join((osd_ref, key))
maas_common.metric_bool(name, osd[key])
for _osd in pg_osds_dump:
if _osd['osd'] == osd_id:
osd = _osd
break
for key in ('kb', 'kb_used', 'kb_avail'):
name = '_'.join((osd_ref, key))
maas_common.metric(name, 'uint64', osd[key])
def get_cluster_statistics(client=None, keyring=None):
metrics = []
ceph_status = get_ceph_status(client=client, keyring=keyring)
# Get overall cluster health
metrics.append({
'name': 'cluster_health',
'type': 'uint32',
'value': STATUSES[ceph_status['health']['overall_status']]})
# Collect epochs for the mon and osd maps
metrics.append({'name': "monmap_epoch",
'type': 'uint32',
'value': ceph_status['monmap']['epoch']})
metrics.append({'name': "osdmap_epoch",
'type': 'uint32',
'value': ceph_status['osdmap']['osdmap']['epoch']})
# Collect OSDs per state
osds = {'total': ceph_status['osdmap']['osdmap']['num_osds'],
'up': ceph_status['osdmap']['osdmap']['num_up_osds'],
'in': ceph_status['osdmap']['osdmap']['num_in_osds']}
for k in osds:
metrics.append({'name': 'osds_%s' % k,
'type': 'uint32',
'value': osds[k]})
# Collect cluster size & utilisation
metrics.append({'name': 'osds_kb_used',
'type': 'uint64',
'value': ceph_status['pgmap']['bytes_used'] / 1024})
metrics.append({'name': 'osds_kb_avail',
'type': 'uint64',
'value': ceph_status['pgmap']['bytes_avail'] / 1024})
metrics.append({'name': 'osds_kb',
'type': 'uint64',
'value': ceph_status['pgmap']['bytes_total'] / 1024})
# Collect num PGs and num healthy PGs
pgs = {'total': ceph_status['pgmap']['num_pgs'], 'active_clean': 0}
for state in ceph_status['pgmap']['pgs_by_state']:
if state['state_name'] == 'active+clean':
pgs['active_clean'] = state['count']
break
for k in pgs:
metrics.append({'name': 'pgs_%s' % k,
'type': 'uint32',
'value': pgs[k]})
# Submit gathered metrics
for m in metrics:
maas_common.metric(m['name'], m['type'], m['value'])
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--name', required=True, help='Ceph client name')
parser.add_argument('--keyring', required=True, help='Ceph client keyring')
subparsers = parser.add_subparsers(dest='subparser_name')
parser_mon = subparsers.add_parser('mon')
parser_mon.add_argument('--host', required=True, help='Mon hostname')
parser_osd = subparsers.add_parser('osd')
parser_osd.add_argument('--osd_ids', required=True,
help='Space separated list of OSD IDs')
subparsers.add_parser('cluster')
return parser.parse_args()
def main(args):
get_statistics = {'cluster': get_cluster_statistics,
'mon': get_mon_statistics,
'osd': get_osd_statistics}
kwargs = {'client': args.name, 'keyring': args.keyring}
if args.subparser_name == 'osd':
kwargs['osd_ids'] = [int(i) for i in args.osd_ids.split(' ')]
if args.subparser_name == 'mon':
kwargs['host'] = args.host
get_statistics[args.subparser_name](**kwargs)
maas_common.status_ok()
if __name__ == '__main__':
with maas_common.print_output():
args = get_args()
main(args)
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.