code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
---
title: ICompletionProposal.attributes - aesi-java
---
[aesi-java](../../index.html) / [com.virtlink.editorservices.codecompletion](../index.html) / [ICompletionProposal](index.html) / [attributes](.)
# attributes
`abstract val attributes: `[`EnumSet`](http://docs.oracle.com/javase/6/docs/api/java/util/EnumSet.html)`<`[`Attribute`](../-attribute/index.html)`>` | Java |
package org.zentaur.core.http;
/*
* Copyright 2012 The Zentaur Server 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.
*/
import org.zentaur.http.Response;
/**
* Factory delegated to {@link Response} instances creation.
*/
public final class ResponseFactory
{
/**
* Creates a new {@link Response} instance.
*
* @return a new {@link Response} instance.
*/
public static Response newResponse()
{
return new DefaultResponse();
}
/**
* Hidden constructor, this class cannot be instantiated.
*/
private ResponseFactory()
{
// do nothing
}
}
| Java |
<?xml version="1.0" encoding="utf-8"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"><ShortName>National Water Supply and Drainage Board</ShortName><Description>National Water Supply and Drainage Board</Description><InputEncoding>UTF-8</InputEncoding><Image type="image/vnd.microsoft.icon" width="16" height="16">http://waterboard.lk/web/templates/poora_temp/favicon.ico</Image><Url type="application/opensearchdescription+xml" rel="self" template="http://waterboard.lk/web/index.php?option=com_search&view=article&id=218&Itemid=325&lang=si&format=opensearch"/><Url type="text/html" template="http://waterboard.lk/web/index.php?option=com_search&searchword={searchTerms}&Itemid=188"/></OpenSearchDescription>
| Java |
// Copyright 2016 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package tikv
import (
"github.com/juju/errors"
"github.com/pingcap/tidb/mysql"
"github.com/pingcap/tidb/terror"
)
var (
// ErrBodyMissing response body is missing error
ErrBodyMissing = errors.New("response body is missing")
)
// TiDB decides whether to retry transaction by checking if error message contains
// string "try again later" literally.
// In TiClient we use `errors.Annotate(err, txnRetryableMark)` to direct TiDB to
// restart a transaction.
// Note that it should be only used if i) the error occurs inside a transaction
// and ii) the error is not totally unexpected and hopefully will recover soon.
const txnRetryableMark = "[try again later]"
// MySQL error instances.
var (
ErrTiKVServerTimeout = terror.ClassTiKV.New(mysql.ErrTiKVServerTimeout, mysql.MySQLErrName[mysql.ErrTiKVServerTimeout]+txnRetryableMark)
ErrResolveLockTimeout = terror.ClassTiKV.New(mysql.ErrResolveLockTimeout, mysql.MySQLErrName[mysql.ErrResolveLockTimeout]+txnRetryableMark)
ErrPDServerTimeout = terror.ClassTiKV.New(mysql.ErrPDServerTimeout, mysql.MySQLErrName[mysql.ErrPDServerTimeout]+"%v")
ErrRegionUnavailable = terror.ClassTiKV.New(mysql.ErrRegionUnavailable, mysql.MySQLErrName[mysql.ErrRegionUnavailable]+txnRetryableMark)
ErrTiKVServerBusy = terror.ClassTiKV.New(mysql.ErrTiKVServerBusy, mysql.MySQLErrName[mysql.ErrTiKVServerBusy]+txnRetryableMark)
ErrGCTooEarly = terror.ClassTiKV.New(mysql.ErrGCTooEarly, mysql.MySQLErrName[mysql.ErrGCTooEarly])
)
func init() {
tikvMySQLErrCodes := map[terror.ErrCode]uint16{
mysql.ErrTiKVServerTimeout: mysql.ErrTiKVServerTimeout,
mysql.ErrResolveLockTimeout: mysql.ErrResolveLockTimeout,
mysql.ErrPDServerTimeout: mysql.ErrPDServerTimeout,
mysql.ErrRegionUnavailable: mysql.ErrRegionUnavailable,
mysql.ErrTiKVServerBusy: mysql.ErrTiKVServerBusy,
mysql.ErrGCTooEarly: mysql.ErrGCTooEarly,
}
terror.ErrClassToMySQLCodes[terror.ClassTiKV] = tikvMySQLErrCodes
}
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mermaid.Loft.Infrastructure.DomainBase
{
public class EntityBase
{
}
}
| Java |
package pl.wavesoftware.examples.wildflyswarm.service.api;
import pl.wavesoftware.examples.wildflyswarm.domain.User;
import java.util.Collection;
/**
* @author Krzysztof Suszynski <krzysztof.suszynski@coi.gov.pl>
* @since 04.03.16
*/
public interface UserService {
/**
* Retrieves a collection of active users
* @return a collection with only active users
*/
Collection<User> fetchActiveUsers();
}
| Java |
#!/bin/bash
# Copyright 2016 - 2020 Crunchy Data Solutions, 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.
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
CONTAINER_NAME='custom-config-ssl'
PGDATA_VOL="${CONTAINER_NAME?}-pgdata"
BACKUP_VOL="${CONTAINER_NAME?}-backup"
${DIR?}/cleanup.sh
${DIR?}/../../ssl-creator.sh "testuser@crunchydata.com" "${CONTAINER_NAME?}" "$(pwd)"
if [[ $? -ne 0 ]]
then
echo "Failed to create certs, exiting.."
exit 1
fi
cp ${DIR?}/certs/server.* ${DIR?}/configs
cp ${DIR?}/certs/ca.* ${DIR?}/configs
echo "Starting the ${CONTAINER_NAME} example..."
docker volume create --driver local --name=${PGDATA_VOL?}
docker volume create --driver local --name=${BACKUP_VOL?}
docker run \
--name=${CONTAINER_NAME?} \
--hostname=${CONTAINER_NAME?} \
--publish=5432:5432 \
--volume=${DIR?}/configs:/pgconf \
--volume=${PGDATA_VOL?}:/pgdata \
--volume=${BACKUP_VOL?}:/backrestrepo \
--env=PG_MODE=primary \
--env=PG_PRIMARY_USER=primaryuser \
--env=PG_PRIMARY_PASSWORD=password \
--env=PG_PRIMARY_HOST=localhost \
--env=PG_PRIMARY_PORT=5432 \
--env=PG_DATABASE=userdb \
--env=PG_USER=testuser \
--env=PG_PASSWORD=password \
--env=PG_ROOT_PASSWORD=password \
--env=PGHOST=/tmp \
--env=XLOGDIR=true \
--env=PGBACKREST=true \
--detach ${CCP_IMAGE_PREFIX?}/crunchy-postgres:${CCP_IMAGE_TAG?}
echo ""
echo "To connect via SSL, run the following once the DB is ready: "
echo "psql \"postgresql://testuser@${CONTAINER_NAME?}:5432/userdb?\
sslmode=verify-full&\
sslrootcert=$CCPROOT/examples/docker/custom-config-ssl/certs/ca.crt&\
sslcrl=$CCPROOT/examples/docker/custom-config-ssl/certs/ca.crl&\
sslcert=$CCPROOT/examples/docker/custom-config-ssl/certs/client.crt&\
sslkey=$CCPROOT/examples/docker/custom-config-ssl/certs/client.key\""
echo "" | Java |
<?php
/**
* Copyright (c) <2016> Protobile contributors and Addvilz <mrtreinis@gmail.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.
*/
namespace Protobile\Framework\CompilerPass;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class RegisterOutputPass implements CompilerPassInterface
{
/**
* @param ContainerBuilder $container
*/
public function process(ContainerBuilder $container)
{
$container->register('app.output', ConsoleOutput::class);
}
}
| Java |
/*
* #%L
* =====================================================
* _____ _ ____ _ _ _ _
* |_ _|_ __ _ _ ___| |_ / __ \| | | | ___ | | | |
* | | | '__| | | / __| __|/ / _` | |_| |/ __|| |_| |
* | | | | | |_| \__ \ |_| | (_| | _ |\__ \| _ |
* |_| |_| \__,_|___/\__|\ \__,_|_| |_||___/|_| |_|
* \____/
*
* =====================================================
*
* Hochschule Hannover
* (University of Applied Sciences and Arts, Hannover)
* Faculty IV, Dept. of Computer Science
* Ricklinger Stadtweg 118, 30459 Hannover, Germany
*
* Email: trust@f4-i.fh-hannover.de
* Website: http://trust.f4.hs-hannover.de/
*
* This file is part of ifmapj, version 2.3.2, implemented by the Trust@HsH
* research group at the Hochschule Hannover.
* %%
* Copyright (C) 2010 - 2016 Trust@HsH
* %%
* 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%
*/
package de.hshannover.f4.trust.ifmapj.messages;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import de.hshannover.f4.trust.ifmapj.exception.IfmapErrorResult;
import de.hshannover.f4.trust.ifmapj.messages.SearchResult.Type;
/**
* Implementation of {@link PollResult}
*
* @author aw
*
*/
class PollResultImpl implements PollResult {
private final List<SearchResult> mResults;
private final Collection<IfmapErrorResult> mErrorResults;
PollResultImpl(List<SearchResult> results, Collection<IfmapErrorResult> eres) {
if (results == null || eres == null) {
throw new NullPointerException("result list is null");
}
mResults = new ArrayList<SearchResult>(results);
mErrorResults = new ArrayList<IfmapErrorResult>(eres);
}
@Override
public List<SearchResult> getResults() {
return Collections.unmodifiableList(mResults);
}
@Override
public Collection<SearchResult> getSearchResults() {
return resultsOfType(SearchResult.Type.searchResult);
}
@Override
public Collection<SearchResult> getUpdateResults() {
return resultsOfType(SearchResult.Type.updateResult);
}
@Override
public Collection<SearchResult> getDeleteResults() {
return resultsOfType(SearchResult.Type.deleteResult);
}
@Override
public Collection<SearchResult> getNotifyResults() {
return resultsOfType(SearchResult.Type.notifyResult);
}
@Override
public Collection<IfmapErrorResult> getErrorResults() {
return Collections.unmodifiableCollection(mErrorResults);
}
private Collection<SearchResult> resultsOfType(Type type) {
List<SearchResult> ret = new ArrayList<SearchResult>();
for (SearchResult sr : mResults) {
if (sr.getType() == type) {
ret.add(sr);
}
}
return Collections.unmodifiableCollection(ret);
}
}
| Java |
---
layout: default
---
What’s wrong with SOAP
======================
Many things.
Brittle
-------
Pretty much every change you might make to an interface is a breaking change for a SOAP client. Want to add a new parameter to a returned object - breaking change. Want to add a new optional parameter to a call - breaking change. Want to change the type of a request parameter from int32 to int64 - breaking change. You get the message. Some of these could be resolved by diverging from the spec on the server side, but we can’t do anything about the myriad of SOAP clients available.
Essentially, almost every minor release of an interface would have to be a major release if SOAP is to be supported. We don’t want to hobble Cougar like this, so we choose to quietly ignore this fact and suggest you don’t use SOAP unless you can control the clients or afford to run many parallel versions of your interface (Cougar can run parallel major versions but can’t run parallel minor versions - a conscious choice and fine since minor versions should be backwards compatible).
If you have to use XML, at least use XML with Rescript.
Big
---
Serialised requests / responses are much larger in SOAP than in other formats such as JSON. This is due both to the SOAP envelope which is a large overhead for small object trees and also due to the expressiveness of XML, compare:
<SomeObject>
<SomeParameter>SomeValue</SomeParameter>
</SomeObject>
{“SomeParameter”:”SomeValue”}
Granted, using tiny names would ameliorate this, but that’s gonna be a pain to debug.
Slow
----
Related to the previous - SOAP is far slower to serialise/deserialise than the alternatives, it’s CPU intensive. Cougar is intended to be high performance, SOAP serialisation costs could far outweigh the processing costs for the operation.
| Java |
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="fragments/layout">
<body>
<form method="post" enctype="multipart/form-data" class="form-horizontal">
<fieldset>
<legend th:text="#{nav.role}">File</legend>
<div class="form-group" th:classappend="${#fields.hasErrors('name')}? 'has-error has-feedback'">
<label for="name" class="col-sm-2 control-label" th:text="#{name}">Name</label>
<div class="col-xs-3">
<input type="text" id="name" name="name" th:field="*{name}" class="form-control" value="ee"/>
<span th:if="${#fields.hasErrors('name')}" th:errors="*{name}" class="help-block">error!</span>
</div>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('file')}? 'has-error has-feedback'">
<label for="file" class="col-sm-2 control-label" th:text="#{file}">File</label>
<div class="col-xs-3">
<input type="file" id="file" name="file" th:field="*{file}" class="form-control" value="ee"/>
<span th:if="${#fields.hasErrors('file')}" th:errors="*{file}" class="help-block">error!</span>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">save</button>
</div>
</div>
</fieldset>
</form>
</div>
</body>
</html> | Java |
/*
* Copyright 2020 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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/resourcemanager/v3/folders.proto
package com.google.cloud.resourcemanager.v3;
/**
*
*
* <pre>
* The request sent to the
* [UpdateFolder][google.cloud.resourcemanager.v3.Folder.UpdateFolder]
* method.
* Only the `display_name` field can be changed. All other fields will be
* ignored. Use the
* [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder] method to
* change the `parent` field.
* </pre>
*
* Protobuf type {@code google.cloud.resourcemanager.v3.UpdateFolderRequest}
*/
public final class UpdateFolderRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.resourcemanager.v3.UpdateFolderRequest)
UpdateFolderRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateFolderRequest.newBuilder() to construct.
private UpdateFolderRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateFolderRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateFolderRequest();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private UpdateFolderRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.resourcemanager.v3.Folder.Builder subBuilder = null;
if (folder_ != null) {
subBuilder = folder_.toBuilder();
}
folder_ =
input.readMessage(
com.google.cloud.resourcemanager.v3.Folder.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(folder_);
folder_ = subBuilder.buildPartial();
}
break;
}
case 18:
{
com.google.protobuf.FieldMask.Builder subBuilder = null;
if (updateMask_ != null) {
subBuilder = updateMask_.toBuilder();
}
updateMask_ =
input.readMessage(com.google.protobuf.FieldMask.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(updateMask_);
updateMask_ = subBuilder.buildPartial();
}
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.resourcemanager.v3.FoldersProto
.internal_static_google_cloud_resourcemanager_v3_UpdateFolderRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.resourcemanager.v3.FoldersProto
.internal_static_google_cloud_resourcemanager_v3_UpdateFolderRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.resourcemanager.v3.UpdateFolderRequest.class,
com.google.cloud.resourcemanager.v3.UpdateFolderRequest.Builder.class);
}
public static final int FOLDER_FIELD_NUMBER = 1;
private com.google.cloud.resourcemanager.v3.Folder folder_;
/**
*
*
* <pre>
* Required. The new definition of the Folder. It must include the `name` field, which
* cannot be changed.
* </pre>
*
* <code>
* .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the folder field is set.
*/
@java.lang.Override
public boolean hasFolder() {
return folder_ != null;
}
/**
*
*
* <pre>
* Required. The new definition of the Folder. It must include the `name` field, which
* cannot be changed.
* </pre>
*
* <code>
* .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The folder.
*/
@java.lang.Override
public com.google.cloud.resourcemanager.v3.Folder getFolder() {
return folder_ == null
? com.google.cloud.resourcemanager.v3.Folder.getDefaultInstance()
: folder_;
}
/**
*
*
* <pre>
* Required. The new definition of the Folder. It must include the `name` field, which
* cannot be changed.
* </pre>
*
* <code>
* .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.resourcemanager.v3.FolderOrBuilder getFolderOrBuilder() {
return getFolder();
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Required. Fields to be updated.
* Only the `display_name` can be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return updateMask_ != null;
}
/**
*
*
* <pre>
* Required. Fields to be updated.
* Only the `display_name` can be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* Required. Fields to be updated.
* Only the `display_name` can be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return getUpdateMask();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (folder_ != null) {
output.writeMessage(1, getFolder());
}
if (updateMask_ != null) {
output.writeMessage(2, getUpdateMask());
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (folder_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getFolder());
}
if (updateMask_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.resourcemanager.v3.UpdateFolderRequest)) {
return super.equals(obj);
}
com.google.cloud.resourcemanager.v3.UpdateFolderRequest other =
(com.google.cloud.resourcemanager.v3.UpdateFolderRequest) obj;
if (hasFolder() != other.hasFolder()) return false;
if (hasFolder()) {
if (!getFolder().equals(other.getFolder())) return false;
}
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask().equals(other.getUpdateMask())) return false;
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasFolder()) {
hash = (37 * hash) + FOLDER_FIELD_NUMBER;
hash = (53 * hash) + getFolder().hashCode();
}
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.resourcemanager.v3.UpdateFolderRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The request sent to the
* [UpdateFolder][google.cloud.resourcemanager.v3.Folder.UpdateFolder]
* method.
* Only the `display_name` field can be changed. All other fields will be
* ignored. Use the
* [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder] method to
* change the `parent` field.
* </pre>
*
* Protobuf type {@code google.cloud.resourcemanager.v3.UpdateFolderRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.resourcemanager.v3.UpdateFolderRequest)
com.google.cloud.resourcemanager.v3.UpdateFolderRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.resourcemanager.v3.FoldersProto
.internal_static_google_cloud_resourcemanager_v3_UpdateFolderRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.resourcemanager.v3.FoldersProto
.internal_static_google_cloud_resourcemanager_v3_UpdateFolderRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.resourcemanager.v3.UpdateFolderRequest.class,
com.google.cloud.resourcemanager.v3.UpdateFolderRequest.Builder.class);
}
// Construct using com.google.cloud.resourcemanager.v3.UpdateFolderRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (folderBuilder_ == null) {
folder_ = null;
} else {
folder_ = null;
folderBuilder_ = null;
}
if (updateMaskBuilder_ == null) {
updateMask_ = null;
} else {
updateMask_ = null;
updateMaskBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.resourcemanager.v3.FoldersProto
.internal_static_google_cloud_resourcemanager_v3_UpdateFolderRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.resourcemanager.v3.UpdateFolderRequest getDefaultInstanceForType() {
return com.google.cloud.resourcemanager.v3.UpdateFolderRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.resourcemanager.v3.UpdateFolderRequest build() {
com.google.cloud.resourcemanager.v3.UpdateFolderRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.resourcemanager.v3.UpdateFolderRequest buildPartial() {
com.google.cloud.resourcemanager.v3.UpdateFolderRequest result =
new com.google.cloud.resourcemanager.v3.UpdateFolderRequest(this);
if (folderBuilder_ == null) {
result.folder_ = folder_;
} else {
result.folder_ = folderBuilder_.build();
}
if (updateMaskBuilder_ == null) {
result.updateMask_ = updateMask_;
} else {
result.updateMask_ = updateMaskBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.resourcemanager.v3.UpdateFolderRequest) {
return mergeFrom((com.google.cloud.resourcemanager.v3.UpdateFolderRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.resourcemanager.v3.UpdateFolderRequest other) {
if (other == com.google.cloud.resourcemanager.v3.UpdateFolderRequest.getDefaultInstance())
return this;
if (other.hasFolder()) {
mergeFolder(other.getFolder());
}
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.resourcemanager.v3.UpdateFolderRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.resourcemanager.v3.UpdateFolderRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private com.google.cloud.resourcemanager.v3.Folder folder_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.resourcemanager.v3.Folder,
com.google.cloud.resourcemanager.v3.Folder.Builder,
com.google.cloud.resourcemanager.v3.FolderOrBuilder>
folderBuilder_;
/**
*
*
* <pre>
* Required. The new definition of the Folder. It must include the `name` field, which
* cannot be changed.
* </pre>
*
* <code>
* .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the folder field is set.
*/
public boolean hasFolder() {
return folderBuilder_ != null || folder_ != null;
}
/**
*
*
* <pre>
* Required. The new definition of the Folder. It must include the `name` field, which
* cannot be changed.
* </pre>
*
* <code>
* .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The folder.
*/
public com.google.cloud.resourcemanager.v3.Folder getFolder() {
if (folderBuilder_ == null) {
return folder_ == null
? com.google.cloud.resourcemanager.v3.Folder.getDefaultInstance()
: folder_;
} else {
return folderBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The new definition of the Folder. It must include the `name` field, which
* cannot be changed.
* </pre>
*
* <code>
* .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setFolder(com.google.cloud.resourcemanager.v3.Folder value) {
if (folderBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
folder_ = value;
onChanged();
} else {
folderBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Required. The new definition of the Folder. It must include the `name` field, which
* cannot be changed.
* </pre>
*
* <code>
* .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setFolder(com.google.cloud.resourcemanager.v3.Folder.Builder builderForValue) {
if (folderBuilder_ == null) {
folder_ = builderForValue.build();
onChanged();
} else {
folderBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Required. The new definition of the Folder. It must include the `name` field, which
* cannot be changed.
* </pre>
*
* <code>
* .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeFolder(com.google.cloud.resourcemanager.v3.Folder value) {
if (folderBuilder_ == null) {
if (folder_ != null) {
folder_ =
com.google.cloud.resourcemanager.v3.Folder.newBuilder(folder_)
.mergeFrom(value)
.buildPartial();
} else {
folder_ = value;
}
onChanged();
} else {
folderBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* Required. The new definition of the Folder. It must include the `name` field, which
* cannot be changed.
* </pre>
*
* <code>
* .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearFolder() {
if (folderBuilder_ == null) {
folder_ = null;
onChanged();
} else {
folder_ = null;
folderBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* Required. The new definition of the Folder. It must include the `name` field, which
* cannot be changed.
* </pre>
*
* <code>
* .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.resourcemanager.v3.Folder.Builder getFolderBuilder() {
onChanged();
return getFolderFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The new definition of the Folder. It must include the `name` field, which
* cannot be changed.
* </pre>
*
* <code>
* .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.resourcemanager.v3.FolderOrBuilder getFolderOrBuilder() {
if (folderBuilder_ != null) {
return folderBuilder_.getMessageOrBuilder();
} else {
return folder_ == null
? com.google.cloud.resourcemanager.v3.Folder.getDefaultInstance()
: folder_;
}
}
/**
*
*
* <pre>
* Required. The new definition of the Folder. It must include the `name` field, which
* cannot be changed.
* </pre>
*
* <code>
* .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.resourcemanager.v3.Folder,
com.google.cloud.resourcemanager.v3.Folder.Builder,
com.google.cloud.resourcemanager.v3.FolderOrBuilder>
getFolderFieldBuilder() {
if (folderBuilder_ == null) {
folderBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.resourcemanager.v3.Folder,
com.google.cloud.resourcemanager.v3.Folder.Builder,
com.google.cloud.resourcemanager.v3.FolderOrBuilder>(
getFolder(), getParentForChildren(), isClean());
folder_ = null;
}
return folderBuilder_;
}
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
updateMaskBuilder_;
/**
*
*
* <pre>
* Required. Fields to be updated.
* Only the `display_name` can be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return updateMaskBuilder_ != null || updateMask_ != null;
}
/**
*
*
* <pre>
* Required. Fields to be updated.
* Only the `display_name` can be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Fields to be updated.
* Only the `display_name` can be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
onChanged();
} else {
updateMaskBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Required. Fields to be updated.
* Only the `display_name` can be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
onChanged();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Required. Fields to be updated.
* Only the `display_name` can be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (updateMask_ != null) {
updateMask_ =
com.google.protobuf.FieldMask.newBuilder(updateMask_).mergeFrom(value).buildPartial();
} else {
updateMask_ = value;
}
onChanged();
} else {
updateMaskBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* Required. Fields to be updated.
* Only the `display_name` can be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearUpdateMask() {
if (updateMaskBuilder_ == null) {
updateMask_ = null;
onChanged();
} else {
updateMask_ = null;
updateMaskBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* Required. Fields to be updated.
* Only the `display_name` can be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Fields to be updated.
* Only the `display_name` can be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* Required. Fields to be updated.
* Only the `display_name` can be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(), getParentForChildren(), isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.resourcemanager.v3.UpdateFolderRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.resourcemanager.v3.UpdateFolderRequest)
private static final com.google.cloud.resourcemanager.v3.UpdateFolderRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.resourcemanager.v3.UpdateFolderRequest();
}
public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateFolderRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateFolderRequest>() {
@java.lang.Override
public UpdateFolderRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new UpdateFolderRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<UpdateFolderRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateFolderRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.resourcemanager.v3.UpdateFolderRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| Java |
//
// XABCheckJobViewController.h
// XAnBao
//
// Created by Minlay on 17/3/29.
// Copyright © 2017年 Minlay. All rights reserved.
//
#import "YBBaseViewController.h"
@interface XABCheckJobViewController : YBBaseViewController
@property(nonatomic, copy)NSString *classId;
@property(nonatomic, assign)NSInteger type;
@property(nonatomic, copy)NSString *className;
@end
| Java |
package com.lyubenblagoev.postfixrest.service;
import com.lyubenblagoev.postfixrest.entity.User;
import com.lyubenblagoev.postfixrest.security.JwtTokenProvider;
import com.lyubenblagoev.postfixrest.security.RefreshTokenProvider;
import com.lyubenblagoev.postfixrest.security.UserPrincipal;
import com.lyubenblagoev.postfixrest.service.model.AuthResponse;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityNotFoundException;
import java.util.Optional;
@Service
@Transactional(readOnly = true)
public class AuthServiceImpl implements AuthService {
private final JwtTokenProvider jwtTokenProvider;
private final RefreshTokenProvider refreshTokenProvider;
private final UserService userService;
public AuthServiceImpl(JwtTokenProvider jwtTokenProvider,
RefreshTokenProvider refreshTokenProvider,
UserService userService) {
this.jwtTokenProvider = jwtTokenProvider;
this.refreshTokenProvider = refreshTokenProvider;
this.userService = userService;
}
@Override
public AuthResponse createTokens(String email) {
Optional<User> userOptional = userService.findByEmail(email);
if (userOptional.isEmpty()) {
throw new EntityNotFoundException("Failed to find user with email " + email);
}
UserPrincipal userPrincipal = new UserPrincipal(userOptional.get());
String token = jwtTokenProvider.createToken(userPrincipal.getUsername(), userPrincipal.getAuthorities());
RefreshTokenProvider.RefreshToken refreshToken = refreshTokenProvider.createToken();
return new AuthResponse(token, refreshToken.getToken(), refreshToken.getExpirationDate());
}
}
| Java |
/**
* @license
* Copyright 2012 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Checkbox field. Checked or not checked.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.FieldCheckbox');
/** @suppress {extraRequire} */
goog.require('Blockly.Events.BlockChange');
goog.require('Blockly.Field');
goog.require('Blockly.fieldRegistry');
goog.require('Blockly.utils.dom');
goog.require('Blockly.utils.object');
/**
* Class for a checkbox field.
* @param {string|boolean=} opt_value The initial value of the field. Should
* either be 'TRUE', 'FALSE' or a boolean. Defaults to 'FALSE'.
* @param {Function=} opt_validator A function that is called to validate
* changes to the field's value. Takes in a value ('TRUE' or 'FALSE') &
* returns a validated value ('TRUE' or 'FALSE'), or null to abort the
* change.
* @param {Object=} opt_config A map of options used to configure the field.
* See the [field creation documentation]{@link https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/checkbox#creation}
* for a list of properties this parameter supports.
* @extends {Blockly.Field}
* @constructor
*/
Blockly.FieldCheckbox = function(opt_value, opt_validator, opt_config) {
/**
* Character for the check mark. Used to apply a different check mark
* character to individual fields.
* @type {?string}
* @private
*/
this.checkChar_ = null;
Blockly.FieldCheckbox.superClass_.constructor.call(
this, opt_value, opt_validator, opt_config);
};
Blockly.utils.object.inherits(Blockly.FieldCheckbox, Blockly.Field);
/**
* The default value for this field.
* @type {*}
* @protected
*/
Blockly.FieldCheckbox.prototype.DEFAULT_VALUE = false;
/**
* Construct a FieldCheckbox from a JSON arg object.
* @param {!Object} options A JSON object with options (checked).
* @return {!Blockly.FieldCheckbox} The new field instance.
* @package
* @nocollapse
*/
Blockly.FieldCheckbox.fromJson = function(options) {
return new Blockly.FieldCheckbox(options['checked'], undefined, options);
};
/**
* Default character for the checkmark.
* @type {string}
* @const
*/
Blockly.FieldCheckbox.CHECK_CHAR = '\u2713';
/**
* Serializable fields are saved by the XML renderer, non-serializable fields
* are not. Editable fields should also be serializable.
* @type {boolean}
*/
Blockly.FieldCheckbox.prototype.SERIALIZABLE = true;
/**
* Mouse cursor style when over the hotspot that initiates editability.
*/
Blockly.FieldCheckbox.prototype.CURSOR = 'default';
/**
* Configure the field based on the given map of options.
* @param {!Object} config A map of options to configure the field based on.
* @protected
* @override
*/
Blockly.FieldCheckbox.prototype.configure_ = function(config) {
Blockly.FieldCheckbox.superClass_.configure_.call(this, config);
if (config['checkCharacter']) {
this.checkChar_ = config['checkCharacter'];
}
};
/**
* Create the block UI for this checkbox.
* @package
*/
Blockly.FieldCheckbox.prototype.initView = function() {
Blockly.FieldCheckbox.superClass_.initView.call(this);
Blockly.utils.dom.addClass(
/** @type {!SVGTextElement} **/ (this.textElement_), 'blocklyCheckbox');
this.textElement_.style.display = this.value_ ? 'block' : 'none';
};
/**
* @override
*/
Blockly.FieldCheckbox.prototype.render_ = function() {
if (this.textContent_) {
this.textContent_.nodeValue = this.getDisplayText_();
}
this.updateSize_(this.getConstants().FIELD_CHECKBOX_X_OFFSET);
};
/**
* @override
*/
Blockly.FieldCheckbox.prototype.getDisplayText_ = function() {
return this.checkChar_ || Blockly.FieldCheckbox.CHECK_CHAR;
};
/**
* Set the character used for the check mark.
* @param {?string} character The character to use for the check mark, or
* null to use the default.
*/
Blockly.FieldCheckbox.prototype.setCheckCharacter = function(character) {
this.checkChar_ = character;
this.forceRerender();
};
/**
* Toggle the state of the checkbox on click.
* @protected
*/
Blockly.FieldCheckbox.prototype.showEditor_ = function() {
this.setValue(!this.value_);
};
/**
* Ensure that the input value is valid ('TRUE' or 'FALSE').
* @param {*=} opt_newValue The input value.
* @return {?string} A valid value ('TRUE' or 'FALSE), or null if invalid.
* @protected
*/
Blockly.FieldCheckbox.prototype.doClassValidation_ = function(opt_newValue) {
if (opt_newValue === true || opt_newValue === 'TRUE') {
return 'TRUE';
}
if (opt_newValue === false || opt_newValue === 'FALSE') {
return 'FALSE';
}
return null;
};
/**
* Update the value of the field, and update the checkElement.
* @param {*} newValue The value to be saved. The default validator guarantees
* that this is a either 'TRUE' or 'FALSE'.
* @protected
*/
Blockly.FieldCheckbox.prototype.doValueUpdate_ = function(newValue) {
this.value_ = this.convertValueToBool_(newValue);
// Update visual.
if (this.textElement_) {
this.textElement_.style.display = this.value_ ? 'block' : 'none';
}
};
/**
* Get the value of this field, either 'TRUE' or 'FALSE'.
* @return {string} The value of this field.
*/
Blockly.FieldCheckbox.prototype.getValue = function() {
return this.value_ ? 'TRUE' : 'FALSE';
};
/**
* Get the boolean value of this field.
* @return {boolean} The boolean value of this field.
*/
Blockly.FieldCheckbox.prototype.getValueBoolean = function() {
return /** @type {boolean} */ (this.value_);
};
/**
* Get the text of this field. Used when the block is collapsed.
* @return {string} Text representing the value of this field
* ('true' or 'false').
*/
Blockly.FieldCheckbox.prototype.getText = function() {
return String(this.convertValueToBool_(this.value_));
};
/**
* Convert a value into a pure boolean.
*
* Converts 'TRUE' to true and 'FALSE' to false correctly, everything else
* is cast to a boolean.
* @param {*} value The value to convert.
* @return {boolean} The converted value.
* @private
*/
Blockly.FieldCheckbox.prototype.convertValueToBool_ = function(value) {
if (typeof value == 'string') {
return value == 'TRUE';
} else {
return !!value;
}
};
Blockly.fieldRegistry.register('field_checkbox', Blockly.FieldCheckbox);
| Java |
package task03.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class TicketSelectionPage extends Page {
public TicketSelectionPage(PageManager pages) {
super(pages);
}
@FindBy(xpath = ".//*[@id='fareRowContainer_0']/tbody/tr[2]/td[2]")
private WebElement firstTicket;
@FindBy(xpath = ".//*[@id='fareRowContainer_0']/tbody/tr[2]/td[2]")
private WebElement secondTicket;
@FindBy(id = "tripSummarySubmitBtn")
private WebElement submitButton;
public void select2Tickets() {
wait.until(ExpectedConditions.elementToBeClickable(firstTicket));
firstTicket.click();
wait.until(ExpectedConditions.elementToBeClickable(secondTicket));
secondTicket.click();
wait.until(ExpectedConditions.elementToBeClickable(submitButton));
submitButton.submit();
}
}
| Java |
using System.Collections;
using System.Collections.Generic;
namespace Basic.Ast
{
public class ParameterList : IEnumerable<Parameter>
{
private readonly List<Parameter> parameters;
public ParameterList()
{
parameters = new List<Parameter>();
}
public MethodDef Method { get; private set; }
#region IEnumerable<Parameter> Members
public IEnumerator<Parameter> GetEnumerator()
{
return parameters.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return parameters.GetEnumerator();
}
#endregion
public void SetMethod(MethodDef method)
{
Method = method;
}
public void Add(Parameter param)
{
parameters.Add(param);
}
public void Define()
{
foreach (Parameter p in parameters)
{
p.Define();
}
}
public void Resolve()
{
foreach (Parameter p in parameters)
{
p.Resolve();
}
}
public void CreateParameterBuilders()
{
foreach (Parameter p in parameters)
{
p.DefineParameterBuilder();
}
}
public Parameter Get(string name)
{
return parameters.Find(x => x.Name == name);
}
}
} | Java |
# at-rule-name-case
Specify lowercase or uppercase for at-rules names.
<!-- prettier-ignore -->
```css
@media (min-width: 10px) {}
/** ↑
* This at-rule name */
```
Only lowercase at-rule names are valid in SCSS.
The [`fix` option](../../../docs/user-guide/usage/options.md#fix) can automatically fix some of the problems reported by this rule.
## Options
`string`: `"lower"|"upper"`
### `"lower"`
The following patterns are considered violations:
<!-- prettier-ignore -->
```css
@Charset 'UTF-8';
```
<!-- prettier-ignore -->
```css
@cHarSeT 'UTF-8';
```
<!-- prettier-ignore -->
```css
@CHARSET 'UTF-8';
```
<!-- prettier-ignore -->
```css
@Media (min-width: 50em) {}
```
<!-- prettier-ignore -->
```css
@mEdIa (min-width: 50em) {}
```
<!-- prettier-ignore -->
```css
@MEDIA (min-width: 50em) {}
```
The following patterns are _not_ considered violations:
<!-- prettier-ignore -->
```css
@charset 'UTF-8';
```
<!-- prettier-ignore -->
```css
@media (min-width: 50em) {}
```
### `"upper"`
The following patterns are considered violations:
<!-- prettier-ignore -->
```css
@Charset 'UTF-8';
```
<!-- prettier-ignore -->
```css
@cHarSeT 'UTF-8';
```
<!-- prettier-ignore -->
```css
@charset 'UTF-8';
```
<!-- prettier-ignore -->
```css
@Media (min-width: 50em) {}
```
<!-- prettier-ignore -->
```css
@mEdIa (min-width: 50em) {}
```
<!-- prettier-ignore -->
```css
@media (min-width: 50em) {}
```
The following patterns are _not_ considered violations:
<!-- prettier-ignore -->
```css
@CHARSET 'UTF-8';
```
<!-- prettier-ignore -->
```css
@MEDIA (min-width: 50em) {}
```
| Java |
/*
Copyright [2011] [Prasad Balan]
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.yarsquidy.x12;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* The class represents methods used to translate a X12 transaction represented
* as a file or string into an X12 object.
*
* @author Prasad Balan
* @version $Id: $Id
*/
public class X12Parser implements Parser {
private static final int SIZE = 106;
/** Constant <code>POS_SEGMENT=105</code> */
public static final int POS_SEGMENT = 105;
/** Constant <code>POS_ELEMENT=3</code> */
public static final int POS_ELEMENT = 3;
/** Constant <code>POS_COMPOSITE_ELEMENT=104</code> */
public static final int POS_COMPOSITE_ELEMENT = 104;
/** Constant <code>START_TAG="ISA"</code> */
public static final String START_TAG = "ISA";
private Cf x12Cf;
private Cf cfMarker;
private Loop loopMarker;
/**
* <p>Constructor for X12Parser.</p>
*
* @param cf a {@link Cf} object.
*/
public X12Parser(Cf cf) {
this.x12Cf = cf;
}
/**
* {@inheritDoc}
*
* The method takes a X12 file and converts it into a X2 object. The X12
* class has methods to convert it into XML format as well as methods to
* modify the contents.
*/
public EDI parse(File fileName) throws FormatException, IOException {
final char[] buffer = new char[SIZE];
FileReader fr = new FileReader(fileName);
int count = fr.read(buffer);
String start = new String(buffer, 0, 3);
fr.close();
if (count != SIZE) {
throw new FormatException("The Interchange Control Header is not " +
"the correct size expected: "+SIZE+" found: "+count);
}
if (!start.startsWith(START_TAG)){
throw new FormatException("The Interchange Control Header Segment element: "+START_TAG+" is missing");
}
Context context = new Context();
context.setSegmentSeparator(buffer[POS_SEGMENT]);
context.setElementSeparator(buffer[POS_ELEMENT]);
context.setCompositeElementSeparator(buffer[POS_COMPOSITE_ELEMENT]);
Scanner scanner = new Scanner(fileName);
X12 x12 = scanSource(scanner, context);
scanner.close();
return x12;
}
/**
* private helper method
* @param scanner - the scanner to use in scanning.
* @param context - context for the scanner.
* @return X12 object found by the scanner.
*/
private X12 scanSource(Scanner scanner, Context context) {
Character segmentSeparator = context.getSegmentSeparator();
String quotedSegmentSeparator = Pattern.quote(segmentSeparator.toString());
scanner.useDelimiter(quotedSegmentSeparator + "\r\n|" + quotedSegmentSeparator + "\n|" + quotedSegmentSeparator);
cfMarker = x12Cf;
X12 x12 = new X12(context);
loopMarker = x12;
Loop loop = x12;
while (scanner.hasNext()) {
String line = scanner.next();
String[] tokens = line.split("\\" + context.getElementSeparator());
if (doesChildLoopMatch(cfMarker, tokens)) {
loop = loop.addChild(cfMarker.getName());
loop.addSegment(line);
} else if (doesParentLoopMatch(cfMarker, tokens, loop)) {
loop = loopMarker.addChild(cfMarker.getName());
loop.addSegment(line);
} else {
loop.addSegment(line);
}
}
return x12;
}
/**
* The method takes a InputStream and converts it into a X2 object. The X12
* class has methods to convert it into XML format as well as methods to
* modify the contents.
*
* @param source
* InputStream
* @return the X12 object
* @throws FormatException if any.
* @throws java.io.IOException if any.
*/
public EDI parse(InputStream source) throws FormatException, IOException {
StringBuilder strBuffer = new StringBuilder();
char[] cbuf = new char[1024];
int length;
Reader reader = new BufferedReader(new InputStreamReader(source));
while ((length = reader.read(cbuf)) != -1) {
strBuffer.append(cbuf, 0, length);
}
String strSource = strBuffer.toString();
return parse(strSource);
}
/**
* The method takes a X12 string and converts it into a X2 object. The X12
* class has methods to convert it into XML format as well as methods to
* modify the contents.
*
* @param source
* String
* @return the X12 object
* @throws FormatException if any.
*/
public EDI parse(String source) throws FormatException {
if (source.length() < SIZE) {
throw new FormatException();
}
Context context = new Context();
context.setSegmentSeparator(source.charAt(POS_SEGMENT));
context.setElementSeparator(source.charAt(POS_ELEMENT));
context.setCompositeElementSeparator(source.charAt(POS_COMPOSITE_ELEMENT));
Scanner scanner = new Scanner(source);
X12 x12 = scanSource(scanner, context);
scanner.close();
return x12;
}
/**
* Checks if the segment (or line read) matches to current loop
*
* @param cf
* Cf
* @param tokens
* String[] represents the segment broken into elements
* @return boolean
*/
private boolean doesLoopMatch(Cf cf, String[] tokens) {
if (cf.getSegment().equals(tokens[0])) {
if (null == cf.getSegmentQualPos()) {
return true;
} else {
for (String qual : cf.getSegmentQuals()) {
if (qual.equals(tokens[cf.getSegmentQualPos()])) {
return true;
}
}
}
}
return false;
}
/**
* Checks if the segment (or line read) matches to any of the child loops
* configuration.
*
* @param parent
* Cf
* @param tokens
* String[] represents the segment broken into elements
* @return boolean
*/
boolean doesChildLoopMatch(Cf parent, String[] tokens) {
for (Cf cf : parent.childList()) {
if (doesLoopMatch(cf, tokens)) {
cfMarker = cf;
return true;
}
}
return false;
}
/**
* Checks if the segment (or line read) matches the parent loop
* configuration.
*
* @param child
* Cf
* @param tokens
* String[] represents the segment broken into elements
* @param loop
* Loop
* @return boolean
*/
private boolean doesParentLoopMatch(Cf child, String[] tokens, Loop loop) {
Cf parent = child.getParent();
if (parent == null)
return false;
loopMarker = loop.getParent();
for (Cf cf : parent.childList()) {
if (doesLoopMatch(cf, tokens)) {
cfMarker = cf;
return true;
}
}
return doesParentLoopMatch(parent, tokens, loopMarker);
}
}
| Java |
#!/bin/sh
./fingerprints ethernet-bus-reconnect.csv ethernet-hub-reconnect.csv ethernet-hub.csv ethernet-switch.csv ethernet-twohosts.csv examples.csv multi.csv $*
| Java |
package com.chenantao.autolayout.utils;
import android.view.ViewGroup;
/**
* Created by Chenantao_gg on 2016/1/20.
*/
public class AutoLayoutGenerate
{
public static <T extends ViewGroup> T generate(Class<T> clazz, Class[] argumentTypes, Object[]
arguments)
{
// Enhancer enhancer = new Enhancer();
// enhancer.setSuperclass(clazz);
// CallbackFilter filter = new ConcreteClassCallbackFilter();
// Callback methodInterceptor = new ConcreteClassMethodInterceptor<T>((Context) arguments[0],
// (AttributeSet) arguments[1]);
// Callback noOp = NoOp.INSTANCE;
// Callback[] callbacks = new Callback[]{methodInterceptor, noOp};
// enhancer.setCallbackFilter(filter);
// enhancer.setCallbacks(callbacks);
// T proxyObj = (T) enhancer.create(argumentTypes, arguments);
// //对onMeasure方法以及generateLayoutParams进行拦截,其他方法不进行操作
// return proxyObj;
return null;
}
// static class ConcreteClassMethodInterceptor<T extends ViewGroup> implements MethodInterceptor
// {
// private AutoLayoutHelper mHelper;
// private Context mContext;
// private AttributeSet mAttrs;
//
// public ConcreteClassMethodInterceptor(Context context, AttributeSet attrs)
// {
// mContext = context;
// mAttrs = attrs;
// }
//
// public Object intercept(Object obj, Method method, Object[] arg, MethodProxy proxy)
// throws Throwable
// {
// if (mHelper == null)
// {
// mHelper = new AutoLayoutHelper((ViewGroup) obj);
// }
// System.out.println("Before:" + method);
// if ("onMeasure".equals(method.getName()))
// {
// //在onMeasure之前adjustChild
// if (!((ViewGroup) obj).isInEditMode())
// {
// mHelper.adjustChildren();
// }
//
// } else if ("generateLayoutParams".equals(method.getName()))
// {
// ViewGroup parent = (ViewGroup) obj;
// final T.LayoutParams layoutParams = (T.LayoutParams) Enhancer.create(T.LayoutParams
// .class, new Class[]{
// AutoLayoutHelper.AutoLayoutParams.class},
// new MethodInterceptor()
// {
// public Object intercept(Object obj, Method method, Object[] args,
// MethodProxy proxy) throws Throwable
// {
// if ("getAutoLayoutInfo".equals(method.getName()))
// {
// return AutoLayoutHelper.getAutoLayoutInfo(mContext, mAttrs);
// }
// return proxy.invoke(obj, args);
// }
// });
// return layoutParams;
// }
// Object object = proxy.invokeSuper(obj, arg);
// System.out.println("After:" + method);
// return object;
// }
// }
//
// static class ConcreteClassCallbackFilter implements CallbackFilter
// {
// public int accept(Method method)
// {
// if ("onMeasure".equals(method.getName()))
// {
// return 0;//Callback callbacks[0]
// } else if ("generateLayoutParams".equals(method.getName()))
// {
// return 0;
// }
// return 1;
// }
// }
// static class LayoutParamsGenerate implements FixedValue
// {
// public LayoutParamsGenerate(Context context, AttributeSet attributeSet)
// {
// }
//
// public Object loadObject() throws Exception
// {
// System.out.println("ConcreteClassFixedValue loadObject ...");
// Object object = 999;
// return object;
// }
// }
}
| Java |
# Copyright 2022 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from django.test.utils import override_settings
from sis_provisioner.tests import (
fdao_pws_override, fdao_hrp_override, fdao_bridge_override)
from sis_provisioner.tests.account_managers import set_uw_account
user_file_name_override = override_settings(
BRIDGE_IMPORT_USER_FILENAME="users")
def set_db_records():
affiemp = set_uw_account("affiemp")
javerage = set_uw_account("javerage")
ellen = set_uw_account("ellen")
staff = set_uw_account("staff")
staff.set_disable()
retiree = set_uw_account("retiree")
tyler = set_uw_account("faculty")
leftuw = set_uw_account("leftuw")
leftuw.set_terminate_date()
testid = set_uw_account("testid")
| Java |
package com.petercipov.mobi.deployer;
import com.petercipov.mobi.Instance;
import com.petercipov.traces.api.Trace;
import java.util.Optional;
import rx.Observable;
/**
*
* @author Peter Cipov
*/
public abstract class RxDeployment {
protected Optional<String> name;
public RxDeployment() {
this.name = Optional.empty();
}
public Optional<String> name() {
return name;
}
/**
* Sets container name
* @since 1.14
* @param name
* @return
*/
public RxDeployment setName(String name) {
this.name = Optional.of(name);
return this;
}
/**
* Adds volume bindings to container as string in format /host/path:/container/path
* @since 1.14
* @param volumeBindings iterable of bindings
* @return
*/
public abstract RxDeployment addVolumes(Iterable<String> volumeBindings);
/**
* Adds volume binding
* @since 1.14
* @param hostPath
* @param containerPath
* @return
*/
public abstract RxDeployment addVolume(String hostPath, String containerPath);
/**
* Adds environment variable to container
* @since 1.14
* @param variable variable in a format NAME=VALUE
* @return
*/
public abstract RxDeployment addEnv(String variable);
/**
* Adds environment variable to container
* @since 1.14
* @param name
* @param value
* @return
*/
public abstract RxDeployment addEnv(String name, String value);
/**
* Add port that should be published
* @since 1.14
* @param port - container port spect in format [tcp/udp]/port. f.e tcp/8080
* @param customPort - remapping port
* @return
*/
public abstract RxDeployment addPortMapping(String port, int customPort);
/**
* Publishes all exposed ports if is set to true
* @since 1.14
* @param publish
* @return
*/
public abstract RxDeployment setPublishAllPorts(boolean publish);
/**
* Publishes all exposed ports
* @since 1.14
* @return
*/
public abstract RxDeployment publishAllPorts();
/**
* Runs the command when starting the container
* @since 1.14
* @param cmd - command in for of single string or multitude of string that
* contains parts of command
* @return
*/
public abstract RxDeployment setCmd(String ... cmd);
/**
* Sets cpu quota
* @since 1.19
* @param quota Microseconds of CPU time that the container can get in a CPU period
* @return
*/
public abstract RxDeployment setCpuQuota(long quota);
/**
* Sets cpu shares
* @since 1.14
* @param shares An integer value containing the container’s CPU Shares (ie. the relative weight vs other containers)
* @return
*/
public abstract RxDeployment setCpuShares(long shares);
/**
* Sets domain name
* @since 1.14
* @param name A string value containing the domain name to use for the container.
* @return
*/
public abstract RxDeployment setDomainName(String name);
/**
* Sets entry point
* @since 1.15
* @param entry A command to run inside container. it overrides one specified by container docker file.
* @return
*/
public abstract RxDeployment setEntryPoint(String ... entry);
/**
* adds container exposed port
* @since 1.14
* @param port in format [tcp/udp]/port. f.e tcp/8080
* @return
*/
public abstract RxDeployment addExposedPort(String port);
/**
* Sets hostname
* @since 1.14
* @param hostName A string value containing the hostname to use for the container.
* @return
*/
public abstract RxDeployment setHostName(String hostName);
/**
* Adds label
* @since 1.18
* @param key
* @param value
* @return
*/
public abstract RxDeployment addLabel(String key, String value);
/**
* Sets MAC address.
* @since 1.15
* @param mac
* @return
*/
public abstract RxDeployment setMacAdress(String mac);
/**
* Sets memory limits
* @since 1.14
* @param memory Memory limit in bytes
* @return
*/
public abstract RxDeployment setMemory(long memory);
/**
* Sets memory limit
* @since 1.14
* @param memory Memory limit in bytes
* @param swap Memory limit for swap. Set -1 to disable swap.
* @return
*/
public abstract RxDeployment setMemory(long memory, long swap);
/**
* Disables networking for the container
* @since 1.14
* @param disabled
* @return
*/
public abstract RxDeployment setNetworkDisabled(boolean disabled);
/**
* Opens stdin
* @since 1.14
* @param open
* @return
*/
public abstract RxDeployment setOpenStdIn(boolean open);
/**
* Opens stdin and closes stdin after the 1. attached client disconnects.
* @since 1.14
* @param once
* @return
*/
public abstract RxDeployment setStdInOnce(boolean once);
/**
* Attaches standard streams to a tty, including stdin if it is not closed.
* @since 1.14
* @param enabled
* @return
*/
public abstract RxDeployment setTty(boolean enabled);
/**
* @since 1.14
* @param user A string value specifying the user inside the containe
* @return
*/
public abstract RxDeployment setUser(String user);
/**
* @since 1.14
* @param workDir A string specifying the working directory for commands to run in.
* @return
*/
public abstract RxDeployment setWorkDir(String workDir);
/**
* Sets path to cgroup
* @since 1.18
* @param parent Path to cgroups under which the cgroup for the container will be created. If the path is not absolute, the path is considered to be relative to the cgroups path of the init process. Cgroups will be created if they do not already exist
* @return
*/
public abstract RxDeployment setCgroupParent(String parent);
/**
* Adds DNS for fontainer
* @since 1.14
* @param dns A list of DNS servers for the container to use
* @return
*/
public abstract RxDeployment addDns(String ... dns);
/**
* Adds DNS search domains
* @since 1.15
* @param dns A list of DNS servers for the container to use.
* @return
*/
public abstract RxDeployment addDnsSearch(String ... dns);
/**
* Adds extra hosts co container /etc/hosts
* @since 1.15
* @param hosts A list of hostnames/IP mappings to add to the container’s /etc/hosts file. Specified in the form ["hostname:IP"]
* @return
*/
public abstract RxDeployment addExtraHosts(String ... hosts);
/**
* Adds links to other containers
* @since 1.14
* @param links A list of links for the container. Each link entry should be in the form of container_name:alias
* @return
*/
public abstract RxDeployment addLinks(String ... links);
/**
* Sets LXC specific configurations. These configurations only work when using the lxc execution driver.
* @since 1.14
* @param key
* @param value
* @return
*/
public abstract RxDeployment addLxcParameter(String key, String value);
/**
* Sets the networking mode for the container
* @since 1.15
* @param mode Supported values are: bridge, host, and container:name|id
* @return
*/
public abstract RxDeployment setNetworkMode(String mode);
/**
* Gives the container full access to the host.
* @since 1.14
* @param privileged
* @return
*/
public abstract RxDeployment setPrivileged(boolean privileged);
/**
* @since 1.15
* @param opts string value to customize labels for MLS systems, such as SELinux.
* @return
*/
public abstract RxDeployment addSecurityOpt(String ... opts);
/**
* Adds volume from an other container
* @since 1.14
* @param volumes volume to inherit from another container. Specified in the form container name:ro|rw
* @return
*/
public abstract RxDeployment addVolumeFrom(String ... volumes);
protected abstract Observable<String> createContainer(Trace trace, Instance image);
}
| Java |
//
// DFShortVideoMessageContent.h
// MongoIM
//
// Created by Allen Zhong on 16/2/14.
// Copyright © 2016年 MongoIM. All rights reserved.
//
#import "DFMediaMessageContent.h"
#import <UIKit/UIKit.h>
#import "DFVideoDecoder.h"
@interface DFShortVideoMessageContent : DFMediaMessageContent
@property (nonatomic, strong) UIImage *cover;
@property (nonatomic, strong) NSString *url;
@property (nonatomic, strong) NSString *filePath;
@property (nonatomic, strong) DFVideoDecoder *decorder;
@end
| Java |
/*
* Copyright 2015 Torridity.
*
* 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 de.tor.tribes.ui.models;
import de.tor.tribes.types.ext.Village;
import de.tor.tribes.ui.wiz.ret.types.RETSourceElement;
import java.util.LinkedList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
/**
*
* @author Torridity
*/
public class RETSourceTableModel extends AbstractTableModel {
private String[] columnNames = new String[]{
"Herkunft"
};
private Class[] types = new Class[]{
Village.class
};
private final List<RETSourceElement> elements = new LinkedList<RETSourceElement>();
public RETSourceTableModel() {
super();
}
public void clear() {
elements.clear();
fireTableDataChanged();
}
public void addRow(RETSourceElement pVillage, boolean pValidate) {
elements.add(pVillage);
if (pValidate) {
fireTableDataChanged();
}
}
@Override
public int getRowCount() {
if (elements == null) {
return 0;
}
return elements.size();
}
@Override
public Class getColumnClass(int columnIndex) {
return types[columnIndex];
}
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
@Override
public String getColumnName(int column) {
return columnNames[column];
}
public void removeRow(int row) {
elements.remove(row);
fireTableDataChanged();
}
public RETSourceElement getRow(int row) {
return elements.get(row);
}
@Override
public Object getValueAt(int row, int column) {
if (elements == null || elements.size() - 1 < row) {
return null;
}
return elements.get(row).getVillage();
}
@Override
public int getColumnCount() {
return columnNames.length;
}
}
| Java |
package com.zk.web.interceptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
public class CustomizedHandlerExceptionResolver implements HandlerExceptionResolver, Ordered {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomizedHandlerExceptionResolver.class);
public int getOrder() {
return Integer.MIN_VALUE;
}
public ModelAndView resolveException(HttpServletRequest aReq, HttpServletResponse aRes, Object aHandler,
Exception exception) {
if (aHandler instanceof HandlerMethod) {
if (exception instanceof BindException) {
return null;
}
}
LOGGER.error(StringUtils.EMPTY, exception);
ModelAndView mav = new ModelAndView("common/error");
String errorMsg = exception.getMessage();
aRes.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
if ("XMLHttpRequest".equals(aReq.getHeader("X-Requested-With"))) {
try {
aRes.setContentType("application/text; charset=utf-8");
PrintWriter writer = aRes.getWriter();
aRes.setStatus(HttpServletResponse.SC_FORBIDDEN);
writer.print(errorMsg);
writer.flush();
writer.close();
return null;
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
mav.addObject("errorMsg", errorMsg);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
exception.printStackTrace(pw);
mav.addObject("stackTrace", sw.getBuffer().toString());
mav.addObject("exception", exception);
return mav;
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.intelligentsia.dowsers.core.serializers.jackson;
import java.io.IOException;
import org.intelligentsia.dowsers.core.reflection.ClassInformation;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
/**
*
* ClassInformationDeserializer.
*
* @author <a href="mailto:jguibert@intelligents-ia.com" >Jerome Guibert</a>
*/
public class ClassInformationDeserializer extends StdDeserializer<ClassInformation> {
/**
* serialVersionUID:long
*/
private static final long serialVersionUID = -6052449554113264932L;
public ClassInformationDeserializer() {
super(ClassInformation.class);
}
@Override
public ClassInformation deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
String description = null;
if (jp.hasCurrentToken()) {
if (jp.getCurrentToken().equals(JsonToken.START_OBJECT)) {
jp.nextValue();
description = jp.getText();
jp.nextToken();
}
}
return description != null ? ClassInformation.parse(description) : null;
}
}
| Java |
package org.jboss.resteasy.reactive.server.vertx.test;
import static org.junit.jupiter.api.Assertions.fail;
import io.smallrye.common.annotation.Blocking;
import io.smallrye.common.annotation.NonBlocking;
import java.util.function.Supplier;
import javax.enterprise.inject.spi.DeploymentException;
import javax.ws.rs.Path;
import org.jboss.resteasy.reactive.server.vertx.test.framework.ResteasyReactiveUnitTest;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
public class BothBlockingAndNonBlockingOnClassTest {
@RegisterExtension
static ResteasyReactiveUnitTest test = new ResteasyReactiveUnitTest()
.setArchiveProducer(new Supplier<>() {
@Override
public JavaArchive get() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(Resource.class);
}
}).setExpectedException(DeploymentException.class);
@Test
public void test() {
fail("Should never have been called");
}
@Path("test")
@Blocking
@NonBlocking
public static class Resource {
@Path("hello")
public String hello() {
return "hello";
}
}
}
| Java |
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#endif
FOUNDATION_EXPORT double Pods_CommuneUITestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_CommuneUITestsVersionString[];
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="zh">
<head>
<!-- Generated by javadoc (1.8.0_111) on Mon Oct 22 12:02:26 CST 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>程序包 com.dtstack.jlogstash.format的使用 (hdfs 1.0.0 API)</title>
<meta name="date" content="2018-10-22">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="\u7A0B\u5E8F\u5305 com.dtstack.jlogstash.format\u7684\u4F7F\u7528 (hdfs 1.0.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>您的浏览器已禁用 JavaScript。</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="跳过导航链接">跳过导航链接</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="导航">
<li><a href="../../../../overview-summary.html">概览</a></li>
<li><a href="package-summary.html">程序包</a></li>
<li>类</li>
<li class="navBarCell1Rev">使用</li>
<li><a href="package-tree.html">树</a></li>
<li><a href="../../../../deprecated-list.html">已过时</a></li>
<li><a href="../../../../index-all.html">索引</a></li>
<li><a href="../../../../help-doc.html">帮助</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>上一个</li>
<li>下一个</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/dtstack/jlogstash/format/package-use.html" target="_top">框架</a></li>
<li><a href="package-use.html" target="_top">无框架</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">所有类</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="程序包的使用 com.dtstack.jlogstash.format" class="title">程序包的使用<br>com.dtstack.jlogstash.format</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="使用表, 列表程序包和解释">
<caption><span>使用<a href="../../../../com/dtstack/jlogstash/format/package-summary.html">com.dtstack.jlogstash.format</a>的程序包</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">程序包</th>
<th class="colLast" scope="col">说明</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.dtstack.jlogstash.format">com.dtstack.jlogstash.format</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.dtstack.jlogstash.format.plugin">com.dtstack.jlogstash.format.plugin</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#com.dtstack.jlogstash.outputs">com.dtstack.jlogstash.outputs</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.dtstack.jlogstash.format">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="使用表, 列表类和解释">
<caption><span><a href="../../../../com/dtstack/jlogstash/format/package-summary.html">com.dtstack.jlogstash.format</a>使用的<a href="../../../../com/dtstack/jlogstash/format/package-summary.html">com.dtstack.jlogstash.format</a>中的类</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">类和说明</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../com/dtstack/jlogstash/format/class-use/CompressEnum.html#com.dtstack.jlogstash.format">CompressEnum</a> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../com/dtstack/jlogstash/format/class-use/ModeEnum.html#com.dtstack.jlogstash.format">ModeEnum</a> </td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../com/dtstack/jlogstash/format/class-use/OutputFormat.html#com.dtstack.jlogstash.format">OutputFormat</a> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../com/dtstack/jlogstash/format/class-use/StoreEnum.html#com.dtstack.jlogstash.format">StoreEnum</a> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.dtstack.jlogstash.format.plugin">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="使用表, 列表类和解释">
<caption><span><a href="../../../../com/dtstack/jlogstash/format/plugin/package-summary.html">com.dtstack.jlogstash.format.plugin</a>使用的<a href="../../../../com/dtstack/jlogstash/format/package-summary.html">com.dtstack.jlogstash.format</a>中的类</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">类和说明</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../com/dtstack/jlogstash/format/class-use/HdfsOutputFormat.html#com.dtstack.jlogstash.format.plugin">HdfsOutputFormat</a> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../com/dtstack/jlogstash/format/class-use/OutputFormat.html#com.dtstack.jlogstash.format.plugin">OutputFormat</a> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.dtstack.jlogstash.outputs">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="使用表, 列表类和解释">
<caption><span><a href="../../../../com/dtstack/jlogstash/outputs/package-summary.html">com.dtstack.jlogstash.outputs</a>使用的<a href="../../../../com/dtstack/jlogstash/format/package-summary.html">com.dtstack.jlogstash.format</a>中的类</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">类和说明</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../com/dtstack/jlogstash/format/class-use/HdfsOutputFormat.html#com.dtstack.jlogstash.outputs">HdfsOutputFormat</a> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="跳过导航链接">跳过导航链接</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="导航">
<li><a href="../../../../overview-summary.html">概览</a></li>
<li><a href="package-summary.html">程序包</a></li>
<li>类</li>
<li class="navBarCell1Rev">使用</li>
<li><a href="package-tree.html">树</a></li>
<li><a href="../../../../deprecated-list.html">已过时</a></li>
<li><a href="../../../../index-all.html">索引</a></li>
<li><a href="../../../../help-doc.html">帮助</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>上一个</li>
<li>下一个</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/dtstack/jlogstash/format/package-use.html" target="_top">框架</a></li>
<li><a href="package-use.html" target="_top">无框架</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">所有类</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2018. All rights reserved.</small></p>
</body>
</html>
| Java |
/*
* *
* * Copyright (C) 2015 Orange
* * 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.orange.servicebroker.staticcreds.stories.support_route_services;
import com.orange.servicebroker.staticcreds.domain.PlanProperties;
import com.orange.servicebroker.staticcreds.domain.ServiceBrokerProperties;
import com.orange.servicebroker.staticcreds.domain.ServiceProperties;
import com.tngtech.jgiven.junit.SimpleScenarioTest;
import org.junit.Test;
import org.springframework.cloud.servicebroker.model.ServiceDefinitionRequires;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author Sebastien Bortolussi
*/
@AddRouteService
@Issue_32
public class ConfigureServiceBrokerWithRouteServiceTest extends SimpleScenarioTest<ConfigureServiceBrokerStage> {
private static ServiceBrokerProperties service_broker_properties_with_route_service_url_at_service_level_and_requires_field_set() {
PlanProperties dev = new PlanProperties("dev");
dev.setId("dev-id");
dev.setCredentials(uriCredentials());
ServiceProperties myServiceProperties = new ServiceProperties();
myServiceProperties.setName("myservice");
myServiceProperties.setId("myservice-id");
myServiceProperties.setRequires(Arrays.asList(ServiceDefinitionRequires.SERVICE_REQUIRES_ROUTE_FORWARDING.toString()));
myServiceProperties.setRouteServiceUrl("https://myloggingservice.org/path");
final Map<String, PlanProperties> myServicePlans = new HashMap<>();
myServicePlans.put("dev", dev);
myServiceProperties.setPlans(myServicePlans);
final Map<String, ServiceProperties> services = new HashMap<>();
services.put("myservice", myServiceProperties);
return new ServiceBrokerProperties(services);
}
private static Map<String, Object> uriCredentials() {
Map<String, Object> credentials = new HashMap<>();
credentials.put("URI", "http://my-api.org");
return credentials;
}
private static ServiceBrokerProperties service_broker_properties_with_route_service_url_at_service_plan_level_and_requires_field_set() {
PlanProperties dev = new PlanProperties("dev");
dev.setId("dev-id");
dev.setCredentials(uriCredentials());
dev.setRouteServiceUrl("https://myloggingservice.org/path");
ServiceProperties myServiceProperties = new ServiceProperties();
myServiceProperties.setName("myservice");
myServiceProperties.setId("myservice-id");
myServiceProperties.setRequires(Arrays.asList(ServiceDefinitionRequires.SERVICE_REQUIRES_ROUTE_FORWARDING.toString()));
final Map<String, PlanProperties> myServicePlans = new HashMap<>();
myServicePlans.put("dev", dev);
myServiceProperties.setPlans(myServicePlans);
final Map<String, ServiceProperties> services = new HashMap<>();
services.put("myservice", myServiceProperties);
return new ServiceBrokerProperties(services);
}
private static ServiceBrokerProperties catalog_with_route_service_url_at_service_level_but_without_requires_field_set() {
PlanProperties dev = new PlanProperties("dev");
dev.setId("dev-id");
dev.setCredentials(uriCredentials());
ServiceProperties myServiceProperties = new ServiceProperties();
myServiceProperties.setName("myservice");
myServiceProperties.setId("myservice-id");
myServiceProperties.setRouteServiceUrl("https://myloggingservice.org/path");
final Map<String, PlanProperties> myServicePlans = new HashMap<>();
myServicePlans.put("dev", dev);
myServiceProperties.setPlans(myServicePlans);
final Map<String, ServiceProperties> services = new HashMap<>();
services.put("myservice", myServiceProperties);
return new ServiceBrokerProperties(services);
}
private static ServiceBrokerProperties service_broker_properties_with_route_service_url_at_service_plan_level_but_without_requires_field_set() {
PlanProperties dev = new PlanProperties("dev");
dev.setId("dev-id");
dev.setCredentials(uriCredentials());
dev.setRouteServiceUrl("https://myloggingservice.org/path");
ServiceProperties myServiceProperties = new ServiceProperties();
myServiceProperties.setName("myservice");
myServiceProperties.setId("myservice-id");
final Map<String, PlanProperties> myServicePlans = new HashMap<>();
myServicePlans.put("dev", dev);
myServiceProperties.setPlans(myServicePlans);
final Map<String, ServiceProperties> services = new HashMap<>();
services.put("myservice", myServiceProperties);
return new ServiceBrokerProperties(services);
}
@Test
public void configure_service_broker_with_same_route_service_url_for_all_service_plans_and_requires_field_set() throws Exception {
when().paas_ops_configures_service_broker_with_following_config(service_broker_properties_with_route_service_url_at_service_level_and_requires_field_set());
then().it_should_succeed();
}
@Test
public void configure_service_broker_with_same_route_service_url_for_all_service_plans_but_omits_requires_field() throws Exception {
when().paas_ops_configures_service_broker_with_following_config(catalog_with_route_service_url_at_service_level_but_without_requires_field_set());
then().it_should_fail();
}
@Test
public void configure_service_broker_with_route_service_url_set_for_a_service_plan_and_requires_field_set() throws Exception {
when().paas_ops_configures_service_broker_with_following_config(service_broker_properties_with_route_service_url_at_service_plan_level_and_requires_field_set());
then().it_should_succeed();
}
@Test
public void configure_service_broker_with_route_service_url_set_for_a_service_plan_but_omits_requires_field() throws Exception {
when().paas_ops_configures_service_broker_with_following_config(service_broker_properties_with_route_service_url_at_service_plan_level_but_without_requires_field_set());
then().it_should_fail();
}
}
| Java |
# Parodia elata F.H.Brandt SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | Java |
/*
* Copyright 2018 Sebastien Callier
*
* 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 sebastien.callier.serialization.codec.extendable.object.field.primitives;
import sebastien.callier.serialization.codec.Codec;
import sebastien.callier.serialization.codec.extendable.object.field.FieldCodec;
import sebastien.callier.serialization.codec.extendable.object.field.LambdaMetaFactoryUtils;
import sebastien.callier.serialization.deserializer.InputStreamWrapper;
import sebastien.callier.serialization.exceptions.CodecGenerationException;
import sebastien.callier.serialization.serializer.OutputStreamWrapper;
import java.io.IOException;
import java.lang.reflect.Method;
/**
* @author Sebastien Callier
* @since 2018
*/
public class ByteFieldCodec implements FieldCodec {
private final Getter get;
private final Setter set;
private final Codec codec;
public ByteFieldCodec(
Method getter,
Method setter,
Codec codec) throws CodecGenerationException {
super();
get = LambdaMetaFactoryUtils.wrapGetter(Getter.class, getter, byte.class);
set = LambdaMetaFactoryUtils.wrapSetter(Setter.class, setter, byte.class);
this.codec = codec;
}
@FunctionalInterface
public interface Getter {
byte get(Object instance);
}
@FunctionalInterface
public interface Setter {
void set(Object instance, byte value);
}
@Override
@SuppressWarnings("unchecked")
public void write(OutputStreamWrapper wrapper, Object instance) throws IOException {
codec.write(wrapper, get.get(instance));
}
@Override
@SuppressWarnings("unchecked")
public void read(InputStreamWrapper wrapper, Object instance) throws IOException {
set.set(instance, (Byte) codec.read(wrapper));
}
} | Java |
import eventlet
import gettext
import sys
from staccato.common import config
import staccato.openstack.common.wsgi as os_wsgi
import staccato.openstack.common.pastedeploy as os_pastedeploy
# Monkey patch socket and time
eventlet.patcher.monkey_patch(all=False, socket=True, time=True)
gettext.install('staccato', unicode=1)
def fail(returncode, e):
sys.stderr.write("ERROR: %s\n" % e)
sys.exit(returncode)
def main():
try:
conf = config.get_config_object()
paste_file = conf.find_file(conf.paste_deploy.config_file)
wsgi_app = os_pastedeploy.paste_deploy_app(paste_file,
'staccato-api',
conf)
server = os_wsgi.Service(wsgi_app, conf.bind_port)
server.start()
server.wait()
except RuntimeError as e:
fail(1, e)
main()
| Java |
<?php
exec('"' . __DIR__ . '/vendor/bin/phinx" rollback -t=0');
exec('"' . __DIR__ . '/vendor/bin/phinx" migrate');
exec('"' . __DIR__ . '/vendor/bin/phinx" seed:run');
?> | Java |
using System;
using System.Drawing;
using NetTopologySuite.Geometries;
namespace SharpMap
{
/// <summary>
/// Utility class that checks Viewport min/max Zoom and constraint
/// </summary>
[Serializable]
public class MapViewPortGuard
{
private double _minimumZoom;
private double _maximumZoom;
private Envelope _maximumExtents;
private double _pixelAspectRatio;
const double MinMinZoomValue = 2d * Double.Epsilon;
/// <summary>
/// Gets or sets a value indicating the minimum zoom level.
/// </summary>
public double MinimumZoom
{
get { return _minimumZoom; }
set
{
if (value < MinMinZoomValue)
value = MinMinZoomValue;
_minimumZoom = value;
}
}
/// <summary>
/// Gets or sets a value indicating the maximum zoom level.
/// </summary>
public double MaximumZoom
{
get { return _maximumZoom; }
set
{
if (value < _minimumZoom)
value = _minimumZoom;
_maximumZoom = value;
}
}
/// <summary>
/// Gets or sets a value indicating the maximum extents
/// </summary>
public Envelope MaximumExtents
{
get { return _maximumExtents ?? (_maximumExtents = new Envelope()); }
set { _maximumExtents = value; }
}
/// <summary>
/// Gets or sets the size of the Map in device units (Pixel)
/// </summary>
public Size Size { get; set; }
/// <summary>
/// Gets or sets the aspect-ratio of the pixel scales. A value less than
/// 1 will make the map streach upwards, and larger than 1 will make it smaller.
/// </summary>
/// <exception cref="ArgumentException">Throws an argument exception when value is 0 or less.</exception>
public double PixelAspectRatio
{
get { return _pixelAspectRatio; }
set
{
if (value <= 0)
throw new ArgumentException("Invalid Pixel Aspect Ratio");
_pixelAspectRatio = value;
}
}
/// <summary>
/// Creates an instance of this class
/// </summary>
internal MapViewPortGuard(Size size, double minZoom, double maxZoom)
{
Size = size;
MinimumZoom = minZoom;
MaximumZoom = maxZoom;
PixelAspectRatio = 1d;
}
/// <summary>
/// Gets or sets a value indicating if <see cref="Map.MaximumExtents"/> should be enforced or not.
/// </summary>
public bool EnforceMaximumExtents { get; set; }
/// <summary>
/// Verifies the zoom level and center of the map
/// </summary>
/// <param name="zoom">The zoom level to test</param>
/// <param name="center">The center of the map. This coordinate might change so you <b>must</b> provide a copy if you want to preserve the old value</param>
/// <returns>The zoom level, might have changed</returns>
public double VerifyZoom(double zoom, Coordinate center)
{
// Zoom within valid region
if (zoom < _minimumZoom)
zoom = _minimumZoom;
else if (zoom > _maximumZoom)
zoom = _maximumZoom;
if (EnforceMaximumExtents)
{
var arWidth = (double) Size.Width/Size.Height;
if (zoom > _maximumExtents.Width)
zoom = _maximumExtents.Width;
if (zoom > arWidth * _maximumExtents.Height)
zoom = arWidth * _maximumExtents.Height;
zoom = VerifyValidViewport(zoom, center);
}
return zoom;
}
/// <summary>
/// Verifies the valid viewport, makes adjustments if required
/// </summary>
/// <param name="zoom">The current zoom</param>
/// <param name="center">The </param>
/// <returns>The verified zoom level</returns>
private double VerifyValidViewport(double zoom, Coordinate center)
{
var maxExtents = MaximumExtents ?? new Envelope();
if (maxExtents.IsNull)
return zoom;
var halfWidth = 0.5d * zoom;
var halfHeight = halfWidth * PixelAspectRatio * ((double)Size.Height / Size.Width);
var maxZoomHeight = _maximumZoom < double.MaxValue ? _maximumZoom : double.MaxValue;
if (2 * halfHeight > maxZoomHeight)
{
halfHeight = 0.5d*maxZoomHeight;
halfWidth = halfHeight / (_pixelAspectRatio * ((double)Size.Height / Size.Width));
zoom = 2 * halfWidth;
}
var testEnvelope = new Envelope(center.X - halfWidth, center.X + halfWidth,
center.Y - halfHeight, center.Y + halfHeight);
if (maxExtents.Contains(testEnvelope))
return zoom;
var dx = testEnvelope.MinX < maxExtents.MinX
? maxExtents.MinX - testEnvelope.MinX
: testEnvelope.MaxX > maxExtents.MaxX
? maxExtents.MaxX - testEnvelope.MaxX
: 0;
var dy = testEnvelope.MinY < maxExtents.MinY
? maxExtents.MinY - testEnvelope.MinY
: testEnvelope.MaxY > maxExtents.MaxY
? maxExtents.MaxY - testEnvelope.MaxY
: 0;
center.X += dx;
center.Y += dy;
return zoom;
}
}
/// <summary>
/// Utility class to lock a map's viewport so it cannot be changed
/// </summary>
public class MapViewportLock
{
private readonly Map _map;
private double _minimumZoom;
private double _maximumZoom;
private Envelope _maximumExtents;
private bool _enforce;
/// <summary>
/// Creates an instance of this class
/// </summary>
/// <param name="map"></param>
public MapViewportLock(Map map)
{
_map = map;
}
/// <summary>
/// Lock the viewport of the map
/// </summary>
public void Lock()
{
if (IsLocked)
return;
// Signal the viewport as locked
IsLocked = true;
// store the current extent settings
_minimumZoom = _map.MinimumZoom;
_maximumZoom = _map.MaximumZoom;
_maximumExtents = _map.MaximumExtents;
_enforce = _map.EnforceMaximumExtents;
// Lock the viewport
_map.MinimumZoom = _map.MaximumZoom = _map.Zoom;
_map.MaximumExtents = _map.Envelope;
_map.EnforceMaximumExtents = true;
}
/// <summary>
/// Gets a value indicating that the map's viewport is locked
/// </summary>
public bool IsLocked { get; private set; }
/// <summary>
/// Unlock the viewport of the map
/// </summary>
public void Unlock()
{
// Unlock the viewport
_map.EnforceMaximumExtents = _enforce;
_map.MaximumExtents = _maximumExtents;
_map.MinimumZoom = _minimumZoom;
_map.MaximumZoom = _maximumZoom;
// Signal the viewport as unlocked
IsLocked = false;
}
}
} | Java |
//
// Copyright 2011 ODIN Working Group. 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.
//
#import <Foundation/Foundation.h>
NSString * MCMODIN1();
| Java |
/*
* Copyright 2010-2015 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.
*/
#include <aws/ec2/model/DescribeNetworkInterfacesResponse.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::EC2::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::Logging;
using namespace Aws::Utils;
using namespace Aws;
DescribeNetworkInterfacesResponse::DescribeNetworkInterfacesResponse()
{
}
DescribeNetworkInterfacesResponse::DescribeNetworkInterfacesResponse(const AmazonWebServiceResult<XmlDocument>& result)
{
*this = result;
}
DescribeNetworkInterfacesResponse& DescribeNetworkInterfacesResponse::operator =(const AmazonWebServiceResult<XmlDocument>& result)
{
const XmlDocument& xmlDocument = result.GetPayload();
XmlNode rootNode = xmlDocument.GetRootElement();
XmlNode resultNode = rootNode;
if (rootNode.GetName() != "DescribeNetworkInterfacesResponse")
{
resultNode = rootNode.FirstChild("DescribeNetworkInterfacesResponse");
}
if(!resultNode.IsNull())
{
XmlNode networkInterfacesNode = resultNode.FirstChild("networkInterfaceSet");
if(!networkInterfacesNode.IsNull())
{
XmlNode networkInterfacesMember = networkInterfacesNode.FirstChild("item");
while(!networkInterfacesMember.IsNull())
{
m_networkInterfaces.push_back(networkInterfacesMember);
networkInterfacesMember = networkInterfacesMember.NextNode("item");
}
}
}
XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata");
m_responseMetadata = responseMetadataNode;
AWS_LOGSTREAM_DEBUG("Aws::EC2::Model::DescribeNetworkInterfacesResponse", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() );
return *this;
}
| Java |
package com.noeasy.money.exception;
public class UserErrorMetadata extends BaseErrorMetadata {
public static final UserErrorMetadata USER_EXIST = new UserErrorMetadata(101, "User exit");
public static final UserErrorMetadata NULL_USER_BEAN = new UserErrorMetadata(102, "Userbean is null");
protected UserErrorMetadata(int pErrorCode, String pErrorMesage) {
super(pErrorCode, pErrorMesage);
}
}
| Java |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
NamingPeopleContentManager = function() {
this.SaveSchema = function(parentCallback) {
var schemaId = jq('#namingPeopleSchema').val();
if (schemaId == 'custom') {
NamingPeopleContentController.SaveCustomNamingSettings(jq('#usrcaption').val().substring(0, 30), jq('#usrscaption').val().substring(0, 30),
jq('#grpcaption').val().substring(0, 30), jq('#grpscaption').val().substring(0, 30),
jq('#usrstatuscaption').val().substring(0, 30), jq('#regdatecaption').val().substring(0, 30),
jq('#grpheadcaption').val().substring(0, 30),
jq('#guestcaption').val().substring(0, 30), jq('#guestscaption').val().substring(0, 30),
function(result) { if (parentCallback != null) parentCallback(result.value); });
}
else
NamingPeopleContentController.SaveNamingSettings(schemaId, function(result) { if (parentCallback != null) parentCallback(result.value); });
}
this.SaveSchemaCallback = function(res) {
}
this.LoadSchemaNames = function(parentCallback) {
var schemaId = jq('#namingPeopleSchema').val();
NamingPeopleContentController.GetPeopleNames(schemaId, function(res) {
var names = res.value;
jq('#usrcaption').val(names.UserCaption);
jq('#usrscaption').val(names.UsersCaption);
jq('#grpcaption').val(names.GroupCaption);
jq('#grpscaption').val(names.GroupsCaption);
jq('#usrstatuscaption').val(names.UserPostCaption);
jq('#regdatecaption').val(names.RegDateCaption);
jq('#grpheadcaption').val(names.GroupHeadCaption);
jq('#guestcaption').val(names.GuestCaption);
jq('#guestscaption').val(names.GuestsCaption);
if (parentCallback != null)
parentCallback(res.value);
});
}
}
NamingPeopleContentViewer = new function() {
this.ChangeValue = function(event) {
jq('#namingPeopleSchema').val('custom');
}
};
jq(document).ready(function() {
jq('.namingPeopleBox input[type="text"]').each(function(i, el) {
jq(el).keypress(function(event) { NamingPeopleContentViewer.ChangeValue(); });
});
var manager = new NamingPeopleContentManager();
jq('#namingPeopleSchema').change(function () {
manager.LoadSchemaNames(null);
});
manager.LoadSchemaNames(null);
}); | Java |
#!/usr/bin/env python
# Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx.
from netmiko import ConnectHandler
def main():
# Definition of routers
rtr1 = {
'device_type': 'cisco_ios',
'ip': '50.76.53.27',
'username': 'pyclass',
'password': '88newclass',
}
rtr2 = {
'device_type': 'cisco_ios',
'ip': '50.76.53.27',
'username': 'pyclass',
'password': '88newclass',
'port': 8022,
}
srx = {
'device_type': 'juniper',
'ip': '50.76.53.27',
'username': 'pyclass',
'password': '88newclass',
'port': 9822,
}
# Create a list of all the routers.
all_routers = [rtr1, rtr2, srx]
# Loop through all the routers and show arp.
for a_router in all_routers:
net_connect = ConnectHandler(**a_router)
output = net_connect.send_command("show arp")
print "\n\n>>>>>>>>> Device {0} <<<<<<<<<".format(a_router['device_type'])
print output
print ">>>>>>>>> End <<<<<<<<<"
if __name__ == "__main__":
main()
| Java |
// Fill out your copyright notice in the Description page of Project Settings.
#include "Projectile.h"
// Sets default values
AProjectile::AProjectile()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
ProjectileMovement = CreateDefaultSubobject<UProjectileMovementComponent>(FName("Projectile Movement"));
ProjectileMovement->bAutoActivate = false;
}
// Called when the game starts or when spawned
void AProjectile::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AProjectile::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
void AProjectile::LaunchProjectile(float Speed)
{
ProjectileMovement->SetVelocityInLocalSpace(FVector::ForwardVector * Speed);
ProjectileMovement->Activate();
}
| Java |
""" IO classes for Omnivor input file
Copyright (C) 2013 DTU Wind Energy
Author: Emmanuel Branlard
Email: ebra@dtu.dk
Last revision: 25/11/2013
Namelist IO: badis functions to read and parse a fortran file into python dictonary and write it back to a file
The parser was adapted from: fortran-namelist on code.google with the following info:
__author__ = 'Stephane Chamberland (stephane.chamberland@ec.gc.ca)'
__version__ = '$Revision: 1.0 $'[11:-2]
__date__ = '$Date: 2006/09/05 21:16:24 $'
__copyright__ = 'Copyright (c) 2006 RPN'
__license__ = 'LGPL'
Recognizes files of the form:
&namelistname
opt1 = value1
...
/
"""
from __future__ import print_function
from we_file_io import WEFileIO, TestWEFileIO
import unittest
import numpy as np
import os.path as path
import sys
import re
import tempfile
import os
__author__ = 'E. Branlard '
class FortranNamelistIO(WEFileIO):
"""
Fortran Namelist IO class
Scan a Fortran Namelist file and put Section/Parameters into a dictionary
Write the file back if needed.
"""
def _write(self):
""" Write a file (overrided)
"""
with open(self.filename, 'w') as f:
for nml in self.data :
f.write('&'+nml+'\n')
# Sorting dictionary data (in the same order as it was created, thanks to id)
SortedList = sorted(self.data[nml].items(), key=lambda(k, v): v['id'])
# for param in self.data[nml]:
for param in map(lambda(k,v):k,SortedList):
f.write(param+'='+','.join(self.data[nml][param]['val']))
if len(self.data[nml][param]['com']) >0:
f.write(' !'+self.data[nml][param]['com'])
f.write('\n')
f.write('/\n')
def _read(self):
""" Read the file (overrided)
"""
with open(self.filename, 'r') as f:
data = f.read()
varname = r'\b[a-zA-Z][a-zA-Z0-9_]*\b'
valueInt = re.compile(r'[+-]?[0-9]+')
valueReal = re.compile(r'[+-]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)')
valueNumber = re.compile(r'\b(([\+\-]?[0-9]+)?\.)?[0-9]*([eE][-+]?[0-9]+)?')
valueBool = re.compile(r"(\.(true|false|t|f)\.)",re.I)
valueTrue = re.compile(r"(\.(true|t)\.)",re.I)
spaces = r'[\s\t]*'
quote = re.compile(r"[\s\t]*[\'\"]")
namelistname = re.compile(r"^[\s\t]*&(" + varname + r")[\s\t]*$")
paramname = re.compile(r"[\s\t]*(" + varname+r')[\s\t]*=[\s\t]*')
namlistend = re.compile(r"^" + spaces + r"/" + spaces + r"$")
#split sections/namelists
mynmlfile = {}
mynmlfileRaw = {}
mynmlname = ''
for item in FortranNamelistIO.clean(data.split("\n"),cleancomma=1):
if re.match(namelistname,item):
mynmlname = re.sub(namelistname,r"\1",item)
mynmlfile[mynmlname] = {}
mynmlfileRaw[mynmlname] = []
elif re.match(namlistend,item):
mynmlname = ''
else:
if mynmlname:
mynmlfileRaw[mynmlname].append(item)
#parse param in each section/namelist
for mynmlname in mynmlfile.keys():
#split strings
bb = []
for item in mynmlfileRaw[mynmlname]:
if item[0]!='!':
# discarding lines that starts with a comment
bb.extend(FortranNamelistIO.splitstring(item))
#split comma and =
aa = []
for item in bb:
if not re.match(quote,item):
aa.extend(re.sub(r"[\s\t]*=",r" =\n",re.sub(r",+",r"\n",item)).split("\n"))
# aa.extend(re.sub(r"[\s\t]*=",r" =\n",item).split("\n"))
else:
aa.append(item)
del(bb)
aa = FortranNamelistIO.clean(aa,cleancomma=1)
myparname = ''
id_cum=0
for item in aa:
if re.search(paramname,item):
#myparname = re.sub(paramname,r"\1",item).lower() ! NO MORE LOWER CASE
myparname = re.sub(paramname,r"\1",item)
id_cum=id_cum+1
mynmlfile[mynmlname][myparname] = {
'val' : [],
'id' : id_cum,
'com' : ''
}
elif paramname:
# Storing comments
item2=item.split('!')
item=item2[0]
if len(item) > 1 :
mynmlfile[mynmlname][myparname]['com']=''.join(item2[1:])
if re.match(valueBool,item):
if re.match(valueTrue,item):
mynmlfile[mynmlname][myparname]['val'].append('.true.')
else:
mynmlfile[mynmlname][myparname]['val'].append('.false.')
else:
# item2=re.sub(r"(^[\'\"]|[\'\"]$)",r"",item.strip())
mynmlfile[mynmlname][myparname]['val'].append(item.strip())
self.data=mynmlfile
# Accessor and mutator dictionary style
def __getitem__(self, key):
""" Transform the class instance into a dictionary."""
return self.data[key]
def __setitem__(self, key, value):
""" Transform the class instance into a dictionary."""
self.data[key] = value
#==== Helper functions for Parsing of files
@staticmethod
def clean(mystringlist,commentexpr=r"^[\s\t]*\#.*$",spacemerge=0,cleancomma=0):
"""
Remove leading and trailing blanks, comments/empty lines from a list of strings
mystringlist = foo.clean(mystringlist,spacemerge=0,commentline=r"^[\s\t]*\#",cleancharlist="")
commentline: definition of commentline
spacemerge: if <>0, merge/collapse multi space
cleancomma: Remove leading and trailing commas
"""
aa = mystringlist
if cleancomma:
aa = [re.sub("(^([\s\t]*\,)+)|((\,[\s\t]*)+$)","",item).strip() for item in aa]
if commentexpr:
aa = [re.sub(commentexpr,"",item).strip() for item in aa]
if spacemerge:
aa = [re.sub("[\s\t]+"," ",item).strip() for item in aa if len(item.strip()) <> 0]
else:
aa = [item.strip() for item in aa if len(item.strip()) <> 0]
return aa
@staticmethod
def splitstring(mystr):
"""
Split a string in a list of strings at quote boundaries
Input: String
Output: list of strings
"""
dquote=r'(^[^\"\']*)(\"[^"]*\")(.*)$'
squote=r"(^[^\"\']*)(\'[^']*\')(.*$)"
mystrarr = re.sub(dquote,r"\1\n\2\n\3",re.sub(squote,r"\1\n\2\n\3",mystr)).split("\n")
#remove zerolenght items
mystrarr = [item for item in mystrarr if len(item) <> 0]
if len(mystrarr) > 1:
mystrarr2 = []
for item in mystrarr:
mystrarr2.extend(FortranNamelistIO.splitstring(item))
mystrarr = mystrarr2
return mystrarr
## Do Some testing -------------------------------------------------------
class TestFortranNamelist(TestWEFileIO):
""" Test class for MyFileType class """
test_file = './test/fortran/fortran_namelist.nml'
def test_output_identical(self):
InputFile=FortranNamelistIO(self.test_file)
test_fileout=tempfile.mkstemp()[1]
InputFile.write(test_fileout)
with open(self.test_file, 'r') as f:
data_expected = f.read()
with open(test_fileout, 'r') as f:
data_read = f.read()
try:
self.assertMultiLineEqual(data_read, data_expected)
finally:
os.remove(test_fileout)
def test_duplication(self):
self._test_duplication(FortranNamelistIO, self.test_file)
## Main function ---------------------------------------------------------
if __name__ == '__main__':
""" This is the main fuction that will run the tests automatically
"""
unittest.main()
| Java |
/*!
* Cube Portfolio - Responsive jQuery Grid Plugin
*
* version: 4.1.1-dev (6 April, 2017)
* require: jQuery v1.7+
*
* Copyright 2013-2017, Mihai Buricea (http://scriptpie.com/cubeportfolio/live-preview/)
* Licensed under CodeCanyon License (http://codecanyon.net/licenses)
*
*/
.cbp,
.cbp *,
.cbp-l-filters-alignCenter .cbp-filter-counter:after,
.cbp-l-filters-alignRight .cbp-filter-counter:after,
.cbp-l-filters-button .cbp-filter-counter:after,
.cbp-l-filters-buttonCenter .cbp-filter-counter:after,
.cbp-l-filters-dropdownHeader:after,
.cbp-l-filters-text .cbp-filter-counter:after,
.cbp-popup-loadingBox:after,
.cbp-popup-wrap,
.cbp-popup-wrap *,
.cbp-popup-wrap:before,
.cbp:after {
box-sizing: border-box
}
.cbp-l-grid-agency-desc,
.cbp-l-grid-agency-title,
.cbp-l-grid-blog-title,
.cbp-l-grid-masonry-projects-desc,
.cbp-l-grid-masonry-projects-title,
.cbp-l-grid-projects-desc,
.cbp-l-grid-projects-title,
.cbp-l-grid-work-desc,
.cbp-l-grid-work-title {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis
}
.cbp-l-filters-alignCenter,
.cbp-l-filters-alignCenter *,
.cbp-l-filters-alignLeft,
.cbp-l-filters-alignLeft *,
.cbp-l-filters-alignRight,
.cbp-l-filters-alignRight *,
.cbp-l-filters-big,
.cbp-l-filters-big *,
.cbp-l-filters-button,
.cbp-l-filters-button *,
.cbp-l-filters-buttonCenter,
.cbp-l-filters-buttonCenter *,
.cbp-l-filters-dropdown,
.cbp-l-filters-dropdown *,
.cbp-l-filters-list,
.cbp-l-filters-list *,
.cbp-l-filters-text,
.cbp-l-filters-text *,
.cbp-l-filters-underline,
.cbp-l-filters-underline *,
.cbp-l-filters-work,
.cbp-l-filters-work *,
.cbp-l-loadMore-bgbutton,
.cbp-l-loadMore-bgbutton *,
.cbp-l-loadMore-button,
.cbp-l-loadMore-button *,
.cbp-l-loadMore-text,
.cbp-l-loadMore-text *,
.cbp-search,
.cbp-search * {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-tap-highlight-color: transparent;
box-sizing: border-box
}
.cbp-nav,
.cbp-popup-close,
.cbp-popup-next,
.cbp-popup-prev {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none
}
.cbp-lazyload:after,
.cbp-popup-loadingBox:after,
.cbp-popup-singlePageInline:after,
.cbp:after {
content: '';
position: absolute;
width: 34px;
height: 34px;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
-webkit-animation: cbp-rotation .8s infinite linear;
animation: cbp-rotation .8s infinite linear;
border-left: 3px solid rgba(114, 144, 182, .15);
border-right: 3px solid rgba(114, 144, 182, .15);
border-bottom: 3px solid rgba(114, 144, 182, .15);
border-top: 3px solid rgba(114, 144, 182, .8);
border-radius: 100%
}
.cbp-l-filters-alignCenter .cbp-filter-item:hover .cbp-filter-counter,
.cbp-l-filters-alignRight .cbp-filter-item:hover .cbp-filter-counter,
.cbp-l-filters-buttonCenter .cbp-filter-item:hover .cbp-filter-counter,
.cbp-l-filters-text .cbp-filter-item:hover .cbp-filter-counter {
opacity: 1;
-webkit-transform: translateY(-44px);
transform: translateY(-44px)
}
.cbp-l-filters-alignCenter .cbp-filter-counter,
.cbp-l-filters-alignRight .cbp-filter-counter,
.cbp-l-filters-button .cbp-filter-counter,
.cbp-l-filters-buttonCenter .cbp-filter-counter,
.cbp-l-filters-text .cbp-filter-counter {
font: 400 11px/18px "Open Sans Condensed", sans-serif;
border-radius: 3px;
color: #FFF;
margin: 0 auto;
padding: 4px 0;
text-align: center;
width: 34px;
position: absolute;
bottom: 0;
left: 0;
right: 0;
opacity: 0;
-webkit-transition: -webkit-transform .25s, opacity .25s;
transition: transform .25s, opacity .25s
}
.cbp-l-filters-alignCenter .cbp-filter-counter:after,
.cbp-l-filters-alignRight .cbp-filter-counter:after,
.cbp-l-filters-button .cbp-filter-counter:after,
.cbp-l-filters-buttonCenter .cbp-filter-counter:after,
.cbp-l-filters-text .cbp-filter-counter:after {
content: "";
position: absolute;
bottom: -4px;
left: 0;
right: 0;
margin: 0 auto;
width: 0;
height: 0;
border-left: 4px solid transparent;
border-right: 4px solid transparent
}
.cbp-item {
display: inline-block;
margin: 0 10px 20px 0
}
.cbp {
position: relative;
margin: 0 auto;
z-index: 1;
height: 400px
}
.cbp>* {
visibility: hidden
}
.cbp-popup-ready.cbp-popup-lightbox .cbp-popup-close,
.cbp-popup-ready.cbp-popup-lightbox .cbp-popup-next,
.cbp-popup-ready.cbp-popup-lightbox .cbp-popup-prev,
.cbp-ready>* {
visibility: visible
}
.cbp .cbp-item {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden
}
.cbp img {
display: block;
border: 0;
width: 100%;
height: auto
}
.cbp a,
.cbp a:active,
.cbp a:hover {
text-decoration: none;
outline: 0
}
.cbp-lazyload {
position: relative;
background: #fff;
display: block
}
.cbp-lazyload img {
opacity: 1
}
.cbp-lazyload img[data-cbp-src] {
opacity: 0
}
.cbp-lazyload img:not([data-cbp-src]) {
-webkit-transition: opacity .7s ease-in-out;
transition: opacity .7s ease-in-out
}
.cbp-lazyload:after {
z-index: 0
}
.cbp-wrapper-outer {
overflow: hidden;
position: relative;
margin: 0 auto
}
.cbp-wrapper,
.cbp-wrapper-helper,
.cbp-wrapper-outer {
list-style-type: none;
padding: 0;
width: 100%;
height: 100%;
z-index: 1
}
.cbp-wrapper,
.cbp-wrapper-helper {
margin: 0
}
.cbp-item-off,
.cbp-popup-lightbox .cbp-popup-close,
.cbp-popup-lightbox .cbp-popup-next,
.cbp-popup-lightbox .cbp-popup-prev,
.cbp-ready:after {
visibility: hidden
}
.cbp-ready:after {
display: none
}
.cbp-ready .cbp-item,
.cbp-ready .cbp-wrapper,
.cbp-ready .cbp-wrapper-helper {
position: absolute;
top: 0;
left: 0
}
.cbp-item-off {
z-index: -1;
pointer-events: none
}
.cbp-item-on2off {
z-index: 0
}
.cbp-item-off2on {
z-index: 1
}
.cbp-item-on2on {
z-index: 2
}
.cbp-item-wrapper {
width: 100%;
height: 100%;
position: relative;
top: 0;
left: 0
}
.cbp-l-inline img,
.cbp-l-project-related-wrap img {
display: block;
width: 100%;
height: auto;
border: 0
}
.cbp-updateItems {
-webkit-transition: height .5s ease-in-out!important;
transition: height .5s ease-in-out!important;
will-change: height
}
.cbp-updateItems .cbp-item {
-webkit-transition: top .5s ease-in-out, left .5s ease-in-out;
transition: top .5s ease-in-out, left .5s ease-in-out
}
.cbp-updateItems .cbp-item-loading {
-webkit-animation: fadeIn .5s ease-in-out;
animation: fadeIn .5s ease-in-out;
-webkit-transition: none;
transition: none
}
.cbp-removeItem {
-webkit-animation: fadeOut .5s ease-in-out;
animation: fadeOut .5s ease-in-out
}
.cbp-panel {
width: 94%;
max-width: 1170px;
margin: 0 auto
}
.cbp-misc-video {
position: relative;
height: 0;
padding-bottom: 56.25%;
background: #000;
text-align: center
}
.cbp-misc-video iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%
}
@-webkit-keyframes cbp-rotation {
0% {
-webkit-transform: rotate(0)
}
100% {
-webkit-transform: rotate(360deg)
}
}
@keyframes cbp-rotation {
0% {
transform: rotate(0)
}
100% {
transform: rotate(360deg)
}
}
@-webkit-keyframes fadeOut {
0% {
opacity: 1
}
100% {
opacity: 0
}
}
@keyframes fadeOut {
0% {
opacity: 1
}
100% {
opacity: 0
}
}
.clearfix:after {
content: " ";
display: block;
height: 0;
clear: both
}
.cbp-l-filters-left {
float: left
}
.cbp-l-filters-right {
float: right
}
.cbp-caption,
.cbp-caption-activeWrap,
.cbp-caption-defaultWrap {
display: block
}
.cbp-caption-activeWrap {
background-color: #282727
}
.cbp-caption-active .cbp-caption,
.cbp-caption-active .cbp-caption-activeWrap,
.cbp-caption-active .cbp-caption-defaultWrap {
overflow: hidden;
position: relative;
z-index: 1
}
.cbp-caption-active .cbp-caption-defaultWrap {
top: 0
}
.cbp-caption-active .cbp-caption-activeWrap {
width: 100%;
position: absolute;
z-index: 2;
height: 100%
}
.cbp-l-caption-title {
color: #fff;
font: 400 16px/21px "Open Sans Condensed", sans-serif
}
.cbp-l-caption-desc {
color: #aaa;
font: 400 12px/16px "Open Sans Condensed", sans-serif
}
.cbp-l-caption-text {
font: 400 14px/21px "Open Sans Condensed", sans-serif;
color: #fff;
letter-spacing: 3px;
padding: 0 6px
}
.cbp-l-caption-buttonLeft,
.cbp-l-caption-buttonRight {
background-color: #547EB1;
color: #FFF;
display: inline-block;
font: 400 12px/30px "Open Sans Condensed", sans-serif;
min-width: 90px;
text-align: center;
margin: 4px;
padding: 0 6px
}
.cbp-l-caption-buttonLeft:hover,
.cbp-l-caption-buttonRight:hover {
opacity: .9
}
.cbp-caption-none .cbp-caption-activeWrap {
display: none
}
.cbp-l-caption-alignLeft .cbp-l-caption-body {
padding: 12px 30px
}
.cbp-caption-fadeIn .cbp-l-caption-alignLeft .cbp-l-caption-body,
.cbp-caption-minimal .cbp-l-caption-alignLeft .cbp-l-caption-body,
.cbp-caption-moveRight .cbp-l-caption-alignLeft .cbp-l-caption-body,
.cbp-caption-opacity .cbp-l-caption-alignLeft .cbp-l-caption-body,
.cbp-caption-overlayRightAlong .cbp-l-caption-alignLeft .cbp-l-caption-body,
.cbp-caption-pushDown .cbp-l-caption-alignLeft .cbp-l-caption-body,
.cbp-caption-pushTop .cbp-l-caption-alignLeft .cbp-l-caption-body,
.cbp-caption-revealBottom .cbp-l-caption-alignLeft .cbp-l-caption-body,
.cbp-caption-revealLeft .cbp-l-caption-alignLeft .cbp-l-caption-body,
.cbp-caption-revealTop .cbp-l-caption-alignLeft .cbp-l-caption-body,
.cbp-caption-zoom .cbp-l-caption-alignLeft .cbp-l-caption-body {
padding-top: 30px
}
.cbp-l-caption-alignCenter {
display: table;
width: 100%;
height: 100%
}
.cbp-l-caption-alignCenter .cbp-l-caption-body {
display: table-cell;
vertical-align: middle;
text-align: center;
padding: 0
}
.cbp-l-caption-alignCenter .cbp-l-caption-buttonLeft,
.cbp-l-caption-alignCenter .cbp-l-caption-buttonRight {
position: relative;
-webkit-transition: -webkit-transform .25s;
transition: transform .25s
}
.cbp-caption-overlayBottom .cbp-l-caption-alignCenter .cbp-l-caption-buttonLeft,
.cbp-caption-overlayBottomAlong .cbp-l-caption-alignCenter .cbp-l-caption-buttonLeft,
.cbp-caption-overlayBottomPush .cbp-l-caption-alignCenter .cbp-l-caption-buttonLeft {
-webkit-transform: translateX(-20px);
transform: translateX(-20px)
}
.cbp-caption-overlayBottom .cbp-l-caption-alignCenter .cbp-l-caption-buttonRight,
.cbp-caption-overlayBottomAlong .cbp-l-caption-alignCenter .cbp-l-caption-buttonRight,
.cbp-caption-overlayBottomPush .cbp-l-caption-alignCenter .cbp-l-caption-buttonRight {
-webkit-transform: translateX(20px);
transform: translateX(20px)
}
.cbp-caption:hover .cbp-l-caption-alignCenter .cbp-l-caption-buttonLeft,
.cbp-caption:hover .cbp-l-caption-alignCenter .cbp-l-caption-buttonRight {
-webkit-transform: translateX(0);
transform: translateX(0)
}
@media only screen and (max-width:480px) {
.cbp-l-filters-left,
.cbp-l-filters-right {
width: 100%
}
.cbp-l-caption-alignLeft .cbp-l-caption-body {
padding: 9px 11px
}
.cbp-l-caption-title {
font-size: 14px;
line-height: 21px
}
.cbp-l-caption-desc {
font-size: 11px;
line-height: 14px
}
.cbp-l-caption-buttonLeft,
.cbp-l-caption-buttonRight {
font-size: 11px;
line-height: 28px;
min-width: 69px;
margin: 3px;
padding: 0 4px
}
.cbp-l-caption-text {
font-size: 13px;
letter-spacing: 1px
}
.cbp-l-filters-alignLeft {
text-align: center
}
}
@media only screen and (max-width:374px) {
.cbp-l-caption-alignLeft .cbp-l-caption-body {
padding: 8px 10px
}
.cbp-l-caption-title {
font-size: 13px;
line-height: 20px
}
.cbp-l-caption-desc {
font-size: 11px;
line-height: 14px
}
.cbp-l-caption-buttonLeft,
.cbp-l-caption-buttonRight {
font-size: 10px;
line-height: 28px;
min-width: 62px;
margin: 1px;
padding: 0 4px
}
}
.cbp-caption-fadeIn .cbp-caption-activeWrap {
opacity: 0;
top: 0;
background-color: rgba(0, 0, 0, .85);
-webkit-transition: opacity .5s;
transition: opacity .5s
}
.cbp-caption-fadeIn .cbp-caption:hover .cbp-caption-activeWrap {
opacity: 1
}
.cbp-caption-minimal .cbp-l-caption-desc,
.cbp-caption-minimal .cbp-l-caption-title {
position: relative;
left: 0;
opacity: 0;
-webkit-transition: -webkit-transform .35s ease-out;
transition: transform .35s ease-out
}
.cbp-caption-minimal .cbp-l-caption-title {
-webkit-transform: translateY(-50%);
transform: translateY(-50%)
}
.cbp-caption-minimal .cbp-l-caption-desc {
-webkit-transform: translateY(70%);
transform: translateY(70%)
}
.cbp-caption-minimal .cbp-caption:hover .cbp-l-caption-desc,
.cbp-caption-minimal .cbp-caption:hover .cbp-l-caption-title {
opacity: 1;
-webkit-transform: translateY(0);
transform: translateY(0)
}
.cbp-caption-minimal .cbp-caption-activeWrap {
top: 0;
background-color: #000;
background-color: rgba(0, 0, 0, .8);
opacity: 0
}
.cbp-caption-minimal .cbp-caption:hover .cbp-caption-activeWrap {
opacity: 1
}
.cbp-caption-moveRight .cbp-caption-activeWrap {
left: -100%;
top: 0;
-webkit-transition: -webkit-transform .35s;
transition: transform .35s
}
.cbp-caption-moveRight .cbp-caption:hover .cbp-caption-activeWrap {
-webkit-transform: translateX(100%);
transform: translateX(100%)
}
.cbp-caption-overlayBottom .cbp-caption-activeWrap {
height: 60px;
background-color: #181616;
background-color: rgba(24, 22, 22, .7);
-webkit-transition: -webkit-transform .25s;
transition: transform .25s
}
.cbp-caption-overlayBottom .cbp-caption:hover .cbp-caption-activeWrap {
-webkit-transform: translateY(-100%);
transform: translateY(-100%)
}
.cbp-caption-overlayBottomAlong .cbp-l-caption-alignCenter .cbp-l-caption-buttonLeft,
.cbp-caption-overlayBottomAlong .cbp-l-caption-alignCenter .cbp-l-caption-buttonRight {
-webkit-transition-duration: .35s;
transition-duration: .35s
}
.cbp-caption-overlayBottomAlong .cbp-caption-activeWrap,
.cbp-caption-overlayBottomAlong .cbp-caption-defaultWrap {
-webkit-transition: -webkit-transform .35s;
transition: transform .35s
}
.cbp-caption-overlayBottomAlong .cbp-caption-activeWrap {
height: 60px
}
.cbp-caption-overlayBottomAlong .cbp-caption:hover .cbp-caption-defaultWrap {
-webkit-transform: translateY(-30px);
transform: translateY(-30px)
}
.cbp-caption-overlayBottomAlong .cbp-caption:hover .cbp-caption-activeWrap {
-webkit-transform: translateY(-100%);
transform: translateY(-100%)
}
.cbp-caption-overlayBottomPush .cbp-caption-activeWrap,
.cbp-caption-overlayBottomPush .cbp-caption-defaultWrap {
-webkit-transition: -webkit-transform .25s;
transition: transform .25s
}
.cbp-caption-overlayBottomPush .cbp-caption-activeWrap {
height: 61px;
-webkit-transform: translateY(0);
transform: translateY(0)
}
.cbp-caption-overlayBottomPush .cbp-caption:hover .cbp-caption-defaultWrap {
-webkit-transform: translateY(-60px);
transform: translateY(-60px)
}
.cbp-caption-overlayBottomPush .cbp-caption:hover .cbp-caption-activeWrap {
-webkit-transform: translateY(-61px);
transform: translateY(-61px)
}
.cbp-caption-overlayBottomReveal .cbp-caption-defaultWrap {
z-index: 2;
-webkit-transition: -webkit-transform .25s;
transition: transform .25s
}
.cbp-caption-overlayBottomReveal .cbp-caption-activeWrap {
bottom: 0;
z-index: 1;
height: 47px
}
.cbp-caption-overlayBottomReveal .cbp-caption:hover .cbp-caption-defaultWrap {
-webkit-transform: translateY(-47px);
transform: translateY(-47px)
}
.cbp-caption-overlayRightAlong .cbp-caption-activeWrap,
.cbp-caption-overlayRightAlong .cbp-caption-defaultWrap {
-webkit-transition: -webkit-transform .4s;
transition: transform .4s
}
.cbp-caption-overlayRightAlong .cbp-caption-activeWrap {
top: 0;
left: -50%;
width: 50%
}
.cbp-caption-overlayRightAlong .cbp-caption:hover .cbp-caption-defaultWrap {
-webkit-transform: translateX(25%);
transform: translateX(25%)
}
.cbp-caption-overlayRightAlong .cbp-caption:hover .cbp-caption-activeWrap {
-webkit-transform: translateX(100%);
transform: translateX(100%)
}
.cbp-caption-pushDown .cbp-caption-activeWrap,
.cbp-caption-pushDown .cbp-caption-defaultWrap {
-webkit-transition: -webkit-transform .4s;
transition: transform .4s
}
.cbp-caption-pushDown .cbp-caption-activeWrap {
top: -100%
}
.cbp-caption-pushDown .cbp-caption:hover .cbp-caption-activeWrap,
.cbp-caption-pushDown .cbp-caption:hover .cbp-caption-defaultWrap {
-webkit-transform: translateY(100%);
transform: translateY(100%)
}
.cbp-caption-pushTop .cbp-caption-activeWrap,
.cbp-caption-pushTop .cbp-caption-defaultWrap {
-webkit-transition: -webkit-transform .4s;
transition: transform .4s
}
.cbp-caption-pushTop .cbp-caption-activeWrap {
height: 102%
}
.cbp-caption-pushTop .cbp-caption:hover .cbp-caption-defaultWrap {
-webkit-transform: translateY(-100%);
transform: translateY(-100%)
}
.cbp-caption-pushTop .cbp-caption:hover .cbp-caption-activeWrap {
-webkit-transform: translateY(-99%);
transform: translateY(-99%)
}
.cbp-caption-revealBottom .cbp-caption-defaultWrap {
z-index: 2;
-webkit-transition: -webkit-transform .4s;
transition: transform .4s
}
.cbp-caption-revealBottom .cbp-caption-activeWrap {
top: 0;
z-index: 1
}
.cbp-caption-revealBottom .cbp-caption:hover .cbp-caption-defaultWrap {
-webkit-transform: translateY(-100%);
transform: translateY(-100%)
}
.cbp-caption-revealLeft .cbp-caption-activeWrap {
left: 100%;
top: 0;
-webkit-transition: -webkit-transform .4s;
transition: transform .4s
}
.cbp-caption-revealLeft .cbp-caption:hover .cbp-caption-activeWrap {
-webkit-transform: translateX(-100%);
transform: translateX(-100%)
}
.cbp-caption-revealTop .cbp-caption-defaultWrap {
z-index: 2;
-webkit-transition: -webkit-transform .4s;
transition: transform .4s
}
.cbp-caption-revealTop .cbp-caption-activeWrap {
top: 0;
z-index: 1
}
.cbp-caption-revealTop .cbp-caption:hover .cbp-caption-defaultWrap {
-webkit-transform: translateY(100%);
transform: translateY(100%)
}
.cbp-caption-zoom .cbp-caption-defaultWrap {
-webkit-transition: -webkit-transform .35s ease-out;
transition: transform .35s ease-out
}
.cbp-caption-zoom .cbp-caption:hover .cbp-caption-defaultWrap {
-webkit-transform: scale(1.25);
transform: scale(1.25)
}
.cbp-caption-zoom .cbp-caption-activeWrap {
opacity: 0;
top: 0;
background-color: rgba(0, 0, 0, .9);
-webkit-transition: opacity .4s;
transition: opacity .4s
}
.cbp-caption-zoom .cbp-caption:hover .cbp-caption-activeWrap {
opacity: 1
}
.cbp-caption-opacity .cbp-item {
padding: 1px
}
.cbp-caption-opacity .cbp-caption,
.cbp-caption-opacity .cbp-caption-activeWrap,
.cbp-caption-opacity .cbp-caption-defaultWrap {
background-color: transparent
}
.cbp-caption-opacity .cbp-caption {
border: 1px solid transparent
}
.cbp-caption-opacity .cbp-caption:hover {
border-color: #EDEDED
}
.cbp-caption-opacity .cbp-caption-defaultWrap {
opacity: 1;
-webkit-transition: opacity .4s;
transition: opacity .4s
}
.cbp-caption-opacity .cbp-caption:hover .cbp-caption-defaultWrap {
opacity: .8
}
.cbp-caption-opacity .cbp-caption:hover .cbp-caption-activeWrap {
top: 0
}
.cbp-caption-expand .cbp-caption-activeWrap {
height: auto;
background-color: transparent
}
.cbp-caption-expand .cbp-caption {
border-bottom: 1px dotted #eaeaea
}
.cbp-caption-expand .cbp-caption-defaultWrap {
cursor: pointer;
font: 500 16px/23px 'Open Sans Condensed', sans-serif;
color: #474747;
padding: 12px 0 11px 26px
}
.cbp-caption-expand .cbp-caption-defaultWrap svg {
position: absolute;
top: 16px;
left: 0
}
.cbp-l-caption-body a {
font: 400 14px/21px 'Open Sans Condensed', sans-serif
}
.cbp-caption-expand .cbp-l-caption-body {
font: 400 13px/21px 'Open Sans Condensed', sans-serif;
color: #888;
padding: 0 0 20px 26px
}
.cbp-caption-expand-active {
-webkit-transition: height .4s!important;
transition: height .4s!important
}
.cbp-caption-expand-active .cbp-item {
-webkit-transition: left .4s, top .4s!important;
transition: left .4s, top .4s!important
}
.cbp-caption-expand-open .cbp-caption-activeWrap {
-webkit-transition: height .4s;
transition: height .4s
}
.cbp-l-filters-alignCenter {
margin-bottom: 30px;
text-align: center;
font: 400 12px/21px sans-serif;
color: #DADADA
}
.cbp-l-filters-alignCenter .cbp-filter-item {
color: #949494;
cursor: pointer;
font: 400 13px/21px 'Open Sans Condensed', sans-serif;
padding: 0 12px;
position: relative;
overflow: visible;
margin: 0 0 10px;
display: inline-block;
-webkit-transition: color .3s ease-in-out;
transition: color .3s ease-in-out
}
.cbp-l-filters-alignCenter .cbp-filter-item:hover {
color: #2D2C2C
}
.cbp-l-filters-alignCenter .cbp-filter-item:hover .cbp-filter-counter {
-webkit-transform: translateY(-30px);
transform: translateY(-30px)
}
.cbp-l-filters-alignCenter .cbp-filter-item.cbp-filter-item-active {
color: #2D2C2C;
cursor: default
}
.cbp-l-filters-alignCenter .cbp-filter-counter {
font: 400 11px/18px 'Open Sans Condensed', sans-serif;
background-color: #626161
}
.cbp-l-filters-alignCenter .cbp-filter-counter:after {
border-top: 4px solid #626161
}
.cbp-l-filters-alignLeft {
margin-bottom: 30px
}
.cbp-l-filters-alignLeft .cbp-filter-item {
background-color: #fff;
border: 1px solid #cdcdcd;
cursor: pointer;
font: 400 12px/30px 'Open Sans Condensed', sans-serif;
padding: 0 13px;
position: relative;
overflow: visible;
margin: 0 4px 10px;
display: inline-block;
color: #888;
-webkit-transition: color .3s ease-in-out, background-color .3s ease-in-out, border .3s ease-in-out;
transition: color .3s ease-in-out, background-color .3s ease-in-out, border .3s ease-in-out
}
.cbp-l-filters-alignLeft .cbp-filter-item:hover {
color: #111
}
.cbp-l-filters-alignLeft .cbp-filter-item.cbp-filter-item-active {
background-color: #6C7A89;
border: 1px solid #6C7A89;
color: #fff;
cursor: default
}
.cbp-l-filters-alignLeft .cbp-filter-item:first-child {
margin-left: 0
}
.cbp-l-filters-alignLeft .cbp-filter-item:last-child {
margin-right: 0
}
.cbp-l-filters-alignLeft .cbp-filter-counter {
display: inline
}
.cbp-l-filters-alignRight {
margin-bottom: 30px;
text-align: right
}
.cbp-l-filters-alignRight .cbp-filter-item {
background-color: transparent;
color: #8B8B8B;
cursor: pointer;
font: 400 11px/31px "Open Sans Condensed", sans-serif;
padding: 0 14px;
position: relative;
overflow: visible;
margin: 0 3px 10px;
border: 1px solid #E4E2E2;
text-transform: uppercase;
display: inline-block;
-webkit-transition: color .3s ease-in-out, background-color .3s ease-in-out, border .3s ease-in-out;
transition: color .3s ease-in-out, background-color .3s ease-in-out, border .3s ease-in-out
}
.cbp-l-filters-alignRight .cbp-filter-item:hover {
color: #2B3444
}
.cbp-l-filters-alignRight .cbp-filter-item.cbp-filter-item-active {
color: #FFF;
background-color: #049372;
border-color: #049372;
cursor: default
}
.cbp-l-filters-alignRight .cbp-filter-item:first-child {
margin-left: 0
}
.cbp-l-filters-alignRight .cbp-filter-item:last-child {
margin-right: 0
}
.cbp-l-filters-alignRight .cbp-filter-counter {
background-color: #049372
}
.cbp-l-filters-alignRight .cbp-filter-counter:after {
border-top: 4px solid #049372
}
.cbp-l-filters-button {
margin-bottom: 30px
}
.cbp-l-filters-button .cbp-filter-item:hover .cbp-filter-counter:after {
display: block
}
.cbp-l-filters-button .cbp-filter-item:hover .cbp-filter-counter {
bottom: 44px;
-ms-filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=100);
opacity: 1
}
.cbp-l-filters-button .cbp-filter-counter {
background-color: #545454
}
.cbp-l-filters-button .cbp-filter-counter:after {
border-top: 4px solid #545454
}
@media only screen and (max-width:480px) {
.cbp-l-filters-alignRight,
.cbp-l-filters-button {
text-align: center
}
}
.cbp-l-filters-buttonCenter {
margin-bottom: 30px;
text-align: center
}
.cbp-l-filters-buttonCenter .cbp-filter-item {
background-color: #FFF;
border: 1px solid #ECECEC;
color: #888;
cursor: pointer;
font: 400 12px/32px 'Open Sans Condensed', sans-serif;
margin: 0 10px 10px 0;
overflow: visible;
padding: 0 17px;
position: relative;
display: inline-block;
-webkit-transition: color .3s ease-in-out, border-color .3s ease-in-out;
transition: color .3s ease-in-out, border-color .3s ease-in-out
}
.cbp-l-filters-buttonCenter .cbp-filter-item:hover {
color: #5d5d5d
}
.cbp-l-filters-buttonCenter .cbp-filter-item.cbp-filter-item-active {
color: #3B9CB3;
border-color: #8CD2E5;
cursor: default
}
.cbp-l-filters-buttonCenter .cbp-filter-item:first-child {
margin-left: 0
}
.cbp-l-filters-buttonCenter .cbp-filter-item:last-child {
margin-right: 0
}
.cbp-l-filters-buttonCenter .cbp-filter-counter {
font: 400 11px/18px 'Open Sans Condensed', sans-serif;
background-color: #68ABBC
}
.cbp-l-filters-buttonCenter .cbp-filter-counter:after {
border-top: 4px solid #68ABBC
}
.cbp-l-filters-dropdown {
margin-bottom: 40px;
height: 38px;
position: relative;
z-index: 5
}
.cbp-l-filters-dropdownWrap {
width: 200px;
position: absolute;
right: 0;
background: #4d4c4d
}
.cbp-l-filters-dropdownHeader {
font: 400 12px/38px "Open Sans Condensed", sans-serif;
margin: 0 17px;
color: #FFF;
cursor: default;
position: relative
}
.cbp-l-filters-dropdownHeader:after {
border-color: #fff transparent;
border-style: solid;
border-width: 5px 5px 0;
content: "";
height: 0;
position: absolute;
right: 0;
top: 50%;
width: 0;
margin-top: -1px
}
.cbp-l-filters-dropdownWrap.cbp-l-filters-dropdownWrap-open .cbp-l-filters-dropdownHeader:after {
border-width: 0 5px 5px
}
.cbp-l-filters-dropdownList {
display: none;
list-style: none;
margin: 0;
padding: 0
}
.cbp-l-filters-dropdownList>li {
margin: 0;
list-style: none
}
.cbp-l-filters-dropdownWrap.cbp-l-filters-dropdownWrap-open .cbp-l-filters-dropdownList {
display: block;
margin: 0
}
.cbp-l-filters-dropdownList .cbp-filter-item {
background: 0 0;
color: #b3b3b3;
width: 100%;
text-align: left;
font: 400 12px/40px "Open Sans Condensed", sans-serif;
margin: 0;
padding: 0 17px;
cursor: pointer;
border: none;
border-top: 1px solid #595959
}
.cbp-l-filters-dropdownList .cbp-filter-item:hover {
color: #e6e6e6
}
.cbp-l-filters-dropdownList .cbp-filter-item-active {
color: #fff;
cursor: default
}
.cbp-l-filters-dropdownWrap .cbp-filter-counter {
display: inline
}
.cbp-l-filters-dropdown-floated {
float: right;
margin-top: -2px;
margin-left: 20px;
width: 200px
}
@media only screen and (max-width:480px) {
.cbp-l-filters-dropdown-floated {
width: 100%;
margin-top: 0;
margin-left: 0
}
.cbp-l-filters-dropdownWrap {
right: 0;
left: 0;
margin: 0 auto
}
}
.cbp-l-filters-list {
margin-bottom: 30px;
content: "";
display: table;
clear: both
}
.cbp-l-filters-list .cbp-filter-item {
background-color: transparent;
color: #585252;
cursor: pointer;
font: 400 12px/35px "Open Sans Condensed", sans-serif;
padding: 0 18px;
position: relative;
overflow: visible;
margin: 0 0 10px;
float: left;
border: 1px solid #3288C4;
border-right-width: 0;
-webkit-transition: left .3s ease-in-out;
transition: left .3s ease-in-out
}
.cbp-l-filters-list .cbp-filter-item:hover {
color: #000
}
.cbp-l-filters-list .cbp-filter-item.cbp-filter-item-active {
cursor: default;
color: #FFF;
background-color: #3288C4
}
.cbp-l-filters-list-first {
border-radius: 6px 0 0 6px
}
.cbp-l-filters-list-last {
border-radius: 0 6px 6px 0;
border-right-width: 1px!important
}
.cbp-l-filters-list .cbp-filter-counter {
display: inline
}
@media only screen and (max-width:600px) {
.cbp-l-filters-list .cbp-filter-item {
margin-right: 5px;
border-radius: 6px;
border-right-width: 1px
}
}
.cbp-l-filters-work {
margin-bottom: 30px;
text-align: center
}
.cbp-l-filters-work .cbp-filter-item {
background-color: #FFF;
color: #888;
cursor: pointer;
font: 600 11px/37px "Open Sans Condensed", sans-serif;
margin: 0 5px 10px 0;
overflow: visible;
padding: 0 16px;
position: relative;
display: inline-block;
text-transform: uppercase;
-webkit-transition: color .3s ease-in-out, background-color .3s ease-in-out;
transition: color .3s ease-in-out, background-color .3s ease-in-out
}
.cbp-l-filters-work .cbp-filter-item:hover {
color: #fff;
background: #607D8B
}
.cbp-l-filters-work .cbp-filter-item.cbp-filter-item-active {
background-color: #607D8B;
color: #fff;
cursor: default
}
.cbp-l-filters-work .cbp-filter-item:first-child {
margin-left: 0
}
.cbp-l-filters-work .cbp-filter-item:last-child {
margin-right: 0
}
.cbp-l-filters-work .cbp-filter-counter {
font: 600 11px/37px "Open Sans Condensed", sans-serif;
text-align: center;
display: inline-block;
margin-left: 8px
}
.cbp-l-filters-work .cbp-filter-counter:before {
content: '('
}
.cbp-l-filters-work .cbp-filter-counter:after {
content: ')'
}
.cbp-l-filters-big {
margin-bottom: 30px;
text-align: center
}
.cbp-l-filters-big .cbp-filter-item {
color: #444;
cursor: pointer;
font: 400 15px/22px Roboto, sans-serif;
margin: 0 8px 10px;
padding: 10px 23px;
position: relative;
display: inline-block;
border: 1px solid transparent;
text-transform: uppercase;
-webkit-transition: color .3s ease-in-out, border .3s ease-in-out;
transition: color .3s ease-in-out, border .3s ease-in-out
}
.cbp-l-filters-big .cbp-filter-item:hover {
color: #888
}
.cbp-l-filters-big .cbp-filter-item.cbp-filter-item-active {
border-color: #d5d5d5;
color: #444;
cursor: default
}
.cbp-l-filters-big .cbp-filter-item:first-child {
margin-left: 0
}
.cbp-l-filters-big .cbp-filter-item:last-child {
margin-right: 0
}
.cbp-l-filters-text {
margin-bottom: 30px;
text-align: center;
font: 400 12px/21px Lato, sans-serif;
color: #DADADA;
padding: 0 15px
}
.cbp-l-filters-text .cbp-filter-item {
color: #949494;
cursor: pointer;
font: 400 13px/21px Lato, sans-serif;
padding: 0 12px;
position: relative;
overflow: visible;
margin: 0 0 10px;
display: inline-block;
-webkit-transition: color .3s ease-in-out;
transition: color .3s ease-in-out
}
.cbp-l-filters-text .cbp-filter-item:hover {
color: #2D2C2C
}
.cbp-l-filters-text .cbp-filter-item:hover .cbp-filter-counter {
-webkit-transform: translateY(-30px);
transform: translateY(-30px)
}
.cbp-l-filters-text .cbp-filter-item.cbp-filter-item-active {
color: #2D2C2C;
cursor: default
}
.cbp-l-filters-text .cbp-filter-counter {
background-color: #626161;
font: 400 11px/18px Lato, sans-serif
}
.cbp-l-filters-text .cbp-filter-counter:after {
border-top: 4px solid #626161
}
.cbp-l-filters-text-sort {
display: inline-block;
font: 400 13px/21px Lato, sans-serif;
color: #949494;
margin-right: 15px
}
@media only screen and (max-width:480px) {
.cbp-l-filters-text-sort {
display: block;
margin-bottom: 10px
}
.cbp-l-filters-underline {
text-align: center
}
}
.cbp-l-filters-underline {
margin-bottom: 30px
}
.cbp-l-filters-underline .cbp-filter-item {
border-bottom: 3px solid transparent;
cursor: pointer;
font: 600 14px/21px "Open Sans Condensed", sans-serif;
padding: 8px 10px;
position: relative;
overflow: visible;
margin: 0 20px 10px 0;
display: inline-block;
color: #787878;
-webkit-transition: color .25s ease-in-out, border-color .25s ease-in-out;
transition: color .25s ease-in-out, border-color .25s ease-in-out
}
.cbp-l-filters-underline .cbp-filter-item:hover {
color: #111
}
.cbp-l-filters-underline .cbp-filter-item.cbp-filter-item-active {
border-bottom-color: #666;
color: #444;
cursor: default
}
.cbp-popup-lightbox-counter,
.cbp-popup-lightbox-title {
font: 400 12px/18px "Open Sans Condensed", sans-serif;
color: #eee
}
.cbp-l-filters-underline .cbp-filter-item:first-child {
margin-left: 0
}
.cbp-l-filters-underline .cbp-filter-item:last-child {
margin-right: 0
}
.cbp-l-filters-underline .cbp-filter-counter {
display: inline
}
.cbp-animation-quicksand {
-webkit-transition: height .6s ease-in-out;
transition: height .6s ease-in-out;
will-change: height
}
.cbp-animation-quicksand .cbp-item {
-webkit-transition: -webkit-transform .6s ease-in-out;
transition: transform .6s ease-in-out;
-webkit-perspective: 1000px;
perspective: 1000px
}
.cbp-animation-quicksand .cbp-item-wrapper {
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d
}
.cbp-animation-quicksand .cbp-item-on2off .cbp-item-wrapper {
-webkit-animation: quicksand-off .6s ease-out both;
animation: quicksand-off .6s ease-out both
}
.cbp-animation-quicksand .cbp-item-off2on .cbp-item-wrapper {
-webkit-animation: quicksand-on .6s ease-out both;
animation: quicksand-on .6s ease-out both
}
@-webkit-keyframes quicksand-off {
100% {
opacity: 0;
-webkit-transform: scale3d(0, 0, 0)
}
}
@keyframes quicksand-off {
100% {
opacity: 0;
transform: scale3d(0, 0, 0)
}
}
@-webkit-keyframes quicksand-on {
0% {
opacity: 0;
-webkit-transform: scale3d(0, 0, 0)
}
}
@keyframes quicksand-on {
0% {
opacity: 0;
transform: scale3d(0, 0, 0)
}
}
.cbp-animation-boxShadow,
.cbp-animation-fadeOut {
-webkit-transition: height .6s ease-in-out;
transition: height .6s ease-in-out;
will-change: height
}
.cbp-animation-boxShadow .cbp-item,
.cbp-animation-fadeOut .cbp-item {
-webkit-transition: -webkit-transform .6s ease-in-out;
transition: transform .6s ease-in-out;
-webkit-perspective: 1000px;
perspective: 1000px
}
.cbp-animation-boxShadow .cbp-item-wrapper,
.cbp-animation-fadeOut .cbp-item-wrapper {
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d
}
.cbp-animation-boxShadow .cbp-item-on2off .cbp-item-wrapper,
.cbp-animation-fadeOut .cbp-item-on2off .cbp-item-wrapper {
-webkit-animation: fadeOut-off .6s ease-in-out both;
animation: fadeOut-off .6s ease-in-out both
}
.cbp-animation-boxShadow .cbp-item-off2on .cbp-item-wrapper,
.cbp-animation-fadeOut .cbp-item-off2on .cbp-item-wrapper {
-webkit-animation: fadeOut-on .6s ease-in-out both;
animation: fadeOut-on .6s ease-in-out both
}
@-webkit-keyframes fadeOut-off {
0% {
opacity: 1
}
100%,
80% {
opacity: 0
}
}
@keyframes fadeOut-off {
0% {
opacity: 1
}
100%,
80% {
opacity: 0
}
}
@-webkit-keyframes fadeOut-on {
0% {
opacity: 0
}
100% {
opacity: 1
}
}
@keyframes fadeOut-on {
0% {
opacity: 0
}
100% {
opacity: 1
}
}
.cbp-animation-flipOut {
-webkit-transition: height .7s ease-in-out;
transition: height .7s ease-in-out;
will-change: height
}
.cbp-animation-flipOut .cbp-item {
-webkit-transition: -webkit-transform .7s ease-in-out;
transition: transform .7s ease-in-out;
-webkit-perspective: 1000px;
perspective: 1000px
}
.cbp-animation-flipOut .cbp-item-wrapper {
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d
}
.cbp-animation-flipOut .cbp-item-on2off .cbp-item-wrapper {
-webkit-animation: flipOut-out .7s both ease-in;
animation: flipOut-out .7s both ease-in
}
.cbp-animation-flipOut .cbp-item-off2on .cbp-item-wrapper {
-webkit-animation: flipOut-in .7s ease-out both;
animation: flipOut-in .7s ease-out both
}
@-webkit-keyframes flipOut-out {
100%,
50% {
-webkit-transform: translateZ(-1000px) rotateY(-90deg);
opacity: .2
}
}
@keyframes flipOut-out {
100%,
50% {
transform: translateZ(-1000px) rotateY(-90deg);
opacity: .2
}
}
@-webkit-keyframes flipOut-in {
0%,
50% {
-webkit-transform: translateZ(-1000px) rotateY(90deg);
opacity: .2
}
}
@keyframes flipOut-in {
0%,
50% {
transform: translateZ(-1000px) rotateY(90deg);
opacity: .2
}
}
.cbp-animation-flipBottom {
-webkit-transition: height .7s ease-in-out;
transition: height .7s ease-in-out;
will-change: height
}
.cbp-animation-flipBottom .cbp-item {
-webkit-transition: -webkit-transform .7s ease-in-out;
transition: transform .7s ease-in-out;
-webkit-perspective: 1000px;
perspective: 1000px
}
.cbp-animation-flipBottom .cbp-item-wrapper {
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d
}
.cbp-animation-flipBottom .cbp-item-on2off .cbp-item-wrapper {
-webkit-animation: flipBottom-out .7s both ease-in;
animation: flipBottom-out .7s both ease-in
}
.cbp-animation-flipBottom .cbp-item-off2on .cbp-item-wrapper {
-webkit-animation: flipBottom-in .7s ease-out both;
animation: flipBottom-in .7s ease-out both
}
@-webkit-keyframes flipBottom-out {
100%,
50% {
-webkit-transform: translateZ(-1000px) rotateX(-90deg);
opacity: .2
}
}
@keyframes flipBottom-out {
100%,
50% {
transform: translateZ(-1000px) rotateX(-90deg);
opacity: .2
}
}
@-webkit-keyframes flipBottom-in {
0%,
50% {
-webkit-transform: translateZ(-1000px) rotateX(90deg);
opacity: .2
}
}
@keyframes flipBottom-in {
0%,
50% {
transform: translateZ(-1000px) rotateX(90deg);
opacity: .2
}
}
.cbp-animation-scaleSides {
-webkit-transition: height .6s ease-in-out;
transition: height .6s ease-in-out;
will-change: height
}
.cbp-animation-scaleSides .cbp-item {
-webkit-transition: -webkit-transform .6s ease-in-out;
transition: transform .6s ease-in-out;
-webkit-perspective: 1000px;
perspective: 1000px
}
.cbp-animation-fadeOutTop,
.cbp-animation-skew {
-webkit-transition: height .6s ease-in-out;
will-change: height
}
.cbp-animation-scaleSides .cbp-item-wrapper {
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d
}
.cbp-animation-scaleSides .cbp-item-on2off .cbp-item-wrapper {
-webkit-animation: scaleSides-out .9s both;
animation: scaleSides-out .9s both
}
.cbp-animation-scaleSides .cbp-item-off2on .cbp-item-wrapper {
-webkit-animation: scaleSides-in .9s both;
animation: scaleSides-in .9s both
}
@-webkit-keyframes scaleSides-out {
100%,
50% {
-webkit-transform: scale(.6);
opacity: 0
}
}
@keyframes scaleSides-out {
100%,
50% {
transform: scale(.6);
opacity: 0
}
}
@-webkit-keyframes scaleSides-in {
0%,
50% {
-webkit-transform: scale(.6);
opacity: 0
}
}
@keyframes scaleSides-in {
0%,
50% {
transform: scale(.6);
opacity: 0
}
}
.cbp-animation-skew {
transition: height .6s ease-in-out
}
.cbp-animation-skew .cbp-item {
-webkit-transition: -webkit-transform .6s ease-in-out;
transition: transform .6s ease-in-out;
-webkit-perspective: 1000px;
perspective: 1000px
}
.cbp-animation-skew .cbp-item-wrapper {
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d
}
.cbp-animation-skew .cbp-item-on2off .cbp-item-wrapper {
-webkit-animation: skew-off .6s ease-out both;
animation: skew-off .6s ease-out both
}
.cbp-animation-skew .cbp-item-off2on .cbp-item-wrapper {
-webkit-animation: skew-on .6s ease-out both;
animation: skew-on .6s ease-out both
}
@-webkit-keyframes skew-off {
100% {
opacity: 0;
-webkit-transform: scale3d(0, 0, 0) skew(20deg, 0)
}
}
@keyframes skew-off {
100% {
opacity: 0;
transform: scale3d(0, 0, 0) skew(20deg, 0)
}
}
@-webkit-keyframes skew-on {
0% {
opacity: 0;
-webkit-transform: scale3d(0, 0, 0) skew(0, 20deg)
}
}
@keyframes skew-on {
0% {
opacity: 0;
transform: scale3d(0, 0, 0) skew(0, 20deg)
}
}
.cbp-animation-fadeOutTop {
transition: height .6s ease-in-out
}
.cbp-animation-sequentially,
.cbp-animation-slideLeft {
-webkit-transition: height .6s ease-in-out;
will-change: height;
transition: height .6s ease-in-out
}
.cbp-animation-fadeOutTop .cbp-wrapper-outer {
overflow: visible
}
.cbp-animation-fadeOutTop .cbp-item {
-webkit-perspective: 1000px;
perspective: 1000px;
overflow: visible
}
.cbp-animation-fadeOutTop .cbp-item-wrapper {
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d
}
.cbp-animation-fadeOutTop .cbp-wrapper-helper .cbp-item-wrapper {
-webkit-animation: fadeOutTop-out .6s both ease-in-out;
animation: fadeOutTop-out .6s both ease-in-out
}
.cbp-animation-fadeOutTop .cbp-wrapper .cbp-item-wrapper {
-webkit-animation: fadeOutTop-in .6s both ease-in-out;
animation: fadeOutTop-in .6s both ease-in-out
}
@-webkit-keyframes fadeOutTop-out {
0% {
-webkit-transform: translateY(0);
opacity: 1
}
100%,
50% {
-webkit-transform: translateY(-30px);
opacity: 0
}
}
@keyframes fadeOutTop-out {
0% {
transform: translateY(0);
opacity: 1
}
100%,
50% {
transform: translateY(-30px);
opacity: 0
}
}
@-webkit-keyframes fadeOutTop-in {
0%,
50% {
-webkit-transform: translateY(-30px);
opacity: 0
}
100% {
-webkit-transform: translateY(0);
opacity: 1
}
}
@keyframes fadeOutTop-in {
0%,
50% {
transform: translateY(-30px);
opacity: 0
}
100% {
transform: translateY(0);
opacity: 1
}
}
.cbp-animation-slideLeft .cbp-item {
-webkit-perspective: 1000px;
perspective: 1000px
}
.cbp-animation-slideLeft .cbp-item-wrapper {
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d
}
.cbp-animation-slideLeft .cbp-wrapper-helper .cbp-item-wrapper {
-webkit-animation: slideLeft-out .8s both ease-in-out;
animation: slideLeft-out .8s both ease-in-out
}
.cbp-animation-slideLeft .cbp-wrapper .cbp-item-wrapper {
-webkit-animation: slideLeft-in .8s both ease-in-out;
animation: slideLeft-in .8s both ease-in-out
}
@-webkit-keyframes slideLeft-out {
0% {
opacity: 1;
transform: scale(1)
}
25% {
opacity: .75;
-webkit-transform: scale(.8)
}
100%,
75% {
opacity: .75;
-webkit-transform: scale(.8) translateX(-200%)
}
}
@keyframes slideLeft-out {
0% {
opacity: 1;
transform: scale(1)
}
25% {
opacity: .75;
transform: scale(.8)
}
100%,
75% {
opacity: .75;
transform: scale(.8) translateX(-200%)
}
}
@-webkit-keyframes slideLeft-in {
0%,
25% {
opacity: .75;
-webkit-transform: scale(.8) translateX(200%)
}
75% {
opacity: .75;
-webkit-transform: scale(.8)
}
100% {
opacity: 1;
-webkit-transform: scale(1) translateX(0)
}
}
@keyframes slideLeft-in {
0%,
25% {
opacity: .75;
transform: scale(.8) translateX(200%)
}
75% {
opacity: .75;
transform: scale(.8)
}
100% {
opacity: 1;
transform: scale(1) translateX(0)
}
}
.cbp-animation-3dflip,
.cbp-animation-flipOutDelay {
-webkit-transition: height .6s ease-in-out;
will-change: height
}
.cbp-animation-sequentially .cbp-wrapper-outer {
overflow: visible
}
.cbp-animation-sequentially .cbp-item {
-webkit-perspective: 1000px;
perspective: 1000px;
overflow: visible
}
.cbp-animation-sequentially .cbp-item-wrapper {
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d
}
.cbp-animation-sequentially .cbp-wrapper-helper .cbp-item-wrapper {
-webkit-animation: fadeOutTop-out .6s both ease;
animation: fadeOutTop-out .6s both ease
}
.cbp-animation-sequentially .cbp-wrapper .cbp-item-wrapper {
-webkit-animation: fadeOutTop-in .6s both ease-out;
animation: fadeOutTop-in .6s both ease-out
}
.cbp-animation-3dflip {
transition: height .6s ease-in-out
}
.cbp-animation-3dflip .cbp-item {
-webkit-perspective: 1000px;
perspective: 1000px
}
.cbp-animation-3dflip .cbp-item-wrapper {
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d
}
.cbp-animation-3dflip .cbp-wrapper-helper .cbp-item-wrapper {
-webkit-transform-origin: 0 50%;
transform-origin: 0 50%;
-webkit-animation: flip-out .6s both ease-in-out;
animation: flip-out .6s both ease-in-out
}
.cbp-animation-3dflip .cbp-wrapper .cbp-item-wrapper {
-webkit-transform-origin: 100% 50%;
transform-origin: 100% 50%;
-webkit-animation: flip-in .6s both ease-in-out;
animation: flip-in .6s both ease-in-out
}
@-webkit-keyframes flip-out {
100% {
opacity: 0;
-webkit-transform: rotateY(90deg)
}
}
@keyframes flip-out {
100% {
opacity: 0;
transform: rotateY(90deg)
}
}
@-webkit-keyframes flip-in {
0% {
opacity: 0;
-webkit-transform: rotateY(-90deg)
}
100% {
opacity: 1;
-webkit-transform: rotateY(0)
}
}
@keyframes flip-in {
0% {
opacity: 0;
transform: rotateY(-90deg)
}
100% {
opacity: 1;
transform: rotateY(0)
}
}
.cbp-animation-flipOutDelay {
transition: height .6s ease-in-out
}
.cbp-animation-rotateSides,
.cbp-animation-slideDelay {
-webkit-transition: height .6s ease-in-out;
will-change: height;
transition: height .6s ease-in-out
}
.cbp-animation-flipOutDelay .cbp-item {
-webkit-perspective: 1000px;
perspective: 1000px
}
.cbp-animation-flipOutDelay .cbp-item-wrapper {
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d
}
.cbp-animation-flipOutDelay .cbp-wrapper-helper .cbp-item-wrapper {
-webkit-animation: flipOut-out 1s both ease-in;
animation: flipOut-out 1s both ease-in
}
.cbp-animation-flipOutDelay .cbp-wrapper .cbp-item-wrapper {
-webkit-animation: flipOut-in 1s both ease-out;
animation: flipOut-in 1s both ease-out
}
.cbp-animation-slideDelay .cbp-item {
-webkit-perspective: 1000px;
perspective: 1000px
}
.cbp-animation-slideDelay .cbp-item-wrapper {
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d
}
.cbp-animation-slideDelay .cbp-wrapper-helper .cbp-item-wrapper {
-webkit-animation: slideDelay-out .5s both ease-in-out;
animation: slideDelay-out .5s both ease-in-out
}
.cbp-animation-slideDelay .cbp-wrapper .cbp-item-wrapper {
-webkit-animation: slideDelay-in .5s both ease-in-out;
animation: slideDelay-in .5s both ease-in-out
}
@-webkit-keyframes slideDelay-out {
100% {
-webkit-transform: translateX(-100%)
}
}
@keyframes slideDelay-out {
100% {
transform: translateX(-100%)
}
}
@-webkit-keyframes slideDelay-in {
0% {
-webkit-transform: translateX(100%)
}
100% {
-webkit-transform: translateX(0)
}
}
@keyframes slideDelay-in {
0% {
transform: translateX(100%)
}
100% {
transform: translateX(0)
}
}
.cbp-animation-foldLeft,
.cbp-animation-unfold {
-webkit-transition: height .6s ease-in-out;
will-change: height
}
.cbp-animation-rotateSides .cbp-item {
-webkit-perspective: 1000px;
perspective: 1000px
}
.cbp-animation-rotateSides .cbp-item-wrapper {
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d
}
.cbp-animation-rotateSides .cbp-wrapper-helper .cbp-item-wrapper {
-webkit-transform-origin: -50% 50%;
-webkit-animation: rotateSides-out .5s both ease-in;
transform-origin: -50% 50%;
animation: rotateSides-out .5s both ease-in
}
.cbp-animation-rotateSides .cbp-wrapper .cbp-item-wrapper {
-webkit-transform-origin: 150% 50%;
-webkit-animation: rotateSides-in .6s both ease-out;
transform-origin: 150% 50%;
animation: rotateSides-in .6s both ease-out
}
@-webkit-keyframes rotateSides-out {
100% {
opacity: 0;
-webkit-transform: translateZ(-500px) rotateY(90deg)
}
}
@keyframes rotateSides-out {
100% {
opacity: 0;
transform: translateZ(-500px) rotateY(90deg)
}
}
@-webkit-keyframes rotateSides-in {
0%,
40% {
opacity: 0;
-webkit-transform: translateZ(-500px) rotateY(-90deg)
}
}
@keyframes rotateSides-in {
0%,
40% {
opacity: 0;
transform: translateZ(-500px) rotateY(-90deg)
}
}
.cbp-animation-foldLeft {
transition: height .6s ease-in-out
}
.cbp-animation-foldLeft .cbp-item {
-webkit-perspective: 1000px;
perspective: 1000px
}
.cbp-animation-foldLeft .cbp-item-wrapper {
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d
}
.cbp-animation-foldLeft .cbp-wrapper-helper .cbp-item-wrapper {
-webkit-transform-origin: 100% 50%;
transform-origin: 100% 50%;
-webkit-animation: foldLeft-out .7s both;
animation: foldLeft-out .7s both
}
.cbp-animation-foldLeft .cbp-wrapper .cbp-item-wrapper {
-webkit-animation: foldLeft-in .7s both;
animation: foldLeft-in .7s both
}
@-webkit-keyframes foldLeft-out {
100% {
opacity: 0;
-webkit-transform: translateX(-100%) rotateY(-90deg)
}
}
@keyframes foldLeft-out {
100% {
opacity: 0;
transform: translateX(-100%) rotateY(-90deg)
}
}
@-webkit-keyframes foldLeft-in {
0% {
opacity: .3;
-webkit-transform: translateX(100%)
}
}
@keyframes foldLeft-in {
0% {
opacity: .3;
transform: translateX(100%)
}
}
.cbp-animation-unfold {
transition: height .6s ease-in-out
}
.cbp-animation-frontRow,
.cbp-animation-scaleDown {
-webkit-transition: height .6s ease-in-out;
will-change: height;
transition: height .6s ease-in-out
}
.cbp-animation-unfold .cbp-item {
-webkit-perspective: 1000px;
perspective: 1000px
}
.cbp-animation-unfold .cbp-item-wrapper {
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d
}
.cbp-animation-unfold .cbp-wrapper-helper .cbp-item-wrapper {
-webkit-animation: unfold-out .8s both;
animation: unfold-out .8s both
}
.cbp-animation-unfold .cbp-wrapper .cbp-item-wrapper {
-webkit-transform-origin: 0 50%;
-webkit-animation: unfold-in .8s both;
transform-origin: 0 50%;
animation: unfold-in .8s both
}
@-webkit-keyframes unfold-out {
90% {
opacity: .3
}
100% {
opacity: 0;
-webkit-transform: translateX(-100%)
}
}
@keyframes unfold-out {
90% {
opacity: .3
}
100% {
opacity: 0;
transform: translateX(-100%)
}
}
@-webkit-keyframes unfold-in {
0% {
opacity: 0;
-webkit-transform: translateX(100%) rotateY(90deg)
}
}
@keyframes unfold-in {
0% {
opacity: 0;
transform: translateX(100%) rotateY(90deg)
}
}
.cbp-animation-scaleDown .cbp-item {
-webkit-perspective: 1000px;
perspective: 1000px
}
.cbp-animation-scaleDown .cbp-item-wrapper {
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d
}
.cbp-animation-scaleDown .cbp-wrapper-helper .cbp-item-wrapper {
-webkit-animation: scaleDown-out .7s both;
animation: scaleDown-out .7s both
}
.cbp-animation-scaleDown .cbp-wrapper .cbp-item-wrapper {
-webkit-animation: scaleDown-in .6s both;
animation: scaleDown-in .6s both
}
@-webkit-keyframes scaleDown-out {
100% {
opacity: 0;
-webkit-transform: scale(.8)
}
}
@keyframes scaleDown-out {
100% {
opacity: 0;
transform: scale(.8)
}
}
@-webkit-keyframes scaleDown-in {
0% {
-webkit-transform: translateX(100%)
}
}
@keyframes scaleDown-in {
0% {
transform: translateX(100%)
}
}
.cbp-animation-bounceBottom,
.cbp-animation-rotateRoom {
-webkit-transition: height .6s ease-in-out;
will-change: height
}
.cbp-animation-frontRow .cbp-item {
-webkit-perspective: 1000px;
perspective: 1000px
}
.cbp-animation-frontRow .cbp-item-wrapper {
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d
}
.cbp-animation-frontRow .cbp-wrapper-helper .cbp-item-wrapper {
-webkit-animation: frontRow-out .7s both ease;
animation: frontRow-out .7s both ease
}
.cbp-animation-frontRow .cbp-wrapper .cbp-item-wrapper {
-webkit-animation: frontRow-in .6s both ease;
animation: frontRow-in .6s both ease
}
@-webkit-keyframes frontRow-out {
100% {
-webkit-transform: translateX(-60%) scale(.8);
opacity: 0
}
}
@keyframes frontRow-out {
100% {
transform: translateX(-60%) scale(.8);
opacity: 0
}
}
@-webkit-keyframes frontRow-in {
0% {
-webkit-transform: translateX(100%) scale(.8)
}
100% {
opacity: 1;
-webkit-transform: translateX(0) scale(1)
}
}
@keyframes frontRow-in {
0% {
transform: translateX(100%) scale(.8)
}
100% {
opacity: 1;
transform: translateX(0) scale(1)
}
}
.cbp-animation-rotateRoom {
transition: height .6s ease-in-out
}
.cbp-animation-rotateRoom .cbp-item {
-webkit-perspective: 1000px;
perspective: 1000px
}
.cbp-animation-rotateRoom .cbp-item-wrapper {
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d
}
.cbp-animation-rotateRoom .cbp-wrapper-helper .cbp-item-wrapper {
-webkit-transform-origin: 100% 50%;
transform-origin: 100% 50%;
-webkit-animation: rotateRoom-out .8s both ease;
animation: rotateRoom-out .8s both ease
}
.cbp-animation-rotateRoom .cbp-wrapper .cbp-item-wrapper {
-webkit-transform-origin: 0 50%;
transform-origin: 0 50%;
-webkit-animation: rotateRoom-in .8s both ease;
animation: rotateRoom-in .8s both ease
}
@-webkit-keyframes rotateRoom-out {
90% {
opacity: .3
}
100% {
opacity: 0;
-webkit-transform: translateX(-100%) rotateY(90deg)
}
}
@keyframes rotateRoom-out {
90% {
opacity: .3
}
100% {
opacity: 0;
transform: translateX(-100%) rotateY(90deg)
}
}
@-webkit-keyframes rotateRoom-in {
0% {
opacity: .3;
-webkit-transform: translateX(100%) rotateY(-90deg)
}
}
@keyframes rotateRoom-in {
0% {
opacity: .3;
transform: translateX(100%) rotateY(-90deg)
}
}
.cbp-animation-bounceBottom {
transition: height .6s ease-in-out
}
.cbp-animation-bounceLeft,
.cbp-animation-bounceTop {
-webkit-transition: height .6s ease-in-out;
will-change: height;
transition: height .6s ease-in-out
}
.cbp-animation-bounceBottom .cbp-wrapper-helper {
-webkit-animation: bounceBottom-out .6s both ease-in-out;
animation: bounceBottom-out .6s both ease-in-out
}
.cbp-animation-bounceBottom .cbp-wrapper {
-webkit-animation: bounceBottom-in .6s both ease-in-out;
animation: bounceBottom-in .6s both ease-in-out
}
@-webkit-keyframes bounceBottom-out {
100% {
-webkit-transform: translateY(100%);
opacity: 0
}
}
@keyframes bounceBottom-out {
100% {
transform: translateY(100%);
opacity: 0
}
}
@-webkit-keyframes bounceBottom-in {
0% {
-webkit-transform: translateY(100%);
opacity: 0
}
100% {
-webkit-transform: translateY(0);
opacity: 1
}
}
@keyframes bounceBottom-in {
0% {
transform: translateY(100%);
opacity: 0
}
100% {
transform: translateY(0);
opacity: 1
}
}
.cbp-animation-bounceLeft .cbp-wrapper-helper {
-webkit-animation: bounceLeft-out .6s both ease-in-out;
animation: bounceLeft-out .6s both ease-in-out
}
.cbp-animation-bounceLeft .cbp-wrapper {
-webkit-animation: bounceLeft-in .6s both ease-in-out;
animation: bounceLeft-in .6s both ease-in-out
}
@-webkit-keyframes bounceLeft-out {
100% {
-webkit-transform: translateX(-100%);
opacity: 0
}
}
@keyframes bounceLeft-out {
100% {
transform: translateX(-100%);
opacity: 0
}
}
@-webkit-keyframes bounceLeft-in {
0% {
-webkit-transform: translateX(-100%);
opacity: 0
}
100% {
-webkit-transform: translateX(0);
opacity: 1
}
}
@keyframes bounceLeft-in {
0% {
transform: translateX(-100%);
opacity: 0
}
100% {
transform: translateX(0);
opacity: 1
}
}
.cbp-animation-bounceTop .cbp-wrapper-helper {
-webkit-animation: bounceTop-out .6s both ease-in-out;
animation: bounceTop-out .6s both ease-in-out
}
.cbp-animation-bounceTop .cbp-wrapper {
-webkit-animation: bounceTop-in .6s both ease-in-out;
animation: bounceTop-in .6s both ease-in-out
}
@-webkit-keyframes bounceTop-out {
100% {
-webkit-transform: translateY(-100%);
opacity: 0
}
}
@keyframes bounceTop-out {
100% {
transform: translateY(-100%);
opacity: 0
}
}
@-webkit-keyframes bounceTop-in {
0% {
-webkit-transform: translateY(-100%);
opacity: 0
}
100% {
-webkit-transform: translateY(0);
opacity: 1
}
}
@keyframes bounceTop-in {
0% {
transform: translateY(-100%);
opacity: 0
}
100% {
transform: translateY(0);
opacity: 1
}
}
.cbp-animation-moveLeft {
-webkit-transition: height .6s ease-in-out;
transition: height .6s ease-in-out;
will-change: height
}
.cbp-animation-moveLeft .cbp-wrapper-helper {
-webkit-animation: moveLeft-out .6s both ease-in-out;
animation: moveLeft-out .6s both ease-in-out
}
.cbp-animation-moveLeft .cbp-wrapper {
-webkit-animation: moveLeft-in .6s both ease-in-out;
animation: moveLeft-in .6s both ease-in-out
}
@-webkit-keyframes moveLeft-out {
100% {
-webkit-transform: translateX(-100%);
opacity: 0
}
}
@keyframes moveLeft-out {
100% {
transform: translateX(-100%);
opacity: 0
}
}
@-webkit-keyframes moveLeft-in {
0% {
-webkit-transform: translateX(100%);
opacity: 0
}
100% {
-webkit-transform: translateX(0);
opacity: 1
}
}
@keyframes moveLeft-in {
0% {
transform: translateX(100%);
opacity: 0
}
100% {
transform: translateX(0);
opacity: 1
}
}
.cbp-displayType-bottomToTop {
-webkit-perspective: 1000px;
perspective: 1000px
}
.cbp-displayType-bottomToTop .cbp-item {
-webkit-animation: fadeInBottomToTop .3s both ease-in;
animation: fadeInBottomToTop .3s both ease-in
}
@-webkit-keyframes fadeInBottomToTop {
0% {
opacity: 0;
-webkit-transform: translateY(50px)
}
100% {
opacity: 1;
-webkit-transform: translateY(0)
}
}
@keyframes fadeInBottomToTop {
0% {
opacity: 0;
transform: translateY(50px)
}
100% {
opacity: 1;
transform: translateY(0)
}
}
.cbp-displayType-fadeIn {
-webkit-animation: fadeIn .5s both ease-in;
animation: fadeIn .5s both ease-in
}
@-webkit-keyframes fadeIn {
0% {
opacity: 0
}
100% {
opacity: 1
}
}
@keyframes fadeIn {
0% {
opacity: 0
}
100% {
opacity: 1
}
}
.cbp-displayType-fadeInToTop {
-webkit-perspective: 1000px;
perspective: 1000px;
-webkit-animation: fadeInToTop .5s both ease-in;
animation: fadeInToTop .5s both ease-in
}
@-webkit-keyframes fadeInToTop {
0% {
opacity: 0;
-webkit-transform: translateY(30px)
}
100% {
opacity: 1;
-webkit-transform: translateY(0)
}
}
@keyframes fadeInToTop {
0% {
opacity: 0;
transform: translateY(30px)
}
100% {
opacity: 1;
transform: translateY(0)
}
}
.cbp-displayType-sequentially .cbp-item {
-webkit-animation: fadeIn .5s both ease-in;
animation: fadeIn .5s both ease-in
}
.cbp-lightbox img {
display: block;
border: 0;
width: 100%;
height: auto
}
.cbp-popup-ie8bg {
position: absolute;
width: 100%;
height: 100%;
min-height: 100%;
top: 0;
left: 0;
z-index: -1;
background: #000
}
.cbp-popup-wrap {
height: 100%;
text-align: center;
position: fixed;
width: 100%;
left: 0;
top: 0;
display: none;
overflow-y: hidden;
-webkit-overflow-scrolling: touch;
overflow-x: hidden;
z-index: 9990;
padding: 0 10px
}
.cbp-popup-wrap video {
outline: 0
}
.cbp-popup-lightbox {
background: rgba(0, 0, 0, .8);
display: flex;
justify-content: center;
align-items: center
}
.cbp-popup-content,
.cbp-popup-wrap:before {
display: inline-block;
vertical-align: middle
}
.cbp-popup-singlePage {
background: #fff;
padding: 0
}
.cbp-popup-wrap:before {
content: "";
height: 100%
}
.cbp-popup-content {
position: relative;
text-align: left;
max-width: 100%
}
.cbp-popup-lightbox .cbp-popup-content {
display: flex
}
.cbp-popup-singlePage .cbp-popup-content {
position: relative;
z-index: 1;
margin-top: 145px;
max-width: 1024px;
vertical-align: top;
width: 94%
}
.cbp-popup-singlePage .cbp-popup-content-basic {
position: relative;
z-index: 1;
margin-top: 104px;
vertical-align: top;
width: 100%;
display: inline-block;
text-align: left
}
.cbp-popup-lightbox-figure {
width: 100%;
position: relative;
padding: 20px 0
}
.cbp-popup-lightbox-bottom {
position: relative;
margin-top: 3px
}
.cbp-popup-lightbox-title {
padding-right: 50px
}
.cbp-popup-lightbox-counter {
position: absolute;
top: 0;
right: 0
}
.cbp-popup-lightbox-img {
width: auto;
max-width: 100%;
height: auto;
display: block;
box-shadow: 0 0 8px rgba(0, 0, 0, .6)
}
.cbp-popup-lightbox-img[data-action] {
cursor: pointer
}
.cbp-popup-lightbox-isIframe .cbp-popup-content {
width: 75%;
display: inline-block
}
@media only screen and (max-width:768px) {
.cbp-popup-lightbox-isIframe .cbp-popup-content {
width: 95%
}
}
.cbp-popup-lightbox-isIframe .cbp-lightbox-bottom {
left: 0;
position: absolute;
top: 100%;
width: 100%;
margin-top: 3px
}
.cbp-popup-lightbox-iframe {
position: relative;
height: 0;
padding-bottom: 56.25%;
background: #000
}
.cbp-popup-lightbox-iframe iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
box-shadow: 0 0 8px rgba(0, 0, 0, .6)
}
.cbp-popup-lightbox-iframe audio {
margin-top: 27%
}
.cbp-popup-lightbox-iframe .cbp-popup-lightbox-bottom {
position: absolute;
left: 0;
top: 100%;
width: 100%
}
.cbp-popup-singlePage .cbp-popup-navigation-wrap {
position: absolute;
top: 0;
left: 0;
width: 100%;
z-index: 9990;
height: 104px;
background-color: #3D4750
}
.cbp-popup-singlePage .cbp-popup-navigation {
position: relative;
width: 100%;
height: 100%
}
.cbp-popup-singlePage-sticky .cbp-popup-navigation-wrap {
position: fixed;
top: 0!important
}
.cbp-popup-singlePage-counter {
color: #fff;
position: absolute;
margin: auto;
right: 40px;
top: 0;
bottom: 0;
font: 400 14px/30px "Open Sans Condensed", sans-serif;
height: 30px
}
.cbp-popup-lightbox .cbp-popup-next,
.cbp-popup-lightbox .cbp-popup-prev,
.cbp-popup-singlePage .cbp-popup-next,
.cbp-popup-singlePage .cbp-popup-prev {
width: 44px;
height: 44px;
top: 0;
margin: auto;
bottom: 0
}
@media only screen and (max-width:768px) {
.cbp-popup-singlePage-counter {
right: 3%
}
}
.cbp-popup-close,
.cbp-popup-next,
.cbp-popup-prev {
padding: 0;
border: none;
position: absolute;
cursor: pointer;
outline: 0;
user-select: none
}
.cbp-popup-lightbox .cbp-popup-prev {
background: url(../img/cbp-sprite.png) no-repeat;
left: 20px
}
.cbp-popup-lightbox .cbp-popup-prev:hover {
background-position: 0 -46px
}
.cbp-popup-singlePage .cbp-popup-prev {
background: url(../img/cbp-sprite.png) 0 -92px no-repeat;
right: 108px;
left: 0
}
.cbp-popup-singlePage .cbp-popup-prev:hover {
background-position: 0 -138px
}
.cbp-popup-lightbox .cbp-popup-next {
background: url(../img/cbp-sprite.png) -46px 0 no-repeat;
right: 20px
}
.cbp-popup-lightbox .cbp-popup-next:hover {
background-position: -46px -46px
}
.cbp-popup-singlePage .cbp-popup-next {
background: url(../img/cbp-sprite.png) -46px -92px no-repeat;
right: 0;
left: 108px
}
.cbp-popup-singlePage .cbp-popup-next:hover {
background-position: -46px -138px
}
.cbp-popup-lightbox .cbp-popup-close {
background: url(../img/cbp-sprite.png) -92px 0 no-repeat;
height: 40px;
width: 40px;
right: 20px;
top: 20px
}
.cbp-popup-lightbox .cbp-popup-close:hover {
background-position: -92px -46px
}
.cbp-popup-singlePage .cbp-popup-close {
background: url(../img/cbp-sprite.png) -92px -92px no-repeat;
height: 44px;
width: 44px;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0
}
.cbp-popup-singlePage .cbp-popup-close:hover {
background-position: -92px -138px
}
.cbp-popup-singlePage .cbp-popup-ie8bg {
background-color: #fff
}
@media only screen and (max-width:360px),
(max-height:600px) {
.cbp-popup-close,
.cbp-popup-next,
.cbp-popup-prev {
-webkit-transform: scale(.8);
transform: scale(.8)
}
.cbp-popup-lightbox .cbp-popup-close {
right: 10px;
top: 10px
}
.cbp-popup-lightbox .cbp-popup-next {
right: 10px
}
.cbp-popup-lightbox .cbp-popup-prev {
left: 10px
}
.cbp-popup-singlePage .cbp-popup-navigation-wrap {
height: 84px
}
.cbp-popup-singlePage .cbp-popup-content {
margin-top: 120px
}
}
.cbp-popup-loadingBox {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0
}
.cbp-popup-lightbox .cbp-popup-loadingBox:after {
border-left: 3px solid rgba(255, 255, 255, .3);
border-right: 3px solid rgba(255, 255, 255, .3);
border-bottom: 3px solid rgba(255, 255, 255, .3);
border-top: 3px solid rgba(255, 255, 255, .85)
}
.cbp-popup-ready .cbp-popup-loadingBox {
visibility: hidden;
display: none
}
.cbp-popup-loading .cbp-popup-loadingBox {
visibility: visible;
display: block
}
.cbp-popup-transitionend {
overflow-y: scroll
}
.cbp-popup-singlePage {
left: 100%;
-webkit-transition: left .6s ease-in-out;
transition: left .6s ease-in-out
}
.cbp-popup-singlePage.cbp-popup-loading .cbp-popup-content {
opacity: 0
}
.cbp-popup-singlePage-open {
left: 0
}
.cbp-popup-singlePage.cbp-popup-singlePage-fade {
left: 0;
opacity: 0;
-webkit-transition: opacity .25s ease-in-out;
transition: opacity .25s ease-in-out
}
.cbp-popup-singlePage-open.cbp-popup-singlePage-fade {
opacity: 1
}
.cbp-popup-singlePage.cbp-popup-singlePage-right {
left: -100%;
-webkit-transition: left .6s ease-in-out;
transition: left .6s ease-in-out
}
.cbp-popup-singlePage-open.cbp-popup-singlePage-right {
left: 0
}
.cbp-l-project-title {
color: #454444;
font: 600 42px/46px "Open Sans Condensed", sans-serif;
letter-spacing: 2px;
margin-bottom: 15px;
text-align: center;
text-transform: uppercase
}
.cbp-l-project-subtitle {
color: #787878;
font: 400 14px/21px "Open Sans Condensed", sans-serif;
margin: 0 auto 50px;
max-width: 500px;
text-align: center
}
.cbp-popup-singlePage .cbp-popup-content .cbp-l-project-img {
display: block;
margin: 0 auto;
max-width: 100%
}
.cbp-l-project-container {
overflow: hidden;
margin: 40px auto 0;
clear: both
}
.cbp-l-project-desc {
float: left;
width: 62%
}
.cbp-l-project-details {
float: right;
width: 38%;
padding-left: 60px;
margin-bottom: 15px
}
@media only screen and (max-width:768px) {
.cbp-l-project-title {
font-size: 30px;
line-height: 34px
}
.cbp-l-project-desc {
width: 100%
}
.cbp-l-project-details {
width: 100%;
margin-top: 20px;
padding-left: 0
}
}
.cbp-l-project-desc-title {
border-bottom: 1px solid #cdcdcd;
margin-bottom: 22px;
color: #444
}
.cbp-l-project-desc-title span,
.cbp-l-project-details-title span {
border-bottom: 1px solid #747474;
display: inline-block;
margin: 0 0 -1px;
font: 400 16px/36px "Open Sans Condensed", sans-serif;
padding: 0 5px 0 0
}
.cbp-l-project-desc-text {
font: 400 16px/20px "Open Sans Condensed", sans-serif;
color: #555;
margin-bottom: 20px
}
.cbp-l-project-details-title {
border-bottom: 1px solid #cdcdcd;
margin-bottom: 19px;
color: #444
}
.cbp-l-project-details-list {
margin: 0;
padding: 0;
list-style: none
}
.cbp-l-project-details-list>div,
.cbp-l-project-details-list>li {
border-bottom: 1px dotted #DFDFDF;
padding: inherit;
color: #666;
font: 400 14px/30px "Open Sans Condensed", sans-serif
}
.cbp-l-project-details-list>div:last-child,
.cbp-l-project-details-list>li:last-child {
border: none
}
.cbp-l-project-details-list strong {
display: inline-block;
color: #696969;
font-weight: 600;
min-width: 100px
}
.cbp-l-project-details-visit {
color: #FFF;
float: right;
clear: both;
text-decoration: none;
font: 400 11px/18px "Open Sans Condensed", sans-serif;
margin-top: 25px;
background-color: #62B57B;
padding: 8px 19px;
text-transform: uppercase;
letter-spacing: .5px
}
.cbp-l-project-details-visit:hover {
opacity: .9;
color: #fff
}
.cbp-l-project-related-wrap {
font-size: 0;
margin: 0;
padding: 0
}
.cbp-l-project-related-item {
margin-left: 5%;
max-width: 30%;
float: left
}
.cbp-l-project-related-item:first-child {
margin-left: 0
}
.cbp-l-project-related-title {
font: 700 14px/18px "Open Sans Condensed", sans-serif;
color: #474747;
margin-top: 20px
}
.cbp-l-project-related-link {
text-decoration: none
}
.cbp-l-project-related-link:hover {
opacity: .9
}
.cbp-l-member-img {
float: left;
width: 40%;
margin-top: 20px
}
.cbp-l-member-img img {
width: auto;
max-width: 100%;
height: auto;
display: inline-block;
border: 0
}
.cbp-popup-singlePageInline-close .cbp-popup-singlePageInline:after,
.cbp-popup-singlePageInline-ready:after {
display: none;
visibility: hidden
}
.cbp-l-member-info {
margin-top: 20px;
padding-left: 25px;
float: left;
width: 60%
}
@media only screen and (max-width:768px) {
.cbp-l-member-img {
width: 100%;
text-align: center
}
.cbp-l-member-info {
width: 100%;
padding-left: 0
}
}
.cbp-l-member-name {
font: 400 28px/28px "Open Sans Condensed", sans-serif;
color: #474747
}
.cbp-l-member-position {
font: 400 13px/21px "Open Sans Condensed", sans-serif;
color: #888;
margin-top: 6px
}
.cbp-l-member-desc {
font: 400 12px/18px "Open Sans Condensed", sans-serif;
margin-top: 25px;
color: #474747
}
.cbp-popup-singlePageInline-open {
-webkit-transition: height .5s 0s!important;
transition: height .5s 0s!important
}
.cbp-popup-singlePageInline-open .cbp-item {
-webkit-transition: -webkit-transform .5s 0s!important;
transition: transform .5s 0s!important
}
.cbp-popup-singlePageInline-close .cbp-popup-singlePageInline .cbp-popup-content,
.cbp-popup-singlePageInline-close .cbp-popup-singlePageInline .cbp-popup-navigation {
-webkit-transition-delay: 0;
transition-delay: 0
}
.cbp-popup-singlePageInline {
width: 100%;
position: absolute;
top: 0;
left: 0;
z-index: 0;
overflow: hidden
}
.cbp-popup-singlePageInline .cbp-popup-content {
opacity: 0;
width: 100%;
z-index: 1;
min-height: 300px
}
.cbp-popup-singlePageInline .cbp-popup-content,
.cbp-popup-singlePageInline .cbp-popup-navigation {
-webkit-transition: opacity .4s ease-in .2s;
transition: opacity .4s ease-in .2s
}
.cbp-popup-singlePageInline .cbp-popup-navigation {
opacity: 0;
position: absolute;
top: 0;
right: 0;
z-index: 2;
width: 40px;
height: 40px
}
.cbp-popup-singlePageInline .cbp-popup-close {
background: url(../img/cbp-sprite.png) -92px 0 no-repeat;
height: 40px;
width: 40px;
right: 20px;
top: 30px
}
.cbp-popup-singlePageInline .cbp-popup-close:hover {
opacity: .7
}
.cbp-popup-singlePageInline-ready {
z-index: 4
}
.cbp-popup-singlePageInline-ready .cbp-popup-content,
.cbp-popup-singlePageInline-ready .cbp-popup-navigation {
opacity: 1
}
.cbp-singlePageInline-active {
opacity: .6!important
}
.cbp-l-inline {
margin: 20px 0;
overflow: hidden;
background: #FAFAFA;
padding: 30px
}
.cbp-l-inline-left {
float: left;
width: 44%
}
.cbp-l-project-img {
max-width: 100%
}
.cbp-l-inline-right {
float: right;
width: 56%;
padding-left: inherit
}
@media only screen and (max-width:768px) {
.cbp-l-inline-left {
width: 100%;
text-align: center;
margin-top: 40px
}
.cbp-l-inline-right {
width: 100%;
padding-left: 0;
margin-top: 20px
}
}
.cbp-l-inline-title {
font: 400 28px/30px "Open Sans Condensed", sans-serif;
color: #474747
}
.cbp-l-inline-subtitle {
font: 400 13px/21px "Open Sans Condensed", sans-serif;
color: #888;
margin-top: 7px
}
.cbp-l-inline-desc {
font: 400 13px/20px "Open Sans Condensed", sans-serif;
color: #474747;
margin-top: 25px;
margin-bottom: 20px
}
.cbp-l-inline-view-wrap {
text-align: right
}
.cbp-l-loadMore-bgbutton,
.cbp-l-loadMore-button,
.cbp-l-loadMore-text {
text-align: center
}
.cbp-l-inline-view {
font: 400 13px/35px "Open Sans Condensed", sans-serif;
color: #9C9C9C;
margin-top: 40px;
display: inline-block;
padding: 0 20px;
border: 1px solid #ccc;
text-decoration: none
}
.cbp-l-inline-view:hover {
color: #757575
}
.cbp-l-inline-details {
margin-bottom: 15px;
font: 13px/22px "Open Sans Condensed", sans-serif
}
.cbp-l-loadMore-button-defaultText,
.cbp-l-loadMore-defaultText {
display: block
}
.cbp-l-loadMore-button-loadingText,
.cbp-l-loadMore-button-noMoreLoading,
.cbp-l-loadMore-loadingText,
.cbp-l-loadMore-noMoreLoading {
display: none
}
.cbp-l-loadMore-loading .cbp-l-loadMore-button-loadingText,
.cbp-l-loadMore-loading .cbp-l-loadMore-loadingText {
display: block
}
.cbp-l-loadMore-loading .cbp-l-loadMore-button-defaultText,
.cbp-l-loadMore-loading .cbp-l-loadMore-button-noMoreLoading,
.cbp-l-loadMore-loading .cbp-l-loadMore-defaultText,
.cbp-l-loadMore-loading .cbp-l-loadMore-noMoreLoading {
display: none
}
.cbp-l-loadMore-stop .cbp-l-loadMore-button-noMoreLoading,
.cbp-l-loadMore-stop .cbp-l-loadMore-noMoreLoading {
display: block
}
.cbp-l-loadMore-stop .cbp-l-loadMore-button-defaultText,
.cbp-l-loadMore-stop .cbp-l-loadMore-button-loadingText,
.cbp-l-loadMore-stop .cbp-l-loadMore-defaultText,
.cbp-l-loadMore-stop .cbp-l-loadMore-loadingText {
display: none
}
.cbp-l-loadMore-bgbutton .cbp-l-loadMore-link {
border: 1px solid #DEDEDE;
color: #7E7B7B;
display: inline-block;
font: 400 13px/40px Lato, sans-serif;
min-width: 80px;
text-decoration: none;
padding: 0 50px;
margin-top: 50px;
outline: 0;
box-shadow: none;
letter-spacing: 1px;
-webkit-transition: color .25s;
transition: color .25s
}
.cbp-l-loadMore-bgbutton .cbp-l-loadMore-link.cbp-l-loadMore-loading,
.cbp-l-loadMore-bgbutton .cbp-l-loadMore-link:hover {
color: #B0B0B0
}
.cbp-l-loadMore-bgbutton .cbp-l-loadMore-link.cbp-l-loadMore-stop {
color: #B0B0B0;
cursor: default
}
.cbp-l-loadMore-button .cbp-l-loadMore-button-link,
.cbp-l-loadMore-button .cbp-l-loadMore-link {
border-bottom: 1px solid #DEDEDE;
color: #444;
display: inline-block;
font: 400 16px/36px "Open Sans Condensed", sans-serif;
min-width: 80px;
text-decoration: none;
padding: 0 30px;
outline: 0;
margin-top: 40px;
box-shadow: none;
-webkit-transition: color .25s;
transition: color .25s
}
.cbp-l-loadMore-button .cbp-l-loadMore-button-link.cbp-l-loadMore-loading,
.cbp-l-loadMore-button .cbp-l-loadMore-button-link:hover,
.cbp-l-loadMore-button .cbp-l-loadMore-link.cbp-l-loadMore-loading,
.cbp-l-loadMore-button .cbp-l-loadMore-link:hover {
color: #B0B0B0
}
.cbp-l-loadMore-button .cbp-l-loadMore-button-link.cbp-l-loadMore-button-stop,
.cbp-l-loadMore-button .cbp-l-loadMore-button-link.cbp-l-loadMore-stop,
.cbp-l-loadMore-button .cbp-l-loadMore-link.cbp-l-loadMore-button-stop,
.cbp-l-loadMore-button .cbp-l-loadMore-link.cbp-l-loadMore-stop {
cursor: default;
color: #B0B0B0
}
.cbp-l-loadMore-text .cbp-l-loadMore-link,
.cbp-l-loadMore-text .cbp-l-loadMore-text-link {
font: 400 15px "Open Sans Condensed", sans-serif;
color: #7E7B7B;
text-decoration: none;
cursor: pointer;
margin-top: 50px;
display: block
}
.cbp-l-loadMore-text .cbp-l-loadMore-stop,
.cbp-l-loadMore-text .cbp-l-loadMore-text-stop {
color: #B0B0B0;
cursor: default
}
.cbp-mode-slider {
-webkit-transition: height .35s;
transition: height .35s
}
.cbp-mode-slider .cbp-item,
.cbp-mode-slider .cbp-wrapper {
-webkit-transition: -webkit-transform .35s;
transition: transform .35s
}
.cbp-mode-slider .cbp-wrapper {
cursor: -webkit-grab;
cursor: -o-grab;
cursor: -ms-grab;
cursor: grab
}
.cbp-mode-slider-dragStart * {
cursor: move!important;
cursor: -ms-grabbing!important;
cursor: -webkit-grabbing!important;
cursor: -moz-grabbing!important;
cursor: grabbing!important
}
.cbp-mode-slider-dragStart .cbp-wrapper {
-webkit-transition: none;
transition: none
}
.cbp-nav-next,
.cbp-nav-prev {
position: relative;
background: #7c8b90;
cursor: pointer;
display: inline-block;
margin-left: 1px;
height: 22px;
width: 21px
}
.cbp-nav-next {
border-radius: 0 2px 2px 0
}
.cbp-nav-prev {
border-radius: 2px 0 0 2px
}
.cbp-nav-next:hover,
.cbp-nav-prev:hover {
opacity: .8
}
.cbp-nav-next:after,
.cbp-nav-prev:after {
content: '';
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
background: url(../img/cbp-sprite.png) no-repeat;
height: 10px;
width: 7px
}
.cbp-nav-next:after {
background-position: -134px 0
}
.cbp-nav-prev:after {
background-position: -134px -12px
}
.cbp-nav-stop {
opacity: .5!important;
cursor: default!important
}
.cbp-nav {
user-select: none
}
.cbp-nav-controls {
position: absolute;
top: -51px;
right: 0;
z-index: 100
}
.cbp-nav-pagination {
position: absolute;
bottom: -30px;
right: 0;
z-index: 100;
left: 0;
text-align: center
}
.cbp-nav-pagination-item,
.cbp-pagination-item {
display: inline-block;
position: relative;
cursor: pointer
}
.cbp-nav-pagination-item {
width: 10px;
height: 10px;
border-radius: 50%;
margin: 0 4px;
background: #c2c2c2;
-webkit-transition: background .5s;
transition: background .5s
}
.cbp-nav-pagination-active {
background: #797979
}
.cbp-pagination-item {
max-width: 100px;
margin-top: 10px;
margin-right: 5px
}
.cbp-pagination-item img {
display: block;
width: 100%;
height: auto;
border: 0
}
.cbp-pagination-item:after {
content: '';
position: absolute;
top: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, .5);
-webkit-transition: background .5s ease-in-out;
transition: background .5s ease-in-out
}
.cbp-pagination-active:after {
background: 0 0
}
.cbp-slider-item,
.cbp-slider-wrap {
margin: 0;
padding: 0;
list-style-type: none
}
.cbp-slider .cbp-nav-controls {
position: static
}
.cbp-slider .cbp-nav-next,
.cbp-slider .cbp-nav-prev {
background: 0 0;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
z-index: 100;
width: 44px;
height: 44px
}
.cbp-slider .cbp-nav-next {
right: 25px;
left: auto
}
.cbp-slider .cbp-nav-prev {
left: 25px;
right: auto
}
.cbp-slider .cbp-nav-next:after,
.cbp-slider .cbp-nav-prev:after {
background: url(../img/cbp-sprite.png) no-repeat;
width: 44px;
height: 44px
}
.cbp-slider .cbp-nav-next:after {
background-position: -46px -92px
}
.cbp-slider .cbp-nav-next:hover:after {
background-position: -46px -46px
}
.cbp-slider .cbp-nav-prev:after {
background-position: 0 -92px
}
.cbp-slider .cbp-nav-prev:hover:after {
background-position: 0 -46px
}
.cbp-slider .cbp-nav-pagination {
text-align: right;
bottom: 20px;
right: 25px;
left: auto
}
.cbp-slider-edge .cbp-nav-controls {
position: static
}
.cbp-slider-edge .cbp-nav-next,
.cbp-slider-edge .cbp-nav-prev {
background: 0 0;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
z-index: 100;
width: 44px;
height: 44px
}
.cbp-slider-edge .cbp-nav-next {
right: 0;
left: auto
}
.cbp-slider-edge .cbp-nav-prev {
left: 0;
right: auto
}
.cbp-slider-edge .cbp-nav-next:after,
.cbp-slider-edge .cbp-nav-prev:after {
background: url(../img/cbp-sprite.png) no-repeat;
width: 9px;
height: 16px
}
.cbp-slider-edge .cbp-nav-next:after {
background-position: -134px -24px
}
.cbp-slider-edge .cbp-nav-prev:after {
background-position: -134px -42px
}
.cbp-slider-edge .cbp-nav-pagination {
bottom: -50px
}
.cbp-slider-edge .cbp-nav-pagination-item {
border: 2px solid #0f0f0f;
opacity: .4;
background: 0 0
}
.cbp-slider-edge .cbp-nav-pagination-active {
background: #000
}
.cbp-slider-inline {
position: relative
}
.cbp-slider-inline .cbp-slider-item {
position: absolute;
width: 100%;
top: 0;
-webkit-transition: left .5s;
transition: left .5s
}
.cbp-slider-inline .cbp-slider-item--active {
position: relative;
z-index: 2
}
.cbp-slider-wrapper {
position: relative;
overflow: hidden
}
.cbp-slider-controls {
position: absolute;
top: 0;
right: 0;
z-index: 100;
opacity: 0;
-webkit-transition: opacity .7s ease-in-out;
transition: opacity .7s ease-in-out
}
.cbp-slider-inline-ready .cbp-slider-controls {
opacity: 1
}
.cbp-l-grid-blog-comments:hover,
.cbp-l-grid-slider-team-social a:hover,
.cbp-social-fb:hover,
.cbp-social-googleplus:hover,
.cbp-social-pinterest:hover,
.cbp-social-twitter:hover {
opacity: .8
}
.cbp-slider-next,
.cbp-slider-prev {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
float: left;
cursor: pointer;
position: relative;
width: 36px;
height: 36px;
background: #547EB1
}
.cbp-slider-next {
margin-left: 1px
}
.cbp-slider-next:after,
.cbp-slider-prev:after {
content: '';
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
background: url(../img/cbp-sprite.png) no-repeat;
width: 9px;
height: 16px
}
.cbp-slider-next:after {
background-position: -134px -60px
}
.cbp-slider-prev:after {
background-position: -134px -78px
}
.cbp-l-grid-agency .cbp-caption:after {
position: absolute;
content: '';
width: 0;
height: 0;
border-bottom: 10px solid #fff;
border-right: 10px solid transparent;
border-left: 10px solid transparent;
bottom: 0;
left: 50%;
margin-left: -5px;
z-index: 1
}
.cbp-l-grid-agency.cbp-caption-zoom .cbp-caption:hover .cbp-caption-defaultWrap {
-webkit-transform: scale(1.15);
transform: scale(1.15)
}
.cbp-l-grid-agency-title {
margin-top: 18px;
font: 700 17px/24px Lato, sans-serif;
color: #666;
text-align: center;
padding: 0 4px
}
.cbp-item:hover .cbp-l-grid-agency-title {
color: #222
}
.cbp-l-grid-agency-desc {
font: 400 12px/21px "Open Sans Condensed", sans-serif;
color: #aaa;
text-align: center
}
@media only screen and (max-width:480px) {
.cbp-l-grid-agency-title {
font-size: 15px;
line-height: 21px
}
}
.cbp-l-grid-work.cbp-caption-zoom .cbp-caption-activeWrap {
background-color: rgba(0, 0, 0, .7)
}
.cbp-l-grid-work .cbp-item {
padding: 3px
}
.cbp-l-grid-work .cbp-item-wrapper {
background-color: #fff;
box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
padding: 7px 7px 27px;
border-top: 1px solid #F4F4F4
}
.cbp-l-grid-work-title {
margin-top: 17px;
font: 400 17px/25px "Roboto Condensed", sans-serif;
color: #607D8B;
text-align: center;
text-transform: uppercase;
display: block
}
.cbp-l-grid-work-title:hover {
color: #365D67
}
.cbp-l-grid-work-desc {
font: 400 11px/16px "Open Sans Condensed", sans-serif;
color: #888;
text-align: center;
text-transform: uppercase
}
@media only screen and (max-width:480px) {
.cbp-l-grid-work-title {
font-size: 15px;
line-height: 21px;
margin-top: 15px
}
.cbp-l-grid-work .cbp-item-wrapper {
padding-bottom: 18px
}
}
.cbp-l-grid-blog-title {
font: 400 18px/30px "Open Sans Condensed", sans-serif;
color: #444;
display: block;
margin-top: 17px
}
.cbp-l-grid-blog-comments,
.cbp-l-grid-blog-date {
font: 400 12px/18px "Open Sans Condensed", sans-serif
}
.cbp-l-grid-blog-title:hover {
color: #787878
}
.cbp-l-grid-blog-date {
color: #787878;
display: inline-block
}
.cbp-l-grid-blog-comments {
color: #3C6FBB;
display: inline-block
}
.cbp-l-grid-blog-desc {
font: 400 13px/18px "Open Sans Condensed", sans-serif;
color: #9B9B9B;
margin-top: 9px
}
.cbp-l-grid-blog-split {
margin: 0 4px;
font: 400 13px/16px "Open Sans Condensed", sans-serif;
color: #787878;
display: inline-block
}
.cbp-l-grid-clients {
height: 180px
}
.cbp-l-clients-title-block {
font: 400 32px/53px Roboto, sans-serif;
color: #666464;
text-align: center;
margin-bottom: 40px
}
.cbp-l-grid-faq .cbp-item {
width: 100%
}
.cbp-l-grid-projects-title {
font: 700 16px/21px "Open Sans Condensed", sans-serif;
color: #474747;
margin-top: 15px
}
.cbp-l-grid-projects-desc {
font: 400 16px/18px "Open Sans Condensed", sans-serif;
color: #444;
margin-top: 5px
}
@media only screen and (max-width:480px) {
.cbp-l-grid-projects-title {
margin-top: 12px
}
.cbp-l-grid-projects-desc {
margin-top: 3px
}
}
.cbp-l-grid-masonry-projects .cbp-caption-activeWrap {
background-color: #59a3b6;
background-color: rgba(89, 163, 182, .95)
}
.cbp-l-grid-masonry-projects .cbp-l-caption-buttonLeft,
.cbp-l-grid-masonry-projects .cbp-l-caption-buttonRight {
background-color: #545454
}
.cbp-l-grid-masonry-projects-title {
font: 500 15px/22px Roboto, sans-serif;
color: #59a3b6;
text-align: center;
display: block;
margin-top: 12px
}
.cbp-l-grid-masonry-projects-title:hover {
color: #457C8B
}
.cbp-l-grid-masonry-projects-desc {
font: 400 12px/18px Roboto, sans-serif;
color: #b2b2b2;
text-align: center
}
.cbp-l-grid-team-name {
font: 400 17px/24px "Open Sans Condensed", sans-serif;
color: #456297;
display: block;
text-align: center;
margin-top: 18px
}
.cbp-l-grid-team-name:hover {
color: #34425C
}
.cbp-l-grid-team-position {
font: italic 400 13px/21px "Open Sans Condensed", sans-serif;
color: #999;
text-align: center
}
@media only screen and (max-width:480px) {
.cbp-l-grid-team-name {
font-size: 15px;
line-height: 22px;
margin-top: 13px
}
.cbp-l-grid-team-position {
font-size: 12px;
line-height: 18px
}
}
.cbp-l-grid-mosaic-flat .cbp-caption-activeWrap {
background-color: #64C28E;
background-color: rgba(101, 199, 150, .95)
}
.cbp-l-grid-mosaic-flat .cbp-l-caption-title {
color: #FFF;
font: 400 14px/21px Lato, sans-serif;
text-transform: uppercase;
letter-spacing: 2px;
display: inline-block
}
.cbp-l-grid-mosaic-flat .cbp-l-caption-title:after {
content: '';
display: block;
width: 40%;
height: 1px;
background-color: #fff;
margin: 8px auto 0
}
@media only screen and (max-width:800px) {
.cbp-l-grid-mosaic-flat .cbp-l-caption-title:after {
display: none
}
}
.cbp-l-grid-mosaic-projects .cbp-caption-activeWrap {
background-color: #59a3b6;
background-color: rgba(89, 163, 182, .97)
}
.cbp-l-grid-mosaic .cbp-caption-activeWrap {
background-color: #FFEA71;
background-color: rgba(255, 234, 113, .95)
}
.cbp-l-grid-mosaic .cbp-l-caption-title {
color: #5A5A5A;
font: 500 18px/22px Roboto, sans-serif;
text-transform: uppercase;
margin-bottom: 5px
}
.cbp-l-grid-mosaic .cbp-l-caption-desc {
color: #585858;
font: 400 13px/20px Roboto, sans-serif
}
@media only screen and (max-width:480px) {
.cbp-l-grid-mosaic .cbp-l-caption-title {
font-size: 16px;
line-height: 22px;
margin-bottom: 0
}
.cbp-l-grid-mosaic .cbp-l-caption-desc {
font-size: 12px;
line-height: 18px
}
}
.cbp-l-slider-title-block {
border-bottom: 1px solid #cdcdcd;
margin-bottom: 22px
}
.cbp-l-slider-title-block div {
padding: 0 2px 6px 0;
display: inline-block;
border-bottom: 1px solid #a9a5a5;
color: #5e5e5e;
margin-bottom: -1px;
font: 15px/21px Roboto, sans-serif
}
.cbp-l-grid-slider-team-name {
float: left;
font: 20px/30px Roboto, sans-serif;
color: #494949;
margin-top: 16px
}
.cbp-l-grid-slider-team-position {
clear: both;
font: 14px/21px Roboto, sans-serif;
color: #A6A6A6
}
.cbp-l-grid-slider-team-desc {
font: 13px/20px Roboto, sans-serif;
color: #969696;
margin-top: 15px
}
.cbp-l-grid-slider-team-social {
float: right;
margin-top: 22px
}
.cbp-l-grid-slider-team-social a {
margin-left: 4px
}
@media only screen and (max-width:600px) {
.cbp-l-grid-slider-team-wrap {
float: left;
width: 100%;
margin-bottom: 10px
}
.cbp-l-grid-slider-team-name {
font-size: 17px;
line-height: 26px;
width: 100%;
margin-top: 12px;
text-align: center
}
.cbp-l-grid-slider-team-social {
width: 100%;
text-align: center;
margin-top: 8px
}
.cbp-l-grid-slider-team-position {
font-size: 13px;
line-height: 20px;
text-align: center
}
.cbp-l-grid-slider-team-desc {
font-size: 12px;
line-height: 18px;
margin-top: 10px;
text-align: center
}
}
.cbp-l-slider-testimonials-wrap {
background: #f8f9f9;
padding: 80px 0 110px;
border-width: 1px 0;
border-style: solid;
border-color: #dce1e2
}
.cbp-l-grid-slider-testimonials-body {
color: #424242;
max-width: 800px;
margin: 0 auto;
font: 20px/32px sans-serif;
text-align: center;
padding: 0 40px
}
.cbp-l-grid-slider-testimonials-footer {
font: 12px/19px Roboto, sans-serif;
color: #777;
text-align: center;
margin-bottom: 10px;
margin-top: 30px
}
.cbp-l-grid-tabs {
height: 100px
}
.cbp-l-grid-tabs .cbp-item {
font: 16px/24px 'Open Sans Condensed', sans-serif;
max-width: 700px;
width: 100%;
margin: 0 auto;
right: 0;
text-align: center;
color: #5a5a5a
}
.cbp-l-testimonials-title-block {
position: relative;
text-align: center;
font: 26px/36px Roboto, sans-serif;
color: #E7E7E7;
margin-bottom: 60px
}
.cbp-l-testimonials-title-block:after {
content: '';
position: absolute;
margin: 0 auto;
width: 23px;
height: 2px;
bottom: -6px;
background-color: #C2C2C2;
left: 0;
right: 0
}
.cbp-l-testimonials-wrap {
background: #2D2D2D;
padding: 60px 0 110px
}
.cbp-l-grid-testimonials-body {
color: #e7e7e7;
max-width: 800px;
margin: 0 auto;
font: 20px/32px Roboto, sans-serif;
text-align: center;
padding: 0 20px
}
.cbp-l-grid-testimonials-footer {
font: 12px/19px Roboto, sans-serif;
color: #C2C2C2;
text-align: center;
margin-bottom: 40px;
margin-top: 35px
}
.cbp-search {
position: relative;
width: 220px;
margin-bottom: 40px
}
.cbp-search-icon,
.cbp-search-nothing {
position: absolute;
top: 0;
text-align: center
}
.cbp-search .cbp-search-nothing {
display: none
}
.cbp-search-icon {
width: 32px;
height: 100%;
right: 0;
cursor: pointer;
pointer-events: none
}
.cbp-search-icon:after {
content: '';
display: block;
background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNzkyIDE3OTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZmlsbD0iIzczNzM3MyIgZD0iTTEyMTYgODMycTAtMTg1LTEzMS41LTMxNi41VDc2OCAzODQgNDUxLjUgNTE1LjUgMzIwIDgzMnQxMzEuNSAzMTYuNVQ3NjggMTI4MHQzMTYuNS0xMzEuNVQxMjE2IDgzMnptNTEyIDgzMnEwIDUyLTM4IDkwdC05MCAzOHEtNTQgMC05MC0zOGwtMzQzLTM0MnEtMTc5IDEyNC0zOTkgMTI0LTE0MyAwLTI3My41LTU1LjV0LTIyNS0xNTAtMTUwLTIyNVQ2NCA4MzJ0NTUuNS0yNzMuNSAxNTAtMjI1IDIyNS0xNTBUNzY4IDEyOHQyNzMuNSA1NS41IDIyNSAxNTAgMTUwIDIyNVQxNDcyIDgzMnEwIDIyMC0xMjQgMzk5bDM0MyAzNDNxMzcgMzcgMzcgOTB6Ii8+PC9zdmc+) center center no-repeat;
width: 100%;
height: 100%;
pointer-events: none
}
.cbp-search-input {
height: 36px;
padding: 0 32px 0 12px;
margin: 0;
border-radius: 1px;
border: 1px solid #c6c3c4;
font: 400 12px "Open Sans Condensed", sans-serif;
width: 100%
}
.cbp-search-input[value]+.cbp-search-icon {
pointer-events: auto
}
.cbp-search-input[value]+.cbp-search-icon:after {
background-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNzkyIDE3OTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZmlsbD0iIzczNzM3MyIgZD0iTTE0OTAgMTMyMnEwIDQwLTI4IDY4bC0xMzYgMTM2cS0yOCAyOC02OCAyOHQtNjgtMjhsLTI5NC0yOTQtMjk0IDI5NHEtMjggMjgtNjggMjh0LTY4LTI4bC0xMzYtMTM2cS0yOC0yOC0yOC02OHQyOC02OGwyOTQtMjk0LTI5NC0yOTRxLTI4LTI4LTI4LTY4dDI4LTY4bDEzNi0xMzZxMjgtMjggNjgtMjh0NjggMjhsMjk0IDI5NCAyOTQtMjk0cTI4LTI4IDY4LTI4dDY4IDI4bDEzNiAxMzZxMjggMjggMjggNjh0LTI4IDY4bC0yOTQgMjk0IDI5NCAyOTRxMjggMjggMjggNjh6Ii8+PC9zdmc+)
}
.cbp-search-nothing {
padding: 0 0 30px;
width: 100%;
font: 13px "Open Sans Condensed", sans-serif
}
@media only screen and (max-width:600px) {
.cbp-search {
width: 100%
}
}
.cbp-l-project-social {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex
}
.cbp-social-fb,
.cbp-social-googleplus,
.cbp-social-pinterest,
.cbp-social-twitter {
margin-right: 9px;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex
}
.cbp-social-fb:focus,
.cbp-social-googleplus:focus,
.cbp-social-pinterest:focus,
.cbp-social-twitter:focus {
outline: 0
}
.cbp-social-fb path {
fill: #415C9B
}
.cbp-social-twitter path {
fill: #55acee
}
.cbp-social-googleplus path {
fill: #E57371
}
.cbp-social-pinterest path {
fill: #cb2027
}
.cbp-popup-content-wrap {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
overflow-y: hidden;
overflow-x: hidden;
-webkit-overflow-scrolling: touch
}
.cbp-popup-transitionend .cbp-popup-content-wrap {
overflow-y: scroll
}
.cbp-popup-transitionend {
overflow-y: hidden;
} | Java |
#include "stdafx.h"
#include "NET_Common.h"
#include "net_client.h"
#include "net_server.h"
#include "net_messages.h"
#include "NET_Log.h"
#include "../xr_3da/xrGame/battleye.h"
#pragma warning(push)
#pragma warning(disable:4995)
#include <malloc.h>
#include "dxerr.h"
//#pragma warning(pop)
static INetLog* pClNetLog = NULL;
#define BASE_PORT_LAN_SV 5445
#define BASE_PORT_LAN_CL 5446
#define BASE_PORT 0
#define END_PORT 65535
void dump_URL (LPCSTR p, IDirectPlay8Address* A)
{
string256 aaaa;
DWORD aaaa_s = sizeof(aaaa);
R_CHK (A->GetURLA(aaaa,&aaaa_s));
Log (p,aaaa);
}
//
INetQueue::INetQueue()
#ifdef PROFILE_CRITICAL_SECTIONS
:cs(MUTEX_PROFILE_ID(INetQueue))
#endif // PROFILE_CRITICAL_SECTIONS
{
unused.reserve (128);
for (int i=0; i<16; i++)
unused.push_back (xr_new<NET_Packet>());
}
INetQueue::~INetQueue()
{
cs.Enter ();
u32 it;
for (it=0; it<unused.size(); it++) xr_delete(unused[it]);
for (it=0; it<ready.size(); it++) xr_delete(ready[it]);
cs.Leave ();
}
static u32 LastTimeCreate = 0;
void INetQueue::CreateCommit(NET_Packet* P)
{
cs.Enter ();
ready.push_back (P);
cs.Leave ();
}
NET_Packet* INetQueue::CreateGet()
{
NET_Packet* P = 0;
cs.Enter ();
if (unused.empty())
{
P = xr_new<NET_Packet> ();
//. ready.push_back (xr_new<NET_Packet> ());
//. P = ready.back ();
LastTimeCreate = GetTickCount();
} else
{
P = unused.back();
//. ready.push_back (unused.back());
unused.pop_back ();
//. P = ready.back ();
}
cs.Leave ();
return P;
}
/*
NET_Packet* INetQueue::Create (const NET_Packet& _other)
{
NET_Packet* P = 0;
cs.Enter ();
//#ifdef _DEBUG
// Msg ("- INetQueue::Create - ready %d, unused %d", ready.size(), unused.size());
//#endif
if (unused.empty())
{
ready.push_back (xr_new<NET_Packet> ());
P = ready.back ();
//---------------------------------------------
LastTimeCreate = GetTickCount();
//---------------------------------------------
} else {
ready.push_back (unused.back());
unused.pop_back ();
P = ready.back ();
}
CopyMemory (P,&_other,sizeof(NET_Packet));
cs.Leave ();
return P;
}
*/
NET_Packet* INetQueue::Retreive ()
{
NET_Packet* P = 0;
cs.Enter ();
//#ifdef _DEBUG
// Msg ("INetQueue::Retreive - ready %d, unused %d", ready.size(), unused.size());
//#endif
if (!ready.empty()) P = ready.front();
//---------------------------------------------
else
{
u32 tmp_time = GetTickCount()-60000;
u32 size = unused.size();
if ((LastTimeCreate < tmp_time) && (size > 32))
{
xr_delete(unused.back());
unused.pop_back();
}
}
//---------------------------------------------
cs.Leave ();
return P;
}
void INetQueue::Release ()
{
cs.Enter ();
//#ifdef _DEBUG
// Msg ("INetQueue::Release - ready %d, unused %d", ready.size(), unused.size());
//#endif
VERIFY (!ready.empty());
//---------------------------------------------
u32 tmp_time = GetTickCount()-60000;
u32 size = unused.size();
if ((LastTimeCreate < tmp_time) && (size > 32))
{
xr_delete(ready.front());
}
else
unused.push_back(ready.front());
//---------------------------------------------
ready.pop_front ();
cs.Leave ();
}
//
const u32 syncQueueSize = 512;
const int syncSamples = 256;
class XRNETSERVER_API syncQueue
{
u32 table [syncQueueSize];
u32 write;
u32 count;
public:
syncQueue() { clear(); }
IC void push (u32 value)
{
table[write++] = value;
if (write == syncQueueSize) write = 0;
if (count <= syncQueueSize) count++;
}
IC u32* begin () { return table; }
IC u32* end () { return table+count; }
IC u32 size () { return count; }
IC void clear () { write=0; count=0; }
} net_DeltaArray;
//-------
XRNETSERVER_API Flags32 psNET_Flags = {0};
XRNETSERVER_API int psNET_ClientUpdate = 30; // FPS
XRNETSERVER_API int psNET_ClientPending = 2;
XRNETSERVER_API char psNET_Name[32] = "Player";
XRNETSERVER_API BOOL psNET_direct_connect = FALSE;
// {0218FA8B-515B-4bf2-9A5F-2F079D1759F3}
static const GUID NET_GUID =
{ 0x218fa8b, 0x515b, 0x4bf2, { 0x9a, 0x5f, 0x2f, 0x7, 0x9d, 0x17, 0x59, 0xf3 } };
// {8D3F9E5E-A3BD-475b-9E49-B0E77139143C}
static const GUID CLSID_NETWORKSIMULATOR_DP8SP_TCPIP =
{ 0x8d3f9e5e, 0xa3bd, 0x475b, { 0x9e, 0x49, 0xb0, 0xe7, 0x71, 0x39, 0x14, 0x3c } };
static HRESULT WINAPI Handler (PVOID pvUserContext, DWORD dwMessageType, PVOID pMessage)
{
IPureClient* C = (IPureClient*)pvUserContext;
return C->net_Handler(dwMessageType,pMessage);
}
//------------------------------------------------------------------------------
void
IPureClient::_SendTo_LL( const void* data, u32 size, u32 flags, u32 timeout )
{
IPureClient::SendTo_LL( const_cast<void*>(data), size, flags, timeout );
}
//------------------------------------------------------------------------------
void IPureClient::_Recieve( const void* data, u32 data_size, u32 /*param*/ )
{
MSYS_PING* cfg = (MSYS_PING*)data;
if( (data_size>2*sizeof(u32))
&& (cfg->sign1==0x12071980)
&& (cfg->sign2==0x26111975)
)
{
// Internal system message
if( (data_size == sizeof(MSYS_PING)) )
{
// It is reverted(server) ping
u32 time = TimerAsync( device_timer );
u32 ping = time - (cfg->dwTime_ClientSend);
u32 delta = cfg->dwTime_Server + ping/2 - time;
net_DeltaArray.push ( delta );
Sync_Average ();
return;
}
if ( data_size == sizeof(MSYS_CONFIG) )
{
MSYS_CONFIG* msys_cfg = (MSYS_CONFIG*)data;
if ( msys_cfg->is_battleye )
{
#ifdef BATTLEYE
if ( !TestLoadBEClient() )
{
net_Connected = EnmConnectionFails;
return;
}
#endif // BATTLEYE
}
net_Connected = EnmConnectionCompleted;
return;
}
Msg( "! Unknown system message" );
return;
}
else if( net_Connected == EnmConnectionCompleted )
{
// one of the messages - decompress it
if( psNET_Flags.test( NETFLAG_LOG_CL_PACKETS ) )
{
if( !pClNetLog )
pClNetLog = xr_new<INetLog>("logs\\net_cl_log.log", timeServer());
if( pClNetLog )
pClNetLog->LogData( timeServer(), const_cast<void*>(data), data_size, TRUE );
}
OnMessage( const_cast<void*>(data), data_size );
}
}
//==============================================================================
IPureClient::IPureClient (CTimer* timer): net_Statistic(timer)
#ifdef PROFILE_CRITICAL_SECTIONS
,net_csEnumeration(MUTEX_PROFILE_ID(IPureClient::net_csEnumeration))
#endif // PROFILE_CRITICAL_SECTIONS
{
NET = NULL;
net_Address_server = NULL;
net_Address_device = NULL;
device_timer = timer;
net_TimeDelta_User = 0;
net_Time_LastUpdate = 0;
net_TimeDelta = 0;
net_TimeDelta_Calculated = 0;
pClNetLog = NULL;//xr_new<INetLog>("logs\\net_cl_log.log", timeServer());
}
IPureClient::~IPureClient ()
{
xr_delete(pClNetLog); pClNetLog = NULL;
psNET_direct_connect = FALSE;
}
void gen_auth_code();
BOOL IPureClient::Connect (LPCSTR options)
{
R_ASSERT (options);
net_Disconnected = FALSE;
if(!psNET_direct_connect && !strstr(options,"localhost") )
{
gen_auth_code ();
}
if(!psNET_direct_connect)
{
//
string256 server_name = "";
// strcpy (server_name,options);
if (strchr(options, '/'))
strncpy(server_name,options, strchr(options, '/')-options);
if (strchr(server_name,'/')) *strchr(server_name,'/') = 0;
string64 password_str = "";
if (strstr(options, "psw="))
{
const char* PSW = strstr(options, "psw=") + 4;
if (strchr(PSW, '/'))
strncpy(password_str, PSW, strchr(PSW, '/') - PSW);
else
strcpy(password_str, PSW);
}
string64 user_name_str = "";
if (strstr(options, "name="))
{
const char* NM = strstr(options, "name=") + 5;
if (strchr(NM, '/'))
strncpy(user_name_str, NM, strchr(NM, '/') - NM);
else
strcpy(user_name_str, NM);
}
string64 user_pass = "";
if (strstr(options, "pass="))
{
const char* UP = strstr(options, "pass=") + 5;
if (strchr(UP, '/'))
strncpy(user_pass, UP, strchr(UP, '/') - UP);
else
strcpy(user_pass, UP);
}
int psSV_Port = BASE_PORT_LAN_SV;
if (strstr(options, "port="))
{
string64 portstr;
strcpy(portstr, strstr(options, "port=")+5);
if (strchr(portstr,'/')) *strchr(portstr,'/') = 0;
psSV_Port = atol(portstr);
clamp(psSV_Port, int(BASE_PORT), int(END_PORT));
};
BOOL bPortWasSet = FALSE;
int psCL_Port = BASE_PORT_LAN_CL;
if (strstr(options, "portcl="))
{
string64 portstr;
strcpy(portstr, strstr(options, "portcl=")+7);
if (strchr(portstr,'/')) *strchr(portstr,'/') = 0;
psCL_Port = atol(portstr);
clamp(psCL_Port, int(BASE_PORT), int(END_PORT));
bPortWasSet = TRUE;
};
// Msg("* Client connect on port %d\n",psNET_Port);
//
net_Connected = EnmConnectionWait;
net_Syncronised = FALSE;
net_Disconnected= FALSE;
//---------------------------
string1024 tmp="";
// HRESULT CoInitializeExRes = CoInitializeEx(NULL, 0);
// if (CoInitializeExRes != S_OK && CoInitializeExRes != S_FALSE)
// {
// DXTRACE_ERR(tmp, CoInitializeExRes);
// CHK_DX(CoInitializeExRes);
// };
//---------------------------
// Create the IDirectPlay8Client object.
HRESULT CoCreateInstanceRes = CoCreateInstance (CLSID_DirectPlay8Client, NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Client, (LPVOID*) &NET);
//---------------------------
if (CoCreateInstanceRes != S_OK)
{
DXTRACE_ERR(tmp, CoCreateInstanceRes );
CHK_DX(CoCreateInstanceRes );
}
//---------------------------
// Initialize IDirectPlay8Client object.
#ifdef DEBUG
R_CHK(NET->Initialize (this, Handler, 0));
#else
R_CHK(NET->Initialize (this, Handler, DPNINITIALIZE_DISABLEPARAMVAL ));
#endif
BOOL bSimulator = FALSE;
if (strstr(Core.Params,"-netsim")) bSimulator = TRUE;
// Create our IDirectPlay8Address Device Address, --- Set the SP for our Device Address
net_Address_device = NULL;
R_CHK(CoCreateInstance (CLSID_DirectPlay8Address,NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Address,(LPVOID*) &net_Address_device ));
R_CHK(net_Address_device->SetSP(bSimulator? &CLSID_NETWORKSIMULATOR_DP8SP_TCPIP : &CLSID_DP8SP_TCPIP ));
// Create our IDirectPlay8Address Server Address, --- Set the SP for our Server Address
WCHAR ServerNameUNICODE [256];
R_CHK(MultiByteToWideChar(CP_ACP, 0, server_name, -1, ServerNameUNICODE, 256 ));
net_Address_server = NULL;
R_CHK(CoCreateInstance (CLSID_DirectPlay8Address,NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Address,(LPVOID*) &net_Address_server ));
R_CHK(net_Address_server->SetSP (bSimulator? &CLSID_NETWORKSIMULATOR_DP8SP_TCPIP : &CLSID_DP8SP_TCPIP ));
R_CHK(net_Address_server->AddComponent (DPNA_KEY_HOSTNAME, ServerNameUNICODE, 2*u32(wcslen(ServerNameUNICODE) + 1), DPNA_DATATYPE_STRING ));
R_CHK(net_Address_server->AddComponent (DPNA_KEY_PORT, &psSV_Port, sizeof(psSV_Port), DPNA_DATATYPE_DWORD ));
// Debug
// dump_URL ("! cl ", net_Address_device);
// dump_URL ("! en ", net_Address_server);
// Now set up the Application Description
DPN_APPLICATION_DESC dpAppDesc;
ZeroMemory (&dpAppDesc, sizeof(DPN_APPLICATION_DESC));
dpAppDesc.dwSize = sizeof(DPN_APPLICATION_DESC);
dpAppDesc.guidApplication = NET_GUID;
// Setup client info
/*strcpy_s( tmp, server_name );
strcat_s( tmp, "/name=" );
strcat_s( tmp, user_name_str );
strcat_s( tmp, "/" );*/
WCHAR ClientNameUNICODE [256];
R_CHK(MultiByteToWideChar (CP_ACP, 0, user_name_str, -1, ClientNameUNICODE, 256 ));
{
DPN_PLAYER_INFO Pinfo;
ZeroMemory (&Pinfo,sizeof(Pinfo));
Pinfo.dwSize = sizeof(Pinfo);
Pinfo.dwInfoFlags = DPNINFO_NAME|DPNINFO_DATA;
Pinfo.pwszName = ClientNameUNICODE;
SClientConnectData cl_data;
cl_data.process_id = GetCurrentProcessId();
strcpy_s( cl_data.name, user_name_str );
strcpy_s( cl_data.pass, user_pass );
Pinfo.pvData = &cl_data;
Pinfo.dwDataSize = sizeof(cl_data);
R_CHK(NET->SetClientInfo (&Pinfo,0,0,DPNSETCLIENTINFO_SYNC));
}
if ( stricmp( server_name, "localhost" ) == 0 )
{
WCHAR SessionPasswordUNICODE[4096];
if ( xr_strlen( password_str ) )
{
CHK_DX(MultiByteToWideChar (CP_ACP, 0, password_str, -1, SessionPasswordUNICODE, 4096 ));
dpAppDesc.dwFlags |= DPNSESSION_REQUIREPASSWORD;
dpAppDesc.pwszPassword = SessionPasswordUNICODE;
};
u32 c_port = u32(psCL_Port);
HRESULT res = S_FALSE;
while (res != S_OK && c_port <=u32(psCL_Port+100))
{
R_CHK(net_Address_device->AddComponent (DPNA_KEY_PORT, &c_port, sizeof(c_port), DPNA_DATATYPE_DWORD ));
res = NET->Connect(
&dpAppDesc, // pdnAppDesc
net_Address_server, // pHostAddr
net_Address_device, // pDeviceInfo
NULL, // pdnSecurity
NULL, // pdnCredentials
NULL, 0, // pvUserConnectData/Size
NULL, // pvAsyncContext
NULL, // pvAsyncHandle
DPNCONNECT_SYNC); // dwFlags
if (res != S_OK)
{
// xr_string res = Debug.error2string(HostSuccess);
if (bPortWasSet)
{
Msg("! IPureClient : port %d is BUSY!", c_port);
return FALSE;
}
#ifdef DEBUG
else
Msg("! IPureClient : port %d is BUSY!", c_port);
#endif
c_port++;
}
else
{
Msg("- IPureClient : created on port %d!", c_port);
}
};
// R_CHK(res);
if (res != S_OK) return FALSE;
// Create ONE node
HOST_NODE NODE;
ZeroMemory (&NODE, sizeof(HOST_NODE));
// Copy the Host Address
R_CHK (net_Address_server->Duplicate(&NODE.pHostAddress ) );
// Retreive session name
char desc[4096];
ZeroMemory (desc,sizeof(desc));
DPN_APPLICATION_DESC* dpServerDesc=(DPN_APPLICATION_DESC*)desc;
DWORD dpServerDescSize=sizeof(desc);
dpServerDesc->dwSize = sizeof(DPN_APPLICATION_DESC);
R_CHK (NET->GetApplicationDesc(dpServerDesc,&dpServerDescSize,0));
if( dpServerDesc->pwszSessionName) {
string4096 dpSessionName;
R_CHK(WideCharToMultiByte(CP_ACP,0,dpServerDesc->pwszSessionName,-1,dpSessionName,sizeof(dpSessionName),0,0));
NODE.dpSessionName = (char*)(&dpSessionName[0]);
}
net_Hosts.push_back (NODE);
} else {
string64 EnumData;
EnumData[0] = 0;
strcat (EnumData, "ToConnect");
DWORD EnumSize = xr_strlen(EnumData) + 1;
// We now have the host address so lets enum
u32 c_port = psCL_Port;
HRESULT res = S_FALSE;
while (res != S_OK && c_port <=END_PORT)
{
R_CHK(net_Address_device->AddComponent (DPNA_KEY_PORT, &c_port, sizeof(c_port), DPNA_DATATYPE_DWORD ));
res = NET->EnumHosts(
&dpAppDesc, // pApplicationDesc
net_Address_server, // pdpaddrHost
net_Address_device, // pdpaddrDeviceInfo
EnumData, EnumSize, // pvUserEnumData, size
10, // dwEnumCount
1000, // dwRetryInterval
1000, // dwTimeOut
NULL, // pvUserContext
NULL, // pAsyncHandle
DPNENUMHOSTS_SYNC // dwFlags
);
if (res != S_OK)
{
// xr_string res = Debug.error2string(HostSuccess);
switch (res)
{
case DPNERR_INVALIDHOSTADDRESS:
{
OnInvalidHost();
return FALSE;
}break;
case DPNERR_SESSIONFULL:
{
OnSessionFull();
return FALSE;
}break;
};
if (bPortWasSet)
{
Msg("! IPureClient : port %d is BUSY!", c_port);
return FALSE;
}
#ifdef DEBUG
else
Msg("! IPureClient : port %d is BUSY!", c_port);
// const char* x = DXGetErrorString9(res);
string1024 tmp = "";
DXTRACE_ERR(tmp, res);
#endif
c_port++;
}
else
{
Msg("- IPureClient : created on port %d!", c_port);
}
};
// ****** Connection
IDirectPlay8Address* pHostAddress = NULL;
if (net_Hosts.empty())
{
OnInvalidHost();
return FALSE;
};
WCHAR SessionPasswordUNICODE[4096];
if ( xr_strlen( password_str) )
{
CHK_DX(MultiByteToWideChar(CP_ACP, 0, password_str, -1, SessionPasswordUNICODE, 4096 ));
dpAppDesc.dwFlags |= DPNSESSION_REQUIREPASSWORD;
dpAppDesc.pwszPassword = SessionPasswordUNICODE;
};
net_csEnumeration.Enter ();
// real connect
for (u32 I=0; I<net_Hosts.size(); I++)
Msg("* HOST #%d: %s\n",I+1,*net_Hosts[I].dpSessionName);
R_CHK(net_Hosts.front().pHostAddress->Duplicate(&pHostAddress ) );
// dump_URL ("! c2s ", pHostAddress);
res = NET->Connect(
&dpAppDesc, // pdnAppDesc
pHostAddress, // pHostAddr
net_Address_device, // pDeviceInfo
NULL, // pdnSecurity
NULL, // pdnCredentials
NULL, 0, // pvUserConnectData/Size
NULL, // pvAsyncContext
NULL, // pvAsyncHandle
DPNCONNECT_SYNC); // dwFlags
// R_CHK(res);
net_csEnumeration.Leave ();
_RELEASE (pHostAddress);
#ifdef DEBUG
// const char* x = DXGetErrorString9(res);
string1024 tmp = "";
DXTRACE_ERR(tmp, res);
#endif
switch (res)
{
case DPNERR_INVALIDPASSWORD:
{
OnInvalidPassword();
}break;
case DPNERR_SESSIONFULL:
{
OnSessionFull();
}break;
case DPNERR_CANTCREATEPLAYER:
{
Msg("! Error: Can\'t create player");
}break;
}
if (res != S_OK) return FALSE;
}
// Caps
/*
GUID sp_guid;
DPN_SP_CAPS sp_caps;
net_Address_device->GetSP(&sp_guid);
ZeroMemory (&sp_caps,sizeof(sp_caps));
sp_caps.dwSize = sizeof(sp_caps);
R_CHK (NET->GetSPCaps(&sp_guid,&sp_caps,0));
sp_caps.dwSystemBufferSize = 0;
R_CHK (NET->SetSPCaps(&sp_guid,&sp_caps,0));
R_CHK (NET->GetSPCaps(&sp_guid,&sp_caps,0));
*/
} //psNET_direct_connect
// Sync
net_TimeDelta = 0;
return TRUE;
}
void IPureClient::Disconnect()
{
if( NET ) NET->Close(0);
// Clean up Host _list_
net_csEnumeration.Enter ();
for (u32 i=0; i<net_Hosts.size(); i++) {
HOST_NODE& N = net_Hosts[i];
_RELEASE (N.pHostAddress);
}
net_Hosts.clear ();
net_csEnumeration.Leave ();
// Release interfaces
_SHOW_REF ("cl_netADR_Server",net_Address_server);
_RELEASE (net_Address_server);
_SHOW_REF ("cl_netADR_Device",net_Address_device);
_RELEASE (net_Address_device);
_SHOW_REF ("cl_netCORE",NET);
_RELEASE (NET);
net_Connected = EnmConnectionWait;
net_Syncronised = FALSE;
}
HRESULT IPureClient::net_Handler(u32 dwMessageType, PVOID pMessage)
{
// HRESULT hr = S_OK;
switch (dwMessageType)
{
case DPN_MSGID_ENUM_HOSTS_RESPONSE:
{
PDPNMSG_ENUM_HOSTS_RESPONSE pEnumHostsResponseMsg;
const DPN_APPLICATION_DESC* pDesc;
// HOST_NODE* pHostNode = NULL;
// WCHAR* pwszSession = NULL;
pEnumHostsResponseMsg = (PDPNMSG_ENUM_HOSTS_RESPONSE) pMessage;
pDesc = pEnumHostsResponseMsg->pApplicationDescription;
// Insert each host response if it isn't already present
net_csEnumeration.Enter ();
BOOL bHostRegistered = FALSE;
for (u32 I=0; I<net_Hosts.size(); I++)
{
HOST_NODE& N = net_Hosts [I];
if ( pDesc->guidInstance == N.dpAppDesc.guidInstance)
{
// This host is already in the list
bHostRegistered = TRUE;
break;
}
}
if (!bHostRegistered)
{
// This host session is not in the list then so insert it.
HOST_NODE NODE;
ZeroMemory (&NODE, sizeof(HOST_NODE));
// Copy the Host Address
R_CHK (pEnumHostsResponseMsg->pAddressSender->Duplicate(&NODE.pHostAddress ) );
CopyMemory(&NODE.dpAppDesc,pDesc,sizeof(DPN_APPLICATION_DESC));
// Null out all the pointers we aren't copying
NODE.dpAppDesc.pwszSessionName = NULL;
NODE.dpAppDesc.pwszPassword = NULL;
NODE.dpAppDesc.pvReservedData = NULL;
NODE.dpAppDesc.dwReservedDataSize = 0;
NODE.dpAppDesc.pvApplicationReservedData = NULL;
NODE.dpAppDesc.dwApplicationReservedDataSize = 0;
if( pDesc->pwszSessionName) {
string4096 dpSessionName;
R_CHK (WideCharToMultiByte(CP_ACP,0,pDesc->pwszSessionName,-1,dpSessionName,sizeof(dpSessionName),0,0));
NODE.dpSessionName = (char*)(&dpSessionName[0]);
}
net_Hosts.push_back (NODE);
}
net_csEnumeration.Leave ();
}
break;
case DPN_MSGID_RECEIVE:
{
PDPNMSG_RECEIVE pMsg = (PDPNMSG_RECEIVE) pMessage;
MultipacketReciever::RecievePacket( pMsg->pReceiveData, pMsg->dwReceiveDataSize );
}
break;
case DPN_MSGID_TERMINATE_SESSION:
{
PDPNMSG_TERMINATE_SESSION pMsg = (PDPNMSG_TERMINATE_SESSION ) pMessage;
char* m_data = (char*)pMsg->pvTerminateData;
u32 m_size = pMsg->dwTerminateDataSize;
HRESULT m_hResultCode = pMsg->hResultCode;
net_Disconnected = TRUE;
if (m_size != 0)
{
OnSessionTerminate(m_data);
//Msg("- Session terminated : %s", m_data);
}
else
{
OnSessionTerminate( (::Debug.error2string(m_hResultCode)));
//Msg("- Session terminated : %s", (::Debug.error2string(m_hResultCode)));
}
};
break;
default:
{
#if 1
LPSTR msg = "";
switch (dwMessageType)
{
case DPN_MSGID_ADD_PLAYER_TO_GROUP: msg = "DPN_MSGID_ADD_PLAYER_TO_GROUP"; break;
case DPN_MSGID_ASYNC_OP_COMPLETE: msg = "DPN_MSGID_ASYNC_OP_COMPLETE"; break;
case DPN_MSGID_CLIENT_INFO: msg = "DPN_MSGID_CLIENT_INFO"; break;
case DPN_MSGID_CONNECT_COMPLETE:
{
PDPNMSG_CONNECT_COMPLETE pMsg = (PDPNMSG_CONNECT_COMPLETE)pMessage;
#ifdef DEBUG
// const char* x = DXGetErrorString9(pMsg->hResultCode);
if (pMsg->hResultCode != S_OK)
{
string1024 tmp="";
DXTRACE_ERR(tmp, pMsg->hResultCode);
}
#endif
if (pMsg->dwApplicationReplyDataSize)
{
string256 ResStr = "";
strncpy(ResStr, (char*)(pMsg->pvApplicationReplyData), pMsg->dwApplicationReplyDataSize);
Msg("Connection result : %s", ResStr);
}
else
msg = "DPN_MSGID_CONNECT_COMPLETE";
}break;
case DPN_MSGID_CREATE_GROUP: msg = "DPN_MSGID_CREATE_GROUP"; break;
case DPN_MSGID_CREATE_PLAYER: msg = "DPN_MSGID_CREATE_PLAYER"; break;
case DPN_MSGID_DESTROY_GROUP: msg = "DPN_MSGID_DESTROY_GROUP"; break;
case DPN_MSGID_DESTROY_PLAYER: msg = "DPN_MSGID_DESTROY_PLAYER"; break;
case DPN_MSGID_ENUM_HOSTS_QUERY: msg = "DPN_MSGID_ENUM_HOSTS_QUERY"; break;
case DPN_MSGID_GROUP_INFO: msg = "DPN_MSGID_GROUP_INFO"; break;
case DPN_MSGID_HOST_MIGRATE: msg = "DPN_MSGID_HOST_MIGRATE"; break;
case DPN_MSGID_INDICATE_CONNECT: msg = "DPN_MSGID_INDICATE_CONNECT"; break;
case DPN_MSGID_INDICATED_CONNECT_ABORTED: msg = "DPN_MSGID_INDICATED_CONNECT_ABORTED"; break;
case DPN_MSGID_PEER_INFO: msg = "DPN_MSGID_PEER_INFO"; break;
case DPN_MSGID_REMOVE_PLAYER_FROM_GROUP: msg = "DPN_MSGID_REMOVE_PLAYER_FROM_GROUP"; break;
case DPN_MSGID_RETURN_BUFFER: msg = "DPN_MSGID_RETURN_BUFFER"; break;
case DPN_MSGID_SEND_COMPLETE: msg = "DPN_MSGID_SEND_COMPLETE"; break;
case DPN_MSGID_SERVER_INFO: msg = "DPN_MSGID_SERVER_INFO"; break;
case DPN_MSGID_TERMINATE_SESSION: msg = "DPN_MSGID_TERMINATE_SESSION"; break;
default: msg = "???"; break;
}
//Msg("! ************************************ : %s",msg);
#endif
}
break;
}
return S_OK;
}
void IPureClient::OnMessage(void* data, u32 size)
{
// One of the messages - decompress it
NET_Packet* P = net_Queue.CreateGet();
P->construct (data, size);
P->timeReceive = timeServer_Async();
u16 tmp_type;
P->r_begin (tmp_type);
net_Queue.CreateCommit (P);
}
void IPureClient::timeServer_Correct(u32 sv_time, u32 cl_time)
{
u32 ping = net_Statistic.getPing();
u32 delta = sv_time + ping/2 - cl_time;
net_DeltaArray.push (delta);
Sync_Average ();
}
void IPureClient::SendTo_LL(void* data, u32 size, u32 dwFlags, u32 dwTimeout)
{
if( net_Disconnected )
return;
if( psNET_Flags.test(NETFLAG_LOG_CL_PACKETS) )
{
if( !pClNetLog)
pClNetLog = xr_new<INetLog>( "logs\\net_cl_log.log", timeServer() );
if( pClNetLog )
pClNetLog->LogData( timeServer(), data, size );
}
DPN_BUFFER_DESC desc;
desc.dwBufferSize = size;
desc.pBufferData = (BYTE*)data;
net_Statistic.dwBytesSended += size;
// verify
VERIFY(desc.dwBufferSize);
VERIFY(desc.pBufferData);
VERIFY(NET);
DPNHANDLE hAsync = 0;
HRESULT hr = NET->Send( &desc, 1, dwTimeout, 0, &hAsync, dwFlags | DPNSEND_COALESCE );
// Msg("- Client::SendTo_LL [%d]", size);
if( FAILED(hr) )
{
Msg ("! ERROR: Failed to send net-packet, reason: %s",::Debug.error2string(hr));
// const char* x = DXGetErrorString9(hr);
string1024 tmp="";
DXTRACE_ERR(tmp, hr);
}
// UpdateStatistic();
}
void IPureClient::Send( NET_Packet& packet, u32 dwFlags, u32 dwTimeout )
{
MultipacketSender::SendPacket( packet.B.data, packet.B.count, dwFlags, dwTimeout );
}
void IPureClient::Flush_Send_Buffer ()
{
MultipacketSender::FlushSendBuffer( 0 );
}
BOOL IPureClient::net_HasBandwidth ()
{
u32 dwTime = TimeGlobal(device_timer);
u32 dwInterval = 0;
if (net_Disconnected) return FALSE;
if (psNET_ClientUpdate != 0) dwInterval = 1000/psNET_ClientUpdate;
if (psNET_Flags.test(NETFLAG_MINIMIZEUPDATES)) dwInterval = 1000; // approx 3 times per second
if(psNET_direct_connect)
{
if( 0 != psNET_ClientUpdate && (dwTime-net_Time_LastUpdate)>dwInterval)
{
net_Time_LastUpdate = dwTime;
return TRUE;
}else
return FALSE;
}else
if (0 != psNET_ClientUpdate && (dwTime-net_Time_LastUpdate)>dwInterval)
{
HRESULT hr;
R_ASSERT (NET);
// check queue for "empty" state
DWORD dwPending=0;
hr = NET->GetSendQueueInfo(&dwPending,0,0);
if (FAILED(hr)) return FALSE;
if (dwPending > u32(psNET_ClientPending))
{
net_Statistic.dwTimesBlocked++;
return FALSE;
};
UpdateStatistic();
// ok
net_Time_LastUpdate = dwTime;
return TRUE;
}
return FALSE;
}
void IPureClient::UpdateStatistic()
{
// Query network statistic for this client
DPN_CONNECTION_INFO CI;
ZeroMemory (&CI,sizeof(CI));
CI.dwSize = sizeof(CI);
HRESULT hr = NET->GetConnectionInfo(&CI,0);
if (FAILED(hr)) return;
net_Statistic.Update(CI);
}
void IPureClient::Sync_Thread ()
{
MSYS_PING clPing;
//***** Ping server
net_DeltaArray.clear();
R_ASSERT (NET);
for (; NET && !net_Disconnected; )
{
// Waiting for queue empty state
if (net_Syncronised) break; // Sleep(2000);
else {
DWORD dwPending=0;
do {
R_CHK (NET->GetSendQueueInfo(&dwPending,0,0));
Sleep (1);
} while (dwPending);
}
// Construct message
clPing.sign1 = 0x12071980;
clPing.sign2 = 0x26111975;
clPing.dwTime_ClientSend = TimerAsync(device_timer);
// Send it
__try {
DPN_BUFFER_DESC desc;
DPNHANDLE hAsync=0;
desc.dwBufferSize = sizeof(clPing);
desc.pBufferData = LPBYTE(&clPing);
if (0==NET || net_Disconnected) break;
if (FAILED(NET->Send(&desc,1,0,0,&hAsync,net_flags(FALSE,FALSE,TRUE)))) {
Msg("* CLIENT: SyncThread: EXIT. (failed to send - disconnected?)");
break;
}
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
Msg("* CLIENT: SyncThread: EXIT. (failed to send - disconnected?)");
break;
}
// Waiting for reply-packet to arrive
if (!net_Syncronised) {
u32 old_size = net_DeltaArray.size();
u32 timeBegin = TimerAsync(device_timer);
while ((net_DeltaArray.size()==old_size)&&(TimerAsync(device_timer)-timeBegin<5000)) Sleep(1);
if (net_DeltaArray.size()>=syncSamples) {
net_Syncronised = TRUE;
net_TimeDelta = net_TimeDelta_Calculated;
// Msg ("* CL_TimeSync: DELTA: %d",net_TimeDelta);
}
}
}
}
void IPureClient::Sync_Average ()
{
//***** Analyze results
s64 summary_delta = 0;
s32 size = net_DeltaArray.size();
u32* I = net_DeltaArray.begin();
u32* E = I+size;
for (; I!=E; I++) summary_delta += *((int*)I);
s64 frac = s64(summary_delta) % s64(size);
if (frac<0) frac=-frac;
summary_delta /= s64(size);
if (frac>s64(size/2)) summary_delta += (summary_delta<0)?-1:1;
net_TimeDelta_Calculated= s32(summary_delta);
net_TimeDelta = (net_TimeDelta*5+net_TimeDelta_Calculated)/6;
// Msg("* CLIENT: d(%d), dc(%d), s(%d)",net_TimeDelta,net_TimeDelta_Calculated,size);
}
void sync_thread(void* P)
{
SetThreadPriority (GetCurrentThread(),THREAD_PRIORITY_TIME_CRITICAL);
IPureClient* C = (IPureClient*)P;
C->Sync_Thread ();
}
void IPureClient::net_Syncronize ()
{
net_Syncronised = FALSE;
net_DeltaArray.clear();
thread_spawn (sync_thread,"network-time-sync",0,this);
}
void IPureClient::ClearStatistic()
{
net_Statistic.Clear();
}
BOOL IPureClient::net_IsSyncronised()
{
return net_Syncronised;
}
#include <WINSOCK2.H>
#include <Ws2tcpip.h>
bool IPureClient::GetServerAddress (ip_address& pAddress, DWORD* pPort)
{
*pPort = 0;
if (!net_Address_server) return false;
WCHAR wstrHostname[ 2048 ] = {0};
DWORD dwHostNameSize = sizeof(wstrHostname);
DWORD dwHostNameDataType = DPNA_DATATYPE_STRING;
CHK_DX(net_Address_server->GetComponentByName( DPNA_KEY_HOSTNAME, wstrHostname, &dwHostNameSize, &dwHostNameDataType ));
string2048 HostName;
CHK_DX(WideCharToMultiByte(CP_ACP,0,wstrHostname,-1,HostName,sizeof(HostName),0,0));
hostent* pHostEnt = gethostbyname(HostName);
char* localIP;
localIP = inet_ntoa (*(struct in_addr *)*pHostEnt->h_addr_list);
pHostEnt = gethostbyname(pHostEnt->h_name);
localIP = inet_ntoa (*(struct in_addr *)*pHostEnt->h_addr_list);
pAddress.set (localIP);
//. pAddress[0] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_net;
//. pAddress[1] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_host;
//. pAddress[2] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_lh;
//. pAddress[3] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_impno;
DWORD dwPort = 0;
DWORD dwPortSize = sizeof(dwPort);
DWORD dwPortDataType = DPNA_DATATYPE_DWORD;
CHK_DX(net_Address_server->GetComponentByName( DPNA_KEY_PORT, &dwPort, &dwPortSize, &dwPortDataType ));
*pPort = dwPort;
return true;
};
| Java |
# IOSStudyResource
IOS学习资源整理,不定期的更新
#完整的IOS项目,具有很大的教学意义
1.https://github.com/JakeLin/SwiftWeather 一天swift版本的天气项目
2.https://github.com/xushao1990/XTNews 仿网易新闻的app,里面介绍了一些比较好的库
3.https://github.com/12207480/KnowingLife 基于天气,查询,团购,新闻类查询应用
#Xcode中不错的插件
1.https://github.com/limejelly/Backlight-for-XCode 高亮当前正在编辑的一行
2.https://github.com/FuzzyAutocomplete/FuzzyAutocompletePlugin 强大的模糊匹配输入 让你写代码的时候再也不用费脑子去记住名字那么长的对象或者函数名了 好用到让你想哭
3.
#IOS第三库依赖管理,类似Java中的maven,Android中的Gradle
1.https://github.com/CocoaPods/CocoaPods
2.https://github.com/Carthage/Carthage
#IOS中百分比布局库,自动布局可以goodbye了
1.https://github.com/jhurray/EZLayout
#带动画效果的UIPagerControl
1.https://github.com/KittenYang/KYAnimatedPageControl
2.https://github.com/Spaceman-Labs/SMPageControl
#非常不错的一个库,显示控件的PlaceHolder或者是UIView的大小
1.https://github.com/adad184/MMPlaceHolder
#UITableViewCell支持滑动显示更多操作按钮的
1.https://github.com/JonasGessner/JGScrollableTableViewCell
2.https://github.com/MortimerGoro/MGSwipeTableCell 非常强大的控件
3.https://github.com/CEWendel/SWTableViewCell 这个用的最多的一个
#IOS非常漂亮的做引导页滚动视图
1.https://github.com/IFTTT/JazzHands
#IOS中不错的菜单
1.https://github.com/12207480/DOPDropDownMenu-Enhanced 高仿美团下拉菜单-优化版
2.https://github.com/KittenYang/KYGooeyMenu 带黏贴效果的菜单
#不错的动画效果库
1.https://github.com/ArtFeel/AFViewShaker 左右震动
2.https://github.com/12207480/TYWaterWaveView 水波纹效果
#十分强大的类似ScrollView的类!提供重用视图及多种3D切换方式
1.https://github.com/nicklockwood/iCarousel
2.https://github.com/12207480/TYHorizenTableView 水平方向的UITableView
#瀑布流
1.https://github.com/ptshih/PSCollectionView
#Json解析
1.https://github.com/SwiftyJSON/SwiftyJSON swift版本
#网络解析
1.https://github.com/Alamofire/Alamofire AFNetworking的swift版本
#WebSocket
1.https://github.com/daltoniam/Starscream 支持IOS和OSX
#数据库封装
1.https://github.com/stephencelis/SQLite.swift sqlite轻量级封装
2.https://github.com/realm/realm-cocoa 志向代替Core Data和SQLite的移动数据库
#图片处理
1.https://github.com/kaishin/gifu 高性能GIF显示类库
2.https://github.com/Nyx0uf/NYXImagesKit 图片过滤等N种效果集合
#自动布局框架
1.https://github.com/robb/Cartography 基于代码级的自动布局封装框架
#进度条
1.https://github.com/kentya6/KYCircularProgress 简单、实用路径可定进程条
#测试框架
1.https://github.com/Quick/Quick 行为驱动测试框架
2.https://github.com/Quick/Nimble 匹配断言测试框架
#手势密码解锁(九宫格)
1.https://github.com/iosdeveloperpanc/PCGestureUnlock 目前最全面最高仿支付宝的手势解锁,而且提供方法进行参数修改,能解决项目开发中所有手势解锁的开发
2.https://github.com/nsdictionary/CoreLock 高仿支付宝解锁
#和Android中TabLayout、PageTab相似的PagesView控件
1.https://github.com/nsdictionary/CorePagesView
#图片选择器(支持多选)
1.https://github.com/questbeat/QBImagePicker QBImagePickerController 扩展了 UIImagePickerController 类用于支持图像的多选操作
#带placeholder的UITextView
1.https://github.com/gcamp/GCPlaceholderTextView
2.https://github.com/lukagabric/LPlaceholderTextView
#IOS视频播放器
1.https://github.com/iMoreApps/ffmpeg-avplayer-for-ios 支持多种视频编码
2.https://github.com/Bilibili/ijkplayer 非常强大的视频解码库,根据fmpeg封装,支持IOS和Android,Bilibili出品
#IOS在线音频播放器
1.https://github.com/muhku/FreeStreamer FreeStreamer是适用于iOS和OS X的音频播放引擎, 专门为播放音频流而设计。该引擎示范UI简单,效率高,占用内存少,用C++写成
#强大的日志log框架
1.https://github.com/CocoaLumberjack/CocoaLumberjack
#聊天页面UI
1.https://github.com/jessesquires/JSQMessagesViewController
#自定义显示消息和通知的框架
1.https://github.com/KrauseFx/TSMessages 在屏幕顶部
#UIWebView进度条
1.https://github.com/ninjinkun/NJKWebViewProgress 非常不错的UIWebView进度条
#UIWebView控件
1.https://github.com/TransitApp/SVWebViewController 非常不错,功能强大
#不错的卡片切换效果
1.https://github.com/cwRichardKim/TinderSimpleSwipeCards
| Java |
/*******************************************************************************
* Copyright (c) 2015-2019 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.deeplearning4j.nn.weights.embeddings;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
import org.deeplearning4j.nn.weights.IWeightInit;
import org.nd4j.common.base.Preconditions;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.shade.jackson.annotation.JsonIgnoreProperties;
import org.nd4j.shade.jackson.annotation.JsonProperty;
/**
* Weight initialization for initializing the parameters of an EmbeddingLayer from a {@link EmbeddingInitializer}
*
* Note: WeightInitEmbedding supports both JSON serializable and non JSON serializable initializations.
* In the case of non-JSON serializable embeddings, they are a one-time only use: once they have been used
* to initialize the parameters, they will be removed from the WeightInitEmbedding instance.
* This is to prevent unnecessary references to potentially large objects in memory (i.e., to avoid memory leaks)
*
* @author Alex Black
*/
@JsonIgnoreProperties("nonSerializableInit")
@EqualsAndHashCode
public class WeightInitEmbedding implements IWeightInit {
private EmbeddingInitializer serializableInit;
private EmbeddingInitializer nonSerializableInit;
public WeightInitEmbedding(@NonNull EmbeddingInitializer embeddingInitializer){
this((embeddingInitializer.jsonSerializable() ? embeddingInitializer : null), (embeddingInitializer.jsonSerializable() ? null : embeddingInitializer));
}
protected WeightInitEmbedding(@JsonProperty("serializableInit") EmbeddingInitializer serializableInit,
@JsonProperty("nonSerializableInit") EmbeddingInitializer nonSerializableInit){
this.serializableInit = serializableInit;
this.nonSerializableInit = nonSerializableInit;
}
@Override
public INDArray init(double fanIn, double fanOut, long[] shape, char order, INDArray paramView) {
EmbeddingInitializer init = serializableInit != null ? serializableInit : nonSerializableInit;
if(init == null){
throw new IllegalStateException("Cannot initialize embedding layer weights: no EmbeddingInitializer is available." +
" This can occur if you save network configuration, load it, and the try to ");
}
Preconditions.checkState(shape[0] == init.vocabSize(), "Parameters shape[0]=%s does not match embedding initializer vocab size of %s", shape[0], init.vocabSize());
Preconditions.checkState(shape[1] == init.vectorSize(), "Parameters shape[1]=%s does not match embedding initializer vector size of %s", shape[1], init.vectorSize());
INDArray reshaped = paramView.reshape('c', shape);
init.loadWeightsInto(reshaped);
//Now that we've loaded weights - let's clear the reference if it's non-serializable so it can be GC'd
this.nonSerializableInit = null;
return reshaped;
}
public long[] shape(){
if(serializableInit != null){
return new long[]{serializableInit.vocabSize(), serializableInit.vectorSize()};
} else if(nonSerializableInit != null){
return new long[]{nonSerializableInit.vocabSize(), nonSerializableInit.vectorSize()};
}
return null;
}
}
| Java |
# coding=utf-8
# Copyright 2012 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2012 NTT DOCOMO, INC.
# Copyright 2014 International Business Machines Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# 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.
"""
IPMI power manager driver.
Uses the 'ipmitool' command (http://ipmitool.sourceforge.net/) to remotely
manage hardware. This includes setting the boot device, getting a
serial-over-LAN console, and controlling the power state of the machine.
NOTE THAT CERTAIN DISTROS MAY INSTALL openipmi BY DEFAULT, INSTEAD OF ipmitool,
WHICH PROVIDES DIFFERENT COMMAND-LINE OPTIONS AND *IS NOT SUPPORTED* BY THIS
DRIVER.
"""
import contextlib
import os
import re
import subprocess
import tempfile
import time
from oslo_concurrency import processutils
from oslo_config import cfg
from oslo_log import log as logging
from oslo_service import loopingcall
from oslo_utils import excutils
from ironic.common import boot_devices
from ironic.common import exception
from ironic.common.i18n import _
from ironic.common.i18n import _LE
from ironic.common.i18n import _LI
from ironic.common.i18n import _LW
from ironic.common import states
from ironic.common import utils
from ironic.conductor import task_manager
from ironic.drivers import base
from ironic.drivers.modules import console_utils
CONF = cfg.CONF
CONF.import_opt('retry_timeout',
'ironic.drivers.modules.ipminative',
group='ipmi')
CONF.import_opt('min_command_interval',
'ironic.drivers.modules.ipminative',
group='ipmi')
LOG = logging.getLogger(__name__)
VALID_PRIV_LEVELS = ['ADMINISTRATOR', 'CALLBACK', 'OPERATOR', 'USER']
VALID_PROTO_VERSIONS = ('2.0', '1.5')
REQUIRED_PROPERTIES = {
'ipmi_address': _("IP address or hostname of the node. Required.")
}
OPTIONAL_PROPERTIES = {
'ipmi_password': _("password. Optional."),
'ipmi_priv_level': _("privilege level; default is ADMINISTRATOR. One of "
"%s. Optional.") % ', '.join(VALID_PRIV_LEVELS),
'ipmi_username': _("username; default is NULL user. Optional."),
'ipmi_bridging': _("bridging_type; default is \"no\". One of \"single\", "
"\"dual\", \"no\". Optional."),
'ipmi_transit_channel': _("transit channel for bridged request. Required "
"only if ipmi_bridging is set to \"dual\"."),
'ipmi_transit_address': _("transit address for bridged request. Required "
"only if ipmi_bridging is set to \"dual\"."),
'ipmi_target_channel': _("destination channel for bridged request. "
"Required only if ipmi_bridging is set to "
"\"single\" or \"dual\"."),
'ipmi_target_address': _("destination address for bridged request. "
"Required only if ipmi_bridging is set "
"to \"single\" or \"dual\"."),
'ipmi_local_address': _("local IPMB address for bridged requests. "
"Used only if ipmi_bridging is set "
"to \"single\" or \"dual\". Optional."),
'ipmi_protocol_version': _('the version of the IPMI protocol; default '
'is "2.0". One of "1.5", "2.0". Optional.'),
}
COMMON_PROPERTIES = REQUIRED_PROPERTIES.copy()
COMMON_PROPERTIES.update(OPTIONAL_PROPERTIES)
CONSOLE_PROPERTIES = {
'ipmi_terminal_port': _("node's UDP port to connect to. Only required for "
"console access.")
}
BRIDGING_OPTIONS = [('local_address', '-m'),
('transit_channel', '-B'), ('transit_address', '-T'),
('target_channel', '-b'), ('target_address', '-t')]
LAST_CMD_TIME = {}
TIMING_SUPPORT = None
SINGLE_BRIDGE_SUPPORT = None
DUAL_BRIDGE_SUPPORT = None
TMP_DIR_CHECKED = None
ipmitool_command_options = {
'timing': ['ipmitool', '-N', '0', '-R', '0', '-h'],
'single_bridge': ['ipmitool', '-m', '0', '-b', '0', '-t', '0', '-h'],
'dual_bridge': ['ipmitool', '-m', '0', '-b', '0', '-t', '0',
'-B', '0', '-T', '0', '-h']}
# Note(TheJulia): This string is hardcoded in ipmitool's lanplus driver
# and is substituted in return for the error code received from the IPMI
# controller. As of 1.8.15, no internationalization support appears to
# be in ipmitool which means the string should always be returned in this
# form regardless of locale.
IPMITOOL_RETRYABLE_FAILURES = ['insufficient resources for session']
def _check_option_support(options):
"""Checks if the specific ipmitool options are supported on host.
This method updates the module-level variables indicating whether
an option is supported so that it is accessible by any driver
interface class in this module. It is intended to be called from
the __init__ method of such classes only.
:param options: list of ipmitool options to be checked
:raises: OSError
"""
for opt in options:
if _is_option_supported(opt) is None:
try:
cmd = ipmitool_command_options[opt]
# NOTE(cinerama): use subprocess.check_call to
# check options & suppress ipmitool output to
# avoid alarming people
with open(os.devnull, 'wb') as nullfile:
subprocess.check_call(cmd, stdout=nullfile,
stderr=nullfile)
except subprocess.CalledProcessError:
LOG.info(_LI("Option %(opt)s is not supported by ipmitool"),
{'opt': opt})
_is_option_supported(opt, False)
else:
LOG.info(_LI("Option %(opt)s is supported by ipmitool"),
{'opt': opt})
_is_option_supported(opt, True)
def _is_option_supported(option, is_supported=None):
"""Indicates whether the particular ipmitool option is supported.
:param option: specific ipmitool option
:param is_supported: Optional Boolean. when specified, this value
is assigned to the module-level variable indicating
whether the option is supported. Used only if a value
is not already assigned.
:returns: True, indicates the option is supported
:returns: False, indicates the option is not supported
:returns: None, indicates that it is not aware whether the option
is supported
"""
global SINGLE_BRIDGE_SUPPORT
global DUAL_BRIDGE_SUPPORT
global TIMING_SUPPORT
if option == 'single_bridge':
if (SINGLE_BRIDGE_SUPPORT is None) and (is_supported is not None):
SINGLE_BRIDGE_SUPPORT = is_supported
return SINGLE_BRIDGE_SUPPORT
elif option == 'dual_bridge':
if (DUAL_BRIDGE_SUPPORT is None) and (is_supported is not None):
DUAL_BRIDGE_SUPPORT = is_supported
return DUAL_BRIDGE_SUPPORT
elif option == 'timing':
if (TIMING_SUPPORT is None) and (is_supported is not None):
TIMING_SUPPORT = is_supported
return TIMING_SUPPORT
def _console_pwfile_path(uuid):
"""Return the file path for storing the ipmi password for a console."""
file_name = "%(uuid)s.pw" % {'uuid': uuid}
return os.path.join(CONF.tempdir, file_name)
@contextlib.contextmanager
def _make_password_file(password):
"""Makes a temporary file that contains the password.
:param password: the password
:returns: the absolute pathname of the temporary file
:raises: PasswordFileFailedToCreate from creating or writing to the
temporary file
"""
f = None
try:
f = tempfile.NamedTemporaryFile(mode='w', dir=CONF.tempdir)
f.write(str(password))
f.flush()
except (IOError, OSError) as exc:
if f is not None:
f.close()
raise exception.PasswordFileFailedToCreate(error=exc)
except Exception:
with excutils.save_and_reraise_exception():
if f is not None:
f.close()
try:
# NOTE(jlvillal): This yield can not be in the try/except block above
# because an exception by the caller of this function would then get
# changed to a PasswordFileFailedToCreate exception which would mislead
# about the problem and its cause.
yield f.name
finally:
if f is not None:
f.close()
def _parse_driver_info(node):
"""Gets the parameters required for ipmitool to access the node.
:param node: the Node of interest.
:returns: dictionary of parameters.
:raises: InvalidParameterValue when an invalid value is specified
:raises: MissingParameterValue when a required ipmi parameter is missing.
"""
info = node.driver_info or {}
bridging_types = ['single', 'dual']
missing_info = [key for key in REQUIRED_PROPERTIES if not info.get(key)]
if missing_info:
raise exception.MissingParameterValue(_(
"Missing the following IPMI credentials in node's"
" driver_info: %s.") % missing_info)
address = info.get('ipmi_address')
username = info.get('ipmi_username')
password = info.get('ipmi_password')
port = info.get('ipmi_terminal_port')
priv_level = info.get('ipmi_priv_level', 'ADMINISTRATOR')
bridging_type = info.get('ipmi_bridging', 'no')
local_address = info.get('ipmi_local_address')
transit_channel = info.get('ipmi_transit_channel')
transit_address = info.get('ipmi_transit_address')
target_channel = info.get('ipmi_target_channel')
target_address = info.get('ipmi_target_address')
protocol_version = str(info.get('ipmi_protocol_version', '2.0'))
if protocol_version not in VALID_PROTO_VERSIONS:
valid_versions = ', '.join(VALID_PROTO_VERSIONS)
raise exception.InvalidParameterValue(_(
"Invalid IPMI protocol version value %(version)s, the valid "
"value can be one of %(valid_versions)s") %
{'version': protocol_version, 'valid_versions': valid_versions})
if port:
try:
port = int(port)
except ValueError:
raise exception.InvalidParameterValue(_(
"IPMI terminal port is not an integer."))
# check if ipmi_bridging has proper value
if bridging_type == 'no':
# if bridging is not selected, then set all bridging params to None
(local_address, transit_channel, transit_address, target_channel,
target_address) = (None,) * 5
elif bridging_type in bridging_types:
# check if the particular bridging option is supported on host
if not _is_option_supported('%s_bridge' % bridging_type):
raise exception.InvalidParameterValue(_(
"Value for ipmi_bridging is provided as %s, but IPMI "
"bridging is not supported by the IPMI utility installed "
"on host. Ensure ipmitool version is > 1.8.11"
) % bridging_type)
# ensure that all the required parameters are provided
params_undefined = [param for param, value in [
("ipmi_target_channel", target_channel),
('ipmi_target_address', target_address)] if value is None]
if bridging_type == 'dual':
params_undefined2 = [param for param, value in [
("ipmi_transit_channel", transit_channel),
('ipmi_transit_address', transit_address)
] if value is None]
params_undefined.extend(params_undefined2)
else:
# if single bridging was selected, set dual bridge params to None
transit_channel = transit_address = None
# If the required parameters were not provided,
# raise an exception
if params_undefined:
raise exception.MissingParameterValue(_(
"%(param)s not provided") % {'param': params_undefined})
else:
raise exception.InvalidParameterValue(_(
"Invalid value for ipmi_bridging: %(bridging_type)s,"
" the valid value can be one of: %(bridging_types)s"
) % {'bridging_type': bridging_type,
'bridging_types': bridging_types + ['no']})
if priv_level not in VALID_PRIV_LEVELS:
valid_priv_lvls = ', '.join(VALID_PRIV_LEVELS)
raise exception.InvalidParameterValue(_(
"Invalid privilege level value:%(priv_level)s, the valid value"
" can be one of %(valid_levels)s") %
{'priv_level': priv_level, 'valid_levels': valid_priv_lvls})
return {
'address': address,
'username': username,
'password': password,
'port': port,
'uuid': node.uuid,
'priv_level': priv_level,
'local_address': local_address,
'transit_channel': transit_channel,
'transit_address': transit_address,
'target_channel': target_channel,
'target_address': target_address,
'protocol_version': protocol_version,
}
def _exec_ipmitool(driver_info, command):
"""Execute the ipmitool command.
:param driver_info: the ipmitool parameters for accessing a node.
:param command: the ipmitool command to be executed.
:returns: (stdout, stderr) from executing the command.
:raises: PasswordFileFailedToCreate from creating or writing to the
temporary file.
:raises: processutils.ProcessExecutionError from executing the command.
"""
ipmi_version = ('lanplus'
if driver_info['protocol_version'] == '2.0'
else 'lan')
args = ['ipmitool',
'-I',
ipmi_version,
'-H',
driver_info['address'],
'-L', driver_info['priv_level']
]
if driver_info['username']:
args.append('-U')
args.append(driver_info['username'])
for name, option in BRIDGING_OPTIONS:
if driver_info[name] is not None:
args.append(option)
args.append(driver_info[name])
# specify retry timing more precisely, if supported
num_tries = max(
(CONF.ipmi.retry_timeout // CONF.ipmi.min_command_interval), 1)
if _is_option_supported('timing'):
args.append('-R')
args.append(str(num_tries))
args.append('-N')
args.append(str(CONF.ipmi.min_command_interval))
end_time = (time.time() + CONF.ipmi.retry_timeout)
while True:
num_tries = num_tries - 1
# NOTE(deva): ensure that no communications are sent to a BMC more
# often than once every min_command_interval seconds.
time_till_next_poll = CONF.ipmi.min_command_interval - (
time.time() - LAST_CMD_TIME.get(driver_info['address'], 0))
if time_till_next_poll > 0:
time.sleep(time_till_next_poll)
# Resetting the list that will be utilized so the password arguments
# from any previous execution are preserved.
cmd_args = args[:]
# 'ipmitool' command will prompt password if there is no '-f'
# option, we set it to '\0' to write a password file to support
# empty password
with _make_password_file(driver_info['password'] or '\0') as pw_file:
cmd_args.append('-f')
cmd_args.append(pw_file)
cmd_args.extend(command.split(" "))
try:
out, err = utils.execute(*cmd_args)
return out, err
except processutils.ProcessExecutionError as e:
with excutils.save_and_reraise_exception() as ctxt:
err_list = [x for x in IPMITOOL_RETRYABLE_FAILURES
if x in e.args[0]]
if ((time.time() > end_time) or
(num_tries == 0) or
not err_list):
LOG.error(_LE('IPMI Error while attempting "%(cmd)s"'
'for node %(node)s. Error: %(error)s'), {
'node': driver_info['uuid'],
'cmd': e.cmd, 'error': e
})
else:
ctxt.reraise = False
LOG.warning(_LW('IPMI Error encountered, retrying '
'"%(cmd)s" for node %(node)s. '
'Error: %(error)s'), {
'node': driver_info['uuid'],
'cmd': e.cmd, 'error': e
})
finally:
LAST_CMD_TIME[driver_info['address']] = time.time()
def _sleep_time(iter):
"""Return the time-to-sleep for the n'th iteration of a retry loop.
This implementation increases exponentially.
:param iter: iteration number
:returns: number of seconds to sleep
"""
if iter <= 1:
return 1
return iter ** 2
def _set_and_wait(target_state, driver_info):
"""Helper function for DynamicLoopingCall.
This method changes the power state and polls the BMCuntil the desired
power state is reached, or CONF.ipmi.retry_timeout would be exceeded by the
next iteration.
This method assumes the caller knows the current power state and does not
check it prior to changing the power state. Most BMCs should be fine, but
if a driver is concerned, the state should be checked prior to calling this
method.
:param target_state: desired power state
:param driver_info: the ipmitool parameters for accessing a node.
:returns: one of ironic.common.states
"""
if target_state == states.POWER_ON:
state_name = "on"
elif target_state == states.POWER_OFF:
state_name = "off"
def _wait(mutable):
try:
# Only issue power change command once
if mutable['iter'] < 0:
_exec_ipmitool(driver_info, "power %s" % state_name)
else:
mutable['power'] = _power_status(driver_info)
except (exception.PasswordFileFailedToCreate,
processutils.ProcessExecutionError,
exception.IPMIFailure):
# Log failures but keep trying
LOG.warning(_LW("IPMI power %(state)s failed for node %(node)s."),
{'state': state_name, 'node': driver_info['uuid']})
finally:
mutable['iter'] += 1
if mutable['power'] == target_state:
raise loopingcall.LoopingCallDone()
sleep_time = _sleep_time(mutable['iter'])
if (sleep_time + mutable['total_time']) > CONF.ipmi.retry_timeout:
# Stop if the next loop would exceed maximum retry_timeout
LOG.error(_LE('IPMI power %(state)s timed out after '
'%(tries)s retries on node %(node_id)s.'),
{'state': state_name, 'tries': mutable['iter'],
'node_id': driver_info['uuid']})
mutable['power'] = states.ERROR
raise loopingcall.LoopingCallDone()
else:
mutable['total_time'] += sleep_time
return sleep_time
# Use mutable objects so the looped method can change them.
# Start 'iter' from -1 so that the first two checks are one second apart.
status = {'power': None, 'iter': -1, 'total_time': 0}
timer = loopingcall.DynamicLoopingCall(_wait, status)
timer.start().wait()
return status['power']
def _power_on(driver_info):
"""Turn the power ON for this node.
:param driver_info: the ipmitool parameters for accessing a node.
:returns: one of ironic.common.states POWER_ON or ERROR.
:raises: IPMIFailure on an error from ipmitool (from _power_status call).
"""
return _set_and_wait(states.POWER_ON, driver_info)
def _power_off(driver_info):
"""Turn the power OFF for this node.
:param driver_info: the ipmitool parameters for accessing a node.
:returns: one of ironic.common.states POWER_OFF or ERROR.
:raises: IPMIFailure on an error from ipmitool (from _power_status call).
"""
return _set_and_wait(states.POWER_OFF, driver_info)
def _power_status(driver_info):
"""Get the power status for a node.
:param driver_info: the ipmitool access parameters for a node.
:returns: one of ironic.common.states POWER_OFF, POWER_ON or ERROR.
:raises: IPMIFailure on an error from ipmitool.
"""
cmd = "power status"
try:
out_err = _exec_ipmitool(driver_info, cmd)
except (exception.PasswordFileFailedToCreate,
processutils.ProcessExecutionError) as e:
LOG.warning(_LW("IPMI power status failed for node %(node_id)s with "
"error: %(error)s."),
{'node_id': driver_info['uuid'], 'error': e})
raise exception.IPMIFailure(cmd=cmd)
if out_err[0] == "Chassis Power is on\n":
return states.POWER_ON
elif out_err[0] == "Chassis Power is off\n":
return states.POWER_OFF
else:
return states.ERROR
def _process_sensor(sensor_data):
sensor_data_fields = sensor_data.split('\n')
sensor_data_dict = {}
for field in sensor_data_fields:
if not field:
continue
kv_value = field.split(':')
if len(kv_value) != 2:
continue
sensor_data_dict[kv_value[0].strip()] = kv_value[1].strip()
return sensor_data_dict
def _get_sensor_type(node, sensor_data_dict):
# Have only three sensor type name IDs: 'Sensor Type (Analog)'
# 'Sensor Type (Discrete)' and 'Sensor Type (Threshold)'
for key in ('Sensor Type (Analog)', 'Sensor Type (Discrete)',
'Sensor Type (Threshold)'):
try:
return sensor_data_dict[key].split(' ', 1)[0]
except KeyError:
continue
raise exception.FailedToParseSensorData(
node=node.uuid,
error=(_("parse ipmi sensor data failed, unknown sensor type"
" data: %(sensors_data)s"),
{'sensors_data': sensor_data_dict}))
def _parse_ipmi_sensors_data(node, sensors_data):
"""Parse the IPMI sensors data and format to the dict grouping by type.
We run 'ipmitool' command with 'sdr -v' options, which can return sensor
details in human-readable format, we need to format them to JSON string
dict-based data for Ceilometer Collector which can be sent it as payload
out via notification bus and consumed by Ceilometer Collector.
:param sensors_data: the sensor data returned by ipmitool command.
:returns: the sensor data with JSON format, grouped by sensor type.
:raises: FailedToParseSensorData when error encountered during parsing.
"""
sensors_data_dict = {}
if not sensors_data:
return sensors_data_dict
sensors_data_array = sensors_data.split('\n\n')
for sensor_data in sensors_data_array:
sensor_data_dict = _process_sensor(sensor_data)
if not sensor_data_dict:
continue
sensor_type = _get_sensor_type(node, sensor_data_dict)
# ignore the sensors which has no current 'Sensor Reading' data
if 'Sensor Reading' in sensor_data_dict:
sensors_data_dict.setdefault(
sensor_type,
{})[sensor_data_dict['Sensor ID']] = sensor_data_dict
# get nothing, no valid sensor data
if not sensors_data_dict:
raise exception.FailedToParseSensorData(
node=node.uuid,
error=(_("parse ipmi sensor data failed, get nothing with input"
" data: %(sensors_data)s")
% {'sensors_data': sensors_data}))
return sensors_data_dict
@task_manager.require_exclusive_lock
def send_raw(task, raw_bytes):
"""Send raw bytes to the BMC. Bytes should be a string of bytes.
:param task: a TaskManager instance.
:param raw_bytes: a string of raw bytes to send, e.g. '0x00 0x01'
:raises: IPMIFailure on an error from ipmitool.
:raises: MissingParameterValue if a required parameter is missing.
:raises: InvalidParameterValue when an invalid value is specified.
"""
node_uuid = task.node.uuid
LOG.debug('Sending node %(node)s raw bytes %(bytes)s',
{'bytes': raw_bytes, 'node': node_uuid})
driver_info = _parse_driver_info(task.node)
cmd = 'raw %s' % raw_bytes
try:
out, err = _exec_ipmitool(driver_info, cmd)
LOG.debug('send raw bytes returned stdout: %(stdout)s, stderr:'
' %(stderr)s', {'stdout': out, 'stderr': err})
except (exception.PasswordFileFailedToCreate,
processutils.ProcessExecutionError) as e:
LOG.exception(_LE('IPMI "raw bytes" failed for node %(node_id)s '
'with error: %(error)s.'),
{'node_id': node_uuid, 'error': e})
raise exception.IPMIFailure(cmd=cmd)
def _check_temp_dir():
"""Check for Valid temp directory."""
global TMP_DIR_CHECKED
# because a temporary file is used to pass the password to ipmitool,
# we should check the directory
if TMP_DIR_CHECKED is None:
try:
utils.check_dir()
except (exception.PathNotFound,
exception.DirectoryNotWritable,
exception.InsufficientDiskSpace) as e:
with excutils.save_and_reraise_exception():
TMP_DIR_CHECKED = False
err_msg = (_("Ipmitool drivers need to be able to create "
"temporary files to pass password to ipmitool. "
"Encountered error: %s") % e)
e.message = err_msg
LOG.error(err_msg)
else:
TMP_DIR_CHECKED = True
class IPMIPower(base.PowerInterface):
def __init__(self):
try:
_check_option_support(['timing', 'single_bridge', 'dual_bridge'])
except OSError:
raise exception.DriverLoadError(
driver=self.__class__.__name__,
reason=_("Unable to locate usable ipmitool command in "
"the system path when checking ipmitool version"))
_check_temp_dir()
def get_properties(self):
return COMMON_PROPERTIES
def validate(self, task):
"""Validate driver_info for ipmitool driver.
Check that node['driver_info'] contains IPMI credentials.
:param task: a TaskManager instance containing the node to act on.
:raises: InvalidParameterValue if required ipmi parameters are missing.
:raises: MissingParameterValue if a required parameter is missing.
"""
_parse_driver_info(task.node)
# NOTE(deva): don't actually touch the BMC in validate because it is
# called too often, and BMCs are too fragile.
# This is a temporary measure to mitigate problems while
# 1314954 and 1314961 are resolved.
def get_power_state(self, task):
"""Get the current power state of the task's node.
:param task: a TaskManager instance containing the node to act on.
:returns: one of ironic.common.states POWER_OFF, POWER_ON or ERROR.
:raises: InvalidParameterValue if required ipmi parameters are missing.
:raises: MissingParameterValue if a required parameter is missing.
:raises: IPMIFailure on an error from ipmitool (from _power_status
call).
"""
driver_info = _parse_driver_info(task.node)
return _power_status(driver_info)
@task_manager.require_exclusive_lock
def set_power_state(self, task, pstate):
"""Turn the power on or off.
:param task: a TaskManager instance containing the node to act on.
:param pstate: The desired power state, one of ironic.common.states
POWER_ON, POWER_OFF.
:raises: InvalidParameterValue if an invalid power state was specified.
:raises: MissingParameterValue if required ipmi parameters are missing
:raises: PowerStateFailure if the power couldn't be set to pstate.
"""
driver_info = _parse_driver_info(task.node)
if pstate == states.POWER_ON:
state = _power_on(driver_info)
elif pstate == states.POWER_OFF:
state = _power_off(driver_info)
else:
raise exception.InvalidParameterValue(
_("set_power_state called "
"with invalid power state %s.") % pstate)
if state != pstate:
raise exception.PowerStateFailure(pstate=pstate)
@task_manager.require_exclusive_lock
def reboot(self, task):
"""Cycles the power to the task's node.
:param task: a TaskManager instance containing the node to act on.
:raises: MissingParameterValue if required ipmi parameters are missing.
:raises: InvalidParameterValue if an invalid power state was specified.
:raises: PowerStateFailure if the final state of the node is not
POWER_ON.
"""
driver_info = _parse_driver_info(task.node)
_power_off(driver_info)
state = _power_on(driver_info)
if state != states.POWER_ON:
raise exception.PowerStateFailure(pstate=states.POWER_ON)
class IPMIManagement(base.ManagementInterface):
def get_properties(self):
return COMMON_PROPERTIES
def __init__(self):
try:
_check_option_support(['timing', 'single_bridge', 'dual_bridge'])
except OSError:
raise exception.DriverLoadError(
driver=self.__class__.__name__,
reason=_("Unable to locate usable ipmitool command in "
"the system path when checking ipmitool version"))
_check_temp_dir()
def validate(self, task):
"""Check that 'driver_info' contains IPMI credentials.
Validates whether the 'driver_info' property of the supplied
task's node contains the required credentials information.
:param task: a task from TaskManager.
:raises: InvalidParameterValue if required IPMI parameters
are missing.
:raises: MissingParameterValue if a required parameter is missing.
"""
_parse_driver_info(task.node)
def get_supported_boot_devices(self, task):
"""Get a list of the supported boot devices.
:param task: a task from TaskManager.
:returns: A list with the supported boot devices defined
in :mod:`ironic.common.boot_devices`.
"""
return [boot_devices.PXE, boot_devices.DISK, boot_devices.CDROM,
boot_devices.BIOS, boot_devices.SAFE]
@task_manager.require_exclusive_lock
def set_boot_device(self, task, device, persistent=False):
"""Set the boot device for the task's node.
Set the boot device to use on next reboot of the node.
:param task: a task from TaskManager.
:param device: the boot device, one of
:mod:`ironic.common.boot_devices`.
:param persistent: Boolean value. True if the boot device will
persist to all future boots, False if not.
Default: False.
:raises: InvalidParameterValue if an invalid boot device is specified
:raises: MissingParameterValue if required ipmi parameters are missing.
:raises: IPMIFailure on an error from ipmitool.
"""
if device not in self.get_supported_boot_devices(task):
raise exception.InvalidParameterValue(_(
"Invalid boot device %s specified.") % device)
# note(JayF): IPMI spec indicates unless you send these raw bytes the
# boot device setting times out after 60s. Since it's possible it
# could be >60s before a node is rebooted, we should always send them.
# This mimics pyghmi's current behavior, and the "option=timeout"
# setting on newer ipmitool binaries.
timeout_disable = "0x00 0x08 0x03 0x08"
send_raw(task, timeout_disable)
cmd = "chassis bootdev %s" % device
if persistent:
cmd = cmd + " options=persistent"
driver_info = _parse_driver_info(task.node)
try:
out, err = _exec_ipmitool(driver_info, cmd)
except (exception.PasswordFileFailedToCreate,
processutils.ProcessExecutionError) as e:
LOG.warning(_LW('IPMI set boot device failed for node %(node)s '
'when executing "ipmitool %(cmd)s". '
'Error: %(error)s'),
{'node': driver_info['uuid'], 'cmd': cmd, 'error': e})
raise exception.IPMIFailure(cmd=cmd)
def get_boot_device(self, task):
"""Get the current boot device for the task's node.
Returns the current boot device of the node.
:param task: a task from TaskManager.
:raises: InvalidParameterValue if required IPMI parameters
are missing.
:raises: IPMIFailure on an error from ipmitool.
:raises: MissingParameterValue if a required parameter is missing.
:returns: a dictionary containing:
:boot_device: the boot device, one of
:mod:`ironic.common.boot_devices` or None if it is unknown.
:persistent: Whether the boot device will persist to all
future boots or not, None if it is unknown.
"""
cmd = "chassis bootparam get 5"
driver_info = _parse_driver_info(task.node)
response = {'boot_device': None, 'persistent': None}
try:
out, err = _exec_ipmitool(driver_info, cmd)
except (exception.PasswordFileFailedToCreate,
processutils.ProcessExecutionError) as e:
LOG.warning(_LW('IPMI get boot device failed for node %(node)s '
'when executing "ipmitool %(cmd)s". '
'Error: %(error)s'),
{'node': driver_info['uuid'], 'cmd': cmd, 'error': e})
raise exception.IPMIFailure(cmd=cmd)
re_obj = re.search('Boot Device Selector : (.+)?\n', out)
if re_obj:
boot_selector = re_obj.groups('')[0]
if 'PXE' in boot_selector:
response['boot_device'] = boot_devices.PXE
elif 'Hard-Drive' in boot_selector:
if 'Safe-Mode' in boot_selector:
response['boot_device'] = boot_devices.SAFE
else:
response['boot_device'] = boot_devices.DISK
elif 'BIOS' in boot_selector:
response['boot_device'] = boot_devices.BIOS
elif 'CD/DVD' in boot_selector:
response['boot_device'] = boot_devices.CDROM
response['persistent'] = 'Options apply to all future boots' in out
return response
def get_sensors_data(self, task):
"""Get sensors data.
:param task: a TaskManager instance.
:raises: FailedToGetSensorData when getting the sensor data fails.
:raises: FailedToParseSensorData when parsing sensor data fails.
:raises: InvalidParameterValue if required ipmi parameters are missing
:raises: MissingParameterValue if a required parameter is missing.
:returns: returns a dict of sensor data group by sensor type.
"""
driver_info = _parse_driver_info(task.node)
# with '-v' option, we can get the entire sensor data including the
# extended sensor informations
cmd = "sdr -v"
try:
out, err = _exec_ipmitool(driver_info, cmd)
except (exception.PasswordFileFailedToCreate,
processutils.ProcessExecutionError) as e:
raise exception.FailedToGetSensorData(node=task.node.uuid,
error=e)
return _parse_ipmi_sensors_data(task.node, out)
class VendorPassthru(base.VendorInterface):
def __init__(self):
try:
_check_option_support(['single_bridge', 'dual_bridge'])
except OSError:
raise exception.DriverLoadError(
driver=self.__class__.__name__,
reason=_("Unable to locate usable ipmitool command in "
"the system path when checking ipmitool version"))
_check_temp_dir()
@base.passthru(['POST'])
@task_manager.require_exclusive_lock
def send_raw(self, task, http_method, raw_bytes):
"""Send raw bytes to the BMC. Bytes should be a string of bytes.
:param task: a TaskManager instance.
:param http_method: the HTTP method used on the request.
:param raw_bytes: a string of raw bytes to send, e.g. '0x00 0x01'
:raises: IPMIFailure on an error from ipmitool.
:raises: MissingParameterValue if a required parameter is missing.
:raises: InvalidParameterValue when an invalid value is specified.
"""
send_raw(task, raw_bytes)
@base.passthru(['POST'])
@task_manager.require_exclusive_lock
def bmc_reset(self, task, http_method, warm=True):
"""Reset BMC with IPMI command 'bmc reset (warm|cold)'.
:param task: a TaskManager instance.
:param http_method: the HTTP method used on the request.
:param warm: boolean parameter to decide on warm or cold reset.
:raises: IPMIFailure on an error from ipmitool.
:raises: MissingParameterValue if a required parameter is missing.
:raises: InvalidParameterValue when an invalid value is specified
"""
node_uuid = task.node.uuid
if warm:
warm_param = 'warm'
else:
warm_param = 'cold'
LOG.debug('Doing %(warm)s BMC reset on node %(node)s',
{'warm': warm_param, 'node': node_uuid})
driver_info = _parse_driver_info(task.node)
cmd = 'bmc reset %s' % warm_param
try:
out, err = _exec_ipmitool(driver_info, cmd)
LOG.debug('bmc reset returned stdout: %(stdout)s, stderr:'
' %(stderr)s', {'stdout': out, 'stderr': err})
except (exception.PasswordFileFailedToCreate,
processutils.ProcessExecutionError) as e:
LOG.exception(_LE('IPMI "bmc reset" failed for node %(node_id)s '
'with error: %(error)s.'),
{'node_id': node_uuid, 'error': e})
raise exception.IPMIFailure(cmd=cmd)
def get_properties(self):
return COMMON_PROPERTIES
def validate(self, task, method, **kwargs):
"""Validate vendor-specific actions.
If invalid, raises an exception; otherwise returns None.
Valid methods:
* send_raw
* bmc_reset
:param task: a task from TaskManager.
:param method: method to be validated
:param kwargs: info for action.
:raises: InvalidParameterValue when an invalid parameter value is
specified.
:raises: MissingParameterValue if a required parameter is missing.
"""
if method == 'send_raw':
if not kwargs.get('raw_bytes'):
raise exception.MissingParameterValue(_(
'Parameter raw_bytes (string of bytes) was not '
'specified.'))
_parse_driver_info(task.node)
class IPMIShellinaboxConsole(base.ConsoleInterface):
"""A ConsoleInterface that uses ipmitool and shellinabox."""
def __init__(self):
try:
_check_option_support(['timing', 'single_bridge', 'dual_bridge'])
except OSError:
raise exception.DriverLoadError(
driver=self.__class__.__name__,
reason=_("Unable to locate usable ipmitool command in "
"the system path when checking ipmitool version"))
_check_temp_dir()
def get_properties(self):
d = COMMON_PROPERTIES.copy()
d.update(CONSOLE_PROPERTIES)
return d
def validate(self, task):
"""Validate the Node console info.
:param task: a task from TaskManager.
:raises: InvalidParameterValue
:raises: MissingParameterValue when a required parameter is missing
"""
driver_info = _parse_driver_info(task.node)
if not driver_info['port']:
raise exception.MissingParameterValue(_(
"Missing 'ipmi_terminal_port' parameter in node's"
" driver_info."))
if driver_info['protocol_version'] != '2.0':
raise exception.InvalidParameterValue(_(
"Serial over lan only works with IPMI protocol version 2.0. "
"Check the 'ipmi_protocol_version' parameter in "
"node's driver_info"))
def start_console(self, task):
"""Start a remote console for the node.
:param task: a task from TaskManager
:raises: InvalidParameterValue if required ipmi parameters are missing
:raises: PasswordFileFailedToCreate if unable to create a file
containing the password
:raises: ConsoleError if the directory for the PID file cannot be
created
:raises: ConsoleSubprocessFailed when invoking the subprocess failed
"""
driver_info = _parse_driver_info(task.node)
path = _console_pwfile_path(driver_info['uuid'])
pw_file = console_utils.make_persistent_password_file(
path, driver_info['password'])
ipmi_cmd = ("/:%(uid)s:%(gid)s:HOME:ipmitool -H %(address)s"
" -I lanplus -U %(user)s -f %(pwfile)s"
% {'uid': os.getuid(),
'gid': os.getgid(),
'address': driver_info['address'],
'user': driver_info['username'],
'pwfile': pw_file})
for name, option in BRIDGING_OPTIONS:
if driver_info[name] is not None:
ipmi_cmd = " ".join([ipmi_cmd,
option, driver_info[name]])
if CONF.debug:
ipmi_cmd += " -v"
ipmi_cmd += " sol activate"
try:
console_utils.start_shellinabox_console(driver_info['uuid'],
driver_info['port'],
ipmi_cmd)
except (exception.ConsoleError, exception.ConsoleSubprocessFailed):
with excutils.save_and_reraise_exception():
utils.unlink_without_raise(path)
def stop_console(self, task):
"""Stop the remote console session for the node.
:param task: a task from TaskManager
:raises: InvalidParameterValue if required ipmi parameters are missing
:raises: ConsoleError if unable to stop the console
"""
driver_info = _parse_driver_info(task.node)
try:
console_utils.stop_shellinabox_console(driver_info['uuid'])
finally:
utils.unlink_without_raise(
_console_pwfile_path(driver_info['uuid']))
def get_console(self, task):
"""Get the type and connection information about the console."""
driver_info = _parse_driver_info(task.node)
url = console_utils.get_shellinabox_console_url(driver_info['port'])
return {'type': 'shellinabox', 'url': url}
| Java |
# Allium rudbaricum Boiss. & Buhse SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | Java |
/*
* Copyright 2020 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.dmn.openapi.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.eclipse.microprofile.openapi.OASFactory;
import org.eclipse.microprofile.openapi.models.media.Schema;
import org.eclipse.microprofile.openapi.models.media.Schema.SchemaType;
import org.kie.dmn.api.core.DMNType;
import org.kie.dmn.core.impl.BaseDMNTypeImpl;
import org.kie.dmn.core.impl.CompositeTypeImpl;
import org.kie.dmn.core.impl.SimpleTypeImpl;
import org.kie.dmn.openapi.NamingPolicy;
import org.kie.dmn.openapi.model.DMNModelIOSets;
import org.kie.dmn.openapi.model.DMNModelIOSets.DSIOSets;
import org.kie.dmn.typesafe.DMNTypeUtils;
public class DMNTypeSchemas {
private final List<DMNModelIOSets> ioSets;
private final Set<DMNType> typesIndex;
private final NamingPolicy namingPolicy;
public DMNTypeSchemas(List<DMNModelIOSets> ioSets, Set<DMNType> typesIndex, NamingPolicy namingPolicy) {
this.ioSets = Collections.unmodifiableList(ioSets);
this.typesIndex = Collections.unmodifiableSet(typesIndex);
this.namingPolicy = namingPolicy;
}
public Map<DMNType, Schema> generateSchemas() {
Map<DMNType, Schema> schemas = new HashMap<>();
for (DMNType t : typesIndex) {
Schema schema = schemaFromType(t);
schemas.put(t, schema);
}
return schemas;
}
private Schema refOrBuiltinSchema(DMNType t) {
if (DMNTypeUtils.isFEELBuiltInType(t)) {
return FEELBuiltinTypeSchemas.from(t);
}
if (typesIndex.contains(t)) {
Schema schema = OASFactory.createObject(Schema.class).ref(namingPolicy.getRef(t));
return schema;
}
throw new UnsupportedOperationException();
}
private boolean isIOSet(DMNType t) {
for (DMNModelIOSets ios : ioSets) {
if (ios.getInputSet().equals(t)) {
return true;
}
for (DSIOSets ds : ios.getDSIOSets()) {
if (ds.getDSInputSet().equals(t)) {
return true;
}
}
}
return false;
}
private Schema schemaFromType(DMNType t) {
if (t instanceof CompositeTypeImpl) {
return schemaFromCompositeType((CompositeTypeImpl) t);
}
if (t instanceof SimpleTypeImpl) {
return schemaFromSimpleType((SimpleTypeImpl) t);
}
throw new UnsupportedOperationException();
}
private Schema schemaFromSimpleType(SimpleTypeImpl t) {
DMNType baseType = t.getBaseType();
if (baseType == null) {
throw new IllegalStateException();
}
Schema schema = refOrBuiltinSchema(baseType);
if (t.getAllowedValues() != null && !t.getAllowedValues().isEmpty()) {
FEELSchemaEnum.parseAllowedValuesIntoSchema(schema, t.getAllowedValues());
}
schema = nestAsItemIfCollection(schema, t);
schema.addExtension(DMNOASConstants.X_DMN_TYPE, getDMNTypeSchemaXDMNTYPEdescr(t));
return schema;
}
private Schema schemaFromCompositeType(CompositeTypeImpl ct) {
Schema schema = OASFactory.createObject(Schema.class).type(SchemaType.OBJECT);
if (ct.getBaseType() == null) { // main case
for (Entry<String, DMNType> fkv : ct.getFields().entrySet()) {
schema.addProperty(fkv.getKey(), refOrBuiltinSchema(fkv.getValue()));
}
if (isIOSet(ct) && ct.getFields().size() > 0) {
schema.required(new ArrayList<>(ct.getFields().keySet()));
}
} else if (ct.isCollection()) {
schema = refOrBuiltinSchema(ct.getBaseType());
} else {
throw new IllegalStateException();
}
schema = nestAsItemIfCollection(schema, ct);
schema.addExtension(DMNOASConstants.X_DMN_TYPE, getDMNTypeSchemaXDMNTYPEdescr(ct));
return schema;
}
private Schema nestAsItemIfCollection(Schema original, DMNType t) {
if (t.isCollection()) {
return OASFactory.createObject(Schema.class).type(SchemaType.ARRAY).items(original);
} else {
return original;
}
}
private String getDMNTypeSchemaXDMNTYPEdescr(DMNType t) {
if (((BaseDMNTypeImpl) t).getBelongingType() == null) { // internals for anonymous inner types.
return t.toString();
} else {
return null;
}
}
}
| Java |
Link analysis between john boards, dating websites, and prostitution websites to find serial/high frequency buyers. How it would work:
Comparison of writing style across websites. There are a number of ways to tell if an author is the same across many mediums. Some parts of a writers signature will vary with context, but sort phrases and word choices will be consistent across mediums, for a small period of time. I believe the way this project would look is simple.
I'd scrape the site types mentioned above, apply the necessary nlp, to establish matching conditions, and then try to build a single person for each handle. The expectation is that handles would change over time or that multiple handles may refer to a single person.
Deliverables:
Pictures associated with high volume consumers of commercial sex - many dating websites require you to upload pictures. And sometimes people just do this because.
A more accurate representation of the number of active users of john boards.
A set of ontologies of terms used by members of various john boards and how that ontology evolves over time and regionally.
A greater understanding of the demand side by age, gender,ethnicity, and socio-economic class - often times people will post salary range, profession and other personal information on dating websites.
A psychological understanding of high volume buyers of sex, statistically - often times people on dating websites will answer a series of questions indicating their psychological make up, used for matching algorithms. If we can link a profile to an investigation, a law enforcement agency could use subpoena compliance to obtain the list of questions and their answers. Such information could even be anonymized passed back to dating websites and be used to statistically flag for buyers of commercial sex by dating websites. This level of cooperation between companies and dating websites is unlikely, but possible.
##To Dos
##Scrapers:
* Build a scraper for dating websites
* Build scrapers for all of the prostitution websites
* Do integrity testing of john board scraper/ integrate selenium scraper for deep web
##Identification of prostitution websites to scrape
* adultsearch
* alibaba
* anunico
* backpage
* cityvibe
* cityxguide
* cityxguideforum
* classivox
* craigslist
* ec21
* eroticmugshots
* eroticreview
* escortadsxxx
* escortphonelist
* escortsinca
* escortsincollege
* escortsintheus
* gmdu
* gulfjobsbank
* happymassage
* justlanded
* liveescortreviews
* manpowervacancy
* massagetroll
* missingkids
* myproviderguide
* myproviderguideforum
* naughtyreviews
* redbook
* redbook_forum
* rubads
* sipsap
* tradekey
* usasexguide
* utopiaguide
##Identification of John Boards to scrape
* usasexguide.com
* erotic review
* Eros
* city vibe
##Identification of dating websites to scrape - to do - indentify all of these
*
##Database:
* Choose a database for storing all of this information, pulling out keywords, hard attributes, and full text
* implement the database
Visualizations:
| Java |
<!doctype html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>My Website, improved</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="stylesheet" href="css/bootstrap.min.css">
<style>
body {
padding-top: 50px;
padding-bottom: 20px;
}
</style>
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/vendor/modernizr-2.8.3-respond-1.4.2.min.js"></script>
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<form class="navbar-form navbar-right" role="form">
<div class="form-group">
<input type="text" placeholder="Email" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="Password" class="form-control">
</div>
<button type="submit" class="btn btn-success">Sign in</button>
</form>
</div><!--/.navbar-collapse -->
</div>
</nav>
<!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron">
<div class="container">
<h1>Hello, world!</h1>
<p>This is a template for a simple marketing or informational website. It includes a large callout called a jumbotron and three supporting pieces of content. Use it as a starting point to create something more unique.</p>
<p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more »</a></p>
</div>
</div>
<div class="container">
<!-- Example row of columns -->
<div class="row">
<div class="col-md-4">
<h2>Heading</h2>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
<p><a class="btn btn-default" href="#" role="button">View details »</a></p>
</div>
<div class="col-md-4">
<h2>Heading</h2>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
<p><a class="btn btn-default" href="#" role="button">View details »</a></p>
</div>
<div class="col-md-4">
<h2>Heading</h2>
<p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p>
<p><a class="btn btn-default" href="#" role="button">View details »</a></p>
</div>
</div>
<hr>
<footer>
<p>© Company 2015</p>
</footer>
</div> <!-- /container --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.2.min.js"><\/script>')</script>
<script src="js/vendor/bootstrap.min.js"></script>
<script src="js/main.js"></script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X','auto');ga('send','pageview');
</script>
</body>
</html>
| Java |
<html>
<head>
<title>Inserir Veiculos</title>
<link rel="stylesheet" href="estilo.css" type="text/css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="JavaScript" type="text/javascript" src="..\MascaraValidacao.js"></script>
<script>
function busca(){
document.form.submit();
return true;
}
</script>
</head>
<body onload="document.form.PLACA.focus();">
<form name="form" method="post" action="InserirVeiculo2.php" onsubmit="return busca();">
<table width="100%" border="1" align="center" cellpadding="0" cellspacing="0" bordercolor="#CCCCCC">
<tr><td bgcolor="#CCCCCC" align="center" class="titulo">Inseri Veículo</td></tr>
<tr>
<table>
<tr>
<td>Placa</td>
<td>Tipo</td>
<td>Modelo</td>
<td>Ano</td>
<td>Cor</td>
<td>Cliente</td>
</tr>
<tr>
<td><input name="PLACA" type="text" id="PLACA" maxlength="8" onKeyPress="ColocaMascaraPlaca(document.form.PLACA);"/></td>
<td><select name=TIPO>
<option value="Carro">Carro</option>
<option value="Moto">Moto</option>
<option value="Caminhao">Caminhão</option>
<option value="Outro">Outro</option>
</select></td>
<td><input name="MODELO" type="text" id="MODELO" maxlength="30"/></td>
<td><input name="ANO" type="text" id="ANO" maxlength="4"/></td>
<td><input name="COR" type="text" id="COR" maxlength="15"/></td>
<td><?php
require_once('funcoes.php');
conectar('localhost', 'root','', 'bd_estacionamento');
$sql=mysql_query("SELECT nome_cliente,id_cliente FROM clientes order by nome_cliente");
echo "<select name=CLIENTES>";
while($rowl = mysql_fetch_assoc($sql)){
echo "<option value=". $rowl['id_cliente'] . ">" . $rowl['nome_cliente'] . "</option>";
}
echo "</select>";// Closing of list box
?></td>
<td><input type="submit" name="Submit" value="Incluir"</td>
</tr>
</table>
</tr>
</table>
</form>
<?php
require_once('funcoes.php');
conectar('localhost', 'root','', 'bd_estacionamento');
$PLACA = $_POST["PLACA"];
$TIPO = $_POST["TIPO"];
$MODELO = $_POST["MODELO"];
$ANO = $_POST["ANO"];
$COR = $_POST["COR"];
$CLIENTES = $_POST["CLIENTES"];
$query = "INSERT INTO veiculos VALUES('', '$TIPO', '$ANO', '$PLACA', '$MODELO', '$COR', '$CLIENTES')";
mysql_query($query) or die ('Falha ao executar query no banco de dados');
mysql_close() or die ('Falha ao fechar o banco de dados');
?>
<?php
require_once('funcoes.php');
conectar('localhost', 'root','', 'bd_estacionamento');
$result = mysql_query("SELECT * FROM veiculos");
echo "<table border=5 style=3 width=100%><tr><td>ID</td><td>Placa</td><td>Tipo</td><td>Modelo</td><td>Ano</td><td>Cor</td><td>Cliente</td></tr>";
while($row = mysql_fetch_assoc($result)){
echo "<tr><td>".$row['id_veiculo']."</td>"."<td>".$row['placa_veiculo']."</td>"."<td>".$row['tipo_veiculo']."</td>"."<td>".$row['modelo_veiculo']."</td>"."<td>".$row['ano_veiculo']."</td>"."<td>".$row['cor_veiculo']."</td>";
$fk = mysql_fetch_assoc(mysql_query("SELECT * FROM clientes where id_cliente='".$row['fk_cliente_veiculo']."'"));
echo "<td>".$fk['nome_cliente']."</td></tr>";
}
echo "</table><br><br>";
echo "";
?>
</body>
</html>
| Java |
/*
* Copyright 2018 OPS4J Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ops4j.kaiserkai.rest;
import com.spotify.docker.client.auth.RegistryAuthSupplier;
import com.spotify.docker.client.exceptions.DockerException;
import com.spotify.docker.client.messages.RegistryAuth;
import com.spotify.docker.client.messages.RegistryConfigs;
/**
* @author Harald Wellmann
*
*/
public class LocalAuthSupplier implements RegistryAuthSupplier {
@Override
public RegistryAuth authFor(String imageName) throws DockerException {
if (imageName.startsWith("127.0.0.1")) {
RegistryAuth auth = RegistryAuth.builder().username("admin").password("admin").build();
return auth;
}
return null;
}
@Override
public RegistryAuth authForSwarm() throws DockerException {
return null;
}
@Override
public RegistryConfigs authForBuild() throws DockerException {
return null;
}
}
| Java |
FORMAT: 1A
# Taskify API
This is the API Blueprint file for Taskify API.
# Group Tasks
## Task Collection [/tasks]
A collection of Tasks objects
### List all Tasks [GET]
Retrieve a collection of Tasks
+ Response 200 (application/json)
+ Body
[
{
"id": 1,
"name": "Buy some goreceries"
},
{
"id": 2,
"name": "Dinner with Katty"
}
]
### Create a new task [POST]
Create a Task
+ Request (application/json)
+ Attributes (object)
+ Response 200
+ Body
{
"id": 1,
"name": "Buy some goreceries"
}
## Tasks [/tasks/{id}]
A single Tasks object with all its details
### Get single Task [GET]
Retrieve a single Task by ID
+ Request
+ Parameters
+ id (number)
+ Response 200 (application/json)
+ Body
{
"id": 1,
"name": "Buy some goreceries"
}
### Modify single Task [PUT]
Edit a single Task by ID
+ Request (application/json)
+ Attributes
+ id (number)
+ Response 200 (application/json)
+ Body
{
"id": 1,
"name": "Buy some goreceries"
}
### Remove single Task [DELETE]
Delete a single Task by ID
+ Request
+ Attributes
+ id (number)
+ Response 204
| Java |
using Google.GData.YouTube;
using NUnit.Framework;
namespace Google.GData.Client.UnitTests.YouTube
{
/// <summary>
///This is a test class for PositionTest and is intended
///to contain all PositionTest Unit Tests
///</summary>
[TestFixture]
[Category("YouTube")]
public class PositionTest
{
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext { get; set; }
/// <summary>
///A test for Position Constructor
///</summary>
[Test]
public void PositionConstructorTest()
{
string initValue = "secret test string";
Position target = new Position(initValue);
Assert.AreEqual(target.Value, initValue, "Object value should be identical after construction");
}
/// <summary>
///A test for Position Constructor
///</summary>
[Test]
public void PositionConstructorTest1()
{
Position target = new Position();
Assert.IsNull(target.Value, "Object value should be null after construction");
}
//You can use the following additional attributes as you write your tests:
//
//
//Use ClassInitialize to run code before running the first test in the class
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext)
//{
//}
//
//Use ClassCleanup to run code after all tests in a class have run
//[ClassCleanup()]
//public static void MyClassCleanup()
//{
//}
//
//Use TestInitialize to run code before running each test
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//Use TestCleanup to run code after each test has run
//[TestCleanup()]
//public void MyTestCleanup()
//{
//}
//
}
} | Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_51) on Thu Apr 28 18:37:57 UTC 2016 -->
<title>Uses of Class org.apache.cassandra.cql3.restrictions.MultiColumnRestriction.IN (apache-cassandra API)</title>
<meta name="date" content="2016-04-28">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.cassandra.cql3.restrictions.MultiColumnRestriction.IN (apache-cassandra API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/cassandra/cql3/restrictions/MultiColumnRestriction.IN.html" title="class in org.apache.cassandra.cql3.restrictions">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/cassandra/cql3/restrictions/class-use/MultiColumnRestriction.IN.html" target="_top">Frames</a></li>
<li><a href="MultiColumnRestriction.IN.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.cassandra.cql3.restrictions.MultiColumnRestriction.IN" class="title">Uses of Class<br>org.apache.cassandra.cql3.restrictions.MultiColumnRestriction.IN</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../org/apache/cassandra/cql3/restrictions/MultiColumnRestriction.IN.html" title="class in org.apache.cassandra.cql3.restrictions">MultiColumnRestriction.IN</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.cassandra.cql3.restrictions">org.apache.cassandra.cql3.restrictions</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.cassandra.cql3.restrictions">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../org/apache/cassandra/cql3/restrictions/MultiColumnRestriction.IN.html" title="class in org.apache.cassandra.cql3.restrictions">MultiColumnRestriction.IN</a> in <a href="../../../../../../org/apache/cassandra/cql3/restrictions/package-summary.html">org.apache.cassandra.cql3.restrictions</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../../org/apache/cassandra/cql3/restrictions/MultiColumnRestriction.IN.html" title="class in org.apache.cassandra.cql3.restrictions">MultiColumnRestriction.IN</a> in <a href="../../../../../../org/apache/cassandra/cql3/restrictions/package-summary.html">org.apache.cassandra.cql3.restrictions</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/cassandra/cql3/restrictions/MultiColumnRestriction.InWithMarker.html" title="class in org.apache.cassandra.cql3.restrictions">MultiColumnRestriction.InWithMarker</a></strong></code>
<div class="block">An IN restriction that uses a single marker for a set of IN values that are tuples.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/cassandra/cql3/restrictions/MultiColumnRestriction.InWithValues.html" title="class in org.apache.cassandra.cql3.restrictions">MultiColumnRestriction.InWithValues</a></strong></code>
<div class="block">An IN restriction that has a set of terms for in values.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/cassandra/cql3/restrictions/MultiColumnRestriction.IN.html" title="class in org.apache.cassandra.cql3.restrictions">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/cassandra/cql3/restrictions/class-use/MultiColumnRestriction.IN.html" target="_top">Frames</a></li>
<li><a href="MultiColumnRestriction.IN.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2016 The Apache Software Foundation</small></p>
</body>
</html>
| Java |
package org.http4s
package headers
class LinkSpec extends HeaderLaws {
// FIXME Uri does not round trip properly: https://github.com/http4s/http4s/issues/1651
// checkAll(name = "Link", headerLaws(Link))
"parse" should {
"accept format RFC 5988" in {
val link = """</feed>; rel="alternate"; type="text/*"; title="main"; rev="previous""""
val parsedLinks = Link.parse(link).map(_.values)
val parsedLink = parsedLinks.map(_.head)
parsedLink.map(_.uri) must beRight(uri"/feed")
parsedLink.map(_.rel) must beRight(Option("alternate"))
parsedLink.map(_.title) must beRight(Option("main"))
parsedLink.map(_.`type`) must beRight(Option(MediaRange.`text/*`))
parsedLink.map(_.rev) must beRight(Option("previous"))
}
"accept format RFC 8288" in {
val links = List(
"""<https://api.github.com/search/code?q=addClass&page=1>; rel="prev"""",
"""<https://api.github.com/search/code?q=addClass&page=3>; rel="next"""",
"""<https://api.github.com/search/code?q=addClass&page=4>; rel="last"""",
"""<https://api.github.com/search/code?q=addClass&page=1>; rel="first""""
)
val parsedLinks = Link
.parse(links.mkString(", "))
.map(_.values)
parsedLinks.map(_.size) must beRight(links.size)
}
}
"render" should {
"properly format link according to RFC 5988" in {
val links = Link(
LinkValue(
uri"/feed",
rel = Some("alternate"),
title = Some("main"),
`type` = Some(MediaRange.`text/*`)
))
links.renderString must_==
"Link: </feed>; rel=alternate; title=main; type=text/*"
}
}
}
| Java |
/*
* Copyright 2020 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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dialogflow/cx/v3beta1/advanced_settings.proto
package com.google.cloud.dialogflow.cx.v3beta1;
public final class AdvancedSettingsProto {
private AdvancedSettingsProto() {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_LoggingSettings_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_LoggingSettings_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
static {
java.lang.String[] descriptorData = {
"\n:google/cloud/dialogflow/cx/v3beta1/adv"
+ "anced_settings.proto\022\"google.cloud.dialo"
+ "gflow.cx.v3beta1\032\037google/api/field_behav"
+ "ior.proto\"\315\001\n\020AdvancedSettings\022^\n\020loggin"
+ "g_settings\030\006 \001(\0132D.google.cloud.dialogfl"
+ "ow.cx.v3beta1.AdvancedSettings.LoggingSe"
+ "ttings\032Y\n\017LoggingSettings\022\"\n\032enable_stac"
+ "kdriver_logging\030\002 \001(\010\022\"\n\032enable_interact"
+ "ion_logging\030\003 \001(\010B\335\001\n&com.google.cloud.d"
+ "ialogflow.cx.v3beta1B\025AdvancedSettingsPr"
+ "otoP\001ZDgoogle.golang.org/genproto/google"
+ "apis/cloud/dialogflow/cx/v3beta1;cx\370\001\001\242\002"
+ "\002DF\252\002\"Google.Cloud.Dialogflow.Cx.V3Beta1"
+ "\352\002&Google::Cloud::Dialogflow::CX::V3beta"
+ "1b\006proto3"
};
descriptor =
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.api.FieldBehaviorProto.getDescriptor(),
});
internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_descriptor,
new java.lang.String[] {
"LoggingSettings",
});
internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_LoggingSettings_descriptor =
internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_descriptor
.getNestedTypes()
.get(0);
internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_LoggingSettings_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_LoggingSettings_descriptor,
new java.lang.String[] {
"EnableStackdriverLogging", "EnableInteractionLogging",
});
com.google.api.FieldBehaviorProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
| Java |
// Copyright 2018 The Oppia 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.
/**
* @fileoverview Unit tests for SuggestionThreadObjectFactory.
*/
// TODO(#7222): Remove the following block of unnnecessary imports once
// SuggestionThreadObjectFactory.ts is upgraded to Angular 8.
import { SuggestionObjectFactory } from
'domain/suggestion/SuggestionObjectFactory.ts';
// ^^^ This block is to be removed.
require('domain/suggestion/SuggestionThreadObjectFactory.ts');
describe('Suggestion thread object factory', function() {
beforeEach(function() {
angular.mock.module('oppia');
});
beforeEach(angular.mock.module('oppia', function($provide) {
$provide.value('SuggestionObjectFactory', new SuggestionObjectFactory());
}));
var SuggestionThreadObjectFactory = null;
var suggestionObjectFactory = null;
beforeEach(angular.mock.inject(function($injector) {
SuggestionThreadObjectFactory = $injector.get(
'SuggestionThreadObjectFactory');
suggestionObjectFactory = $injector.get('SuggestionObjectFactory');
}));
it('should create a new suggestion thread from a backend dict.', function() {
var suggestionThreadBackendDict = {
last_updated: 1000,
original_author_username: 'author',
status: 'accepted',
subject: 'sample subject',
summary: 'sample summary',
message_count: 10,
state_name: 'state 1',
thread_id: 'exploration.exp1.thread1'
};
var suggestionBackendDict = {
suggestion_id: 'exploration.exp1.thread1',
suggestion_type: 'edit_exploration_state_content',
target_type: 'exploration',
target_id: 'exp1',
target_version_at_submission: 1,
status: 'accepted',
author_name: 'author',
change: {
cmd: 'edit_state_property',
property_name: 'content',
state_name: 'state_1',
new_value: {
html: 'new suggestion content'
},
old_value: {
html: 'old suggestion content'
}
},
last_updated: 1000
};
var suggestionThread = SuggestionThreadObjectFactory.createFromBackendDicts(
suggestionThreadBackendDict, suggestionBackendDict);
expect(suggestionThread.status).toEqual('accepted');
expect(suggestionThread.subject).toEqual('sample subject');
expect(suggestionThread.summary).toEqual('sample summary');
expect(suggestionThread.originalAuthorName).toEqual('author');
expect(suggestionThread.lastUpdated).toEqual(1000);
expect(suggestionThread.messageCount).toEqual(10);
expect(suggestionThread.threadId).toEqual('exploration.exp1.thread1');
expect(suggestionThread.suggestion.suggestionType).toEqual(
'edit_exploration_state_content');
expect(suggestionThread.suggestion.targetType).toEqual('exploration');
expect(suggestionThread.suggestion.targetId).toEqual('exp1');
expect(suggestionThread.suggestion.suggestionId).toEqual(
'exploration.exp1.thread1');
expect(suggestionThread.suggestion.status).toEqual('accepted');
expect(suggestionThread.suggestion.authorName).toEqual('author');
expect(suggestionThread.suggestion.newValue.html).toEqual(
'new suggestion content');
expect(suggestionThread.suggestion.oldValue.html).toEqual(
'old suggestion content');
expect(suggestionThread.suggestion.lastUpdated).toEqual(1000);
expect(suggestionThread.suggestion.getThreadId()).toEqual(
'exploration.exp1.thread1');
expect(suggestionThread.isSuggestionThread()).toEqual(true);
expect(suggestionThread.isSuggestionHandled()).toEqual(true);
suggestionThread.suggestion.status = 'review';
expect(suggestionThread.isSuggestionHandled()).toEqual(false);
expect(suggestionThread.getSuggestionStatus()).toEqual('review');
expect(suggestionThread.getSuggestionStateName()).toEqual('state_1');
expect(suggestionThread.getReplacementHtmlFromSuggestion()).toEqual(
'new suggestion content');
var messages = [{
text: 'message1'
}, {
text: 'message2'
}];
suggestionThread.setMessages(messages);
expect(suggestionThread.messages).toEqual(messages);
});
});
| Java |
#!/usr/bin/env python
from random import choice
from python.decorators import euler_timer
SQUARES = ["GO",
"A1", "CC1", "A2", "T1", "R1", "B1", "CH1", "B2", "B3",
"JAIL",
"C1", "U1", "C2", "C3", "R2", "D1", "CC2", "D2", "D3",
"FP",
"E1", "CH2", "E2", "E3", "R3", "F1", "F2", "U2", "F3",
"G2J",
"G1", "G2", "CC3", "G3", "R4", "CH3", "H1", "T2", "H2"]
def roll_die(size):
first_die = choice(range(1, size + 1))
second_die = choice(range(1, size + 1))
return (first_die + second_die, (first_die == second_die))
def back(square, step):
index = SQUARES.index(square)
new_index = (index - step) % len(SQUARES)
return SQUARES[new_index]
def next_specific(square, next_type):
if next_type not in ["R", "U"]:
raise Exception("next_specific only intended for R and U")
# R1=5, R2=15, R3=25, R4=35
index = SQUARES.index(square)
if next_type == "R":
if 0 <= index < 5 or 35 < index:
return "R1"
elif 5 < index < 15:
return "R2"
elif 15 < index < 25:
return "R3"
elif 25 < index < 35:
return "R4"
else:
raise Exception("Case should not occur")
# U1=12, U2=28
elif next_type == "U":
if 0 <= index < 12 or index > 28:
return "U1"
elif 12 < index < 28:
return "U2"
else:
return Exception("Case should not occur")
else:
raise Exception("Case should not occur")
def next_square(landing_square, chance_card, chest_card):
if landing_square not in ["CC1", "CC2", "CC3", "CH1", "CH2", "CH3", "G2J"]:
return (landing_square, chance_card, chest_card)
if landing_square == "G2J":
return ("JAIL", chance_card, chest_card)
elif landing_square in ["CC1", "CC2", "CC3"]:
# 1/16 Go, Jail
# 14/16 Stay
chest_card = (chest_card + 1) % 16
if chest_card == 0:
return ("GO", chance_card, chest_card)
elif chest_card == 1:
return ("JAIL", chance_card, chest_card)
else:
return (landing_square, chance_card, chest_card)
elif landing_square in ["CH1", "CH2", "CH3"]:
# 1/16 Go, Jail, C1, E3, H2, R1, next U, back 3
# 1/8 Next R
chance_card = (chance_card + 1) % 16
if chance_card == 0:
return ("GO", chance_card, chest_card)
elif chance_card == 1:
return ("JAIL", chance_card, chest_card)
elif chance_card == 2:
return ("C1", chance_card, chest_card)
elif chance_card == 3:
return ("E3", chance_card, chest_card)
elif chance_card == 4:
return ("H2", chance_card, chest_card)
elif chance_card == 5:
return ("R1", chance_card, chest_card)
elif chance_card == 6:
return (next_specific(landing_square, "U"),
chance_card, chest_card)
elif chance_card == 7:
return next_square(back(landing_square, 3),
chance_card, chest_card)
elif chance_card in [8, 9]:
return (next_specific(landing_square, "R"),
chance_card, chest_card)
else:
return (landing_square, chance_card, chest_card)
else:
raise Exception("Case should not occur")
def main(verbose=False):
GAME_PLAY = 10 ** 6
dice_size = 4
visited = {"GO": 1}
current = "GO"
chance_card = 0
chest_card = 0
doubles = 0
for place in xrange(GAME_PLAY):
total, double = roll_die(dice_size)
if double:
doubles += 1
else:
doubles = 0
if doubles == 3:
doubles = 0
current = "JAIL"
else:
index = SQUARES.index(current)
landing_square = SQUARES[(index + total) % len(SQUARES)]
(current, chance_card,
chest_card) = next_square(landing_square, chance_card, chest_card)
# if current is not in visited, sets to 1
# (default 0 returned by get)
visited[current] = visited.get(current, 0) + 1
top_visited = sorted(visited.items(),
key=lambda pair: pair[1],
reverse=True)
top_visited = [SQUARES.index(square[0]) for square in top_visited[:3]]
return ''.join(str(index).zfill(2) for index in top_visited)
if __name__ == '__main__':
print euler_timer(84)(main)(verbose=True)
| Java |
# Chlorobotryaceae FAMILY
#### Status
ACCEPTED
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
null
#### Original name
null
### Remarks
null | Java |
/*
* SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include "esp_bit_defs.h"
/// Mask of interrupts sending to the host.
typedef enum {
SDIO_SLAVE_HOSTINT_BIT0 = BIT(0), ///< General purpose interrupt bit 0.
SDIO_SLAVE_HOSTINT_BIT1 = BIT(1),
SDIO_SLAVE_HOSTINT_BIT2 = BIT(2),
SDIO_SLAVE_HOSTINT_BIT3 = BIT(3),
SDIO_SLAVE_HOSTINT_BIT4 = BIT(4),
SDIO_SLAVE_HOSTINT_BIT5 = BIT(5),
SDIO_SLAVE_HOSTINT_BIT6 = BIT(6),
SDIO_SLAVE_HOSTINT_BIT7 = BIT(7),
SDIO_SLAVE_HOSTINT_SEND_NEW_PACKET = BIT(23), ///< New packet available
} sdio_slave_hostint_t;
/// Timing of SDIO slave
typedef enum {
SDIO_SLAVE_TIMING_PSEND_PSAMPLE = 0,/**< Send at posedge, and sample at posedge. Default value for HS mode.
* Normally there's no problem using this to work in DS mode.
*/
SDIO_SLAVE_TIMING_NSEND_PSAMPLE ,///< Send at negedge, and sample at posedge. Default value for DS mode and below.
SDIO_SLAVE_TIMING_PSEND_NSAMPLE, ///< Send at posedge, and sample at negedge
SDIO_SLAVE_TIMING_NSEND_NSAMPLE, ///< Send at negedge, and sample at negedge
} sdio_slave_timing_t;
/// Configuration of SDIO slave mode
typedef enum {
SDIO_SLAVE_SEND_STREAM = 0, ///< Stream mode, all packets to send will be combined as one if possible
SDIO_SLAVE_SEND_PACKET = 1, ///< Packet mode, one packets will be sent one after another (only increase packet_len if last packet sent).
} sdio_slave_sending_mode_t;
| Java |
package rds
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DescribeSQLLogFiles invokes the rds.DescribeSQLLogFiles API synchronously
// api document: https://help.aliyun.com/api/rds/describesqllogfiles.html
func (client *Client) DescribeSQLLogFiles(request *DescribeSQLLogFilesRequest) (response *DescribeSQLLogFilesResponse, err error) {
response = CreateDescribeSQLLogFilesResponse()
err = client.DoAction(request, response)
return
}
// DescribeSQLLogFilesWithChan invokes the rds.DescribeSQLLogFiles API asynchronously
// api document: https://help.aliyun.com/api/rds/describesqllogfiles.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeSQLLogFilesWithChan(request *DescribeSQLLogFilesRequest) (<-chan *DescribeSQLLogFilesResponse, <-chan error) {
responseChan := make(chan *DescribeSQLLogFilesResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DescribeSQLLogFiles(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DescribeSQLLogFilesWithCallback invokes the rds.DescribeSQLLogFiles API asynchronously
// api document: https://help.aliyun.com/api/rds/describesqllogfiles.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeSQLLogFilesWithCallback(request *DescribeSQLLogFilesRequest, callback func(response *DescribeSQLLogFilesResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DescribeSQLLogFilesResponse
var err error
defer close(result)
response, err = client.DescribeSQLLogFiles(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DescribeSQLLogFilesRequest is the request struct for api DescribeSQLLogFiles
type DescribeSQLLogFilesRequest struct {
*requests.RpcRequest
OwnerId requests.Integer `position:"Query" name:"OwnerId"`
ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
DBInstanceId string `position:"Query" name:"DBInstanceId"`
FileName string `position:"Query" name:"FileName"`
PageSize requests.Integer `position:"Query" name:"PageSize"`
PageNumber requests.Integer `position:"Query" name:"PageNumber"`
OwnerAccount string `position:"Query" name:"OwnerAccount"`
}
// DescribeSQLLogFilesResponse is the response struct for api DescribeSQLLogFiles
type DescribeSQLLogFilesResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
TotalRecordCount int `json:"TotalRecordCount" xml:"TotalRecordCount"`
PageNumber int `json:"PageNumber" xml:"PageNumber"`
PageRecordCount int `json:"PageRecordCount" xml:"PageRecordCount"`
Items ItemsInDescribeSQLLogFiles `json:"Items" xml:"Items"`
}
// CreateDescribeSQLLogFilesRequest creates a request to invoke DescribeSQLLogFiles API
func CreateDescribeSQLLogFilesRequest() (request *DescribeSQLLogFilesRequest) {
request = &DescribeSQLLogFilesRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Rds", "2014-08-15", "DescribeSQLLogFiles", "rds", "openAPI")
return
}
// CreateDescribeSQLLogFilesResponse creates a response to parse from DescribeSQLLogFiles response
func CreateDescribeSQLLogFilesResponse() (response *DescribeSQLLogFilesResponse) {
response = &DescribeSQLLogFilesResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
| Java |
#
# Cookbook Name:: bcpc
# Recipe:: diamond
#
# Copyright 2013, Bloomberg Finance L.P.
#
# 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.
#
if node['bcpc']['enabled']['metrics'] then
include_recipe "bcpc::default"
cookbook_file "/tmp/diamond.deb" do
source "bins/diamond.deb"
owner "root"
mode 00444
end
%w{python-support python-configobj python-pip python-httplib2}.each do |pkg|
package pkg do
action :upgrade
end
end
package "diamond" do
provider Chef::Provider::Package::Dpkg
source "/tmp/diamond.deb"
action :upgrade
options "--force-confold --force-confdef"
end
if node['bcpc']['virt_type'] == "kvm"
package "ipmitool" do
action :upgrade
end
package "smartmontools" do
action :upgrade
end
end
cookbook_file "/tmp/pyrabbit-1.0.1.tar.gz" do
source "bins/pyrabbit-1.0.1.tar.gz"
owner "root"
mode 00444
end
bash "install-pyrabbit" do
code <<-EOH
pip install /tmp/pyrabbit-1.0.1.tar.gz
EOH
not_if "pip freeze|grep pyrabbit"
end
bash "diamond-set-user" do
user "root"
code <<-EOH
sed --in-place '/^DIAMOND_USER=/d' /etc/default/diamond
echo 'DIAMOND_USER="root"' >> /etc/default/diamond
EOH
not_if "grep -e '^DIAMOND_USER=\"root\"' /etc/default/diamond"
notifies :restart, "service[diamond]", :delayed
end
template "/etc/diamond/diamond.conf" do
source "diamond.conf.erb"
owner "diamond"
group "root"
mode 00600
variables(:servers => get_head_nodes)
notifies :restart, "service[diamond]", :delayed
end
service "diamond" do
action [:enable, :start]
end
end
| Java |
import { promises as fsPromises } from 'fs';
import { expect } from 'chai';
describe('Verify stryker runs with mocha < 6', () => {
let strykerLog: string;
before(async () => {
strykerLog = await fsPromises.readFile('./stryker.log', 'utf8');
});
it('should warn about old mocha version', async () => {
expect(strykerLog).contains('DEPRECATED: Mocha < 6 detected. Please upgrade to at least Mocha version 6. Stryker will drop support for Mocha < 6 in V5');
});
});
| Java |
# AUTOGENERATED FILE
FROM balenalib/asus-tinker-edge-t-fedora:34-run
ENV NODE_VERSION 16.14.0
ENV YARN_VERSION 1.22.4
RUN for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver keyserver.ubuntu.com --recv-keys "$key" ; \
done \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-arm64.tar.gz" \
&& echo "82d71968c82eb391f463df62ba277563a3bd01ce43bba0e7e1c533991567b8fe node-v$NODE_VERSION-linux-arm64.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-arm64.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-arm64.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Fedora 34 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v16.14.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | Java |
import React from 'react';
import RadioButton from '../RadioButton';
import { mount } from 'enzyme';
const render = (props) => mount(
<RadioButton
{...props}
className="extra-class"
name="test-name"
value="test-value"
/>
);
describe('RadioButton', () => {
describe('renders as expected', () => {
const wrapper = render({
checked: true,
});
const input = wrapper.find('input');
const label = wrapper.find('label');
const div = wrapper.find('div');
describe('input', () => {
it('is of type radio', () => {
expect(input.props().type).toEqual('radio');
});
it('has the expected class', () => {
expect(input.hasClass('bx--radio-button')).toEqual(true);
});
it('has a unique id set by default', () => {
expect(input.props().id).toBeDefined();
});
it('should have checked set when checked is passed', () => {
wrapper.setProps({ checked: true });
expect(input.props().checked).toEqual(true);
});
it('should set the name prop as expected', () => {
expect(input.props().name).toEqual('test-name');
});
});
describe('label', () => {
it('should set htmlFor', () => {
expect(label.props().htmlFor)
.toEqual(input.props().id);
});
it('should set the correct class', () => {
expect(label.props().className).toEqual('bx--radio-button__label');
});
it('should render a span with the correct class', () => {
const span = label.find('span');
expect(span.hasClass('bx--radio-button__appearance')).toEqual(true);
});
it('should render label text', () => {
wrapper.setProps({ labelText: 'test label text' });
expect(label.text()).toMatch(/test label text/);
});
});
describe('wrapper', () => {
it('should have the correct class', () => {
expect(div.hasClass('radioButtonWrapper')).toEqual(true);
});
it('should have extra classes applied', () => {
expect(div.hasClass('extra-class')).toEqual(true);
});
});
});
it('should set defaultChecked as expected', () => {
const wrapper = render({
defaultChecked: true,
});
const input = wrapper.find('input');
expect(input.props().defaultChecked).toEqual(true);
wrapper.setProps({ defaultChecked: false });
expect(input.props().defaultChecked).toEqual(false);
});
it('should set id if one is passed in', () => {
const wrapper = render({
id: 'unique-id',
});
const input = wrapper.find('input');
expect(input.props().id).toEqual('unique-id');
});
describe('events', () => {
it('should invoke onChange with expected arguments', () => {
const onChange = jest.fn();
const wrapper = render({ onChange });
const input = wrapper.find('input');
const inputElement = input.get(0);
inputElement.checked = true;
wrapper.find('input').simulate('change');
const call = onChange.mock.calls[0];
expect(call[0]).toEqual('test-value');
expect(call[1]).toEqual('test-name');
expect(call[2].target).toBe(inputElement);
});
});
});
| Java |
/**
* Copyright (C) 2010-2013 Alibaba Group Holding Limited
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.alibaba.rocketmq.client.impl.consumer;
import com.alibaba.rocketmq.client.log.ClientLogger;
import com.alibaba.rocketmq.common.message.MessageConst;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.alibaba.rocketmq.common.protocol.body.ProcessQueueInfo;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Queue consumption snapshot
*
* @author shijia.wxr<vintage.wang@gmail.com>
* @since 2013-7-24
*/
public class ProcessQueue {
public final static long RebalanceLockMaxLiveTime = Long.parseLong(System.getProperty(
"rocketmq.client.rebalance.lockMaxLiveTime", "30000"));
public final static long RebalanceLockInterval = Long.parseLong(System.getProperty(
"rocketmq.client.rebalance.lockInterval", "20000"));
private final static long PullMaxIdleTime = Long.parseLong(System.getProperty(
"rocketmq.client.pull.pullMaxIdleTime", "120000"));
private final Logger log = ClientLogger.getLog();
private final ReadWriteLock lockTreeMap = new ReentrantReadWriteLock();
private final TreeMap<Long, MessageExt> msgTreeMap = new TreeMap<Long, MessageExt>();
private final AtomicLong msgCount = new AtomicLong();
private final Lock lockConsume = new ReentrantLock();
private final TreeMap<Long, MessageExt> msgTreeMapTemp = new TreeMap<Long, MessageExt>();
private final AtomicLong tryUnlockTimes = new AtomicLong(0);
private volatile long queueOffsetMax = 0L;
private volatile boolean dropped = false;
private volatile long lastPullTimestamp = System.currentTimeMillis();
private volatile long lastConsumeTimestamp = System.currentTimeMillis();
private volatile boolean locked = false;
private volatile long lastLockTimestamp = System.currentTimeMillis();
private volatile boolean consuming = false;
private volatile long msgAccCnt = 0;
public boolean isLockExpired() {
boolean result = (System.currentTimeMillis() - this.lastLockTimestamp) > RebalanceLockMaxLiveTime;
return result;
}
public boolean isPullExpired() {
boolean result = (System.currentTimeMillis() - this.lastPullTimestamp) > PullMaxIdleTime;
return result;
}
public boolean putMessage(final List<MessageExt> msgs) {
boolean dispatchToConsume = false;
try {
this.lockTreeMap.writeLock().lockInterruptibly();
try {
int validMsgCnt = 0;
for (MessageExt msg : msgs) {
MessageExt old = msgTreeMap.put(msg.getQueueOffset(), msg);
if (null == old) {
validMsgCnt++;
this.queueOffsetMax = msg.getQueueOffset();
}
}
msgCount.addAndGet(validMsgCnt);
if (!msgTreeMap.isEmpty() && !this.consuming) {
dispatchToConsume = true;
this.consuming = true;
}
if (!msgs.isEmpty()) {
MessageExt messageExt = msgs.get(msgs.size() - 1);
String property = messageExt.getProperty(MessageConst.PROPERTY_MAX_OFFSET);
if (property != null) {
long accTotal = Long.parseLong(property) - messageExt.getQueueOffset();
if (accTotal > 0) {
this.msgAccCnt = accTotal;
}
}
}
} finally {
this.lockTreeMap.writeLock().unlock();
}
} catch (InterruptedException e) {
log.error("putMessage exception", e);
}
return dispatchToConsume;
}
public long getMaxSpan() {
try {
this.lockTreeMap.readLock().lockInterruptibly();
try {
if (!this.msgTreeMap.isEmpty()) {
return this.msgTreeMap.lastKey() - this.msgTreeMap.firstKey();
}
} finally {
this.lockTreeMap.readLock().unlock();
}
} catch (InterruptedException e) {
log.error("getMaxSpan exception", e);
}
return 0;
}
public long removeMessage(final List<MessageExt> msgs) {
long result = -1;
final long now = System.currentTimeMillis();
try {
this.lockTreeMap.writeLock().lockInterruptibly();
this.lastConsumeTimestamp = now;
try {
if (!msgTreeMap.isEmpty()) {
result = this.queueOffsetMax + 1;
int removedCnt = 0;
for (MessageExt msg : msgs) {
MessageExt prev = msgTreeMap.remove(msg.getQueueOffset());
if (prev != null) {
removedCnt--;
}
}
msgCount.addAndGet(removedCnt);
if (!msgTreeMap.isEmpty()) {
result = msgTreeMap.firstKey();
}
}
} finally {
this.lockTreeMap.writeLock().unlock();
}
} catch (Throwable t) {
log.error("removeMessage exception", t);
}
return result;
}
public TreeMap<Long, MessageExt> getMsgTreeMap() {
return msgTreeMap;
}
public AtomicLong getMsgCount() {
return msgCount;
}
public boolean isDropped() {
return dropped;
}
public void setDropped(boolean dropped) {
this.dropped = dropped;
}
public boolean isLocked() {
return locked;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
public void rollback() {
try {
this.lockTreeMap.writeLock().lockInterruptibly();
try {
this.msgTreeMap.putAll(this.msgTreeMapTemp);
this.msgTreeMapTemp.clear();
} finally {
this.lockTreeMap.writeLock().unlock();
}
} catch (InterruptedException e) {
log.error("rollback exception", e);
}
}
public long commit() {
try {
this.lockTreeMap.writeLock().lockInterruptibly();
try {
Long offset = this.msgTreeMapTemp.lastKey();
msgCount.addAndGet(this.msgTreeMapTemp.size() * (-1));
this.msgTreeMapTemp.clear();
if (offset != null) {
return offset + 1;
}
} finally {
this.lockTreeMap.writeLock().unlock();
}
} catch (InterruptedException e) {
log.error("commit exception", e);
}
return -1;
}
public void makeMessageToCosumeAgain(List<MessageExt> msgs) {
try {
this.lockTreeMap.writeLock().lockInterruptibly();
try {
for (MessageExt msg : msgs) {
this.msgTreeMapTemp.remove(msg.getQueueOffset());
this.msgTreeMap.put(msg.getQueueOffset(), msg);
}
} finally {
this.lockTreeMap.writeLock().unlock();
}
} catch (InterruptedException e) {
log.error("makeMessageToCosumeAgain exception", e);
}
}
public List<MessageExt> takeMessags(final int batchSize) {
List<MessageExt> result = new ArrayList<MessageExt>(batchSize);
final long now = System.currentTimeMillis();
try {
this.lockTreeMap.writeLock().lockInterruptibly();
this.lastConsumeTimestamp = now;
try {
if (!this.msgTreeMap.isEmpty()) {
for (int i = 0; i < batchSize; i++) {
Map.Entry<Long, MessageExt> entry = this.msgTreeMap.pollFirstEntry();
if (entry != null) {
result.add(entry.getValue());
msgTreeMapTemp.put(entry.getKey(), entry.getValue());
} else {
break;
}
}
}
if (result.isEmpty()) {
consuming = false;
}
} finally {
this.lockTreeMap.writeLock().unlock();
}
} catch (InterruptedException e) {
log.error("take Messages exception", e);
}
return result;
}
public void clear() {
try {
this.lockTreeMap.writeLock().lockInterruptibly();
try {
this.msgTreeMap.clear();
this.msgTreeMapTemp.clear();
this.msgCount.set(0);
this.queueOffsetMax = 0L;
} finally {
this.lockTreeMap.writeLock().unlock();
}
} catch (InterruptedException e) {
log.error("rollback exception", e);
}
}
public long getLastLockTimestamp() {
return lastLockTimestamp;
}
public void setLastLockTimestamp(long lastLockTimestamp) {
this.lastLockTimestamp = lastLockTimestamp;
}
public Lock getLockConsume() {
return lockConsume;
}
public long getLastPullTimestamp() {
return lastPullTimestamp;
}
public void setLastPullTimestamp(long lastPullTimestamp) {
this.lastPullTimestamp = lastPullTimestamp;
}
public long getMsgAccCnt() {
return msgAccCnt;
}
public void setMsgAccCnt(long msgAccCnt) {
this.msgAccCnt = msgAccCnt;
}
public long getTryUnlockTimes() {
return this.tryUnlockTimes.get();
}
public void incTryUnlockTimes() {
this.tryUnlockTimes.incrementAndGet();
}
public void fillProcessQueueInfo(final ProcessQueueInfo info) {
try {
this.lockTreeMap.readLock().lockInterruptibly();
if (!this.msgTreeMap.isEmpty()) {
info.setCachedMsgMinOffset(this.msgTreeMap.firstKey());
info.setCachedMsgMaxOffset(this.msgTreeMap.lastKey());
info.setCachedMsgCount(this.msgTreeMap.size());
}
if (!this.msgTreeMapTemp.isEmpty()) {
info.setTransactionMsgMinOffset(this.msgTreeMapTemp.firstKey());
info.setTransactionMsgMaxOffset(this.msgTreeMapTemp.lastKey());
info.setTransactionMsgCount(this.msgTreeMapTemp.size());
}
info.setLocked(this.locked);
info.setTryUnlockTimes(this.tryUnlockTimes.get());
info.setLastLockTimestamp(this.lastLockTimestamp);
info.setDroped(this.dropped);
info.setLastPullTimestamp(this.lastPullTimestamp);
info.setLastConsumeTimestamp(this.lastConsumeTimestamp);
} catch (Exception e) {
} finally {
this.lockTreeMap.readLock().unlock();
}
}
public long getLastConsumeTimestamp() {
return lastConsumeTimestamp;
}
public void setLastConsumeTimestamp(long lastConsumeTimestamp) {
this.lastConsumeTimestamp = lastConsumeTimestamp;
}
}
| Java |
% Environment Variables
Cargo sets and reads a number of environment variables which your code can detect
or override. Here is a list of the variables Cargo sets, organized by when it interacts
with them:
# Environment variables Cargo reads
You can override these environment variables to change Cargo's behavior on your
system:
* `CARGO_HOME` - Cargo maintains a local cache of the registry index and of git
checkouts of crates. By default these are stored under `$HOME/.cargo`, but
this variable overrides the location of this directory. Once a crate is cached
it is not removed by the clean command.
* `CARGO_TARGET_DIR` - Location of where to place all generated artifacts,
relative to the current working directory.
* `RUSTC` - Instead of running `rustc`, Cargo will execute this specified
compiler instead.
* `RUSTDOC` - Instead of running `rustdoc`, Cargo will execute this specified
`rustdoc` instance instead.
* `RUSTFLAGS` - A space-separated list of custom flags to pass to all compiler
invocations that Cargo performs. In contrast with `cargo rustc`, this is
useful for passing a flag to *all* compiler instances.
Note that Cargo will also read environment variables for `.cargo/config`
configuration values, as described in [that documentation][config-env]
[config-env]: config.html#environment-variables
# Environment variables Cargo sets for crates
Cargo exposes these environment variables to your crate when it is compiled. To get the
value of any of these variables in a Rust program, do this:
```
let version = env!("CARGO_PKG_VERSION");
```
`version` will now contain the value of `CARGO_PKG_VERSION`.
* `CARGO_MANIFEST_DIR` - The directory containing the manifest of your package.
* `CARGO_PKG_VERSION` - The full version of your package.
* `CARGO_PKG_VERSION_MAJOR` - The major version of your package.
* `CARGO_PKG_VERSION_MINOR` - The minor version of your package.
* `CARGO_PKG_VERSION_PATCH` - The patch version of your package.
* `CARGO_PKG_VERSION_PRE` - The pre-release version of your package.
* `CARGO_PKG_AUTHORS` - Colon seperated list of authors from the manifest of your package.
* `CARGO_PKG_NAME` - The name of your package.
* `CARGO_PKG_DESCRIPTION` - The description of your package.
* `CARGO_PKG_HOMEPAGE` - The home page of your package.
# Environment variables Cargo sets for build scripts
Cargo sets several environment variables when build scripts are run. Because these variables
are not yet set when the build script is compiled, the above example using `env!` won't work
and instead you'll need to retrieve the values when the build script is run:
```
use std::env;
let out_dir = env::var("OUT_DIR").unwrap();
```
`out_dir` will now contain the value of `OUT_DIR`.
* `CARGO_MANIFEST_DIR` - The directory containing the manifest for the package
being built (the package containing the build
script). Also note that this is the value of the
current working directory of the build script when it
starts.
* `CARGO_MANIFEST_LINKS` - the manifest `links` value.
* `CARGO_FEATURE_<name>` - For each activated feature of the package being
built, this environment variable will be present
where `<name>` is the name of the feature uppercased
and having `-` translated to `_`.
* `OUT_DIR` - the folder in which all output should be placed. This folder is
inside the build directory for the package being built, and it is
unique for the package in question.
* `TARGET` - the target triple that is being compiled for. Native code should be
compiled for this triple. Some more information about target
triples can be found in [clang’s own documentation][clang].
* `HOST` - the host triple of the rust compiler.
* `NUM_JOBS` - the parallelism specified as the top-level parallelism. This can
be useful to pass a `-j` parameter to a system like `make`.
* `OPT_LEVEL`, `DEBUG` - values of the corresponding variables for the
profile currently being built.
* `PROFILE` - name of the profile currently being built (see
[profiles][profile]).
* `DEP_<name>_<key>` - For more information about this set of environment
variables, see build script documentation about [`links`][links].
[links]: build-script.html#the-links-manifest-key
[profile]: manifest.html#the-profile-sections
[clang]:http://clang.llvm.org/docs/CrossCompilation.html#target-triple
| Java |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using FeedProcessor.Contracts;
using FeedProcessor.Enums;
using FeedProcessor.FeedItems;
using FeedProcessor.Net;
namespace FeedProcessor.Feeds
{
/// <summary>
/// A feed which loads tweets from the twitter straming API.
/// </summary>
internal class TwitterStreamingFeed : Feed
{
/// <summary>
/// A mapping of twitter user ids to user names.
/// </summary>
private static Dictionary<string, string> _twitterUserNameCache = new Dictionary<string, string>();
/// <summary>
/// The username to use for the twitter streaming API.
/// </summary>
private string _twitterUsername;
/// <summary>
/// The password to use for the twitter streaming API.
/// </summary>
private string _twitterPassword;
/// <summary>
/// A JSON deserializer.
/// </summary>
private DataContractJsonSerializer _json = new DataContractJsonSerializer(typeof(TwitterJsonStatus));
/// <summary>
/// The background task which is connected to the streaming API.
/// </summary>
private Task _task;
/// <summary>
/// Initializes a new instance of the <see cref="TwitterStreamingFeed"/> class.
/// </summary>
/// <param name="username">The username.</param>
/// <param name="password">The password.</param>
internal TwitterStreamingFeed(string username, string password)
: base(TimeSpan.FromDays(1), DateTime.MinValue)
{
_twitterUsername = username;
_twitterPassword = password;
SourceType = SourceType.Twitter;
}
/// <summary>
/// Builds the query that is passed to the feed service.
/// </summary>
/// <returns>The query URI.</returns>
internal override Uri BuildQuery()
{
return new Uri(string.Format(CultureInfo.InvariantCulture, "http://stream.twitter.com/1/statuses/filter.json?{0}", Query));
}
/// <summary>
/// Initiates a request to the feed service.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Really do want all exceptions."), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Debug.WriteLine(System.String)", Justification = "It's just a log message.")]
protected override void Poll()
{
if (_task != null)
{
return;
}
_task = Task.Factory.StartNew(new Action(() =>
{
HttpWebResponse webResponse = null;
StreamReader responseStream = null;
HttpWebRequest webRequest = null;
int wait = 250;
try
{
while (true)
{
try
{
// Connect
webRequest = (HttpWebRequest)WebRequest.Create(BuildQuery());
webRequest.Credentials = new NetworkCredential(_twitterUsername, _twitterPassword);
webRequest.Timeout = -1;
webResponse = (HttpWebResponse)webRequest.GetResponse();
responseStream = new StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding("utf-8"));
// Read the stream.
while (true)
{
wait = 250;
ProcessResponse(responseStream.ReadLine());
RetryTime(HttpStatusCode.OK);
}
}
catch (WebException ex)
{
Debug.WriteLine(ex.Message);
if (ex.Status == WebExceptionStatus.ProtocolError)
{
// -- From Twitter Docs --
// When a HTTP error (> 200) is returned, back off exponentially.
// Perhaps start with a 10 second wait, double on each subsequent failure,
// and finally cap the wait at 240 seconds.
// Exponential Backoff
if (wait < 10000)
{
wait = 10000;
}
else
{
if (wait < 240000)
{
wait = wait * 2;
}
}
}
else
{
// -- From Twitter Docs --
// When a network error (TCP/IP level) is encountered, back off linearly.
// Perhaps start at 250 milliseconds and cap at 16 seconds.
// Linear Backoff
if (wait < 16000)
{
wait += 250;
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
finally
{
if (webRequest != null)
{
webRequest.Abort();
}
if (responseStream != null)
{
responseStream.Close();
responseStream = null;
}
if (webResponse != null)
{
webResponse.Close();
webResponse = null;
}
Debug.WriteLine("Waiting: " + wait);
RetryTime(HttpStatusCode.NotAcceptable);
Thread.Sleep(wait);
}
}
}
catch (Exception ex)
{
RetryTime(HttpStatusCode.NotAcceptable);
Debug.WriteLine(ex.Message);
Debug.WriteLine("Waiting: " + wait);
Thread.Sleep(wait);
}
}));
}
/// <summary>
/// Processes the response from the feed service.
/// </summary>
/// <param name="response">response from the feed service.</param>
internal override void ProcessResponse(object responseObject)
{
string response = responseObject.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(response);
TwitterJsonStatus status = null;
using (MemoryStream stream = new MemoryStream(byteArray))
{
status = _json.ReadObject(stream) as TwitterJsonStatus;
}
StatusFeedItem feedItem = new StatusFeedItem
{
Author = status.user.screen_name,
AvatarUri = new Uri(status.user.profile_image_url),
Date = DateTimeOffset.ParseExact(status.created_at, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture).DateTime,
ServiceId = status.id,
Uri = new Uri(string.Format(CultureInfo.InvariantCulture, "http://twitter.com/#!/{0}/status/{1}", status.user.screen_name, status.id)),
Status = status.text
};
RaiseGotNewFeedItem(feedItem);
}
/// <summary>
/// Returns a time after which it's ok to make another query.
/// </summary>
/// <param name="httpStatusCode">The HTTP status code returned from the last attempt.</param>
/// <returns>
/// The time after which it's ok to make another query.
/// </returns>
internal override DateTime RetryTime(HttpStatusCode httpStatusCode)
{
RaiseSourceStatusUpdated(httpStatusCode == HttpStatusCode.OK);
return DateTime.MinValue;
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#region Utility Methods
#region GetFlickrUserIdFromUserName
/// <summary>
/// Callback for GetTwitterUserIdFromUserName.
/// </summary>
/// <param name="userId">The userId returned by the twitter API.</param>
internal delegate void GetTwitterUserIdFromUserNameCallback(string userId);
/// <summary>
/// Gets the twitter user id from a username.
/// </summary>
/// <param name="username">The username.</param>
/// <param name="callback">The callback.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Really do want all exceptions.")]
internal static void GetTwitterUserIdFromUserName(string username, GetTwitterUserIdFromUserNameCallback callback)
{
if (_twitterUserNameCache.ContainsValue(username))
{
callback((from kvp in _twitterUserNameCache where kvp.Value == username select kvp.Key).FirstOrDefault());
return;
}
string query = string.Format(CultureInfo.InvariantCulture, "http://api.twitter.com/1/users/show.xml?screen_name={0}", username);
AsyncWebRequest request = new AsyncWebRequest();
request.Request(new Uri(query));
request.Result += (sender, e) =>
{
if (e.Status != HttpStatusCode.OK)
{
callback(null);
}
try
{
string userid = XDocument.Parse(e.Response).Element("user").Element("id").Value;
_twitterUserNameCache[userid] = username;
callback(userid);
}
catch
{
callback(null);
}
};
}
#endregion
#endregion
}
}
| Java |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Alexander Y. Kleymenov
* @version $Revision$
*/
package javax.crypto.spec;
import java.io.Serializable;
import java.security.spec.KeySpec;
import java.util.Arrays;
import javax.crypto.SecretKey;
/**
* A key specification for a <code>SecretKey</code> and also a secret key
* implementation that is provider-independent. It can be used for raw secret
* keys that can be specified as <code>byte[]</code>.
*/
public class SecretKeySpec implements SecretKey, KeySpec, Serializable {
// The 5.0 spec. doesn't declare this serialVersionUID field
// In order to be compatible it is explicitly declared here
// for details see HARMONY-233
private static final long serialVersionUID = 6577238317307289933L;
private final byte[] key;
private final String algorithm;
private final String format = "RAW";
/**
* Creates a new <code>SecretKeySpec</code> for the specified key data and
* algorithm name.
*
* @param key
* the key data.
* @param algorithm
* the algorithm name.
* @throws IllegalArgumentException
* if the key data or the algorithm name is null or if the key
* data is empty.
*/
public SecretKeySpec(byte[] key, String algorithm) {
if (key == null) {
throw new IllegalArgumentException("key == null");
}
if (key.length == 0) {
throw new IllegalArgumentException("key.length == 0");
}
if (algorithm == null) {
throw new IllegalArgumentException("algorithm == null");
}
this.algorithm = algorithm;
this.key = new byte[key.length];
System.arraycopy(key, 0, this.key, 0, key.length);
}
/**
* Creates a new <code>SecretKeySpec</code> for the key data from the
* specified buffer <code>key</code> starting at <code>offset</code> with
* length <code>len</code> and the specified <code>algorithm</code> name.
*
* @param key
* the key data.
* @param offset
* the offset.
* @param len
* the size of the key data.
* @param algorithm
* the algorithm name.
* @throws IllegalArgumentException
* if the key data or the algorithm name is null, the key data
* is empty or <code>offset</code> and <code>len</code> do not
* specify a valid chunk in the buffer <code>key</code>.
* @throws ArrayIndexOutOfBoundsException
* if <code>offset</code> or <code>len</code> is negative.
*/
public SecretKeySpec(byte[] key, int offset, int len, String algorithm) {
if (key == null) {
throw new IllegalArgumentException("key == null");
}
if (key.length == 0) {
throw new IllegalArgumentException("key.length == 0");
}
// BEGIN android-changed
if (len < 0 || offset < 0) {
throw new ArrayIndexOutOfBoundsException("len < 0 || offset < 0");
}
// END android-changed
if (key.length - offset < len) {
throw new IllegalArgumentException("key too short");
}
if (algorithm == null) {
throw new IllegalArgumentException("algorithm == null");
}
this.algorithm = algorithm;
this.key = new byte[len];
System.arraycopy(key, offset, this.key, 0, len);
}
/**
* Returns the algorithm name.
*
* @return the algorithm name.
*/
public String getAlgorithm() {
return algorithm;
}
/**
* Returns the name of the format used to encode the key.
*
* @return the format name "RAW".
*/
public String getFormat() {
return format;
}
/**
* Returns the encoded form of this secret key.
*
* @return the encoded form of this secret key.
*/
public byte[] getEncoded() {
byte[] result = new byte[key.length];
System.arraycopy(key, 0, result, 0, key.length);
return result;
}
/**
* Returns the hash code of this <code>SecretKeySpec</code> object.
*
* @return the hash code.
*/
@Override
public int hashCode() {
int result = algorithm.length();
for (byte element : key) {
result += element;
}
return result;
}
/**
* Compares the specified object with this <code>SecretKeySpec</code>
* instance.
*
* @param obj
* the object to compare.
* @return true if the algorithm name and key of both object are equal,
* otherwise false.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof SecretKeySpec)) {
return false;
}
SecretKeySpec ks = (SecretKeySpec) obj;
return (algorithm.equalsIgnoreCase(ks.algorithm))
&& (Arrays.equals(key, ks.key));
}
}
| Java |
#!/bin/bash
exec puppet agent --no-daemonize --server puppet --logdest console --verbose
| Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode;
import java.io.File;
import java.io.IOException;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.fs.permission.PermissionStatus;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.server.common.GenerationStamp;
import org.apache.hadoop.hdfs.server.common.Storage;
import org.apache.hadoop.hdfs.server.namenode.BlocksMap.BlockInfo;
/**
*
* CreateEditsLog Synopsis: CreateEditsLog -f numFiles StartingBlockId
* numBlocksPerFile [-r replicafactor] [-d editsLogDirectory] Default
* replication factor is 1 Default edits log directory is /tmp/EditsLogOut
*
* Create a name node's edits log in /tmp/EditsLogOut. The file
* /tmp/EditsLogOut/current/edits can be copied to a name node's
* dfs.name.dir/current direcotry and the name node can be started as usual.
*
* The files are created in /createdViaInjectingInEditsLog The file names
* contain the starting and ending blockIds; hence once can create multiple
* edits logs using this command using non overlapping block ids and feed the
* files to a single name node.
*
* See Also @link #DataNodeCluster for injecting a set of matching blocks
* created with this command into a set of simulated data nodes.
*
*/
public class CreateEditsLog {
static final String BASE_PATH = "/createdViaInjectingInEditsLog";
static final String EDITS_DIR = "/tmp/EditsLogOut";
static String edits_dir = EDITS_DIR;
static final public long BLOCK_GENERATION_STAMP = GenerationStamp.FIRST_VALID_STAMP;
static void addFiles(FSEditLog editLog, int numFiles, short replication,
int blocksPerFile, long startingBlockId,
FileNameGenerator nameGenerator) {
PermissionStatus p = new PermissionStatus("joeDoe", "people",
new FsPermission((short) 0777));
INodeDirectory dirInode = new INodeDirectory(p, 0L);
editLog.logMkDir(BASE_PATH, dirInode);
long blockSize = 10;
BlockInfo[] blocks = new BlockInfo[blocksPerFile];
for (int iB = 0; iB < blocksPerFile; ++iB) {
blocks[iB] = new BlockInfo(new Block(0, blockSize,
BLOCK_GENERATION_STAMP), replication);
}
long currentBlockId = startingBlockId;
long bidAtSync = startingBlockId;
for (int iF = 0; iF < numFiles; iF++) {
for (int iB = 0; iB < blocksPerFile; ++iB) {
blocks[iB].setBlockId(currentBlockId++);
}
try {
INodeFileUnderConstruction inode = new INodeFileUnderConstruction(
null, replication, 0, blockSize, blocks, p, "", "",
null);
// Append path to filename with information about blockIDs
String path = "_" + iF + "_B" + blocks[0].getBlockId()
+ "_to_B" + blocks[blocksPerFile - 1].getBlockId()
+ "_";
String filePath = nameGenerator.getNextFileName("");
filePath = filePath + path;
// Log the new sub directory in edits
if ((iF % nameGenerator.getFilesPerDirectory()) == 0) {
String currentDir = nameGenerator.getCurrentDir();
dirInode = new INodeDirectory(p, 0L);
editLog.logMkDir(currentDir, dirInode);
}
editLog.logOpenFile(filePath, inode);
editLog.logCloseFile(filePath, inode);
if (currentBlockId - bidAtSync >= 2000) { // sync every 2K
// blocks
editLog.logSync();
bidAtSync = currentBlockId;
}
} catch (IOException e) {
System.out.println("Creating trascation for file " + iF
+ " encountered exception " + e);
}
}
System.out.println("Created edits log in directory " + edits_dir);
System.out.println(" containing " + numFiles
+ " File-Creates, each file with " + blocksPerFile + " blocks");
System.out.println(" blocks range: " + startingBlockId + " to "
+ (currentBlockId - 1));
}
static String usage = "Usage: createditlogs "
+ " -f numFiles startingBlockIds NumBlocksPerFile [-r replicafactor] "
+ "[-d editsLogDirectory]\n"
+ " Default replication factor is 1\n"
+ " Default edits log direcory is " + EDITS_DIR + "\n";
static void printUsageExit() {
System.out.println(usage);
System.exit(-1);
}
static void printUsageExit(String err) {
System.out.println(err);
printUsageExit();
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
long startingBlockId = 1;
int numFiles = 0;
short replication = 1;
int numBlocksPerFile = 0;
if (args.length == 0) {
printUsageExit();
}
for (int i = 0; i < args.length; i++) { // parse command line
if (args[i].equals("-h"))
printUsageExit();
if (args[i].equals("-f")) {
if (i + 3 >= args.length || args[i + 1].startsWith("-")
|| args[i + 2].startsWith("-")
|| args[i + 3].startsWith("-")) {
printUsageExit("Missing num files, starting block and/or number of blocks");
}
numFiles = Integer.parseInt(args[++i]);
startingBlockId = Integer.parseInt(args[++i]);
numBlocksPerFile = Integer.parseInt(args[++i]);
if (numFiles <= 0 || numBlocksPerFile <= 0) {
printUsageExit("numFiles and numBlocksPerFile most be greater than 0");
}
} else if (args[i].equals("-r") || args[i + 1].startsWith("-")) {
if (i + 1 >= args.length) {
printUsageExit("Missing num files, starting block and/or number of blocks");
}
replication = Short.parseShort(args[++i]);
} else if (args[i].equals("-d")) {
if (i + 1 >= args.length || args[i + 1].startsWith("-")) {
printUsageExit("Missing edits logs directory");
}
edits_dir = args[++i];
} else {
printUsageExit();
}
}
File editsLogDir = new File(edits_dir);
File subStructureDir = new File(edits_dir + "/"
+ Storage.STORAGE_DIR_CURRENT);
if (!editsLogDir.exists()) {
if (!editsLogDir.mkdir()) {
System.out.println("cannot create " + edits_dir);
System.exit(-1);
}
}
if (!subStructureDir.exists()) {
if (!subStructureDir.mkdir()) {
System.out.println("cannot create subdirs of " + edits_dir);
System.exit(-1);
}
}
FSImage fsImage = new FSImage(new File(edits_dir));
FileNameGenerator nameGenerator = new FileNameGenerator(BASE_PATH, 100);
FSEditLog editLog = fsImage.getEditLog();
editLog.createEditLogFile(fsImage.getFsEditName());
editLog.open();
addFiles(editLog, numFiles, replication, numBlocksPerFile,
startingBlockId, nameGenerator);
editLog.logSync();
editLog.close();
}
}
| Java |
// Copyright 2015 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License. See the AUTHORS file
// for names of contributors.
//
// Author: Spencer Kimball (spencer.kimball@gmail.com)
package log
import (
"encoding/json"
"fmt"
"os"
"reflect"
"unicode/utf8"
"golang.org/x/net/context"
"github.com/cockroachdb/cockroach/roachpb"
"github.com/cockroachdb/cockroach/util/caller"
)
// AddStructured creates a structured log entry to be written to the
// specified facility of the logger.
func AddStructured(ctx context.Context, s Severity, depth int, format string, args []interface{}) {
file, line, _ := caller.Lookup(depth + 1)
entry := LogEntry{}
entry.set(ctx, format, args)
logging.outputLogEntry(s, file, line, false, &entry)
}
// getJSON returns a JSON representation of the specified argument.
// Returns nil if the type is simple and does not require a separate
// JSON representation.
func getJSON(arg interface{}) []byte {
// Not much point in storying strings and byte slices twice, as
// they're nearly always exactly specified in the format string.
switch arg.(type) {
case string, []byte, roachpb.Key, roachpb.EncodedKey:
return nil
}
jsonBytes, err := json.Marshal(arg)
if err != nil {
return []byte(fmt.Sprintf("{\"error\": %q}", err.Error()))
}
return jsonBytes
}
func (entry *LogEntry) set(ctx context.Context, format string, args []interface{}) {
entry.Format, entry.Args = parseFormatWithArgs(format, args)
if ctx != nil {
for i := Field(0); i < maxField; i++ {
if v := ctx.Value(i); v != nil {
switch vTyp := v.(type) {
case roachpb.NodeID:
entry.NodeID = &vTyp
case roachpb.StoreID:
entry.StoreID = &vTyp
case roachpb.RangeID:
entry.RangeID = &vTyp
case roachpb.Method:
entry.Method = &vTyp
case roachpb.Key:
entry.Key = vTyp
}
}
}
}
}
// parseFormatWithArgs parses the format string, matching each
// format specifier with an argument from the args array.
func parseFormatWithArgs(format string, args []interface{}) (string, []LogEntry_Arg) {
// Process format string.
var logArgs []LogEntry_Arg
var buf []byte
var idx int
end := len(format)
for i := 0; i < end; {
lasti := i
for i < end && format[i] != '%' {
i++
}
if i > lasti {
buf = append(buf, format[lasti:i]...)
}
if i >= end {
break
}
start := i
// Process one verb.
i++
F:
for ; i < end; i++ {
switch format[i] {
case '#', '0', '+', '-', ' ':
default:
break F
}
}
// TODO(spencer): should arg numbers dynamic precision be
// supported? They're so rare, better to just panic here for now.
if i < end && (format[i] == '[' || format[i] == '*') {
panic(fmt.Sprintf("arg numbers in format not supported by logger: %s", format))
}
// Read optional width.
for ; i < end && format[i] >= '0' && format[i] <= '9'; i++ {
}
// Read optional precision.
if i < end && format[i] == '.' {
for i = i + 1; i < end && format[i] >= '0' && format[i] <= '9'; i++ {
}
}
if i >= end {
break
}
c, w := utf8.DecodeRuneInString(format[i:])
i += w
// Escape and add percent directly to format buf.
if c == '%' {
buf = append(buf, '%', '%')
continue
}
buf = append(buf, "%s"...)
// New format string always gets %s, though we use the actual
// format to generate the string here for the log argument.
if idx >= len(args) {
fmt.Fprintf(os.Stderr, "ERROR: insufficient parameters specified for format string %s", format)
return string(append(buf, format[i:]...)), logArgs
}
logArgs = append(logArgs, makeLogArg(format[start:i], args[idx]))
idx++ // advance to next arg index
}
// Add arguments which were not processed via format specifiers.
for ; idx < len(args); idx++ {
logArgs = append(logArgs, makeLogArg("%v", args[idx]))
}
return string(buf), logArgs
}
func makeLogArg(format string, arg interface{}) LogEntry_Arg {
var tstr string
if t := reflect.TypeOf(arg); t != nil {
tstr = t.String()
}
return LogEntry_Arg{
Type: tstr,
Str: fmt.Sprintf(format, arg),
Json: getJSON(arg),
}
}
| Java |
# Enterovibrio Thompson et al., 2002 GENUS
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
International Journal of Systematic and Evolutionary Microbiology 52: -. [2015-2022]
#### Original name
null
### Remarks
null | Java |
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace JFrog.Artifactory.Model
{
/// <summary>
/// Artifactory MsBuild info model
/// </summary>
public class Build
{
public readonly static string STARTED_FORMAT = "{0}";//.000+0000";
public readonly static string ARTIFACTORY_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.ssszzzz";
/// <summary>
/// build/assembly version
/// </summary>
public string version { get { return "1.0.1"; } }
/// <summary>
/// project name
/// </summary>
public string name { get; set; }
/// <summary>
/// build number
/// </summary>
public string number { get; set; }
public string type { get; set; }
public BuildAgent buildAgent { get; set; }
public Agent agent { get; set; }
/// <summary>
/// Build start time
/// </summary>
public string started { get; set; }
/// <summary>
/// Build start time
/// </summary>
public string startedDateMillis { get; set; }
/// <summary>
/// Build duration in millis
/// </summary>
public long durationMillis { get; set; }
/// <summary>
/// The user who executed the build (TFS user or system user)
/// </summary>
public string principal { get; set; }
/// <summary>
/// The artifactory user used for deploythe build’s artifacts
/// </summary>
public string artifactoryPrincipal { get; set; }
/// <summary>
/// build url in the build server
/// </summary>
public string url { get; set; }
/// <summary>
/// system variables
/// </summary>
public IDictionary<string,string> properties { get; set; }
/// <summary>
/// Version control revision (Changeset number in TFS)
/// </summary>
public string vcsRevision { get; set; }
public LicenseControl licenseControl { get; set; }
public BlackDuckGovernance blackDuckGovernance { get; set; }
public BuildRetention buildRetention { get; set; }
/// <summary>
/// A list of one or more modules produced by this build
/// </summary>
public List<Module> modules { get; set; }
public DeployClient deployClient { set; get; }
public Dictionary<string, string> getDefaultProperties()
{
Dictionary<string, string> result = new Dictionary<string, string>();
result.Add("build.name", name);
result.Add("build.number", number);
result.Add("build.timestamp", startedDateMillis);
result.Add("vcs.revision", vcsRevision);
return result;
}
/// <summary>
/// Preparing the properties (Matrix params) to suitable Url Query
/// </summary>
/// <param name="matrixParam"></param>
/// <returns></returns>
public static string buildMatrixParamsString(List<KeyValuePair<string, string>> matrixParam)
{
StringBuilder matrix = new StringBuilder();
if (matrixParam != null)
{
matrixParam.ForEach(
pair => matrix.Append(";").Append(WebUtility.UrlEncode(pair.Key)).Append("=").
Append(WebUtility.UrlEncode(pair.Value))
);
}
return matrix.ToString();
}
}
/// <summary>
/// Build agent name and version, for example MSBuild 12.0
/// </summary>
public class BuildAgent
{
public string name { get; set; }
public string version { get; set; }
}
/// <summary>
/// CI server name and version, for example TFS 2013
/// </summary>
//public class Agent
//{
// public string name { get; set; }
// public string version { get; set; }
//}
public class LicenseControl
{
public string runChecks { get; set; }
public string includePublishedArtifacts { get; set; }
public string autoDiscover { get; set; }
public List<string> licenseViolationsRecipients { get; set; }
public List<string> scopes { get; set; }
}
public class BlackDuckGovernance
{
public string runChecks { get; set; }
public string appName { get; set; }
public string appVersion { get; set; }
public string autoCreateMissingComponentRequests { get; set; }
public string autoDiscardStaleComponentRequests { get; set; }
public string includePublishedArtifacts { get; set; }
public List<string> reportRecipients { get; set; }
public List<string> scopes { get; set; }
}
public class BuildRetention
{
public int count { get; set; }
public bool deleteBuildArtifacts { get; set; }
public List<string> buildNumbersNotToBeDiscarded { get; set; }
}
/// <summary>
/// build module data
/// </summary>
public class Module
{
public Module(string projectName)
{
Artifacts = new HashSet<Artifact>(new Artifact());
Dependencies = new List<Dependency>();
id = projectName;
}
/// <summary>
/// module identifier
/// </summary>
public string id { get; set; }
/// <summary>
/// A list of artifacts deployed for this module
/// </summary>
public HashSet<Artifact> Artifacts { get; set; }
/// <summary>
/// A list of dependencies used when building this module
/// </summary>
public List<Dependency> Dependencies { get; set; }
}
public class Artifact : IEqualityComparer<Artifact>
{
public string type { get; set; }
public string sha1 { get; set; }
public string md5 { get; set; }
public string name { get; set; }
public bool Equals(Artifact a, Artifact b)
{
if (!a.type.Equals(b.type))
return false;
if (!a.sha1.Equals(b.sha1))
return false;
if (!a.md5.Equals(b.md5))
return false;
if (!a.name.Equals(b.name))
return false;
return true;
}
public int GetHashCode(Artifact obj)
{
int hash = 17;
hash = hash * 31 + obj.type.GetHashCode();
hash = hash * 31 + obj.sha1.GetHashCode();
hash = hash * 31 + obj.md5.GetHashCode();
hash = hash * 31 + obj.name.GetHashCode();
return hash;
}
}
public class Dependency
{
public string type { get; set; }
public string sha1 { get; set; }
public string md5 { get; set; }
public string id { get; set; }
public List<string> scopes { get; set; }
}
public class DeployClient
{
public int timeout { get; set; }
public Proxy proxy { set; get; }
}
public class Proxy
{
private string host;
private int port;
private string username;
private string password;
private bool isCredentialsExists;
public Proxy() { }
public Proxy(string host, int port)
{
this.host = host;
this.port = port;
this.isCredentialsExists = false;
}
public Proxy(string host, int port, string username, string password)
{
this.host = host;
this.port = port;
this.username = username;
this.password = password;
this.isCredentialsExists = true;
}
public string Host { get { return this.host; } }
public int Port { get { return this.port; } }
public string Username { get { return this.username; } }
public string Password { get { return this.password; } }
public bool IsCredentialsExists { get { return this.isCredentialsExists; } }
public bool IsBypass { get; set; }
}
//public static class Json
//{
// public static const string version = "version";
// public static const string name = "name";
// public static const string number = "number";
// public static const string buildAgent = "buildAgent";
// public static const string agent = "agent";
// public static const string started = "started";
// public static const string durationMillis = "durationMillis";
// public static const string principal = "principal";
// public static const string artifactoryPrincipal = "artifactoryPrincipal";
// public static const string url = "url";
// public static const string vcsRevision = "vcsRevision";
// public static const string licenseControl = "licenseControl";
// public static const string buildRetention = "buildRetention";
// public static const string properties = "properties";
// public static const string modules = "modules";
// public static const string dependencies = "dependencies";
// public static const string artifacts = "artifacts";
// public static const string scopes = "scopes";
//}
}
| Java |
/*
* Copyright 2017-2022 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.
*/
package com.amazonaws.services.datapipeline.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.datapipeline.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* DeactivatePipelineResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeactivatePipelineResultJsonUnmarshaller implements Unmarshaller<DeactivatePipelineResult, JsonUnmarshallerContext> {
public DeactivatePipelineResult unmarshall(JsonUnmarshallerContext context) throws Exception {
DeactivatePipelineResult deactivatePipelineResult = new DeactivatePipelineResult();
return deactivatePipelineResult;
}
private static DeactivatePipelineResultJsonUnmarshaller instance;
public static DeactivatePipelineResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new DeactivatePipelineResultJsonUnmarshaller();
return instance;
}
}
| Java |
/**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spectator.placeholders;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Tag;
import java.util.Map;
/**
* An extension of the {@link Id} interface that allows the list of tag names attached
* to the Id to be declared in advance of the use of the metric. This can be used to
* provide a default value for a tag or to use a TagFactory implementation that uses
* context available in the execution environment to compute the value of the tag.
*/
public interface PlaceholderId {
/** Description of the measurement that is being collected. */
String name();
/** New id with an additional tag value. */
PlaceholderId withTag(String k, String v);
/** New id with an additional tag value. */
PlaceholderId withTag(Tag t);
/** New id with additional tag values. */
PlaceholderId withTags(Iterable<Tag> tags);
/** New id with additional tag values. */
PlaceholderId withTags(Map<String, String> tags);
/**
* New id with an additional tag factory.
* @param factory
* the factory to use to generate the values for the tag
*/
PlaceholderId withTagFactory(TagFactory factory);
/**
* New id with additional tag factories.
* @param factories
* a collection of factories for producing values for the tags
*/
PlaceholderId withTagFactories(Iterable<TagFactory> factories);
/**
* Invokes each of the associated tag factories to produce a Id based on the
* runtime context available when this method is invoked. If an associated
* TagFactory produces a non-null Tag, then the returned Id will have that
* Tag associated with it.
*
* @return an Id that has the same name as this id and the resolved tag values attached
*/
Id resolveToId();
}
| Java |
# Copyright 2022 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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.
#
"""add tenant_id to lcm_subscriptions and lcm_op_occs
Revision ID: d6ae359ab0d6
Revises: 3ff50553e9d3
Create Date: 2022-01-06 13:35:53.868106
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'd6ae359ab0d6'
down_revision = '3ff50553e9d3'
def upgrade(active_plugins=None, options=None):
op.add_column('vnf_lcm_subscriptions',
sa.Column('tenant_id', sa.String(length=64),
nullable=False))
op.add_column('vnf_lcm_op_occs',
sa.Column('tenant_id', sa.String(length=64),
nullable=False))
| Java |
# Prunus brachypoda var. eglandulosa W.C.Cheng VARIETY
#### Status
DOUBTFUL
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | Java |
/*
* This is a manifest file that'll be compiled into application.css, which will include all the files
* listed below.
*
* Any CSS file within this directory can be referenced here using a relative path.
*
* You're free to add application-wide styles to this file and they'll appear at the top of the
* compiled file, but it's generally better to create a new file per style scope.
*
*= require imms.bootstrap.pack
*= require imms.datatable.pack
*= require_self
*/
| Java |
/*
* Copyright 2014 - 2016 Real Logic 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 io.aeron.driver;
import io.aeron.driver.media.ReceiveChannelEndpoint;
import io.aeron.driver.media.UdpChannel;
import org.agrona.concurrent.status.ReadablePosition;
import java.util.IdentityHashMap;
import java.util.Map;
/**
* Subscription registration from a client used for liveness tracking
*/
public class SubscriptionLink implements DriverManagedResource
{
private final long registrationId;
private final long clientLivenessTimeoutNs;
private final int streamId;
private final boolean isReliable;
private final String channelUri;
private final ReceiveChannelEndpoint channelEndpoint;
private final AeronClient aeronClient;
private final Map<PublicationImage, ReadablePosition> positionByImageMap = new IdentityHashMap<>();
private final IpcPublication ipcPublication;
private final ReadablePosition ipcPublicationSubscriberPosition;
private final UdpChannel spiedChannel;
private NetworkPublication spiedPublication = null;
private ReadablePosition spiedPosition = null;
private boolean reachedEndOfLife = false;
public SubscriptionLink(
final long registrationId,
final ReceiveChannelEndpoint channelEndpoint,
final int streamId,
final String channelUri,
final AeronClient aeronClient,
final long clientLivenessTimeoutNs,
final boolean isReliable)
{
this.registrationId = registrationId;
this.channelEndpoint = channelEndpoint;
this.streamId = streamId;
this.channelUri = channelUri;
this.aeronClient = aeronClient;
this.ipcPublication = null;
this.ipcPublicationSubscriberPosition = null;
this.spiedChannel = null;
this.clientLivenessTimeoutNs = clientLivenessTimeoutNs;
this.isReliable = isReliable;
}
public SubscriptionLink(
final long registrationId,
final int streamId,
final String channelUri,
final IpcPublication ipcPublication,
final ReadablePosition subscriberPosition,
final AeronClient aeronClient,
final long clientLivenessTimeoutNs)
{
this.registrationId = registrationId;
this.channelEndpoint = null; // will prevent matches between PublicationImages and IpcPublications
this.streamId = streamId;
this.channelUri = channelUri;
this.aeronClient = aeronClient;
this.ipcPublication = ipcPublication;
ipcPublication.incRef();
this.ipcPublicationSubscriberPosition = subscriberPosition;
this.spiedChannel = null;
this.clientLivenessTimeoutNs = clientLivenessTimeoutNs;
this.isReliable = true;
}
public SubscriptionLink(
final long registrationId,
final UdpChannel spiedChannel,
final int streamId,
final String channelUri,
final AeronClient aeronClient,
final long clientLivenessTimeoutNs)
{
this.registrationId = registrationId;
this.channelEndpoint = null;
this.streamId = streamId;
this.channelUri = channelUri;
this.aeronClient = aeronClient;
this.ipcPublication = null;
this.ipcPublicationSubscriberPosition = null;
this.spiedChannel = spiedChannel;
this.clientLivenessTimeoutNs = clientLivenessTimeoutNs;
this.isReliable = true;
}
public long registrationId()
{
return registrationId;
}
public ReceiveChannelEndpoint channelEndpoint()
{
return channelEndpoint;
}
public int streamId()
{
return streamId;
}
public String channelUri()
{
return channelUri;
}
public boolean isReliable()
{
return isReliable;
}
public boolean matches(final ReceiveChannelEndpoint channelEndpoint, final int streamId)
{
return channelEndpoint == this.channelEndpoint && streamId == this.streamId;
}
public boolean matches(final NetworkPublication publication)
{
boolean result = false;
if (null != spiedChannel)
{
result = streamId == publication.streamId() &&
publication.sendChannelEndpoint().udpChannel().canonicalForm().equals(spiedChannel.canonicalForm());
}
return result;
}
public void addImage(final PublicationImage image, final ReadablePosition position)
{
positionByImageMap.put(image, position);
}
public void removeImage(final PublicationImage image)
{
positionByImageMap.remove(image);
}
public void addSpiedPublication(final NetworkPublication publication, final ReadablePosition position)
{
spiedPublication = publication;
spiedPosition = position;
}
public void removeSpiedPublication()
{
spiedPublication = null;
spiedPosition = null;
}
public void close()
{
positionByImageMap.forEach(PublicationImage::removeSubscriber);
if (null != ipcPublication)
{
ipcPublication.removeSubscription(ipcPublicationSubscriberPosition);
ipcPublication.decRef();
}
else if (null != spiedPublication)
{
spiedPublication.removeSpyPosition(spiedPosition);
}
}
public void onTimeEvent(final long time, final DriverConductor conductor)
{
if (time > (aeronClient.timeOfLastKeepalive() + clientLivenessTimeoutNs))
{
reachedEndOfLife = true;
conductor.cleanupSubscriptionLink(SubscriptionLink.this);
}
}
public boolean hasReachedEndOfLife()
{
return reachedEndOfLife;
}
public void timeOfLastStateChange(final long time)
{
// not set this way
}
public long timeOfLastStateChange()
{
return aeronClient.timeOfLastKeepalive();
}
public void delete()
{
close();
}
}
| Java |
/* */ package com.webbuilder.interact;
/* */
/* */ import com.webbuilder.controls.Query;
/* */ import com.webbuilder.utils.CompressUtil;
/* */ import com.webbuilder.utils.DateUtil;
/* */ import com.webbuilder.utils.DbUtil;
/* */ import com.webbuilder.utils.FileUtil;
/* */ import com.webbuilder.utils.StringUtil;
/* */ import com.webbuilder.utils.SysUtil;
/* */ import com.webbuilder.utils.WebUtil;
/* */ import com.webbuilder.utils.XMLParser;
/* */ import java.awt.Color;
/* */ import java.awt.Graphics;
/* */ import java.awt.image.BufferedImage;
/* */ import java.io.File;
/* */ import java.io.FileInputStream;
/* */ import java.io.InputStream;
/* */ import java.io.PrintWriter;
/* */ import java.sql.Connection;
/* */ import java.sql.PreparedStatement;
/* */ import java.sql.Timestamp;
/* */ import java.util.Calendar;
/* */ import java.util.Date;
/* */ import java.util.HashMap;
/* */ import java.util.HashSet;
/* */ import java.util.Iterator;
/* */ import javax.imageio.ImageIO;
/* */ import javax.servlet.http.HttpServletRequest;
/* */ import javax.servlet.http.HttpServletResponse;
/* */ import javax.servlet.http.HttpSession;
/* */ import javax.swing.Icon;
/* */ import javax.swing.filechooser.FileSystemView;
/* */ import org.dom4j.Attribute;
/* */ import org.dom4j.Document;
/* */ import org.dom4j.Element;
/* */ import org.json.JSONArray;
/* */ import org.json.JSONObject;
/* */
/* */ public class Explorer
/* */ {
/* */ public void getRcvFilter(HttpServletRequest request, HttpServletResponse response)
/* */ throws Exception
/* */ {
/* 42 */ String find = StringUtil.fetchString(request, "findCombo");
/* */
/* 44 */ if (!StringUtil.isEmpty(find)) {
/* 45 */ request.setAttribute("findValue", "%" + find + "%");
/* 46 */ String sql = " and WB_NAME like {?findValue?}";
/* 47 */ request.setAttribute("whereSql", sql);
/* */ } else {
/* 49 */ DbUtil.getDefaultWhere(request, response, "WB_DATE,WB_CODE=b",
/* 50 */ false);
/* */ }
/* */ }
/* */
/* */ public void sendFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
/* 55 */ Connection conn = DbUtil.fetchConnection(request, request.getAttribute(
/* 56 */ "sys.jndi").toString());
/* 57 */ String depts = request.getAttribute("WB_RDEPT").toString();
/* 58 */ String roles = request.getAttribute("WB_RROLE").toString();
/* 59 */ String users = request.getAttribute("WB_RUSER").toString();
/* 60 */ String scope = request.getAttribute("sys.scope").toString();
/* 61 */ String dbType = request.getAttribute("sys.dbType").toString();
/* 62 */ HashSet userList = new HashSet();
/* */
/* 64 */ userList = DbUtil.getUserList(conn, dbType, scope, depts, roles, users);
/* 65 */ conn.setAutoCommit(false);
/* */ try {
/* 67 */ PreparedStatement stm = null;
/* 68 */ int k = 0; int l = userList.size();
/* 69 */ boolean commitAll = false; boolean added = false;
/* 70 */ stm = conn
/* 71 */ .prepareStatement("insert into WB_FILERECEIVE values(?,?,?,?,null)");
/* */ try {
/* 73 */ stm.setString(1, scope);
/* 74 */ stm.setTimestamp(2,
/* 75 */ new Timestamp(DateUtil.stringToStdDate(
/* 75 */ request.getAttribute("sys.now").toString()).getTime()));
/* 76 */ stm.setString(3, request.getAttribute("sys.code").toString());
/* 77 */ while ( userList.iterator().hasNext()) {
String s=userList.iterator().next().toString();
/* 78 */ k++;
/* 79 */ stm.setString(4, s);
/* 80 */ stm.addBatch();
/* 81 */ if (!added)
/* 82 */ added = true;
/* 83 */ if (k % 1000 == 0) {
/* 84 */ if (k == l)
/* 85 */ commitAll = true;
/* 86 */ stm.executeBatch();
/* */ }
/* */ }
/* 89 */ if ((added) && (!commitAll))
/* 90 */ stm.executeBatch();
/* */ } finally {
/* 92 */ DbUtil.closeStatement(stm);
/* */ }
/* 94 */ conn.commit();
/* */ } catch (Exception e) {
/* 96 */ conn.rollback();
/* 97 */ throw new Exception(e);
/* */ } finally {
/* 99 */ conn.setAutoCommit(true);
/* */ }
/* */ }
/* */
/* */ private String createUserDir(String root) throws Exception {
/* 104 */ Date dt = new Date();
/* 105 */ String y = "y" + Integer.toString(DateUtil.yearOf(dt));
/* 106 */ String d = "d" + Integer.toString(DateUtil.dayOfYear(dt));
/* 107 */ String h = "h" + Integer.toString(DateUtil.hourOfDay(dt));
/* 108 */ Calendar cal = Calendar.getInstance();
/* 109 */ cal.setTime(dt);
/* 110 */ int m = cal.get(12);
/* 111 */ h = h + "m" + Integer.toString(m / 10);
/* 112 */ String rel = y + "/" + d + "/" + h + "/";
/* 113 */ File file = FileUtil.getUniqueFile(new File(root + "/" + rel + "s" +
/* 114 */ DateUtil.formatDate(dt, "ssSSS")));
/* 115 */ rel = rel + file.getName();
/* 116 */ File dir = new File(root + "/" + rel);
/* 117 */ if (!dir.mkdirs())
/* 118 */ throw new Exception("不能创建目录。");
/* 119 */ return rel;
/* */ }
/* */
/* */ public void createPubDir(HttpServletRequest request, HttpServletResponse response) throws Exception
/* */ {
/* 124 */ String root = request.getAttribute("sys.path").toString() +
/* 125 */ "WEB-INF/myfile";
/* 126 */ String scope = request.getAttribute("sys.scope").toString();
/* */
/* 128 */ String sysPubDir = FileUtil.fetchPubDir(root, scope);
/* 129 */ request.setAttribute("sysPubDir", sysPubDir);
/* */ }
/* */
/* */ public void createUserDir(HttpServletRequest request, HttpServletResponse response) throws Exception
/* */ {
/* 134 */ String userPath = request.getAttribute("sys.rootpath").toString();
/* */
/* 136 */ if (StringUtil.isEmpty(userPath)) {
/* 137 */ String root = request.getAttribute("sys.path").toString() +
/* 138 */ "WEB-INF/myfile";
/* 139 */ String path = createUserDir(root);
/* 140 */ Query query = new Query();
/* 141 */ query.setRequest(request);
/* 142 */ query.type = "update";
/* 143 */ request.setAttribute("rootPath", path);
/* 144 */ query.sql = "update WB_USER set ROOT_PATH={?rootPath?} where USERNAME={?sys.user?}";
/* 145 */ query.jndi = StringUtil.fetchString(request, "sys.jndi");
/* 146 */ query.setName("query.updateUser");
/* 147 */ query.create();
/* 148 */ request.getSession(false).setAttribute("sys.rootpath",
/* 149 */ root + "/" + path);
/* 150 */ request.setAttribute("sys.rootpath", root + "/" + path);
/* */ } else {
/* 152 */ File dir = new File(userPath);
/* 153 */ if ((!dir.exists()) && (!dir.mkdirs()))
/* 154 */ throw new Exception("不能创建用户目录。");
/* */ }
/* */ }
/* */
/* */ public void setOrder(HttpServletRequest request, HttpServletResponse response) throws Exception
/* */ {
/* 160 */ JSONArray files = new JSONArray(request.getParameter("orderTree"));
/* 161 */ int j = files.length();
/* 162 */ if (j == 0)
/* 163 */ return;
/* 164 */ File dir = new File(request.getParameter("orderDir"));
/* */
/* 168 */ HashMap hashMap = new HashMap();
/* */
/* 170 */ XMLParser mapXml = new XMLParser(FileUtil.getUserIndex(dir, request.getAttribute(
/* 171 */ "sys.scope").toString(), false));
/* 172 */ Element root = mapXml.document.getRootElement();
/* 173 */ Iterator iterator = root.elementIterator();
/* 174 */ while (iterator.hasNext()) {
/* 175 */ Element el = (Element)iterator.next();
/* 176 */ hashMap.put(el.attribute("name").getText(), el);
/* */ }
/* 178 */ for (int i = 0; i < j; i++) {
/* 179 */ String name = new JSONObject(files.getString(i)).getString("filename");
/* 180 */ Element el = (Element)hashMap.get(name);
/* 181 */ if (el != null) {
/* 182 */ root.add(el.createCopy());
/* 183 */ root.remove(el);
/* */ }
/* */ }
/* 186 */ mapXml.save();
/* */ }
/* */
/* */ public void getOrder(HttpServletRequest request, HttpServletResponse response)
/* */ throws Exception
/* */ {
/* 195 */ StringBuilder buf = new StringBuilder();
/* 196 */ boolean added = false;
/* */
/* 198 */ buf.append("[");
/* 199 */ File file = new File(request.getParameter("dir"));
/* 200 */ File mapFile = FileUtil.getUserIndex(file, request.getAttribute("sys.scope")
/* 201 */ .toString(), false);
/* 202 */ if (mapFile.exists()) {
/* 203 */ XMLParser mapXml = new XMLParser(mapFile);
/* 204 */ Element el = mapXml.document.getRootElement();
/* 205 */ if (el != null) {
/* 206 */ Iterator iterator = el.elementIterator();
/* 207 */ while (iterator.hasNext()) {
/* 208 */ el = (Element)iterator.next();
/* 209 */ if (added)
/* 210 */ buf.append(",");
/* */ else
/* 212 */ added = true;
/* 213 */ buf.append("{text:\"");
/* 214 */ String text = StringUtil.replaceParameters(request, el.attribute(
/* 215 */ "caption").getValue());
/* 216 */ String name = el.attribute("name").getValue();
/* 217 */ if (StringUtil.isEmpty(text))
/* 218 */ text = name;
/* 219 */ buf.append(StringUtil.toExpress(text));
/* 220 */ text = el.attribute("icon").getValue();
/* 221 */ if (!StringUtil.isEmpty(text)) {
/* 222 */ buf.append("\",iconCls:\"");
/* 223 */ buf.append(text);
/* */ }
/* 225 */ buf.append("\",filename:\"");
/* 226 */ buf.append(name);
/* 227 */ buf.append("\",leaf:true}");
/* */ }
/* */ }
/* */ }
/* 231 */ buf.append("]");
/* 232 */ response.getWriter().print(buf);
/* */ }
/* */
/* */ public void getProperty(HttpServletRequest request, HttpServletResponse response)
/* */ throws Exception
/* */ {
/* 243 */ File file = new File(request.getParameter("fileName"));
/* 244 */ File mapFile = FileUtil.getUserIndex(file.getParentFile(), request
/* 245 */ .getAttribute("sys.scope").toString(), false);
/* 246 */ if (mapFile.exists()) {
/* 247 */ String fileName = file.getName();
/* 248 */ XMLParser mapXml = new XMLParser(mapFile);
/* 249 */ Element el = mapXml.document.getRootElement();
/* 250 */ if (el != null) {
/* 251 */ Iterator iterator = el.elementIterator();
/* 252 */ while (iterator.hasNext()) {
/* 253 */ el = (Element)iterator.next();
/* 254 */ if (!StringUtil.isSame(el.attribute("name").getText(),
/* 255 */ fileName)) continue;
/* 256 */ StringBuilder buf = new StringBuilder();
/* 257 */ buf.append("{fileCaption:\"");
/* 258 */ Attribute attr = el.attribute("caption");
/* 259 */ if (attr != null)
/* 260 */ buf.append(StringUtil.toExpress(attr.getText()));
/* 261 */ buf.append("\",fileRole:\"");
/* 262 */ attr = el.attribute("role");
/* 263 */ if (attr != null)
/* 264 */ buf.append(StringUtil.toExpress(attr.getText()));
/* 265 */ buf.append("\",fileIcon:\"");
/* 266 */ attr = el.attribute("icon");
/* 267 */ if (attr != null)
/* 268 */ buf.append(attr.getText());
/* 269 */ buf.append("\",fileHint:\"");
/* 270 */ attr = el.attribute("hint");
/* 271 */ if (attr != null)
/* 272 */ buf.append(attr.getText());
/* 273 */ buf.append("\",fileHidden:\"");
/* 274 */ attr = el.attribute("hidden");
/* 275 */ if (attr != null)
/* 276 */ buf.append(StringUtil.toExpress(attr.getText()));
/* */ else
/* 278 */ buf.append("0");
/* 279 */ buf.append("\"}");
/* 280 */ response.getWriter().print(buf);
/* 281 */ return;
/* */ }
/* */ }
/* */ }
/* */ }
/* */
/* */ public void setPropertyCopy(HttpServletRequest request, HttpServletResponse response)
/* */ throws Exception
/* */ {
/* 290 */ innerSetProperty(request, response, true);
/* */ }
/* */
/* */ public void setProperty(HttpServletRequest request, HttpServletResponse response) throws Exception
/* */ {
/* 295 */ innerSetProperty(request, response, false);
/* */ }
/* */
/* */ private void innerSetProperty(HttpServletRequest request, HttpServletResponse response, boolean createCopy)
/* */ throws Exception
/* */ {
/* 304 */ String caption = request.getParameter("fileCaption");
/* 305 */ String role = request.getParameter("fileRole");
/* 306 */ String icon = request.getParameter("fileIcon");
/* 307 */ String hint = request.getParameter("fileHint");
/* 308 */ String hidden = request.getParameter("fileHidden");
/* 309 */ JSONArray files = new JSONArray(request.getParameter("setFile"));
/* 310 */ HashMap map = new HashMap();
/* */
/* 313 */ File file = new File(files.getString(0));
/* 314 */ File dir = file.getParentFile();
/* 315 */ XMLParser mapXml = new XMLParser(FileUtil.getUserIndex(dir, request.getAttribute(
/* 316 */ "sys.scope").toString(), createCopy));
/* 317 */ Element root = mapXml.document.getRootElement();
/* 318 */ if (root != null) {
/* 319 */ Iterator iterator = root.elementIterator();
/* 320 */ while (iterator.hasNext()) {
/* 321 */ Element el = (Element)iterator.next();
/* 322 */ String name = el.attribute("name").getText();
/* 323 */ file = new File(dir, name);
/* 324 */ if ((!file.exists()) || (map.containsKey(name)))
/* 325 */ root.remove(el);
/* */ else
/* 327 */ map.put(name, el);
/* */ }
/* */ } else {
/* 330 */ root = mapXml.document.addElement("map");
/* 331 */ }int j = files.length();
/* 332 */ for (int i = 0; i < j; i++) {
/* 333 */ String name = FileUtil.extractFileName(files.getString(i));
/* 334 */ Element el = (Element)map.get(name);
/* 335 */ if (el == null) {
/* 336 */ el = root.addElement("file");
/* 337 */ el.addAttribute("name", name);
/* 338 */ el.addAttribute("caption", caption);
/* 339 */ el.addAttribute("role", role);
/* 340 */ el.addAttribute("icon", icon);
/* 341 */ el.addAttribute("hint", hint);
/* 342 */ el.addAttribute("hidden", hidden);
/* */ } else {
/* 344 */ el.attribute("name").setText(name);
/* 345 */ el.attribute("caption").setText(caption);
/* 346 */ el.attribute("role").setText(role);
/* 347 */ el.attribute("icon").setText(icon);
/* 348 */ el.attribute("hint").setText(hint);
/* 349 */ el.attribute("hidden").setText(hidden);
/* */ }
/* */ }
/* 352 */ mapXml.save();
/* */ }
/* */
/* */ public void importFile(HttpServletRequest request, HttpServletResponse response) throws Exception
/* */ {
/* 357 */ String importDir = request.getAttribute("importDir").toString();
/* 358 */ FileUtil.checkRight(request, new File(importDir));
/* 359 */ InputStream stream = (InputStream)request.getAttribute("importFile");
/* 360 */ String fn = request.getAttribute("importFile__file").toString();
/* */
/* 362 */ if (StringUtil.isEqual(request.getAttribute("importType").toString(),
/* 363 */ "1")) {
/* 364 */ if (StringUtil.isSame(FileUtil.extractFileExt(fn), "zip"))
/* 365 */ CompressUtil.unzip(stream, new File(importDir),
/* 366 */ (String)request.getAttribute("sys.fileCharset"));
/* */ else
/* 368 */ throw new Exception("请选择一个zip格式的压缩文件。");
/* */ }
/* 370 */ else FileUtil.saveInputStreamToFile(stream, new File(importDir, fn));
/* */ }
/* */
/* */ public void exportFile(HttpServletRequest request, HttpServletResponse response)
/* */ throws Exception
/* */ {
/* 375 */ String[] list = StringUtil.split(request.getParameter("exportFiles"),
/* 376 */ "|");
/* 378 */ int i = 0; int j = list.length;
/* */
/* 380 */ File[] files = new File[j];
/* */
/* 382 */ for (i = 0; i < j; i++) {
/* 383 */ WebUtil.recordLog(request, "explorer导出:" + list[i], 1);
/* 384 */ files[i] = new File(list[i]);
/* 385 */ FileUtil.checkRight(request, files[i]);
/* */ }
/* */ String fileName;
/* 387 */ if (j == 1) {
/* 388 */ fileName = FileUtil.extractFileNameNoExt(files[0].getName());
/* */ } else {
/* 390 */ File parentFile = files[0].getParentFile();
/* 391 */ fileName = "";
/* 392 */ if (parentFile != null)
/* 393 */ fileName = FileUtil.extractFileNameNoExt(parentFile.getName());
/* 394 */ if (StringUtil.isEmpty(fileName))
/* 395 */ fileName = "data";
/* */ }
/* 397 */ boolean useZip = (StringUtil.isEqual(request.getParameter("exportType"), "1")) ||
/* 398 */ (j > 1) || (files[0].isDirectory());
/* 399 */ response.reset();
/* 400 */ if (!useZip) {
/* 401 */ response.setHeader("content-length", Long.toString(files[0]
/* 402 */ .length()));
/* 403 */ fileName = files[0].getName();
/* */ } else {
/* 405 */ fileName = fileName + ".zip";
/* 406 */ }response.setHeader("content-type", "application/force-download");
/* 407 */ String charset = (String)request.getAttribute("sys.fileCharset");
/* 408 */ response.setHeader("content-disposition", "attachment;filename=" +
/* 409 */ WebUtil.getFileName(fileName, charset));
/* 410 */ if (useZip) {
/* 411 */ CompressUtil.zip(files, response.getOutputStream(),
/* 412 */ (String)request.getAttribute("sys.fileCharset"));
/* */ } else {
/* 414 */ FileInputStream inputStream = new FileInputStream(files[0]);
/* 415 */ SysUtil.inputStreamToOutputStream(inputStream, response
/* 416 */ .getOutputStream());
/* 417 */ inputStream.close();
/* */ }
/* */ }
/* */
/* */ public void exportFile2(HttpServletRequest request, HttpServletResponse response)
/* */ throws Exception
/* */ {
/* */ String root = request.getAttribute("sys.path").toString() +
"WEB-INF/myfile.doc";
/* 378 */ int i = 0; int j = 1;
/* */
/* 380 */ File[] files = new File[j];
/* */
/* 382 */
/* 383 */ WebUtil.recordLog(request, "explorer导出:" + root, 1);
/* 384 */ files[i] = new File(root);
/* 385 */ FileUtil.checkRight(request, files[i]);
/* */
/* */ String fileName;
/* 387 */ if (j == 1) {
/* 388 */ fileName = FileUtil.extractFileNameNoExt(files[0].getName());
/* */ } else {
/* 390 */ File parentFile = files[0].getParentFile();
/* 391 */ fileName = "";
/* 392 */ if (parentFile != null)
/* 393 */ fileName = FileUtil.extractFileNameNoExt(parentFile.getName());
/* 394 */ if (StringUtil.isEmpty(fileName))
/* 395 */ fileName = "data";
/* */ }
/* 397 */ boolean useZip = (StringUtil.isEqual(request.getParameter("exportType"), "1")) ||
/* 398 */ (j > 1) || (files[0].isDirectory());
/* 399 */ response.reset();
/* 400 */ if (!useZip) {
/* 401 */ response.setHeader("content-length", Long.toString(files[0]
/* 402 */ .length()));
/* 403 */ fileName = files[0].getName();
/* */ } else {
/* 405 */ fileName = fileName + ".zip";
/* 406 */ }response.setHeader("content-type", "application/force-download");
/* 407 */ String charset = (String)request.getAttribute("sys.fileCharset");
/* 408 */ response.setHeader("content-disposition", "attachment;filename=" +
/* 409 */ WebUtil.getFileName(fileName, charset));
/* 410 */ if (useZip) {
/* 411 */ CompressUtil.zip(files, response.getOutputStream(),
/* 412 */ (String)request.getAttribute("sys.fileCharset"));
/* */ } else {
/* 414 */ FileInputStream inputStream = new FileInputStream(files[0]);
/* 415 */ SysUtil.inputStreamToOutputStream(inputStream, response
/* 416 */ .getOutputStream());
/* 417 */ inputStream.close();
/* */ }
/* */ }
/* */
/* */ public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception
/* */ {
/* 423 */ String fileName = request.getParameter("file");
/* */ try {
/* 425 */ Runtime.getRuntime().exec(fileName);
/* */ } catch (Exception e) {
/* 427 */ throw new Exception("执行 \"" + FileUtil.extractFileName(fileName) +
/* 428 */ "\"错误。");
/* */ }
/* */ }
/* */
/* */ public void openFile(HttpServletRequest request, HttpServletResponse response) throws Exception
/* */ {
/* 434 */ FileUtil.checkRight(request, new File(request.getParameter("file")));
/* 435 */ String charset = request.getParameter("charset");
/* */
/* 437 */ if (StringUtil.isEmpty(charset))
/* 438 */ charset = (String)request.getAttribute("sys.charset");
/* 439 */ response.getWriter().print(
/* 440 */ FileUtil.readText(request.getParameter("file"), charset));
/* */ }
/* */
/* */ public void saveFile(HttpServletRequest request, HttpServletResponse response) throws Exception
/* */ {
/* 445 */ FileUtil.checkRight(request, new File(request.getParameter("file")));
/* 446 */ String charset = request.getParameter("charset");
/* 447 */ if (StringUtil.isEmpty(charset))
/* 448 */ charset = (String)request.getAttribute("sys.charset");
/* 449 */ FileUtil.writeText(request.getParameter("file"), request
/* 450 */ .getParameter("text"), charset);
/* */ }
/* */
/* */ public void deleteFiles(HttpServletRequest request, HttpServletResponse response)
/* */ throws Exception
/* */ {
/* 457 */ JSONArray files = new JSONArray(request.getParameter("files"));
/* 458 */ int j = files.length();
/* */
/* 460 */ for (int i = 0; i < j; i++) {
/* 461 */ String fileName = files.getString(i);
/* 462 */ File file = new File(fileName);
/* 463 */ FileUtil.checkRight(request, file);
/* 464 */ WebUtil.recordLog(request, "explorer删除:" + fileName, 1);
/* 465 */ if (file.isDirectory())
/* 466 */ FileUtil.deleteFolder(file);
/* 467 */ else if (!file.delete())
/* 468 */ throw new Exception("不能删除文件 \"" + file.getName() + "\"。");
/* */ }
/* */ }
/* */
/* */ public void pasteFiles(HttpServletRequest request, HttpServletResponse response) throws Exception
/* */ {
/* 474 */ String filesParam = request.getParameter("files");
/* 475 */ String dir = request.getParameter("dir") + "/";
/* 476 */ File destFile = new File(dir);
/* 477 */ JSONArray files = new JSONArray(filesParam);
/* 478 */ boolean isCut = StringUtil.getStringBool(request.getParameter("isCut"));
/* 479 */ int j = files.length();
/* */
/* 481 */ for (int i = 0; i < j; i++) {
/* 482 */ File file = new File(files.getString(i));
/* 483 */ File dest = new File(dir + file.getName());
/* 484 */ FileUtil.checkRight(request, file);
/* 485 */ FileUtil.checkRight(request, dest);
/* 486 */ WebUtil.recordLog(request, "explorer贴粘:" + (isCut ? "剪切" : "复制") +
/* 487 */ "," + files.getString(i) + "至" + dir, 1);
/* 488 */ if (file.isDirectory()) {
/* 489 */ if (FileUtil.isSubFolder(file, destFile))
/* 490 */ throw new Exception("不能复制相同的文件夹。");
/* 491 */ FileUtil.copyFolder(file, dest, true, isCut);
/* */ } else {
/* 493 */ FileUtil.copyFile(file, dest, true, isCut);
/* */ }
/* */ }
/* */ }
/* */
/* */ public void rename(HttpServletRequest request, HttpServletResponse response) throws Exception {
/* 499 */ String fileName = request.getParameter("fileName");
/* 500 */ String rename = request.getParameter("fileValue");
/* 501 */ File file = new File(fileName);
/* 502 */ FileUtil.checkRight(request, file);
/* 503 */ if ((rename.indexOf("/") > -1) ||
/* 504 */ (rename.indexOf("\\") > -1) ||
/* 505 */ (!file.renameTo(
/* 506 */ new File(FileUtil.extractFilePath(fileName) +
/* 506 */ rename))))
/* 507 */ throw new Exception("重命名失败。");
/* */ }
/* */
/* */ public void newFile(HttpServletRequest request, HttpServletResponse response) throws Exception
/* */ {
/* 512 */ String name = request.getParameter("fileValue");
/* 513 */ String fileName = request.getParameter("dir") + "/" + name;
/* 514 */ String type = request.getParameter("type");
/* */
/* 517 */ File file = new File(fileName);
/* 518 */ FileUtil.checkRight(request, file);
/* */ boolean flag;
/* */
/* 519 */ if (type.equals("dir"))
/* 520 */ flag = file.mkdir();
/* */ else
/* 522 */ flag = file.createNewFile();
/* 523 */ if (!flag)
/* 524 */ throw new Exception("不能创建\"" + name + "\"");
/* */ }
/* */
/* */ public void getPubDir(HttpServletRequest request, HttpServletResponse response) throws Exception
/* */ {
/* 529 */ String dir = request.getParameter("dir");
/* 530 */ StringBuilder buf = new StringBuilder();
/* 531 */ String root = request.getAttribute("sys.path").toString() +
/* 532 */ "WEB-INF/myfile";
/* 533 */ String scope = request.getAttribute("sys.scope").toString();
/* */
/* 535 */ if (StringUtil.isEmpty(dir)) {
/* 536 */ loadPubDir(FileUtil.fetchPubDir(root, scope), buf);
/* */ } else {
/* 538 */ File fl = new File(dir);
/* 539 */ FileUtil.checkRight(request, fl);
/* 540 */ File[] files = fl.listFiles();
/* 541 */ FileUtil.sortFiles(files);
/* 542 */ loadFilesBuf(files, buf);
/* */ }
/* 544 */ response.getWriter().print(buf);
/* */ }
/* */
/* */ public void getUserDir(HttpServletRequest request, HttpServletResponse response) throws Exception
/* */ {
/* 549 */ String dir = request.getParameter("dir");
/* 550 */ StringBuilder buf = new StringBuilder();
/* */
/* 552 */ if (StringUtil.isEmpty(dir)) {
/* 553 */ loadUserDir((String)request.getAttribute("sys.rootpath"), buf);
/* */ } else {
/* 555 */ File fl = new File(dir);
/* 556 */ FileUtil.checkRight(request, fl);
/* 557 */ File[] files = fl.listFiles();
/* 558 */ FileUtil.sortFiles(files);
/* 559 */ loadFilesBuf(files, buf);
/* */ }
/* 561 */ response.getWriter().print(buf);
/* */ }
/* */
/* */ public void getDir(HttpServletRequest request, HttpServletResponse response) throws Exception
/* */ {
/* 566 */ String dir = request.getParameter("dir");
/* 567 */ boolean appRoot = StringUtil.getStringBool(request
/* 568 */ .getParameter("setAppRoot"));
/* 569 */ StringBuilder buf = new StringBuilder();
/* */
/* 571 */ if (StringUtil.isEmpty(dir)) {
/* 572 */ if ((appRoot) || (!loadFilesBuf(File.listRoots(), buf))) {
/* 573 */ buf = new StringBuilder();
/* 574 */ loadAppDir((String)request.getAttribute("sys.path"), buf);
/* */ }
/* */ } else {
/* 577 */ File[] files = new File(dir).listFiles();
/* 578 */ FileUtil.sortFiles(files);
/* 579 */ loadFilesBuf(files, buf);
/* */ }
/* 581 */ response.getWriter().print(buf);
/* */ }
/* */
/* */ public void getFile(HttpServletRequest request, HttpServletResponse response) throws Exception
/* */ {
/* 586 */ String dir = request.getParameter("dir");
/* 587 */ File dirFile = new File(dir);
/* 588 */ FileUtil.checkRight(request, dirFile);
/* 589 */ File[] files = dirFile.listFiles();
/* 590 */ if (files == null) {
/* 591 */ response.getWriter().print("{total:0,row:[]}");
/* 592 */ return;
/* */ }
/* 594 */ FileUtil.sortFiles(files);
/* 595 */ StringBuilder buf = new StringBuilder();
/* 596 */ FileSystemView fileView = FileSystemView.getFileSystemView();
/* 597 */ boolean isFirst = true;
/* 598 */ String start = request.getParameter("start");
/* 599 */ String limit = request.getParameter("limit");
/* 600 */ int count = 0;
/* */ int startValue;
/* */
/* 602 */ if (start == null)
/* 603 */ startValue = 1;
/* */ else
/* 605 */ startValue = Integer.parseInt(start) + 1;
/* */ int limitValue;
/* */
/* 606 */ if (limit == null)
/* 607 */ limitValue = 2147483647 - startValue;
/* */ else
/* 609 */ limitValue = Integer.parseInt(limit);
/* 610 */ int end = startValue + limitValue - 1;
/* 611 */ buf.append("{total:");
/* 612 */ buf.append(files.length);
/* 613 */ buf.append(",row:[");
/* 614 */ for (File file : files) {
/* 615 */ count++;
/* 616 */ if (count < startValue)
/* */ continue;
/* 618 */ if (count > end)
/* */ break;
/* 620 */ if (isFirst)
/* 621 */ isFirst = false;
/* */ else
/* 623 */ buf.append(",");
/* 624 */ boolean isDir = file.isDirectory();
/* 625 */ buf.append("{filename:\"");
/* 626 */ if (isDir)
/* 627 */ buf.append("0");
/* */ else
/* 629 */ buf.append("1");
/* 630 */ String fileName = file.getName();
/* 631 */ buf.append(fileName);
/* 632 */ buf.append("\",size:");
/* 633 */ if (isDir)
/* 634 */ buf.append(-1);
/* */ else
/* 636 */ buf.append(file.length());
/* 637 */ buf.append(",file:\"");
/* 638 */ buf.append(StringUtil.replace(file.getAbsolutePath(), "\\", "/"));
/* 639 */ buf.append("\",type:\"");
/* 640 */ if (isDir) {
/* 641 */ buf.append("0文件夹"); } else {
/* */ String type;
/* */ try { type = fileView.getSystemTypeDescription(file);
/* */ }
/* */ catch (Exception e)
/* */ {
/* */
/* 646 */ type = null;
/* */ }
/* 648 */ if (type != null) {
/* 649 */ buf.append("1" + StringUtil.toExpress(type));
/* */ } else {
/* 651 */ String ext = FileUtil.extractFileExt(fileName);
/* 652 */ if (StringUtil.isEmpty(ext)) {
/* 653 */ buf.append("1文件");
/* */ } else {
/* 655 */ buf.append("1" + ext);
/* 656 */ buf.append(" 文件");
/* */ }
/* */ }
/* */ }
/* 660 */ buf.append("\",modifyTime:\"");
/* 661 */ buf.append(DateUtil.dateToString(new Date(file.lastModified())));
/* 662 */ buf.append("\"}");
/* */ }
/* 664 */ buf.append("]}");
/* 665 */ response.getWriter().print(buf);
/* */ }
/* */
/* */ public void getIcon(HttpServletRequest request, HttpServletResponse response)
/* */ throws Exception
/* */ {
/* 671 */ File file = new File(new String(request.getParameter("file")
/* 671 */ .getBytes("ISO-8859-1"), "utf-8")); FileSystemView fileView = FileSystemView.getFileSystemView(); Icon icon = fileView.getSystemIcon(file); response.reset(); if (icon == null) { response.setContentType("image/gif"); InputStream is = new FileInputStream(request.getAttribute("sys.path") + "webbuilder/images/file.gif"); SysUtil.inputStreamToOutputStream(is, response.getOutputStream()); is.close(); } else { response.setContentType("image/jpeg"); int width = icon.getIconWidth(); int height = icon.getIconHeight(); BufferedImage image = new BufferedImage(width, height, 1); Graphics graphics = image.getGraphics(); graphics.setColor(Color.white); graphics.fillRect(0, 0, width, height); icon.paintIcon(null, graphics, 0, 0); ImageIO.write(image, "jpeg", response.getOutputStream()); graphics.dispose();
/* */ }
/* */ }
/* */
/* */ private void loadPubDir(String pubDir, StringBuilder buf)
/* */ {
/* 697 */ buf.append("[");
/* 698 */ buf.append("{text:\"公共文件\",dir:\"");
/* 699 */ buf.append(StringUtil.toExpress(pubDir));
/* 700 */ buf.append("\"}");
/* 701 */ buf.append("]");
/* */ }
/* */
/* */ private void loadUserDir(String userDir, StringBuilder buf) {
/* 705 */ buf.append("[");
/* 706 */ buf.append("{text:\"我的文件\",dir:\"");
/* 707 */ buf.append(StringUtil.toExpress(userDir));
/* 708 */ buf.append("\"}");
/* 709 */ buf.append("]");
/* */ }
/* */
/* */ private void loadAppDir(String appDir, StringBuilder buf) {
/* 713 */ String s = FileUtil.extractFileDir(appDir);
/* 714 */ buf.append("[");
/* 715 */ buf.append("{text:\"");
/* 716 */ buf.append(StringUtil.toExpress(s));
/* 717 */ buf.append("\",dir:\"");
/* 718 */ buf.append(StringUtil.toExpress(s));
/* 719 */ buf.append("\"}");
/* 720 */ buf.append("]");
/* */ }
/* */
/* */ private boolean loadFilesBuf(File[] files, StringBuilder buf) {
/* 724 */ boolean isOk = false; boolean isFirst = true;
/* */
/* 727 */ buf.append("[");
/* 728 */ for (File file : files) {
/* 729 */ if (file.isDirectory()) {
/* 730 */ isOk = true;
/* 731 */ if (isFirst)
/* 732 */ isFirst = false;
/* */ else
/* 734 */ buf.append(",");
/* 735 */ buf.append("{text:\"");
/* 736 */ String name = file.getName();
/* 737 */ String dir = StringUtil.replace(file.getAbsolutePath(), "\\", "/");
/* 738 */ if (StringUtil.isEmpty(name))
/* 739 */ name = FileUtil.extractFileDir(dir);
/* 740 */ buf.append(StringUtil.toExpress(name));
/* 741 */ buf.append("\",dir:\"");
/* 742 */ buf.append(StringUtil.replace(dir, "\\", "/"));
/* 743 */ if (FileUtil.hasSubFile(file, true))
/* 744 */ buf.append("\"}");
/* */ else
/* 746 */ buf.append("\",leaf:true,iconCls:\"icon_folder\"}");
/* */ }
/* */ }
/* 749 */ buf.append("]");
/* 750 */ return isOk;
/* */ }
/* */ }
/* Location: Z:\EXT\WebBuilderServer (1)\WEB-INF\lib\webbuilder2.jar
* Qualified Name: com.webbuilder.interact.Explorer
* JD-Core Version: 0.6.0
*/ | Java |
package org.fax4j.spi.email;
import java.io.IOException;
import javax.mail.Message;
import javax.mail.Transport;
import org.fax4j.FaxException;
import org.fax4j.FaxJob;
import org.fax4j.common.Logger;
import org.fax4j.spi.AbstractFax4JClientSpi;
import org.fax4j.util.Connection;
import org.fax4j.util.ReflectionHelper;
/**
* This class implements the fax client service provider interface.<br>
* This parial implementation will invoke the requests by sending emails to a mail server that supports
* conversion between email messages and fax messages.<br>
* The mail SPI supports persistent connection to enable to reuse the same connection for all fax
* operation invocations or to create a new connection for each fax operation invocation.<br>
* By default the SPI will create a new connection for each operation invocation however the
* <b>org.fax4j.spi.mail.persistent.connection</b> set to true will enable to reuse the connection.<br>
* To set the user/password values of the mail connection the following 2 properties must be defined:
* <b>org.fax4j.spi.mail.user.name</b> and <b>org.fax4j.spi.mail.password</b><br>
* All properties defined in the fax4j configuration will be passed to the mail connection therefore it is
* possible to define mail specific properties (see java mail for more info) in the fax4j properties.<br>
* Implementing SPI class will have to implement the createXXXFaxJobMessage methods.<br>
* These methods will return the message to be sent for that fax job operation. In case the method
* returns null, this class will throw an UnsupportedOperationException exception.
* <br>
* The configuration of the fax4j framework is made up of 3 layers.<br>
* The configuration is based on simple properties.<br>
* Each layer overrides the lower layers by adding/changing the property values.<br>
* The first layer is the internal fax4j.properties file located in the fax4j jar.<br>
* This layer contains the preconfigured values for the fax4j framework and can be changed
* by updating these properties in the higher layers.<br>
* The second layer is the external fax4j.properties file that is located on the classpath.<br>
* This file is optional and provides the ability to override the internal configuration for the
* entire fax4j framework.<br>
* The top most layer is the optional java.util.Properties object provided by the external classes
* when creating a new fax client.<br>
* These properties enable to override the configuration of the lower 2 layers.<br>
* <br>
* <b>SPI Status (Draft, Beta, Stable): </b>Stable<br>
* <br>
* Below table describes the configuration values relevant for this class.<br>
* <b>Configuration:</b>
* <table summary="" border="1">
* <tr>
* <td>Name</td>
* <td>Description</td>
* <td>Preconfigured Value</td>
* <td>Default Value</td>
* <td>Mandatory</td>
* </tr>
* <tr>
* <td>org.fax4j.spi.mail.persistent.connection</td>
* <td>True to reuse the same mail connection for all fax activites, false to create a
* new mail connection for each fax activity.</td>
* <td>false</td>
* <td>false</td>
* <td>false</td>
* </tr>
* <tr>
* <td>org.fax4j.spi.mail.connection.factory.class.name</td>
* <td>The connection factory class name</td>
* <td>org.fax4j.spi.email.MailConnectionFactoryImpl</td>
* <td>org.fax4j.spi.email.MailConnectionFactoryImpl</td>
* <td>false</td>
* </tr>
* <tr>
* <td>org.fax4j.spi.mail.user.name</td>
* <td>The mail account user name.</td>
* <td>none</td>
* <td>none</td>
* <td>false</td>
* </tr>
* <tr>
* <td>org.fax4j.spi.mail.password</td>
* <td>The mail account password.</td>
* <td>none</td>
* <td>none</td>
* <td>false</td>
* </tr>
* <tr>
* <td>javax mail properties</td>
* <td>Any of the javax mail properties can be defined in the fax4j properties.<br>
* These properties will be passed to the java mail framework.</td>
* <td>mail.transport.protocol=smtp<br>
* mail.smtp.port=25</td>
* <td>none</td>
* <td>false</td>
* </tr>
* </table>
* <br>
* <b>Limitations:</b><br>
* <ul>
* <li>This SPI is based on the java mail infrastructure, therefore this SPI cannot
* connect to mail servers through a proxy server.
* <li>This SPI provides only partial implementation (this is an abstract class).
* </ul>
* <br>
* <b>Dependencies:</b><br>
* <ul>
* <li>Required jar files: mail-1.4.jar, activation-1.1.jar
* </ul>
* <br>
*
* @author Sagie Gur-Ari
* @version 1.12
* @since 0.1
*/
public abstract class AbstractMailFaxClientSpi extends AbstractFax4JClientSpi
{
/**
* The use persistent connection flag which defines if the SPI will use a new
* connection for each request or will reuse the same connection
*/
private boolean usePersistentConnection;
/**The mail connection factory*/
private MailConnectionFactory connectionFactory;
/**The mail connection*/
private Connection<MailResourcesHolder> connection;
/**
* This class holds the SPI configuration constants.
*
* @author Sagie Gur-Ari
* @version 1.03
* @since 0.1
*/
public enum FaxClientSpiConfigurationConstants
{
/**
* The use persistent connection property key which defines if the SPI will use a new
* connection for each request or will reuse the same connection
*/
USE_PERSISTENT_CONNECTION_PROPERTY_KEY("org.fax4j.spi.mail.persistent.connection"),
/**The connection factory class name*/
CONNECTION_FACTORY_CLASS_NAME_PROPERTY_KEY("org.fax4j.spi.mail.connection.factory.class.name"),
/**The user name used to connect to the mail server*/
USER_NAME_PROPERTY_KEY("org.fax4j.spi.mail.user.name"),
/**The password used to connect to the mail server*/
PASSWORD_PROPERTY_KEY("org.fax4j.spi.mail.password");
/**The string value*/
private String value;
/**
* This is the class constructor.
*
* @param value
* The string value
*/
private FaxClientSpiConfigurationConstants(String value)
{
this.value=value;
}
/**
* This function returns the string value.
*
* @return The string value
*/
@Override
public final String toString()
{
return this.value;
}
}
/**
* This is the default constructor.
*/
public AbstractMailFaxClientSpi()
{
super();
}
/**
* This function initializes the fax client SPI.
*/
@Override
protected void initializeImpl()
{
//get logger
Logger logger=this.getLogger();
//get use persistent connection value
this.usePersistentConnection=Boolean.parseBoolean(this.getConfigurationValue(FaxClientSpiConfigurationConstants.USE_PERSISTENT_CONNECTION_PROPERTY_KEY));
logger.logDebug(new Object[]{"Using persistent connection: ",String.valueOf(this.usePersistentConnection)},null);
//setup connection factory
String className=this.getConfigurationValue(FaxClientSpiConfigurationConstants.CONNECTION_FACTORY_CLASS_NAME_PROPERTY_KEY);
this.connectionFactory=this.createMailConnectionFactoryImpl(className);
if(this.connectionFactory==null)
{
throw new FaxException("Mail connection factory is not available.");
}
}
/**
* Creates and returns the mail connection factory.
*
* @param className
* The connection factory class name
* @return The mail connection factory
*/
protected final MailConnectionFactory createMailConnectionFactoryImpl(String className)
{
String factoryClassName=className;
if(factoryClassName==null)
{
factoryClassName=MailConnectionFactoryImpl.class.getName();
}
//create new instance
MailConnectionFactory factory=(MailConnectionFactory)ReflectionHelper.createInstance(factoryClassName);
//initialize
factory.initialize(this);
return factory;
}
/**
* Releases the connection if open.
*
* @throws Throwable
* Any throwable
*/
@Override
protected void finalize() throws Throwable
{
//get reference
Connection<MailResourcesHolder> mailConnection=this.connection;
//release connection
this.closeMailConnection(mailConnection);
super.finalize();
}
/**
* Creates and returns the mail connection to be used to send the fax
* via mail.
*
* @return The mail connection
*/
protected Connection<MailResourcesHolder> createMailConnection()
{
//create new connection
Connection<MailResourcesHolder> mailConnection=this.connectionFactory.createConnection();
//log debug
Logger logger=this.getLogger();
logger.logInfo(new Object[]{"Created mail connection."},null);
return mailConnection;
}
/**
* This function closes the provided mail connection.
*
* @param mailConnection
* The mail connection to close
* @throws IOException
* Never thrown
*/
protected void closeMailConnection(Connection<MailResourcesHolder> mailConnection) throws IOException
{
if(mailConnection!=null)
{
//get logger
Logger logger=this.getLogger();
//release connection
logger.logInfo(new Object[]{"Closing mail connection."},null);
mailConnection.close();
}
}
/**
* Returns the mail connection to be used to send the fax
* via mail.
*
* @return The mail connection
*/
protected Connection<MailResourcesHolder> getMailConnection()
{
Connection<MailResourcesHolder> mailConnection=null;
if(this.usePersistentConnection)
{
synchronized(this)
{
if(this.connection==null)
{
//create new connection
this.connection=this.createMailConnection();
}
}
//get connection
mailConnection=this.connection;
}
else
{
//create new connection
mailConnection=this.createMailConnection();
}
return mailConnection;
}
/**
* This function will send the mail message.
*
* @param faxJob
* The fax job object containing the needed information
* @param mailConnection
* The mail connection (will be released if not persistent)
* @param message
* The message to send
*/
protected void sendMail(FaxJob faxJob,Connection<MailResourcesHolder> mailConnection,Message message)
{
if(message==null)
{
this.throwUnsupportedException();
}
else
{
//get holder
MailResourcesHolder mailResourcesHolder=mailConnection.getResource();
//get transport
Transport transport=mailResourcesHolder.getTransport();
try
{
//send message
message.saveChanges();
if(transport==null)
{
Transport.send(message,message.getAllRecipients());
}
else
{
transport.sendMessage(message,message.getAllRecipients());
}
}
catch(Throwable throwable)
{
throw new FaxException("Unable to send message.",throwable);
}
finally
{
if(!this.usePersistentConnection)
{
try
{
//close connection
this.closeMailConnection(mailConnection);
}
catch(Exception exception)
{
//log error
Logger logger=this.getLogger();
logger.logInfo(new Object[]{"Error while releasing mail connection."},exception);
}
}
}
}
}
/**
* This function will submit a new fax job.<br>
* The fax job ID may be populated by this method in the provided
* fax job object.
*
* @param faxJob
* The fax job object containing the needed information
*/
@Override
protected void submitFaxJobImpl(FaxJob faxJob)
{
//get connection
Connection<MailResourcesHolder> mailConnection=this.getMailConnection();
//get holder
MailResourcesHolder mailResourcesHolder=mailConnection.getResource();
//create message
Message message=this.createSubmitFaxJobMessage(faxJob,mailResourcesHolder);
//send message
this.sendMail(faxJob,mailConnection,message);
}
/**
* This function will suspend an existing fax job.
*
* @param faxJob
* The fax job object containing the needed information
*/
@Override
protected void suspendFaxJobImpl(FaxJob faxJob)
{
//get connection
Connection<MailResourcesHolder> mailConnection=this.getMailConnection();
//get holder
MailResourcesHolder mailResourcesHolder=mailConnection.getResource();
//create message
Message message=this.createSuspendFaxJobMessage(faxJob,mailResourcesHolder);
//send message
this.sendMail(faxJob,mailConnection,message);
}
/**
* This function will resume an existing fax job.
*
* @param faxJob
* The fax job object containing the needed information
*/
@Override
protected void resumeFaxJobImpl(FaxJob faxJob)
{
//get connection
Connection<MailResourcesHolder> mailConnection=this.getMailConnection();
//get holder
MailResourcesHolder mailResourcesHolder=mailConnection.getResource();
//create message
Message message=this.createResumeFaxJobMessage(faxJob,mailResourcesHolder);
//send message
this.sendMail(faxJob,mailConnection,message);
}
/**
* This function will cancel an existing fax job.
*
* @param faxJob
* The fax job object containing the needed information
*/
@Override
protected void cancelFaxJobImpl(FaxJob faxJob)
{
//get connection
Connection<MailResourcesHolder> mailConnection=this.getMailConnection();
//get holder
MailResourcesHolder mailResourcesHolder=mailConnection.getResource();
//create message
Message message=this.createCancelFaxJobMessage(faxJob,mailResourcesHolder);
//send message
this.sendMail(faxJob,mailConnection,message);
}
/**
* This function will create the message used to invoke the fax
* job action.<br>
* If this method returns null, the SPI will throw an UnsupportedOperationException.
*
* @param faxJob
* The fax job object containing the needed information
* @param mailResourcesHolder
* The mail resources holder
* @return The message to send (if null, the SPI will throw an UnsupportedOperationException)
*/
protected abstract Message createSubmitFaxJobMessage(FaxJob faxJob,MailResourcesHolder mailResourcesHolder);
/**
* This function will create the message used to invoke the fax
* job action.<br>
* If this method returns null, the SPI will throw an UnsupportedOperationException.
*
* @param faxJob
* The fax job object containing the needed information
* @param mailResourcesHolder
* The mail resources holder
* @return The message to send (if null, the SPI will throw an UnsupportedOperationException)
*/
protected abstract Message createSuspendFaxJobMessage(FaxJob faxJob,MailResourcesHolder mailResourcesHolder);
/**
* This function will create the message used to invoke the fax
* job action.<br>
* If this method returns null, the SPI will throw an UnsupportedOperationException.
*
* @param faxJob
* The fax job object containing the needed information
* @param mailResourcesHolder
* The mail resources holder
* @return The message to send (if null, the SPI will throw an UnsupportedOperationException)
*/
protected abstract Message createResumeFaxJobMessage(FaxJob faxJob,MailResourcesHolder mailResourcesHolder);
/**
* This function will create the message used to invoke the fax
* job action.<br>
* If this method returns null, the SPI will throw an UnsupportedOperationException.
*
* @param faxJob
* The fax job object containing the needed information
* @param mailResourcesHolder
* The mail resources holder
* @return The message to send (if null, the SPI will throw an UnsupportedOperationException)
*/
protected abstract Message createCancelFaxJobMessage(FaxJob faxJob,MailResourcesHolder mailResourcesHolder);
} | Java |
<html><!-- Created using the cpp_pretty_printer from the dlib C++ library. See http://dlib.net for updates. --><head><title>dlib C++ Library - quantum_computing_abstract.h</title></head><body bgcolor='white'><pre>
<font color='#009900'>// Copyright (C) 2008 Davis E. King (davis@dlib.net)
</font><font color='#009900'>// License: Boost Software License See LICENSE.txt for the full license.
</font><font color='#0000FF'>#undef</font> DLIB_QUANTUM_COMPUTINg_ABSTRACT_
<font color='#0000FF'>#ifdef</font> DLIB_QUANTUM_COMPUTINg_ABSTRACT_
<font color='#0000FF'>#include</font> <font color='#5555FF'><</font>complex<font color='#5555FF'>></font>
<font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='../matrix.h.html'>../matrix.h</a>"
<font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='../rand.h.html'>../rand.h</a>"
<font color='#0000FF'>namespace</font> dlib
<b>{</b>
<font color='#009900'>// ----------------------------------------------------------------------------------------
</font>
<font color='#0000FF'>typedef</font> std::complex<font color='#5555FF'><</font><font color='#0000FF'><u>double</u></font><font color='#5555FF'>></font> qc_scalar_type;
<font color='#009900'>// ----------------------------------------------------------------------------------------
</font>
<font color='#0000FF'>class</font> <b><a name='quantum_register'></a>quantum_register</b>
<b>{</b>
<font color='#009900'>/*!
INITIAL VALUE
- num_bits() == 1
- state_vector().nr() == 2
- state_vector().nc() == 1
- state_vector()(0) == 1
- state_vector()(1) == 0
- probability_of_bit(0) == 0
- i.e. This register represents a single quantum bit and it is
completely in the 0 state.
WHAT THIS OBJECT REPRESENTS
This object represents a set of quantum bits.
!*/</font>
<font color='#0000FF'>public</font>:
<b><a name='quantum_register'></a>quantum_register</b><font face='Lucida Console'>(</font>
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
ensures
- this object is properly initialized
!*/</font>
<font color='#0000FF'><u>int</u></font> <b><a name='num_bits'></a>num_bits</b> <font face='Lucida Console'>(</font>
<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>;
<font color='#009900'>/*!
ensures
- returns the number of quantum bits in this register
!*/</font>
<font color='#0000FF'><u>void</u></font> <b><a name='set_num_bits'></a>set_num_bits</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'><u>int</u></font> new_num_bits
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
requires
- 1 <= new_num_bits <= 30
ensures
- #num_bits() == new_num_bits
- #state_vector().nr() == 2^new_num_bits
(i.e. the size of the state_vector is exponential in the number of bits in a register)
- for all valid i:
- probability_of_bit(i) == 0
!*/</font>
<font color='#0000FF'><u>void</u></font> <b><a name='zero_all_bits'></a>zero_all_bits</b><font face='Lucida Console'>(</font>
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
ensures
- for all valid i:
- probability_of_bit(i) == 0
!*/</font>
<font color='#0000FF'><u>void</u></font> <b><a name='append'></a>append</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'>const</font> quantum_register<font color='#5555FF'>&</font> reg
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
ensures
- #num_bits() == num_bits() + reg.num_bits()
- #this->state_vector() == tensor_product(this->state_vector(), reg.state_vector())
- The original bits in *this become the high order bits of the resulting
register and all the bits in reg end up as the low order bits in the
resulting register.
!*/</font>
<font color='#0000FF'><u>double</u></font> <b><a name='probability_of_bit'></a>probability_of_bit</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'><u>int</u></font> bit
<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>;
<font color='#009900'>/*!
requires
- 0 <= bit < num_bits()
ensures
- returns the probability of measuring the given bit and it being in the 1 state.
- The returned value is also equal to the sum of norm(state_vector()(i)) for all
i where the bit'th bit in i is set to 1. (note that the lowest order bit is bit 0)
!*/</font>
<font color='#0000FF'>template</font> <font color='#5555FF'><</font><font color='#0000FF'>typename</font> rand_type<font color='#5555FF'>></font>
<font color='#0000FF'><u>bool</u></font> <b><a name='measure_bit'></a>measure_bit</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'><u>int</u></font> bit,
rand_type<font color='#5555FF'>&</font> rnd
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
requires
- 0 <= bit < num_bits()
- rand_type == an implementation of dlib/rand/rand_float_abstract.h
ensures
- measures the given bit in this register. Let R denote the boolean
result of the measurement, where true means the bit was measured to
have value 1 and false means it had a value of 0.
- if (R == true) then
- returns true
- #probability_of_bit(bit) == 1
- else
- returns false
- #probability_of_bit(bit) == 0
!*/</font>
<font color='#0000FF'>template</font> <font color='#5555FF'><</font><font color='#0000FF'>typename</font> rand_type<font color='#5555FF'>></font>
<font color='#0000FF'><u>bool</u></font> <b><a name='measure_and_remove_bit'></a>measure_and_remove_bit</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'><u>int</u></font> bit,
rand_type<font color='#5555FF'>&</font> rnd
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
requires
- num_bits() > 1
- 0 <= bit < num_bits()
- rand_type == an implementation of dlib/rand/rand_float_abstract.h
ensures
- measures the given bit in this register. Let R denote the boolean
result of the measurement, where true means the bit was measured to
have value 1 and false means it had a value of 0.
- #num_bits() == num_bits() - 1
- removes the bit that was measured from this register.
- if (R == true) then
- returns true
- else
- returns false
!*/</font>
<font color='#0000FF'>const</font> matrix<font color='#5555FF'><</font>qc_scalar_type,<font color='#979000'>0</font>,<font color='#979000'>1</font><font color='#5555FF'>></font><font color='#5555FF'>&</font> <b><a name='state_vector'></a>state_vector</b><font face='Lucida Console'>(</font>
<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>;
<font color='#009900'>/*!
ensures
- returns a const reference to the state vector that describes the state of
the quantum bits in this register.
!*/</font>
matrix<font color='#5555FF'><</font>qc_scalar_type,<font color='#979000'>0</font>,<font color='#979000'>1</font><font color='#5555FF'>></font><font color='#5555FF'>&</font> <b><a name='state_vector'></a>state_vector</b><font face='Lucida Console'>(</font>
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
ensures
- returns a non-const reference to the state vector that describes the state of
the quantum bits in this register.
!*/</font>
<font color='#0000FF'><u>void</u></font> <b><a name='swap'></a>swap</b> <font face='Lucida Console'>(</font>
quantum_register<font color='#5555FF'>&</font> item
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
ensures
- swaps *this and item
!*/</font>
<b>}</b>;
<font color='#0000FF'>inline</font> <font color='#0000FF'><u>void</u></font> <b><a name='swap'></a>swap</b> <font face='Lucida Console'>(</font>
quantum_register<font color='#5555FF'>&</font> a,
quantum_register<font color='#5555FF'>&</font> b
<font face='Lucida Console'>)</font> <b>{</b> a.<font color='#BB00BB'>swap</font><font face='Lucida Console'>(</font>b<font face='Lucida Console'>)</font>; <b>}</b>
<font color='#009900'>/*!
provides a global swap function
!*/</font>
<font color='#009900'>// ----------------------------------------------------------------------------------------
</font>
<font color='#0000FF'>template</font> <font color='#5555FF'><</font><font color='#0000FF'>typename</font> T<font color='#5555FF'>></font>
<font color='#0000FF'>class</font> <b><a name='gate_exp'></a>gate_exp</b>
<b>{</b>
<font color='#009900'>/*!
REQUIREMENTS ON T
T must be some object that inherits from gate_exp and implements its own
version of operator() and compute_state_element().
WHAT THIS OBJECT REPRESENTS
This object represents an expression that evaluates to a quantum gate
that operates on T::num_bits qubits.
This object makes it easy to create new types of gate objects. All
you need to do is inherit from gate_exp in the proper way and
then you can use your new gate objects in conjunction with all the
others.
!*/</font>
<font color='#0000FF'>public</font>:
<font color='#0000FF'>static</font> <font color='#0000FF'>const</font> <font color='#0000FF'><u>long</u></font> num_bits <font color='#5555FF'>=</font> T::num_bits;
<font color='#0000FF'>static</font> <font color='#0000FF'>const</font> <font color='#0000FF'><u>long</u></font> dims <font color='#5555FF'>=</font> T::dims;
<b><a name='gate_exp'></a>gate_exp</b><font face='Lucida Console'>(</font>
T<font color='#5555FF'>&</font> exp
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
ensures
- #&ref() == &exp
!*/</font>
<font color='#0000FF'>const</font> qc_scalar_type <b><a name='operator'></a>operator</b><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font face='Lucida Console'>(</font>
<font color='#0000FF'><u>long</u></font> r,
<font color='#0000FF'><u>long</u></font> c
<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>;
<font color='#009900'>/*!
requires
- 0 <= r < dims
- 0 <= c < dims
ensures
- returns ref()(r,c)
!*/</font>
<font color='#0000FF'><u>void</u></font> <b><a name='apply_gate_to'></a>apply_gate_to</b> <font face='Lucida Console'>(</font>
quantum_register<font color='#5555FF'>&</font> reg
<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>;
<font color='#009900'>/*!
requires
- reg.num_bits() == num_bits
ensures
- applies this quantum gate to the given quantum register
- Let M represent the matrix for this quantum gate, then
#reg().state_vector() = M*reg().state_vector()
!*/</font>
<font color='#0000FF'>template</font> <font color='#5555FF'><</font><font color='#0000FF'>typename</font> exp<font color='#5555FF'>></font>
qc_scalar_type <b><a name='compute_state_element'></a>compute_state_element</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'><</font>exp<font color='#5555FF'>></font><font color='#5555FF'>&</font> reg,
<font color='#0000FF'><u>long</u></font> row_idx
<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>;
<font color='#009900'>/*!
requires
- reg.nr() == dims
- reg.nc() == 1
- 0 <= row_idx < dims
ensures
- Let M represent the matrix for this gate, then
this function returns rowm(M*reg, row_idx)
(i.e. returns the row_idx row of what you get when you apply this
gate to the given column vector in reg)
- This function works by calling ref().compute_state_element(reg,row_idx)
!*/</font>
<font color='#0000FF'>const</font> T<font color='#5555FF'>&</font> <b><a name='ref'></a>ref</b><font face='Lucida Console'>(</font>
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
ensures
- returns a reference to the subexpression contained in this object
!*/</font>
<font color='#0000FF'>const</font> matrix<font color='#5555FF'><</font>qc_scalar_type<font color='#5555FF'>></font> <b><a name='mat'></a>mat</b> <font face='Lucida Console'>(</font>
<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>;
<font color='#009900'>/*!
ensures
- returns a dense matrix object that contains the matrix for this gate
!*/</font>
<b>}</b>;
<font color='#009900'>// ----------------------------------------------------------------------------------------
</font>
<font color='#0000FF'>template</font> <font color='#5555FF'><</font><font color='#0000FF'>typename</font> T, <font color='#0000FF'>typename</font> U<font color='#5555FF'>></font>
<font color='#0000FF'>class</font> <b><a name='composite_gate'></a>composite_gate</b> : <font color='#0000FF'>public</font> gate_exp<font color='#5555FF'><</font>composite_gate<font color='#5555FF'><</font>T,U<font color='#5555FF'>></font> <font color='#5555FF'>></font>
<b>{</b>
<font color='#009900'>/*!
REQUIREMENTS ON T AND U
Both must be gate expressions that inherit from gate_exp
WHAT THIS OBJECT REPRESENTS
This object represents a quantum gate that is the tensor product of
two other quantum gates.
As an example, suppose you have 3 registers, reg_high, reg_low, and reg_all. Also
suppose that reg_all is what you get when you append reg_high and reg_low,
so reg_all.state_vector() == tensor_product(reg_high.state_vector(),reg_low.state_vector()).
Then applying a composite gate to reg_all would give you the same thing as
applying the lhs gate to reg_high and the rhs gate to reg_low and then appending
the two resulting registers. So the lhs gate of a composite_gate applies to
the high order bits of a regitser and the rhs gate applies to the lower order bits.
!*/</font>
<font color='#0000FF'>public</font>:
<b><a name='composite_gate'></a>composite_gate</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'>const</font> composite_gate<font color='#5555FF'>&</font> g
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
ensures
- *this is a copy of g
!*/</font>
<b><a name='composite_gate'></a>composite_gate</b><font face='Lucida Console'>(</font>
<font color='#0000FF'>const</font> gate_exp<font color='#5555FF'><</font>T<font color='#5555FF'>></font><font color='#5555FF'>&</font> lhs_,
<font color='#0000FF'>const</font> gate_exp<font color='#5555FF'><</font>U<font color='#5555FF'>></font><font color='#5555FF'>&</font> rhs_
<font face='Lucida Console'>)</font>:
<font color='#009900'>/*!
ensures
- #lhs == lhs_.ref()
- #rhs == rhs_.ref()
- #num_bits == T::num_bits + U::num_bits
- #dims == 2^num_bits
- #&ref() == this
!*/</font>
<font color='#0000FF'>const</font> qc_scalar_type <b><a name='operator'></a>operator</b><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font face='Lucida Console'>(</font>
<font color='#0000FF'><u>long</u></font> r,
<font color='#0000FF'><u>long</u></font> c
<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>;
<font color='#009900'>/*!
requires
- 0 <= r < dims
- 0 <= c < dims
ensures
- Let M denote the tensor product of lhs with rhs, then this function
returns M(r,c)
(i.e. returns lhs(r/U::dims,c/U::dims)*rhs(r%U::dims, c%U::dims))
!*/</font>
<font color='#0000FF'>template</font> <font color='#5555FF'><</font><font color='#0000FF'>typename</font> exp<font color='#5555FF'>></font>
qc_scalar_type compute_state_element <font face='Lucida Console'>(</font>
<font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'><</font>exp<font color='#5555FF'>></font><font color='#5555FF'>&</font> reg,
<font color='#0000FF'><u>long</u></font> row_idx
<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>;
<font color='#009900'>/*!
requires
- reg.nr() == dims
- reg.nc() == 1
- 0 <= row_idx < dims
ensures
- Let M represent the matrix for this gate, then this function
returns rowm(M*reg, row_idx)
(i.e. returns the row_idx row of what you get when you apply this
gate to the given column vector in reg)
- This function works by calling rhs.compute_state_element() and using elements
of the matrix in lhs.
!*/</font>
<font color='#0000FF'>static</font> <font color='#0000FF'>const</font> <font color='#0000FF'><u>long</u></font> num_bits;
<font color='#0000FF'>static</font> <font color='#0000FF'>const</font> <font color='#0000FF'><u>long</u></font> dims;
<font color='#0000FF'>const</font> T lhs;
<font color='#0000FF'>const</font> U rhs;
<b>}</b>;
<font color='#009900'>// ----------------------------------------------------------------------------------------
</font>
<font color='#0000FF'>template</font> <font color='#5555FF'><</font><font color='#0000FF'><u>long</u></font> bits<font color='#5555FF'>></font>
<font color='#0000FF'>class</font> <b><a name='gate'></a>gate</b> : <font color='#0000FF'>public</font> gate_exp<font color='#5555FF'><</font>gate<font color='#5555FF'><</font>bits<font color='#5555FF'>></font> <font color='#5555FF'>></font>
<b>{</b>
<font color='#009900'>/*!
REQUIREMENTS ON bits
0 < bits <= 30
WHAT THIS OBJECT REPRESENTS
This object represents a quantum gate that operates on bits qubits.
It stores its gate matrix explicitly in a dense in-memory matrix.
!*/</font>
<font color='#0000FF'>public</font>:
<b><a name='gate'></a>gate</b><font face='Lucida Console'>(</font>
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
ensures
- num_bits == bits
- dims == 2^bits
- #&ref() == this
- for all valid r and c:
#(*this)(r,c) == 0
!*/</font>
<b><a name='gate'></a>gate</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'>const</font> gate<font color='#5555FF'>&</font> g
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
ensures
- *this is a copy of g
!*/</font>
<font color='#0000FF'>template</font> <font color='#5555FF'><</font><font color='#0000FF'>typename</font> T<font color='#5555FF'>></font>
<font color='#0000FF'>explicit</font> <b><a name='gate'></a>gate</b><font face='Lucida Console'>(</font>
<font color='#0000FF'>const</font> gate_exp<font color='#5555FF'><</font>T<font color='#5555FF'>></font><font color='#5555FF'>&</font> g
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
requires
- T::num_bits == num_bits
ensures
- num_bits == bits
- dims == 2^bits
- #&ref() == this
- for all valid r and c:
#(*this)(r,c) == g(r,c)
!*/</font>
<font color='#0000FF'>const</font> qc_scalar_type<font color='#5555FF'>&</font> <b><a name='operator'></a>operator</b><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font face='Lucida Console'>(</font>
<font color='#0000FF'><u>long</u></font> r,
<font color='#0000FF'><u>long</u></font> c
<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>;
<font color='#009900'>/*!
requires
- 0 <= r < dims
- 0 <= c < dims
ensures
- Let M denote the matrix for this gate, then this function
returns a const reference to M(r,c)
!*/</font>
qc_scalar_type<font color='#5555FF'>&</font> <b><a name='operator'></a>operator</b><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font face='Lucida Console'>(</font>
<font color='#0000FF'><u>long</u></font> r,
<font color='#0000FF'><u>long</u></font> c
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
requires
- 0 <= r < dims
- 0 <= c < dims
ensures
- Let M denote the matrix for this gate, then this function
returns a non-const reference to M(r,c)
!*/</font>
<font color='#0000FF'>template</font> <font color='#5555FF'><</font><font color='#0000FF'>typename</font> exp<font color='#5555FF'>></font>
qc_scalar_type <b><a name='compute_state_element'></a>compute_state_element</b> <font face='Lucida Console'>(</font>
<font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'><</font>exp<font color='#5555FF'>></font><font color='#5555FF'>&</font> reg,
<font color='#0000FF'><u>long</u></font> row_idx
<font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>;
<font color='#009900'>/*!
requires
- reg.nr() == dims
- reg.nc() == 1
- 0 <= row_idx < dims
ensures
- Let M represent the matrix for this gate, then this function
returns rowm(M*reg, row_idx)
(i.e. returns the row_idx row of what you get when you apply this
gate to the given column vector in reg)
!*/</font>
<font color='#0000FF'>static</font> <font color='#0000FF'>const</font> <font color='#0000FF'><u>long</u></font> num_bits;
<font color='#0000FF'>static</font> <font color='#0000FF'>const</font> <font color='#0000FF'><u>long</u></font> dims;
<b>}</b>;
<font color='#009900'>// ----------------------------------------------------------------------------------------
</font>
<font color='#0000FF'>template</font> <font color='#5555FF'><</font><font color='#0000FF'>typename</font> T, <font color='#0000FF'>typename</font> U<font color='#5555FF'>></font>
<font color='#0000FF'>const</font> composite_gate<font color='#5555FF'><</font>T,U<font color='#5555FF'>></font> <b><a name='operator'></a>operator</b>, <font face='Lucida Console'>(</font>
<font color='#0000FF'>const</font> gate_exp<font color='#5555FF'><</font>T<font color='#5555FF'>></font><font color='#5555FF'>&</font> lhs,
<font color='#0000FF'>const</font> gate_exp<font color='#5555FF'><</font>U<font color='#5555FF'>></font><font color='#5555FF'>&</font> rhs
<font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>return</font> composite_gate<font color='#5555FF'><</font>T,U<font color='#5555FF'>></font><font face='Lucida Console'>(</font>lhs,rhs<font face='Lucida Console'>)</font>; <b>}</b>
<font color='#009900'>/*!
ensures
- returns a composite_gate that represents the tensor product of the lhs
gate with the rhs gate.
!*/</font>
<font color='#009900'>// ----------------------------------------------------------------------------------------
</font>
<font color='#0000FF'>namespace</font> quantum_gates
<b>{</b>
<font color='#0000FF'>inline</font> <font color='#0000FF'>const</font> gate<font color='#5555FF'><</font><font color='#979000'>1</font><font color='#5555FF'>></font> <b><a name='hadamard'></a>hadamard</b><font face='Lucida Console'>(</font>
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
ensures
- returns the Hadamard gate.
(i.e. A gate with a matrix of
|1, 1|
1/sqrt(2) * |1,-1| )
!*/</font>
<font color='#0000FF'>inline</font> <font color='#0000FF'>const</font> gate<font color='#5555FF'><</font><font color='#979000'>1</font><font color='#5555FF'>></font> <b><a name='x'></a>x</b><font face='Lucida Console'>(</font>
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
ensures
- returns the not gate.
(i.e. A gate with a matrix of
|0, 1|
|1, 0| )
!*/</font>
<font color='#0000FF'>inline</font> <font color='#0000FF'>const</font> gate<font color='#5555FF'><</font><font color='#979000'>1</font><font color='#5555FF'>></font> <b><a name='y'></a>y</b><font face='Lucida Console'>(</font>
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
ensures
- returns the y gate.
(i.e. A gate with a matrix of
|0,-i|
|i, 0| )
!*/</font>
<font color='#0000FF'>inline</font> <font color='#0000FF'>const</font> gate<font color='#5555FF'><</font><font color='#979000'>1</font><font color='#5555FF'>></font> <b><a name='z'></a>z</b><font face='Lucida Console'>(</font>
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
ensures
- returns the z gate.
(i.e. A gate with a matrix of
|1, 0|
|0,-1| )
!*/</font>
<font color='#0000FF'>inline</font> <font color='#0000FF'>const</font> gate<font color='#5555FF'><</font><font color='#979000'>1</font><font color='#5555FF'>></font> <b><a name='noop'></a>noop</b><font face='Lucida Console'>(</font>
<font face='Lucida Console'>)</font>;
<font color='#009900'>/*!
ensures
- returns the no-op or identity gate.
(i.e. A gate with a matrix of
|1, 0|
|0, 1| )
!*/</font>
<font color='#0000FF'>template</font> <font color='#5555FF'><</font>
<font color='#0000FF'><u>int</u></font> control_bit,
<font color='#0000FF'><u>int</u></font> target_bit
<font color='#5555FF'>></font>
<font color='#0000FF'>class</font> <b><a name='cnot'></a>cnot</b> : <font color='#0000FF'>public</font> gate_exp<font color='#5555FF'><</font>cnot<font color='#5555FF'><</font>control_bit, target_bit<font color='#5555FF'>></font> <font color='#5555FF'>></font>
<b>{</b>
<font color='#009900'>/*!
REQUIREMENTS ON control_bit AND target_bit
- control_bit != target_bit
WHAT THIS OBJECT REPRESENTS
This object represents the controlled-not quantum gate. It is a gate that
operates on abs(control_bit-target_bit)+1 qubits.
In terms of the computational basis vectors, this gate maps input
vectors to output vectors in the following way:
- if (the input vector corresponds to a state where the control_bit
qubit is 1) then
- this gate outputs the computational basis vector that
corresponds to the state where the target_bit has been flipped
with respect to the input vector
- else
- this gate outputs the input vector unmodified
!*/</font>
<b>}</b>;
<font color='#0000FF'>template</font> <font color='#5555FF'><</font>
<font color='#0000FF'><u>int</u></font> control_bit1,
<font color='#0000FF'><u>int</u></font> control_bit2,
<font color='#0000FF'><u>int</u></font> target_bit
<font color='#5555FF'>></font>
<font color='#0000FF'>class</font> <b><a name='toffoli'></a>toffoli</b> : <font color='#0000FF'>public</font> gate_exp<font color='#5555FF'><</font>toffoli<font color='#5555FF'><</font>control_bit1, control_bit2, target_bit<font color='#5555FF'>></font> <font color='#5555FF'>></font>
<b>{</b>
<font color='#009900'>/*!
REQUIREMENTS ON control_bit1, control_bit2, AND target_bit
- all the arguments denote different bits, i.e.:
- control_bit1 != target_bit
- control_bit2 != target_bit
- control_bit1 != control_bit2
- The target bit can't be in-between the control bits, i.e.:
- (control_bit1 < target_bit && control_bit2 < target_bit) ||
(control_bit1 > target_bit && control_bit2 > target_bit)
WHAT THIS OBJECT REPRESENTS
This object represents the toffoli variant of a controlled-not quantum gate.
It is a gate that operates on max(abs(control_bit2-target_bit),abs(control_bit1-target_bit))+1
qubits.
In terms of the computational basis vectors, this gate maps input
vectors to output vectors in the following way:
- if (the input vector corresponds to a state where the control_bit1 and
control_bit2 qubits are 1) then
- this gate outputs the computational basis vector that
corresponds to the state where the target_bit has been flipped
with respect to the input vector
- else
- this gate outputs the input vector unmodified
!*/</font>
<b>}</b>;
<font color='#009900'>// ------------------------------------------------------------------------------------
</font>
<b>}</b>
<font color='#009900'>// ----------------------------------------------------------------------------------------
</font>
<b>}</b>
<font color='#0000FF'>#endif</font> <font color='#009900'>// DLIB_QUANTUM_COMPUTINg_ABSTRACT_
</font>
</pre></body></html> | Java |
package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_1435 {
}
| Java |
/*
* Hibernate Validator, declare and validate application constraints
*
* License: Apache License, Version 2.0
* See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package org.hibernate.validator.test.internal.engine.messageinterpolation;
import static org.hibernate.validator.testutil.ConstraintViolationAssert.assertThat;
import static org.hibernate.validator.testutil.ConstraintViolationAssert.violationOf;
import static org.testng.Assert.fail;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.MessageInterpolator;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.Max;
import org.hibernate.validator.HibernateValidatorConfiguration;
import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator;
import org.hibernate.validator.spi.resourceloading.ResourceBundleLocator;
import org.hibernate.validator.testutil.TestForIssue;
import org.hibernate.validator.testutils.ValidatorUtil;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
/**
* @author Hardy Ferentschik
*/
@TestForIssue(jiraKey = "HV-798")
public class EscapedInterpolationVariableTest {
private Validator validator;
@BeforeTest
public void setUp() {
MessageInterpolator interpolator = new ResourceBundleMessageInterpolator(
new ResourceBundleLocator() {
@Override
public ResourceBundle getResourceBundle(Locale locale) {
return new ResourceBundle() {
@Override
protected Object handleGetObject(String key) {
if ( "key-1".equals( key ) ) {
return "\\{escapedParameterKey\\}";
}
else if ( "key-2".equals( key ) ) {
// since {} are unbalanced the original key (key-2) should be returned from the interpolation
return "{escapedParameterKey\\}";
}
else if ( "key-3".equals( key ) ) {
// since {} are unbalanced the original key (key-3) should be returned from the interpolation
return "\\{escapedParameterKey}";
}
else if ( "key-4".equals( key ) ) {
return "foo";
}
else {
fail( "Unexpected key: " + key );
}
return null;
}
@Override
public Enumeration<String> getKeys() {
throw new UnsupportedOperationException();
}
};
}
}, false
);
HibernateValidatorConfiguration config = ValidatorUtil.getConfiguration();
ValidatorFactory factory = config.messageInterpolator( interpolator ).buildValidatorFactory();
validator = factory.getValidator();
}
@Test
public void testEscapedOpeningAndClosingBrace() throws Exception {
Set<ConstraintViolation<A>> constraintViolations = validator.validate( new A() );
assertThat( constraintViolations ).containsOnlyViolations(
violationOf( Max.class ).withMessage( "{escapedParameterKey}" )
);
}
@Test
public void testEscapedClosingBrace() throws Exception {
Set<ConstraintViolation<B>> constraintViolations = validator.validate( new B() );
assertThat( constraintViolations ).containsOnlyViolations(
violationOf( Max.class ).withMessage( "{key-2}" )
);
}
@Test
public void testEscapedOpenBrace() throws Exception {
Set<ConstraintViolation<C>> constraintViolations = validator.validate( new C() );
assertThat( constraintViolations ).containsOnlyViolations(
violationOf( Max.class ).withMessage( "{key-3}" )
);
}
@Test
public void testMessageStaysUnchangedDueToSingleCurlyBrace() throws Exception {
Set<ConstraintViolation<D>> constraintViolations = validator.validate( new D() );
assertThat( constraintViolations ).containsOnlyViolations(
violationOf( Max.class ).withMessage( "{key-4} {" )
);
}
private class A {
@Max(value = 1, message = "{key-1}")
private int a = 2;
}
private class B {
@Max(value = 1, message = "{key-2}")
private int a = 2;
}
private class C {
@Max(value = 1, message = "{key-3}")
private int a = 2;
}
private class D {
@Max(value = 1, message = "{key-4} {")
private int a = 2;
}
}
| Java |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cats.Helpers;
using Cats.Models;
using Cats.Models.PSNP;
using Cats.Data;
using Cats.Services.Administration;
using Cats.Services.PSNP;
using Cats.Services.Security;
using Cats.Services.Transaction;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Cats.Services.EarlyWarning;
using Cats.Services.Common;
using Cats.Infrastructure;
using log4net;
using IAdminUnitService = Cats.Services.EarlyWarning.IAdminUnitService;
namespace Cats.Areas.PSNP
{
public class RegionalPSNPPlanController : Controller
{
private int _regionalPsnpId = 0;
private readonly IRegionalPSNPPlanService _regionalPSNPPlanService;
private readonly IAdminUnitService _adminUnitService;
private readonly IRationService _rationService;
private readonly IBusinessProcessService _BusinessProcessService;
private readonly IBusinessProcessStateService _BusinessProcessStateService;
private readonly IApplicationSettingService _ApplicationSettingService;
private readonly ILog _log;
private readonly IPlanService _planService;
private readonly IUserAccountService _userAccountService;
private readonly Cats.Services.Transaction.ITransactionService _transactionService;
private readonly IUserProfileService _userProfileService;
public RegionalPSNPPlanController(IRegionalPSNPPlanService regionalPSNPPlanServiceParam
, IRationService rationServiceParam
, IAdminUnitService adminUnitServiceParam
, IBusinessProcessService BusinessProcessServiceParam
, IBusinessProcessStateService BusinessProcessStateServiceParam
, IApplicationSettingService ApplicationSettingParam
, ILog log
, IPlanService planService
,IUserAccountService userAccountService, ITransactionService transactionService, IUserProfileService userProfileService)
{
this._regionalPSNPPlanService = regionalPSNPPlanServiceParam;
this._rationService = rationServiceParam;
this._adminUnitService = adminUnitServiceParam;
this._BusinessProcessService = BusinessProcessServiceParam;
this._BusinessProcessStateService = BusinessProcessStateServiceParam;
this._ApplicationSettingService = ApplicationSettingParam;
this._log = log;
this._planService = planService;
this._userAccountService = userAccountService;
_transactionService = transactionService;
this._userProfileService = userProfileService;
}
public IEnumerable<RegionalPSNPPlanViewModel> toViewModel(IEnumerable<Cats.Models.RegionalPSNPPlan> list)
{
var datePref = _userAccountService.GetUserInfo(HttpContext.User.Identity.Name).DatePreference;
try
{
return (from plan in list
select new RegionalPSNPPlanViewModel
{
RegionalPSNPPlanID = plan.RegionalPSNPPlanID,
Duration = plan.Duration,
PlanName = plan.Plan.PlanName,
Year = plan.Year,
// RegionName = plan.Region.Name,
RationName = plan.Ration.RefrenceNumber,
From = plan.Plan.StartDate.ToCTSPreferedDateFormat(datePref),
To = plan.Plan.EndDate.ToCTSPreferedDateFormat(datePref),
StatusName = plan.AttachedBusinessProcess.CurrentState.BaseStateTemplate.Name,
UserId = plan.User
});
}
catch (Exception e)
{
var log = new Logger();
log.LogAllErrorsMesseges(e,_log);
}
return new List<RegionalPSNPPlanViewModel>();
}
public void LoadLookups()
{
ViewBag.RegionID = new SelectList(_adminUnitService.FindBy(t => t.AdminUnitTypeID == 2), "AdminUnitID", "Name");
ViewBag.RationID = new SelectList(_rationService.GetAllRation(), "RationID", "RefrenceNumber");
var psnpPlans = _planService.FindBy(p => p.ProgramID == 2);
ViewBag.PlanId = new SelectList(_planService.FindBy(p => p.ProgramID == 2), "PlanID", "PlanName");
}
//
// GET: /PSNP/RegionalPSNPPlan/
public ActionResult Index()
{
IEnumerable<RegionalPSNPPlan> list = (IEnumerable<Cats.Models.RegionalPSNPPlan>)_regionalPSNPPlanService.GetAllRegionalPSNPPlan();
return View(list);
}
public ActionResult GetListAjax([DataSourceRequest] DataSourceRequest request)
{
IEnumerable<Cats.Models.RegionalPSNPPlan> list = (IEnumerable<Cats.Models.RegionalPSNPPlan>)_regionalPSNPPlanService.GetAllRegionalPSNPPlan().OrderByDescending(m=>m.RegionalPSNPPlanID);
return Json(toViewModel(list).ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
public ActionResult Print(int id = 0)
{
if (id == 0)
{
RedirectToAction("Index");
}
var reportPath = Server.MapPath("~/Report/PSNP/AnnualPlan.rdlc");
var reportData = _regionalPSNPPlanService.GetAnnualPlanRpt(id);
var dataSourceName = "annualplan";
var result = ReportHelper.PrintReport(reportPath, reportData, dataSourceName);
return File(result.RenderBytes, result.MimeType);
}
public ActionResult Details(int id = 0)
{
RegionalPSNPPlan regionalpsnpplan = _regionalPSNPPlanService.FindById(id);
if (regionalpsnpplan == null)
{
return HttpNotFound();
}
return View(regionalpsnpplan);
}
public ActionResult Promote(BusinessProcessState st)
{
var isReject = _BusinessProcessService.CheckPlanBeforeReject(st);
if (isReject)
{
}
_BusinessProcessService.PromotWorkflow(st);
return RedirectToAction("Index");
}
public ActionResult promotWorkflow(int id, int nextState)
{
RegionalPSNPPlan item = _regionalPSNPPlanService.FindById(id);
item.StatusID = nextState;
_regionalPSNPPlanService.UpdateRegionalPSNPPlan(item);
if (item.StatusID == (int) Cats.Models.Constant.PSNPWorkFlow.Completed)
PostPSNP(item);
return RedirectToAction("Index");
}
public void PostPSNP(RegionalPSNPPlan plan)
{
try
{
var ration = _rationService.FindBy(r => r.RationID == plan.RationID).FirstOrDefault();
_transactionService.PostPSNPPlan(plan, ration);
}
catch (Exception ex)
{
_log.Error("Error in posting psnp:",new Exception(ex.Message));
}
}
//
// GET: /PSNP/RegionalPSNPPlan/Create
public ActionResult Create()
{
LoadLookups();
return View();
}
//
// POST: /PSNP/RegionalPSNPPlan/Create
[HttpPost]
public ActionResult Create(RegionalPSNPPlan regionalpsnpplan)
{
var planName = regionalpsnpplan.Plan.PlanName;
var startDate = regionalpsnpplan.Plan.StartDate;
var firstDayOfTheMonth = startDate.AddDays(1 - startDate.Day);
var endDate = firstDayOfTheMonth.AddMonths(regionalpsnpplan.Duration).AddDays(-1);
UserProfile user = _userProfileService.GetUser(User.Identity.Name);
if (ModelState.IsValid)
{
_regionalPSNPPlanService.AddPsnpPlan(planName, firstDayOfTheMonth, endDate);
var plan = _planService.Get(m => m.PlanName == planName,null,"Program").FirstOrDefault();
regionalpsnpplan.Plan = plan;
//check if this psnp plan exitsts for this year and Plan
var exists = plan != null && _regionalPSNPPlanService.DoesPsnpPlanExistForThisRegion(plan.PlanID, regionalpsnpplan.Year);
if (!exists)
{
int BP_PSNP = _ApplicationSettingService.getPSNPWorkflow();
if (BP_PSNP != 0)
{
BusinessProcessState createdstate = new BusinessProcessState
{
DatePerformed = DateTime.Now,
PerformedBy = "System",
Comment = "Created workflow for PSNP Plan"
};
var psnpPlan= _regionalPSNPPlanService.CreatePsnpPlan(regionalpsnpplan.Year,regionalpsnpplan.Duration,regionalpsnpplan.RationID,regionalpsnpplan.StatusID,plan.PlanID,user.UserProfileID);
//_planService.ChangePlanStatus(regionalpsnpplan.PlanId);
BusinessProcess bp = _BusinessProcessService.CreateBusinessProcess(BP_PSNP,
regionalpsnpplan.
RegionalPSNPPlanID,
"PSNP", createdstate);
psnpPlan.StatusID = bp.BusinessProcessID;
_regionalPSNPPlanService.UpdateRegionalPSNPPlan(psnpPlan);
return RedirectToAction("Index");
}
ViewBag.ErrorMessage1 = "The workflow assosiated with PSNP planning doesnot exist.";
ViewBag.ErrorMessage2 = "Please make sure the workflow is created and configured.";
}
LoadLookups();
ModelState.AddModelError("Errors", @"PSNP plan already made for this period and plan Name.");
return View(regionalpsnpplan);
}
LoadLookups();
return View(regionalpsnpplan);
}
//
// GET: /PSNP/RegionalPSNPPlan/Edit/5
public ActionResult Edit(int id = 0)
{
LoadLookups();
RegionalPSNPPlan regionalpsnpplan = _regionalPSNPPlanService.FindById(id);
if (regionalpsnpplan == null)
{
return HttpNotFound();
}
return View(regionalpsnpplan);
}
[HttpPost]
public ActionResult Edit(RegionalPSNPPlan regionalpsnpplan)
{
if (ModelState.IsValid)
{
_regionalPSNPPlanService.UpdateRegionalPSNPPlan(regionalpsnpplan);
return RedirectToAction("Index");
}
LoadLookups();
return View(regionalpsnpplan);
}
//
// GET: /PSNP/RegionalPSNPPlan/Delete/5
public ActionResult Delete(int id = 0)
{
RegionalPSNPPlan regionalpsnpplan = _regionalPSNPPlanService.FindById(id);
if (regionalpsnpplan == null)
{
return HttpNotFound();
}
return View(regionalpsnpplan);
}
//
// POST: /PSNP/RegionalPSNPPlan/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
_regionalPSNPPlanService.DeleteById(id);
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
}
} | Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_80) on Thu Jun 18 14:08:33 EDT 2015 -->
<title>UpdateStatement (apache-cassandra API)</title>
<meta name="date" content="2015-06-18">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="UpdateStatement (apache-cassandra API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/UpdateStatement.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/apache/cassandra/cql/WhereClause.html" title="class in org.apache.cassandra.cql"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/cassandra/cql/UpdateStatement.html" target="_top">Frames</a></li>
<li><a href="UpdateStatement.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#fields_inherited_from_class_org.apache.cassandra.cql.AbstractModification">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.cassandra.cql</div>
<h2 title="Class UpdateStatement" class="title">Class UpdateStatement</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li><a href="../../../../org/apache/cassandra/cql/AbstractModification.html" title="class in org.apache.cassandra.cql">org.apache.cassandra.cql.AbstractModification</a></li>
<li>
<ul class="inheritance">
<li>org.apache.cassandra.cql.UpdateStatement</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="strong">UpdateStatement</span>
extends <a href="../../../../org/apache/cassandra/cql/AbstractModification.html" title="class in org.apache.cassandra.cql">AbstractModification</a></pre>
<div class="block">An <code>UPDATE</code> statement parsed from a CQL query statement.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="fields_inherited_from_class_org.apache.cassandra.cql.AbstractModification">
<!-- -->
</a>
<h3>Fields inherited from class org.apache.cassandra.cql.<a href="../../../../org/apache/cassandra/cql/AbstractModification.html" title="class in org.apache.cassandra.cql">AbstractModification</a></h3>
<code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html#cLevel">cLevel</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#columnFamily">columnFamily</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#defaultConsistency">defaultConsistency</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#keyName">keyName</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#keyspace">keyspace</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#timestamp">timestamp</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#timeToLive">timeToLive</a></code></li>
</ul>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#UpdateStatement(java.lang.String,%20java.lang.String,%20java.lang.String,%20java.util.List,%20java.util.List,%20java.util.List,%20org.apache.cassandra.cql.Attributes)">UpdateStatement</a></strong>(java.lang.String keyspace,
java.lang.String columnFamily,
java.lang.String keyName,
java.util.List<<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>> columnNames,
java.util.List<<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>> columnValues,
java.util.List<<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>> keys,
<a href="../../../../org/apache/cassandra/cql/Attributes.html" title="class in org.apache.cassandra.cql">Attributes</a> attrs)</code>
<div class="block">Creates a new UpdateStatement from a column family name, a consistency level,
key, and lists of column names and values.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#UpdateStatement(java.lang.String,%20java.lang.String,%20java.lang.String,%20java.util.Map,%20java.util.List,%20org.apache.cassandra.cql.Attributes)">UpdateStatement</a></strong>(java.lang.String keyspace,
java.lang.String columnFamily,
java.lang.String keyName,
java.util.Map<<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>,<a href="../../../../org/apache/cassandra/cql/Operation.html" title="class in org.apache.cassandra.cql">Operation</a>> columns,
java.util.List<<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>> keys,
<a href="../../../../org/apache/cassandra/cql/Attributes.html" title="class in org.apache.cassandra.cql">Attributes</a> attrs)</code>
<div class="block">Creates a new UpdateStatement from a column family name, columns map, consistency
level, and key term.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#getColumnFamily()">getColumnFamily</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.util.List<<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#getColumnNames()">getColumnNames</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.util.Map<<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>,<a href="../../../../org/apache/cassandra/cql/Operation.html" title="class in org.apache.cassandra.cql">Operation</a>></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#getColumns()">getColumns</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.util.List<<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#getColumnValues()">getColumnValues</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../org/apache/cassandra/db/marshal/AbstractType.html" title="class in org.apache.cassandra.db.marshal">AbstractType</a><?></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#getComparator(java.lang.String)">getComparator</a></strong>(java.lang.String keyspace)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../org/apache/cassandra/db/ConsistencyLevel.html" title="enum in org.apache.cassandra.db">ConsistencyLevel</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#getConsistencyLevel()">getConsistencyLevel</a></strong>()</code>
<div class="block">Returns the consistency level of this <code>UPDATE</code> statement, either
one parsed from the CQL statement, or the default level otherwise.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.util.List<<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#getKeys()">getKeys</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../org/apache/cassandra/db/marshal/AbstractType.html" title="class in org.apache.cassandra.db.marshal">AbstractType</a><?></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#getKeyType(java.lang.String)">getKeyType</a></strong>(java.lang.String keyspace)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#isSetConsistencyLevel()">isSetConsistencyLevel</a></strong>()</code>
<div class="block">True if an explicit consistency level was parsed from the statement.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.util.List<<a href="../../../../org/apache/cassandra/db/IMutation.html" title="interface in org.apache.cassandra.db">IMutation</a>></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#prepareRowMutations(java.lang.String,%20org.apache.cassandra.thrift.ThriftClientState,%20java.util.List)">prepareRowMutations</a></strong>(java.lang.String keyspace,
<a href="../../../../org/apache/cassandra/thrift/ThriftClientState.html" title="class in org.apache.cassandra.thrift">ThriftClientState</a> clientState,
java.util.List<java.nio.ByteBuffer> variables)</code>
<div class="block">Convert statement into a list of mutations to apply on the server</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.util.List<<a href="../../../../org/apache/cassandra/db/IMutation.html" title="interface in org.apache.cassandra.db">IMutation</a>></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#prepareRowMutations(java.lang.String,%20org.apache.cassandra.thrift.ThriftClientState,%20java.lang.Long,%20java.util.List)">prepareRowMutations</a></strong>(java.lang.String keyspace,
<a href="../../../../org/apache/cassandra/thrift/ThriftClientState.html" title="class in org.apache.cassandra.thrift">ThriftClientState</a> clientState,
java.lang.Long timestamp,
java.util.List<java.nio.ByteBuffer> variables)</code>
<div class="block">Convert statement into a list of mutations to apply on the server</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql/UpdateStatement.html#toString()">toString</a></strong>()</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_org.apache.cassandra.cql.AbstractModification">
<!-- -->
</a>
<h3>Methods inherited from class org.apache.cassandra.cql.<a href="../../../../org/apache/cassandra/cql/AbstractModification.html" title="class in org.apache.cassandra.cql">AbstractModification</a></h3>
<code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html#getKeyName()">getKeyName</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#getKeyspace()">getKeyspace</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#getTimestamp(org.apache.cassandra.thrift.ThriftClientState)">getTimestamp</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#getTimeToLive()">getTimeToLive</a>, <a href="../../../../org/apache/cassandra/cql/AbstractModification.html#isSetTimestamp()">isSetTimestamp</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="UpdateStatement(java.lang.String, java.lang.String, java.lang.String, java.util.Map, java.util.List, org.apache.cassandra.cql.Attributes)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>UpdateStatement</h4>
<pre>public UpdateStatement(java.lang.String keyspace,
java.lang.String columnFamily,
java.lang.String keyName,
java.util.Map<<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>,<a href="../../../../org/apache/cassandra/cql/Operation.html" title="class in org.apache.cassandra.cql">Operation</a>> columns,
java.util.List<<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>> keys,
<a href="../../../../org/apache/cassandra/cql/Attributes.html" title="class in org.apache.cassandra.cql">Attributes</a> attrs)</pre>
<div class="block">Creates a new UpdateStatement from a column family name, columns map, consistency
level, and key term.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>keyspace</code> - Keyspace (optional)</dd><dd><code>columnFamily</code> - column family name</dd><dd><code>keyName</code> - alias key name</dd><dd><code>columns</code> - a map of column name/values pairs</dd><dd><code>keys</code> - the keys to update</dd><dd><code>attrs</code> - additional attributes for statement (CL, timestamp, timeToLive)</dd></dl>
</li>
</ul>
<a name="UpdateStatement(java.lang.String, java.lang.String, java.lang.String, java.util.List, java.util.List, java.util.List, org.apache.cassandra.cql.Attributes)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>UpdateStatement</h4>
<pre>public UpdateStatement(java.lang.String keyspace,
java.lang.String columnFamily,
java.lang.String keyName,
java.util.List<<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>> columnNames,
java.util.List<<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>> columnValues,
java.util.List<<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>> keys,
<a href="../../../../org/apache/cassandra/cql/Attributes.html" title="class in org.apache.cassandra.cql">Attributes</a> attrs)</pre>
<div class="block">Creates a new UpdateStatement from a column family name, a consistency level,
key, and lists of column names and values. It is intended for use with the
alternate update format, <code>INSERT</code>.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>keyspace</code> - Keyspace (optional)</dd><dd><code>columnFamily</code> - column family name</dd><dd><code>keyName</code> - alias key name</dd><dd><code>columnNames</code> - list of column names</dd><dd><code>columnValues</code> - list of column values (corresponds to names)</dd><dd><code>keys</code> - the keys to update</dd><dd><code>attrs</code> - additional attributes for statement (CL, timestamp, timeToLive)</dd></dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getConsistencyLevel()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getConsistencyLevel</h4>
<pre>public <a href="../../../../org/apache/cassandra/db/ConsistencyLevel.html" title="enum in org.apache.cassandra.db">ConsistencyLevel</a> getConsistencyLevel()</pre>
<div class="block">Returns the consistency level of this <code>UPDATE</code> statement, either
one parsed from the CQL statement, or the default level otherwise.</div>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html#getConsistencyLevel()">getConsistencyLevel</a></code> in class <code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html" title="class in org.apache.cassandra.cql">AbstractModification</a></code></dd>
<dt><span class="strong">Returns:</span></dt><dd>the consistency level as a Thrift enum.</dd></dl>
</li>
</ul>
<a name="isSetConsistencyLevel()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isSetConsistencyLevel</h4>
<pre>public boolean isSetConsistencyLevel()</pre>
<div class="block">True if an explicit consistency level was parsed from the statement.</div>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html#isSetConsistencyLevel()">isSetConsistencyLevel</a></code> in class <code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html" title="class in org.apache.cassandra.cql">AbstractModification</a></code></dd>
<dt><span class="strong">Returns:</span></dt><dd>true if a consistency was parsed, false otherwise.</dd></dl>
</li>
</ul>
<a name="prepareRowMutations(java.lang.String, org.apache.cassandra.thrift.ThriftClientState, java.util.List)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>prepareRowMutations</h4>
<pre>public java.util.List<<a href="../../../../org/apache/cassandra/db/IMutation.html" title="interface in org.apache.cassandra.db">IMutation</a>> prepareRowMutations(java.lang.String keyspace,
<a href="../../../../org/apache/cassandra/thrift/ThriftClientState.html" title="class in org.apache.cassandra.thrift">ThriftClientState</a> clientState,
java.util.List<java.nio.ByteBuffer> variables)
throws <a href="../../../../org/apache/cassandra/exceptions/InvalidRequestException.html" title="class in org.apache.cassandra.exceptions">InvalidRequestException</a>,
<a href="../../../../org/apache/cassandra/exceptions/UnauthorizedException.html" title="class in org.apache.cassandra.exceptions">UnauthorizedException</a></pre>
<div class="block">Convert statement into a list of mutations to apply on the server</div>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html#prepareRowMutations(java.lang.String,%20org.apache.cassandra.thrift.ThriftClientState,%20java.util.List)">prepareRowMutations</a></code> in class <code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html" title="class in org.apache.cassandra.cql">AbstractModification</a></code></dd>
<dt><span class="strong">Parameters:</span></dt><dd><code>keyspace</code> - The working keyspace</dd><dd><code>clientState</code> - current client status</dd>
<dt><span class="strong">Returns:</span></dt><dd>list of the mutations</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../../../org/apache/cassandra/exceptions/InvalidRequestException.html" title="class in org.apache.cassandra.exceptions">InvalidRequestException</a></code> - on the wrong request</dd>
<dd><code><a href="../../../../org/apache/cassandra/exceptions/UnauthorizedException.html" title="class in org.apache.cassandra.exceptions">UnauthorizedException</a></code></dd></dl>
</li>
</ul>
<a name="prepareRowMutations(java.lang.String, org.apache.cassandra.thrift.ThriftClientState, java.lang.Long, java.util.List)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>prepareRowMutations</h4>
<pre>public java.util.List<<a href="../../../../org/apache/cassandra/db/IMutation.html" title="interface in org.apache.cassandra.db">IMutation</a>> prepareRowMutations(java.lang.String keyspace,
<a href="../../../../org/apache/cassandra/thrift/ThriftClientState.html" title="class in org.apache.cassandra.thrift">ThriftClientState</a> clientState,
java.lang.Long timestamp,
java.util.List<java.nio.ByteBuffer> variables)
throws <a href="../../../../org/apache/cassandra/exceptions/InvalidRequestException.html" title="class in org.apache.cassandra.exceptions">InvalidRequestException</a>,
<a href="../../../../org/apache/cassandra/exceptions/UnauthorizedException.html" title="class in org.apache.cassandra.exceptions">UnauthorizedException</a></pre>
<div class="block">Convert statement into a list of mutations to apply on the server</div>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html#prepareRowMutations(java.lang.String,%20org.apache.cassandra.thrift.ThriftClientState,%20java.lang.Long,%20java.util.List)">prepareRowMutations</a></code> in class <code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html" title="class in org.apache.cassandra.cql">AbstractModification</a></code></dd>
<dt><span class="strong">Parameters:</span></dt><dd><code>keyspace</code> - The working keyspace</dd><dd><code>clientState</code> - current client status</dd><dd><code>timestamp</code> - global timestamp to use for all mutations</dd>
<dt><span class="strong">Returns:</span></dt><dd>list of the mutations</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../../../org/apache/cassandra/exceptions/InvalidRequestException.html" title="class in org.apache.cassandra.exceptions">InvalidRequestException</a></code> - on the wrong request</dd>
<dd><code><a href="../../../../org/apache/cassandra/exceptions/UnauthorizedException.html" title="class in org.apache.cassandra.exceptions">UnauthorizedException</a></code></dd></dl>
</li>
</ul>
<a name="getColumnFamily()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getColumnFamily</h4>
<pre>public java.lang.String getColumnFamily()</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html#getColumnFamily()">getColumnFamily</a></code> in class <code><a href="../../../../org/apache/cassandra/cql/AbstractModification.html" title="class in org.apache.cassandra.cql">AbstractModification</a></code></dd>
</dl>
</li>
</ul>
<a name="getKeys()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getKeys</h4>
<pre>public java.util.List<<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>> getKeys()</pre>
</li>
</ul>
<a name="getColumns()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getColumns</h4>
<pre>public java.util.Map<<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>,<a href="../../../../org/apache/cassandra/cql/Operation.html" title="class in org.apache.cassandra.cql">Operation</a>> getColumns()
throws <a href="../../../../org/apache/cassandra/exceptions/InvalidRequestException.html" title="class in org.apache.cassandra.exceptions">InvalidRequestException</a></pre>
<dl><dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../../../org/apache/cassandra/exceptions/InvalidRequestException.html" title="class in org.apache.cassandra.exceptions">InvalidRequestException</a></code></dd></dl>
</li>
</ul>
<a name="toString()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>toString</h4>
<pre>public java.lang.String toString()</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>toString</code> in class <code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
<a name="getKeyType(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getKeyType</h4>
<pre>public <a href="../../../../org/apache/cassandra/db/marshal/AbstractType.html" title="class in org.apache.cassandra.db.marshal">AbstractType</a><?> getKeyType(java.lang.String keyspace)</pre>
</li>
</ul>
<a name="getComparator(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getComparator</h4>
<pre>public <a href="../../../../org/apache/cassandra/db/marshal/AbstractType.html" title="class in org.apache.cassandra.db.marshal">AbstractType</a><?> getComparator(java.lang.String keyspace)</pre>
</li>
</ul>
<a name="getColumnNames()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getColumnNames</h4>
<pre>public java.util.List<<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>> getColumnNames()</pre>
</li>
</ul>
<a name="getColumnValues()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getColumnValues</h4>
<pre>public java.util.List<<a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql">Term</a>> getColumnValues()</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/UpdateStatement.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/apache/cassandra/cql/Term.html" title="class in org.apache.cassandra.cql"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/apache/cassandra/cql/WhereClause.html" title="class in org.apache.cassandra.cql"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/cassandra/cql/UpdateStatement.html" target="_top">Frames</a></li>
<li><a href="UpdateStatement.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#fields_inherited_from_class_org.apache.cassandra.cql.AbstractModification">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2015 The Apache Software Foundation</small></p>
</body>
</html>
| Java |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.giraph.benchmark;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.giraph.GiraphConfiguration;
import org.apache.giraph.examples.MinimumDoubleCombiner;
import org.apache.giraph.graph.EdgeListVertex;
import org.apache.giraph.graph.GiraphJob;
import org.apache.giraph.io.PseudoRandomVertexInputFormat;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Logger;
import java.io.IOException;
/**
* Single-source shortest paths benchmark.
*/
public class ShortestPathsBenchmark implements Tool {
/** Class logger */
private static final Logger LOG =
Logger.getLogger(ShortestPathsBenchmark.class);
/** Configuration */
private Configuration conf;
/**
* Vertex implementation
*/
public static class ShortestPathsBenchmarkVertex extends
EdgeListVertex<LongWritable, DoubleWritable, DoubleWritable,
DoubleWritable> {
@Override
public void compute(Iterable<DoubleWritable> messages) throws IOException {
ShortestPathsComputation.computeShortestPaths(this, messages);
}
}
@Override
public Configuration getConf() {
return conf;
}
@Override
public void setConf(Configuration conf) {
this.conf = conf;
}
@Override
public final int run(final String[] args) throws Exception {
Options options = new Options();
options.addOption("h", "help", false, "Help");
options.addOption("v", "verbose", false, "Verbose");
options.addOption("w",
"workers",
true,
"Number of workers");
options.addOption("V",
"aggregateVertices",
true,
"Aggregate vertices");
options.addOption("e",
"edgesPerVertex",
true,
"Edges per vertex");
options.addOption("c",
"vertexClass",
true,
"Vertex class (0 for HashMapVertex, 1 for EdgeListVertex)");
options.addOption("nc",
"noCombiner",
false,
"Don't use a combiner");
HelpFormatter formatter = new HelpFormatter();
if (args.length == 0) {
formatter.printHelp(getClass().getName(), options, true);
return 0;
}
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption('h')) {
formatter.printHelp(getClass().getName(), options, true);
return 0;
}
if (!cmd.hasOption('w')) {
LOG.info("Need to choose the number of workers (-w)");
return -1;
}
if (!cmd.hasOption('V')) {
LOG.info("Need to set the aggregate vertices (-V)");
return -1;
}
if (!cmd.hasOption('e')) {
LOG.info("Need to set the number of edges " +
"per vertex (-e)");
return -1;
}
int workers = Integer.parseInt(cmd.getOptionValue('w'));
GiraphJob job = new GiraphJob(getConf(), getClass().getName());
if (!cmd.hasOption('c') ||
(Integer.parseInt(cmd.getOptionValue('c')) == 1)) {
job.getConfiguration().setVertexClass(ShortestPathsBenchmarkVertex.class);
} else {
job.getConfiguration().setVertexClass(
HashMapVertexShortestPathsBenchmark.class);
}
LOG.info("Using class " +
job.getConfiguration().get(GiraphConfiguration.VERTEX_CLASS));
job.getConfiguration().setVertexInputFormatClass(
PseudoRandomVertexInputFormat.class);
if (!cmd.hasOption("nc")) {
job.getConfiguration().setVertexCombinerClass(
MinimumDoubleCombiner.class);
}
job.getConfiguration().setWorkerConfiguration(workers, workers, 100.0f);
job.getConfiguration().setLong(
PseudoRandomVertexInputFormat.AGGREGATE_VERTICES,
Long.parseLong(cmd.getOptionValue('V')));
job.getConfiguration().setLong(
PseudoRandomVertexInputFormat.EDGES_PER_VERTEX,
Long.parseLong(cmd.getOptionValue('e')));
boolean isVerbose = false;
if (cmd.hasOption('v')) {
isVerbose = true;
}
if (job.run(isVerbose)) {
return 0;
} else {
return -1;
}
}
/**
* Execute the benchmark.
*
* @param args Typically the command line arguments.
* @throws Exception Any exception from the computation.
*/
public static void main(final String[] args) throws Exception {
System.exit(ToolRunner.run(new ShortestPathsBenchmark(), args));
}
}
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gtk;
namespace SailorsTab.Common
{
public class UIHelper
{
public static void ShowErrorDialog(Gtk.Widget parent, string message, params object[] parameters)
{
MessageDialog messagedialog1 = new MessageDialog(findParentWindow(parent), (DialogFlags)3, MessageType.Error, ButtonsType.Ok, message, parameters);
messagedialog1.Run();
messagedialog1.Destroy();
}
public static int ShowInfoDialog(Gtk.Widget parent, string message, params object[] parameters)
{
MessageDialog messagedialog1 = new MessageDialog(findParentWindow(parent), (DialogFlags)3, MessageType.Question, ButtonsType.YesNo, false, message, parameters);
int num1 = messagedialog1.Run();
messagedialog1.Destroy();
return num1;
}
private static Window findParentWindow(Gtk.Widget parent)
{
Window window = null;
do
{
if (parent is Window)
{
window = (Window)parent;
}
else
{
parent = parent.Parent;
}
}
while (window == null);
return window;
}
}
}
| Java |
# NetApp Data ONTAP device module
[](https://coveralls.io/r/fatmcgav/fatmcgav-netapp?branch=develop)
####Table of Contents
1. [Overview](#overview)
1. [Module Description](#module-description)
1. [Setup](#setup)
* [Requirements](#requirements)
* [NetApp Manageability SDK](#netapp-manageability-sdk)
* [Device Proxy System Setup](#device-proxy-system-setup)
1. [Usage](#usage)
* [Beginning with netapp](#beginning-with-netapp)
<!-- * [NetApp operations](#netapp-operations) -->
* [Classes and Defined Types](#classes-and-defined-types)
* [Types and Providers](#types-and-providers)
1. [Limitations](#limitations)
* [TODO](#todo)
1. [Development](#development)
* [Testing](#testing)
* [Contributors](#contributors)
## Overview
The NetApp Data ONTAP device module is designed to add support for managing
NetApp Data ONTAP configuration using Puppet and its Network Device
functionality.
The NetApp Data ONTAP device module has been written and tested against NetApp
Data ONTAP 8.2 Cluster-mode.
<!--
- It may also work on 7-mode.
- It should be compatible with other ONTAP versions than just 8.2, but not tested
-->
## Module Description
This module uses the NetApp Manageability SDK to manage various aspects of the
NetApp Data ONTAP software.
The following items are supported:
XXX Verify these
* Creation, modification and deletion of volumes, including auto-increment,
snapshot schedules and volume options.
* Creation, modification and deletion of QTrees.
* Creation, modification and deletion of NFS Exports, including NFS export
security.
* Creation, modification and deletion of users, groups and roles.
* Creation, modification and deletion of Quotas.
* Creation of snapmirror relationships.
* Creation of snapmirror schedules.
## Setup
## Requirements
Because we can not directly install Puppet on the NetApp Data ONTAP operating
system, it must be managed through an intermediate proxy system running `puppet
device`. The requirements for the proxy system are:
* Puppet 3.7 or greater
* NetApp Manageability SDK Ruby libraries
* Faraday gem
The proxy system must be able to connect to the Puppet master (default port of
8140) and to the NetApp Data ONTAP (default port of 443).
### NetApp Manageability SDK
Due to licensing, you must download the NetApp Manageability SDK separately.
The NetApp Ruby libraries are contained within the NetApp Manageability SDK,
which is available for download from [NetApp
NOW](http://support.netapp.com/NOW/cgi-bin/software?product=NetApp+Manageability+SDK&platform=All+Platforms).
Please note that you need a NetApp NOW account to download the
SDK.
Once you have downloaded and extracted the SDK, the Ruby SDK libraries must be
copied into the module:
`$ cp netapp-manageability-sdk-5.*/lib/ruby/NetApp/*.rb [module dir]/netapp/lib/puppet/netapp_sdk/`
### Device Proxy System Setup
To configure a Data ONTAP device, you must create a proxy system
able to run `puppet device` and have a device.conf file that refers to the
NetApp ONTAP system or vserver. Refer to the [device.conf man
page](https://docs.puppetlabs.com/puppet/latest/reference/config_file_device.html)
for information on the format of device.conf.
The netapp module can manage two different kinds of devices: Data ONTAP cluster
operating system and Data ONTAP cluster vservers. The device `type` of the
device.conf entry is always `netapp`.
For example, if you had a Data ONTAP operating system with the node management
interface addressable by the DNS name of ontap01.example.com and credentials
of admin & netapp123, the device.conf entry would be:
~~~
[ontap01.example.com]
type netapp
url https://admin:netapp123@ontap01.example.com
~~~
Note: The device certname must match the hostname of the node.
You can also specify a virtual server to operate on by providing the connection
information for a physical system which is configured with the vserver and
specify a path in the url that represents the name of your vserver. For
example, if the above Data ONTAP node ontap01 is configured with a vserver
called "vserver01," the device entry could be:
~~~
[vserver01.example.com]
type netapp
url https://admin:netapp123@ontap01.example.com/vserver01
~~~
Note: The device certname does not need to match the hostname of the node as
with a system device entry.
You can place the device entries in the default `${confdir}/device.conf` file
or create a separate config file for each device. For example, the above examples could
go in `${confdir}/device/ontap01.example.com.conf` and
`${confdir}/device/vserver01.example.com.conf`. Device configurations in separate files must be specified by `puppet device --deviceconfig /path/to/device-file.conf` to be used by `puppet device` run.
## Usage
### Beginning with netapp
Continuing from the example in [Device Proxy System
Setup](#device-proxy-system-setup), we can define a node definition for
ontap01.example.com to create a vserver with an aggregate of 6 disks and a LIF:
<!-- similar to https://library.netapp.com/ecmdocs/ECMP1196798/html/GUID-6D897853-FE9E-430C-971E-47096FDD462E.html -->
~~~
node 'ontap01.example.com' {
netapp_aggregate { 'aggr1':
ensure => present,
diskcount => '6',
}
netapp_vserver { 'vserver01':
ensure => present,
rootvol => 'vserver01_root',
rootvolaggr => 'aggr1',
rootvolsecstyle => 'unix',
}
netapp_lif { 'vserver01_lif':
ensure => present,
homeport => 'e0c',
homenode => 'ontap01',
address => '10.0.207.5',
vserver => 'vserver01',
netmask => '255.255.255.0',
dataprotocols => ['nfs'],
}
}
~~~
Next we should create a node definition for the vserver with a volume that has export policies for NFS, and a qtree on the volume:
~~~
node 'vserver01.example.com' {
netapp_export_policy { 'nfs_exports':
ensure => present,
}
netapp_export_rule { 'nfs_exports:1':
ensure => present,
clientmatch => '10.0.0.0/8',
protocol => ['nfs'],
superusersecurity => 'none',
rorule => ['sys','none'],
rwrule => ['sys','none'],
}
netapp_volume { 'vserver01_root':
exportpolicy => 'nfs_exports',
}
netapp_volume { 'nfsvol':
ensure => present,
aggregate => 'aggr1',
initsize => '200g',
exportpolicy => 'nfs_exports',
junctionpath => '/nfsvol',
}
netapp_qtree { 'qtree1':
ensure => present,
volume => 'nfsvol',
}
netapp_nfs { 'vserver01':
ensure => present,
state => 'on',
v3 => 'disabled',
v40 => 'enabled',
}
}
~~~
If the device configuration are both in `$confdir/device.conf`, they can now be
configured by running `puppet device --verbose --user=root`.
If the device configurations are is separate files, you can use the following
command to run puppet against a single device at a time:
~~~
puppet device --verbose --user=root --deviceconfig /etc/puppet/device/ontap01.example.com.conf
~~~
<!--
### NetApp operations
As part of this module, there is a define called 'netapp::vqe', which can be used to create a volume, add a qtree and create an NFS export.
An example of this is:
~~~
netapp::vqe { 'volume_name':
ensure => present,
size => '1t',
aggr => 'aggr2',
spaceres => 'volume',
snapresv => 20,
autosize => 'grow',
persistent => true
}
~~~
This will create a NetApp volume called `v_volume_name` with a qtree called `q_volume_name`.
The volume will have an initial size of 1 Terabyte in Aggregate aggr2.
The space reservation mode will be set to volume, and snapshot space reserve will be set to 20%.
The volume will be able to auto increment, and the NFS export will be persistent.
You can also use any of the types individually, or create new defined types as required.
-->\
### Classes and Defined Types
None as of this first release. Common operations may be encapsulated in defined resource types.
### Types and Providers
[`netapp_aggregate`](#type-netapp_aggregate)
[`netapp_cluster_id`](#type-netapp_cluster_id)
[`netapp_cluster_peer`](#type-netapp_cluster_peer)
[`netapp_export_policy`](#type-netapp_export_policy)
[`netapp_export_rule`](#type-netapp_export_rule)
[`netapp_group`](#type-netapp_group)
[`netapp_license`](#type-netapp_license)
[`netapp_lif`](#type-netapp_lif)
[`netapp_lun`](#type-netapp_lun)
[`netapp_lun_map`](#type-netapp_lun_map)
[`netapp_nfs`](#type-netapp_nfs)
[`netapp_notify`](#type-netapp_notify)
[`netapp_qtree`](#type-netapp_qtree)
[`netapp_quota`](#type-netapp_quota)
[`netapp_role`](#type-netapp_role)
[`netapp_snapmirror`](#type-netapp_snapmirror)
[`netapp_user`](#type-netapp_user)
[`netapp_volume`](#type-netapp_volume)
[`netapp_vserver`](#type-netapp_vserver)
[`netapp_vserver_option`](#type-netapp_vserver_option)
[`netapp_vserver_sis_config`](#type-netapp_vserver_sis_config)
### Type: netapp_aggregate
Manage Netapp Aggregate creation, modification and deletion.
#### Parameters
All parameters, except where otherwise noted, are optional.
##### `blocktype`
The indirect block format for the aggregate. Default value: '64_bit'.
Valid values are `64_bit`, `32_bit`.
##### `checksumstyle`
Aggregate checksum style. Default value: 'block'.
Valid values are `advanced_zoned`, `block`.
##### `diskcount`
Number of disks to place in the aggregate, including parity disks.
##### `disksize`
Disk size with unit to assign to aggregate.
##### `disktype`
Disk types to use with aggregate. Only required when multiple disk types are connected.
Valid values are `ATA`, `BSAS`, `EATA`, `FCAL`, `FSAS`, `LUN`, `MSATA`, `SAS`, `SATA`, `SCSI`, `SSD`, `XATA`, `XSAS`.
##### `ensure`
The basic state that the resource should be in.
Valid values are `present`, `absent`.
##### `groupselectionmode`
How should Data ONTAP add disks to raidgroups.
Valid values are `last`, `one`, `new`, `all`.
##### `ismirrored`
Should the aggregate be mirrored (have two plexes). Defaults to false.
Valid values are `true`, `false`.
##### `name`
The aggregate name
##### `nodes`
Target nodes to create aggregate. May be an array.
##### `raidsize`
Maximum number of disks in each RAID group in aggregate.
Valid values are between 2 and 28
##### `raidtype`
Raid type to use in the new aggregate. Default: raid4.
Valid values are `raid4`, `raid_dp`.
##### `state`
The aggregate state. Default value: 'online'.
Valid values are `online`, `offline`.
##### `striping`
Should the new aggregate be striped? Default: not_striped.
Valid values are `striped`, `not_striped`.
### Type: netapp_cluster_id
Not yet reviewed.
### Type: netapp_cluster_peer
Not yet reviewed.
### Type: netapp_export_policy
Manage Netapp CMode Export Policy creation and deletion.
#### Parameters
##### `ensure`
The basic property that the resource should be in.
Valid values are `present`, `absent`.
##### `name`
The export policy name.
### Type: netapp_export_rule
Manage Netapp CMode Export rule creation, modification and deletion.
#### Parameters
##### `allowdevenabled`
Should the NFS server allow creation of devices. Defaults to true.
Valid values are `true`, `false`.
##### `allowsetuid`
Should the NFS server allow setuid. Defaults to true.
Valid values are `true`, `false`.
##### `anonuid`
User name or ID to map anonymous users to. Defaults to 65534.
##### `clientmatch`
*Required*. Client match specification for the export rule. May take an fqdn, IP address, IP hyphenated range, or CIDR notation.
##### `ensure`
The basic state that the resource should be in.
Valid values are `present`, `absent`.
##### `exportchownmode`
Change ownership mode. Defaults to 'restricted'.
Valid values are `restricted`, `unrestricted`.
##### `name`
The export policy. Composite name based on policy name and rule index. Must take the form of `policy_name:rule_number` where the rule number is an integer and the policy name is an existing export policy.
##### `ntfsunixsecops`
Ignore/Fail Unix security operations on NTFS volumes. Defaults to 'fail'.
Valid values are `ignore`, `fail`.
##### `protocol`
Client access protocol. Defaults to 'any'.
Valid values are `any`, `nfs2`, `nfs3`, `nfs`, `cifs`, `nfs4`, `flexcache`.
##### `rorule`
Property to configure read only rules. Defaults to 'any'.
Valid values are `any`, `none`, `never`, `never`, `krb5`, `ntlm`, `sys`, `spinauth`.
##### `rwrule`
Property to configure read write rules. Defaults to 'any'.
Valid values are `any`, `none`, `never`, `never`, `krb5`, `ntlm`, `sys`, `spinauth`.
##### `superusersecurity`
Superuser security flavor. Defaults to 'any'.
Valid values are `any`, `none`, `never`, `never`, `krb5`, `ntlm`, `sys`, `spinauth`.
### Type: netapp_group
Not yet implemented.
### Type: netapp_igroup
Manage Netapp initiator groups
#### Parameters
##### name
**Namevar:** If omitted, this parameter's value defaults to the resource's title.
Initiator group name.
##### group_type
Initiator group type.
Valid values are `fcp`, `iscsi`, `mixed`.
##### members
An array of initiator WWPNs or aliases to be members of the initiator group.
##### os_type
OS type of the initiators within the group. The os type applies to all initiators within the group and governs the finer details of SCSI protocol interaction with these initiators. Required.
Valid values are `solaris`, `windows`, `hpux`, `aix`, `linux`, `netware`, `vmware`, `openvms`, `xen`, `hyper_v`.
##### portset
The name of the portset to which the igroup should be bound. A value of `false` will unbind the portset.
Valid values are a string or the boolean `false`
### Type: netapp_iscsi
Manage Netapp ISCSI service. There may only ever be one of these declared per VServer.
#### Parameters
##### svm
**Namevar:** If omitted, this parameter's value defaults to the resource's title.
ISCSI service SVM.
##### target_alias
ISCSI WWPN alias. May be any string that is a valid ISCSI target WWPN.
##### state
ISCSI service state.
Valid values are `on`, `off`.
### Type: netapp_iscsi_security
Manage Netapp ISCSI initiator (client) authentication.
#### Parameters
##### initiator
**Namevar:** If omitted, this parameter's value defaults to the resource's title.
ISCSI initiator name.
##### auth_type
ISCSI initiator authentication type.
Valid values are `chap`, `none`, `deny`.
##### radius
ISCSI radius CHAP setting.
Valid values are `true`, `false`.
##### username
ISCSI initiator inbound CHAP username.
##### password
ISCSI initiator inbound CHAP password.
Valid values are 12-16 hexidecimal digits.
##### outbound_username
ISCSI initiator outbound CHAP username.
##### outbound_password
ISCSI initiator outbound CHAP password.
Valid values are 12-16 hexidecimal digits.
### Type: netapp_license
Not yet reviewed.
### Type: netapp_lif
Manage Netapp Logical Inteface (LIF) creation, modification and deletion.
#### Parameters
##### `address`
LIF IP address. *Required*
##### `administrativestatus`
LIF administratative status. Defaults to: 'up'.
Valid values are `up`, `down`.
##### `comment`
LIF comment.
##### `dataprotocols`
LIF data protocols.
Valid values are `nfs`, `cifs`, `iscsi`, `fcp`, `fcache`, `none`.
##### `dnsdomainname`
LIF dns domain name.
##### `ensure`
The basic property that the resource should be in.
Valid values are `present`, `absent`.
##### `failovergroup`
LIF failover group name.
##### `failoverpolicy`
LIF failover policy. Defaults to: 'nextavail'.
Valid values are `nextavail`, `priority`, `disabled`.
##### `firewallpolicy`
LIF firewall policy. Default is based on the port role.
Valid values are `mgmt`, `cluster`, `intercluster`.
##### `homenode`
*Required*. LIF home node.
##### `homeport`
*Required*. LIF home port.
##### `interfacename`
**Namevar:** If omitted, this parameter's value defaults to the resource's title. LIF name.
##### `isautorevert`
Should the LIF revert to its home node. Defaults to: `false`.
Valid values are `true`, `false`.
##### `netmask`
LIF netmask. *Required* if `netmasklength` is not specified.
##### `netmasklength`
LIF netmask length. *Required* if `netmask` is not specified.
##### `role`
LIF Role. Defaults to: 'data'.
Valid values are `undef`, `cluster`, `data`, `node_mgmt`, `intercluster`, `cluster_mgmt`.
##### `routinggroupname`
LIF Routing group. Valid format is {dcn}{ip address}/{subnet}.
##### `usefailovergroup`
Whether the failover group should be automatically created. Defaults to: 'disabled'.
Valid values are `disabled`, `enabled`, `system_defined`.
##### `vserver`
*Required*. LIF Vserver name.
### Type: netapp_lun
Not yet reviewed.
### Type: netapp_lun_map
Not yet reviewed.
### Type: netapp_nfs
Manage NetApp NFS service
#### Parameters
##### `vserver`
**Namevar:** If omitted, this parameter's value defaults to the resource's title. NFS service SVM. This resource can only be applied to vservers, so the title is redundant.
##### `state`
NFS Service State
Valid values are `on`, `off`.
##### `v3`
Control NFS v3 access
Valid values are `enabled`, `disabled`.
##### `v40`
Control NFS v4.0 access
Valid values are `enabled`, `disabled`.
##### `v41`
Control NFS v4.1 access
Valid values are `enabled`, `disabled`.
### Type: netapp_notify
Not yet reviewed.
### Type: netapp_qtree
Manage Netapp Qtree creation, modification and deletion.
#### Parameters
##### `ensure`
The basic property that the resource should be in.
Valid values are `present`, `absent`.
##### `exportpolicy`
The export policy with which the qtree is associated. (Note: Not yet implemented)
##### `name`
The qtree name.
##### `volume`
*Required.*. The volume to create the qtree against.
### Type: netapp_quota
Not yet reviewed.
### Type: netapp_role
Not yet reviewed.
### Type: netapp_sis_policy
Manage Netapp sis policies.
#### Parameters
##### `type`
The type of policy.
Valid values are `threshold`, `scheduled`.
##### `job_schedule`
Job schedule name. E.g., 'daily'.
##### `duration`
Job duration in hours.
##### `enabled`
Manage whether the sis policy is enabled.
Valid values are `true`, `false`, `yes`, `no`, `enabled`, `disabled`
##### `comment`
Comment for the policy.
##### `qos_policy`
QoS policy name. E.g., 'best\_effort'
### Type: netapp_snapmirror
Not yet reviewed.
### Type: netapp_user
Not yet reviewed.
### Type: netapp_volume
Manage Netapp Volume creation, modification and deletion.
#### Parameters
##### `aggregate`
*Required.*. The aggregate this volume should be created in.
##### `autosize`
Whether volume autosize should be grow, grow/shrink, or off.
Valid values are `off`, `grow`, `grow_shrink`.
##### `ensure`
The basic state that the resource should be in.
Valid values are `present`, `absent`.
##### `exportpolicy`
The export policy with which the volume is associated.
##### `initsize`
The initial volume size. *Required.* Valid format is /[0-9]+[kmgt]/.
##### `junctionpath`
The fully-qualified pathname in the owning vserver's namespace at which a volume is mounted.
Valid values are absolute file paths or `false`.
##### `languagecode`
The language code this volume should use.
Valid values are `C`, `ar`, `cs`, `da`, `de`, `en`, `en_US`, `es`, `fi`, `fr`, `he`, `hr`, `hu`, `it`, `ja`, `ja_v1`, `ko`, `no`, `nl`, `pl`, `pt`, `ro`, `ru`, `sk`, `sl`, `sv`, `tr`, `zh`, `zh_TW`.
##### `name`
The volume name. Valid characters are a-z, 1-9 & underscore.
##### `options`
The volume options hash. XXX Needs more details
##### `snapreserve`
The percentage of space to reserve for snapshots.
##### `snapschedule`
The volume snapshot schedule, in a hash format. Valid keys are: 'minutes', 'hours', 'days', 'weeks', 'which-hours', 'which-minutes'. XXX Needs an example
##### `spaceres`
The space reservation mode.
Valid values are `none`, `file`, `volume`.
##### `state`
The volume state.
Valid values are `online`, `offline`, `restricted`.
### Type: netapp_vserver
Manage Netapp Vserver creation, modification and deletion.
#### Parameters
##### `aggregatelist`
Vserver aggregate list. May be an array.
##### `allowedprotos`
Vserver allowed protocols.
Valid values are `nfs`, `cifs`, `fcp`, `iscsi`, `ndmpd`.
##### `comment`
Vserver comment.
##### `ensure`
The basic property that the resource should be in.
Valid values are `present`, `absent`.
##### `language`
Vserver language. Defaults to `c.UTF-8`
Valid values are `c`, `c.UTF-8`, `ar`, `cs`, `da`, `de`, `en`, `en_us`, `es`, `fi`, `fr`, `he`, `hr`, `hu`, `it`, `ja`, `ja_v1`, `ja_jp.pck`, `ja_jp.932`, `ja_jp.pck_v2`, `ko`, `no`, `nl`, `pl`, `pt`, `ro`, `ru`, `sk`, `sl`, `sv`, `tr`, `zh`, `zh.gbk`, `zh_tw`.
##### `maxvolumes`
Vserver maximum allowed volumes.
##### `name`
The vserver name
##### `namemappingswitch`
Vserver name mapping switch. Defaults to 'file'.
Valid values are `file`, `ldap`.
##### `nameserverswitch`
Vserver name server switch.
Valid values are `file`, `ldap`, `nis`.
##### `quotapolicy`
Vserver quota policy.
##### `rootvol`
*Required.* The vserver root volume.
##### `rootvolaggr`
*Required.* Vserver root volume aggregate.
##### `rootvolsecstyle`
*Required.* Vserver root volume security style.
Valid values are `unix`, `ntfs`, `mixed`, `unified`.
##### `snapshotpolicy`
Vserver snapshot policy.
##### `state`
The vserver state.
Valid values are `stopped`, `running`.
### Type: netapp_vserver_option
Manage Netapp Vserver option modification.
#### Parameters
##### `ensure`
The basic property that the resource should be in.
Valid values are `present`, `absent`.
##### `name`
The vserver option name.
##### `value`
The vserver option value.
### Type: netapp_sis_config
Manage Netapp Vserver sis config modification.
#### Parameters
##### `compression`
Enable compression on the sis volume.
Valid options: `true`, `false`.
##### `enabled`
Enable sis on a volume.
Valid options: `true`, `false`.
##### `ensure`
The basic property that the resource should be in.
Valid values are `present`, `absent`.
##### `idd`
Enables file level incompressible data detection and quick check incompressible data detection for large files.
Valid options: `true`, `false`.
##### `inline_compression`
Enable inline compression on the sis volume.
Valid options: `true`, `false`.
##### `path`
(**Namevar:** If omitted, this parameter's value defaults to the resource's title.) The full path of the sis volume, `/vol/<vol_name>`.
##### `policy`
The sis policy name to be attached to the volume.
##### `quick_check_fsize`
Quick check file size for Incompressible Data Detection. Accepts integers
Values can match `/^\d+$/`.
##### `sis_schedule`
The schedule string for the sis operation.
Accepts the following formats:
* `day_list[@hour_list]`
* `hour_list[@day_list]`
* `-`
* `auto`
* `manual`
## TODO
The following items are yet to be implemented:
* Data Fabric Manager support
* Support adding/deleting/modifying cifs shares
* LDAP and/or AD configuration
* QA remaining resources
## Development
The following section applies to developers of this module only.
### Testing
You will need to install the NetApp Manageability SDK Ruby libraries for most of the tests to work.
How to obtain these files is detailed in the NetApp Manageability SDK section above.
| Java |
using FluentAssertions;
using Nest.Tests.MockData.Domain;
using NUnit.Framework;
namespace Nest.Tests.Integration.Template
{
[TestFixture]
public class TemplateTests : IntegrationTests
{
[Test]
public void SimplePutAndGet()
{
this.Client.DeleteTemplate("put-template-with-settings");
var putResponse = this.Client.PutTemplate("put-template-with-settings", t => t
.Template("donotinfluencothertests-*")
.Order(42)
);
Assert.IsTrue(putResponse.Acknowledged);
var templateResponse = this.Client.GetTemplate("put-template-with-settings");
templateResponse.Should().NotBeNull();
templateResponse.IsValid.Should().BeTrue();
templateResponse.TemplateMapping.Should().NotBeNull();
templateResponse.TemplateMapping.Mappings.Should().NotBeNull();
var settings = templateResponse.TemplateMapping.Settings;
templateResponse.TemplateMapping.Order.Should().Be(42);
settings.Should().NotBeNull();
}
[Test]
public void PutTemplateWithSettings()
{
this.Client.DeleteTemplate("put-template-with-settings");
var putResponse = this.Client.PutTemplate("put-template-with-settings", t=>t
.Template("donotinfluencothertests-*")
.Settings(s=>s
.Add("index.number_of_shards", 3)
.Add("index.number_of_replicas", 2)
)
);
Assert.IsTrue(putResponse.Acknowledged);
var templateResponse = this.Client.GetTemplate("put-template-with-settings");
templateResponse.Should().NotBeNull();
templateResponse.IsValid.Should().BeTrue();
templateResponse.TemplateMapping.Should().NotBeNull();
templateResponse.TemplateMapping.Mappings.Should().NotBeNull();
var settings = templateResponse.TemplateMapping.Settings;
settings.Should().NotBeNull();
Assert.AreEqual("3", settings["index.number_of_shards"]);
Assert.AreEqual("2", settings["index.number_of_replicas"]);
}
[Test]
public void PutTemplateWithMappings()
{
this.Client.DeleteTemplate("put-template-with-mappings");
var putResponse = this.Client.PutTemplate("put-template-with-mappings",t => t
.Template("donotinfluencothertests")
.AddMapping<ElasticsearchProject>(s=>s
.AllField(a=>a.Enabled(false))
)
);
Assert.IsTrue(putResponse.Acknowledged);
var templateResponse = this.Client.GetTemplate("put-template-with-mappings");
templateResponse.Should().NotBeNull();
templateResponse.IsValid.Should().BeTrue();
templateResponse.TemplateMapping.Should().NotBeNull();
templateResponse.TemplateMapping.Mappings.Should().NotBeNull().And.NotBeEmpty();
var mappings = templateResponse.TemplateMapping.Mappings;
Assert.IsTrue(mappings.ContainsKey("elasticsearchprojects"), "put-template-with-mappings template should have a `mytype` mapping");
Assert.NotNull(mappings["elasticsearchprojects"].AllFieldMapping, "`mytype` mapping should contain the _all field mapping");
Assert.AreEqual(false, mappings["elasticsearchprojects"].AllFieldMapping.Enabled, "_all { enabled } should be set to false");
}
[Test]
public void PutTemplateWithWarmers()
{
this.Client.DeleteTemplate("put-template-with-warmers");
var putResponse = this.Client.PutTemplate("put-template-with-warmers", t => t
.Template("donotinfluencothertests2")
.AddWarmer<ElasticsearchProject>(w => w
.WarmerName("matchall")
.Type("elasticsearchprojects")
.Search(s=>s
.MatchAll()
)
)
);
Assert.IsTrue(putResponse.Acknowledged);
var templateResponse = this.Client.GetTemplate("put-template-with-warmers");
templateResponse.Should().NotBeNull();
templateResponse.IsValid.Should().BeTrue();
templateResponse.TemplateMapping.Should().NotBeNull();
//possible elasticsearch bug https://github.com/elasticsearch/elasticsearch/issues/2868
//templateResponse.TemplateMapping.Warmers.Should().NotBeNull().And.NotBeEmpty();
}
}
}
| Java |
//
// ========================================================================
// Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.spdy.parser;
import java.io.ByteArrayInputStream;
import java.nio.ByteBuffer;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.jetty.spdy.SessionException;
import org.eclipse.jetty.spdy.api.SessionStatus;
import org.eclipse.jetty.spdy.frames.ControlFrameType;
import org.eclipse.jetty.spdy.frames.CredentialFrame;
public class CredentialBodyParser extends ControlFrameBodyParser
{
private final List<Certificate> certificates = new ArrayList<>();
private final ControlFrameParser controlFrameParser;
private State state = State.SLOT;
private int totalLength;
private int cursor;
private short slot;
private int proofLength;
private byte[] proof;
private int certificateLength;
private byte[] certificate;
public CredentialBodyParser(ControlFrameParser controlFrameParser)
{
this.controlFrameParser = controlFrameParser;
}
@Override
public boolean parse(ByteBuffer buffer)
{
while (buffer.hasRemaining())
{
switch (state)
{
case SLOT:
{
if (buffer.remaining() >= 2)
{
slot = buffer.getShort();
checkSlotValid();
state = State.PROOF_LENGTH;
}
else
{
state = State.SLOT_BYTES;
cursor = 2;
}
break;
}
case SLOT_BYTES:
{
byte currByte = buffer.get();
--cursor;
slot += (currByte & 0xFF) << 8 * cursor;
if (cursor == 0)
{
checkSlotValid();
state = State.PROOF_LENGTH;
}
break;
}
case PROOF_LENGTH:
{
if (buffer.remaining() >= 4)
{
proofLength = buffer.getInt() & 0x7F_FF_FF_FF;
state = State.PROOF;
}
else
{
state = State.PROOF_LENGTH_BYTES;
cursor = 4;
}
break;
}
case PROOF_LENGTH_BYTES:
{
byte currByte = buffer.get();
--cursor;
proofLength += (currByte & 0xFF) << 8 * cursor;
if (cursor == 0)
{
proofLength &= 0x7F_FF_FF_FF;
state = State.PROOF;
}
break;
}
case PROOF:
{
totalLength = controlFrameParser.getLength() - 2 - 4 - proofLength;
proof = new byte[proofLength];
if (buffer.remaining() >= proofLength)
{
buffer.get(proof);
state = State.CERTIFICATE_LENGTH;
if (totalLength == 0)
{
onCredential();
return true;
}
}
else
{
state = State.PROOF_BYTES;
cursor = proofLength;
}
break;
}
case PROOF_BYTES:
{
proof[proofLength - cursor] = buffer.get();
--cursor;
if (cursor == 0)
{
state = State.CERTIFICATE_LENGTH;
if (totalLength == 0)
{
onCredential();
return true;
}
}
break;
}
case CERTIFICATE_LENGTH:
{
if (buffer.remaining() >= 4)
{
certificateLength = buffer.getInt() & 0x7F_FF_FF_FF;
state = State.CERTIFICATE;
}
else
{
state = State.CERTIFICATE_LENGTH_BYTES;
cursor = 4;
}
break;
}
case CERTIFICATE_LENGTH_BYTES:
{
byte currByte = buffer.get();
--cursor;
certificateLength += (currByte & 0xFF) << 8 * cursor;
if (cursor == 0)
{
certificateLength &= 0x7F_FF_FF_FF;
state = State.CERTIFICATE;
}
break;
}
case CERTIFICATE:
{
totalLength -= 4 + certificateLength;
certificate = new byte[certificateLength];
if (buffer.remaining() >= certificateLength)
{
buffer.get(certificate);
if (onCertificate())
return true;
}
else
{
state = State.CERTIFICATE_BYTES;
cursor = certificateLength;
}
break;
}
case CERTIFICATE_BYTES:
{
certificate[certificateLength - cursor] = buffer.get();
--cursor;
if (cursor == 0)
{
if (onCertificate())
return true;
}
break;
}
default:
{
throw new IllegalStateException();
}
}
}
return false;
}
private void checkSlotValid()
{
if (slot <= 0)
throw new SessionException(SessionStatus.PROTOCOL_ERROR,
"Invalid slot " + slot + " for " + ControlFrameType.CREDENTIAL + " frame");
}
private boolean onCertificate()
{
certificates.add(deserializeCertificate(certificate));
if (totalLength == 0)
{
onCredential();
return true;
}
else
{
certificateLength = 0;
state = State.CERTIFICATE_LENGTH;
}
return false;
}
private Certificate deserializeCertificate(byte[] bytes)
{
try
{
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
return certificateFactory.generateCertificate(new ByteArrayInputStream(bytes));
}
catch (CertificateException x)
{
throw new SessionException(SessionStatus.PROTOCOL_ERROR, x);
}
}
private void onCredential()
{
CredentialFrame frame = new CredentialFrame(controlFrameParser.getVersion(), slot,
Arrays.copyOf(proof, proof.length), certificates.toArray(new Certificate[certificates.size()]));
controlFrameParser.onControlFrame(frame);
reset();
}
private void reset()
{
state = State.SLOT;
totalLength = 0;
cursor = 0;
slot = 0;
proofLength = 0;
proof = null;
certificateLength = 0;
certificate = null;
certificates.clear();
}
public enum State
{
SLOT, SLOT_BYTES, PROOF_LENGTH, PROOF_LENGTH_BYTES, PROOF, PROOF_BYTES,
CERTIFICATE_LENGTH, CERTIFICATE_LENGTH_BYTES, CERTIFICATE, CERTIFICATE_BYTES
}
}
| Java |
# Stephanotis acuminata Brongn. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | Java |
package com.ctrip.xpipe.redis.core.protocal;
/**
* @author wenchao.meng
*
* 2016年3月24日 下午6:27:48
*/
public interface RedisProtocol {
int REDIS_PORT_DEFAULT = 6379;
int KEEPER_PORT_DEFAULT = 6380;
int RUN_ID_LENGTH = 40;
String CRLF = "\r\n";
String OK = "OK";
String KEEPER_ROLE_PREFIX = "keeperrole";
static String booleanToString(boolean yes){
if(yes){
return "yes";
}
return "no";
}
}
| Java |
<?
namespace CodeCraft;
use CodeCraft\Helpers\LanguageLink;
class SiteRouter
{
private $language = [];
private $defaultLanguage = 'ru';
private $languageUrlMap = [];
private $languageList = ['ru' => ['ru',
'be',
'uk',
'ky',
'ab',
'mo',
'et',
'lv'],
'en' => 'en'];
/**
* @param array $languageUrlMap - ['language' => 'url', ..., 'default' => 'url']
*/
public function __construct($languageUrlMap) {
$this->setLanguageUrlMap($languageUrlMap);
if (($list = strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']))) {
if (preg_match_all('/([a-z]{1,8}(?:-[a-z]{1,8})?)(?:;q=([0-9.]+))?/', $list, $list)) {
$this->language = array_combine($list[1], $list[2]);
foreach ($this->language as $n => $v) {
$this->language[$n] = $v ? $v : 1;
}
arsort($this->language, SORT_NUMERIC);
}
} else {
$this->language = [];
}
}
/**
* @param array $languageUrlMap
*/
public function setLanguageUrlMap(array $languageUrlMap) {
$this->languageUrlMap = $languageUrlMap;
}
/**
* @return array
*/
public function getLanguageUrlMap() {
return $this->languageUrlMap;
}
/**
* @param array $languageList
*
* @return string
*/
private function getBestMatch(array $languageList) {
$languages = array();
foreach ($languageList as $lang => $alias) {
if (is_array($alias)) {
foreach ($alias as $alias_lang) {
$languages[strtolower($alias_lang)] = strtolower($lang);
}
} else {
$languages[strtolower($alias)] = strtolower($lang);
}
}
foreach ($this->language as $l => $v) {
$s = strtok($l, '-');
if (isset($languages[$s])) {
return $languages[$s];
}
}
return $this->defaultLanguage;
}
/**
* @param array $languageList
*/
public function setLanguageList(array $languageList) {
$this->languageList = $languageList;
}
/**
* @param string $pathTo404
*/
public function route($pathTo404 = '') {
$language = $this->getBestMatch($this->languageList);
$languageUrlMap = $this->getLanguageUrlMap();
LanguageLink::setRootAlternateHeader($language);
if ($languageUrlMap[$language] || $languageUrlMap['default']) {
LocalRedirect($languageUrlMap[$language] ?: $languageUrlMap['default'], false, '301 Moved Permanently');
} else {
$this->showNotFoundPage($pathTo404);
}
}
/**
* @param string $pathTo404
*
* @buffer_restart
*
* @require 404 page
*
* @die
*/
public function showNotFoundPage($pathTo404 = '') {
if (!$pathTo404) {
$pathTo404 = $_SERVER['DOCUMENT_ROOT'] . '/' . $this->getBestMatch($this->languageList) . '/404.php';
}
global $APPLICATION;
$APPLICATION->RestartBuffer();
try {
require_once($pathTo404);
} catch (\Exception $e) {
\CHTTP::SetStatus('404 Not Found');
echo '<h1>404 Not Found</h1>';
}
die;
}
} | Java |
//
// YRMConst.h
// Budejie
//
// Created by 叶仁明 on 2017/2/6.
// Copyright © 2017年 叶仁明. All rights reserved.
//
#import <UIKit/UIKit.h>
UIKIT_EXTERN CGFloat const YRMTitlesViewH;
UIKIT_EXTERN CGFloat const YRMTitlesViewY;
UIKIT_EXTERN CGFloat const YRMTopicCellTextY;
UIKIT_EXTERN CGFloat const YRMTopicCellBottomToolBarH;
UIKIT_EXTERN CGFloat const YRMTopicCellMargin;
//图片最大的高度,超过该高度显示查看完整图片的按钮
UIKIT_EXTERN CGFloat const YRMTopicCellPictureMaxH;
//图片超过最大高度时,显示的截取图片的高度
UIKIT_EXTERN CGFloat const YRMTopicCellPictureBreakH;
| Java |
package com.pi.xerosync.dbconnect;
/**
* User: thomas Date: 18/02/14
*/
public interface XeroCredentials {
String getXeroConsumerKey();
String getXeroConsumerSecret();
String getPrivateKeyPath();
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.