repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
misterfong/liquidweb-twilio | index.js | 1166 | var express = require('express'),
bodyParser = require('body-parser'),
stormAPI = require('stormondemand'),
client = new stormAPI({ username: process.env.USER, password: process.env.PASSWORD });
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.all('/', function(request, response) {
var body = request.body.Body;
if (body === 'bandwidth') {
var output = "<Response><Sms>";
client.Monitoring.Bandwidth.stats({ uniq_id: process.env.SERVER_ID}, function (res) {
output += "=== Monthly Bandwidth Stats ==";
output += " Total: " + res.averages.month.both.GB + "GB "
output += " Incoming: " + res.averages.month.in.GB + " GB ";
output += " Outgoing: " + res.averages.month.out.GB + " GB ";
output += " Quota: " + res.pricing.quota + " GB ";
output += "</Sms></Response>";
response.send(output);
});
} else {
response.send("commands available: bandwidth");
}
});
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'));
});
| apache-2.0 |
mycontroller-org/mycontroller | modules/core/src/main/java/org/mycontroller/standalone/backup/mixins/SerializerSimpleUser.java | 1705 | /*
* Copyright 2015-2019 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* 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.mycontroller.standalone.backup.mixins;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.mycontroller.standalone.api.jaxrs.utils.RestUtils;
import org.mycontroller.standalone.db.tables.User;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
/**
* @author Jeeva Kandasamy (jkandasa)
* @since 1.5.0
*/
public class SerializerSimpleUser extends JsonSerializer<User> {
@Override
public void serialize(User item, JsonGenerator jgen, SerializerProvider provider) throws IOException,
JsonProcessingException {
if (item != null) {
Map<String, Object> data = new HashMap<String, Object>();
data.put("id", item.getId());
RestUtils.getObjectMapper().writeValue(jgen, data);
} else {
jgen.writeNull();
}
}
}
| apache-2.0 |
majetideepak/arrow | cpp/src/arrow/util/parsing-util-test.cc | 12885 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include <locale>
#include <stdexcept>
#include <string>
#include <gtest/gtest.h>
#include "arrow/type.h"
#include "arrow/util/parsing.h"
namespace arrow {
using internal::StringConverter;
template <typename ConverterType, typename C_TYPE>
void AssertConversion(ConverterType& converter, const std::string& s, C_TYPE expected) {
typename ConverterType::value_type out;
ASSERT_TRUE(converter(s.data(), s.length(), &out))
<< "Conversion failed for '" << s << "' (expected to return " << expected << ")";
ASSERT_EQ(out, expected) << "Conversion failed for '" << s << "'";
}
template <typename ConverterType>
void AssertConversionFails(ConverterType& converter, const std::string& s) {
typename ConverterType::value_type out;
ASSERT_FALSE(converter(s.data(), s.length(), &out))
<< "Conversion should have failed for '" << s << "' (returned " << out << ")";
}
class LocaleGuard {
public:
explicit LocaleGuard(const char* new_locale) : global_locale_(std::locale()) {
try {
std::locale::global(std::locale(new_locale));
} catch (std::runtime_error&) {
// Locale unavailable, ignore
}
}
~LocaleGuard() { std::locale::global(global_locale_); }
protected:
std::locale global_locale_;
};
TEST(StringConversion, ToBoolean) {
StringConverter<BooleanType> converter;
AssertConversion(converter, "true", true);
AssertConversion(converter, "tRuE", true);
AssertConversion(converter, "FAlse", false);
AssertConversion(converter, "false", false);
AssertConversion(converter, "1", true);
AssertConversion(converter, "0", false);
AssertConversionFails(converter, "");
}
TEST(StringConversion, ToFloat) {
StringConverter<FloatType> converter;
AssertConversion(converter, "1.5", 1.5f);
AssertConversion(converter, "0", 0.0f);
// XXX ASSERT_EQ doesn't distinguish signed zeros
AssertConversion(converter, "-0.0", -0.0f);
AssertConversion(converter, "-1e20", -1e20f);
AssertConversionFails(converter, "");
AssertConversionFails(converter, "e");
}
TEST(StringConversion, ToDouble) {
StringConverter<DoubleType> converter;
AssertConversion(converter, "1.5", 1.5);
AssertConversion(converter, "0", 0);
// XXX ASSERT_EQ doesn't distinguish signed zeros
AssertConversion(converter, "-0.0", -0.0);
AssertConversion(converter, "-1e100", -1e100);
AssertConversionFails(converter, "");
AssertConversionFails(converter, "e");
}
#ifndef _WIN32
// Test that casting is locale-independent
// ARROW-6108: can't run these tests on Windows. std::locale() will simply throw
// on release builds, but may crash with an assertion failure on debug builds.
// (similar issue here: https://gerrit.libreoffice.org/#/c/54110/)
TEST(StringConversion, ToFloatLocale) {
// French locale uses the comma as decimal point
LocaleGuard locale_guard("fr_FR.UTF-8");
StringConverter<FloatType> converter;
AssertConversion(converter, "1.5", 1.5f);
}
TEST(StringConversion, ToDoubleLocale) {
// French locale uses the comma as decimal point
LocaleGuard locale_guard("fr_FR.UTF-8");
StringConverter<DoubleType> converter;
AssertConversion(converter, "1.5", 1.5f);
}
#endif // _WIN32
TEST(StringConversion, ToInt8) {
StringConverter<Int8Type> converter;
AssertConversion(converter, "0", 0);
AssertConversion(converter, "127", 127);
AssertConversion(converter, "0127", 127);
AssertConversion(converter, "-128", -128);
AssertConversion(converter, "-00128", -128);
// Non-representable values
AssertConversionFails(converter, "128");
AssertConversionFails(converter, "-129");
AssertConversionFails(converter, "");
AssertConversionFails(converter, "-");
AssertConversionFails(converter, "0.0");
AssertConversionFails(converter, "e");
}
TEST(StringConversion, ToUInt8) {
StringConverter<UInt8Type> converter;
AssertConversion(converter, "0", 0);
AssertConversion(converter, "26", 26);
AssertConversion(converter, "255", 255);
AssertConversion(converter, "0255", 255);
// Non-representable values
AssertConversionFails(converter, "-1");
AssertConversionFails(converter, "256");
AssertConversionFails(converter, "260");
AssertConversionFails(converter, "1234");
AssertConversionFails(converter, "");
AssertConversionFails(converter, "-");
AssertConversionFails(converter, "0.0");
AssertConversionFails(converter, "e");
}
TEST(StringConversion, ToInt16) {
StringConverter<Int16Type> converter;
AssertConversion(converter, "0", 0);
AssertConversion(converter, "32767", 32767);
AssertConversion(converter, "032767", 32767);
AssertConversion(converter, "-32768", -32768);
AssertConversion(converter, "-0032768", -32768);
// Non-representable values
AssertConversionFails(converter, "32768");
AssertConversionFails(converter, "-32769");
AssertConversionFails(converter, "");
AssertConversionFails(converter, "-");
AssertConversionFails(converter, "0.0");
AssertConversionFails(converter, "e");
}
TEST(StringConversion, ToUInt16) {
StringConverter<UInt16Type> converter;
AssertConversion(converter, "0", 0);
AssertConversion(converter, "6660", 6660);
AssertConversion(converter, "65535", 65535);
AssertConversion(converter, "065535", 65535);
// Non-representable values
AssertConversionFails(converter, "-1");
AssertConversionFails(converter, "65536");
AssertConversionFails(converter, "123456");
AssertConversionFails(converter, "");
AssertConversionFails(converter, "-");
AssertConversionFails(converter, "0.0");
AssertConversionFails(converter, "e");
}
TEST(StringConversion, ToInt32) {
StringConverter<Int32Type> converter;
AssertConversion(converter, "0", 0);
AssertConversion(converter, "2147483647", 2147483647);
AssertConversion(converter, "02147483647", 2147483647);
AssertConversion(converter, "-2147483648", -2147483648LL);
AssertConversion(converter, "-002147483648", -2147483648LL);
// Non-representable values
AssertConversionFails(converter, "2147483648");
AssertConversionFails(converter, "-2147483649");
AssertConversionFails(converter, "");
AssertConversionFails(converter, "-");
AssertConversionFails(converter, "0.0");
AssertConversionFails(converter, "e");
}
TEST(StringConversion, ToUInt32) {
StringConverter<UInt32Type> converter;
AssertConversion(converter, "0", 0);
AssertConversion(converter, "432198765", 432198765UL);
AssertConversion(converter, "4294967295", 4294967295UL);
AssertConversion(converter, "04294967295", 4294967295UL);
// Non-representable values
AssertConversionFails(converter, "-1");
AssertConversionFails(converter, "4294967296");
AssertConversionFails(converter, "12345678901");
AssertConversionFails(converter, "");
AssertConversionFails(converter, "-");
AssertConversionFails(converter, "0.0");
AssertConversionFails(converter, "e");
}
TEST(StringConversion, ToInt64) {
StringConverter<Int64Type> converter;
AssertConversion(converter, "0", 0);
AssertConversion(converter, "9223372036854775807", 9223372036854775807LL);
AssertConversion(converter, "09223372036854775807", 9223372036854775807LL);
AssertConversion(converter, "-9223372036854775808", -9223372036854775807LL - 1);
AssertConversion(converter, "-009223372036854775808", -9223372036854775807LL - 1);
// Non-representable values
AssertConversionFails(converter, "9223372036854775808");
AssertConversionFails(converter, "-9223372036854775809");
AssertConversionFails(converter, "");
AssertConversionFails(converter, "-");
AssertConversionFails(converter, "0.0");
AssertConversionFails(converter, "e");
}
TEST(StringConversion, ToUInt64) {
StringConverter<UInt64Type> converter;
AssertConversion(converter, "0", 0);
AssertConversion(converter, "18446744073709551615", 18446744073709551615ULL);
// Non-representable values
AssertConversionFails(converter, "-1");
AssertConversionFails(converter, "18446744073709551616");
AssertConversionFails(converter, "");
AssertConversionFails(converter, "-");
AssertConversionFails(converter, "0.0");
AssertConversionFails(converter, "e");
}
TEST(StringConversion, ToTimestamp1) {
{
StringConverter<TimestampType> converter(timestamp(TimeUnit::SECOND));
AssertConversion(converter, "1970-01-01", 0);
AssertConversion(converter, "1989-07-14", 616377600);
AssertConversion(converter, "2000-02-29", 951782400);
AssertConversion(converter, "3989-07-14", 63730281600LL);
AssertConversion(converter, "1900-02-28", -2203977600LL);
AssertConversionFails(converter, "");
AssertConversionFails(converter, "1970");
AssertConversionFails(converter, "19700101");
AssertConversionFails(converter, "1970/01/01");
AssertConversionFails(converter, "1970-01-01 ");
AssertConversionFails(converter, "1970-01-01Z");
// Invalid dates
AssertConversionFails(converter, "1970-00-01");
AssertConversionFails(converter, "1970-13-01");
AssertConversionFails(converter, "1970-01-32");
AssertConversionFails(converter, "1970-02-29");
AssertConversionFails(converter, "2100-02-29");
}
{
StringConverter<TimestampType> converter(timestamp(TimeUnit::MILLI));
AssertConversion(converter, "1970-01-01", 0);
AssertConversion(converter, "1989-07-14", 616377600000LL);
AssertConversion(converter, "3989-07-14", 63730281600000LL);
AssertConversion(converter, "1900-02-28", -2203977600000LL);
}
{
StringConverter<TimestampType> converter(timestamp(TimeUnit::MICRO));
AssertConversion(converter, "1970-01-01", 0);
AssertConversion(converter, "1989-07-14", 616377600000000LL);
AssertConversion(converter, "3989-07-14", 63730281600000000LL);
AssertConversion(converter, "1900-02-28", -2203977600000000LL);
}
{
StringConverter<TimestampType> converter(timestamp(TimeUnit::NANO));
AssertConversion(converter, "1970-01-01", 0);
AssertConversion(converter, "1989-07-14", 616377600000000000LL);
AssertConversion(converter, "2018-11-13", 1542067200000000000LL);
AssertConversion(converter, "1900-02-28", -2203977600000000000LL);
}
}
TEST(StringConversion, ToTimestamp2) {
{
StringConverter<TimestampType> converter(timestamp(TimeUnit::SECOND));
AssertConversion(converter, "1970-01-01 00:00:00", 0);
AssertConversion(converter, "2018-11-13 17:11:10", 1542129070);
AssertConversion(converter, "2018-11-13T17:11:10", 1542129070);
AssertConversion(converter, "2018-11-13 17:11:10Z", 1542129070);
AssertConversion(converter, "2018-11-13T17:11:10Z", 1542129070);
AssertConversion(converter, "1900-02-28 12:34:56", -2203932304LL);
// Invalid dates
AssertConversionFails(converter, "1970-02-29 00:00:00");
AssertConversionFails(converter, "2100-02-29 00:00:00");
// Invalid times
AssertConversionFails(converter, "1970-01-01 24:00:00");
AssertConversionFails(converter, "1970-01-01 00:60:00");
AssertConversionFails(converter, "1970-01-01 00:00:60");
}
{
StringConverter<TimestampType> converter(timestamp(TimeUnit::MILLI));
AssertConversion(converter, "2018-11-13 17:11:10", 1542129070000LL);
AssertConversion(converter, "2018-11-13T17:11:10Z", 1542129070000LL);
AssertConversion(converter, "3989-07-14T11:22:33Z", 63730322553000LL);
AssertConversion(converter, "1900-02-28 12:34:56", -2203932304000LL);
}
{
StringConverter<TimestampType> converter(timestamp(TimeUnit::MICRO));
AssertConversion(converter, "2018-11-13 17:11:10", 1542129070000000LL);
AssertConversion(converter, "2018-11-13T17:11:10Z", 1542129070000000LL);
AssertConversion(converter, "3989-07-14T11:22:33Z", 63730322553000000LL);
AssertConversion(converter, "1900-02-28 12:34:56", -2203932304000000LL);
}
{
StringConverter<TimestampType> converter(timestamp(TimeUnit::NANO));
AssertConversion(converter, "2018-11-13 17:11:10", 1542129070000000000LL);
AssertConversion(converter, "2018-11-13T17:11:10Z", 1542129070000000000LL);
AssertConversion(converter, "1900-02-28 12:34:56", -2203932304000000000LL);
}
}
} // namespace arrow
| apache-2.0 |
AloneStone/ruby_twitter | db/migrate/20170330062416_create_tweet.rb | 200 | class CreateTweet < ActiveRecord::Migration[5.0]
def change
create_table :tweets do |t|
t.string :content
t.references :user, foreign_key: true
t.timestamps
end
end
end
| apache-2.0 |
GSTU/oop-examples | GamesLabs/2015/IT-22/Jigsaw1/GameSettings.cs | 1091 | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
namespace MinThantSin.OpenSourceGames
{
public static class GameSettings
{
public static readonly string BACKGROUND_PICTURE_NAME = "background_tile.bmp";
public static readonly int MIN_PIECE_WIDTH = 50; // Минимальная ширина части в пикселях
public static readonly int MIN_PIECE_HEIGHT = 50; // Минимальная высота части в пикселях
// Устоновим кол столбцои и строк
public static readonly int NUM_ROWS = 4;
public static readonly int NUM_COLUMNS = 4;
public static readonly int SNAP_TOLERANCE = 15;
public static readonly byte GHOST_PICTURE_ALPHA = 127;
public static readonly int PIECE_OUTLINE_WIDTH = 4;
public static readonly bool DRAW_PIECE_OUTLINE = true;
public static readonly int DROP_SHADOW_DEPTH = 3;
public static readonly Color DROP_SHADOW_COLOR = Color.FromArgb(50, 50, 50);
}
}
| apache-2.0 |
cinderella/incubator-cloudstack | awsapi/src/com/amazon/ec2/CreateVpcResponseType.java | 25191 | // 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.
/**
* CreateVpcResponseType.java
*
* This file was auto-generated from WSDL
* by the Apache Axis2 version: 1.5.1 Built on : Oct 19, 2009 (10:59:34 EDT)
*/
package com.amazon.ec2;
/**
* CreateVpcResponseType bean class
*/
public class CreateVpcResponseType
implements org.apache.axis2.databinding.ADBBean{
/* This type was generated from the piece of schema that had
name = CreateVpcResponseType
Namespace URI = http://ec2.amazonaws.com/doc/2009-10-31/
Namespace Prefix = ns1
*/
private static java.lang.String generatePrefix(java.lang.String namespace) {
if(namespace.equals("http://ec2.amazonaws.com/doc/2009-10-31/")){
return "ns1";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
/**
* field for RequestId
*/
protected java.lang.String localRequestId ;
/**
* Auto generated getter method
* @return java.lang.String
*/
public java.lang.String getRequestId(){
return localRequestId;
}
/**
* Auto generated setter method
* @param param RequestId
*/
public void setRequestId(java.lang.String param){
this.localRequestId=param;
}
/**
* field for Vpc
*/
protected com.amazon.ec2.VpcType localVpc ;
/**
* Auto generated getter method
* @return com.amazon.ec2.VpcType
*/
public com.amazon.ec2.VpcType getVpc(){
return localVpc;
}
/**
* Auto generated setter method
* @param param Vpc
*/
public void setVpc(com.amazon.ec2.VpcType param){
this.localVpc=param;
}
/**
* isReaderMTOMAware
* @return true if the reader supports MTOM
*/
public static boolean isReaderMTOMAware(javax.xml.stream.XMLStreamReader reader) {
boolean isReaderMTOMAware = false;
try{
isReaderMTOMAware = java.lang.Boolean.TRUE.equals(reader.getProperty(org.apache.axiom.om.OMConstants.IS_DATA_HANDLERS_AWARE));
}catch(java.lang.IllegalArgumentException e){
isReaderMTOMAware = false;
}
return isReaderMTOMAware;
}
/**
*
* @param parentQName
* @param factory
* @return org.apache.axiom.om.OMElement
*/
public org.apache.axiom.om.OMElement getOMElement (
final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{
org.apache.axiom.om.OMDataSource dataSource =
new org.apache.axis2.databinding.ADBDataSource(this,parentQName){
public void serialize(org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
CreateVpcResponseType.this.serialize(parentQName,factory,xmlWriter);
}
};
return new org.apache.axiom.om.impl.llom.OMSourcedElementImpl(
parentQName,factory,dataSource);
}
public void serialize(final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory,
org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
serialize(parentQName,factory,xmlWriter,false);
}
public void serialize(final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory,
org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter,
boolean serializeType)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
java.lang.String prefix = null;
java.lang.String namespace = null;
prefix = parentQName.getPrefix();
namespace = parentQName.getNamespaceURI();
if ((namespace != null) && (namespace.trim().length() > 0)) {
java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeStartElement(namespace, parentQName.getLocalPart());
} else {
if (prefix == null) {
prefix = generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, parentQName.getLocalPart(), namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
} else {
xmlWriter.writeStartElement(parentQName.getLocalPart());
}
if (serializeType){
java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://ec2.amazonaws.com/doc/2009-10-31/");
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
namespacePrefix+":CreateVpcResponseType",
xmlWriter);
} else {
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
"CreateVpcResponseType",
xmlWriter);
}
}
namespace = "http://ec2.amazonaws.com/doc/2009-10-31/";
if (! namespace.equals("")) {
prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = generatePrefix(namespace);
xmlWriter.writeStartElement(prefix,"requestId", namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
} else {
xmlWriter.writeStartElement(namespace,"requestId");
}
} else {
xmlWriter.writeStartElement("requestId");
}
if (localRequestId==null){
// write the nil attribute
throw new org.apache.axis2.databinding.ADBException("requestId cannot be null!!");
}else{
xmlWriter.writeCharacters(localRequestId);
}
xmlWriter.writeEndElement();
if (localVpc==null){
throw new org.apache.axis2.databinding.ADBException("vpc cannot be null!!");
}
localVpc.serialize(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2009-10-31/","vpc"),
factory,xmlWriter);
xmlWriter.writeEndElement();
}
/**
* Util method to write an attribute with the ns prefix
*/
private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace,attName,attValue);
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeAttribute(java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (namespace.equals(""))
{
xmlWriter.writeAttribute(attName,attValue);
}
else
{
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace,attName,attValue);
}
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName,
javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String attributeNamespace = qname.getNamespaceURI();
java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace);
if (attributePrefix == null) {
attributePrefix = registerPrefix(xmlWriter, attributeNamespace);
}
java.lang.String attributeValue;
if (attributePrefix.trim().length() > 0) {
attributeValue = attributePrefix + ":" + qname.getLocalPart();
} else {
attributeValue = qname.getLocalPart();
}
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName, attributeValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace, attName, attributeValue);
}
}
/**
* method to handle Qnames
*/
private void writeQName(javax.xml.namespace.QName qname,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String namespaceURI = qname.getNamespaceURI();
if (namespaceURI != null) {
java.lang.String prefix = xmlWriter.getPrefix(namespaceURI);
if (prefix == null) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
} else {
// i.e this is the default namespace
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
} else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
}
private void writeQNames(javax.xml.namespace.QName[] qnames,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (qnames != null) {
// we have to store this data until last moment since it is not possible to write any
// namespace data after writing the charactor data
java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer();
java.lang.String namespaceURI = null;
java.lang.String prefix = null;
for (int i = 0; i < qnames.length; i++) {
if (i > 0) {
stringToWrite.append(" ");
}
namespaceURI = qnames[i].getNamespaceURI();
if (namespaceURI != null) {
prefix = xmlWriter.getPrefix(namespaceURI);
if ((prefix == null) || (prefix.length() == 0)) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
}
xmlWriter.writeCharacters(stringToWrite.toString());
}
}
/**
* Register a namespace prefix
*/
private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = generatePrefix(namespace);
while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) {
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
/**
* databinding method to get an XML representation of this object
*
*/
public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName)
throws org.apache.axis2.databinding.ADBException{
java.util.ArrayList elementList = new java.util.ArrayList();
java.util.ArrayList attribList = new java.util.ArrayList();
elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2009-10-31/",
"requestId"));
if (localRequestId != null){
elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localRequestId));
} else {
throw new org.apache.axis2.databinding.ADBException("requestId cannot be null!!");
}
elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2009-10-31/",
"vpc"));
if (localVpc==null){
throw new org.apache.axis2.databinding.ADBException("vpc cannot be null!!");
}
elementList.add(localVpc);
return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray());
}
/**
* Factory class that keeps the parse method
*/
public static class Factory{
/**
* static method to create the object
* Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable
* If this object is not an element, it is a complex type and the reader is at the event just after the outer start element
* Postcondition: If this object is an element, the reader is positioned at its end element
* If this object is a complex type, the reader is positioned at the end element of its outer element
*/
public static CreateVpcResponseType parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{
CreateVpcResponseType object =
new CreateVpcResponseType();
int event;
java.lang.String nillableValue = null;
java.lang.String prefix ="";
java.lang.String namespaceuri ="";
try {
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){
java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance",
"type");
if (fullTypeName!=null){
java.lang.String nsPrefix = null;
if (fullTypeName.indexOf(":") > -1){
nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":"));
}
nsPrefix = nsPrefix==null?"":nsPrefix;
java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1);
if (!"CreateVpcResponseType".equals(type)){
//find namespace for the prefix
java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (CreateVpcResponseType)com.amazon.ec2.ExtensionMapper.getTypeObject(
nsUri,type,reader);
}
}
}
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
java.util.Vector handledAttributes = new java.util.Vector();
reader.next();
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2009-10-31/","requestId").equals(reader.getName())){
java.lang.String content = reader.getElementText();
object.setRequestId(
org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content));
reader.next();
} // End of if for expected property start element
else{
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName());
}
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2009-10-31/","vpc").equals(reader.getName())){
object.setVpc(com.amazon.ec2.VpcType.Factory.parse(reader));
reader.next();
} // End of if for expected property start element
else{
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName());
}
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.isStartElement())
// A start element we are not expecting indicates a trailing invalid property
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName());
} catch (javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
}//end of factory class
}
| apache-2.0 |
446541492/solo | src/main/java/org/b3log/solo/repository/impl/TagArticleRepositoryImpl.java | 2698 | /*
* Copyright (c) 2010-2016, b3log.org & hacpai.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.b3log.solo.repository.impl;
import java.util.List;
import org.b3log.solo.model.Article;
import org.b3log.solo.model.Tag;
import org.b3log.solo.repository.TagArticleRepository;
import org.b3log.latke.Keys;
import org.b3log.latke.repository.AbstractRepository;
import org.b3log.latke.repository.FilterOperator;
import org.b3log.latke.repository.PropertyFilter;
import org.b3log.latke.repository.Query;
import org.b3log.latke.repository.RepositoryException;
import org.b3log.latke.repository.SortDirection;
import org.b3log.latke.repository.annotation.Repository;
import org.b3log.latke.util.CollectionUtils;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* Tag-Article relation repository.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.0.0.9, Nov 9, 2011
* @since 0.3.1
*/
@Repository
public class TagArticleRepositoryImpl extends AbstractRepository implements TagArticleRepository {
/**
* Public constructor.
*/
public TagArticleRepositoryImpl() {
super(Tag.TAG + "_" + Article.ARTICLE);
}
@Override
public List<JSONObject> getByArticleId(final String articleId) throws RepositoryException {
final Query query = new Query().setFilter(new PropertyFilter(Article.ARTICLE + "_" + Keys.OBJECT_ID, FilterOperator.EQUAL, articleId)).setPageCount(
1);
final JSONObject result = get(query);
final JSONArray array = result.optJSONArray(Keys.RESULTS);
return CollectionUtils.jsonArrayToList(array);
}
@Override
public JSONObject getByTagId(final String tagId, final int currentPageNum, final int pageSize) throws RepositoryException {
final Query query = new Query().setFilter(new PropertyFilter(Tag.TAG + "_" + Keys.OBJECT_ID, FilterOperator.EQUAL, tagId)).addSort(Article.ARTICLE + "_" + Keys.OBJECT_ID, SortDirection.DESCENDING).setCurrentPageNum(currentPageNum).setPageSize(pageSize).setPageCount(
1);
return get(query);
}
}
| apache-2.0 |
ampproject/validator-java | src/main/java/dev/amp/validator/selector/Selector.java | 1540 | /*
*
* ====================================================================
* 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.
* ====================================================================
*/
/*
* Changes to the original project are Copyright 2019, Verizon Media Inc..
*/
package dev.amp.validator.selector;
import dev.amp.validator.css.CssValidationException;
import dev.amp.validator.css.Token;
import dev.amp.validator.visitor.SelectorVisitor;
import java.util.function.Consumer;
/**
* Abstract super class for CSS Selectors. The Token class, which this
* class inherits from, has line, col, and tokenType fields.
*
* @author nhant01
* @author GeorgeLuo
*/
public abstract class Selector extends Token {
/** @param selector selector function */
public abstract void forEachChild(Consumer<Selector> selector);
/** @param visitor a SelectorVisitor instance
* @throws CssValidationException
*/
public abstract void accept(SelectorVisitor visitor) throws CssValidationException;
}
| apache-2.0 |
ConsecroMUD/ConsecroMUD | com/suscipio_solutions/consecro_mud/Abilities/Properties/Prop_ItemTransporter.java | 9257 | package com.suscipio_solutions.consecro_mud.Abilities.Properties;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Vector;
import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Container;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Item;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Wearable;
import com.suscipio_solutions.consecro_mud.Locales.interfaces.Room;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.interfaces.Environmental;
import com.suscipio_solutions.consecro_mud.core.interfaces.ItemPossessor;
import com.suscipio_solutions.consecro_mud.core.interfaces.PhysicalAgent;
import com.suscipio_solutions.consecro_mud.core.interfaces.ShopKeeper;
import com.suscipio_solutions.consecro_mud.core.interfaces.Tickable;
@SuppressWarnings({"unchecked","rawtypes"})
public class Prop_ItemTransporter extends Property
{
@Override public String ID() { return "Prop_ItemTransporter"; }
@Override public String name(){ return "Item Transporter";}
@Override protected int canAffectCode(){return Ability.CAN_MOBS|Ability.CAN_ITEMS|Ability.CAN_ROOMS;}
protected Room roomDestination=null;
protected MOB mobDestination=null;
protected Container nextDestination=null;
protected static Map<String,List<PhysicalAgent>> possiblePossibilities=new Hashtable<String,List<PhysicalAgent>>();
protected static Map<String,Integer> lastLooks=new Hashtable<String,Integer>();
@Override
public String accountForYourself()
{ return "Item Transporter"; }
public Item ultimateParent(Item item)
{
if(item==null) return null;
if(item.container()==null) return item;
if(item.container().container()==item)
item.container().setContainer(null);
if(item.container()==item)
item.setContainer(null);
return ultimateParent(item.container());
}
private synchronized boolean setDestination()
{
List<PhysicalAgent> possibilities=possiblePossibilities.get(text());
Integer lastLook=lastLooks.get(text());
if((possibilities==null)||(lastLook==null)||(lastLook.intValue()<0))
{
possibilities=new Vector();
possiblePossibilities.put(text(),possibilities);
lastLook=Integer.valueOf(10);
lastLooks.put(text(),lastLook);
}
else
lastLooks.put(text(),Integer.valueOf(lastLook.intValue()-1));
if(possibilities.size()==0)
{
roomDestination=null;
mobDestination=null;
nextDestination=null;
try
{
for(final Enumeration r=CMLib.map().rooms();r.hasMoreElements();)
{
final Room room=(Room)r.nextElement();
Ability A=room.fetchEffect("Prop_ItemTransReceiver");
if((A!=null)&&(A.text().equalsIgnoreCase(text())))
possibilities.add(room);
for(int i=0;i<room.numItems();i++)
{
final Item item=room.getItem(i);
if((item!=null)&&(item!=affected))
{
A=item.fetchEffect("Prop_ItemTransReceiver");
if((A!=null)&&(A.text().equalsIgnoreCase(text())))
possibilities.add(item);
}
}
for(int m=0;m<room.numInhabitants();m++)
{
final MOB mob=room.fetchInhabitant(m);
if((mob!=null)&&(mob!=affected))
{
A=mob.fetchEffect("Prop_ItemTransReceiver");
if((A!=null)&&(A.text().equalsIgnoreCase(text())))
possibilities.add(mob);
for(int i=0;i<mob.numItems();i++)
{
final Item item=mob.getItem(i);
if((item!=null)&&(item!=affected))
{
A=item.fetchEffect("Prop_ItemTransReceiver");
if((A!=null)&&(A.text().equalsIgnoreCase(text())))
possibilities.add(item);
}
}
}
}
}
}catch(final NoSuchElementException e){}
}
if(possibilities.size()>0)
{
final PhysicalAgent P=possibilities.get(CMLib.dice().roll(1,possibilities.size(),-1));
nextDestination=null;
if(P instanceof Room)
roomDestination=(Room)P;
else
if(P instanceof MOB)
mobDestination=(MOB)P;
else
if(P instanceof Container)
{
nextDestination=(Container)P;
if((nextDestination!=null)&&(nextDestination.owner()!=null))
{
if(nextDestination.owner() instanceof Room)
roomDestination=(Room)nextDestination.owner();
else
if(nextDestination.owner() instanceof MOB)
mobDestination=(MOB)nextDestination.owner();
}
else
nextDestination=null;
}
else
if(P instanceof Item)
{
nextDestination=null;
final Item I = (Item)P;
if(I.owner()!=null)
{
if(I.owner() instanceof Room)
roomDestination=(Room)I.owner();
else
if(I.owner() instanceof MOB)
mobDestination=(MOB)I.owner();
}
}
}
if((mobDestination==null)&&(roomDestination==null))
return false;
return true;
}
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!super.okMessage(myHost,msg))
return false;
if(affected==null) return true;
if(((msg.amITarget(affected))
&&((msg.targetMinor()==CMMsg.TYP_PUT)
||(msg.targetMinor()==CMMsg.TYP_GIVE))
&&(msg.tool() instanceof Item))
||((affected instanceof MOB)
&&(msg.amISource((MOB)affected))
&&((msg.targetMinor()==CMMsg.TYP_GET)||(msg.targetMinor()==CMMsg.TYP_PUSH)||(msg.targetMinor()==CMMsg.TYP_PULL))
&&(msg.target() instanceof Item))
||((affected instanceof Room)
&&(msg.targetMinor()==CMMsg.TYP_DROP)
&&(msg.target() instanceof Item))
||((affected instanceof Room)
&&(msg.sourceMinor()==CMMsg.TYP_THROW)
&&(affected==CMLib.map().roomLocation(msg.target()))
&&(msg.tool() instanceof Item)))
{
if(!setDestination())
{
msg.source().tell(L("The transporter has no possible ItemTransReceiver with the code '@x1'.",text()));
return false;
}
}
return true;
}
public synchronized void tryToMoveStuff()
{
if((mobDestination!=null)||(roomDestination!=null))
{
final Room room=roomDestination;
final MOB mob=mobDestination;
Room roomMover=null;
MOB mobMover=null;
Item container=null;
if(affected==null) return;
if(affected instanceof Room)
roomMover=(Room)affected;
else
if(affected instanceof MOB)
mobMover=(MOB)affected;
else
if(affected instanceof Item)
{
container=(Item)affected;
if((container.owner()!=null)&&(container.owner() instanceof Room))
roomMover=(Room)container.owner();
else
if((container.owner()!=null)&&(container.owner() instanceof MOB))
mobMover=(MOB)container.owner();
}
final Vector itemsToMove=new Vector();
if(roomMover!=null)
{
for(int i=0;i<roomMover.numItems();i++)
{
final Item item=roomMover.getItem(i);
if((item!=null)
&&(item!=container)
&&(item.amWearingAt(Wearable.IN_INVENTORY))
&&((item.container()==container)||(ultimateParent(item)==container)))
itemsToMove.addElement(item);
}
for(int i=0;i<itemsToMove.size();i++)
roomMover.delItem((Item)itemsToMove.elementAt(i));
}
else
if(mobMover!=null)
{
final int oldNum=itemsToMove.size();
for(int i=0;i<mobMover.numItems();i++)
{
final Item item=mobMover.getItem(i);
if((item!=null)
&&(item!=container)
&&(item.amWearingAt(Wearable.IN_INVENTORY))
&&((item.container()==container)||(ultimateParent(item)==container)))
itemsToMove.addElement(item);
}
for(int i=oldNum;i<itemsToMove.size();i++)
mobMover.delItem((Item)itemsToMove.elementAt(i));
}
if(itemsToMove.size()>0)
{
mobDestination=null;
roomDestination=null;
if(room!=null)
for(int i=0;i<itemsToMove.size();i++)
{
final Item item=(Item)itemsToMove.elementAt(i);
if((item.container()==null)||(item.container()==container))
item.setContainer(nextDestination);
room.addItem(item,ItemPossessor.Expire.Player_Drop);
}
if(mob!=null)
for(int i=0;i<itemsToMove.size();i++)
{
final Item item=(Item)itemsToMove.elementAt(i);
if((item.container()==null)||(item.container()==container))
item.setContainer(nextDestination);
if(mob instanceof ShopKeeper)
((ShopKeeper)mob).getShop().addStoreInventory(item);
else
mob.addItem(item);
}
if(room!=null) room.recoverRoomStats();
if(mob!=null)
{
mob.recoverCharStats();
mob.recoverPhyStats();
mob.recoverMaxState();
}
}
}
}
@Override
public boolean tick(Tickable ticking, int tickID)
{
if(tickID==Tickable.TICKID_MOB)
tryToMoveStuff();
return true;
}
@Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
// amazingly important that this happens first!
super.executeMsg(myHost,msg);
if((msg.targetMinor()==CMMsg.TYP_GET)
||(msg.targetMinor()==CMMsg.TYP_GIVE)
||(msg.targetMinor()==CMMsg.TYP_PUT)
||(msg.targetMinor()==CMMsg.TYP_PUSH)
||(msg.targetMinor()==CMMsg.TYP_PULL)
||(msg.sourceMinor()==CMMsg.TYP_THROW)
||(msg.targetMinor()==CMMsg.TYP_DROP))
tryToMoveStuff();
}
}
| apache-2.0 |
danielpalme/IocPerformance | IocPerformance/Adapters/ContainerAdapterBase.cs | 3267 | using System;
using System.Linq;
using System.Xml.Linq;
using IocPerformance.Classes.AspNet;
using Microsoft.Extensions.DependencyInjection;
namespace IocPerformance.Adapters
{
public abstract class ContainerAdapterBase : IContainerAdapter
{
public virtual string Version
{
get
{
return XDocument
.Load("../../IocPerformance.csproj")
.Root
.Descendants("PackageReference")
.First(e => e.Attribute("Include").Value == this.PackageName)
.Attribute("Version").Value;
}
}
public virtual string Name => this.PackageName;
public abstract string PackageName
{
get;
}
public abstract string Url
{
get;
}
public virtual bool SupportsInterception => false;
public virtual bool SupportsPropertyInjection => false;
public virtual bool SupportsChildContainer => false;
public virtual bool SupportAspNetCore => false;
public virtual bool SupportsConditional => false;
public virtual bool SupportGeneric => false;
public virtual bool SupportsMultiple => false;
public virtual bool SupportsTransient => true;
public virtual bool SupportsCombined => true;
public virtual bool SupportsBasic => true;
public virtual bool SupportsPrepareAndRegister => true;
public abstract void PrepareBasic();
public override string ToString()
{
return this.Name;
}
public virtual void Prepare()
{
this.PrepareBasic(); // by default any prepare should at least support basic one
}
public abstract object Resolve(Type type);
public virtual IChildContainerAdapter CreateChildContainerAdapter()
{
throw new NotImplementedException();
}
public abstract void Dispose();
protected void RegisterAspNetCoreClasses(IServiceCollection serviceCollection)
{
serviceCollection.AddTransient<TestController1>();
serviceCollection.AddTransient<TestController2>();
serviceCollection.AddTransient<TestController3>();
serviceCollection.AddTransient<IRepositoryTransient1, RepositoryTransient1>();
serviceCollection.AddTransient<IRepositoryTransient2, RepositoryTransient2>();
serviceCollection.AddTransient<IRepositoryTransient3, RepositoryTransient3>();
serviceCollection.AddTransient<IRepositoryTransient4, RepositoryTransient4>();
serviceCollection.AddTransient<IRepositoryTransient5, RepositoryTransient5>();
serviceCollection.AddScoped<IScopedService1, ScopedService1>();
serviceCollection.AddScoped<IScopedService2, ScopedService2>();
serviceCollection.AddScoped<IScopedService3, ScopedService3>();
serviceCollection.AddScoped<IScopedService4, ScopedService4>();
serviceCollection.AddScoped<IScopedService5, ScopedService5>();
}
}
} | apache-2.0 |
Stormancer/stormancer-management-for-net | Stormancer.Management.Cmd/Commands/Emulator/RegisterAppCommand.cs | 1406 | using Newtonsoft.Json;
using Stormancer.Management.Cmd.Commands.Accounts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Stormancer.Management.Cmd.Emulator
{
class RegisterAppCommand : Command
{
private string name;
private string directory;
public override string Name
{
get { return "test app"; }
}
public override async Task Run()
{
//using (var client = Host.CreateEmulatorClient())
//{
// var data = JsonConvert.SerializeObject(directory);
// var result = await client.PutAsync("applications/" + name, new StringContent(data, Encoding.UTF8, "application/json"));
//}
//var use = new SelectAccount { Emulator = true, Application = name };
//use.Init(this.Host);
//await use.Run();
}
public override void Validate()
{
EnsureParameterExist(ref name, "name");
EnsureParameterExist(ref directory, "directory");
}
public override void ParseParameters(Mono.Options.OptionSet p)
{
p.Add("name=", v => name = v);
p.Add("directory=", v => directory = v);
}
}
}
| apache-2.0 |
googlesamples/arcore-illusive-images | Assets/GoogleARCore/SDK/Scripts/DetectedPlane.cs | 5238 | //-----------------------------------------------------------------------
// <copyright file="DetectedPlane.cs" company="Google">
//
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCore
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using GoogleARCoreInternal;
using UnityEngine;
/// <summary>
/// A planar surface in the real world detected and tracked by ARCore.
/// </summary>
public class DetectedPlane : Trackable
{
/// <summary>
/// Construct DetectedPlane from a native handle.
/// </summary>
/// <param name="nativeHandle">A handle to the native ARCore API Trackable.</param>
/// <param name="nativeApi">The ARCore native api.</param>
internal DetectedPlane(IntPtr nativeHandle, NativeSession nativeApi)
: base(nativeHandle, nativeApi)
{
m_TrackableNativeHandle = nativeHandle;
m_NativeSession = nativeApi;
}
/// <summary>
/// Gets a reference to the plane subsuming this plane, if any. If not null, only the subsuming plane should be
/// considered valid for rendering.
/// </summary>
public DetectedPlane SubsumedBy
{
get
{
if (_IsSessionDestroyed())
{
Debug.LogError("SubsumedBy:: Trying to access a session that has already been destroyed.");
return null;
}
return m_NativeSession.PlaneApi.GetSubsumedBy(m_TrackableNativeHandle);
}
}
/// <summary>
/// Gets the position and orientation of the plane's center in Unity world space.
/// </summary>
public Pose CenterPose
{
get
{
if (_IsSessionDestroyed())
{
Debug.LogError("CenterPose:: Trying to access a session that has already been destroyed.");
return new Pose();
}
return m_NativeSession.PlaneApi.GetCenterPose(m_TrackableNativeHandle);
}
}
/// <summary>
/// Gets the extent of the plane in the X dimension, centered on the plane position.
/// </summary>
public float ExtentX
{
get
{
if (_IsSessionDestroyed())
{
Debug.LogError("ExtentX:: Trying to access a session that has already been destroyed.");
return 0f;
}
return m_NativeSession.PlaneApi.GetExtentX(m_TrackableNativeHandle);
}
}
/// <summary>
/// Gets the extent of the plane in the Z dimension, centered on the plane position.
/// </summary>
public float ExtentZ
{
get
{
if (_IsSessionDestroyed())
{
Debug.LogError("ExtentZ:: Trying to access a session that has already been destroyed.");
return 0f;
}
return m_NativeSession.PlaneApi.GetExtentZ(m_TrackableNativeHandle);
}
}
/// <summary>
/// Gets the type of the plane.
/// </summary>
public DetectedPlaneType PlaneType
{
get
{
if (_IsSessionDestroyed())
{
Debug.LogError("PlaneType:: Trying to access a session that has already been destroyed.");
return DetectedPlaneType.HorizontalUpwardFacing;
}
return m_NativeSession.PlaneApi.GetPlaneType(m_TrackableNativeHandle);
}
}
/// <summary>
/// Gets a list of points (in clockwise order) in Unity world space representing a boundary polygon for
/// the plane.
/// </summary>
/// <param name="boundaryPolygonPoints">A list of <b>Vector3</b> to be filled by the method call.</param>
[SuppressMemoryAllocationError(Reason = "List could be resized.")]
public void GetBoundaryPolygon(List<Vector3> boundaryPolygonPoints)
{
if (_IsSessionDestroyed())
{
Debug.LogError("GetBoundaryPolygon:: Trying to access a session that has already been destroyed.");
return;
}
m_NativeSession.PlaneApi.GetPolygon(m_TrackableNativeHandle, boundaryPolygonPoints);
}
}
} | apache-2.0 |
huashengzzz/SmartChart | app/src/main/java/com/smart/smartchart/widget/weatherview/PicUtil.java | 2182 | package com.smart.smartchart.widget.weatherview;
import com.smart.smartchart.R;
public class PicUtil {
public static int getDayWeatherPic(String weatherName) {
switch (weatherName) {
case "晴":
return R.drawable.icon_cloudy;
case "多云":
return R.drawable.icon_cloudy;
case "阴":
return R.drawable.icon_cloudy;
case "雷阵雨":
return R.drawable.icon_cloudy;
case "雨夹雪":
return R.drawable.icon_cloudy;
case "小雨":
return R.drawable.icon_cloudy;
case "中雨":
return R.drawable.icon_cloudy;
case "大雨":
return R.drawable.icon_cloudy;
case "暴雨":
return R.drawable.icon_cloudy;
case "大雪":
return R.drawable.icon_cloudy;
case "中雪":
return R.drawable.icon_cloudy;
case "冰雹":
return R.drawable.icon_cloudy;
}
return R.drawable.icon_cloudy;
}
public static int getNightWeatherPic(String weatherName) {
switch (weatherName) {
case "晴":
return R.drawable.icon_cloudy;
case "多云":
return R.drawable.icon_cloudy;
case "阴":
return R.drawable.icon_cloudy;
case "雷阵雨":
return R.drawable.icon_cloudy;
case "雨夹雪":
return R.drawable.icon_cloudy;
case "小雨":
return R.drawable.icon_cloudy;
case "中雨":
return R.drawable.icon_cloudy;
case "大雨":
return R.drawable.icon_cloudy;
case "暴雨":
return R.drawable.icon_cloudy;
case "大雪":
return R.drawable.icon_cloudy;
case "中雪":
return R.drawable.icon_cloudy;
case "冰雹":
return R.drawable.icon_cloudy;
}
return R.drawable.icon_cloudy;
}
}
| apache-2.0 |
ZA-PT/Obsidian.Authentication.WordPress | src/obsidian.php | 1834 | <?php
/*
Plugin Name: Obsidian Authentication Plugin
Plugin URI: https://github.com/ZA-PT/Obsidian.Authentication.WordPress
Description: A WordPress plugin provided a convenient way to access Obsidian-based Authentication Server.
Version: 0.9.9
Author: ZA-PT
Author URI: http://www.za-pt.org
License: Apache License 2.0
License URI: http://www.apache.org/licenses/LICENSE-2.0.html
Text Domain :obsidian-auth
*/
define("ROOT_PATH",__DIR__);
require_once(ROOT_PATH."/helper/jwt.php");
require_once(ROOT_PATH."/hook-handler.php");
require_once(ROOT_PATH."/views/view-controller.php");
require_once(ROOT_PATH."/authentication/client.php");
//enable session
if(!session_id()) session_start();
/*load text domain form internationalization*/
load_plugin_textdomain( "obsidian-auth", "", ROOT_PATH."/lang/" );
/*setup hook for plugin installation*/
register_activation_hook(__FILE__,"obsidian_hook_handler::register_activation_hook_handler");
register_deactivation_hook(__FILE__,"obsidian_hook_handler::register_deactivation_hook_handler");
/*setup hook for Resource Owner Password Credential Mode*/
add_filter("authenticate","obsidian_hook_handler::authenticate_handler",30,3);
/*setup hook into 'init' action to enable Authorization Code Mode and Implict Mode*/
add_filter("init","obsidian_hook_handler::init_handler");
/*setup hook into 'login_form' action to insert login button*/
add_action("login_form","obsidian_hook_handler::login_form_handler");
/*setup hook into 'user_profile_form' to insert profile binding*/
add_action("show_user_profile", "obsidian_hook_handler::edit_user_profile_handler");
add_action("edit_user_profile", "obsidian_hook_handler::edit_user_profile_handler");
/*setup hook into 'admin_menu' to insert option page*/
add_action("admin_menu", "obsidian_hook_handler::admin_menu_handler");
?> | apache-2.0 |
reminisceme/deployment | scala-base/bootstrap/src/main/scala/Bootstrap.scala | 69 | object Bootstrap extends App {
println("SBT is now bootstraped!")
}
| apache-2.0 |
agwlvssainokuni/springapp | admin/src/main/java/cherry/admin/secure/asyncproc/AsyncProcForm.java | 969 | /*
* Copyright 2015,2014 agwlvssainokuni
*
* 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 cherry.admin.secure.asyncproc;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class AsyncProcForm extends AsyncProcFormBase {
private static final long serialVersionUID = 1L;
}
| apache-2.0 |
spiegela/ecs-cf-service-broker | src/test/java/com/emc/ecs/management/sdk/BaseUrlActionTest.java | 1836 | package com.emc.ecs.management.sdk;
import com.emc.ecs.cloudfoundry.broker.EcsManagementClientException;
import com.emc.ecs.common.EcsActionTest;
import com.emc.ecs.management.sdk.model.BaseUrl;
import com.emc.ecs.management.sdk.model.BaseUrlInfo;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class BaseUrlActionTest extends EcsActionTest {
@Before
public void setUp() throws EcsManagementClientException {
connection.login();
}
@After
public void cleanup() throws EcsManagementClientException {
connection.logout();
}
@Test
public void testBaseUrlListAndGet() throws EcsManagementClientException {
BaseUrl baseUrl1 = BaseUrlAction.list(connection).get(0);
BaseUrl baseUrl2 = BaseUrlAction.list(connection).get(1);
BaseUrlInfo baseUrlInfo1 = BaseUrlAction.get(connection,
baseUrl1.getId());
BaseUrlInfo baseUrlInfo2 = BaseUrlAction.get(connection,
baseUrl2.getId());
assertTrue(baseUrlInfo1.getBaseurl().equals("localhost"));
assertTrue(baseUrlInfo1.getName().equals("DefaultBaseUrl"));
assertTrue(baseUrlInfo1.getNamespaceUrl(namespace, false)
.equals("http://localhost:9020"));
assertTrue(baseUrlInfo1.getNamespaceUrl(namespace, true)
.equals("https://localhost:9021"));
assertTrue(baseUrlInfo2.getBaseurl().equals("s3.10.5.5.5.xip.io"));
assertTrue(baseUrlInfo2.getName().equals("xip.io"));
assertTrue(baseUrlInfo2.getNamespaceUrl(namespace, false)
.equals("http://ns1.s3.10.5.5.5.xip.io:9020"));
assertTrue(baseUrlInfo2.getNamespaceUrl(namespace, true)
.equals("https://ns1.s3.10.5.5.5.xip.io:9021"));
}
} | apache-2.0 |
prometheus/promdash | app/assets/javascripts/angular/services/rickshaw_data_transformer.js | 1347 | angular.module("Prometheus.services").factory('RickshawDataTransformer', [function() {
function parseValue(value) {
if (value == "NaN" || value == "Inf" || value == "-Inf") {
// Show special float values as gaps, since there's no better way to
// display them.
return null;
} else {
return parseFloat(value);
}
}
function metricToTsName(labels) {
var tsName = (labels.__name__ || '') + "{";
var labelStrings = [];
for (var label in labels) {
if (label != "__name__") {
labelStrings.push(label + "=\"" + labels[label] + "\"");
}
}
tsName += labelStrings.join(",") + "}";
return tsName;
}
return function(data, axisIDByExprID) {
var series = [];
if (!data) {
return;
}
series = series.concat(data.data.map(function(ts) {
var name = metricToTsName(ts.metric);
return {
name: name,
// uniqName is added to be kept as a unique, unmodified identifier for a series.
uniqName: name,
type: data.type,
axisID: axisIDByExprID[data.expID],
expID: data.expID,
labels: ts.metric,
data: ts.values.map(function(value) {
return {
x: value[0],
y: parseValue(value[1])
};
})
};
}));
return series;
};
}]);
| apache-2.0 |
agorava/agorava-utils | solder-generics/api/src/main/java/org/agorava/utils/solder/reflection/AnnotationInspector.java | 13458 | /*
* Copyright 2012 Agorava
*
* 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.agorava.utils.solder.reflection;
import javax.enterprise.inject.Stereotype;
import javax.enterprise.inject.spi.Annotated;
import javax.enterprise.inject.spi.BeanManager;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* Inspect an {@link AnnotatedElement} or {@link Annotated} to obtain its meta-annotations and annotations,
* featuring support for {@link Stereotype} annotations as a transitive annotation provider.
*
* @author Pete Muir
* @author Dan Allen
* @author Ove Ranheim
*/
public class AnnotationInspector {
private AnnotationInspector() {
}
/**
* Discover if the {@link AnnotatedElement} has been annotated with the
* specified annotation type. This method discovers annotations defined on
* the element as well as annotations inherited from a CDI @
* {@link Stereotype} on the element.
*
* @param element The element to inspect
* @param annotationType The annotation type to expect
* @param beanManager The CDI BeanManager instance
* @return <code>true</code> if annotation is present either on the element
* itself or one of its stereotypes, <code>false</code> if the
* annotation is not present
*/
public static boolean isAnnotationPresent(AnnotatedElement element, Class<? extends Annotation> annotationType, BeanManager beanManager) {
if (element.isAnnotationPresent(annotationType)) {
return true;
}
return isAnnotationPresentOnStereotype(Arrays.asList(element.getAnnotations()), annotationType, beanManager);
}
/**
* Discover if the {@link Annotated} has been annotated with the specified
* annotation type. This method discovers annotations defined on
* the element as well as annotations inherited from a CDI @
* {@link Stereotype} on the element.
*
* @param element The element to inspect
* @param annotationType The annotation type to expect
* @param beanManager The CDI BeanManager instance
* @return <code>true</code> if annotation is present either on the element itself or one of its stereotypes,
* <code>false</code> if the annotation is not present
*/
public static boolean isAnnotationPresent(Annotated annotated, Class<? extends Annotation> annotationType, BeanManager beanManager) {
if (annotated.isAnnotationPresent(annotationType)) {
return true;
}
return isAnnotationPresentOnStereotype(annotated.getAnnotations(), annotationType, beanManager);
}
/**
* Discover if the {@link AnnotatedElement} has been annotated with the
* specified annotation type. If the transitive argument is <code>true</code>
* , this method also discovers annotations inherited from a CDI @
* {@link Stereotype} on the element.
*
* @param element The element to inspect
* @param annotationType The annotation to expect
* @param transitive Whether annotations provided by stereotypes should be
* considered
* @param beanManager The CDI BeanManager instance
* @return <code>true</code> if annotation is present on the element itself
* or (if specified) one of its stereotypes, <code>false</code> if the annotation is
* not present
*/
public static boolean isAnnotationPresent(AnnotatedElement element, Class<? extends Annotation> annotationType, boolean transitive, BeanManager beanManager) {
if (transitive) {
return isAnnotationPresent(element, annotationType, beanManager);
} else {
return element.isAnnotationPresent(annotationType);
}
}
/**
* Discover if the {@link AnnotatedElement} has been annotated with a @
* {@link Stereotype} that provides the annotation type.
*
* @param element The element to inspect
* @param annotationType The annotation type to expect
* @param beanManager The CDI BeanManager instance
* @return <code>true</code> if annotation is provided by a stereotype on the element,
* <code>false</code> if the annotation is not present
*/
public static boolean isAnnotationPresentOnStereotype(AnnotatedElement element, Class<? extends Annotation> annotationType, BeanManager beanManager) {
return isAnnotationPresentOnStereotype(Arrays.asList(element.getAnnotations()), annotationType, beanManager);
}
/**
* Discover if the {@link Annotated} has been annotated with a @
* {@link Stereotype} that provides the specified annotation type.
*
* @param element The element to inspect.
* @param annotationType The annotation type to expect
* @param beanManager The CDI BeanManager instance
* @return <code>true</code> if annotation is provided by a stereotype on the element,
* <code>false</code> if the annotation is not present
*/
public static boolean isAnnotationPresentOnStereotype(Annotated annotated, Class<? extends Annotation> annotationType, BeanManager beanManager) {
return isAnnotationPresentOnStereotype(annotated.getAnnotations(), annotationType, beanManager);
}
/**
* Inspect the {@link AnnotatedElement} and retrieve the specified annotation
* type, if present. This method discovers annotations defined on
* the element as well as annotations inherited from a CDI @
* {@link Stereotype} on the element.
*
* @param element The element to inspect
* @param annotationType The annotation type to expect
* @param beanManager The CDI BeanManager instance
* @return The annotation instance found on this element or null if no
* matching annotation was found.
*/
public static <A extends Annotation> A getAnnotation(AnnotatedElement element, Class<A> annotationType, BeanManager beanManager) {
if (element.isAnnotationPresent(annotationType)) {
return annotationType.cast(element.getAnnotation(annotationType));
}
return getAnnotationFromStereotype(Arrays.asList(element.getAnnotations()), annotationType, beanManager);
}
/**
* Inspect the {@link Annotated} and retrieve the specified annotation
* type, if present. This method discovers annotations defined on
* the element as well as annotations inherited from a CDI @
* {@link Stereotype} on the element.
*
* @param annotated The element to inspect
* @param annotationType The annotation type to expect
* @param beanManager The CDI BeanManager instance
* @return The annotation instance found on this element or null if no
* matching annotation was found.
*/
public static <A extends Annotation> A getAnnotation(Annotated annotated, Class<A> annotationType, BeanManager beanManager) {
if (annotated.isAnnotationPresent(annotationType)) {
return annotationType.cast(annotated.getAnnotation(annotationType));
}
return getAnnotationFromStereotype(annotated.getAnnotations(), annotationType, beanManager);
}
/**
* Inspect the {@link AnnotatedElement} for a specific annotation type. If the
* transitive argument is <code>true</code> , this method also discovers
* annotations inherited from a CDI @ {@link Stereotype} on the element.
*
* @param element The element to inspect
* @param annotationType The annotation type to expect
* @param transitive Whether the annotation may be used as a meta-annotation
* or not
* @param beanManager The CDI BeanManager instance
* @return The annotation instance found on this element or null if no
* matching annotation was found.
*/
public static <A extends Annotation> A getAnnotation(AnnotatedElement element, final Class<A> annotationType, boolean transitive, BeanManager beanManager) {
if (transitive) {
return getAnnotation(element, annotationType, beanManager);
} else {
return element.getAnnotation(annotationType);
}
}
/**
* Discover if the {@link AnnotatedElement} has been annotated with a @
* {@link Stereotype} that provides the annotation type and return it.
*
* @param element The element to inspect
* @param annotationType The annotation type to expect
* @param beanManager The CDI BeanManager instance
* @return The annotation instance found on this element or null if no
* matching annotation was found.
*/
public static <A extends Annotation> A getAnnotationFromStereotype(AnnotatedElement element, Class<A> annotationType, BeanManager beanManager) {
return getAnnotationFromStereotype(Arrays.asList(element.getAnnotations()), annotationType, beanManager);
}
/**
* Discover if the {@link Annotated} has been annotated with a @
* {@link Stereotype} that provides the specified annotation type and
* return it.
*
* @param element The element to inspect.
* @param annotationType The annotation type to expect
* @param beanManager The CDI BeanManager instance
* @return The annotation instance found on this element or null if no
* matching annotation was found.
*/
public static <A extends Annotation> A getAnnotationFromStereotype(Annotated annotated, Class<A> annotationType, BeanManager beanManager) {
return getAnnotationFromStereotype(annotated.getAnnotations(), annotationType, beanManager);
}
/**
* Inspects an annotated element for the given meta annotation. This should
* only be used for user defined meta annotations, where the annotation must
* be physically present.
*
* @param element The element to inspect
* @param annotationType The meta annotation to search for
* @return The annotation instance found on this element or null if no
* matching annotation was found.
*/
public static <A extends Annotation> A getMetaAnnotation(Annotated element, final Class<A> annotationType) {
for (Annotation annotation : element.getAnnotations()) {
if (annotation.annotationType().isAnnotationPresent(annotationType)) {
return annotation.annotationType().getAnnotation(annotationType);
}
}
return null;
}
/**
* Inspects an annotated element for any annotations with the given meta
* annotation. This should only be used for user defined meta annotations,
* where the annotation must be physically present.
*
* @param element The element to inspect
* @param annotationType The meta annotation to search for
* @return The annotation instances found on this element or an empty set if
* no matching meta-annotation was found.
*/
public static Set<Annotation> getAnnotations(Annotated element, final Class<? extends Annotation> metaAnnotationType) {
Set<Annotation> annotations = new HashSet<Annotation>();
for (Annotation annotation : element.getAnnotations()) {
if (annotation.annotationType().isAnnotationPresent(metaAnnotationType)) {
annotations.add(annotation);
}
}
return annotations;
}
private static boolean isAnnotationPresentOnStereotype(Collection<Annotation> annotations, Class<? extends Annotation> annotationType, BeanManager beanManager) {
for (Annotation candidate : annotations) {
if (beanManager.isStereotype(candidate.annotationType())) {
for (Annotation stereotyped : beanManager.getStereotypeDefinition(candidate.annotationType())) {
if (stereotyped.annotationType().equals(annotationType)) {
return true;
}
}
}
}
return false;
}
private static <A extends Annotation> A getAnnotationFromStereotype(Collection<Annotation> annotations, Class<A> annotationType, BeanManager beanManager) {
for (Annotation candidate : annotations) {
if (beanManager.isStereotype(candidate.annotationType())) {
for (Annotation stereotyped : beanManager.getStereotypeDefinition(candidate.annotationType())) {
if (stereotyped.annotationType().equals(annotationType)) {
return annotationType.cast(stereotyped);
}
}
}
}
return null;
}
}
| apache-2.0 |
mulesoft-consulting/sumtotal-connector | lib/apache-cxf-2.7.5/samples/ws_security/sign_enc/src/main/java/demo/wssec/client/UTPasswordCallback.java | 2225 | /**
* 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 demo.wssec.client;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import org.apache.ws.security.WSPasswordCallback;
/**
*/
public class UTPasswordCallback implements CallbackHandler {
private Map<String, String> passwords =
new HashMap<String, String>();
public UTPasswordCallback() {
passwords.put("Alice", "ecilA");
passwords.put("abcd", "dcba");
passwords.put("clientx509v1", "storepassword");
passwords.put("serverx509v1", "storepassword");
}
/**
* Here, we attempt to get the password from the private
* alias/passwords map.
*/
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
WSPasswordCallback pc = (WSPasswordCallback)callbacks[i];
String pass = passwords.get(pc.getIdentifier());
if (pass != null) {
pc.setPassword(pass);
return;
}
}
}
/**
* Add an alias/password pair to the callback mechanism.
*/
public void setAliasPassword(String alias, String password) {
passwords.put(alias, password);
}
}
| apache-2.0 |
Karasiq/shadowcloud | model/src/main/scala/com/karasiq/shadowcloud/model/utils/RegionHealth.scala | 1067 | package com.karasiq.shadowcloud.model.utils
import com.karasiq.shadowcloud.model.StorageId
@SerialVersionUID(0L)
final case class RegionHealth(usedSpace: Long, storages: Map[StorageId, StorageHealth]) extends HealthStatus {
def totalSpace: Long = createSum(_.totalSpace)
// def usedSpace: Long = createSum(_.usedSpace)
def freeSpace: Long = createSum(_.freeSpace)
def writableSpace: Long = createSum(_.writableSpace)
def online: Boolean = {
storages.nonEmpty && storages.values.exists(_.online)
}
def fullyOnline: Boolean = {
storages.nonEmpty && storages.values.forall(_.online)
}
def toStorageHealth: StorageHealth = {
StorageHealth.normalized(writableSpace, totalSpace, usedSpace, online)
}
private[this] def createSum(getValue: StorageHealth ⇒ Long): Long = {
val result = storages.values.filter(_.online).map(h ⇒ BigInt(getValue(h))).sum
if (!result.isValidLong) Long.MaxValue
else if (result < 0) 0L
else result.longValue()
}
}
object RegionHealth {
val empty = RegionHealth(0L, Map.empty)
}
| apache-2.0 |
mjm-cycronix/cloudturbine | CT2DB/src/cycronix/CT2DB/DBauthenticate.java | 3093 | package cycronix.CT2DB;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.session.AppKeyPair;
public class DBauthenticate {
// You don't need to change these, leave them alone.
final static private String ACCOUNT_PREFS_NAME = "DBA_prefs";
final static private String ACCESS_SECRET_NAME = "DBA_secret_name";
private SharedPreferences prefs;
DropboxAPI<AndroidAuthSession> mApi;
// constructor
public DBauthenticate(Context context, String APP_KEY, String APP_SECRET) {
prefs = context.getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
// We create a new AuthSession so that we can use the Dropbox API.
AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeyPair);
loadAuth(session);
mApi = new DropboxAPI<AndroidAuthSession>(session);
if(!session.authenticationSuccessful())
mApi.getSession().startOAuth2Authentication(context);
}
/**
* Retrieve the access keys returned from Trusted Authenticator in a local store
*/
private void loadAuth(AndroidAuthSession session) {
String secret = prefs.getString(ACCESS_SECRET_NAME, null);
if (secret == null || secret.length() == 0) return;
// Log.i("CT2DB","loadAuth: "+secret);
session.setOAuth2AccessToken(secret);
}
/**
* Keep the access keys returned from Trusted Authenticator in a local
* store, rather than storing user name & password, and re-authenticating each
* time (which is not to be done, ever).
*/
private void storeAuth(AndroidAuthSession session) {
// Store the OAuth 2 access token, if there is one.
String oauth2AccessToken = session.getOAuth2AccessToken();
if (oauth2AccessToken != null) {
Editor edit = prefs.edit();
edit.putString(ACCESS_SECRET_NAME, oauth2AccessToken);
edit.apply();
// Log.i("CT2DB","storeAuth: "+oauth2AccessToken);
return;
}
}
public void clearKeys() {
Editor edit = prefs.edit();
edit.clear();
edit.commit();
}
// The next method must be called in the onResume() method of the
// activity from which session.startAuthentication() was called, so
// that Dropbox authentication completes properly.
public DropboxAPI<AndroidAuthSession> resume() {
AndroidAuthSession session = mApi.getSession();
if (session.authenticationSuccessful()) {
try {
// Mandatory call to complete the auth
session.finishAuthentication();
// Store it locally in our app for later use
storeAuth(session);
} catch (IllegalStateException e) {
mApi = null;
}
}
return mApi;
}
}
| apache-2.0 |
DaKaZ/useek_mobile_poc | app/controllers/home.js | 544 |
function openGamesWindow(e){
// alert('TODO: Open Games Window');
Alloy.createController("videos").getView().open();
}
function openAccountWindow(e){
alert('TODO: Open Account Window');
}
function openFeaturedGame(e){
alert('TODO: Open Featured Game');
}
function openSignIn(e){
alert('TODO: Open Sign In Window');
}
function openSignUp(e){
alert('TODO: Open Sign Up Window');
}
function openLearnMore(e){
alert('TODO: Open Learn More Window');
}
function showMenu(e) {
$.trigger('openMenu');
}
var max_width = Ti.UI.FILL; | apache-2.0 |
ilya-klyuchnikov/buck | src-gen/com/facebook/buck/artifact_cache/thrift/BuckCacheDeleteResponse.java | 12498 | /**
* Autogenerated by Thrift Compiler (0.10.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.facebook.buck.artifact_cache.thrift;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2017-12-07")
public class BuckCacheDeleteResponse implements org.apache.thrift.TBase<BuckCacheDeleteResponse, BuckCacheDeleteResponse._Fields>, java.io.Serializable, Cloneable, Comparable<BuckCacheDeleteResponse> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("BuckCacheDeleteResponse");
private static final org.apache.thrift.protocol.TField DEBUG_INFO_FIELD_DESC = new org.apache.thrift.protocol.TField("debugInfo", org.apache.thrift.protocol.TType.STRUCT, (short)1);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new BuckCacheDeleteResponseStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new BuckCacheDeleteResponseTupleSchemeFactory();
public DeleteDebugInfo debugInfo; // optional
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
DEBUG_INFO((short)1, "debugInfo");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // DEBUG_INFO
return DEBUG_INFO;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final _Fields optionals[] = {_Fields.DEBUG_INFO};
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.DEBUG_INFO, new org.apache.thrift.meta_data.FieldMetaData("debugInfo", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, DeleteDebugInfo.class)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(BuckCacheDeleteResponse.class, metaDataMap);
}
public BuckCacheDeleteResponse() {
}
/**
* Performs a deep copy on <i>other</i>.
*/
public BuckCacheDeleteResponse(BuckCacheDeleteResponse other) {
if (other.isSetDebugInfo()) {
this.debugInfo = new DeleteDebugInfo(other.debugInfo);
}
}
public BuckCacheDeleteResponse deepCopy() {
return new BuckCacheDeleteResponse(this);
}
@Override
public void clear() {
this.debugInfo = null;
}
public DeleteDebugInfo getDebugInfo() {
return this.debugInfo;
}
public BuckCacheDeleteResponse setDebugInfo(DeleteDebugInfo debugInfo) {
this.debugInfo = debugInfo;
return this;
}
public void unsetDebugInfo() {
this.debugInfo = null;
}
/** Returns true if field debugInfo is set (has been assigned a value) and false otherwise */
public boolean isSetDebugInfo() {
return this.debugInfo != null;
}
public void setDebugInfoIsSet(boolean value) {
if (!value) {
this.debugInfo = null;
}
}
public void setFieldValue(_Fields field, java.lang.Object value) {
switch (field) {
case DEBUG_INFO:
if (value == null) {
unsetDebugInfo();
} else {
setDebugInfo((DeleteDebugInfo)value);
}
break;
}
}
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case DEBUG_INFO:
return getDebugInfo();
}
throw new java.lang.IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case DEBUG_INFO:
return isSetDebugInfo();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that == null)
return false;
if (that instanceof BuckCacheDeleteResponse)
return this.equals((BuckCacheDeleteResponse)that);
return false;
}
public boolean equals(BuckCacheDeleteResponse that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_debugInfo = true && this.isSetDebugInfo();
boolean that_present_debugInfo = true && that.isSetDebugInfo();
if (this_present_debugInfo || that_present_debugInfo) {
if (!(this_present_debugInfo && that_present_debugInfo))
return false;
if (!this.debugInfo.equals(that.debugInfo))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((isSetDebugInfo()) ? 131071 : 524287);
if (isSetDebugInfo())
hashCode = hashCode * 8191 + debugInfo.hashCode();
return hashCode;
}
@Override
public int compareTo(BuckCacheDeleteResponse other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.valueOf(isSetDebugInfo()).compareTo(other.isSetDebugInfo());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetDebugInfo()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.debugInfo, other.debugInfo);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("BuckCacheDeleteResponse(");
boolean first = true;
if (isSetDebugInfo()) {
sb.append("debugInfo:");
if (this.debugInfo == null) {
sb.append("null");
} else {
sb.append(this.debugInfo);
}
first = false;
}
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
if (debugInfo != null) {
debugInfo.validate();
}
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class BuckCacheDeleteResponseStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public BuckCacheDeleteResponseStandardScheme getScheme() {
return new BuckCacheDeleteResponseStandardScheme();
}
}
private static class BuckCacheDeleteResponseStandardScheme extends org.apache.thrift.scheme.StandardScheme<BuckCacheDeleteResponse> {
public void read(org.apache.thrift.protocol.TProtocol iprot, BuckCacheDeleteResponse struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // DEBUG_INFO
if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
struct.debugInfo = new DeleteDebugInfo();
struct.debugInfo.read(iprot);
struct.setDebugInfoIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, BuckCacheDeleteResponse struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.debugInfo != null) {
if (struct.isSetDebugInfo()) {
oprot.writeFieldBegin(DEBUG_INFO_FIELD_DESC);
struct.debugInfo.write(oprot);
oprot.writeFieldEnd();
}
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class BuckCacheDeleteResponseTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public BuckCacheDeleteResponseTupleScheme getScheme() {
return new BuckCacheDeleteResponseTupleScheme();
}
}
private static class BuckCacheDeleteResponseTupleScheme extends org.apache.thrift.scheme.TupleScheme<BuckCacheDeleteResponse> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, BuckCacheDeleteResponse struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet optionals = new java.util.BitSet();
if (struct.isSetDebugInfo()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetDebugInfo()) {
struct.debugInfo.write(oprot);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, BuckCacheDeleteResponse struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
struct.debugInfo = new DeleteDebugInfo();
struct.debugInfo.read(iprot);
struct.setDebugInfoIsSet(true);
}
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
| apache-2.0 |
jon-w/chef-repo | cookbooks/ldapclient/metadata.rb | 295 | name 'ldapclient'
maintainer 'Daisy Hill Cat Farm'
maintainer_email 'jonwil194@gmail.com'
license 'All rights reserved'
description 'Installs/Configures ldapclient'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.1.0'
| apache-2.0 |
lwch/2048 | html/api/mongo.php | 523 | <?php
function mongo() {
static $m = null;
if ($m === null) $m = new MongoClient();
return $m;
}
function uuid($len) {
$res = '';
for ($i = 0; $i < $len; ++$i) {
$type = mt_rand(0, 2);
switch ($type) {
case 0:
$res .= chr(0x30 + mt_rand(0, 9));
break;
case 1:
$res .= chr(0x61 + mt_rand(0, 25));
break;
case 2:
$res .= chr(0x41 + mt_rand(0, 25));
break;
}
}
return $res;
}
| apache-2.0 |
jmderuty/archeagecraft | ArcheageCraft/ArcheageCraft/Migrations/201411152255419_prices.cs | 404 | namespace ArcheageCraft.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class prices : DbMigration
{
public override void Up()
{
DropColumn("dbo.Prices", "UserId");
}
public override void Down()
{
AddColumn("dbo.Prices", "UserId", c => c.Int(nullable: false));
}
}
}
| apache-2.0 |
Arc3D/arcgis-runtime-samples-dotnet | src/ArcGISRuntime.Samples.Shared/Models/SubCategoryModel.cs | 1977 | // Copyright 2016 Esri.
//
// 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.
using ArcGISRuntime.Samples.Shared.Models;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace ArcGISRuntime.Samples.Models
{
/// <summary>
/// SubCategoryModel defines how samples are grouped under the categories.
/// </summary>
/// <remarks>
/// SubCategories are defined in a groups.json file that is used to construct the <see cref="SubCategoryModel"/>s.
/// </remarks>
[DataContract(Name = "SubCategories")]
public class SubCategoryModel
{
/// <summary>
/// Gets or sets the human readable name of the sub-category.
/// </summary>
[DataMember]
public string Name { get; set; }
/// <summary>
/// Gets or sets the name of the sub-category.
/// </summary>
[DataMember]
public string SubCategoryName { get; set; }
/// <summary>
/// Gets or sets if the category should be shown as a sub-category.
/// </summary>
[DataMember]
public bool ShowGroup { get; set; }
/// <summary>
/// Gets all sample infos that are part of this group.
/// </summary>
[DataMember]
public List<SampleInfo> SampleInfos { get; set; }
/// <summary>
/// Gets all the samples.
/// </summary>
[IgnoreDataMember]
public List<SampleModel> Samples { get; set; }
}
}
| apache-2.0 |
mwjmurphy/Axel-Framework | axel-web-db/src/main/java/org/xmlactions/pager/jasper/JasperReportHandler.java | 3010 | package org.xmlactions.pager.jasper;
import java.io.File;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmlactions.action.ActionConst;
import org.xmlactions.action.actions.BaseAction;
import org.xmlactions.action.config.IExecContext;
import org.xmlactions.db.DBUtils;
import org.xmlactions.db.config.StorageConfig;
import org.xmlactions.pager.actions.form.ClientParamNames;
import org.xmlactions.web.HttpParam;
import org.xmlactions.web.PagerWebConst;
public class JasperReportHandler extends BaseAction {
private static final Logger logger = LoggerFactory.getLogger(JasperReportHandler.class);
@Override
public String execute(IExecContext execContext) throws Exception {
List<HttpParam> params = (List<HttpParam>)execContext.get(PagerWebConst.REQUEST_LIST);
Validate.notNull(params, "Missing [" + PagerWebConst.REQUEST_LIST + "] from the execContext");
String jasperFileName = null;
String storage_config_ref = null;
String outputFileName = null;
HashMap<String, Object> map = new HashMap<String, Object>();
for (HttpParam param : params) {
if (param.getKey().equalsIgnoreCase("jasperFileName")) {
jasperFileName = (String)param.getValue();
} else if (param.getKey().equals(ClientParamNames.STORAGE_CONFIG_REF)) {
storage_config_ref = (String) param.getValue();
} else if (param.getKey().equals("outputFileName")) {
outputFileName = (String) param.getValue();
} else {
map.put(param.getKey(), (String) param.getValue());
}
}
Validate.notNull(jasperFileName, "Missing [jasperFileName] from the httpRequest");
String path = (String) execContext.get(ActionConst.WEB_REAL_PATH_BEAN_REF);
File file = new File(path, jasperFileName);
if (!file.exists() || file.isDirectory()) {
Validate.notNull(null, "File [" + file.getAbsolutePath() + "] not found.");
}
Validate.notNull(outputFileName, "Missing [outputFileName] from the httpRequest");
Validate.notNull(storage_config_ref, "Missing [" + ClientParamNames.STORAGE_CONFIG_REF + "] from the httpRequest");
StorageConfig storageConfig = (StorageConfig) execContext.get(storage_config_ref);
Validate.notNull(storageConfig, "No [" + StorageConfig.class.getName() + "] found in ExecContext ["
+ storage_config_ref + "]");
ReportGenerator reportGenerator = new ReportGenerator();
Connection conn = null;
try {
conn = storageConfig.getDbConnector().getConnection(execContext);
byte [] image = reportGenerator.generateJasperToPdf(conn, map, file.getAbsolutePath());
execContext.put("image", image);
execContext.put("outputFileName", outputFileName);
} finally {
DBUtils.closeQuietly(conn);
}
// TODO Auto-generated method stub
return null;
}
}
| apache-2.0 |
Kangz/nxt-standalone | src/backend/Sampler.cpp | 1444 | // Copyright 2017 The Dawn 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.
#include "backend/Sampler.h"
#include "backend/Device.h"
#include "backend/ValidationUtils_autogen.h"
namespace backend {
MaybeError ValidateSamplerDescriptor(DeviceBase*, const dawn::SamplerDescriptor* descriptor) {
DAWN_TRY_ASSERT(descriptor->nextInChain == nullptr, "nextInChain must be nullptr");
DAWN_TRY(ValidateFilterMode(descriptor->minFilter));
DAWN_TRY(ValidateFilterMode(descriptor->magFilter));
DAWN_TRY(ValidateFilterMode(descriptor->mipmapFilter));
DAWN_TRY(ValidateAddressMode(descriptor->addressModeU));
DAWN_TRY(ValidateAddressMode(descriptor->addressModeV));
DAWN_TRY(ValidateAddressMode(descriptor->addressModeW));
return {};
}
// SamplerBase
SamplerBase::SamplerBase(DeviceBase*, const dawn::SamplerDescriptor*) {
}
} // namespace backend
| apache-2.0 |
computerRND/webScienceRND | core/t_scopeMod/t_scopeMod.php | 69 | <?php namespace core\t_scopeMod;
trait t_scopeMod
{
}
| apache-2.0 |
sonu283304/onos | protocols/pcep/pcepio/src/test/java/org/onosproject/pcepio/types/BgpLsIdentifierSubTlvTest.java | 1213 | /*
* Copyright 2015 Open Networking Laboratory
*
* 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.onosproject.pcepio.types;
import com.google.common.testing.EqualsTester;
import org.junit.Test;
/**
* Test of the BgpLsIdentifierSubTlv.
*/
public class BgpLsIdentifierSubTlvTest {
private final BgpLsIdentifierSubTlv tlv1 = BgpLsIdentifierSubTlv.of(1);
private final BgpLsIdentifierSubTlv sameAsTlv1 = BgpLsIdentifierSubTlv.of(1);
private final BgpLsIdentifierSubTlv tlv2 = BgpLsIdentifierSubTlv.of(2);
@Test
public void basics() {
new EqualsTester()
.addEqualityGroup(tlv1, sameAsTlv1)
.addEqualityGroup(tlv2)
.testEquals();
}
}
| apache-2.0 |
davidtsadler/ebay-sdk-php | test/Metadata/Types/GetPoliciesForReturnsRestRequestTest.php | 815 | <?php
/**
* DO NOT EDIT THIS FILE!
*
* This file was automatically generated from external sources.
*
* Any manual change here will be lost the next time the SDK
* is updated. You've been warned!
*/
namespace DTS\eBaySDK\Test\Metadata\Types;
use DTS\eBaySDK\Metadata\Types\GetPoliciesForReturnsRestRequest;
class GetPoliciesForReturnsRestRequestTest extends \PHPUnit_Framework_TestCase
{
private $obj;
protected function setUp()
{
$this->obj = new GetPoliciesForReturnsRestRequest();
}
public function testCanBeCreated()
{
$this->assertInstanceOf('\DTS\eBaySDK\Metadata\Types\GetPoliciesForReturnsRestRequest', $this->obj);
}
public function testExtendsBaseType()
{
$this->assertInstanceOf('\DTS\eBaySDK\Types\BaseType', $this->obj);
}
}
| apache-2.0 |
mamoo/es6katas | class/solutions/creation.js | 1376 | // 22: class - creation
// To do: make all tests pass, leave the assert lines unchanged!
// Source: http://es6katas.org/
describe('class creation', () => {
it('is as simple as `class XXX {}`', function() {
let TestClass = class {};
const instance = new TestClass();
assert.equal(typeof instance, 'object');
});
it('class is block scoped', () => {
//class Inside {}
{class Inside {}}
assert.equal(typeof Inside, 'undefined');
});
it('special method is `constructor`', function() {
class User {
constructor(id) {
this.id = id;
}
}
const user = new User(42);
assert.equal(user.id, 42);
});
it('defining a method is simple', function() {
class User {
writesTests() {
return false;
}
}
const notATester = new User();
assert.equal(notATester.writesTests(), false);
});
it('multiple methods need no commas (opposed to object notation)', function() {
class User {
wroteATest() { this.everWroteATest = true; }
isLazy() { return !this.everWroteATest; }
}
const tester = new User();
assert.equal(tester.isLazy(), true);
tester.wroteATest();
assert.equal(tester.isLazy(), false);
});
it('anonymous class', () => {
const classType = typeof class{};
assert.equal(classType, 'function');
});
});
| apache-2.0 |
HMAZonderland/phpAmazonMWS | test/Inbound/AmazonShipmentTest.php | 14465 | <?php
namespace CPIGroupTest\Inbound;
use CPIGroup\Inbound\AmazonShipment;
use CPIGroup\Inbound\AmazonShipmentPlanner;
/**
* Generated by PHPUnit_SkeletonGenerator 1.2.0 on 2012-12-12 at 13:17:14.
*/
class AmazonShipmentTest extends \PHPUnit_Framework_TestCase
{
/**
* @var AmazonShipment
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
resetLog();
$this->object = new AmazonShipment('testStore', true, null, __DIR__ . '/../test-config.php');
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
}
public function testSetAddress()
{
$this->assertFalse($this->object->setAddress(null)); //can't be nothing
$this->assertFalse($this->object->setAddress('address')); //can't be a string
$this->assertFalse($this->object->setAddress(array())); //can't be empty
$this->assertFalse($this->object->setAddress(array('address' => 'address'))); //missing keys
$check = parseLog();
$this->assertEquals('Tried to set address to invalid values', $check[1]);
$this->assertEquals('Tried to set address to invalid values', $check[2]);
$this->assertEquals('Tried to set address to invalid values', $check[3]);
$this->assertEquals('Tried to set address with invalid array', $check[4]);
$a1 = array();
$a1['Name'] = 'Name';
$a1['AddressLine1'] = 'AddressLine1';
$a1['AddressLine2'] = 'AddressLine2';
$a1['City'] = 'City';
$a1['DistrictOrCounty'] = 'DistrictOrCounty';
$a1['StateOrProvinceCode'] = 'StateOrProvinceCode';
$a1['CountryCode'] = 'CountryCode';
$a1['PostalCode'] = 'PostalCode';
$this->assertNull($this->object->setAddress($a1));
$o = $this->object->getOptions();
$this->assertArrayHasKey('InboundShipmentHeader.ShipFromAddress.Name', $o);
$this->assertEquals('Name', $o['InboundShipmentHeader.ShipFromAddress.Name']);
$this->assertArrayHasKey('InboundShipmentHeader.ShipFromAddress.AddressLine1', $o);
$this->assertEquals('AddressLine1', $o['InboundShipmentHeader.ShipFromAddress.AddressLine1']);
$this->assertArrayHasKey('InboundShipmentHeader.ShipFromAddress.AddressLine2', $o);
$this->assertEquals('AddressLine2', $o['InboundShipmentHeader.ShipFromAddress.AddressLine2']);
$this->assertArrayHasKey('InboundShipmentHeader.ShipFromAddress.DistrictOrCounty', $o);
$this->assertEquals('DistrictOrCounty', $o['InboundShipmentHeader.ShipFromAddress.DistrictOrCounty']);
$this->assertArrayHasKey('InboundShipmentHeader.ShipFromAddress.City', $o);
$this->assertEquals('City', $o['InboundShipmentHeader.ShipFromAddress.City']);
$this->assertArrayHasKey('InboundShipmentHeader.ShipFromAddress.StateOrProvinceCode', $o);
$this->assertEquals('StateOrProvinceCode', $o['InboundShipmentHeader.ShipFromAddress.StateOrProvinceCode']);
$this->assertArrayHasKey('InboundShipmentHeader.ShipFromAddress.CountryCode', $o);
$this->assertEquals('CountryCode', $o['InboundShipmentHeader.ShipFromAddress.CountryCode']);
$this->assertArrayHasKey('InboundShipmentHeader.ShipFromAddress.PostalCode', $o);
$this->assertEquals('PostalCode', $o['InboundShipmentHeader.ShipFromAddress.PostalCode']);
$a2 = array();
$a2['Name'] = 'Name2';
$a2['AddressLine1'] = 'AddressLine1-2';
$a2['City'] = 'City2';
$a2['StateOrProvinceCode'] = 'StateOrProvinceCode2';
$a2['CountryCode'] = 'CountryCode2';
$a2['PostalCode'] = 'PostalCode2';
$this->assertNull($this->object->setAddress($a2)); //testing reset
$o2 = $this->object->getOptions();
$this->assertArrayHasKey('InboundShipmentHeader.ShipFromAddress.Name', $o2);
$this->assertEquals('Name2', $o2['InboundShipmentHeader.ShipFromAddress.Name']);
$this->assertNull($o2['InboundShipmentHeader.ShipFromAddress.AddressLine2']);
$this->assertNull($o2['InboundShipmentHeader.ShipFromAddress.DistrictOrCounty']);
}
public function testSetItems()
{
$this->assertFalse($this->object->setItems(null)); //can't be nothing
$this->assertFalse($this->object->setItems('item')); //can't be a string
$this->assertFalse($this->object->setItems(array())); //can't be empty
$break = array();
$break[0]['Bork'] = 'bork bork';
$this->assertFalse($this->object->setItems($break)); //missing seller sku
$break[0]['SellerSKU'] = 'some sku';
$this->assertFalse($this->object->setItems($break)); //missing quantity
$check = parseLog();
$this->assertEquals('Tried to set Items to invalid values', $check[1]);
$this->assertEquals('Tried to set Items to invalid values', $check[2]);
$this->assertEquals('Tried to set Items to invalid values', $check[3]);
$this->assertEquals('Tried to set Items with invalid array', $check[4]);
$this->assertEquals('Tried to set Items with invalid array', $check[5]);
$i = array();
$i[0]['SellerSKU'] = 'SellerSKU';
$i[0]['Quantity'] = 'Quantity';
$i[0]['QuantityInCase'] = 'QuantityInCase';
$i[1]['SellerSKU'] = 'SellerSKU2';
$i[1]['Quantity'] = 'Quantity2';
$this->assertNull($this->object->setItems($i));
$o = $this->object->getOptions();
$this->assertArrayHasKey('InboundShipmentItems.member.1.SellerSKU', $o);
$this->assertEquals('SellerSKU', $o['InboundShipmentItems.member.1.SellerSKU']);
$this->assertArrayHasKey('InboundShipmentItems.member.1.QuantityShipped', $o);
$this->assertEquals('Quantity', $o['InboundShipmentItems.member.1.QuantityShipped']);
$this->assertArrayHasKey('InboundShipmentItems.member.1.QuantityInCase', $o);
$this->assertEquals('QuantityInCase', $o['InboundShipmentItems.member.1.QuantityInCase']);
$this->assertArrayHasKey('InboundShipmentItems.member.1.SellerSKU', $o);
$this->assertEquals('SellerSKU2', $o['InboundShipmentItems.member.2.SellerSKU']);
$this->assertArrayHasKey('InboundShipmentItems.member.2.QuantityShipped', $o);
$this->assertEquals('Quantity2', $o['InboundShipmentItems.member.2.QuantityShipped']);
$i2 = array();
$i2[0]['SellerSKU'] = 'NewSellerSKU';
$i2[0]['Quantity'] = 'NewQuantity';
$this->assertNull($this->object->setItems($i2)); //will cause reset
$o2 = $this->object->getOptions();
$this->assertArrayHasKey('InboundShipmentItems.member.1.SellerSKU', $o2);
$this->assertEquals('NewSellerSKU', $o2['InboundShipmentItems.member.1.SellerSKU']);
$this->assertArrayHasKey('InboundShipmentItems.member.1.QuantityShipped', $o2);
$this->assertEquals('NewQuantity', $o2['InboundShipmentItems.member.1.QuantityShipped']);
$this->assertArrayNotHasKey('InboundShipmentItems.member.1.QuantityInCase', $o2);
$this->assertArrayNotHasKey('InboundShipmentItems.member.2.SellerSKU', $o2);
$this->assertArrayNotHasKey('InboundShipmentItems.member.2.QuantityShipped', $o2);
}
public function testSetStatus()
{
$this->assertFalse($this->object->setStatus(null)); //can't be nothing
$this->assertFalse($this->object->setStatus(5)); //can't be an int
$this->assertFalse($this->object->setStatus('wrong')); //not a valid value
$this->assertNull($this->object->setStatus('WORKING'));
$this->assertNull($this->object->setStatus('SHIPPED'));
$this->assertNull($this->object->setStatus('CANCELLED'));
$o = $this->object->getOptions();
$this->assertArrayHasKey('InboundShipmentHeader.ShipmentStatus', $o);
$this->assertEquals('CANCELLED', $o['InboundShipmentHeader.ShipmentStatus']);
}
public function testSetShipmentId()
{
$this->assertFalse($this->object->setShipmentId(null)); //can't be nothing
$this->assertFalse($this->object->setShipmentId(5)); //can't be an int
$this->assertNull($this->object->setShipmentId('777'));
$o = $this->object->getOptions();
$this->assertArrayHasKey('ShipmentId', $o);
$this->assertEquals('777', $o['ShipmentId']);
}
public function testUsePlan()
{
$planner = new AmazonShipmentPlanner('testStore', true, 'fetchPlan.xml', __DIR__ . '/../test-config.php');
$a = array();
$a['Name'] = 'Name';
$a['AddressLine1'] = 'AddressLine1';
$a['City'] = 'City';
$a['StateOrProvinceCode'] = 'StateOrProvinceCode';
$a['CountryCode'] = 'CountryCode';
$a['PostalCode'] = 'PostalCode';
$planner->setAddress($a);
$i = array();
$i[0]['SellerSKU'] = 'NewSellerSKU';
$i[0]['Quantity'] = 'NewQuantity';
$planner->setItems($i);
$this->assertNull($planner->fetchPlan());
$plan = $planner->getPlan(0);
$this->assertNull($this->object->usePlan($plan));
$o = $this->object->getOptions();
$this->assertEquals('FBA63J76R', $o['InboundShipmentHeader.ShipmentId']);
$this->assertEquals('PHX6', $o['InboundShipmentHeader.DestinationFulfillmentCenterId']);
$this->assertEquals('NO_LABEL', $o['InboundShipmentHeader.LabelPrepType']);
$this->assertEquals('Amazon.com', $o['InboundShipmentHeader.ShipFromAddress.Name']);
$this->assertEquals('4750 West Mohave St', $o['InboundShipmentHeader.ShipFromAddress.AddressLine1']);
$this->assertEquals(null, $o['InboundShipmentHeader.ShipFromAddress.AddressLine2']);
$this->assertEquals('Phoenix', $o['InboundShipmentHeader.ShipFromAddress.City']);
$this->assertEquals(null, $o['InboundShipmentHeader.ShipFromAddress.DistrictOrCounty']);
$this->assertEquals('AZ', $o['InboundShipmentHeader.ShipFromAddress.StateOrProvinceCode']);
$this->assertEquals('US', $o['InboundShipmentHeader.ShipFromAddress.CountryCode']);
$this->assertEquals('85043', $o['InboundShipmentHeader.ShipFromAddress.PostalCode']);
$this->assertEquals('Football2415', $o['InboundShipmentItems.member.1.SellerSKU']);
$this->assertEquals('3', $o['InboundShipmentItems.member.1.QuantityShipped']);
$this->assertEquals('TeeballBall3251', $o['InboundShipmentItems.member.2.SellerSKU']);
$this->assertEquals('5', $o['InboundShipmentItems.member.2.QuantityShipped']);
resetLog();
$this->assertFalse($this->object->usePlan(null));
$check = parseLog();
$this->assertEquals('usePlan requires an array', $check[0]);
return $this->object;
}
/**
* @depends testUsePlan
*/
public function testCreateShipment($o)
{
resetLog();
$this->object = new AmazonShipment('testStore', true, null, __DIR__ . '/../test-config.php');
$this->assertFalse($this->object->createShipment()); //no ID set
$this->object->setShipmentId('55');
$this->assertFalse($this->object->createShipment()); //no header set
$a = array();
$a['Name'] = 'Name';
$a['AddressLine1'] = 'AddressLine1';
$a['City'] = 'City';
$a['StateOrProvinceCode'] = 'StateOrProvinceCode';
$a['CountryCode'] = 'CountryCode';
$a['PostalCode'] = 'PostalCode';
$this->object->setAddress($a);
$this->assertFalse($this->object->createShipment()); //no items yet
$o->setMock(true, 'createShipment.xml');
$this->assertTrue($o->createShipment()); //this one is good
$op = $o->getOptions();
$this->assertEquals('CreateInboundShipment', $op['Action']);
$check = parseLog();
$this->assertEquals('Shipment ID must be set in order to create it', $check[1]);
$this->assertEquals('Header must be set in order to make a shipment', $check[2]);
$this->assertEquals('Items must be set in order to make a shipment', $check[3]);
$this->assertEquals('Single Mock File set: createShipment.xml', $check[5]);
$this->assertEquals('Fetched Mock File: mock/createShipment.xml', $check[6]);
$this->assertEquals('Successfully created Shipment #FBA63JX44', $check[7]);
return $o;
}
/**
* @depends testCreateShipment
*/
public function testGetShipmentId($o)
{
$get = $o->getShipmentId();
$this->assertEquals('FBA63JX44', $get);
$this->assertFalse($this->object->getShipmentId()); //not fetched yet for this object
}
/**
* @depends testUsePlan
*/
public function testUpdateShipment($o)
{
resetLog();
$this->object = new AmazonShipment('testStore', true, null, __DIR__ . '/../test-config.php');
$this->assertFalse($this->object->updateShipment()); //no ID set
$this->object->setShipmentId('55');
$this->assertFalse($this->object->updateShipment()); //no header set
$a = array();
$a['Name'] = 'Name';
$a['AddressLine1'] = 'AddressLine1';
$a['City'] = 'City';
$a['StateOrProvinceCode'] = 'StateOrProvinceCode';
$a['CountryCode'] = 'CountryCode';
$a['PostalCode'] = 'PostalCode';
$this->object->setAddress($a);
$this->assertFalse($this->object->updateShipment()); //no items yet
$o->setMock(true, 'updateShipment.xml');
$this->assertTrue($o->updateShipment()); //this one is good
$op = $o->getOptions();
$this->assertEquals('UpdateInboundShipment', $op['Action']);
$check = parseLog();
$this->assertEquals('Shipment ID must be set in order to update it', $check[1]);
$this->assertEquals('Header must be set in order to update a shipment', $check[2]);
$this->assertEquals('Items must be set in order to update a shipment', $check[3]);
$this->assertEquals('Single Mock File set: updateShipment.xml', $check[5]);
$this->assertEquals('Fetched Mock File: mock/updateShipment.xml', $check[6]);
$this->assertEquals('Successfully updated Shipment #FBA63J76R', $check[7]);
}
}
require_once(__DIR__ . '/../helperFunctions.php'); | apache-2.0 |
Minato262/Design-Pattern | src/java/test/org/designpattern/core/factories/TestAbstractProductionManageFactory.java | 1239 | /*
* Copyright 2016-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.designpattern.core.factories;
import org.junit.Test;
/**
* {@link AbstractProductionManageFactory} 的测试类
*
* @author kay
* @version 1.0
*/
public class TestAbstractProductionManageFactory extends AbstractProductionManageFactory {
@Override
public <T> T getProduction() {
return null;
}
@Override
public <T> T create() {
return null;
}
@Test
public void test(){
System.out.println(this.FACTORY_CLASSNAME);
}
@Test
public void testAbstractCreate(){
System.out.println(this.create(this.FACTORY_CLASSNAME));
}
}
| apache-2.0 |
gastaldi/hibernate-validator | hibernate-validator/src/test/java/org/hibernate/validator/test/constraints/composition/CompositeConstraintTest.java | 3353 | /*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual 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.hibernate.validator.test.constraints.composition;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.testng.annotations.Test;
import org.hibernate.validator.testutil.ValidatorUtil;
import static org.hibernate.validator.testutil.ConstraintViolationAssert.assertCorrectConstraintTypes;
import static org.hibernate.validator.testutil.ConstraintViolationAssert.assertCorrectConstraintViolationMessages;
import static org.hibernate.validator.testutil.ConstraintViolationAssert.assertNumberOfViolations;
/**
* @author Gerhard Petracek
* @author Hardy Ferentschik
*/
public class CompositeConstraintTest {
/**
* HV-182
*/
@Test
public void testCorrectAnnotationTypeForWithReportAsSingleViolation() {
Validator currentValidator = ValidatorUtil.getValidator();
for ( int i = 0; i < 100; i++ ) {
Set<ConstraintViolation<Person>> constraintViolations = currentValidator.validate(
new Person(
null, "Gerhard"
)
);
assertNumberOfViolations( constraintViolations, 1 );
assertCorrectConstraintTypes( constraintViolations, ValidNameSingleViolation.class );
assertCorrectConstraintViolationMessages( constraintViolations, "invalid name" );
constraintViolations = currentValidator.validate(
new Person(
"G", "Gerhard"
)
);
assertNumberOfViolations( constraintViolations, 1 );
assertCorrectConstraintTypes( constraintViolations, ValidNameSingleViolation.class );
assertCorrectConstraintViolationMessages( constraintViolations, "invalid name" );
}
}
/**
* HV-182
*/
@Test
public void testCorrectAnnotationTypeReportMultipleViolations() {
Validator currentValidator = ValidatorUtil.getValidator();
for ( int i = 0; i < 100; i++ ) {
Set<ConstraintViolation<Person>> constraintViolations = currentValidator.validate(
new Person(
"Gerd", null
)
);
assertNumberOfViolations( constraintViolations, 1 );
assertCorrectConstraintTypes( constraintViolations, NotNull.class );
assertCorrectConstraintViolationMessages( constraintViolations, "may not be null" );
constraintViolations = currentValidator.validate(
new Person(
"Gerd", "G"
)
);
assertNumberOfViolations( constraintViolations, 1 );
assertCorrectConstraintTypes( constraintViolations, Size.class );
assertCorrectConstraintViolationMessages( constraintViolations, "size must be between 2 and 10" );
}
}
}
| apache-2.0 |
google-research/falken | sdk/cpp/src/core/client_info.cc | 5492 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "src/core/client_info.h"
#include <utility>
#include "src/core/macros.h"
#if !defined(FALKEN_SDK_VERSION)
#define FALKEN_SDK_VERSION 0.0.0
#endif // !defined(FALKEN_SDK_VERSION)
#if !defined(FALKEN_SDK_CHANGELIST)
#define FALKEN_SDK_CHANGELIST 0
#endif // !defined(FALKEN_SDK_CHANGELIST)
#if !defined(FALKEN_SDK_COMMIT)
#define FALKEN_SDK_COMMIT 0
#endif // !defined(FALKEN_SDK_COMMIT)
#define FALKEN_SDK_VERSION_STRING FALKEN_EXPAND_STRINGIFY(FALKEN_SDK_VERSION)
#define FALKEN_SDK_CHANGELIST_STRING \
FALKEN_EXPAND_STRINGIFY(FALKEN_SDK_CHANGELIST)
#define FALKEN_SDK_COMMIT_STRING FALKEN_EXPAND_STRINGIFY(FALKEN_SDK_COMMIT)
namespace {
// clang-format=off
#if defined(NDEBUG)
static const char kBuildType[] = "release";
#else
static const char kBuildType[] = "debug";
#endif // defined(NDEBUG)
// Detect operating system and architecture.
#if defined(_MSC_VER) // MSVC.
const char kOperatingSystem[] = "windows";
#if defined(_DLL) && _DLL == 1
const char kCppRuntimeOrStl[] = "MD";
#else
const char kCppRuntimeOrStl[] = "MT";
#endif // defined(_MT) && _MT == 1
#if ((defined(_M_X64) && _M_X64 == 100) || \
(defined(_M_AMD64) && _M_AMD64 == 100))
const char kCpuArchitecture[] = "x86_64";
#elif defined(_M_IX86) && _M_IX86 == 600
const char kCpuArchitecture[] = "x86";
#elif defined(_M_ARM64) && _M_ARM64 == 1
const char kCpuArchitecture[] = "arm64";
#elif defined(_M_ARM) && _M_ARM == 7
const char kCpuArchitecture[] = "arm32";
#else
#error Unknown Windows architecture.
#endif // Architecture
#elif defined(__APPLE__)
#include <TargetConditionals.h> // NOLINT
const char kCppRuntimeOrStl[] = "libcpp";
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
const char kOperatingSystem[] = "ios";
#elif TARGET_OS_MAC
const char kOperatingSystem[] = "darwin";
#else
#error Unknown Apple operating system.
#endif // OS
#if __i386__
const char kCpuArchitecture[] = "x86";
#elif __amd64__
const char kCpuArchitecture[] = "x86_64";
#elif __aarch64__
const char kCpuArchitecture[] = "arm64";
#elif __arm__
const char kCpuArchitecture[] = "arm32";
#else
#error Unknown Apple architecture.
#endif // Architecture
#elif defined(__ANDROID__)
const char* kOperatingSystem = "android";
#if __i386__
const char kCpuArchitecture[] = "x86";
#elif __amd64__
const char kCpuArchitecture[] = "x86_64";
#elif __aarch64__
const char kCpuArchitecture[] = "arm64";
#elif __ARM_EABI__ || __arm__
const char kCpuArchitecture[] = "armeabi-v7a";
#elif __mips__ || __mips
#if __mips__ == 32 || __mips == 32
const char kCpuArchitecture[] = "mips";
#elif __mips__ == 64 || __mips == 64
const char kCpuArchitecture[] = "mips64";
#else
#error Unknown MIPS version. __mips__
#endif // __mips__
#else
#error Unknown Android architecture.
#endif // Architecture
#if defined(_STLPORT_VERSION)
const char kCppRuntimeOrStl[] = "stlport";
#elif defined(_GLIBCXX_UTILITY)
const char kCppRuntimeOrStl[] = "gnustl";
#elif defined(_LIBCPP_STD_VER)
const char kCppRuntimeOrStl[] = "libcpp";
#else
#error Unknown Android STL.
#endif // STL
#elif defined(__linux__) || defined(__ggp__) // Linux variants.
#if defined(__ggp__)
const char kOperatingSystem[] = "stadia";
#else
const char kOperatingSystem[] = "linux";
#endif // defined(__ggp__)
#if defined(_GLIBCXX_UTILITY)
const char kCppRuntimeOrStl[] = "gnustl";
#elif defined(_LIBCPP_STD_VER)
const char kCppRuntimeOrStl[] = "libcpp";
#else
#error Unknown STL.
#endif // STL
#if __amd64__
const char kCpuArchitecture[] = "x86_64";
#elif __i386__
const char kCpuArchitecture[] = "x86";
#else
#error Unknown Linux architecture.
#endif // Architecture
#else
#error Unknown operating system.
#endif // Operating system
// clang-format=on
} // namespace
namespace falken {
std::string GetVersionInformation() {
static const char kFalkenSdkVersionString[] =
"Version " FALKEN_SDK_VERSION_STRING " (CL: " FALKEN_SDK_CHANGELIST_STRING
", Commit: " FALKEN_SDK_COMMIT_STRING
#if !defined(NDEBUG)
", Debug"
#endif // !defined(NDEBUG)
")";
return std::string(kFalkenSdkVersionString);
}
std::string GetUserAgent() {
static const char kFalkenUserAgentPrefix[] = "falken-";
std::string user_agent;
auto append_to_user_agent = [&user_agent](const char* key,
const char* value) {
if (!user_agent.empty()) user_agent += " ";
user_agent += kFalkenUserAgentPrefix;
user_agent += key;
user_agent += "/";
user_agent += value;
};
append_to_user_agent("cpp", FALKEN_SDK_VERSION_STRING);
append_to_user_agent("cpp-commit", FALKEN_SDK_COMMIT_STRING);
append_to_user_agent("cpp-cl", FALKEN_SDK_CHANGELIST_STRING);
append_to_user_agent("cpp-build", kBuildType);
append_to_user_agent("cpp-runtime", kCppRuntimeOrStl);
append_to_user_agent("os", kOperatingSystem);
append_to_user_agent("cpu", kCpuArchitecture);
return user_agent;
}
} // namespace falken
| apache-2.0 |
ToQuery/CleverWeb | src/main/webapp/app/api/system/role.js | 1223 | import request from '@/utils/request'
const biz_path = '/sys/role/'
function query(queryParam, page = undefined) {
const query = Object.assign({}, queryParam) // copy obj
if (page) {
Object.assign(query, page)
}
return request({
url: biz_path,
method: 'get',
params: query
})
}
function list(queryParam) {
const query = Object.assign({}, queryParam) // copy obj
return request({
url: biz_path + 'list',
method: 'get',
params: query
})
}
function get(id) {
return request({
url: biz_path + id,
method: 'get'
})
}
function save(data) {
return request({
url: biz_path,
method: 'post',
data: data
})
}
function update(data, rootPwd = '') {
return request({
url: biz_path,
method: 'put',
data: data,
params: { rootPwd: rootPwd }
})
}
function saveOrUpdate(data, rootPwd = '') {
if (data.id !== undefined && data.id !== null && data.id !== '') {
return update(data, rootPwd)
} else {
return save(data)
}
}
function deleteById(id) {
return request({
url: biz_path,
method: 'delete',
params: { ids: id }
})
}
export default {
query,
list,
get,
save,
update,
saveOrUpdate,
deleteById
}
| apache-2.0 |
dmilos/color | example/less-than-1k/assign/lms/lms2YPbPr2020.cpp | 784 | #include <iostream>
#include <iomanip>
#include "color/color.hpp"
int main( int argc, char *argv[] )
{
::color::lms< float > c0; //!< Instead of float you may put std::uint8_t,std::uint16_t, std::uint32_t, std::uint64_t, double, long double
::color::YPbPr< std::uint8_t, ::color::constant::YPbPr::BT_2020_entity > c1; //!< Instead of std::uint8_t you may put std::uint16_t, std::uint32_t, std::uint64_t, float, double, long double
c0 = ::color::constant::lavender_t{};
c1 = ::color::constant::orange_t{};
// Assign
c0 = c1;
std::cout << c0[0] << ", " << c0[1] << ", " << c0[2] << std::endl;
// .. and vice versa
c1 = c0;
std::cout << c1[0] << ", " << c1[1] << ", " << c1[2] << std::endl;
return EXIT_SUCCESS;
}
| apache-2.0 |
Epi-Info/Epi-Info-Cloud-Contact-Tracing | Cloud Enter/Epi.Compatibility/Epi.Core/CommandProcessorResults.cs | 4994 | using System.Collections;
using System.Collections.ObjectModel;
using System.Data;
using System.Xml;
using System.Collections.Generic;
namespace Epi
{
/// <summary>
/// Process Command Results event handler delegate.
/// </summary>
/// <param name="results">Command Processor Results</param>
public delegate void ProcessCommandResultsHandler(CommandProcessorResults results);
/// <summary>
/// Command Processor Results class
/// </summary>
public class CommandProcessorResults
{
#region Private Attributes
private ArrayList actions = new ArrayList();
private bool resetOutput = false;
private string htmlOutput = string.Empty;
private XmlDocument xmlOutput = null;
private DataSet dsOutput = null;
private string fileNameOutput;
private string outTableName;
private ArrayList commandBlock = new ArrayList();
private Dictionary<Epi.Action, Collection<string>> checkCodeList;
#endregion Private Attributes
#region Constructors
/// <summary>
/// command processor results
/// </summary>
public CommandProcessorResults()
{
}
#endregion Constructors
#region Public Methods
/// <summary>
/// Reset Command Processor
/// </summary>
public void Clear()
{
if (dsOutput != null) // DEFECT: 200
{
dsOutput.Dispose();
}
else
{
dsOutput = null;
}
htmlOutput = string.Empty;
xmlOutput = null;
actions.Clear();
}
#endregion Public Methods
#region Public Properties
/// <summary>
/// List of actions to perform after the command has executed.
/// </summary>
public ArrayList Actions
{
get
{
return actions;
}
}
/// <summary>
/// Indicates if the output stream should be reset before adding results.
/// </summary>
public bool ResetOutput
{
get
{
return this.resetOutput;
}
set
{
resetOutput = value;
}
}
/// <summary>
/// Gets/sets the <see cref="System.Data.DataSet"/> output for command processor
/// </summary>
public DataSet DsOutput
{
get
{
if (this.dsOutput == null)
{
this.dsOutput = new DataSet();
}
return this.dsOutput;
}
set
{
this.dsOutput = value;
}
}
/// <summary>
/// Gets/sets the HTML output for command processor
/// </summary>
public string HtmlOutput
{
get
{
return this.htmlOutput;
}
set
{
this.htmlOutput = value;
}
}
/// <summary>
/// Gets/sets the Xml output for command processor
/// </summary>
public XmlDocument XmlOutput
{
get
{
return this.xmlOutput;
}
set
{
this.xmlOutput = value;
}
}
/// <summary>
/// Gets/sets the name of a file for command processor
/// </summary>
public string FileNameOutput
{
get { return fileNameOutput; }
set { fileNameOutput = value; }
}
/// <summary>
/// Gets/sets the name of a file for command processor
/// </summary>
public string OutTableName
{
get { return outTableName; }
set { outTableName = value; }
}
/// <summary>
/// Gets/sets the Menu command block for command processor
/// </summary>
public ArrayList MenuCommandBlock
{
get
{
return this.commandBlock;
}
set
{
this.commandBlock = value;
}
}
/// <summary>
/// Gets/sets the list which houses items in which check code actions will be executed upon
/// </summary>
//public ArrayList CheckCodeList
public Dictionary<Epi.Action, Collection<string>> CheckCodeList
{
get
{
if (this.checkCodeList == null)
{
checkCodeList = new Dictionary<Epi.Action, Collection<string>>();
}
return this.checkCodeList;
}
set
{
this.checkCodeList = value;
}
}
#endregion Public Properties
}
} | apache-2.0 |
itachi1706/DroidEggs | app/src/main/java/com/itachi1706/droideggs/PieEgg/EasterEgg/paint/PaintActivity.java | 13221 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.itachi1706.droideggs.PieEgg.EasterEgg.paint;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.OvershootInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Magnifier;
import com.itachi1706.droideggs.R;
import java.util.Arrays;
import java.util.stream.IntStream;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import static android.view.MotionEvent.ACTION_CANCEL;
import static android.view.MotionEvent.ACTION_DOWN;
import static android.view.MotionEvent.ACTION_MOVE;
import static android.view.MotionEvent.ACTION_UP;
@RequiresApi(24)
public class PaintActivity extends Activity {
private static final float MAX_BRUSH_WIDTH_DP = 100f;
private static final float MIN_BRUSH_WIDTH_DP = 1f;
private static final int NUM_BRUSHES = 6;
private static final int NUM_COLORS = 6;
private Painting painting = null;
private CutoutAvoidingToolbar toolbar = null;
private LinearLayout brushes = null;
private LinearLayout colors = null;
private Magnifier magnifier = null;
private boolean sampling = false;
private View.OnClickListener buttonHandler = view -> {
switch (view.getId()) {
case R.id.btnBrush:
view.setSelected(true);
hideToolbar(colors);
toggleToolbar(brushes);
break;
case R.id.btnColor:
view.setSelected(true);
hideToolbar(brushes);
toggleToolbar(colors);
break;
case R.id.btnClear:
painting.clear();
break;
case R.id.btnSample:
sampling = true;
view.setSelected(true);
break;
case R.id.btnZen:
painting.setZenMode(!painting.getZenMode());
view.animate()
.setStartDelay(200)
.setInterpolator(new OvershootInterpolator())
.rotation(painting.getZenMode() ? 0f : 90f);
break;
}
};
private void showToolbar(View bar) {
if (bar.getVisibility() != View.GONE) return;
bar.setVisibility(View.VISIBLE);
bar.setTranslationY(toolbar.getHeight()/2);
bar.animate()
.translationY(toolbar.getHeight())
.alpha(1f)
.setDuration(220)
.start();
}
private void hideToolbar(View bar) {
if (bar.getVisibility() != View.VISIBLE) return;
bar.animate()
.translationY(toolbar.getHeight()/2)
.alpha(0f)
.setDuration(150)
.withEndAction(() -> bar.setVisibility(View.GONE))
.start();
}
private void toggleToolbar(View bar) {
if (bar.getVisibility() == View.VISIBLE) {
hideToolbar(bar);
} else {
showToolbar(bar);
}
}
private BrushPropertyDrawable widthButtonDrawable;
private BrushPropertyDrawable colorButtonDrawable;
private float maxBrushWidth, minBrushWidth;
private int nightMode = Configuration.UI_MODE_NIGHT_UNDEFINED;
static final float lerp(float f, float a, float b) {
return a + (b-a) * f;
}
@SuppressLint("ClickableViewAccessibility")
void setupViews(Painting oldPainting) {
setContentView(R.layout.pie_activity_paint);
painting = oldPainting != null ? oldPainting : new Painting(this);
((FrameLayout) findViewById(R.id.contentView)).addView(painting,
new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
painting.setPaperColor(ContextCompat.getColor(getApplicationContext(), R.color.paper_color));
painting.setPaintColor(ContextCompat.getColor(getApplicationContext(),R.color.paint_color));
toolbar = findViewById(R.id.toolbar);
brushes = findViewById(R.id.brushes);
colors = findViewById(R.id.colors);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) magnifier = new Magnifier(painting);
painting.setOnTouchListener(
(view, event) -> {
switch (event.getActionMasked()) {
case ACTION_DOWN:
case ACTION_MOVE:
if (sampling) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) magnifier.show(event.getX(), event.getY());
colorButtonDrawable.setWellColor(
painting.sampleAt(event.getX(), event.getY()));
return true;
}
break;
case ACTION_CANCEL:
if (sampling) {
findViewById(R.id.btnSample).setSelected(false);
sampling = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) magnifier.dismiss();
}
break;
case ACTION_UP:
if (sampling) {
findViewById(R.id.btnSample).setSelected(false);
sampling = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) magnifier.dismiss();
painting.setPaintColor(
painting.sampleAt(event.getX(), event.getY()));
refreshBrushAndColor();
}
break;
}
return false; // allow view to continue handling
});
findViewById(R.id.btnBrush).setOnClickListener(buttonHandler);
findViewById(R.id.btnColor).setOnClickListener(buttonHandler);
findViewById(R.id.btnClear).setOnClickListener(buttonHandler);
findViewById(R.id.btnSample).setOnClickListener(buttonHandler);
findViewById(R.id.btnZen).setOnClickListener(buttonHandler);
findViewById(R.id.btnColor).setOnLongClickListener(view -> {
colors.removeAllViews();
showToolbar(colors);
refreshBrushAndColor();
return true;
});
findViewById(R.id.btnClear).setOnLongClickListener(view -> {
painting.invertContents();
return true;
});
widthButtonDrawable = new BrushPropertyDrawable(this);
widthButtonDrawable.setFrameColor(ContextCompat.getColor(getApplicationContext(),R.color.toolbar_icon_color));
colorButtonDrawable = new BrushPropertyDrawable(this);
colorButtonDrawable.setFrameColor(ContextCompat.getColor(getApplicationContext(),R.color.toolbar_icon_color));
((ImageButton) findViewById(R.id.btnBrush)).setImageDrawable(widthButtonDrawable);
((ImageButton) findViewById(R.id.btnColor)).setImageDrawable(colorButtonDrawable);
refreshBrushAndColor();
}
private void refreshBrushAndColor() {
final LinearLayout.LayoutParams button_lp = new LinearLayout.LayoutParams(
0, ViewGroup.LayoutParams.WRAP_CONTENT);
button_lp.weight = 1f;
if (brushes.getChildCount() == 0) {
for (int i = 0; i < NUM_BRUSHES; i++) {
final BrushPropertyDrawable icon = new BrushPropertyDrawable(this);
icon.setFrameColor(ContextCompat.getColor(getApplicationContext(),R.color.toolbar_icon_color));
// exponentially increasing brush size
final float width = lerp(
(float) Math.pow((float) i / NUM_BRUSHES, 2f), minBrushWidth,
maxBrushWidth);
icon.setWellScale(width / maxBrushWidth);
icon.setWellColor(ContextCompat.getColor(getApplicationContext(),R.color.toolbar_icon_color));
final ImageButton button = new ImageButton(this);
button.setImageDrawable(icon);
button.setBackground(getDrawable(R.drawable.pie_toolbar_button_bg));
button.setOnClickListener(
view -> {
brushes.setSelected(false);
hideToolbar(brushes);
painting.setBrushWidth(width);
refreshBrushAndColor();
});
brushes.addView(button, button_lp);
}
}
if (colors.getChildCount() == 0) {
final Palette pal = new Palette(NUM_COLORS);
for (final int c : IntStream.concat(
IntStream.of(Color.BLACK, Color.WHITE),
Arrays.stream(pal.getColors(), 0, pal.getColors().length)
).toArray()) {
final BrushPropertyDrawable icon = new BrushPropertyDrawable(this);
icon.setFrameColor(ContextCompat.getColor(getApplicationContext(),R.color.toolbar_icon_color));
icon.setWellColor(c);
final ImageButton button = new ImageButton(this);
button.setImageDrawable(icon);
button.setBackground(getDrawable(R.drawable.pie_toolbar_button_bg));
button.setOnClickListener(
view -> {
colors.setSelected(false);
hideToolbar(colors);
painting.setPaintColor(c);
refreshBrushAndColor();
});
colors.addView(button, button_lp);
}
}
widthButtonDrawable.setWellScale(painting.getBrushWidth() / maxBrushWidth);
widthButtonDrawable.setWellColor(painting.getPaintColor());
colorButtonDrawable.setWellColor(painting.getPaintColor());
}
private void refreshNightMode(Configuration config) {
int newNightMode =
(config.uiMode & Configuration.UI_MODE_NIGHT_MASK);
if (nightMode != newNightMode) {
if (nightMode != Configuration.UI_MODE_NIGHT_UNDEFINED) {
painting.invertContents();
((ViewGroup) painting.getParent()).removeView(painting);
setupViews(painting);
final View decorView = getWindow().getDecorView();
int decorSUIV = decorView.getSystemUiVisibility();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
if (newNightMode == Configuration.UI_MODE_NIGHT_YES) {
decorView.setSystemUiVisibility(
decorSUIV & ~View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
} else {
decorView.setSystemUiVisibility(
decorSUIV | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
}
nightMode = newNightMode;
}
}
public PaintActivity() {
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
painting.onTrimMemory();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
refreshNightMode(newConfig);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.flags = lp.flags
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
getWindow().setAttributes(lp);
maxBrushWidth = MAX_BRUSH_WIDTH_DP * getResources().getDisplayMetrics().density;
minBrushWidth = MIN_BRUSH_WIDTH_DP * getResources().getDisplayMetrics().density;
setupViews(null);
refreshNightMode(getResources().getConfiguration());
}
@Override
public void onPostResume() {
super.onPostResume();
}
} | apache-2.0 |
google/nomulus | core/src/main/java/google/registry/model/JsonMapBuilder.java | 2836 | // Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.model;
import static com.google.common.collect.ImmutableList.toImmutableList;
import com.google.common.collect.Streams;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.annotation.Nullable;
/**
* Helper class for {@link Jsonifiable} classes to generate JSON maps for RPC responses.
*
* <p>The returned map is mutable. Map entries can be {@code null} but list entries can not. If a
* list is passed as {@code null}, it'll be substituted with empty list. Lists are not mutable.
*/
public final class JsonMapBuilder {
private final Map<String, Object> map = new LinkedHashMap<>();
public JsonMapBuilder put(String name, @Nullable Boolean value) {
map.put(name, value);
return this;
}
public JsonMapBuilder put(String name, @Nullable Number value) {
map.put(name, value);
return this;
}
public JsonMapBuilder put(String name, @Nullable String value) {
map.put(name, value);
return this;
}
public JsonMapBuilder put(String name, @Nullable Jsonifiable value) {
map.put(name, value == null ? null : value.toJsonMap());
return this;
}
public JsonMapBuilder put(String name, @Nullable Enum<?> value) {
map.put(name, value == null ? null : value.name());
return this;
}
public <T> JsonMapBuilder putString(String name, @Nullable T value) {
map.put(name, value == null ? null : value.toString());
return this;
}
public <T> JsonMapBuilder putListOfStrings(String name, @Nullable Iterable<T> value) {
map.put(
name,
value == null
? Collections.EMPTY_LIST
: Streams.stream(value).map(Object::toString).collect(toImmutableList()));
return this;
}
public JsonMapBuilder putListOfJsonObjects(
String name, @Nullable Iterable<? extends Jsonifiable> value) {
map.put(
name,
value == null
? Collections.EMPTY_LIST
: Streams.stream(value).map(Jsonifiable::toJsonMap).collect(toImmutableList()));
return this;
}
/** Returns mutable JSON object. Please dispose of the builder object after calling me. */
public Map<String, Object> build() {
return map;
}
}
| apache-2.0 |
stepanovdg/big-data-plugin | impl/shim/oozie/src/main/java/org/pentaho/big/data/impl/shim/oozie/OozieServiceImpl.java | 2764 | /*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2002-2016 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.big.data.impl.shim.oozie;
import org.pentaho.bigdata.api.oozie.OozieServiceException;
import org.pentaho.bigdata.api.oozie.OozieJobInfo;
import org.pentaho.bigdata.api.oozie.OozieService;
import org.pentaho.oozie.shim.api.OozieClient;
import org.pentaho.oozie.shim.api.OozieClientException;
import org.pentaho.oozie.shim.api.OozieJob;
import static org.apache.oozie.client.OozieClient.APP_PATH;
import static org.apache.oozie.client.OozieClient.COORDINATOR_APP_PATH;
import static org.apache.oozie.client.OozieClient.BUNDLE_APP_PATH;
import java.util.Properties;
public class OozieServiceImpl implements OozieService {
private final OozieClient delegate;
public OozieServiceImpl( OozieClient oozieClient ) {
this.delegate = oozieClient;
}
@Override
public String getClientBuildVersion() {
return delegate.getClientBuildVersion();
}
@Override
public String getProtocolUrl() throws OozieServiceException {
try {
return delegate.getProtocolUrl();
} catch ( OozieClientException e ) {
throw new OozieServiceException( e, e.getErrorCode() );
}
}
@Override
public boolean hasAppPath( Properties props ) {
return props.containsKey( APP_PATH )
|| props.containsKey( COORDINATOR_APP_PATH )
|| props.containsKey( BUNDLE_APP_PATH );
}
@Override
public OozieJobInfo run( Properties props ) throws OozieServiceException {
try {
OozieJob job = delegate.run( props );
return new OozieJobInfoDelegate( job );
} catch ( OozieClientException e ) {
throw new OozieServiceException( e, e.getErrorCode() );
}
}
@Override
public void validateWSVersion() throws OozieServiceException {
try {
delegate.validateWSVersion();
} catch ( OozieClientException e ) {
throw new OozieServiceException( e, e.getErrorCode() );
}
}
}
| apache-2.0 |
aliascc/Arenal-Engine | CodeSolution/Code/AEngine_Scripting/AngelScript/Add-ons/AngelScriptAddOn.cpp | 1242 | /*
* Copyright (c) 2018 <Carlos Chacón>
* 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.
*/
/*************************
* Precompiled Header *
**************************/
#include "precomp_scripting.h"
/**********************
* System Includes *
***********************/
/*************************
* 3rd Party Includes *
**************************/
/***************************
* Game Engine Includes *
****************************/
#include "AngelScriptAddOn.h"
//Always include last
#include "Memory\MemLeaks.h"
/********************
* Function Defs *
*********************/
AngelScriptAddOn::AngelScriptAddOn(uint32_t addOnID)
: m_AddOnID(addOnID)
{
}
AngelScriptAddOn::~AngelScriptAddOn()
{
}
| apache-2.0 |
leppa/home-assistant | tests/helpers/test_temperature.py | 1096 | """Tests Home Assistant temperature helpers."""
import pytest
from homeassistant.const import (
PRECISION_HALVES,
PRECISION_TENTHS,
PRECISION_WHOLE,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
from homeassistant.helpers.temperature import display_temp
TEMP = 24.636626
def test_temperature_not_a_number(hass):
"""Test that temperature is a number."""
temp = "Temperature"
with pytest.raises(Exception) as exception:
display_temp(hass, temp, TEMP_CELSIUS, PRECISION_HALVES)
assert "Temperature is not a number: {}".format(temp) in str(exception.value)
def test_celsius_halves(hass):
"""Test temperature to celsius rounding to halves."""
assert display_temp(hass, TEMP, TEMP_CELSIUS, PRECISION_HALVES) == 24.5
def test_celsius_tenths(hass):
"""Test temperature to celsius rounding to tenths."""
assert display_temp(hass, TEMP, TEMP_CELSIUS, PRECISION_TENTHS) == 24.6
def test_fahrenheit_wholes(hass):
"""Test temperature to fahrenheit rounding to wholes."""
assert display_temp(hass, TEMP, TEMP_FAHRENHEIT, PRECISION_WHOLE) == -4
| apache-2.0 |
Sofia2/dotnet-api | Indra.Sofia2.SSAP.SSAP/SSAPQueryResultFormat.cs | 235 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Indra.Sofia2.SSAP.SSAP
{
public enum SSAPQueryResultFormat
{
JSON,
TABLE
}
}
| apache-2.0 |
googleapis/java-aiplatform | proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/ListTensorboardExperimentsRequestOrBuilder.java | 5095 | /*
* 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/aiplatform/v1/tensorboard_service.proto
package com.google.cloud.aiplatform.v1;
public interface ListTensorboardExperimentsRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.aiplatform.v1.ListTensorboardExperimentsRequest)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Required. The resource name of the Tensorboard to list TensorboardExperiments.
* Format:
* 'projects/{project}/locations/{location}/tensorboards/{tensorboard}'
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
java.lang.String getParent();
/**
*
*
* <pre>
* Required. The resource name of the Tensorboard to list TensorboardExperiments.
* Format:
* 'projects/{project}/locations/{location}/tensorboards/{tensorboard}'
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
com.google.protobuf.ByteString getParentBytes();
/**
*
*
* <pre>
* Lists the TensorboardExperiments that match the filter expression.
* </pre>
*
* <code>string filter = 2;</code>
*
* @return The filter.
*/
java.lang.String getFilter();
/**
*
*
* <pre>
* Lists the TensorboardExperiments that match the filter expression.
* </pre>
*
* <code>string filter = 2;</code>
*
* @return The bytes for filter.
*/
com.google.protobuf.ByteString getFilterBytes();
/**
*
*
* <pre>
* The maximum number of TensorboardExperiments to return. The service may
* return fewer than this value. If unspecified, at most 50
* TensorboardExperiments will be returned. The maximum value is 1000; values
* above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 3;</code>
*
* @return The pageSize.
*/
int getPageSize();
/**
*
*
* <pre>
* A page token, received from a previous
* [TensorboardService.ListTensorboardExperiments][google.cloud.aiplatform.v1.TensorboardService.ListTensorboardExperiments] call.
* Provide this to retrieve the subsequent page.
* When paginating, all other parameters provided to
* [TensorboardService.ListTensorboardExperiments][google.cloud.aiplatform.v1.TensorboardService.ListTensorboardExperiments] must
* match the call that provided the page token.
* </pre>
*
* <code>string page_token = 4;</code>
*
* @return The pageToken.
*/
java.lang.String getPageToken();
/**
*
*
* <pre>
* A page token, received from a previous
* [TensorboardService.ListTensorboardExperiments][google.cloud.aiplatform.v1.TensorboardService.ListTensorboardExperiments] call.
* Provide this to retrieve the subsequent page.
* When paginating, all other parameters provided to
* [TensorboardService.ListTensorboardExperiments][google.cloud.aiplatform.v1.TensorboardService.ListTensorboardExperiments] must
* match the call that provided the page token.
* </pre>
*
* <code>string page_token = 4;</code>
*
* @return The bytes for pageToken.
*/
com.google.protobuf.ByteString getPageTokenBytes();
/**
*
*
* <pre>
* Field to use to sort the list.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
java.lang.String getOrderBy();
/**
*
*
* <pre>
* Field to use to sort the list.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
com.google.protobuf.ByteString getOrderByBytes();
/**
*
*
* <pre>
* Mask specifying which fields to read.
* </pre>
*
* <code>.google.protobuf.FieldMask read_mask = 6;</code>
*
* @return Whether the readMask field is set.
*/
boolean hasReadMask();
/**
*
*
* <pre>
* Mask specifying which fields to read.
* </pre>
*
* <code>.google.protobuf.FieldMask read_mask = 6;</code>
*
* @return The readMask.
*/
com.google.protobuf.FieldMask getReadMask();
/**
*
*
* <pre>
* Mask specifying which fields to read.
* </pre>
*
* <code>.google.protobuf.FieldMask read_mask = 6;</code>
*/
com.google.protobuf.FieldMaskOrBuilder getReadMaskOrBuilder();
}
| apache-2.0 |
A11yance/axobject-query | src/etc/objects/SplitterRole.js | 229 | /**
* @flow
*/
const SplitterRole: AXObjectModelDefinition = {
relatedConcepts: [
{
module: 'ARIA',
concept: {
name: 'separator',
},
},
],
type: 'widget',
};
export default SplitterRole; | apache-2.0 |
googleapis/java-resourcemanager | proto-google-cloud-resourcemanager-v3/src/main/java/com/google/cloud/resourcemanager/v3/DeleteProjectMetadataOrBuilder.java | 969 | /*
* 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/projects.proto
package com.google.cloud.resourcemanager.v3;
public interface DeleteProjectMetadataOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.resourcemanager.v3.DeleteProjectMetadata)
com.google.protobuf.MessageOrBuilder {}
| apache-2.0 |
stmueller/yoda | PODA/src/main/java/com/erp/model/HtmlBO.java | 1100 | package com.erp.model;
public class HtmlBO {
//<a href="javascript:void(0)" onclick="loadBarcodeImg(${grnObj.grnNo})" class="tooltipLink" title="Print GRN Barcode">
// <span style="color:#333" class="glyphicon glyphicon-barcode"></span></a>*/
private String clickAction="";
private String cls="";
private String title="";
public String getClickAction() {
return clickAction;
}
public void setClickAction(String clickAction) {
this.clickAction = clickAction;
}
public String getCls() {
return cls;
}
public void setCls(String cls) {
this.cls = cls;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getServerUrl() {
return serverUrl;
}
public void setServerUrl(String serverUrl) {
this.serverUrl = serverUrl;
}
public String getGlyphicons() {
return glyphicons;
}
public void setGlyphicons(String glyphicons) {
this.glyphicons = glyphicons;
}
private String serverUrl="";
private String glyphicons="";
}
| apache-2.0 |
chirino/docker-maven-plugin | src/test/java/integration/DockerAccessIT.java | 6207 | package integration;
import java.io.File;
import java.io.IOException;
import java.util.*;
import com.google.common.collect.Lists;
import io.fabric8.maven.docker.AbstractDockerMojo;
import io.fabric8.maven.docker.access.*;
import io.fabric8.maven.docker.access.hc.DockerAccessWithHcClient;
import io.fabric8.maven.docker.config.Arguments;
import io.fabric8.maven.docker.config.DockerMachineConfiguration;
import io.fabric8.maven.docker.model.Container.PortBinding;
import io.fabric8.maven.docker.util.AnsiLogger;
import io.fabric8.maven.docker.util.Logger;
import org.apache.maven.plugin.logging.SystemStreamLog;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;
/*
* if run from your ide, this test assumes you have configured the runner w/ the appropriate env variables
*
* it also assumes that 'removeImage' does what it's supposed to do as it's used in test setup.
*/
@Ignore
public class DockerAccessIT {
private static final String CONTAINER_NAME = "integration-test";
private static final String IMAGE = "busybox:buildroot-2014.02";
private static final String IMAGE_TAG = "busybox:tagged";
private static final int PORT = 5677;
private String containerId;
private final DockerAccessWithHcClient dockerClient;
public DockerAccessIT() throws IOException {
AnsiLogger logger = new AnsiLogger(new SystemStreamLog(), true, true);
String url = createDockerConnectionDetector(logger).extractUrl(null);
this.dockerClient = createClient(url, logger);
}
private DockerConnectionDetector createDockerConnectionDetector(Logger logger) {
DockerMachineConfiguration machine = new DockerMachineConfiguration("default","false");
return new DockerConnectionDetector(
Collections.<DockerConnectionDetector.DockerHostProvider>singletonList(new DockerMachine(logger, machine)));
}
@Before
public void setup() throws DockerAccessException {
// yes - this is a big don't do for tests
testRemoveImage(IMAGE);
testRemoveImage(IMAGE_TAG);
}
@Test
@Ignore
public void testBuildImage() throws DockerAccessException {
File file = new File("src/test/resources/integration/busybox-test.tar");
dockerClient.buildImage(IMAGE_TAG, file, null, false, false, Collections.<String, String>emptyMap());
assertTrue(hasImage(IMAGE_TAG));
testRemoveImage(IMAGE_TAG);
}
@Test
public void testPullStartStopRemove() throws DockerAccessException, InterruptedException {
testDoesNotHave();
try {
testPullImage();
testTagImage();
testCreateContainer();
testStartContainer();
testExecContainer();
testQueryPortMapping();
testStopContainer();
Thread.sleep(2000);
testRemoveContainer();
} finally {
testRemoveImage(IMAGE);
}
}
private DockerAccessWithHcClient createClient(String baseUrl, Logger logger) {
try {
String certPath = createDockerConnectionDetector(logger).getCertPath(null);
return new DockerAccessWithHcClient("v" + AbstractDockerMojo.API_VERSION, baseUrl, certPath, 20, logger);
} catch (@SuppressWarnings("unused") IOException e) {
// not using ssl, so not going to happen
logger.error(e.getMessage());
throw new RuntimeException();
}
}
private void testCreateContainer() throws DockerAccessException {
PortMapping portMapping = new PortMapping(Arrays.asList(new String[] {PORT + ":" + PORT }), new Properties());
ContainerHostConfig hostConfig = new ContainerHostConfig().portBindings(portMapping);
ContainerCreateConfig createConfig = new ContainerCreateConfig(IMAGE).command(new Arguments("ping google.com")).hostConfig(hostConfig);
containerId = dockerClient.createContainer(createConfig, CONTAINER_NAME);
assertNotNull(containerId);
String name = dockerClient.inspectContainer(containerId).getName();
assertEquals(CONTAINER_NAME, name);
}
private void testDoesNotHave() throws DockerAccessException {
assertFalse(hasImage(IMAGE));
}
private void testPullImage() throws DockerAccessException {
dockerClient.pullImage(IMAGE, null, null);
assertTrue(hasImage(IMAGE));
}
private void testQueryPortMapping() throws DockerAccessException {
Map<String, PortBinding> portMap = dockerClient.inspectContainer(containerId).getPortBindings();
assertEquals(5677, portMap.values().iterator().next().getHostPort().intValue());
}
private void testRemoveContainer() throws DockerAccessException {
dockerClient.removeContainer(containerId, true);
}
private void testRemoveImage(String image) throws DockerAccessException {
dockerClient.removeImage(image, false);
assertFalse(hasImage(image));
}
private void testStartContainer() throws DockerAccessException {
dockerClient.startContainer(containerId);
assertTrue(dockerClient.inspectContainer(containerId).isRunning());
}
private void testExecContainer() throws DockerAccessException {
Arguments arguments = new Arguments();
arguments.setExec(Lists.newArrayList("echo", "test", "echo"));
String execContainerId = dockerClient.createExecContainer(this.containerId, arguments);
//assertThat(dockerClient.startExecContainer(execContainerId), is("test echo"));
}
private void testStopContainer() throws DockerAccessException {
dockerClient.stopContainer(containerId, 0);
assertFalse(dockerClient.inspectContainer(containerId).isRunning());
}
private void testTagImage() throws DockerAccessException {
dockerClient.tag(IMAGE, IMAGE_TAG,false);
assertTrue(hasImage(IMAGE_TAG));
dockerClient.removeImage(IMAGE_TAG, false);
assertFalse(hasImage(IMAGE_TAG));
}
private boolean hasImage(String image) throws DockerAccessException {
return dockerClient.hasImage(image);
}
}
| apache-2.0 |
lizhi5753186/PushSharp | Tests/PushSharp.Tests/GcmTests.cs | 10045 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using PushSharp.Android;
using PushSharp.Core;
using PushSharp.Tests.TestServers;
namespace PushSharp.Tests
{
public class GcmTests
{
private int testPort = 2000;
[Test]
public void GCM_All_ShouldSucceed()
{
TestNotifications(false, 10, 10, 0);
}
[Test]
public void GCM_All_ShouldFail()
{
var toFail = new int[10];
for (int i = 0; i < toFail.Length; i++)
toFail[i] = i;
TestNotifications(false, 10, 0, 10, toFail);
}
[Test]
public void GCM_First_ShouldFail()
{
TestNotifications(false, 10, 9, 1, new int[] { 0 });
}
[Test]
public void GCM_Last_ShouldFail()
{
TestNotifications(false, 10, 9, 1, new int[] { 9 });
}
[Test]
public void GCM_Middles_ShouldFail()
{
TestNotifications(false, 10, 8, 2, new int[] { 3, 6 });
}
[Test]
public void GCM_Single_ShouldFail()
{
TestNotifications(false, 1, 0, 1, new int[] { 0 });
}
[Test]
public void GCM_Single_ShouldSucceed()
{
TestNotifications(false, 1, 1, 0);
}
[Test]
public void GCM_Batched_All_ShouldSucceed()
{
TestNotifications(false, 10, 10, 0);
}
[Test]
public void GCM_Batched_All_ShouldFail()
{
var toFail = new int[10];
for (int i = 0; i < toFail.Length; i++)
toFail[i] = i;
TestNotifications(false, 10, 0, 10, toFail);
}
[Test]
public void GCM_Batched_First_ShouldFail()
{
TestNotifications(false, 10, 9, 1, new int[] { 0 });
}
[Test]
public void GCM_Batched_Last_ShouldFail()
{
TestNotifications(false, 10, 9, 1, new int[] { 9 });
}
[Test]
public void GCM_Batched_Middles_ShouldFail()
{
TestNotifications(false, 10, 8, 2, new int[] { 3, 6 });
}
[Test]
public void GCM_Batched_Single_ShouldFail()
{
TestNotifications(false, 1, 0, 1, new int[] { 0 });
}
[Test]
public void GCM_Batched_Single_ShouldSucceed()
{
TestNotifications(false, 1, 1, 0);
}
[Test]
public void GCM_Subscription_ShouldBeExpired()
{
int msgIdOn = 1;
int pushFailCount = 0;
int pushSuccessCount = 0;
int subChangedCount = 0;
int subExpiredCount = 0;
var notifications = new List<GcmNotification>() {
new GcmNotification().ForDeviceRegistrationId("NOTREGISTERED").WithJson(@"{""key"":""value""}")
};
TestNotifications(notifications,
new List<GcmMessageResponseFilter>() {
new GcmMessageResponseFilter()
{
IsMatch = (request, s) => {
return s.Equals("NOTREGISTERED", StringComparison.InvariantCultureIgnoreCase);
},
Status = new GcmMessageResult() {
ResponseStatus = GcmMessageTransportResponseStatus.NotRegistered,
MessageId = "1:" + msgIdOn++
}
}
},
(sender, notification) => pushSuccessCount++, //Success
(sender, notification, error) => pushFailCount++, //Failed
(sender, oldId, newId, notification) => subChangedCount++,
(sender, id, expiryDate, notification) => subExpiredCount++
);
Assert.AreEqual(0, pushFailCount, "Client - Failed Count");
Assert.AreEqual(0, pushSuccessCount, "Client - Success Count");
Assert.AreEqual(0, subChangedCount, "Client - SubscriptionId Changed Count");
Assert.AreEqual(notifications.Count, subExpiredCount, "Client - SubscriptionId Expired Count");
}
[Test]
public void GCM_Subscription_ShouldBeChanged()
{
int msgIdOn = 1;
int pushFailCount = 0;
int pushSuccessCount = 0;
int subChangedCount = 0;
int subExpiredCount = 0;
var notifications = new List<GcmNotification>() {
new GcmNotification().ForDeviceRegistrationId("NOTREGISTERED").WithJson(@"{""key"":""value""}")
};
TestNotifications(notifications,
new List<GcmMessageResponseFilter>() {
new GcmMessageResponseFilter()
{
IsMatch = (request, s) => {
return s.Equals("NOTREGISTERED", StringComparison.InvariantCultureIgnoreCase);
},
Status = new GcmMessageResult() {
ResponseStatus = GcmMessageTransportResponseStatus.NotRegistered,
CanonicalRegistrationId = "NEWID",
MessageId = "1:" + msgIdOn++
}
}
},
(sender, notification) => pushSuccessCount++, //Success
(sender, notification, error) => pushFailCount++, //Failed
(sender, oldId, newId, notification) => subChangedCount++,
(sender, id, expiryDate, notification) => subExpiredCount++
);
Assert.AreEqual(0, pushFailCount, "Client - Failed Count");
Assert.AreEqual(0, pushSuccessCount, "Client - Success Count");
Assert.AreEqual(notifications.Count, subChangedCount, "Client - SubscriptionId Changed Count");
Assert.AreEqual(0, subExpiredCount, "Client - SubscriptionId Expired Count");
}
public void TestNotifications(bool shouldBatch, int toQueue, int expectSuccessful, int expectFailed, int[] indexesToFail = null)
{
testPort++;
int msgIdOn = 1000;
int pushFailCount = 0;
int pushSuccessCount = 0;
int serverReceivedCount = 0;
int serverReceivedFailCount = 0;
int serverReceivedSuccessCount = 0;
//var notification = new GcmNotification();
var server = new TestServers.GcmTestServer();
server.MessageResponseFilters.Add(new GcmMessageResponseFilter()
{
IsMatch = (request, s) => {
return s.Equals("FAIL", StringComparison.InvariantCultureIgnoreCase);
},
Status = new GcmMessageResult() {
ResponseStatus = GcmMessageTransportResponseStatus.InvalidRegistration,
MessageId = "1:" + msgIdOn++
}
});
server.MessageResponseFilters.Add(new GcmMessageResponseFilter()
{
IsMatch = (request, s) => {
return s.Equals("NOTREGISTERED", StringComparison.InvariantCultureIgnoreCase);
},
Status = new GcmMessageResult() {
ResponseStatus = GcmMessageTransportResponseStatus.NotRegistered,
MessageId = "1:" + msgIdOn++
}
});
//var waitServerFinished = new ManualResetEvent(false);
server.Start(testPort, response =>
{
serverReceivedCount += (int)response.NumberOfCanonicalIds;
serverReceivedSuccessCount += (int) response.NumberOfSuccesses;
serverReceivedFailCount += (int) response.NumberOfFailures;
});
var settings = new GcmPushChannelSettings("SENDERAUTHTOKEN");
settings.OverrideUrl("http://localhost:" + (testPort) + "/");
var push = new GcmPushService(settings);
push.OnNotificationSent += (sender, notification1) => pushSuccessCount++;
push.OnNotificationFailed += (sender, notification1, error) => {
pushFailCount++;
};
var json = @"{""key"":""value1""}";
if (shouldBatch)
{
var regIds = new List<string>();
for (int i = 0; i < toQueue; i++)
regIds.Add((indexesToFail != null && indexesToFail.Contains(i)) ? "FAIL" : "SUCCESS");
var n = new GcmNotification();
n.RegistrationIds.AddRange(regIds);
n.WithJson(json);
push.QueueNotification(n);
}
else
{
for (int i = 0; i < toQueue; i++)
push.QueueNotification(new GcmNotification()
.ForDeviceRegistrationId((indexesToFail != null && indexesToFail.Contains(i)) ? "FAIL" : "SUCCESS")
.WithJson(json));
}
push.Stop();
push.Dispose();
server.Dispose();
//waitServerFinished.WaitOne();
Console.WriteLine("TEST-> DISPOSE.");
Assert.AreEqual(toQueue, serverReceivedCount, "Server - Received Count");
Assert.AreEqual(expectFailed, serverReceivedFailCount, "Server - Failed Count");
Assert.AreEqual(expectSuccessful, serverReceivedSuccessCount, "Server - Success Count");
Assert.AreEqual(expectFailed, pushFailCount, "Client - Failed Count");
Assert.AreEqual(expectSuccessful, pushSuccessCount, "Client - Success Count");
}
public void TestNotifications(List<GcmNotification> notifications,
List<GcmMessageResponseFilter> responseFilters,
Action<object, INotification> sentCallback,
Action<object, INotification, Exception> failedCallback,
Action<object, string, string, INotification> subscriptionChangedCallback,
Action<object, string, DateTime, INotification> subscriptionExpiredCallback)
{
testPort++;
int pushFailCount = 0;
int pushSuccessCount = 0;
int serverReceivedCount = 0;
int serverReceivedFailCount = 0;
int serverReceivedSuccessCount = 0;
var server = new TestServers.GcmTestServer();
server.MessageResponseFilters.AddRange(responseFilters);
server.Start(testPort, response => {
serverReceivedCount += (int)response.NumberOfCanonicalIds;
serverReceivedSuccessCount += (int) response.NumberOfSuccesses;
serverReceivedFailCount += (int) response.NumberOfFailures;
});
var settings = new GcmPushChannelSettings("SENDERAUTHTOKEN");
settings.OverrideUrl("http://localhost:" + (testPort) + "/");
var push = new GcmPushService(settings);
push.OnNotificationSent += (sender, notification1) => {
pushSuccessCount++;
sentCallback(sender, notification1);
};
push.OnNotificationFailed += (sender, notification1, error) => {
pushFailCount++;
failedCallback(sender, notification1, error);
};
push.OnDeviceSubscriptionChanged += (sender, oldSubscriptionId, newSubscriptionId, notification) => subscriptionChangedCallback(sender, oldSubscriptionId, newSubscriptionId, notification);
push.OnDeviceSubscriptionExpired += (sender, expiredSubscriptionId, expirationDateUtc, notification) => subscriptionExpiredCallback(sender, expiredSubscriptionId, expirationDateUtc, notification);
foreach (var n in notifications)
push.QueueNotification(n);
push.Stop();
push.Dispose();
server.Dispose();
//waitServerFinished.WaitOne();
Console.WriteLine("TEST-> DISPOSE.");
}
}
}
| apache-2.0 |
lumpiluk/poehling-hotel-manager | de.pension-poehling.fxmanager/src/application/customControls/SimpleTablesView.java | 6942 | /*
* Copyright 2014 Lukas Stratmann
*
* 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 application.customControls;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.NoSuchElementException;
import java.util.ResourceBundle;
import application.customControls.AbstractForm.Mode;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.ToolBar;
import data.DataSupervisor;
import data.HotelData;
/**
* @author lumpiluk
*
*/
public class SimpleTablesView extends AbstractControl {
@FXML // ResourceBundle that was given to the FXMLLoader
private ResourceBundle resources;
@FXML // URL location of the FXML file that was given to the FXMLLoader
private URL location;
@FXML // fx:id="tbFlags"
private ToggleButton tbFlags; // Value injected by FXMLLoader
@FXML // fx:id="btnItemCancel"
private Button btnItemCancel; // Value injected by FXMLLoader
@FXML // fx:id="tbCountries"
private ToggleButton tbCountries; // Value injected by FXMLLoader
@FXML // fx:id="btnAddItem"
private Button btnAddItem; // Value injected by FXMLLoader
@FXML // fx:id="btnRemoveItem"
private Button btnRemoveItem; // Value injected by FXMLLoader
@FXML // fx:id="btnItemOk"
private Button btnItemOk; // Value injected by FXMLLoader
@FXML // fx:id="tfItem"
private TextField tfItem; // Value injected by FXMLLoader
@FXML // fx:id="toggleGroup"
private ToggleGroup toggleGroup; // Value injected by FXMLLoader
@FXML // fx:id="tbTitles"
private ToggleButton tbTitles; // Value injected by FXMLLoader
@FXML // fx:id="tbStates"
private ToggleButton tbStates; // Value injected by FXMLLoader
@FXML // fx:id="lvItems"
private ListView<?> lvItems; // Value injected by FXMLLoader
@FXML // fx:id="listTools"
private ToolBar listTools; // Value injected by FXMLLoader
private DataSupervisor dataSupervisor;
private Mode currentMode;
/**
* @throws IOException
*/
public SimpleTablesView() throws IOException {
super();
}
public void initData(DataSupervisor dataSupervisor) {
this.dataSupervisor = dataSupervisor;
toggleGroup.selectedToggleProperty().addListener(
(observable, oldVal, newVal) -> {
// make toggleButtons persistent within group: don't allow no button to be selected!
if (newVal == null) {
oldVal.setSelected(true);
return;
}
if (newVal == tbFlags) {
getLvItems().setItems(dataSupervisor.getFlagsObservable());
} else if (newVal == tbTitles) {
getLvItems().setItems(dataSupervisor.getTitlesObservable());
} else if (newVal == tbStates) {
getLvItems().setItems(dataSupervisor.getStatesObservable());
} else if (newVal == tbCountries) {
getLvItems().setItems(dataSupervisor.getCountriesObservable());
}
});
getLvItems().setItems(dataSupervisor.getTitlesObservable());
changeMode(Mode.DISPLAY);
}
private void setFormDisable(final boolean value) {
tfItem.setDisable(value);
}
/**
* Set the current state of the control.<br />
* DISPLAY: form disabled, just show customers selected in table<br />
* ADD: form enabled, after pressing OK new customer will be added<br />
* EDIT: form enabled, after pressing OK selected customer will be updated
* @param m the mode to change to
*/
private void changeMode(Mode m) {
currentMode = m;
listTools.getItems().clear();
switch (m) {
case DISPLAY:
setFormDisable(true);
listTools.getItems().addAll(btnAddItem, btnRemoveItem);
break;
case ADD:
setFormDisable(false);
listTools.getItems().addAll(btnItemOk, btnItemCancel);
break;
default:
break;
}
}
@SuppressWarnings("unchecked")
private ListView<String> getLvItems() {
return (ListView<String>) lvItems;
}
@FXML
void btnAddItemClicked(ActionEvent event) {
changeMode(Mode.ADD);
}
@FXML
void btnRemoveItemClicked(ActionEvent event) {
// TODO: ask user for confirmation!
if (!getLvItems().getSelectionModel().isEmpty()) {
getLvItems().getItems().removeAll(
getLvItems().getSelectionModel().getSelectedItems());
}
}
@FXML
void btnItemOkClicked(ActionEvent event) {
if (currentMode == Mode.ADD) {
getLvItems().getItems().add(tfItem.getText());
}
changeMode(Mode.DISPLAY);
}
@FXML
void btnItemCancelClicked(ActionEvent event) {
changeMode(Mode.DISPLAY);
}
@FXML // This method is called by the FXMLLoader when initialization is complete
void initialize() {
assert tbFlags != null : "fx:id=\"tbFlags\" was not injected: check your FXML file 'SimpleTablesView.fxml'.";
assert btnItemCancel != null : "fx:id=\"btnItemCancel\" was not injected: check your FXML file 'SimpleTablesView.fxml'.";
assert tbCountries != null : "fx:id=\"tbCountries\" was not injected: check your FXML file 'SimpleTablesView.fxml'.";
assert btnAddItem != null : "fx:id=\"btnAddItem\" was not injected: check your FXML file 'SimpleTablesView.fxml'.";
assert btnRemoveItem != null : "fx:id=\"btnRemoveItem\" was not injected: check your FXML file 'SimpleTablesView.fxml'.";
assert btnItemOk != null : "fx:id=\"btnItemOk\" was not injected: check your FXML file 'SimpleTablesView.fxml'.";
assert tfItem != null : "fx:id=\"tfItem\" was not injected: check your FXML file 'SimpleTablesView.fxml'.";
assert toggleGroup != null : "fx:id=\"toggleGroup\" was not injected: check your FXML file 'SimpleTablesView.fxml'.";
assert tbTitles != null : "fx:id=\"tbTitles\" was not injected: check your FXML file 'SimpleTablesView.fxml'.";
assert tbStates != null : "fx:id=\"tbStates\" was not injected: check your FXML file 'SimpleTablesView.fxml'.";
assert lvItems != null : "fx:id=\"lvItems\" was not injected: check your FXML file 'SimpleTablesView.fxml'.";
assert listTools != null : "fx:id=\"listTools\" was not injected: check your FXML file 'SimpleTablesView.fxml'.";
}
}
| apache-2.0 |
tlkzzz/xpjfx | src/main/java/com/tlkzzz/jeesite/modules/cw/web/FReceiptController.java | 8426 | /**
* Copyright © 2012-2016 <a href="https://github.com/tlkzzz/jeesite">JeeSite</a> All rights reserved.
*/
package com.tlkzzz.jeesite.modules.cw.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.tlkzzz.jeesite.modules.ck.entity.CCkinfo;
import com.tlkzzz.jeesite.modules.ck.entity.CGoods;
import com.tlkzzz.jeesite.modules.ck.entity.CHouse;
import com.tlkzzz.jeesite.modules.ck.entity.CStore;
import com.tlkzzz.jeesite.modules.ck.service.CStoreService;
import com.tlkzzz.jeesite.modules.cw.entity.FFixedAssetsCgbm;
import com.tlkzzz.jeesite.modules.sys.utils.ExcelCreateUtils;
import com.tlkzzz.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.tlkzzz.jeesite.common.config.Global;
import com.tlkzzz.jeesite.common.persistence.Page;
import com.tlkzzz.jeesite.common.web.BaseController;
import com.tlkzzz.jeesite.common.utils.StringUtils;
import com.tlkzzz.jeesite.modules.cw.entity.FReceipt;
import com.tlkzzz.jeesite.modules.cw.service.FReceiptService;
import java.util.ArrayList;
import java.util.List;
/**
* 收款Controller
* @author xrc
* @version 2017-04-10
*/
@Controller
@RequestMapping(value = "${adminPath}/cw/fReceipt")
public class FReceiptController extends BaseController {
@Autowired
private FReceiptService fReceiptService;
@Autowired
private CStoreService cStoreService;
@ModelAttribute
public FReceipt get(@RequestParam(required=false) String id) {
FReceipt entity = null;
if (StringUtils.isNotBlank(id)){
entity = fReceiptService.get(id);
}
if (entity == null){
entity = new FReceipt();
}
return entity;
}
/**
* 现金费用list
* @param fReceipt
* @param request
* @param response
* @param model
* @return
*/
@RequiresPermissions("cw:fReceipt:view")
@RequestMapping(value = {"list", ""})
public String list(FReceipt fReceipt, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<FReceipt> page = fReceiptService.findPage(new Page<FReceipt>(request, response), fReceipt);
Double Sum=0.00;
Double htSum=0.00;
if(page.getList().size()>0){
List<FReceipt> fReceiptList=page.getList();
for(int i=0;i<fReceiptList.size();i++) {
if (StringUtils.isNotBlank(fReceiptList.get(i).getJe())) {
Double je = Double.parseDouble(fReceiptList.get(i).getJe());
Sum += je;
}
if (StringUtils.isNotBlank(fReceiptList.get(i).getHtje())) {
Double htje = Double.parseDouble(fReceiptList.get(i).getHtje());
htSum += htje;
}
}
}
model.addAttribute("page", page);
model.addAttribute("fReceipt", fReceipt);
model.addAttribute("Sum",Sum);
model.addAttribute("htSum",htSum);
return "modules/cw/fReceiptList";
}
/**
* 现金费用单
* @param fReceipt
* @param model
* @return
*/
@RequiresPermissions("cw:fReceipt:view")
@RequestMapping(value = "xjform")
public String xjform(FReceipt fReceipt, Model model) {//现金费用单
model.addAttribute("fReceipt", fReceipt);
return "modules/cw/fReceiptxjForm";
}
@RequiresPermissions("cw:fReceipt:edit")
@RequestMapping(value = "xjsave")
public String xjsave(FReceipt fReceipt, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, fReceipt)){//现金费用单保存信息
return form(fReceipt, model);
}
fReceiptService.outOfTheLibrary(fReceipt,"6","0");
addMessage(redirectAttributes, "现金费用单成功");
return "redirect:"+Global.getAdminPath()+"/cw/fReceipt/?repage";
}
/**
* 一般费用单
* @param fReceipt
* @param model
* @return
*/
@RequiresPermissions("cw:fReceipt:view")
@RequestMapping(value = "ybform")
public String ybform(FReceipt fReceipt, Model model) {//一般费用单
model.addAttribute("fReceipt", fReceipt);
return "modules/cw/fReceiptybForm";
}
@RequiresPermissions("cw:fReceipt:edit")
@RequestMapping(value = "ybsave")
public String ybsave(FReceipt fReceipt, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, fReceipt)){//一般费用单保存
return form(fReceipt, model);
}
fReceiptService.outOfTheLibrary(fReceipt,"7","0");
addMessage(redirectAttributes, "一般费用单成功");
return "redirect:"+Global.getAdminPath()+"/cw/fReceipt/?repage";
}
@RequiresPermissions("cw:fReceipt:view")
@RequestMapping(value = "form")
public String form(FReceipt fReceipt, Model model) {
model.addAttribute("fReceipt", fReceipt);
return "error/400" ;
}
/**
* 其他费用单
* @param fReceipt
* @param model
* @return
*/
@RequiresPermissions("cw:fReceipt:view")
@RequestMapping(value = "qtform")
public String qtform(FReceipt fReceipt, Model model) {//其他费用单
model.addAttribute("fReceipt", fReceipt);
return "modules/cw/fReceiptqtForm";
}
@RequiresPermissions("cw:fReceipt:edit")
@RequestMapping(value = "qtsave")
public String qtsave(FReceipt fReceipt, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, fReceipt)){//其他费用单保存
return form(fReceipt, model);
}
fReceiptService.outOfTheLibrary(fReceipt,"8","0");
addMessage(redirectAttributes, "其他费用单成功");
return "redirect:"+Global.getAdminPath()+"/cw/fReceipt/?repage";
}
/**
* 审核
* @param fReceipt
* @param
* @return
*/
@ResponseBody
@RequestMapping(value = "shenhe")
public String shenhe(FReceipt fReceipt) {
String retStr = "false";
if (fReceipt != null && !fReceipt.getIsNewRecord()) {
fReceipt.setApprovalStatus("1");
//获取当前登入者
fReceipt.setAuditor(UserUtils.getUser());
fReceiptService.save(fReceipt);
retStr = "true";
}
return retStr;
}
@RequiresPermissions("cw:fReceipt:edit")
@RequestMapping(value = "delete")
public String delete(FReceipt fReceipt, RedirectAttributes redirectAttributes) {
fReceiptService.delete(fReceipt);
addMessage(redirectAttributes, "删除收款成功");
String str = "";
if(fReceipt.getReceiptType()==""){
return "error/404" ;
}
return "redirect:"+Global.getAdminPath()+"/cw/fReceipt/?repage";
}
@RequiresPermissions("cw:fReceipt:view")
@RequestMapping(value = "GysReturn")
public String GysReturn(FReceipt fReceipt, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<FReceipt> page = fReceiptService.findPage(new Page<FReceipt>(request, response), fReceipt);
model.addAttribute("page", page);
model.addAttribute("fReceipt", fReceipt);
return "modules/cw/GysReturn";
}
/** 导出 **/
@RequestMapping(value = "yfkexcel")
public String yfkexcel(FReceipt fReceipt, String type, Model model,HttpServletResponse response){
List<FReceipt> list = new ArrayList<FReceipt>();
if(StringUtils.isBlank(type)||"1".equals(type)){
list = fReceiptService.findList(fReceipt);
ExcelCreateUtils.yskexport(response,list,"1");
}else if("2".equals(type)){//通过客户分类查询
list = fReceiptService.findListByStore(fReceipt);
ExcelCreateUtils.yskexport(response,list,"2");
}else if("3".equals(type)){
list = fReceiptService.findArrearsList(fReceipt);
ExcelCreateUtils.yskexport(response,list,"3");
}
return null;
}
/** 财务报表开始 **/
@RequiresPermissions("cw:fReceipt:view")
@RequestMapping(value = "reportList")
public String reportList(FReceipt fReceipt, String type, Model model){
List<FReceipt> list = new ArrayList<FReceipt>();
if(StringUtils.isBlank(type)||"1".equals(type)){
list = fReceiptService.findList(fReceipt);
}else if("2".equals(type)){//通过客户分类查询
list = fReceiptService.findListByStore(fReceipt);
}else if("3".equals(type)){
list = fReceiptService.findArrearsList(fReceipt);
}
model.addAttribute("storeList", cStoreService.findList(new CStore()));
model.addAttribute("fReceipt", fReceipt);
model.addAttribute("list", list);
model.addAttribute("type", type);
return "modules/report/fReceiptReportList";
}
} | apache-2.0 |
losipiuk/presto | presto-main/src/main/java/io/prestosql/operator/aggregation/state/StateCompiler.java | 36087 | /*
* 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.prestosql.operator.aggregation.state;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Ordering;
import io.airlift.bytecode.BytecodeBlock;
import io.airlift.bytecode.ClassDefinition;
import io.airlift.bytecode.DynamicClassLoader;
import io.airlift.bytecode.FieldDefinition;
import io.airlift.bytecode.MethodDefinition;
import io.airlift.bytecode.Parameter;
import io.airlift.bytecode.Scope;
import io.airlift.bytecode.Variable;
import io.airlift.bytecode.control.IfStatement;
import io.airlift.bytecode.expression.BytecodeExpression;
import io.airlift.slice.Slice;
import io.prestosql.array.BlockBigArray;
import io.prestosql.array.BooleanBigArray;
import io.prestosql.array.ByteBigArray;
import io.prestosql.array.DoubleBigArray;
import io.prestosql.array.IntBigArray;
import io.prestosql.array.LongBigArray;
import io.prestosql.array.ObjectBigArray;
import io.prestosql.array.SliceBigArray;
import io.prestosql.operator.aggregation.GroupedAccumulator;
import io.prestosql.spi.block.Block;
import io.prestosql.spi.block.BlockBuilder;
import io.prestosql.spi.function.AccumulatorStateFactory;
import io.prestosql.spi.function.AccumulatorStateMetadata;
import io.prestosql.spi.function.AccumulatorStateSerializer;
import io.prestosql.spi.type.RowType;
import io.prestosql.spi.type.Type;
import io.prestosql.sql.gen.CallSiteBinder;
import io.prestosql.sql.gen.SqlTypeBytecodeExpression;
import org.openjdk.jol.info.ClassLayout;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static com.google.common.base.CaseFormat.LOWER_CAMEL;
import static com.google.common.base.CaseFormat.UPPER_CAMEL;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Iterables.getOnlyElement;
import static io.airlift.bytecode.Access.FINAL;
import static io.airlift.bytecode.Access.PRIVATE;
import static io.airlift.bytecode.Access.PUBLIC;
import static io.airlift.bytecode.Access.STATIC;
import static io.airlift.bytecode.Access.a;
import static io.airlift.bytecode.Parameter.arg;
import static io.airlift.bytecode.ParameterizedType.type;
import static io.airlift.bytecode.expression.BytecodeExpressions.add;
import static io.airlift.bytecode.expression.BytecodeExpressions.constantBoolean;
import static io.airlift.bytecode.expression.BytecodeExpressions.constantClass;
import static io.airlift.bytecode.expression.BytecodeExpressions.constantInt;
import static io.airlift.bytecode.expression.BytecodeExpressions.constantNull;
import static io.airlift.bytecode.expression.BytecodeExpressions.constantNumber;
import static io.airlift.bytecode.expression.BytecodeExpressions.defaultValue;
import static io.airlift.bytecode.expression.BytecodeExpressions.equal;
import static io.airlift.bytecode.expression.BytecodeExpressions.getStatic;
import static io.airlift.bytecode.expression.BytecodeExpressions.newInstance;
import static io.prestosql.spi.type.BigintType.BIGINT;
import static io.prestosql.spi.type.BooleanType.BOOLEAN;
import static io.prestosql.spi.type.DoubleType.DOUBLE;
import static io.prestosql.spi.type.IntegerType.INTEGER;
import static io.prestosql.spi.type.TinyintType.TINYINT;
import static io.prestosql.spi.type.VarbinaryType.VARBINARY;
import static io.prestosql.sql.gen.SqlTypeBytecodeExpression.constantType;
import static io.prestosql.type.UnknownType.UNKNOWN;
import static io.prestosql.util.CompilerUtils.defineClass;
import static io.prestosql.util.CompilerUtils.makeClassName;
import static java.util.Objects.requireNonNull;
public final class StateCompiler
{
private StateCompiler() {}
private static Class<?> getBigArrayType(Class<?> type)
{
if (type.equals(long.class)) {
return LongBigArray.class;
}
if (type.equals(byte.class)) {
return ByteBigArray.class;
}
if (type.equals(double.class)) {
return DoubleBigArray.class;
}
if (type.equals(boolean.class)) {
return BooleanBigArray.class;
}
if (type.equals(int.class)) {
return IntBigArray.class;
}
if (type.equals(Slice.class)) {
return SliceBigArray.class;
}
if (type.equals(Block.class)) {
return BlockBigArray.class;
}
return ObjectBigArray.class;
}
public static <T> AccumulatorStateSerializer<T> generateStateSerializer(Class<T> clazz)
{
return generateStateSerializer(clazz, new DynamicClassLoader(clazz.getClassLoader()));
}
public static <T> AccumulatorStateSerializer<T> generateStateSerializer(Class<T> clazz, DynamicClassLoader classLoader)
{
return generateStateSerializer(clazz, ImmutableMap.of(), classLoader);
}
public static <T> AccumulatorStateSerializer<T> generateStateSerializer(Class<T> clazz, Map<String, Type> fieldTypes, DynamicClassLoader classLoader)
{
AccumulatorStateMetadata metadata = getMetadataAnnotation(clazz);
if (metadata != null && metadata.stateSerializerClass() != void.class) {
try {
return (AccumulatorStateSerializer<T>) metadata.stateSerializerClass().getConstructor().newInstance();
}
catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
ClassDefinition definition = new ClassDefinition(
a(PUBLIC, FINAL),
makeClassName(clazz.getSimpleName() + "Serializer"),
type(Object.class),
type(AccumulatorStateSerializer.class));
CallSiteBinder callSiteBinder = new CallSiteBinder();
// Generate constructor
definition.declareDefaultConstructor(a(PUBLIC));
List<StateField> fields = enumerateFields(clazz, fieldTypes);
generateGetSerializedType(definition, fields, callSiteBinder);
generateSerialize(definition, callSiteBinder, clazz, fields);
generateDeserialize(definition, callSiteBinder, clazz, fields);
Class<?> serializerClass = defineClass(definition, AccumulatorStateSerializer.class, callSiteBinder.getBindings(), classLoader);
try {
return (AccumulatorStateSerializer<T>) serializerClass.getConstructor().newInstance();
}
catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
private static void generateGetSerializedType(ClassDefinition definition, List<StateField> fields, CallSiteBinder callSiteBinder)
{
BytecodeBlock body = definition.declareMethod(a(PUBLIC), "getSerializedType", type(Type.class)).getBody();
Type type;
if (fields.size() > 1) {
List<Type> types = fields.stream().map(StateField::getSqlType).collect(toImmutableList());
type = RowType.anonymous(types);
}
else if (fields.size() == 1) {
type = getOnlyElement(fields).getSqlType();
}
else {
type = UNKNOWN;
}
body.comment("return %s", type.getTypeSignature())
.append(constantType(callSiteBinder, type))
.retObject();
}
private static <T> AccumulatorStateMetadata getMetadataAnnotation(Class<T> clazz)
{
AccumulatorStateMetadata metadata = clazz.getAnnotation(AccumulatorStateMetadata.class);
if (metadata != null) {
return metadata;
}
// If the annotation wasn't found, then search the super classes
for (Class<?> superInterface : clazz.getInterfaces()) {
metadata = superInterface.getAnnotation(AccumulatorStateMetadata.class);
if (metadata != null) {
return metadata;
}
}
return null;
}
private static <T> void generateDeserialize(ClassDefinition definition, CallSiteBinder binder, Class<T> clazz, List<StateField> fields)
{
Parameter block = arg("block", Block.class);
Parameter index = arg("index", int.class);
Parameter state = arg("state", Object.class);
MethodDefinition method = definition.declareMethod(a(PUBLIC), "deserialize", type(void.class), block, index, state);
BytecodeBlock deserializerBody = method.getBody();
Scope scope = method.getScope();
if (fields.size() == 1) {
StateField field = getOnlyElement(fields);
Method setter = getSetter(clazz, field);
if (!field.isPrimitiveType()) {
deserializerBody.append(new IfStatement()
.condition(block.invoke("isNull", boolean.class, index))
.ifTrue(state.cast(setter.getDeclaringClass()).invoke(setter, constantNull(field.getType())))
.ifFalse(state.cast(setter.getDeclaringClass()).invoke(setter, constantType(binder, field.getSqlType()).getValue(block, index))));
}
else {
// For primitive type, we need to cast here because we serialize byte fields with TINYINT/INTEGER (whose java type is long).
deserializerBody.append(
state.cast(setter.getDeclaringClass()).invoke(
setter,
constantType(binder, field.getSqlType()).getValue(block, index).cast(field.getType())));
}
}
else if (fields.size() > 1) {
Variable row = scope.declareVariable(Block.class, "row");
deserializerBody.append(row.set(block.invoke("getObject", Object.class, index, constantClass(Block.class)).cast(Block.class)));
int position = 0;
for (StateField field : fields) {
Method setter = getSetter(clazz, field);
if (!field.isPrimitiveType()) {
deserializerBody.append(new IfStatement()
.condition(row.invoke("isNull", boolean.class, constantInt(position)))
.ifTrue(state.cast(setter.getDeclaringClass()).invoke(setter, constantNull(field.getType())))
.ifFalse(state.cast(setter.getDeclaringClass()).invoke(setter, constantType(binder, field.getSqlType()).getValue(row, constantInt(position)))));
}
else {
// For primitive type, we need to cast here because we serialize byte fields with TINYINT/INTEGER (whose java type is long).
deserializerBody.append(
state.cast(setter.getDeclaringClass()).invoke(
setter,
constantType(binder, field.getSqlType()).getValue(row, constantInt(position)).cast(field.getType())));
}
position++;
}
}
deserializerBody.ret();
}
private static <T> void generateSerialize(ClassDefinition definition, CallSiteBinder binder, Class<T> clazz, List<StateField> fields)
{
Parameter state = arg("state", Object.class);
Parameter out = arg("out", BlockBuilder.class);
MethodDefinition method = definition.declareMethod(a(PUBLIC), "serialize", type(void.class), state, out);
Scope scope = method.getScope();
BytecodeBlock serializerBody = method.getBody();
if (fields.size() == 0) {
serializerBody.append(out.invoke("appendNull", BlockBuilder.class).pop());
}
else if (fields.size() == 1) {
Method getter = getGetter(clazz, getOnlyElement(fields));
SqlTypeBytecodeExpression sqlType = constantType(binder, getOnlyElement(fields).getSqlType());
Variable fieldValue = scope.declareVariable(getter.getReturnType(), "value");
serializerBody.append(fieldValue.set(state.cast(getter.getDeclaringClass()).invoke(getter)));
if (!getOnlyElement(fields).isPrimitiveType()) {
serializerBody.append(new IfStatement()
.condition(equal(fieldValue, constantNull(getter.getReturnType())))
.ifTrue(out.invoke("appendNull", BlockBuilder.class).pop())
.ifFalse(sqlType.writeValue(out, fieldValue)));
}
else {
// For primitive type, we need to cast here because we serialize byte fields with TINYINT/INTEGER (whose java type is long).
serializerBody.append(sqlType.writeValue(out, fieldValue.cast(getOnlyElement(fields).getSqlType().getJavaType())));
}
}
else if (fields.size() > 1) {
Variable rowBuilder = scope.declareVariable(BlockBuilder.class, "rowBuilder");
serializerBody.append(rowBuilder.set(out.invoke("beginBlockEntry", BlockBuilder.class)));
for (StateField field : fields) {
Method getter = getGetter(clazz, field);
SqlTypeBytecodeExpression sqlType = constantType(binder, field.getSqlType());
Variable fieldValue = scope.createTempVariable(getter.getReturnType());
serializerBody.append(fieldValue.set(state.cast(getter.getDeclaringClass()).invoke(getter)));
if (!field.isPrimitiveType()) {
serializerBody.append(new IfStatement().condition(equal(fieldValue, constantNull(getter.getReturnType())))
.ifTrue(rowBuilder.invoke("appendNull", BlockBuilder.class).pop())
.ifFalse(sqlType.writeValue(rowBuilder, fieldValue)));
}
else {
// For primitive type, we need to cast here because we serialize byte fields with TINYINT/INTEGER (whose java type is long).
serializerBody.append(sqlType.writeValue(rowBuilder, fieldValue.cast(field.getSqlType().getJavaType())));
}
}
serializerBody.append(out.invoke("closeEntry", BlockBuilder.class).pop());
}
serializerBody.ret();
}
private static Method getSetter(Class<?> clazz, StateField field)
{
try {
return clazz.getMethod(field.getSetterName(), field.getType());
}
catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
private static Method getGetter(Class<?> clazz, StateField field)
{
try {
return clazz.getMethod(field.getGetterName());
}
catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
public static <T> AccumulatorStateFactory<T> generateStateFactory(Class<T> clazz)
{
return generateStateFactory(clazz, new DynamicClassLoader(clazz.getClassLoader()));
}
public static <T> AccumulatorStateFactory<T> generateStateFactory(Class<T> clazz, DynamicClassLoader classLoader)
{
return generateStateFactory(clazz, ImmutableMap.of(), classLoader);
}
public static <T> AccumulatorStateFactory<T> generateStateFactory(Class<T> clazz, Map<String, Type> fieldTypes, DynamicClassLoader classLoader)
{
AccumulatorStateMetadata metadata = getMetadataAnnotation(clazz);
if (metadata != null && metadata.stateFactoryClass() != void.class) {
try {
return (AccumulatorStateFactory<T>) metadata.stateFactoryClass().getConstructor().newInstance();
}
catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
Class<? extends T> singleStateClass = generateSingleStateClass(clazz, fieldTypes, classLoader);
Class<? extends T> groupedStateClass = generateGroupedStateClass(clazz, fieldTypes, classLoader);
ClassDefinition definition = new ClassDefinition(
a(PUBLIC, FINAL),
makeClassName(clazz.getSimpleName() + "Factory"),
type(Object.class),
type(AccumulatorStateFactory.class));
// Generate constructor
definition.declareDefaultConstructor(a(PUBLIC));
// Generate single state creation method
definition.declareMethod(a(PUBLIC), "createSingleState", type(Object.class))
.getBody()
.newObject(singleStateClass)
.dup()
.invokeConstructor(singleStateClass)
.retObject();
// Generate grouped state creation method
definition.declareMethod(a(PUBLIC), "createGroupedState", type(Object.class))
.getBody()
.newObject(groupedStateClass)
.dup()
.invokeConstructor(groupedStateClass)
.retObject();
// Generate getters for state class
definition.declareMethod(a(PUBLIC), "getSingleStateClass", type(Class.class, singleStateClass))
.getBody()
.push(singleStateClass)
.retObject();
definition.declareMethod(a(PUBLIC), "getGroupedStateClass", type(Class.class, groupedStateClass))
.getBody()
.push(groupedStateClass)
.retObject();
Class<?> factoryClass = defineClass(definition, AccumulatorStateFactory.class, classLoader);
try {
return (AccumulatorStateFactory<T>) factoryClass.getConstructor().newInstance();
}
catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
private static <T> Class<? extends T> generateSingleStateClass(Class<T> clazz, Map<String, Type> fieldTypes, DynamicClassLoader classLoader)
{
ClassDefinition definition = new ClassDefinition(
a(PUBLIC, FINAL),
makeClassName("Single" + clazz.getSimpleName()),
type(Object.class),
type(clazz));
FieldDefinition instanceSize = generateInstanceSize(definition);
// Add getter for class size
definition.declareMethod(a(PUBLIC), "getEstimatedSize", type(long.class))
.getBody()
.getStaticField(instanceSize)
.retLong();
// Generate constructor
MethodDefinition constructor = definition.declareConstructor(a(PUBLIC));
constructor.getBody()
.append(constructor.getThis())
.invokeConstructor(Object.class);
// Generate fields
List<StateField> fields = enumerateFields(clazz, fieldTypes);
for (StateField field : fields) {
generateField(definition, constructor, field);
}
constructor.getBody()
.ret();
return defineClass(definition, clazz, classLoader);
}
private static FieldDefinition generateInstanceSize(ClassDefinition definition)
{
// Store instance size in static field
FieldDefinition instanceSize = definition.declareField(a(PRIVATE, STATIC, FINAL), "INSTANCE_SIZE", long.class);
definition.getClassInitializer()
.getBody()
.comment("INSTANCE_SIZE = ClassLayout.parseClass(%s.class).instanceSize()", definition.getName())
.push(definition.getType())
.invokeStatic(ClassLayout.class, "parseClass", ClassLayout.class, Class.class)
.invokeVirtual(ClassLayout.class, "instanceSize", int.class)
.intToLong()
.putStaticField(instanceSize);
return instanceSize;
}
private static <T> Class<? extends T> generateGroupedStateClass(Class<T> clazz, Map<String, Type> fieldTypes, DynamicClassLoader classLoader)
{
ClassDefinition definition = new ClassDefinition(
a(PUBLIC, FINAL),
makeClassName("Grouped" + clazz.getSimpleName()),
type(AbstractGroupedAccumulatorState.class),
type(clazz),
type(GroupedAccumulator.class));
FieldDefinition instanceSize = generateInstanceSize(definition);
List<StateField> fields = enumerateFields(clazz, fieldTypes);
// Create constructor
MethodDefinition constructor = definition.declareConstructor(a(PUBLIC));
constructor.getBody()
.append(constructor.getThis())
.invokeConstructor(AbstractGroupedAccumulatorState.class);
// Create ensureCapacity
MethodDefinition ensureCapacity = definition.declareMethod(a(PUBLIC), "ensureCapacity", type(void.class), arg("size", long.class));
// Generate fields, constructor, and ensureCapacity
List<FieldDefinition> fieldDefinitions = new ArrayList<>();
for (StateField field : fields) {
fieldDefinitions.add(generateGroupedField(definition, constructor, ensureCapacity, field));
}
constructor.getBody().ret();
ensureCapacity.getBody().ret();
// Generate getEstimatedSize
MethodDefinition getEstimatedSize = definition.declareMethod(a(PUBLIC), "getEstimatedSize", type(long.class));
BytecodeBlock body = getEstimatedSize.getBody();
Variable size = getEstimatedSize.getScope().declareVariable(long.class, "size");
// initialize size to the size of the instance
body.append(size.set(getStatic(instanceSize)));
// add field to size
for (FieldDefinition field : fieldDefinitions) {
body.append(size.set(add(size, getEstimatedSize.getThis().getField(field).invoke("sizeOf", long.class))));
}
// return size
body.append(size.ret());
return defineClass(definition, clazz, classLoader);
}
private static void generateField(ClassDefinition definition, MethodDefinition constructor, StateField stateField)
{
FieldDefinition field = definition.declareField(a(PRIVATE), UPPER_CAMEL.to(LOWER_CAMEL, stateField.getName()) + "Value", stateField.getType());
// Generate getter
MethodDefinition getter = definition.declareMethod(a(PUBLIC), stateField.getGetterName(), type(stateField.getType()));
getter.getBody()
.append(getter.getThis().getField(field).ret());
// Generate setter
Parameter value = arg("value", stateField.getType());
MethodDefinition setter = definition.declareMethod(a(PUBLIC), stateField.getSetterName(), type(void.class), value);
setter.getBody()
.append(setter.getThis().setField(field, value))
.ret();
constructor.getBody()
.append(constructor.getThis().setField(field, stateField.initialValueExpression()));
}
private static FieldDefinition generateGroupedField(ClassDefinition definition, MethodDefinition constructor, MethodDefinition ensureCapacity, StateField stateField)
{
Class<?> bigArrayType = getBigArrayType(stateField.getType());
FieldDefinition field = definition.declareField(a(PRIVATE), UPPER_CAMEL.to(LOWER_CAMEL, stateField.getName()) + "Values", bigArrayType);
// Generate getter
MethodDefinition getter = definition.declareMethod(a(PUBLIC), stateField.getGetterName(), type(stateField.getType()));
getter.getBody()
.append(getter.getThis().getField(field).invoke(
"get",
stateField.getType(),
getter.getThis().invoke("getGroupId", long.class))
.ret());
// Generate setter
Parameter value = arg("value", stateField.getType());
MethodDefinition setter = definition.declareMethod(a(PUBLIC), stateField.getSetterName(), type(void.class), value);
setter.getBody()
.append(setter.getThis().getField(field).invoke(
"set",
void.class,
setter.getThis().invoke("getGroupId", long.class),
value))
.ret();
Scope ensureCapacityScope = ensureCapacity.getScope();
ensureCapacity.getBody()
.append(ensureCapacity.getThis().getField(field).invoke("ensureCapacity", void.class, ensureCapacityScope.getVariable("size")));
// Initialize field in constructor
constructor.getBody()
.append(constructor.getThis().setField(field, newInstance(field.getType(), stateField.initialValueExpression())));
return field;
}
/**
* Enumerates all the fields in this state interface.
*
* @param clazz a subclass of AccumulatorState
* @param fieldTypes a map of field name and Type
* @return list of state fields. Ordering is guaranteed to be stable, and have all primitive fields at the beginning.
*/
private static List<StateField> enumerateFields(Class<?> clazz, Map<String, Type> fieldTypes)
{
ImmutableList.Builder<StateField> builder = ImmutableList.builder();
final Set<Class<?>> primitiveClasses = ImmutableSet.of(byte.class, boolean.class, long.class, double.class, int.class);
for (Method method : clazz.getMethods()) {
if (method.getName().equals("getEstimatedSize")) {
continue;
}
if (method.getName().startsWith("get")) {
Class<?> type = method.getReturnType();
String name = method.getName().substring(3);
builder.add(new StateField(name, type, getInitialValue(method), method.getName(), Optional.ofNullable(fieldTypes.get(name))));
}
if (method.getName().startsWith("is")) {
Class<?> type = method.getReturnType();
checkArgument(type == boolean.class, "Only boolean is support for 'is' methods");
String name = method.getName().substring(2);
builder.add(new StateField(name, type, getInitialValue(method), method.getName(), Optional.of(BOOLEAN)));
}
}
// We need this ordering because the serializer and deserializer are on different machines, and so the ordering of fields must be stable
Ordering<StateField> ordering = new Ordering<StateField>()
{
@Override
public int compare(StateField left, StateField right)
{
if (primitiveClasses.contains(left.getType()) && !primitiveClasses.contains(right.getType())) {
return -1;
}
if (primitiveClasses.contains(right.getType()) && !primitiveClasses.contains(left.getType())) {
return 1;
}
// If they're the category, just sort by name
return left.getName().compareTo(right.getName());
}
};
List<StateField> fields = ordering.sortedCopy(builder.build());
checkInterface(clazz, fields);
return fields;
}
private static Object getInitialValue(Method method)
{
Object value = null;
for (Annotation annotation : method.getAnnotations()) {
if (annotation instanceof InitialLongValue) {
checkArgument(value == null, "%s has multiple initialValue annotations", method.getName());
checkArgument(method.getReturnType() == long.class, "%s does not return a long, but is annotated with @InitialLongValue", method.getName());
value = ((InitialLongValue) annotation).value();
}
else if (annotation instanceof InitialDoubleValue) {
checkArgument(value == null, "%s has multiple initialValue annotations", method.getName());
checkArgument(method.getReturnType() == double.class, "%s does not return a double, but is annotated with @InitialDoubleValue", method.getName());
value = ((InitialDoubleValue) annotation).value();
}
else if (annotation instanceof InitialBooleanValue) {
checkArgument(value == null, "%s has multiple initialValue annotations", method.getName());
checkArgument(method.getReturnType() == boolean.class, "%s does not return a boolean, but is annotated with @InitialBooleanValue", method.getName());
value = ((InitialBooleanValue) annotation).value();
}
}
return value;
}
private static void checkInterface(Class<?> clazz, List<StateField> fields)
{
checkArgument(clazz.isInterface(), clazz.getName() + " is not an interface");
Set<String> setters = new HashSet<>();
Set<String> getters = new HashSet<>();
Set<String> isGetters = new HashSet<>();
Map<String, Class<?>> fieldTypes = new HashMap<>();
for (StateField field : fields) {
fieldTypes.put(field.getName(), field.getType());
}
for (Method method : clazz.getMethods()) {
if (Modifier.isStatic(method.getModifiers())) {
continue;
}
if (method.getName().equals("getEstimatedSize")) {
checkArgument(method.getReturnType().equals(long.class), "getEstimatedSize must return long");
checkArgument(method.getParameterTypes().length == 0, "getEstimatedSize may not have parameters");
continue;
}
if (method.getName().startsWith("get")) {
String name = method.getName().substring(3);
checkArgument(fieldTypes.get(name).equals(method.getReturnType()),
"Expected %s to return type %s, but found %s", method.getName(), fieldTypes.get(name), method.getReturnType());
checkArgument(method.getParameterTypes().length == 0, "Expected %s to have zero parameters", method.getName());
getters.add(name);
}
else if (method.getName().startsWith("is")) {
String name = method.getName().substring(2);
checkArgument(fieldTypes.get(name) == boolean.class,
"Expected %s to have type boolean, but found %s", name, fieldTypes.get(name));
checkArgument(method.getParameterTypes().length == 0, "Expected %s to have zero parameters", method.getName());
checkArgument(method.getReturnType() == boolean.class, "Expected %s to return boolean", method.getName());
isGetters.add(name);
}
else if (method.getName().startsWith("set")) {
String name = method.getName().substring(3);
checkArgument(method.getParameterTypes().length == 1, "Expected setter to have one parameter");
checkArgument(fieldTypes.get(name).equals(method.getParameterTypes()[0]),
"Expected %s to accept type %s, but found %s", method.getName(), fieldTypes.get(name), method.getParameterTypes()[0]);
checkArgument(getInitialValue(method) == null, "initial value annotation not allowed on setter");
checkArgument(method.getReturnType().equals(void.class), "%s may not return a value", method.getName());
setters.add(name);
}
else {
throw new IllegalArgumentException("Cannot generate implementation for method: " + method.getName());
}
}
checkArgument(getters.size() + isGetters.size() == setters.size() && setters.size() == fields.size(), "Wrong number of getters/setters");
}
private static final class StateField
{
private final String name;
private final String getterName;
private final Class<?> type;
private final Object initialValue;
private final Optional<Type> sqlType;
private StateField(String name, Class<?> type, Object initialValue, String getterName, Optional<Type> sqlType)
{
this.name = requireNonNull(name, "name is null");
checkArgument(!name.isEmpty(), "name is empty");
this.type = requireNonNull(type, "type is null");
this.getterName = requireNonNull(getterName, "getterName is null");
this.initialValue = initialValue;
checkArgument(sqlType != null, "sqlType is null");
if (sqlType.isPresent()) {
checkArgument(
type.isAssignableFrom(sqlType.get().getJavaType()) ||
((type == byte.class) && TINYINT.equals(sqlType.get())) ||
((type == int.class) && INTEGER.equals(sqlType.get())),
"Stack type (%s) and provided sql type (%s) are incompatible", type.getName(), sqlType.get().getDisplayName());
}
else {
sqlType = sqlTypeFromStackType(type);
}
this.sqlType = sqlType;
}
private static Optional<Type> sqlTypeFromStackType(Class<?> stackType)
{
if (stackType == long.class) {
return Optional.of(BIGINT);
}
if (stackType == double.class) {
return Optional.of(DOUBLE);
}
if (stackType == boolean.class) {
return Optional.of(BOOLEAN);
}
if (stackType == byte.class) {
return Optional.of(TINYINT);
}
if (stackType == int.class) {
return Optional.of(INTEGER);
}
if (stackType == Slice.class) {
return Optional.of(VARBINARY);
}
return Optional.empty();
}
String getGetterName()
{
return getterName;
}
String getSetterName()
{
return "set" + getName();
}
public String getName()
{
return name;
}
public Class<?> getType()
{
return type;
}
Type getSqlType()
{
if (!sqlType.isPresent()) {
throw new IllegalArgumentException("Unsupported type: " + type);
}
return sqlType.get();
}
boolean isPrimitiveType()
{
Class<?> type = getType();
return (type == long.class || type == double.class || type == boolean.class || type == byte.class || type == int.class);
}
public BytecodeExpression initialValueExpression()
{
if (initialValue == null) {
return defaultValue(type);
}
if (initialValue instanceof Number) {
return constantNumber((Number) initialValue);
}
if (initialValue instanceof Boolean) {
return constantBoolean((boolean) initialValue);
}
throw new IllegalArgumentException("Unsupported initial value type: " + initialValue.getClass());
}
}
}
| apache-2.0 |
microcks/microcks | commons/model/src/main/java/io/github/microcks/domain/TestCaseResult.java | 2094 | /*
* Licensed to Laurent Broudoux (the "Author") under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Author licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.github.microcks.domain;
import java.util.ArrayList;
import java.util.List;
/**
* Companion objects for TestResult. Each TestCaseResult correspond to a
* particuliar service operation / action reference by the operationName field.
* TestCaseResults owns a collection of TestStepResults (one for every request
* associated to service operation / action).
* @author laurent
*/
public class TestCaseResult {
private boolean success = false;
private long elapsedTime = -1;
private String operationName;
private List<TestStepResult> testStepResults = new ArrayList<>();
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public long getElapsedTime() {
return elapsedTime;
}
public void setElapsedTime(long elapsedTime) {
this.elapsedTime = elapsedTime;
}
public String getOperationName() {
return operationName;
}
public void setOperationName(String operationName) {
this.operationName = operationName;
}
public List<TestStepResult> getTestStepResults() {
return testStepResults;
}
public void setTestStepResults(List<TestStepResult> testStepResults) {
this.testStepResults = testStepResults;
}
}
| apache-2.0 |
google/fest | third_party/fest-swing/src/test/java/org/fest/swing/test/builder/JFrames.java | 2277 | /*
* Created on Aug 28, 2008
*
* 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.
*
* Copyright @2008-2013 the original author or authors.
*/
package org.fest.swing.test.builder;
import static org.fest.swing.edt.GuiActionRunner.execute;
import javax.swing.JFrame;
import org.fest.swing.annotation.RunsInCurrentThread;
import org.fest.swing.annotation.RunsInEDT;
import org.fest.swing.edt.GuiQuery;
/**
* Factory of {@code JFrame}s.
*
* @author Alex Ruiz
*/
public final class JFrames {
private JFrames() {}
public static JFrameFactory frame() {
return new JFrameFactory();
}
public static class JFrameFactory {
private String name;
private boolean resizable = true;
private String title;
public JFrameFactory withName(String newName) {
name = newName;
return this;
}
public JFrameFactory withTitle(String newTitle) {
title = newTitle;
return this;
}
public JFrameFactory resizable(boolean shouldBeResizable) {
resizable = shouldBeResizable;
return this;
}
@RunsInEDT
public JFrame createAndShow() {
return execute(new GuiQuery<JFrame>() {
@Override
protected JFrame executeInEDT() {
JFrame frame = create();
frame.pack();
frame.setVisible(true);
return frame;
}
});
}
@RunsInEDT
public JFrame createNew() {
return execute(new GuiQuery<JFrame>() {
@Override
protected JFrame executeInEDT() {
return create();
}
});
}
@RunsInCurrentThread
private JFrame create() {
JFrame frame = new JFrame();
frame.setName(name);
frame.setTitle(title);
frame.setResizable(resizable);
return frame;
}
}
} | apache-2.0 |
jinglining/flink | flink-connectors/flink-connector-elasticsearch7/src/main/java/org/apache/flink/streaming/connectors/elasticsearch/table/Elasticsearch7DynamicSinkFactory.java | 6698 | /*
* 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.flink.streaming.connectors.elasticsearch.table;
import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.table.api.TableSchema;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.connector.format.EncodingFormat;
import org.apache.flink.table.connector.sink.DynamicTableSink;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.factories.DynamicTableSinkFactory;
import org.apache.flink.table.factories.FactoryUtil;
import org.apache.flink.table.factories.SerializationFormatFactory;
import org.apache.flink.table.utils.TableSchemaUtils;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.apache.flink.streaming.connectors.elasticsearch.table.ElasticsearchOptions.BULK_FLASH_MAX_SIZE_OPTION;
import static org.apache.flink.streaming.connectors.elasticsearch.table.ElasticsearchOptions.BULK_FLUSH_BACKOFF_DELAY_OPTION;
import static org.apache.flink.streaming.connectors.elasticsearch.table.ElasticsearchOptions.BULK_FLUSH_BACKOFF_MAX_RETRIES_OPTION;
import static org.apache.flink.streaming.connectors.elasticsearch.table.ElasticsearchOptions.BULK_FLUSH_BACKOFF_TYPE_OPTION;
import static org.apache.flink.streaming.connectors.elasticsearch.table.ElasticsearchOptions.BULK_FLUSH_INTERVAL_OPTION;
import static org.apache.flink.streaming.connectors.elasticsearch.table.ElasticsearchOptions.BULK_FLUSH_MAX_ACTIONS_OPTION;
import static org.apache.flink.streaming.connectors.elasticsearch.table.ElasticsearchOptions.CONNECTION_MAX_RETRY_TIMEOUT_OPTION;
import static org.apache.flink.streaming.connectors.elasticsearch.table.ElasticsearchOptions.CONNECTION_PATH_PREFIX;
import static org.apache.flink.streaming.connectors.elasticsearch.table.ElasticsearchOptions.FAILURE_HANDLER_OPTION;
import static org.apache.flink.streaming.connectors.elasticsearch.table.ElasticsearchOptions.FLUSH_ON_CHECKPOINT_OPTION;
import static org.apache.flink.streaming.connectors.elasticsearch.table.ElasticsearchOptions.FORMAT_OPTION;
import static org.apache.flink.streaming.connectors.elasticsearch.table.ElasticsearchOptions.HOSTS_OPTION;
import static org.apache.flink.streaming.connectors.elasticsearch.table.ElasticsearchOptions.INDEX_OPTION;
import static org.apache.flink.streaming.connectors.elasticsearch.table.ElasticsearchOptions.KEY_DELIMITER_OPTION;
/**
* A {@link DynamicTableSinkFactory} for discovering {@link Elasticsearch7DynamicSink}.
*/
@Internal
public class Elasticsearch7DynamicSinkFactory implements DynamicTableSinkFactory {
private static final Set<ConfigOption<?>> requiredOptions = Stream.of(
HOSTS_OPTION,
INDEX_OPTION
).collect(Collectors.toSet());
private static final Set<ConfigOption<?>> optionalOptions = Stream.of(
KEY_DELIMITER_OPTION,
FAILURE_HANDLER_OPTION,
FLUSH_ON_CHECKPOINT_OPTION,
BULK_FLASH_MAX_SIZE_OPTION,
BULK_FLUSH_MAX_ACTIONS_OPTION,
BULK_FLUSH_INTERVAL_OPTION,
BULK_FLUSH_BACKOFF_TYPE_OPTION,
BULK_FLUSH_BACKOFF_MAX_RETRIES_OPTION,
BULK_FLUSH_BACKOFF_DELAY_OPTION,
CONNECTION_MAX_RETRY_TIMEOUT_OPTION,
CONNECTION_PATH_PREFIX,
FORMAT_OPTION
).collect(Collectors.toSet());
@Override
public DynamicTableSink createDynamicTableSink(Context context) {
TableSchema tableSchema = context.getCatalogTable().getSchema();
ElasticsearchValidationUtils.validatePrimaryKey(tableSchema);
final FactoryUtil.TableFactoryHelper helper = FactoryUtil.createTableFactoryHelper(this, context);
final EncodingFormat<SerializationSchema<RowData>> format = helper.discoverEncodingFormat(
SerializationFormatFactory.class,
FORMAT_OPTION);
helper.validate();
Configuration configuration = new Configuration();
context.getCatalogTable()
.getOptions()
.forEach(configuration::setString);
Elasticsearch7Configuration config = new Elasticsearch7Configuration(configuration, context.getClassLoader());
validate(config, configuration);
return new Elasticsearch7DynamicSink(
format,
config,
TableSchemaUtils.getPhysicalSchema(tableSchema));
}
private void validate(Elasticsearch7Configuration config, Configuration originalConfiguration) {
config.getFailureHandler(); // checks if we can instantiate the custom failure handler
config.getHosts(); // validate hosts
validate(
config.getIndex().length() >= 1,
() -> String.format("'%s' must not be empty", INDEX_OPTION.key()));
int maxActions = config.getBulkFlushMaxActions();
validate(
maxActions == -1 || maxActions >= 1,
() -> String.format(
"'%s' must be at least 1 character. Got: %s",
BULK_FLUSH_MAX_ACTIONS_OPTION.key(),
maxActions)
);
long maxSize = config.getBulkFlushMaxByteSize();
long mb1 = 1024 * 1024;
validate(
maxSize == -1 || (maxSize >= mb1 && maxSize % mb1 == 0),
() -> String.format(
"'%s' must be in MB granularity. Got: %s",
BULK_FLASH_MAX_SIZE_OPTION.key(),
originalConfiguration.get(BULK_FLASH_MAX_SIZE_OPTION).toHumanReadableString())
);
validate(
config.getBulkFlushBackoffRetries().map(retries -> retries >= 1).orElse(true),
() -> String.format(
"'%s' must be at least 1. Got: %s",
BULK_FLUSH_BACKOFF_MAX_RETRIES_OPTION.key(),
config.getBulkFlushBackoffRetries().get())
);
}
private static void validate(boolean condition, Supplier<String> message) {
if (!condition) {
throw new ValidationException(message.get());
}
}
@Override
public String factoryIdentifier() {
return "elasticsearch-7";
}
@Override
public Set<ConfigOption<?>> requiredOptions() {
return requiredOptions;
}
@Override
public Set<ConfigOption<?>> optionalOptions() {
return optionalOptions;
}
}
| apache-2.0 |
spcs/synaps | synaps/__init__.py | 929 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright (c) 2012 Samsung SDS Co., LTD
# 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 gettext
import logging
gettext.install('synaps', unicode=1)
logging.basicConfig(format='%(message)s')
| apache-2.0 |
bmanojkumar/Mini_google | src/searchengine/indexer/Indexer.java | 16821 | /**
*
* Copyright: Copyright (c) 2004 Carnegie Mellon University
*
* This program is part of an implementation for the PARKR project which is
* about developing a search engine using efficient Datastructures.
*
* Modified by Mahender on 12-10-2009
*/
package searchengine.indexer;
import java.awt.List;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import searchengine.dictionary.AVLDictionary;
import searchengine.dictionary.BSTDictionary;
import searchengine.dictionary.DictionaryInterface;
import searchengine.dictionary.HashDictionary;
import searchengine.dictionary.ListDictionary;
import searchengine.dictionary.MyHashDictionary;
import searchengine.dictionary.ObjectIterator;
import searchengine.element.PageElementInterface;
import searchengine.element.PageWord;
/**
* Web-indexing objects. This class implements the Indexer interface using a
* list-based index structure.
*
* A Hash Map based implementation of Indexing
*/
public class Indexer implements IndexerInterface {
/**
* The constructor for ListWebIndex.
*/
// Index Structure
DictionaryInterface index;
int i = 0;
boolean noresults = false;
boolean firsttime = false;
boolean more = false;
String ll = "";
String repeat = "";
boolean repeat1 = false;
// This is for calculating the term frequency
HashMap<String, Integer> wordFrequency = new HashMap<String, Integer>();
HashMap<String, String> restore = new HashMap<String, String>();
// HashMap<String,Integer> rank = new HashMap<String,Integer>();
HashMap<String, String> rank = new HashMap<String, String>();
SetImplementation<String> sett = new SetImplementation<String>();
SetImplementation<String> settemp = new SetImplementation<String>();
public Indexer(String mode) {
// hash - Dictionary Structure based on a Hashtable or HashMap from the
// Java collections
// list - Dictionary Structure based on Linked List
// myhash - Dictionary Structure based on a Hashtable implemented by the
// students
// bst - Dictionary Structure based on a Binary Search Tree implemented
// by the students
// avl - Dictionary Structure based on AVL Tree implemented by the
// students
// HERE WE SELECT THE NECESSARY INDEX
if (mode.equals("hash"))
index = new HashDictionary();
else if (mode.equals("list")) {
// System.out.println("calling list dict");
index = new ListDictionary();
} else if (mode.equals("myhash"))
index = new MyHashDictionary<String, String>();
else if (mode.equals("bst"))
index = new BSTDictionary();
else if (mode.equals("avl"))
index = new AVLDictionary();
}
/**
* Add the given web page to the index.
*
* @param arr
* The web page to add to the index
* @param keywords
* The keywords that are in the web page
* @param links
* The hyperlinks that are in the web page
*/
// HERE WE ADD THE GIVE PAGE TO DICTIONARY
public void addPage(String url, ObjectIterator<?> keywords) {
// //////////////////////////////////////////////////////////////////
// Write your Code here as part of Integrating and Running Mini Google
// assignment
//
// /////////////////////////////////////////////////////////////////
// if(keywords == null) System.out.println("nulll.... ");
// System.out.println(keywords.size());
wordFrequency.clear();
System.out.println(++i + " :" + url);
// System.out.println(keywords.toString());
while (keywords.hasNext() == true) {
String k = (String) keywords.next();
// System.out.println(k);
// System.out.println(wordFrequency.containsKey(k));
if (wordFrequency.containsKey(k)) {
// System.out.println("updating...");
wordFrequency.put(k, (Integer) wordFrequency.get(k) + 1);
} else {
// System.out.println("new...");
wordFrequency.put(k, 1);
}
}
// System.out.println(wordFrequency.size());
for (String s : wordFrequency.keySet()) {
// System.out.println("hi");
// System.out.println("word :"+ s +" = " + wordFrequency.get(s));
// index.insert(url+" "+wordFrequency.get(s), s);
String[] keys = null;
if (firsttime == false) {
// keys = (String[]) index.getKeys();
firsttime = true;
index.insert(s, url + "$" + wordFrequency.get(s));
} else {
// if(keys == null) System.out.println("ewfemw");
keys = (String[]) index.getKeys();
if (!Arrays.asList(keys).contains(s)) {
index.insert(s, url + "$" + wordFrequency.get(s));
} else {
index.insert(s, index.getValue(s) + "," + url + "$"
+ wordFrequency.get(s));
}
}
}
String[] keys = (String[]) index.getKeys();
// System.out.println("length :" + keys.length);
int i = 0;
/*
* while(i<keys.length) { System.out.print(i+1); System.out.println(") "
* +keys[i] +", "+index.getValue(keys[i])); i++; }
*/
}
/**
* Produce a printable representation of the index.
*
* @return a String representation of the index structure
*/
/**
* Retrieve all of the web pages that contain the given keyword.
*
* @param keyword
* The keyword to search on
* @return An iterator of the web pages that match.
*/
// HERE WE RETRIEVE THE KEYWORD URLS FROM THE FILE
public ObjectIterator<?> retrievePages(String keyword, String operator) {
// //////////////////////////////////////////////////////////////////
// Write your Code here as part of Integrating and Running Mini Google
// assignment
//
// /////////////////////////////////////////////////////////////////
HashMap<String, String> temp = new HashMap<String, String>();
String j = null;
String[] p = null;
String s = keyword;
// j = restore.get(s); //we'll get urls here
String[] kk = (String[]) index.getKeys();
for (int i = 0; i < kk.length; i++) {
if (kk[i].equals(keyword)) {
System.out.println("found...");
j = (String) index.getValue(kk[i]);
}
}
System.out.println(s);
// j = (String) index.getValue(s);
System.out.println(j);
if (j != null)
p = j.split(",");
if (rank.isEmpty() && j != null) {
// System.out.println("first time...");
for (String h : p) {
// System.out.println(h);
String[] l = h.split("\\$");
// System.out.println(l[0]);
// System.out.println(l[1]);
String[] temp1 = l[0].split("/");
// System.out.println("length :" + temp1.length);
int t = (Integer.parseInt(l[1]) / temp1.length) * 100;
l[1] = Integer.toString(t);
// System.out.println("rank" + l[0] + " " + l[1]);
rank.put(l[0], l[1]);
}
rank = sortByValue(rank);
for (String k : rank.keySet()) {
sett.add(k);
}
/*
* System.out.println("1"); System.out.println(sett.toString());
*/
// System.out.println(rank.toString());
} else if (j != null) {
more = true;
// System.out.println("another time");
for (String h : p) {
String[] l = h.split("\\$");
String[] temp1 = l[0].split("/");
int t = (Integer.parseInt(l[1]) / temp1.length) * 100;
l[1] = Integer.toString(t);
temp.put(l[0], l[1]);
}
// System.out.println(temp.toString());
temp = sortByValue(temp);
for (String k : temp.keySet()) {
settemp.add(k);
}
// System.out.println("2");
// System.out.println("sett" + sett.toString());
if (operator.equalsIgnoreCase("and"))
sett = (SetImplementation<String>) sett.intersection(settemp);
else if (operator.equalsIgnoreCase("or"))
sett = (SetImplementation<String>) sett.union(settemp);
else if (operator.equalsIgnoreCase("not"))
sett = (SetImplementation<String>) sett.difference(settemp);
// System.out.println(sett.toString());
rank.clear();
// rank = temp;
rank.putAll(temp);
// System.out.println(rank.toString());
temp.clear();
} else if (j == null && operator.equalsIgnoreCase("and")) {
System.out.println(" into null....");
sett.clear();
settemp.clear();
sett.fclear();
settemp.fclear();
// System.out.println("j is null..");
/*
* settemp.clear(); sett = (SetImplementation<String>)
* sett.difference(settemp);
*/
}
return new ObjectIterator<PageElementInterface>(
new Vector<PageElementInterface>());
}
/**
* Retrieve all of the web pages that contain any of the given keywords.
*
* @param keywords
* The keywords to search on
* @return An iterator of the web pages that match.
*
* Calculating the Intersection of the pages here itself
**/
HashMap<String, String> sortByValue(HashMap<String, String> map) {
LinkedList<String> list = new LinkedList(map.entrySet());
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) cleanComparison((((Map.Entry) (o1))
.getValue()).toString()))
.compareTo(cleanComparison((((Map.Entry) (o2))
.getValue()).toString()));
}
});
HashMap<String, String> result = new LinkedHashMap<String, String>();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
result.put((String) entry.getKey(), (String) entry.getValue());
}
return result;
}
String cleanComparison(String s) {
String result = s.toLowerCase();
String[] or = { "á", "é", "í", "ó", "ú", "ä", "ë", "ï", "ö", "ü", "à",
"è", "ì", "ò", "ù" };
String[] res = { "a", "e", "i", "o", "u", "a", "e", "i", "o", "u", "a",
"e", "i", "o", "u" };
for (int i = 0; i < or.length; i++) {
result = result.replace(or[i], res[i]);
}
return result;
}
public ObjectIterator<?> retrievePages(ObjectIterator<?> keywords) {
return null;
}
public ObjectIterator<?> retrievePages(ObjectIterator<?> keywords,
String operator) {
// //////////////////////////////////////////////////////////////////
// Write your Code here as part of Integrating and Running Mini Google
// assignment
//
// /////////////////////////////////////////////////////////////////
boolean firsttime = true;
System.out.println(keywords.size());
while (keywords.hasNext()) {
// System.out.println();
if (firsttime) {
ll = keywords.next().toString();
retrievePages(ll, operator);
firsttime = false;
} else {
operator = keywords.next().toString();
System.out.println("operator :" + operator);
if (operator.equalsIgnoreCase("and")
|| operator.equalsIgnoreCase("or")
|| operator.equalsIgnoreCase("not")) {
if (keywords.hasNext()) {
repeat = ll;
ll = keywords.next().toString();
if (repeat.equals(ll)) {
System.out.println("repeated!!" + repeat);
repeat1 = true;
} else {
System.out.println("not repeated!!" + repeat);
repeat1 = false;
}
System.out.println("string :" + ll);
if (operator.equalsIgnoreCase("and")
|| operator.equalsIgnoreCase("or")
|| operator.equalsIgnoreCase("not")) {
System.out.println("inside...kkk");
if (!repeat1) {
System.out.println("repeat call..");
retrievePages(ll, operator);
}
}
}
} else {
retrievePages(operator, "and");
}
}
}
// System.out.println(rank.toString());
rank = sortByValue(rank);
// System.out.println(rank.toString());
if (noresults == false) {
/*
* int i = 0; for(String k:rank.keySet()) { i++;
* System.out.println(i + ": " + k + " --->" + rank.get(k) +
* " times"); }
*/
}
// System.out.println("set..values" + sett.size());
Iterator<String> l;
if (more) {
l = sett.finaliterator();
} else {
l = sett.iterator();
}
Vector<String> vec = new Vector<String>();
while (l.hasNext()) {
vec.add(l.next());
// System.out.println(l.next());
}
// Vector<String> vec = new Vector<String>();
/*
* System.out.println(); System.out.println();
*/
// SORTING HERE....DONT WORRY............
// Map<String, String> map = new TreeMap<String, String>(rank);
/*
* ArrayList<Integer> kp = new ArrayList<Integer>();
*
* for(Integer t:rank.keySet()) { i++; //System.out.println(i + ". " + t
* + " --> " + rank.get(t)); kp.add(t); }
*
*
*
*
* Collections.sort(kp);
*
* int[] tr = new int[kp.size()];
*
* for(int i=0;i<kp.size();i++) { tr[i] = kp.get(i); }
*
*
*
* for(int i = tr.length-1;i>=0;i--) { //System.out.println(i);
* System.out.println(rank.get((tr[i]))+ "-->" + tr[i] + " times"); }
*/
/*
*
*
* ArrayList<String> sortedKeys=new ArrayList<String>(rank.keySet());
* Collections.sort(sortedKeys);
*
* String[] a = (String[]) sortedKeys.toArray();
*
* for(int i=0;i<a.length;i++) { System.out.println(i + ". " + i+1 +
* " --> " + rank.get(a[i])); }
*/
/*
* int i = 0; System.out.println(map.size()); for(String
* t:rank.keySet()) { i++; System.out.println(i + ". " + t + " --> " +
* rank.get(t)); }
*/
return new ObjectIterator<String>(vec);
}
/**
* Save the index to a file.
*
* @param stream
* The stream to write the index
*/
public void save(FileOutputStream stream) throws IOException {
// //////////////////////////////////////////////////////////////////
// Write your Code here as part of Integrating and Running Mini Google
// assignment
//
// /////////////////////////////////////////////////////////////////
String[] keys = (String[]) index.getKeys();
// System.out.println("length :" + keys.length);
int i = 0;
while (i < keys.length) {
if (keys[i] != null) {
String str = keys[i] + " " + index.getValue(keys[i]) + "\n";
byte[] bytes = str.getBytes();
stream.write(bytes);
i++;
}
}
stream.close();
}
/**
* Restore the index from a file.
*
* @param stream
* The stream to read the index
*/
public void restore(FileInputStream stream) throws IOException {
// //////////////////////////////////////////////////////////////////
// Write your Code here as part of Integrating and Running Mini Google
// assignment
//
// /////////////////////////////////////////////////////////////////
byte[] b = new byte[stream.available()];
stream.read(b);
String s = "";
ArrayList<String> arr = new ArrayList<String>();
for (int i = 0; i < b.length; i++) {
// System.out.print((char)b[i]);
if ((char) b[i] != '\n') {
s = s + (char) b[i];
} else {
arr.add(s);
s = "";
}
}
for (String k : arr) {
// System.out.println(k);
String[] split = k.split(" ");
/*
* if(split.length > 1) restore.put(split[0], split[1]);
*/
// System.out.println(split[0]);
if (split.length > 1)
index.insert(split[0], split[1]);
}
// for(String t:restore.keySet())
// {
// System.out.println("word :"+ t +" = " + restore.get(t));
// }
/*
* String str = b.toString(); System.out.println(str);
*
* String arr[] = str.split("\n");
*
* for(String k:arr) { System.out.println(k); }
*/
}
/*
* Remove Page method not implemented right now
*
* @see searchengine.indexer#removePage(java.net.URL)
*/
public void removePage(URL url) {
}
@Override
public ObjectIterator<?> retrievePages(PageWord keyword) {
// TODO Auto-generated method stub
return null;
}
public void addPage(URL url, ObjectIterator<?> keywords) {
// TODO Auto-generated method stub
}
public String toString() {
// //////////////////////////////////////////////////////////////////
// Write your Code here as part of Integrating and Running Mini Google
// assignment
//
// /////////////////////////////////////////////////////////////////
return "You dont need to implement it\n";
}
public ObjectIterator<?> retrievePages(String keyword) {
return null;
}
};
| apache-2.0 |
arquillian/arquillian-extension-warp | impl/src/main/java/org/jboss/arquillian/warp/impl/utils/net/PortProber.java | 5670 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.jboss.arquillian.warp.impl.utils.net;
import org.jboss.arquillian.warp.impl.utils.Platform;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import static java.lang.Math.max;
import static java.util.concurrent.TimeUnit.SECONDS;
public class PortProber {
private static final Random random = new Random();
private static final EphemeralPortRangeDetector ephemeralRangeDetector;
static {
final Platform current = Platform.getCurrent();
if (current.is(Platform.LINUX)) {
ephemeralRangeDetector = LinuxEphemeralPortRangeDetector.getInstance();
} else if (current.is(Platform.XP)) {
ephemeralRangeDetector = new OlderWindowsVersionEphemeralPortDetector();
} else {
ephemeralRangeDetector = new FixedIANAPortRange();
}
}
public static final int HIGHEST_PORT = 65535;
public static final int START_OF_USER_PORTS = 1024;
private PortProber() {
// Utility class
}
public static int findFreePort() {
for (int i = 0; i < 5; i++) {
int seedPort = createAcceptablePort();
int suggestedPort = checkPortIsFree(seedPort);
if (suggestedPort != -1) {
return suggestedPort;
}
}
throw new RuntimeException("Unable to find a free port");
}
public static Callable<Integer> freeLocalPort(final int port) {
return new Callable<Integer>() {
public Integer call()
throws Exception {
if (checkPortIsFree(port) != -1) {
return port;
}
return null;
}
};
}
/**
* Returns a port that is within a probable free range. <p/> Based on the ports in
* http://en.wikipedia.org/wiki/Ephemeral_ports, this method stays away from all well-known
* ephemeral port ranges, since they can arbitrarily race with the operating system in
* allocations. Due to the port-greedy nature of selenium this happens fairly frequently.
* Staying within the known safe range increases the probability tests will run green quite
* significantly.
*
* @return a random port number
*/
private static int createAcceptablePort() {
synchronized (random) {
final int FIRST_PORT;
final int LAST_PORT;
int freeAbove = HIGHEST_PORT - ephemeralRangeDetector.getHighestEphemeralPort();
int freeBelow = max(0, ephemeralRangeDetector.getLowestEphemeralPort() - START_OF_USER_PORTS);
if (freeAbove > freeBelow) {
FIRST_PORT = ephemeralRangeDetector.getHighestEphemeralPort();
LAST_PORT = 65535;
} else {
FIRST_PORT = 1024;
LAST_PORT = ephemeralRangeDetector.getLowestEphemeralPort();
}
if (FIRST_PORT == LAST_PORT) {
return FIRST_PORT;
}
if (FIRST_PORT > LAST_PORT) {
throw new UnsupportedOperationException("Could not find ephemeral port to use");
}
final int randomInt = random.nextInt();
final int portWithoutOffset = Math.abs(randomInt % (LAST_PORT - FIRST_PORT + 1));
return portWithoutOffset + FIRST_PORT;
}
}
private static int checkPortIsFree(int port) {
ServerSocket socket;
try {
socket = new ServerSocket();
socket.setReuseAddress(true);
socket.bind(new InetSocketAddress("localhost", port));
int localPort = socket.getLocalPort();
socket.close();
return localPort;
} catch (IOException e) {
return -1;
}
}
public static boolean pollPort(int port) {
return pollPort(port, 15, SECONDS);
}
public static boolean pollPort(int port, int timeout, TimeUnit unit) {
long end = System.currentTimeMillis() + unit.toMillis(timeout);
while (System.currentTimeMillis() < end) {
try {
Socket socket = new Socket();
socket.setReuseAddress(true);
socket.bind(new InetSocketAddress("localhost", port));
socket.close();
return true;
} catch (ConnectException e) {
// Ignore this
} catch (UnknownHostException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return false;
}
}
| apache-2.0 |
openweave/openweave-core | src/lib/profiles/heartbeat/WeaveHeartbeatSender.cpp | 19201 | /*
*
* Copyright (c) 2013-2017 Nest Labs, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* This file implements Weave Heartbeat Sender.
*
*/
#include "WeaveHeartbeat.h"
#include <Weave/Support/CodeUtils.h>
#include <Weave/Support/MathUtils.h>
#include <Weave/Profiles/time/WeaveTime.h>
// We want and assume the default managed namespace is Current and that is, explicitly, the managed namespace this code desires.
#include <Weave/Profiles/data-management/DataManagement.h>
namespace nl {
namespace Weave {
namespace Profiles {
namespace Heartbeat {
WeaveHeartbeatSender::WeaveHeartbeatSender()
{
mHeartbeatBase = 0;
mFabricState = NULL;
mExchangeMgr = NULL;
mBinding = NULL;
mExchangeCtx = NULL;
mEventCallback = NULL;
mHeartbeatInterval_msec = 0;
mHeartbeatPhase_msec = 0;
mHeartbeatWindow_msec = 0;
mSubscriptionState = 0;
mRequestAck = false;
}
/**
* Initialize the Weave Heartbeat Sender.
*
* @param[in] exchangeMgr A pointer to the system Weave Exchange Manager.
* @param[in] binding A pointer to a Weave binding object which will be used to address the peer node.
* @param[in] eventCallback A pointer to a function that will be called to notify the application of events or
* state changes that occur in the sender.
* @param[in] appState A pointer to application-specific data. This pointer will be returned in callbacks
* to the application.
*
* @retval #WEAVE_ERROR_INCORRECT_STATE If the WeaveHeartbeatSender object has already been initialized.
* @retval #WEAVE_ERROR_INVALID_ARGUMENT If any of the supplied arguments is null.
* @retval #WEAVE_NO_ERROR On success.
*/
WEAVE_ERROR WeaveHeartbeatSender::Init(WeaveExchangeManager *exchangeMgr, Binding *binding, EventCallback eventCallback, void *appState)
{
WEAVE_ERROR err = WEAVE_NO_ERROR;
VerifyOrExit(mExchangeMgr == NULL, err = WEAVE_ERROR_INCORRECT_STATE);
VerifyOrExit(exchangeMgr != NULL, err = WEAVE_ERROR_INVALID_ARGUMENT);
VerifyOrExit(binding != NULL, err = WEAVE_ERROR_INVALID_ARGUMENT);
VerifyOrExit(eventCallback != NULL, err = WEAVE_ERROR_INVALID_ARGUMENT);
AppState = appState;
mHeartbeatBase = 0;
mFabricState = exchangeMgr->FabricState;
mExchangeMgr = exchangeMgr;
mBinding = binding;
binding->AddRef();
mExchangeCtx = NULL;
mEventCallback = eventCallback;
mHeartbeatInterval_msec = 0;
mHeartbeatPhase_msec = 0;
mHeartbeatWindow_msec = 0;
mSubscriptionState = 0;
mRequestAck = false;
// Set the protocol callback on the binding object. NOTE: This should only happen once the
// app has explicitly started the subscription process by calling either InitiateSubscription() or
// InitiateCounterSubscription(). Otherwise the client object might receive callbacks from
// the binding before it's ready.
mBinding->SetProtocolLayerCallback(BindingEventCallback, this);
#if DEBUG
// Verify that the application's event callback function correctly calls the default handler.
//
// NOTE: If your code receives WEAVE_ERROR_DEFAULT_EVENT_HANDLER_NOT_CALLED it means that the event hander
// function you supplied does not properly call WeaveHeartbeatSender::DefaultEventHandler for unrecognized/
// unhandled events.
//
{
InEventParam inParam;
OutEventParam outParam;
inParam.Clear();
inParam.Source = this;
outParam.Clear();
mEventCallback(appState, kEvent_DefaultCheck, inParam, outParam);
VerifyOrExit(outParam.DefaultHandlerCalled, err = WEAVE_ERROR_DEFAULT_EVENT_HANDLER_NOT_CALLED);
}
#endif
exit:
if (err != WEAVE_NO_ERROR)
{
Shutdown();
}
return err;
}
/**
* Shutdown the Weave Heartbeat Sender.
*
* @retval #WEAVE_NO_ERROR On success.
*/
WEAVE_ERROR WeaveHeartbeatSender::Shutdown()
{
if (mExchangeMgr != NULL)
{
StopHeartbeat();
}
if (mExchangeCtx != NULL)
{
mExchangeCtx->Abort();
mExchangeCtx = NULL;
}
if (mBinding != NULL)
{
mBinding->Release();
mBinding = NULL;
}
mExchangeMgr = NULL;
mFabricState = NULL;
mEventCallback = NULL;
return WEAVE_NO_ERROR;
}
/**
* Get heartbeat timing configuration
*
* @param[out] interval A reference to an integer to receive the heartbeat interval.
* @param[out] phase A reference to an integer to receive the heartbeat phase.
* @param[out] window A reference to an integer to receive the heartbeat randomization window.
*
*/
void WeaveHeartbeatSender::GetConfiguration(uint32_t& interval, uint32_t& phase, uint32_t& window) const
{
interval = mHeartbeatInterval_msec;
phase = mHeartbeatPhase_msec;
window = mHeartbeatWindow_msec;
}
/**
* Set heartbeat timing configuration
*
* @param[in] interval Interval to use when sending Weave Heartbeat messages.
* @param[in] phase Phase to use when sending Weave Heartbeat messages.
* @param[in] window Window range to use for choosing random interval
*
*/
void WeaveHeartbeatSender::SetConfiguration(uint32_t interval, uint32_t phase, uint32_t window)
{
mHeartbeatInterval_msec = interval;
mHeartbeatPhase_msec = phase;
mHeartbeatWindow_msec = window;
}
/**
* Start sending Weave Heartbeat messages.
*
* @retval #INET_ERROR_NO_MEMORY if StartTimer() failed
* @retval #WEAVE_NO_ERROR on success
*
*/
WEAVE_ERROR WeaveHeartbeatSender::StartHeartbeat()
{
WEAVE_ERROR err = WEAVE_NO_ERROR;
VerifyOrExit(mHeartbeatInterval_msec > 0, err = WEAVE_ERROR_INCORRECT_STATE);
mHeartbeatBase = GetHeartbeatBase();
err = ScheduleHeartbeat();
exit:
return err;
}
/**
* Schedule sending Weave Heartbeat messages.
*
* @retval WEAVE_SYSTEM_ERROR_NO_MEMORY if StartTimer() failed
* @retval #WEAVE_NO_ERROR on success
*
*/
WEAVE_ERROR WeaveHeartbeatSender::ScheduleHeartbeat()
{
// deltaTicks is mostly +ve and less than mHeartbeatInterval_msec since heartbeatBase is one interval ahead
int32_t deltaTicks = (int32_t)(mHeartbeatBase - GetPlatformTimeMs());
int32_t interval = deltaTicks + mHeartbeatPhase_msec + GetRandomInterval(0, mHeartbeatWindow_msec);
// Update the mHeartBeatBase after the interval has been calculated so as to not
// add the heartbeat interval twice to the base (causing heartbeat to be missed at the
// first interval).
mHeartbeatBase += mHeartbeatInterval_msec;
// Bounds check for interval
if (interval < 0)
interval = 0;
return mExchangeMgr->MessageLayer->SystemLayer->StartTimer(static_cast<uint32_t>(interval), HandleHeartbeatTimer, this);
}
/**
* Stop sending Weave Heartbeat messages.
*
* @retval #WEAVE_NO_ERROR unconditionally
*
*/
WEAVE_ERROR WeaveHeartbeatSender::StopHeartbeat()
{
mExchangeMgr->MessageLayer->SystemLayer->CancelTimer(HandleHeartbeatTimer, this);
return WEAVE_NO_ERROR;
}
/**
* Send a Weave Heartbeat message now.
*
* @retval #WEAVE_ERROR_INCORRECT_STATE if WeaveHeartbeatSender is not initialized
* @retval #WEAVE_NO_ERROR on success
*
*/
WEAVE_ERROR WeaveHeartbeatSender::SendHeartbeatNow()
{
WEAVE_ERROR err = WEAVE_NO_ERROR;
const bool scheduleNextHeartbeat = true;
VerifyOrExit(mExchangeMgr != NULL, err = WEAVE_ERROR_INCORRECT_STATE);
SendHeartbeat(!scheduleNextHeartbeat);
exit:
return err;
}
/**
* Get epoch time base for Weave Heartbeat messages.
*
*/
uint64_t WeaveHeartbeatSender::GetHeartbeatBase()
{
uint64_t now = GetPlatformTimeMs();
// Divide 64-bit now in msec by 1000 and return 32-bit now in sec
uint32_t now_sec = Platform::DivideBy1000(now);
// Convert heartbeat interval to sec
uint32_t interval_sec = mHeartbeatInterval_msec / 1000;
// Aligned to the next heartbeat interval
return 1000ULL * (now_sec / interval_sec + 1) * interval_sec;
}
/**
* Get UTC time or monotonic time in ms if UTC time not available
*/
uint64_t WeaveHeartbeatSender::GetPlatformTimeMs(void)
{
WEAVE_ERROR err;
uint64_t now_ms;
err = System::Layer::GetClock_RealTimeMS(now_ms);
if (err != WEAVE_SYSTEM_NO_ERROR || now_ms == 0)
{
now_ms = System::Layer::GetClock_MonotonicMS();
}
return now_ms;
}
/**
* Get random interval within a target range for a Weave Heartbeat
*
* @param[in] minVal Min value of the target range
* @param[in] maxVal Max value of the target range
*
* @retval #WEAVE_NO_ERROR A random value within the target range
*
*/
uint32_t WeaveHeartbeatSender::GetRandomInterval(uint32_t minVal, uint32_t maxVal)
{
const uint32_t range = maxVal - minVal + 1;
const uint32_t buckets = RAND_MAX / range;
const uint32_t limit = buckets * range;
uint32_t r;
do
{
r = rand();
} while (r >= limit);
return minVal + (r / buckets);
}
/**
* Send a Weave Heartbeat message when the timer fires.
*
*/
void WeaveHeartbeatSender::HandleHeartbeatTimer(System::Layer* aSystemLayer, void* aAppState, System::Error aError)
{
const bool scheduleNextHeartbeat = true;
WeaveHeartbeatSender* sender = reinterpret_cast<WeaveHeartbeatSender*>(aAppState);
sender->SendHeartbeat(scheduleNextHeartbeat);
}
/**
* Send Weave Heartbeat messages to the peer.
*/
void WeaveHeartbeatSender::SendHeartbeat(bool scheduleNextHeartbeat)
{
WEAVE_ERROR err = WEAVE_NO_ERROR;
PacketBuffer *payload = NULL;
bool heartbeatSentWithoutACK = false;
// Abort any existing exchange that is still in progress. In practice this should never be necessary.
// However if the application configures the total WRM retry time longer than the heartbeat interval
// we don't want to allow exchanges to pile up.
if (mExchangeCtx != NULL)
{
mExchangeCtx->Abort();
mExchangeCtx = NULL;
}
// Schedule the next heartbeat if requested.
if (scheduleNextHeartbeat)
{
err = ScheduleHeartbeat();
SuccessOrExit(err);
}
// If the binding is NOT ready, but is in a state where it can be prepared...
if (mBinding->CanBePrepared())
{
// Ask the application to prepare the binding by delivering a PrepareRequested API event to it via the
// binding's callback. At some point the binding will call back to the WeaveHeartbeatSender object
// signaling that preparation has completed (successfully or otherwise). In the success case, the
// callback will cause SendHeartbeat() to be called again, at which point the heartbeat message will
// be sent.
//
// Note that the callback from the binding can happen synchronously within the RequestPrepare() method,
// implying that SendHeartbeat() will recurse.
//
err = mBinding->RequestPrepare();
SuccessOrExit(err);
// Wait for the binding to call back.
ExitNow();
}
// If the binding is in the process of being prepared, wait for it to call us back.
if (mBinding->IsPreparing())
{
ExitNow();
}
// Verify that the binding is ready to be used. Based on the above checks, if the binding is NOT in the
// ready state then it is not possible to proceed.
VerifyOrExit(mBinding->IsReady(), err = WEAVE_ERROR_INCORRECT_STATE);
// Call back to the application to update the subscription state value. If the application
// chooses not to handle this event the current value will be used.
{
InEventParam inParam;
OutEventParam outParam;
inParam.Clear();
inParam.Source = this;
outParam.Clear();
mEventCallback(AppState, kEvent_UpdateSubscriptionState, inParam, outParam);
}
// Allocate a packet buffer to hold the heartbeat message.
payload = PacketBuffer::NewWithAvailableSize(kHeartbeatMessageLength);
VerifyOrExit(payload != NULL, err = WEAVE_ERROR_NO_MEMORY);
// Encode the heartbeat message.
nl::Weave::Encoding::Put8(payload->Start(), mSubscriptionState);
payload->SetDataLength(kHeartbeatMessageLength);
// Allocate and initialize a new exchange context for sending the heartbeat message.
err = mBinding->NewExchangeContext(mExchangeCtx);
SuccessOrExit(err);
mExchangeCtx->AppState = this;
#if WEAVE_CONFIG_ENABLE_RELIABLE_MESSAGING
// If the application requested reliable transmission, arrange to request an ACK for the heartbeat message.
// Note that if the application configured the binding to use WRM, then an ACK will always be requested
// regardless of the state of the SendReliably flag.
if (mRequestAck)
mExchangeCtx->SetAutoRequestAck(true);
// Setup callbacks for ACK received and WRM send errors.
mExchangeCtx->OnAckRcvd = HandleAckReceived;
mExchangeCtx->OnSendError = HandleSendError;
#endif
// Send the heartbeat message to the peer.
err = mExchangeCtx->SendMessage(kWeaveProfile_Heartbeat, kHeartbeatMessageType_Heartbeat, payload);
payload = NULL;
SuccessOrExit(err);
heartbeatSentWithoutACK = !mExchangeCtx->AutoRequestAck();
exit:
// Discard the packet buffer if necessary.
if (payload != NULL)
{
PacketBuffer::Free(payload);
}
// If a heartbeat message was successfully sent WITHOUT requesting an ACK
// OR if an error occurred while trying to send a heartbeat...
if (heartbeatSentWithoutACK || err != WEAVE_NO_ERROR)
{
InEventParam inParam;
OutEventParam outParam;
// Discard the exchange context, as it is no longer needed.
if (mExchangeCtx != NULL)
{
mExchangeCtx->Abort();
mExchangeCtx = NULL;
}
// Deliver either a HeartbeatSent or HeartbeatFailed event to the application based on what happened.
inParam.Clear();
inParam.Source = this;
inParam.HeartbeatFailed.Reason = err;
outParam.Clear();
EventType eventType = (err == WEAVE_NO_ERROR) ? kEvent_HeartbeatSent : kEvent_HeartbeatFailed;
mEventCallback(AppState, eventType, inParam, outParam);
}
}
/**
* Default handler function for WeaveHeartbeatSender API events.
*
* Applications must call this function for any API events that they don't handle.
*/
void WeaveHeartbeatSender::DefaultEventHandler(void *appState, EventType eventType, const InEventParam& inParam, OutEventParam& outParam)
{
// No specific behavior currently required.
outParam.DefaultHandlerCalled = true;
}
/**
* Handle events from the binding object associated with the WeaveHeartbeatSender.
*/
void WeaveHeartbeatSender::BindingEventCallback(void *appState, Binding::EventType eventType, const Binding::InEventParam& inParam, Binding::OutEventParam& outParam)
{
const bool scheduleNextHeartbeat = true;
WeaveHeartbeatSender *sender = (WeaveHeartbeatSender *)appState;
switch (eventType)
{
case Binding::kEvent_BindingReady:
// Binding is ready. So send the heartbeat now.
sender->SendHeartbeat(!scheduleNextHeartbeat);
break;
case Binding::kEvent_PrepareFailed:
{
InEventParam senderInParam;
OutEventParam senderOutParam;
senderInParam.Clear();
senderInParam.Source = sender;
senderInParam.HeartbeatFailed.Reason = inParam.PrepareFailed.Reason;
senderOutParam.Clear();
// Deliver a HeartBeat failed event to the application.
sender->mEventCallback(sender->AppState, kEvent_HeartbeatFailed, senderInParam, senderOutParam);
break;
}
default:
Binding::DefaultEventHandler(appState, eventType, inParam, outParam);
}
}
/**
* Handle the reception of a WRM acknowledgment for a heartbeat message that was sent reliably.
*/
void WeaveHeartbeatSender::HandleAckReceived(ExchangeContext *ec, void *msgCtxt)
{
WeaveHeartbeatSender *sender = (WeaveHeartbeatSender *)ec->AppState;
InEventParam inParam;
OutEventParam outParam;
VerifyOrDie(sender->mExchangeCtx == ec);
sender->mExchangeCtx->Abort();
sender->mExchangeCtx = NULL;
inParam.Clear();
inParam.Source = sender;
outParam.Clear();
sender->mEventCallback(sender->AppState, kEvent_HeartbeatSent, inParam, outParam);
}
/**
* Handle a failure to transmit a heartbeat message that was sent reliably.
*/
void WeaveHeartbeatSender::HandleSendError(ExchangeContext *ec, WEAVE_ERROR err, void *msgCtxt)
{
WeaveHeartbeatSender *sender = (WeaveHeartbeatSender *)ec->AppState;
InEventParam inParam;
OutEventParam outParam;
VerifyOrDie(sender->mExchangeCtx == ec);
sender->mExchangeCtx->Abort();
sender->mExchangeCtx = NULL;
inParam.Clear();
inParam.Source = sender;
inParam.HeartbeatFailed.Reason = err;
outParam.Clear();
sender->mEventCallback(sender->AppState, kEvent_HeartbeatFailed, inParam, outParam);
}
/**
* @fn Binding *WeaveHeartbeatSender::GetBinding() const
*
* Get the binding object associated with heartbeat sender.
*/
/**
* @fn bool WeaveHeartbeatSender::GetRequestAck() const
*
* Returns a flag indicating whether heartbeat messages will be sent reliably using Weave Reliable Messaging.
*/
/**
* @fn void WeaveHeartbeatSender::SetRequestAck(bool val)
*
* Sets a flag indicating whether heartbeat messages should be sent reliably using Weave Reliable Messaging.
*
* Note that this flag is only meaningful when using UDP as a transport.
*
* @param[in] val True if heartbeat messages should be sent reliably.
*/
/**
* @fn uint8_t WeaveHeartbeatSender::GetSubscriptionState() const
*
* Get the current subscription state value.
*/
/**
* @fn void WeaveHeartbeatSender::SetSubscriptionState(uint8_t val)
*
* Set the current subscription state.
*
* @param[in] val An 8-bit subscription state value to be conveyed with the heartbeat message.
*/
/**
* @fn WeaveHeartbeatSender::EventCallback WeaveHeartbeatSender::GetEventCallback() const
*
* Returns the function that will be called to notify the application of events or changes that occur in the
* WeaveHeartbeatSender.
*/
/**
* @fn void WeaveHeartbeatSender::SetEventCallback(EventCallback eventCallback)
*
* Sets the function that will be called to notify the application of events or changes that occur in the
* WeaveHeartbeatSender.
*/
} // namespace Heartbeat
} // namespace Profiles
} // namespace Weave
} // namespace nl
| apache-2.0 |
kubernetes/autoscaler | cluster-autoscaler/cloudprovider/aws/instance_type_cache.go | 2946 | /*
Copyright 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package aws
import (
"sync"
"time"
"k8s.io/apimachinery/pkg/util/rand"
"k8s.io/client-go/tools/cache"
"k8s.io/utils/clock"
)
const (
asgInstanceTypeCacheTTL = time.Minute * 20
cacheMinTTL = 120
cacheMaxTTL = 600
)
// instanceTypeExpirationStore caches the canonical instance type for an ASG.
// The store expires its keys based on a TTL. This TTL can have a jitter applied to it.
// This allows to get a better repartition of the AWS queries.
type instanceTypeExpirationStore struct {
cache.Store
jitterClock clock.Clock
awsService *awsWrapper
}
type instanceTypeCachedObject struct {
name string
instanceType string
}
type jitterClock struct {
clock.Clock
jitter bool
sync.RWMutex
}
func newAsgInstanceTypeCache(awsService *awsWrapper) *instanceTypeExpirationStore {
jc := &jitterClock{}
return newAsgInstanceTypeCacheWithClock(
awsService,
jc,
cache.NewExpirationStore(func(obj interface{}) (s string, e error) {
return obj.(instanceTypeCachedObject).name, nil
}, &cache.TTLPolicy{
TTL: asgInstanceTypeCacheTTL,
Clock: jc,
}),
)
}
func newAsgInstanceTypeCacheWithClock(awsService *awsWrapper, jc clock.Clock, store cache.Store) *instanceTypeExpirationStore {
return &instanceTypeExpirationStore{
store,
jc,
awsService,
}
}
func (c *jitterClock) Since(ts time.Time) time.Duration {
since := time.Since(ts)
c.RLock()
defer c.RUnlock()
if c.jitter {
return since + (time.Second * time.Duration(rand.IntnRange(cacheMinTTL, cacheMaxTTL)))
}
return since
}
func (es instanceTypeExpirationStore) populate(autoscalingGroups []*asg) error {
asgsToQuery := []*asg{}
if c, ok := es.jitterClock.(*jitterClock); ok {
c.Lock()
c.jitter = true
c.Unlock()
}
for _, asg := range autoscalingGroups {
if asg == nil {
continue
}
_, found, _ := es.GetByKey(asg.AwsRef.Name)
if found {
continue
}
asgsToQuery = append(asgsToQuery, asg)
}
if c, ok := es.jitterClock.(*jitterClock); ok {
c.Lock()
c.jitter = false
c.Unlock()
}
// List expires old entries
_ = es.List()
instanceTypesByAsg, err := es.awsService.getInstanceTypesForAsgs(asgsToQuery)
if err != nil {
return err
}
for asgName, instanceType := range instanceTypesByAsg {
es.Add(instanceTypeCachedObject{
name: asgName,
instanceType: instanceType,
})
}
return nil
}
| apache-2.0 |
jbosgi/jbosgi-resolver | api/src/main/java/org/jboss/osgi/resolver/spi/AbstractWiring.java | 9910 | /*
* #%L
* JBossOSGi Resolver API
* %%
* Copyright (C) 2010 - 2012 JBoss by Red Hat
* %%
* 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 org.jboss.osgi.resolver.spi;
import static org.jboss.osgi.resolver.ResolverMessages.MESSAGES;
import static org.osgi.framework.namespace.IdentityNamespace.IDENTITY_NAMESPACE;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.jboss.osgi.resolver.XCapability;
import org.jboss.osgi.resolver.XPackageRequirement;
import org.jboss.osgi.resolver.XResource;
import org.jboss.osgi.resolver.XWire;
import org.jboss.osgi.resolver.XWiring;
import org.osgi.framework.namespace.HostNamespace;
import org.osgi.resource.Capability;
import org.osgi.resource.Namespace;
import org.osgi.resource.Requirement;
import org.osgi.resource.Wire;
import org.osgi.resource.Wiring;
import org.osgi.service.resolver.HostedCapability;
/**
* The abstract implementation of a {@link Wiring}.
*
* @author thomas.diesler@jboss.com
* @since 02-Jul-2010
*/
public class AbstractWiring implements XWiring {
private final XResource resource;
private final List<Wire> required = new ArrayList<Wire>();
private final Map<String, List<Wire>> provided = new HashMap<String, List<Wire>>();
public AbstractWiring(XResource resource, List<Wire> reqwires, List<Wire> provwires) {
if (resource == null)
throw MESSAGES.illegalArgumentNull("resource");
this.resource = resource;
synchronized (this) {
// Necessary to guard collections post-construction
if (reqwires != null) {
for (Wire wire : reqwires) {
addRequiredWire(wire);
}
}
if (provwires != null) {
for (Wire wire : provwires) {
addProvidedWire(wire);
}
}
}
}
@Override
public XResource getResource() {
return resource;
}
@Override
public boolean isEffective() {
return resource.getWiringSupport().isEffective();
}
@Override
public void addRequiredWire(Wire wire) {
synchronized (required) {
if (wire instanceof AbstractWire) {
((XWire) wire).setRequirerWiring(this);
}
required.add(wire);
}
}
@Override
public void addProvidedWire(Wire wire) {
synchronized (this) {
if (wire instanceof AbstractWire) {
((XWire) wire).setProviderWiring(this);
}
Capability cap = wire.getCapability();
List<Wire> nswires = provided.get(cap.getNamespace());
if (nswires == null) {
nswires = new ArrayList<Wire>();
provided.put(cap.getNamespace(), nswires);
}
// Ensures an implementation delivers a bundle wiring's provided
// wires
// in
// the proper order. The ordering rules are as follows.
//
// (1) For a given name space, the list contains the wires in the
// order
// the
// capabilities were specified in the manifests of the bundle
// revision
// and
// the attached fragments of this bundle wiring.
//
// (2) There is no ordering defined between wires in different
// namespaces.
//
// (3) There is no ordering defined between multiple wires for the
// same
// capability, but the wires must be contiguous, and the group must
// be
// ordered as in (1).
int index = 0;
if (nswires.size() > 0) {
int capindex = getCapabilityIndex(cap);
for (Wire aux : nswires) {
int auxindex = getCapabilityIndex(aux.getCapability());
if (auxindex < capindex) {
index++;
}
}
}
nswires.add(index, wire);
}
}
private int getCapabilityIndex(Capability cap) {
return getResource().getCapabilities(cap.getNamespace()).indexOf(cap);
}
@Override
public List<Capability> getResourceCapabilities(String namespace) {
List<Capability> result = new ArrayList<Capability>(resource.getCapabilities(namespace));
synchronized (this) {
// Add capabilities from attached fragments
for (Wire wire : getProvidedResourceWires(HostNamespace.HOST_NAMESPACE)) {
for (Capability cap : wire.getRequirer().getCapabilities(namespace)) {
// The osgi.identity capability provided by attached
// fragment
// must not be included in the capabilities of the host
// wiring
if (IDENTITY_NAMESPACE.equals(cap.getNamespace())) {
continue;
}
result.add(cap);
}
}
}
// Remove unwanted caps
Iterator<Capability> capit = result.iterator();
while (capit.hasNext()) {
boolean removed = false;
XCapability cap = (XCapability) capit.next();
XResource res = cap.getResource();
// Capabilities with {@link
// Namespace#CAPABILITY_EFFECTIVE_DIRECTIVE}
// not equal to {@link Namespace#EFFECTIVE_RESOLVE} are not
// returned
String effdir = cap.getDirectives().get(Namespace.CAPABILITY_EFFECTIVE_DIRECTIVE);
if (effdir != null && !effdir.equals(Namespace.EFFECTIVE_RESOLVE)) {
capit.remove();
removed = true;
}
// A package declared to be both exported and imported,
// only one is selected and the other is discarded
if (!removed) {
String capns = cap.getNamespace();
Object capval = cap.getAttributes().get(capns);
for (Wire wire : required) {
Capability wirecap = wire.getCapability();
Object wirecapval = wirecap.getAttributes().get(wirecap.getNamespace());
if (capns.equals(wirecap.getNamespace()) && capval.equals(wirecapval)) {
capit.remove();
removed = true;
break;
}
}
}
// Remove identity capability for fragments
String type = res.getIdentityCapability().getType();
if (!removed && IDENTITY_NAMESPACE.equals(cap.getNamespace()) && XResource.TYPE_FRAGMENT.equals(type)) {
capit.remove();
removed = true;
}
}
return Collections.unmodifiableList(result);
}
protected HostedCapability getHostedCapability(XCapability cap) {
return new AbstractHostedCapability(resource, cap);
}
@Override
public List<Requirement> getResourceRequirements(String namespace) {
List<Requirement> result = new ArrayList<Requirement>();
synchronized (this) {
for (Wire wire : getRequiredResourceWires(namespace)) {
// A fragment may have multiple wire for the same host
// requirement
Requirement req = wire.getRequirement();
if (!result.contains(req)) {
result.add(req);
}
}
// Add dynamic package requirements that are not included already
for (Requirement req : getResource().getRequirements(namespace)) {
if (req instanceof XPackageRequirement) {
XPackageRequirement preq = (XPackageRequirement) req;
if (preq.isDynamic() && !result.contains(req)) {
result.add(req);
}
}
}
}
return Collections.unmodifiableList(result);
}
@Override
public List<Wire> getProvidedResourceWires(String namespace) {
List<Wire> result = new ArrayList<Wire>();
synchronized (this) {
if (namespace != null) {
List<Wire> nswires = provided.get(namespace);
if (nswires != null) {
result.addAll(nswires);
}
} else {
for (List<Wire> wire : provided.values()) {
result.addAll(wire);
}
}
}
return Collections.unmodifiableList(result);
}
@Override
public List<Wire> getRequiredResourceWires(String namespace) {
List<Wire> result = new ArrayList<Wire>();
synchronized (this) {
for (Wire wire : required) {
Requirement req = wire.getRequirement();
if (namespace == null || namespace.equals(req.getNamespace())) {
result.add(wire);
}
}
}
return Collections.unmodifiableList(result);
}
@Override
public String toString() {
return "Wiring[" + resource + "]";
}
}
| apache-2.0 |
volkc/REScala | Examples/examples/src/main/scala/examples/timeElapsing/TimeElapsing.scala | 558 | package examples.timeElapsing
import rescala._
import rescala._
object TimeElapsing extends App {
println("start!")
val tick = Var(0)
val second = Signal{ tick() % 60 }
val minute = Signal{ tick()/60 % 60 }
val hour = Signal{ tick()/(60*60) % 60 }
val day = Signal{ tick()/(60*60*24) % 24 }
// Note, day is still circular. At some point day==0 again
// What if one wants that minutes depend on seconds ?
while(true){
Thread.sleep(0)
println((second.now, minute.now, hour.now, day.now))
tick.set(tick.now + 1)
}
}
| apache-2.0 |
artikcloud/artikcloud-ruby | lib/artikcloud/models/whitelist_result_envelope.rb | 6251 | =begin
#ARTIK Cloud API
#No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
=end
require 'date'
module ArtikCloud
#
class WhitelistResultEnvelope
# Device type id
attr_accessor :dtid
# Page starting position
attr_accessor :offset
# Page size
attr_accessor :count
# Total number or whitelist vdids
attr_accessor :total
# Array of whitelisted vdids
attr_accessor :data
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'dtid' => :'dtid',
:'offset' => :'offset',
:'count' => :'count',
:'total' => :'total',
:'data' => :'data'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'dtid' => :'String',
:'offset' => :'Integer',
:'count' => :'Integer',
:'total' => :'Integer',
:'data' => :'Array<Whitelist>'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v}
if attributes.has_key?(:'dtid')
self.dtid = attributes[:'dtid']
end
if attributes.has_key?(:'offset')
self.offset = attributes[:'offset']
end
if attributes.has_key?(:'count')
self.count = attributes[:'count']
end
if attributes.has_key?(:'total')
self.total = attributes[:'total']
end
if attributes.has_key?(:'data')
if (value = attributes[:'data']).is_a?(Array)
self.data = value
end
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properies with the reasons
def list_invalid_properties
invalid_properties = Array.new
return invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
return true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
dtid == o.dtid &&
offset == o.offset &&
count == o.count &&
total == o.total &&
data == o.data
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[dtid, offset, count, total, data].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = ArtikCloud.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map{ |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| apache-2.0 |
spring-projects/spring-social-twitter | spring-social-twitter/src/main/java/org/springframework/social/twitter/api/ImageSize.java | 938 | /*
* Copyright 2014 the original author or 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.social.twitter.api;
/**
* Enumeration of image sizes supported by Twitter
* @author Craig Walls
*/
public enum ImageSize {
/**
* 24px x 24px
*/
MINI,
/**
* 48px x 48px
*/
NORMAL,
/**
* 73px x 73px
*/
BIGGER,
/**
* The original image size
*/
ORIGINAL
}
| apache-2.0 |
CankingApp/MiniPay | app/src/test/java/com/canking/paydemo/ExampleUnitTest.java | 397 | package com.canking.paydemo;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
lucastheisen/apache-directory-server | protocol-dhcp/src/main/java/org/apache/directory/server/dhcp/options/DhcpOption.java | 11600 | /*
* Copyright 2005 The Apache Software 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.
*
*/
package org.apache.directory.server.dhcp.options;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.directory.server.dhcp.options.dhcp.BootfileName;
import org.apache.directory.server.dhcp.options.dhcp.ClientIdentifier;
import org.apache.directory.server.dhcp.options.dhcp.DhcpMessageType;
import org.apache.directory.server.dhcp.options.dhcp.IpAddressLeaseTime;
import org.apache.directory.server.dhcp.options.dhcp.MaximumDhcpMessageSize;
import org.apache.directory.server.dhcp.options.dhcp.OptionOverload;
import org.apache.directory.server.dhcp.options.dhcp.ParameterRequestList;
import org.apache.directory.server.dhcp.options.dhcp.RebindingTimeValue;
import org.apache.directory.server.dhcp.options.dhcp.RenewalTimeValue;
import org.apache.directory.server.dhcp.options.dhcp.RequestedIpAddress;
import org.apache.directory.server.dhcp.options.dhcp.ServerIdentifier;
import org.apache.directory.server.dhcp.options.dhcp.TftpServerName;
import org.apache.directory.server.dhcp.options.dhcp.UnrecognizedOption;
import org.apache.directory.server.dhcp.options.dhcp.VendorClassIdentifier;
import org.apache.directory.server.dhcp.options.misc.DefaultFingerServers;
import org.apache.directory.server.dhcp.options.misc.DefaultIrcServers;
import org.apache.directory.server.dhcp.options.misc.DefaultWwwServers;
import org.apache.directory.server.dhcp.options.misc.MobileIpHomeAgents;
import org.apache.directory.server.dhcp.options.misc.NbddServers;
import org.apache.directory.server.dhcp.options.misc.NetbiosNameServers;
import org.apache.directory.server.dhcp.options.misc.NetbiosNodeType;
import org.apache.directory.server.dhcp.options.misc.NetbiosScope;
import org.apache.directory.server.dhcp.options.misc.NisDomain;
import org.apache.directory.server.dhcp.options.misc.NisPlusDomain;
import org.apache.directory.server.dhcp.options.misc.NisPlusServers;
import org.apache.directory.server.dhcp.options.misc.NisServers;
import org.apache.directory.server.dhcp.options.misc.NntpServers;
import org.apache.directory.server.dhcp.options.misc.NtpServers;
import org.apache.directory.server.dhcp.options.misc.Pop3Servers;
import org.apache.directory.server.dhcp.options.misc.SmtpServers;
import org.apache.directory.server.dhcp.options.misc.StdaServers;
import org.apache.directory.server.dhcp.options.misc.StreetTalkServers;
import org.apache.directory.server.dhcp.options.misc.VendorSpecificInformation;
import org.apache.directory.server.dhcp.options.misc.XWindowDisplayManagers;
import org.apache.directory.server.dhcp.options.misc.XWindowFontServers;
import org.apache.directory.server.dhcp.options.perhost.DefaultIpTimeToLive;
import org.apache.directory.server.dhcp.options.perhost.IpForwarding;
import org.apache.directory.server.dhcp.options.perhost.MaximumDatagramSize;
import org.apache.directory.server.dhcp.options.perhost.NonLocalSourceRouting;
import org.apache.directory.server.dhcp.options.perhost.PathMtuAgingTimeout;
import org.apache.directory.server.dhcp.options.perhost.PathMtuPlateauTable;
import org.apache.directory.server.dhcp.options.perhost.PolicyFilter;
import org.apache.directory.server.dhcp.options.perinterface.AllSubnetsAreLocal;
import org.apache.directory.server.dhcp.options.perinterface.BroadcastAddress;
import org.apache.directory.server.dhcp.options.perinterface.InterfaceMtu;
import org.apache.directory.server.dhcp.options.perinterface.MaskSupplier;
import org.apache.directory.server.dhcp.options.perinterface.PerformMaskDiscovery;
import org.apache.directory.server.dhcp.options.perinterface.PerformRouterDiscovery;
import org.apache.directory.server.dhcp.options.perinterface.RouterSolicitationAddress;
import org.apache.directory.server.dhcp.options.perinterface.StaticRoute;
import org.apache.directory.server.dhcp.options.tcp.TcpDefaultTimeToLive;
import org.apache.directory.server.dhcp.options.tcp.TcpKeepaliveGarbage;
import org.apache.directory.server.dhcp.options.tcp.TcpKeepaliveInterval;
import org.apache.directory.server.dhcp.options.vendor.BootFileSize;
import org.apache.directory.server.dhcp.options.vendor.CookieServers;
import org.apache.directory.server.dhcp.options.vendor.DomainName;
import org.apache.directory.server.dhcp.options.vendor.DomainNameServers;
import org.apache.directory.server.dhcp.options.vendor.ExtensionsPath;
import org.apache.directory.server.dhcp.options.vendor.HostName;
import org.apache.directory.server.dhcp.options.vendor.ImpressServers;
import org.apache.directory.server.dhcp.options.vendor.LogServers;
import org.apache.directory.server.dhcp.options.vendor.LprServers;
import org.apache.directory.server.dhcp.options.vendor.MeritDumpFile;
import org.apache.directory.server.dhcp.options.vendor.NameServers;
import org.apache.directory.server.dhcp.options.vendor.ResourceLocationServers;
import org.apache.directory.server.dhcp.options.vendor.RootPath;
import org.apache.directory.server.dhcp.options.vendor.Routers;
import org.apache.directory.server.dhcp.options.vendor.SubnetMask;
import org.apache.directory.server.dhcp.options.vendor.SwapServer;
import org.apache.directory.server.dhcp.options.vendor.TimeOffset;
import org.apache.directory.server.dhcp.options.vendor.TimeServers;
import org.apache.directory.server.i18n.I18n;
/**
* The Dynamic Host Configuration Protocol (DHCP) provides a framework
* for passing configuration information to hosts on a TCP/IP network.
* Configuration parameters and other control information are carried in
* tagged data items that are stored in the 'options' field of the DHCP
* message. The data items themselves are also called "options."
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public abstract class DhcpOption
{
/**
* An array of concrete implementations of DhcpOption.
*/
private static Class OPTION_CLASSES[] =
{ BootfileName.class, ClientIdentifier.class, DhcpMessageType.class, IpAddressLeaseTime.class,
MaximumDhcpMessageSize.class, org.apache.directory.server.dhcp.options.dhcp.Message.class,
OptionOverload.class, ParameterRequestList.class, RebindingTimeValue.class, RenewalTimeValue.class,
RequestedIpAddress.class, ServerIdentifier.class, TftpServerName.class, VendorClassIdentifier.class,
ClientIdentifier.class, DhcpMessageType.class, IpAddressLeaseTime.class, MaximumDhcpMessageSize.class,
OptionOverload.class, ParameterRequestList.class, RebindingTimeValue.class, RenewalTimeValue.class,
RequestedIpAddress.class, ServerIdentifier.class, TftpServerName.class, UnrecognizedOption.class,
VendorClassIdentifier.class, DefaultFingerServers.class, DefaultIrcServers.class, DefaultWwwServers.class,
MobileIpHomeAgents.class, NbddServers.class, NetbiosNameServers.class, NetbiosNodeType.class,
NetbiosScope.class, NisDomain.class, NisPlusDomain.class, NisPlusServers.class, NisServers.class,
NntpServers.class, NtpServers.class, Pop3Servers.class, SmtpServers.class, StdaServers.class,
StreetTalkServers.class, VendorSpecificInformation.class, XWindowDisplayManagers.class,
XWindowFontServers.class, DefaultIpTimeToLive.class, IpForwarding.class, MaximumDatagramSize.class,
NonLocalSourceRouting.class, PathMtuAgingTimeout.class, PathMtuPlateauTable.class, PolicyFilter.class,
AllSubnetsAreLocal.class, BroadcastAddress.class, InterfaceMtu.class, MaskSupplier.class,
PerformMaskDiscovery.class, PerformRouterDiscovery.class, RouterSolicitationAddress.class,
StaticRoute.class, TcpDefaultTimeToLive.class, TcpKeepaliveGarbage.class, TcpKeepaliveInterval.class,
BootFileSize.class, CookieServers.class, DomainName.class, DomainNameServers.class, ExtensionsPath.class,
HostName.class, ImpressServers.class, LogServers.class, LprServers.class, MeritDumpFile.class,
NameServers.class, ResourceLocationServers.class, RootPath.class, Routers.class, SubnetMask.class,
SwapServer.class, TimeOffset.class, TimeServers.class, };
/**
* A map of concrete implementations of DhcpOption indexed by tag code.
*/
private static Map OPTION_CLASS_BY_CODE;
/**
* A map of tag codes indexed by OptionClass subclass.
*/
private static Map CODE_BY_CLASS;
static
{
try
{
// initialize the tag-to-class and class-to-tag map
Map classByCode = new HashMap();
Map codeByClass = new HashMap();
for ( int i = 0; i < OPTION_CLASSES.length; i++ )
{
Class c = OPTION_CLASSES[i];
if ( !DhcpOption.class.isAssignableFrom( c ) )
{
throw new RuntimeException( I18n.err( I18n.ERR_639, c ) );
}
DhcpOption o = ( DhcpOption ) c.newInstance();
Integer tagInt = Integer.valueOf( o.getTag() );
classByCode.put( tagInt, c );
codeByClass.put( c, tagInt );
}
OPTION_CLASS_BY_CODE = Collections.unmodifiableMap( classByCode );
CODE_BY_CLASS = Collections.unmodifiableMap( codeByClass );
}
catch ( Exception e )
{
throw new RuntimeException( I18n.err( I18n.ERR_640 ), e );
}
}
public static Class getClassByTag( int tag )
{
return ( Class ) OPTION_CLASS_BY_CODE.get( Integer.valueOf( tag ) );
}
public static int getTagByClass( Class c )
{
return ( ( Integer ) CODE_BY_CLASS.get( c ) ).intValue();
}
/**
* The default data array used for simple (unparsed) options.
*/
private byte[] data;
/**
* Get the option's code tag.
*
* @return byte
*/
public abstract byte getTag();
/**
* Set the data (wire format) from a byte array. The default implementation
* just records the data as a byte array. Subclasses may parse the data into
* something more meaningful.
*
* @param data
*/
public void setData( byte data[] )
{
this.data = data;
}
/**
* Get the data (wire format) into a byte array. Subclasses must provide an
* implementation which serializes the parsed data back into a byte array if
* they override {@link #setData(byte[])}.
*
* @return byte[]
*/
public byte[] getData()
{
return data;
}
public final void writeTo( ByteBuffer out )
{
out.put( getTag() );
// FIXME: handle continuation, i.e. options longer than 128 bytes?
byte data[] = getData();
if ( data.length > 255 )
{
throw new IllegalArgumentException( I18n.err( I18n.ERR_641 ) );
}
out.put( ( byte ) data.length );
out.put( data );
}
}
| apache-2.0 |
BlueBrain/bluima | modules/bluima_topic_models/src/main/scala/ch/epfl/bbp/uima/topicmodels/annotators/IllegalCharacterSequenceAnnotator.scala | 2094 | package ch.epfl.bbp.uima.topicmodels.annotators
import org.apache.uima.UimaContext
import org.apache.uima.fit.util.JCasUtil
import org.apache.uima.jcas.JCas
import scala.collection.immutable.HashSet
import org.apache.uima.analysis_component.JCasAnnotator_ImplBase
import de.julielab.jules.types.Token
import scala.collection.JavaConversions._
import ch.epfl.bbp.uima.types.Noise
/**
* Marks tokens containing illegal character sequences with the Noise annotation
*
* Note, that if the character sequences contain whitespaces such as " " or "\t" they are removed by the UIMA framework.
*/
//@TypeCapability(inputs = Array(ch.epfl.bbp.uima.types.Token), outputs = Array(ch.epfl.bbp.uima.types.Noise))
class IllegalCharacterSequenceAnnotator extends JCasAnnotator_ImplBase {
private var characterBlackList: Set[String] = null
override def initialize(context: UimaContext) {
super.initialize(context)
val blacklist = context.getConfigParameterValue(IllegalCharacterSequenceAnnotator.CharacterBlackList)
if(blacklist == null)
AnnotatorUtils.getLogger.warn("No blacklist set in IllegalCharacterAnnotator!")
val list = if (blacklist != null) blacklist.asInstanceOf[Array[String]] else Array.empty[String]
val whitespace = AnnotatorUtils.getBooleanParamFromContext(context, IllegalCharacterSequenceAnnotator.IncludeWhiteSpace, false, false)
characterBlackList = (new HashSet() ++ list) ++ (if(whitespace) " " :: "\t" :: Nil else Nil)
}
override def process(doc: JCas) {
val tokens = JCasUtil.select(doc, classOf[Token])
for (t <- tokens) {
val tokenStr = t.getCoveredText.toLowerCase
if (characterBlackList.exists(tokenStr.contains(_))) {
(new Noise(doc, t.getBegin, t.getEnd())).addToIndexes
}
}
}
}
object IllegalCharacterSequenceAnnotator {
val CharacterBlackList = "characterblackList" // (String Array) List of character sequences not allowed to appear in any token.
val IncludeWhiteSpace = "includewhitespace" // (Boolean) also marks tokens if they contain whitespaces such as " " or "\t"
} | apache-2.0 |
AppGeo/GPV | WebApp/MarkupPanel.ascx.cs | 3128 | // Copyright 2012 Applied Geographics, 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Web.UI.HtmlControls;
public partial class MarkupPanel : System.Web.UI.UserControl
{
public void Initialize(Configuration config, AppState appState, Configuration.ApplicationRow application)
{
using (OleDbConnection connection = AppContext.GetDatabaseConnection())
{
LoadMarkupCategories(application, appState, connection);
if (AppAuthentication.Mode != AuthenticationMode.None)
{
tboMarkupUser.Attributes["value"] = AppUser.GetDisplayName(connection);
tboMarkupUser.Attributes["disabled"] = "disabled";
chkMarkupLock.Style["visibility"] = "visible";
labMarkupLock.Style["visibility"] = "visible";
cmdNewMarkup.CssClass = cmdNewMarkup.CssClass.Replace("btnControlLock", "");
}
}
}
private void LoadMarkupCategories(Configuration.ApplicationRow application, AppState appState, OleDbConnection connection)
{
bool selected = false;
foreach (Configuration.ApplicationMarkupCategoryRow link in application.GetApplicationMarkupCategoryRows())
{
string roles = link.MarkupCategoryRow.IsAuthorizedRolesNull() ? "public" : link.MarkupCategoryRow.AuthorizedRoles;
if (AppUser.RoleIsInList(roles, connection))
{
HtmlGenericControl option = new HtmlGenericControl("option");
option.Attributes["value"] = link.CategoryID;
option.InnerText = link.MarkupCategoryRow.DisplayName;
if (link.CategoryID == appState.MarkupCategory)
{
option.Attributes["selected"] = "selected";
selected = true;
}
ddlMarkupCategory.Controls.Add(option);
}
}
if (!selected)
{
appState.MarkupCategory = "";
appState.MarkupGroups = new StringCollection();
if (ddlMarkupCategory.Controls.Count > 0)
{
appState.MarkupCategory = ((HtmlGenericControl)ddlMarkupCategory.Controls[0]).Attributes["value"];
}
}
}
private bool SetDefaultTool(string name)
{
HtmlControl defaultTool = Page.FindControl("opt" + name, false) as HtmlControl;
bool found = defaultTool != null;
if (found)
{
defaultTool.Attributes["class"] += " Selected";
}
return found;
}
private void ShowError(string message)
{
Session["StartError"] = message;
Server.Transfer("StartViewer.aspx");
}
}
| apache-2.0 |
hirohanin/pig7hadoop21 | contrib/piggybank/java/src/test/java/org/apache/pig/piggybank/test/storage/TestHiveColumnarLoader.java | 9972 | /**
* 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.pig.piggybank.test.storage;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import junit.framework.TestCase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocalFileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.io.RCFile;
import org.apache.hadoop.hive.ql.io.RCFileOutputFormat;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.hive.serde2.columnar.BytesRefArrayWritable;
import org.apache.hadoop.hive.serde2.columnar.BytesRefWritable;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.DefaultCodec;
import org.apache.pig.ExecType;
import org.apache.pig.FuncSpec;
import org.apache.pig.PigServer;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.junit.Assert;
import org.junit.Test;
public class TestHiveColumnarLoader extends TestCase{
static Configuration conf = new Configuration();
static File simpleDataFile = null;
static File datePartitionedDir = null;
//used for cleanup
static List<String> datePartitionedRCFiles;
static List<String> datePartitionedDirs;
static private FileSystem fs;
static int columnMaxSize = 30;
static int columnCount = 3;
static int simpleRowCount = 10;
static String endingDate = null;
static String startingDate = null;
static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
static Calendar calendar = null;
static int datePartitionedRowCount;
@Override
public synchronized void setUp() throws Exception {
fs = LocalFileSystem.getLocal(conf);
produceSimpleData();
produceDatePartitionedData();
}
@Override
public void tearDown(){
deletePartitionedDirs(datePartitionedDir);
datePartitionedDir.delete();
}
private void deletePartitionedDirs(File file){
if(file.isDirectory()){
File[] children = file.listFiles();
if(children != null){
for(File child : children){
deletePartitionedDirs(child);
}
}
}
file.delete();
}
@Test
public void test1DayDatePartitionedFilesWithProjection() throws IOException{
int count = 0;
String funcSpecString = "org.apache.pig.piggybank.storage.HiveColumnarLoader('f1 string,f2 string,f3 string'" +
", '" + startingDate + ":" + startingDate + "')";
System.out.println(funcSpecString);
PigServer server = new PigServer(ExecType.LOCAL);
server.setBatchOn();
server.registerFunction("org.apache.pig.piggybank.storage.HiveColumnarLoader", new FuncSpec(funcSpecString));
server.registerQuery("a = LOAD '" + datePartitionedDir.getAbsolutePath() + "' using " + funcSpecString + ";");
server.registerQuery("b = FOREACH a GENERATE f2 as p;");
Iterator<Tuple> result = server.openIterator("b");
Tuple t = null;
while( (t = result.next()) != null) {
assertEquals(1, t.size());
assertEquals(DataType.CHARARRAY, t.getType(0));
count++;
}
Assert.assertEquals(50, count);
}
@Test
public void test1DayDatePartitionedFiles() throws IOException{
int count = 0;
String funcSpecString = "org.apache.pig.piggybank.storage.HiveColumnarLoader('f1 string,f2 string,f3 string'" +
", '" + startingDate + ":" + startingDate + "')";
System.out.println(funcSpecString);
PigServer server = new PigServer(ExecType.LOCAL);
server.setBatchOn();
server.registerFunction("org.apache.pig.piggybank.storage.HiveColumnarLoader", new FuncSpec(funcSpecString));
server.registerQuery("a = LOAD '" + datePartitionedDir.getAbsolutePath() + "' using " + funcSpecString + ";");
Iterator<Tuple> result = server.openIterator("a");
while( (result.next()) != null){
count++;
}
Assert.assertEquals(50, count);
}
@Test
public void testDatePartitionedFiles() throws IOException{
int count = 0;
String funcSpecString = "org.apache.pig.piggybank.storage.HiveColumnarLoader('f1 string,f2 string,f3 string'"
+ ", '" + startingDate + ":" + endingDate + "')";
System.out.println(funcSpecString);
PigServer server = new PigServer(ExecType.LOCAL);
server.setBatchOn();
server.registerFunction("org.apache.pig.piggybank.storage.HiveColumnarLoader", new FuncSpec(funcSpecString));
server.registerQuery("a = LOAD '" + datePartitionedDir.getAbsolutePath() + "' using " + funcSpecString + ";");
Iterator<Tuple> result = server.openIterator("a");
while( (result.next()) != null){
count++;
}
Assert.assertEquals(datePartitionedRowCount, count);
}
private static void produceDatePartitionedData() throws IOException {
datePartitionedRowCount = 0;
datePartitionedDir = new File("testhiveColumnarLoader-dateDir-" + System.currentTimeMillis());
datePartitionedDir.mkdir();
datePartitionedDir.deleteOnExit();
int dates = 4;
calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, Calendar.MONDAY);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
startingDate = dateFormat.format(calendar.getTime());
datePartitionedRCFiles = new ArrayList<String>();
datePartitionedDirs = new ArrayList<String>();
for(int i = 0; i < dates; i++){
File file = new File(datePartitionedDir, "daydate=" + dateFormat.format(calendar.getTime()));
calendar.add(Calendar.DAY_OF_MONTH, 1);
file.mkdir();
file.deleteOnExit();
//for each daydate write 5 partitions
for(int pi = 0; pi < 5; pi++){
Path path = new Path(new Path(file.getAbsolutePath()),
"parition" + pi);
datePartitionedRowCount +=
writeRCFileTest(fs, simpleRowCount, path, columnCount, new DefaultCodec(), columnCount);
new File(path.toString()).deleteOnExit();
datePartitionedRCFiles.add(path.toString());
datePartitionedDirs.add(file.toString());
}
}
endingDate = dateFormat.format(calendar.getTime());
}
/**
* Writes out a simple temporary file with 5 columns and 100 rows.<br/>
* Data is random numbers.
* @throws SerDeException
* @throws IOException
*/
private static final void produceSimpleData() throws SerDeException, IOException{
simpleDataFile = File.createTempFile("testhiveColumnarLoader", ".txt");
simpleDataFile.deleteOnExit();
Path path = new Path(simpleDataFile.getPath());
writeRCFileTest(fs, simpleRowCount, path, columnCount, new DefaultCodec(), columnCount);
}
static Random randomCharGenerator = new Random(3);
static Random randColLenGenerator = new Random(20);
private static void resetRandomGenerators() {
randomCharGenerator = new Random(3);
randColLenGenerator = new Random(20);
}
private static int writeRCFileTest(FileSystem fs, int rowCount, Path file,
int columnNum, CompressionCodec codec, int columnCount) throws IOException {
fs.delete(file, true);
int rowsWritten = 0;
resetRandomGenerators();
RCFileOutputFormat.setColumnNumber(conf, columnNum);
RCFile.Writer writer = new RCFile.Writer(fs, conf, file, null, codec);
byte[][] columnRandom;
BytesRefArrayWritable bytes = new BytesRefArrayWritable(columnNum);
columnRandom = new byte[columnNum][];
for (int i = 0; i < columnNum; i++) {
BytesRefWritable cu = new BytesRefWritable();
bytes.set(i, cu);
}
for (int i = 0; i < rowCount; i++) {
nextRandomRow(columnRandom, bytes, columnCount);
rowsWritten++;
writer.append(bytes);
}
writer.close();
return rowsWritten;
}
private static void nextRandomRow(byte[][] row, BytesRefArrayWritable bytes, int columnCount) {
bytes.resetValid(row.length);
for (int i = 0; i < row.length; i++) {
row[i] = new byte[columnCount];
for (int j = 0; j < columnCount; j++)
row[i][j] = getRandomChar(randomCharGenerator);
bytes.get(i).set(row[i], 0, columnCount);
}
}
private static int CHAR_END = 122 - 7;
private static byte getRandomChar(Random random) {
byte b = 0;
do {
b = (byte) random.nextInt(CHAR_END);
} while ((b < 65));
if (b > 90) {
b = 7;
}
return b;
}
}
| apache-2.0 |
zycgit/configuration | hasor-garbage/schema/ParamDefine.java | 1639 | /*
* Copyright 2008-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.hasor.core.binder.schema;
/**
* 表示一个bean定义中的一种参数
* @version 2010-9-15
* @author 赵永春 (zyc@byshell.org)
*/
public class ParamDefine extends AbstractPropertyDefine {
/*属性索引,负数为自动分配*/
private int index = -1;
/*属性名*/
private String name = null;
/*------------------------------------------------------------------*/
/**获取属性索引,负数为自动分配*/
public int getIndex() {
return this.index;
}
/**设置属性索引,负数为自动分配*/
public void setIndex(int index) {
this.index = index;
}
/**返回属性名。*/
public String getName() {
return this.name;
}
/**设置属性名*/
public void setName(String name) {
this.name = name;
};
/**返回具有特征的字符串。*/
public String toString() {
return this.getClass().getSimpleName() + "@" + this.hashCode() + " index=" + this.getIndex();
}
} | apache-2.0 |
24ark/CategorizedGalleryView | app/src/main/java/com/arkitvora/categorizedgalleryview/MainActivity.java | 3456 | package com.arkitvora.categorizedgalleryview;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Categorized gallery view");
initGalleryFragment();
}
private void initGalleryFragment() {
GalleryFragment galleryFragment = new GalleryFragment().newInstance(getGalleryData());
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.content_frame, galleryFragment , "GALLERY_FRAGMENT").commit();
}
private ArrayList<GalleryData> getGalleryData() {
ArrayList<GalleryData> galleryData = new ArrayList<>();
ArrayList<String> beachImageSet = new ArrayList<>(Arrays.asList("https://images.pexels.com/photos/29724/pexels-photo-29724.jpg?h=350&auto=compress" , "https://images.pexels.com/photos/68672/beach-beverage-caribbean-cocktail-68672.jpeg?h=350&auto=compress","https://images.pexels.com/photos/108074/pexels-photo-108074.jpeg?h=350&auto=compress&cs=tinysrgb", "https://images.pexels.com/photos/26331/pexels-photo-26331.jpg?h=350&auto=compress&cs=tinysrgb"));
ArrayList<String> mountainImageSet = new ArrayList<>(Arrays.asList("https://images.pexels.com/photos/115045/pexels-photo-115045.jpeg?h=350&auto=compress","https://images.pexels.com/photos/7039/pexels-photo.jpeg?h=350&auto=compress", "https://images.pexels.com/photos/67517/pexels-photo-67517.jpeg?h=350&auto=compress"));
ArrayList<String> forestImageSet = new ArrayList<>(Arrays.asList("https://images.pexels.com/photos/94616/pexels-photo-94616.jpeg?h=350&auto=compress", "https://images.pexels.com/photos/24586/pexels-photo-24586.jpg?h=350&auto=compress", "https://images.pexels.com/photos/240125/pexels-photo-240125.jpeg?h=350&auto=compress&cs=tinysrgb"));
ArrayList<String> desertImageSet = new ArrayList<>(Arrays.asList("https://images.pexels.com/photos/109031/pexels-photo-109031.jpeg?h=350&auto=compress&cs=tinysrgb", "https://images.pexels.com/photos/60013/desert-drought-dehydrated-clay-soil-60013.jpeg?h=350&auto=compress&cs=tinysrgb","https://images.pexels.com/photos/6496/man-person-jumping-desert.jpg?h=350&auto=compress","https://images.pexels.com/photos/28051/pexels-photo-28051.jpg?h=350&auto=compress","https://images.pexels.com/photos/71241/pexels-photo-71241.jpeg?h=350&auto=compress"));
GalleryData beachesDataSet = new GalleryData("Beaches" , beachImageSet);
GalleryData mountainsDataSet = new GalleryData("Mountains" , mountainImageSet);
GalleryData forestsDataSet = new GalleryData("Forests" , forestImageSet);
GalleryData desertsDataSet = new GalleryData("Deserts" , desertImageSet);
galleryData.add(beachesDataSet);
galleryData.add(mountainsDataSet);
galleryData.add(forestsDataSet);
galleryData.add(desertsDataSet);
return galleryData;
}
}
| apache-2.0 |
18380460383/eshare | RxTools-library/src/main/java/com/vondear/rxtools/RxIntentUtils.java | 4257 | package com.vondear.rxtools;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import java.io.File;
/**
* Created by vondear on 2016/1/24.
*/
public class RxIntentUtils {
/**
* 获取安装App(支持7.0)的意图
* @param context
* @param filePath
* @param fileProvide
* @return
*/
public static Intent getInstallAppIntent(Context context, String filePath, String fileProvide) {
//apk文件的本地路径
File apkfile = new File(filePath);
if (!apkfile.exists()) {
return null;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri contentUri;
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
contentUri = FileProvider.getUriForFile(context, fileProvide, apkfile);
} else {
contentUri = Uri.fromFile(apkfile);
}
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
return intent;
}
/**
* 获取卸载App的意图
*
* @param packageName 包名
* @return 意图
*/
public static Intent getUninstallAppIntent(String packageName) {
Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:" + packageName));
return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
/**
* 获取打开App的意图
*
* @param context 上下文
* @param packageName 包名
* @return 意图
*/
public static Intent getLaunchAppIntent(Context context, String packageName) {
return getIntentByPackageName(context, packageName);
}
/**
* 根据包名获取意图
*
* @param context 上下文
* @param packageName 包名
* @return 意图
*/
private static Intent getIntentByPackageName(Context context, String packageName) {
return context.getPackageManager().getLaunchIntentForPackage(packageName);
}
/**
* 获取App信息的意图
*
* @param packageName 包名
* @return 意图
*/
public static Intent getAppInfoIntent(String packageName) {
Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");
return intent.setData(Uri.parse("package:" + packageName));
}
/**
* 获取App信息分享的意图
*
* @param info 分享信息
* @return 意图
*/
public static Intent getShareInfoIntent(String info) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
return intent.putExtra(Intent.EXTRA_TEXT, info);
}
/**
* 获取其他应用的Intent
*
* @param packageName 包名
* @param className 全类名
* @return 意图
*/
public static Intent getComponentNameIntent(String packageName, String className) {
return getComponentNameIntent(packageName, className, null);
}
/**
* 获取其他应用的Intent
*
* @param packageName 包名
* @param className 全类名
* @return 意图
*/
public static Intent getComponentNameIntent(String packageName, String className, Bundle bundle) {
Intent intent = new Intent(Intent.ACTION_VIEW);
if (bundle != null) intent.putExtras(bundle);
ComponentName cn = new ComponentName(packageName, className);
intent.setComponent(cn);
return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
/**
* 获取App具体设置的意图
*
* @param packageName 包名
* @return intent
*/
public static Intent getAppDetailsSettingsIntent(String packageName) {
Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");
intent.setData(Uri.parse("package:" + packageName));
return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
}
| apache-2.0 |
vistadataproject/metaPureJS | services/userMetaService/lookupDefaultPatientList-spec.js | 695 | 'use strict';
const userMetaService = require('../userMetaService');
const serviceTestUtils = require('../tests/serviceTestUtils');
describe('lookupDefaultPatientList asynchronous specs', () => {
let context;
beforeAll(() => {
context = serviceTestUtils.beforeAllScript(userMetaService).context;
});
const testDefault = (res) => {
expect(res).toEqual([]);
};
it('Empty arg returns Object', (done) => {
userMetaService.lookupDefaultPatientList(context, (err, res) => {
if (err) {
return serviceTestUtils.handleError(err, done);
}
testDefault(res);
done();
});
});
});
| apache-2.0 |
188383/WakerUp | src/pl/zeromskiego/androidapp/onas.java | 606 | package pl.zeromskiego.androidapp;
import android.app.Activity;
import android.os.Bundle;
public class onas extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.a_onas);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
public void onDestroy()
{
// RUN SUPER | REGISTER ACTIVITY AS NULL IN APP CLAS
super.onDestroy();
}
}
| apache-2.0 |
kkirsche/go-nessus | Godeps/_workspace/src/github.com/kkirsche/go-scp/files.go | 332 | package goScp
import (
"log"
"os"
"strings"
)
func createNewFile(filename string) *os.File {
file, err := os.Create(strings.TrimSpace(filename))
if err != nil {
log.Fatal(err)
}
return file
}
func writeParitalToFile(file *os.File, content []byte) {
_, err := file.Write(content)
if err != nil {
log.Fatal(err)
}
}
| apache-2.0 |
InterestingLab/waterdrop | waterdrop-config/src/main/java/io/github/interestinglab/waterdrop/config/impl/Path.java | 6266 | /**
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
*/
package io.github.interestinglab.waterdrop.config.impl;
import io.github.interestinglab.waterdrop.config.ConfigException;
import io.github.interestinglab.waterdrop.config.ConfigParseOptions;
import java.util.Iterator;
import java.util.List;
final class Path {
final private String first;
final private Path remainder;
Path(String first, Path remainder) {
this.first = first;
this.remainder = remainder;
}
Path(String... elements) {
if (elements.length == 0)
throw new ConfigException.BugOrBroken("empty path");
this.first = elements[0];
if (elements.length > 1) {
PathBuilder pb = new PathBuilder();
for (int i = 1; i < elements.length; ++i) {
pb.appendKey(elements[i]);
}
this.remainder = pb.result();
} else {
this.remainder = null;
}
}
// append all the paths in the list together into one path
Path(List<Path> pathsToConcat) {
this(pathsToConcat.iterator());
}
// append all the paths in the iterator together into one path
Path(Iterator<Path> i) {
if (!i.hasNext())
throw new ConfigException.BugOrBroken("empty path");
Path firstPath = i.next();
this.first = firstPath.first;
PathBuilder pb = new PathBuilder();
if (firstPath.remainder != null) {
pb.appendPath(firstPath.remainder);
}
while (i.hasNext()) {
pb.appendPath(i.next());
}
this.remainder = pb.result();
}
String first() {
return first;
}
/**
*
* @return path minus the first element or null if no more elements
*/
Path remainder() {
return remainder;
}
/**
*
* @return path minus the last element or null if we have just one element
*/
Path parent() {
if (remainder == null)
return null;
PathBuilder pb = new PathBuilder();
Path p = this;
while (p.remainder != null) {
pb.appendKey(p.first);
p = p.remainder;
}
return pb.result();
}
/**
*
* @return last element in the path
*/
String last() {
Path p = this;
while (p.remainder != null) {
p = p.remainder;
}
return p.first;
}
Path prepend(Path toPrepend) {
PathBuilder pb = new PathBuilder();
pb.appendPath(toPrepend);
pb.appendPath(this);
return pb.result();
}
int length() {
int count = 1;
Path p = remainder;
while (p != null) {
count += 1;
p = p.remainder;
}
return count;
}
Path subPath(int removeFromFront) {
int count = removeFromFront;
Path p = this;
while (p != null && count > 0) {
count -= 1;
p = p.remainder;
}
return p;
}
Path subPath(int firstIndex, int lastIndex) {
if (lastIndex < firstIndex)
throw new ConfigException.BugOrBroken("bad call to subPath");
Path from = subPath(firstIndex);
PathBuilder pb = new PathBuilder();
int count = lastIndex - firstIndex;
while (count > 0) {
count -= 1;
pb.appendKey(from.first());
from = from.remainder();
if (from == null)
throw new ConfigException.BugOrBroken("subPath lastIndex out of range " + lastIndex);
}
return pb.result();
}
boolean startsWith(Path other) {
Path myRemainder = this;
Path otherRemainder = other;
if (otherRemainder.length() <= myRemainder.length()) {
while(otherRemainder != null) {
if (!otherRemainder.first().equals(myRemainder.first()))
return false;
myRemainder = myRemainder.remainder();
otherRemainder = otherRemainder.remainder();
}
return true;
}
return false;
}
@Override
public boolean equals(Object other) {
if (other instanceof Path) {
Path that = (Path) other;
return this.first.equals(that.first)
&& ConfigImplUtil.equalsHandlingNull(this.remainder,
that.remainder);
} else {
return false;
}
}
@Override
public int hashCode() {
return 41 * (41 + first.hashCode())
+ (remainder == null ? 0 : remainder.hashCode());
}
// this doesn't have a very precise meaning, just to reduce
// noise from quotes in the rendered path for average cases
static boolean hasFunkyChars(String s) {
int length = s.length();
if (length == 0)
return false;
for (int i = 0; i < length; ++i) {
char c = s.charAt(i);
if (Character.isLetterOrDigit(c) || c == '-' || c == '_' || c == '.')
continue;
else
return true;
}
return false;
}
private void appendToStringBuilder(StringBuilder sb) {
if (hasFunkyChars(first) || first.isEmpty())
sb.append(ConfigImplUtil.renderJsonString(first));
else
sb.append(first);
if (remainder != null) {
sb.append(ConfigParseOptions.pathTokenSeparator);
remainder.appendToStringBuilder(sb);
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Path(");
appendToStringBuilder(sb);
sb.append(")");
return sb.toString();
}
/**
* toString() is a debugging-oriented version while this is an
* error-message-oriented human-readable one.
*/
String render() {
StringBuilder sb = new StringBuilder();
appendToStringBuilder(sb);
return sb.toString();
}
static Path newKey(String key) {
return new Path(key, null);
}
static Path newPath(String path) {
return PathParser.parsePath(path);
}
}
| apache-2.0 |
milaboratory/milib | src/main/java/com/milaboratory/util/io/HasPosition.java | 693 | /*
* Copyright 2019 MiLaboratory, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.milaboratory.util.io;
public interface HasPosition {
long getPosition();
}
| apache-2.0 |
zhangminglei/flink | flink-runtime/src/test/java/org/apache/flink/runtime/metrics/dump/MetricQueryServiceTest.java | 4495 | /*
* 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.flink.runtime.metrics.dump;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.metrics.Counter;
import org.apache.flink.metrics.Gauge;
import org.apache.flink.metrics.Histogram;
import org.apache.flink.metrics.Meter;
import org.apache.flink.metrics.SimpleCounter;
import org.apache.flink.metrics.util.TestHistogram;
import org.apache.flink.runtime.akka.AkkaUtils;
import org.apache.flink.runtime.metrics.MetricRegistryConfiguration;
import org.apache.flink.runtime.metrics.MetricRegistryImpl;
import org.apache.flink.runtime.metrics.groups.TaskManagerMetricGroup;
import org.apache.flink.util.TestLogger;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.testkit.TestActorRef;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Tests for the {@link MetricQueryService}.
*/
public class MetricQueryServiceTest extends TestLogger {
@Test
public void testCreateDump() throws Exception {
ActorSystem s = AkkaUtils.createLocalActorSystem(new Configuration());
ActorRef serviceActor = MetricQueryService.startMetricQueryService(s, null);
TestActorRef testActorRef = TestActorRef.create(s, Props.create(TestActor.class));
TestActor testActor = (TestActor) testActorRef.underlyingActor();
final Counter c = new SimpleCounter();
final Gauge<String> g = new Gauge<String>() {
@Override
public String getValue() {
return "Hello";
}
};
final Histogram h = new TestHistogram();
final Meter m = new Meter() {
@Override
public void markEvent() {
}
@Override
public void markEvent(long n) {
}
@Override
public double getRate() {
return 5;
}
@Override
public long getCount() {
return 10;
}
};
MetricRegistryImpl registry = new MetricRegistryImpl(MetricRegistryConfiguration.defaultMetricRegistryConfiguration());
final TaskManagerMetricGroup tm = new TaskManagerMetricGroup(registry, "host", "id");
MetricQueryService.notifyOfAddedMetric(serviceActor, c, "counter", tm);
MetricQueryService.notifyOfAddedMetric(serviceActor, g, "gauge", tm);
MetricQueryService.notifyOfAddedMetric(serviceActor, h, "histogram", tm);
MetricQueryService.notifyOfAddedMetric(serviceActor, m, "meter", tm);
serviceActor.tell(MetricQueryService.getCreateDump(), testActorRef);
synchronized (testActor.lock) {
if (testActor.message == null) {
testActor.lock.wait();
}
}
MetricDumpSerialization.MetricSerializationResult dump = (MetricDumpSerialization.MetricSerializationResult) testActor.message;
testActor.message = null;
assertTrue(dump.serializedMetrics.length > 0);
MetricQueryService.notifyOfRemovedMetric(serviceActor, c);
MetricQueryService.notifyOfRemovedMetric(serviceActor, g);
MetricQueryService.notifyOfRemovedMetric(serviceActor, h);
MetricQueryService.notifyOfRemovedMetric(serviceActor, m);
serviceActor.tell(MetricQueryService.getCreateDump(), testActorRef);
synchronized (testActor.lock) {
if (testActor.message == null) {
testActor.lock.wait();
}
}
MetricDumpSerialization.MetricSerializationResult emptyDump = (MetricDumpSerialization.MetricSerializationResult) testActor.message;
testActor.message = null;
assertEquals(0, emptyDump.serializedMetrics.length);
s.shutdown();
}
private static class TestActor extends UntypedActor {
public Object message;
public Object lock = new Object();
@Override
public void onReceive(Object message) throws Exception {
synchronized (lock) {
this.message = message;
lock.notifyAll();
}
}
}
}
| apache-2.0 |
google/earthengine-community | samples/javascript/guides/features04.js | 7218 | /**
* Copyright 2020 The Google Earth Engine Community 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.
*/
/**
* @fileoverview Earth Engine Developer's Guide examples
* from 'Feature Collections' page
*/
// [START earthengine__features04__fc_information]
// Load watersheds from a data table.
var sheds = ee.FeatureCollection('USGS/WBD/2017/HUC06')
// Filter to the continental US.
.filterBounds(ee.Geometry.Rectangle(-127.18, 19.39, -62.75, 51.29))
// Convert 'areasqkm' property from string to number.
.map(function(feature){
var num = ee.Number.parse(feature.get('areasqkm'));
return feature.set('areasqkm', num);
});
// Display the table and print its first element.
Map.addLayer(sheds, {}, 'watersheds');
print('First watershed', sheds.first());
// Print the number of watersheds.
print('Count:', sheds.size());
// Print stats for an area property.
print('Area stats:', sheds.aggregate_stats('areasqkm'));
// [END earthengine__features04__fc_information]
// [START earthengine__features04__fc_column_info]
// Import a protected areas point feature collection.
var wdpa = ee.FeatureCollection("WCMC/WDPA/current/points");
// Define a function to print metadata column names and datatypes. This function
// is intended to be applied by the `evaluate` method which provides the
// function a client-side dictionary allowing the 'columns' object of the
// feature collection metadata to be subset by dot notation or bracket notation
// (`tableMetadata['columns']`).
function getCols(tableMetadata) {
print(tableMetadata.columns);
}
// Fetch collection metadata (`.limit(0)`) and apply the
// previously defined function using `evaluate()`. The printed object is a
// dictionary where keys are column names and values are datatypes.
wdpa.limit(0).evaluate(getCols);
// [END earthengine__features04__fc_column_info]
// [START earthengine__features04__fc_filtering]
// Load watersheds from a data table.
var sheds = ee.FeatureCollection('USGS/WBD/2017/HUC06')
// Convert 'areasqkm' property from string to number.
.map(function(feature){
var num = ee.Number.parse(feature.get('areasqkm'));
return feature.set('areasqkm', num);
});
// Define a region roughly covering the continental US.
var continentalUS = ee.Geometry.Rectangle(-127.18, 19.39, -62.75, 51.29);
// Filter the table geographically: only watersheds in the continental US.
var filtered = sheds.filterBounds(continentalUS);
// Check the number of watersheds after filtering for location.
print('Count after filter:', filtered.size());
// Filter to get only larger continental US watersheds.
var largeSheds = filtered.filter(ee.Filter.gt('areasqkm', 25000));
// Check the number of watersheds after filtering for size and location.
print('Count after filtering by size:', largeSheds.size());
// [END earthengine__features04__fc_filtering]
Map.addLayer(largeSheds, {}, 'large watersheds');
// [START earthengine__features04__add_property]
// Load watersheds from a data table.
var sheds = ee.FeatureCollection('USGS/WBD/2017/HUC06');
// This function computes the feature's geometry area and adds it as a property.
var addArea = function(feature) {
return feature.set({areaHa: feature.geometry().area().divide(100 * 100)});
};
// Map the area getting function over the FeatureCollection.
var areaAdded = sheds.map(addArea);
// Print the first feature from the collection with the added property.
print('First feature:', areaAdded.first());
// [END earthengine__features04__add_property]
// [START earthengine__features04__centroids]
// This function creates a new feature from the centroid of the geometry.
var getCentroid = function(feature) {
// Keep this list of properties.
var keepProperties = ['name', 'huc6', 'tnmid', 'areasqkm'];
// Get the centroid of the feature's geometry.
var centroid = feature.geometry().centroid();
// Return a new Feature, copying properties from the old Feature.
return ee.Feature(centroid).copyProperties(feature, keepProperties);
};
// Map the centroid getting function over the features.
var centroids = sheds.map(getCentroid);
// Display the results.
Map.addLayer(centroids, {color: 'FF0000'}, 'centroids');
// [END earthengine__features04__centroids]
// [START earthengine__features04__reduce_column]
// Load watersheds from a data table and filter to the continental US.
var sheds = ee.FeatureCollection('USGS/WBD/2017/HUC06')
.filterBounds(ee.Geometry.Rectangle(-127.18, 19.39, -62.75, 51.29));
// This function computes the squared difference between an area property
// and area computed directly from the feature's geometry.
var areaDiff = function(feature) {
// Compute area in sq. km directly from the geometry.
var area = feature.geometry().area().divide(1000 * 1000);
// Compute the differece between computed area and the area property.
var diff = area.subtract(ee.Number.parse(feature.get('areasqkm')));
// Return the feature with the squared difference set to the 'diff' property.
return feature.set('diff', diff.pow(2));
};
// Calculate RMSE for population of difference pairs.
var rmse = ee.Number(
// Map the difference function over the collection.
sheds.map(areaDiff)
// Reduce to get the mean squared difference.
.reduceColumns(ee.Reducer.mean(), ['diff'])
.get('mean')
)
// Compute the square root of the mean square to get RMSE.
.sqrt();
// Print the result.
print('RMSE=', rmse);
// [END earthengine__features04__reduce_column]
// [START earthengine__features04__reduce_regions]
// Load an image of daily precipitation in mm/day.
var precip = ee.Image(ee.ImageCollection('NASA/ORNL/DAYMET_V3').first());
// Load watersheds from a data table and filter to the continental US.
var sheds = ee.FeatureCollection('USGS/WBD/2017/HUC06')
.filterBounds(ee.Geometry.Rectangle(-127.18, 19.39, -62.75, 51.29));
// Add the mean of each image as new properties of each feature.
var withPrecip = precip.reduceRegions(sheds, ee.Reducer.mean())
.filter(ee.Filter.notNull(['prcp']));
// This function computes total rainfall in cubic meters.
var prcpVolume = function(feature) {
// Precipitation in mm/day -> meters -> sq. meters.
var volume = ee.Number(feature.get('prcp'))
.divide(1000).multiply(feature.geometry().area());
return feature.set('volume', volume);
};
var highVolume = withPrecip
// Map the function over the collection.
.map(prcpVolume)
// Sort descending.
.sort('volume', false)
// Get only the 5 highest volume watersheds.
.limit(5)
// Extract the names to a list.
.reduceColumns(ee.Reducer.toList(), ['name']).get('list');
// Print the resulting FeatureCollection.
print(highVolume);
// [END earthengine__features04__reduce_regions]
| apache-2.0 |
cmmanish/OldUITempTest | examples/v201109/GetAllUserLists.java | 2517 | // Copyright 2011, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package v201109;
import com.google.api.adwords.lib.AdWordsService;
import com.google.api.adwords.lib.AdWordsServiceLogger;
import com.google.api.adwords.lib.AdWordsUser;
import com.google.api.adwords.v201109.cm.OrderBy;
import com.google.api.adwords.v201109.cm.Selector;
import com.google.api.adwords.v201109.cm.SortOrder;
import com.google.api.adwords.v201109.cm.UserList;
import com.google.api.adwords.v201109.cm.UserListPage;
import com.google.api.adwords.v201109.cm.UserListServiceInterface;
/**
* This example gets all users lists. To add a user list, run AddUserList.java.
*
* Tags: UserListService.get
*
* @author api.arogal@gmail.com (Adam Rogal)
*/
public class GetAllUserLists {
public static void main(String[] args) {
try {
// Log SOAP XML request and response.
AdWordsServiceLogger.log();
// Get AdWordsUser from "~/adwords.properties".
AdWordsUser user = new AdWordsUser();
// Get the UserListService.
UserListServiceInterface userListService =
user.getService(AdWordsService.V201109.USER_LIST_SERVICE);
// Create selector.
Selector selector = new Selector();
selector.setFields(new String[] {"Id", "Name", "Status", "Size"});
selector.setOrdering(new OrderBy[] {new OrderBy("Name", SortOrder.ASCENDING)});
// Get all user lists.
UserListPage page = userListService.get(selector);
// Display user lists.
if (page.getEntries() != null) {
for (UserList userList : page.getEntries()) {
System.out.printf("User list with name '%s', id '%d', status '%s', and number of "
+ "users '%d' was found.\n", userList.getName(), userList.getId(),
userList.getStatus(), userList.getSize());
}
} else {
System.out.println("No user lists were found.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| apache-2.0 |
mikeleishen/bacosys | frame/frame-service/src/main/java/com/xinyou/frame/response/BasicResponse.java | 1225 | package com.xinyou.frame.response;
import java.util.List;
import com.xinyou.frame.domain.models.EntityListDM;
public class BasicResponse <T,T1> {
private String status = "0";
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public long getSvrdt() {
return svrdt;
}
public void setSvrdt(long svrdt) {
this.svrdt = svrdt;
}
public T getDataEntity() {
return dataEntity;
}
public void setDataEntity(T dataEntity) {
this.dataEntity = dataEntity;
}
public List<T> getDataList() {
return dataList;
}
public void setDataList(List<T> dataList) {
this.dataList = dataList;
}
public List<T1> getDataList2() {
return dataList2;
}
public void setDataList2(List<T1> dataList2) {
this.dataList2 = dataList2;
}
public EntityListDM<T, T1> getDataDM() {
return dataDM;
}
public void setDataDM(EntityListDM<T, T1> dataDM) {
this.dataDM = dataDM;
}
private String info = "";
private long svrdt = 0;
private T dataEntity;
private List<T> dataList;
private List<T1> dataList2;
private EntityListDM<T,T1> dataDM;
}
| apache-2.0 |
dpvreony/tplhelper | src/Dhgms.TplHelper/Controller/Task/Sql/EmbeddedInteger32.cs | 2944 | // --------------------------------------------------------------------------------------------------------------------
// <copyright company="DHGMS Solutions" file="EmbeddedInteger32.cs">
// 2004-2012 DHGMS Solutions. Some Rights Reserved. Licensed under GNU General Public License version 2 (GPLv2)
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Dhgms.TplHelper.Controller.Task.Sql
{
using System.Data.Common;
using System.Reflection;
using Dhgms.DataManager.Model.Helper.Database;
using Dhgms.TplHelper.Model.Info.TaskResult;
/// <summary>
/// Base class for an SQL task that processes a 32-bit integer from an embedded script
/// </summary>
/// <typeparam name="TDatabaseHelperClass">
/// The type for the database helper
/// </typeparam>
/// <typeparam name="TParameterClass">
/// The type for the SQL Parameters
/// </typeparam>
public abstract class EmbeddedInteger32<TDatabaseHelperClass, TParameterClass> :
Embedded<SingleResultInteger32, TDatabaseHelperClass, TParameterClass>
where TDatabaseHelperClass : DatabaseHelperBase<TParameterClass>, new()
where TParameterClass : DbParameter
{
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="EmbeddedInteger32{TDatabaseHelperClass,TParameterClass}"/> class.
/// </summary>
/// <param name="taskName">
/// </param>
/// <param name="connectionString">
/// </param>
/// <param name="assembly">
/// </param>
/// <param name="resourceNamespace">
/// </param>
/// <param name="resourceFileName">
/// </param>
/// <param name="assumeSqlSafe">
/// Whether to skip the SQL injection safety check. Use only if you know the code you are passing in is safe and contains a quoted string that is preventing it passing the saftey check
/// </param>
protected EmbeddedInteger32(
string taskName,
string connectionString,
Assembly assembly,
string resourceNamespace,
string resourceFileName,
bool assumeSqlSafe)
: base(taskName, connectionString, assembly, resourceNamespace, resourceFileName, assumeSqlSafe)
{
}
#endregion
#region Methods
/// <summary>
/// The OnProcess event for doing the donkey work
/// </summary>
/// <param name="result">
/// The result.
/// </param>
protected override void OnProcess(SingleResultInteger32 result)
{
result.Result = this.DbHelper.GetInteger32(
this.ConnectionString, this.GetSql(), this.GetParameters(), this.AssumeSqlSafe);
}
#endregion
}
} | apache-2.0 |
lime-company/lime-security-powerauth-push | powerauth-push-server/src/main/java/io/getlime/push/repository/model/PushCampaignUserEntity.java | 3242 | /*
* Copyright 2016 Wultra s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.getlime.push.repository.model;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/**
* Class representing campaign users to get a certain message.
*
* @author Martin Tupy, martin.tupy.work@gmail.com
*/
@Entity
@Table(name = "push_campaign_user")
public class PushCampaignUserEntity implements Serializable {
/**
* Campaign user ID.
*/
@Id
@Column(name = "id")
@SequenceGenerator(name = "push_campaign_user", sequenceName = "push_campaign_user_seq")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "push_campaign_user")
private Long id;
/**
* Campaign ID.
*/
@Column(name = "campaign_id", nullable = false, updatable = false)
private Long campaignId;
/**
* User ID.
*/
@Column(name = "user_id", nullable = false, updatable = false)
private String userId;
/**
* App ID.
*/
@Column(name = "app_id", nullable = false, updatable = false)
private Long appId;
/**
* Timestamp created.
*/
@Column(name = "timestamp_created", nullable = false, updatable = false)
private Date timestampCreated;
/**
* Get campaign user ID.
* @return Campaign user ID.
*/
public Long getId() {
return id;
}
/**
* Set campaign user ID.
* @param id Campaign user ID.
*/
public void setId(Long id) {
this.id = id;
}
/**
* Get campaign ID.
* @return Campaign ID.
*/
public Long getCampaignId() {
return campaignId;
}
/**
* Set campaign ID.
* @param campaignId Campaign ID.
*/
public void setCampaignId(Long campaignId) {
this.campaignId = campaignId;
}
/**
* Get app ID.
* @return App ID.
*/
public Long getAppId() {
return appId;
}
/**
* Set app ID.
* @param appId App ID.
*/
public void setAppId(Long appId) {
this.appId = appId;
}
/**
* Get user ID.
* @return User ID.
*/
public String getUserId() {
return userId;
}
/**
* Set user ID.
* @param userId User ID.
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* Get timestamp created.
* @return Timestamp created.
*/
public Date getTimestampCreated() {
return timestampCreated;
}
/**
* Set timestamp created.
* @param timestampCreated Timestamp created.
*/
public void setTimestampCreated(Date timestampCreated) {
this.timestampCreated = timestampCreated;
}
}
| apache-2.0 |
andrewjskatz/sqlest | src/test/scala/sqlest/ast/SelectSpec.scala | 2269 | /*
* Copyright 2014 JHC Systems Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sqlest.ast
import org.scalatest._
import org.scalatest.matchers._
import sqlest._
class SelectSpec extends FlatSpec with Matchers {
class MyTable(alias: Option[String]) extends Table("mytable", alias) {
val col1 = column[Int]("col1")
val col2 = column[Int]("col2")
}
object MyTable extends MyTable(None)
"simplest select possible" should "produce the right sql" in {
val query = select.from(MyTable)
query.columns should equal(List(MyTable.col1, MyTable.col2))
query.from should equal(MyTable)
query.where should equal(None)
query.order should equal(Nil)
query.limit should equal(None)
query.offset should equal(None)
}
"select with explicit column list" should "produce the right sql" in {
val query = select(MyTable.col1).from(MyTable)
query.columns should equal(List(MyTable.col1))
query.from should equal(MyTable)
query.where should equal(None)
query.order should equal(Nil)
query.limit should equal(None)
query.offset should equal(None)
}
"repeated calls to select.where()" should "append new filters" in {
val query = select.from(MyTable).where(MyTable.col1 > 1).where(MyTable.col1 < 2)
query.where should equal(Some(MyTable.col1 > 1 && MyTable.col1 < 2))
}
"repeated calls to select.order()" should "append new orders" in {
val query = select.from(MyTable)
query.columns should equal(List(MyTable.col1, MyTable.col2))
}
"repeated calls to select.page()" should "override the old values" in {
val query = select.from(MyTable).page(1, 10).page(2, 20)
query.limit should equal(Some(20))
query.offset should equal(Some(40))
}
} | apache-2.0 |
abhijitsarkar/feign | app/org/abhijitsarkar/feign/dao/RequestRepository.scala | 4206 | package org.abhijitsarkar.feign.dao
import javax.inject.{Inject, Singleton}
import com.google.inject.ImplementedBy
import org.abhijitsarkar.feign.api.persistence.{RecordRequest, RequestService}
import org.abhijitsarkar.feign.domain.RequestFormat._
import org.slf4j.LoggerFactory
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.Json
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import reactivemongo.api.{Cursor, ReadPreference}
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.Future
import scala.util.{Failure, Success}
/**
* @author Abhijit Sarkar
*/
@ImplementedBy(classOf[MongoDbRequestRepository])
trait RequestRepository extends RequestService
@Singleton
class MongoDbRequestRepository @Inject()(val reactiveMongoApi: ReactiveMongoApi) extends RequestRepository {
private val logger = LoggerFactory.getLogger(classOf[MongoDbRequestRepository])
private val futureCollection = reactiveMongoApi.database.map(_.collection[JSONCollection]("feign"))
private def logResult(id: Option[String], f: Future[_]) = {
f.onComplete {
case Success(_) => logger.debug(s"""Successfully executed database request${id.map(_ => " with id: " + id).getOrElse("")}.""")
case Failure(ex) => logger.error(s"""Failed to execute database request${id.map(_ => " with id: " + id).getOrElse("")}.""", ex)
}
}
override def findAll: Future[Seq[RecordRequest]] = {
logger.warn(s"Attempting to find all recorded requests.")
val result = futureCollection
.flatMap(_.find(Json.obj()).cursor[RecordRequest](ReadPreference.primary)
.foldWhile(Seq.empty[RecordRequest], 100)({ (acc, req) =>
Cursor.Cont(acc :+ req)
}, Cursor.FailOnError((a, t) => logger.error("Failed to find requests.", t))))
logResult(None, result)
result
}
override def find(id: String): Future[Option[RecordRequest]] = {
logger.debug(s"Attempting to find recorded request for id: ${id}.")
val result = futureCollection
.flatMap(_.find(Json.obj("id" -> id)).one[RecordRequest])
logResult(Some(id), result)
result.map {
case x@Some(_) => logger.debug(s"Successfully found request with id: ${id}."); x
case _ => logger.warn(s"Failed to find request with id: ${id}."); None
}
}
implicit val recordRequestMongoFormat = Json.format[RecordRequest]
override def create(request: RecordRequest): Future[Option[String]] = {
logger.debug(s"Attempting to persist request for id: ${request.id}.")
val future = futureCollection.flatMap(_.insert[RecordRequest](request))
logResult(Some(request.id), future)
for {
result <- future
either = result.ok match {
case true => logger.debug(s"Successfully persisted request with id. ${request.id}."); Some(request.id)
case _ => {
logger.error(s"Failed to persist request with id: ${request.id}. Reason: ${result.writeErrors.toString}.")
None
}
}
} yield either
}
override def deleteAll: Future[Option[Int]] = {
logger.warn(s"Attempting to delete all recorded requests.")
val future = futureCollection.flatMap(_.remove(Json.obj()))
logResult(None, future)
for {
result <- future
either = result.ok match {
case true => logger.debug(s"Successfully deleted all requests."); Some(result.n)
case _ => {
logger.warn(s"Failed to delete requests. Reason: ${result.writeErrors.toString}.")
None
}
}
} yield either
}
override def delete(id: String): Future[Option[String]] = {
logger.debug(s"Attempting to delete recorded request for id: ${id}.")
val future = futureCollection.flatMap(_.remove(Json.obj("id" -> id)))
logResult(Some(id), future)
for {
result <- future
either = result.ok match {
case true => logger.debug(s"Successfully deleted request with id. ${id}."); Some(id)
case _ => {
logger.warn(s"Failed to delete request with id: ${id}. Reason: ${result.writeErrors.toString}.")
None
}
}
} yield either
}
} | apache-2.0 |
gustavoresque/creative_infovis | server/databases/WebService/webservice.js | 2010 |
//var postData = querystring.stringify({
// 'msg': 'Hello World!'
//});
//TODO: refatorar para sintaxe de classes.
var WebService = function (url, method, headers, callback) {
this.url = url;
this.method = method;
this.headers = headers;
var result = /^(https?)\:\/\/((\w+((\-\w+)|(\.\w+))*)(\:(\d+))?)(\/([\w\-\/\_\.]+))?(\?([\w\-\/\_\.\+\=\&\:\%]+))?$/g.exec(url);
if(!result){
callback("URL inválida");
return undefined;
}
if(result[8]){
this.port = parseInt(result[7]);
}
if(result[1] === "http"){
this.http = require('http');
this.port = this.port || 80;
}else{
this.http = require('https');
this.port = this.port || 443;
}
this.host = result[3];
this.path = (result[9]||"")+(result[11]||"");
return this;
};
WebService.prototype.send = function (callback) {
var self = this;
var options = {
hostname: self.host,
port: self.port,
path: self.path,
method: self.method,
headers: self.headers
};
var req = self.http.request(options, function (res) {
console.log("STATUS: " + res.statusCode);
console.log("HEADERS: " + JSON.stringify(res.headers));
var data="";
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("INICIO do BODY");
console.log("BODY: " + chunk);
data += chunk;
});
res.on('end', function () {
console.log('No more data in response.');
if(res.statusCode === 200){
callback(undefined, data);
}else{
callback({message: "problema", statusCode: res.statusCode}, data);
}
});
});
req.on('error', function (e) {
callback(e);
});
// write data to request body
//req.write('');
req.end();
};
module.exports = WebService;
| apache-2.0 |
teknologika/Tapstream | Config.cs | 2192 | using System;
namespace TapstreamMetrics.Sdk
{
public sealed class Config
{
// Deprecated, hardware-id field
private string hardware = null;
// Optional hardware identifiers that can be provided by the caller
private string odin1 = null;
// Set these to false if you do NOT want to collect this data.
private bool collectDeviceUniqueId = true;
// Set these if you want to override the names of the automatic events sent by the sdk
private string installEventName = null;
private string openEventName = null;
// Unset these if you want to disable the sending of the automatic events
private bool fireAutomaticInstallEvent = true;
private bool fireAutomaticOpenEvent = true;
// Properties for the private members above:
public string Hardware
{
get { return hardware; }
set { hardware = value; }
}
public string Odin1
{
get { return odin1; }
set { odin1 = value; }
}
#region iOS
public string Udid { get; set; }
public string Idfa { get; set; }
public string SecureUdid { get; set;}
public string OpenUdid { get; set;}
#endregion
//TODO: ifdef for mac support
//public string SerialNumber { get; set;}
public bool CollectDeviceUniqueId
{
get { return collectDeviceUniqueId; }
set { collectDeviceUniqueId = value; }
}
public string InstallEventName
{
get { return installEventName; }
set { installEventName = value; }
}
public string OpenEventName
{
get { return openEventName; }
set { openEventName = value; }
}
public bool FireAutomaticInstallEvent
{
get { return fireAutomaticInstallEvent; }
set { fireAutomaticInstallEvent = value; }
}
public bool FireAutomaticOpenEvent
{
get { return fireAutomaticOpenEvent; }
set { fireAutomaticOpenEvent = value; }
}
}
}
| apache-2.0 |
areskts/xdeveloper | xdeveloper-xvalidator/src/main/java/jjwu/xdeveloper/xvalidators/handlers/NotEmptyHandler.java | 2622 | /****************************************************************
* 文件名 : NotEmptyHandler.java
* 日期 : 2012-8-14
* Company: 上海绿岸网络科技有限公司
* (C) Copyright Green Shore Network Technology Co.,Ltd.2012
* All Rights Reserved.
* 注意: 本内容仅限于上海绿岸网络科技有限公司内部使用,禁止转发
****************************************************************/
package jjwu.xdeveloper.xvalidators.handlers;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;
import jjwu.xdeveloper.xvalidators.annotation.Ivalidator;
import jjwu.xdeveloper.xvalidators.annotation.NotEmpty;
import jjwu.xdeveloper.xvalidators.exeception.XvalidatorException;
import jjwu.xdeveloper.xvalidators.util.GetFiledValue;
/**
*
* @类名: NotEmptyHandler
* @描述: 空对象验证处理类
*
* @作者: 吴君杰
* @邮箱: wujunjie@iwgame.com
* @日期: 2012-8-14上午09:20:28
* @版本: 1.0
*/
public class NotEmptyHandler implements Handler {
/* (non-Javadoc)
* @see org.tony.annotation.validators.Handler#validate(org.tony.annotation.validators.IwAnnotation, java.lang.reflect.Field)
*/
@Override
public void validate(Ivalidator targetObj, Field field) throws XvalidatorException {
// TODO Auto-generated method stub
if (field.isAnnotationPresent(NotEmpty.class)) {
checkNotEmpty(targetObj, field);
}
}
public void checkNotEmpty(Ivalidator targetObj,Field field) throws XvalidatorException{
NotEmpty validateNotEmpty = field.getAnnotation(NotEmpty.class);
String message = validateNotEmpty.errmsg();
Object value = GetFiledValue.getFieldValue(targetObj, field.getName());
//POJO
if(value == null){
throw new XvalidatorException(message + " But the value of Field[" + field.getName() + "] is Null.");
}
//Map
if(value instanceof Map<?,?>){
if(((Map<?,?>)value).isEmpty()){
throw new XvalidatorException(message + " But the value of Field[" + field.getName() + "] is Empty.");
}
//List & Set
}else if(value instanceof Collection<?>){
if(((Collection<?>)value).isEmpty() || ((Collection<?>)value).size() ==0){
throw new XvalidatorException(message + " But the value of Field[" + field.getName() + "] is Empty.");
}
//Other
}else{
String temp = value.toString().trim();
if(temp.isEmpty()||"null".equals(temp)){
throw new XvalidatorException(message + " But the value of Field[" + field.getName() + "] length is Zero or Empty.");
}
}
}
}
| apache-2.0 |
jmillert/pokeraidbot | src/main/java/pokeraidbot/commands/NewRaidExCommand.java | 3692 | package pokeraidbot.commands;
import com.jagrosh.jdautilities.commandclient.CommandEvent;
import com.jagrosh.jdautilities.commandclient.CommandListener;
import net.dv8tion.jda.core.entities.User;
import pokeraidbot.Utils;
import pokeraidbot.domain.config.LocaleService;
import pokeraidbot.domain.errors.UserMessedUpException;
import pokeraidbot.domain.gym.Gym;
import pokeraidbot.domain.gym.GymRepository;
import pokeraidbot.domain.pokemon.Pokemon;
import pokeraidbot.domain.pokemon.PokemonRepository;
import pokeraidbot.domain.raid.Raid;
import pokeraidbot.domain.raid.RaidRepository;
import pokeraidbot.infrastructure.jpa.config.Config;
import pokeraidbot.infrastructure.jpa.config.ServerConfigRepository;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import static pokeraidbot.Utils.assertCreateRaidTimeNotBeforeNow;
import static pokeraidbot.Utils.assertTimeNotInNoRaidTimespan;
/**
* !raid new [Pokemon] [Ends at (yyyy-MM-dd HH:mm)] [Pokestop name]
*/
public class NewRaidExCommand extends ConfigAwareCommand {
private final GymRepository gymRepository;
private final RaidRepository raidRepository;
private final PokemonRepository pokemonRepository;
private final LocaleService localeService;
public NewRaidExCommand(GymRepository gymRepository, RaidRepository raidRepository,
PokemonRepository pokemonRepository, LocaleService localeService,
ServerConfigRepository serverConfigRepository,
CommandListener commandListener) {
super(serverConfigRepository, commandListener, localeService);
this.pokemonRepository = pokemonRepository;
this.localeService = localeService;
this.name = "ex";
this.help = localeService.getMessageFor(LocaleService.NEW_EX_RAID_HELP, LocaleService.DEFAULT);
this.gymRepository = gymRepository;
this.raidRepository = raidRepository;
}
@Override
protected void executeWithConfig(CommandEvent commandEvent, Config config) {
final User user = commandEvent.getAuthor();
final String userName = user.getName();
final String[] args = commandEvent.getArgs().split(" ");
String pokemonName = args[0];
final Pokemon pokemon = pokemonRepository.search(pokemonName, user);
String dateString = args[1];
String timeString = args[2];
LocalTime endsAtTime = Utils.parseTime(user, timeString, localeService);
LocalDate endsAtDate = Utils.parseDate(user, dateString, localeService);
LocalDateTime endsAt = LocalDateTime.of(endsAtDate, endsAtTime);
assertTimeNotInNoRaidTimespan(user, endsAtTime, localeService);
if (endsAtDate.isAfter(LocalDate.now().plusDays(7))) {
throw new UserMessedUpException(user, localeService.getMessageFor(LocaleService.EX_DATE_LIMITS,
localeService.getLocaleForUser(user)));
}
assertCreateRaidTimeNotBeforeNow(user, endsAt, localeService);
StringBuilder gymNameBuilder = new StringBuilder();
for (int i = 3; i < args.length; i++) {
gymNameBuilder.append(args[i]).append(" ");
}
String gymName = gymNameBuilder.toString().trim();
final Gym gym = gymRepository.search(user, gymName, config.getRegion());
final Raid raid = new Raid(pokemon, endsAt, gym, localeService, config.getRegion());
raidRepository.newRaid(userName, raid);
replyBasedOnConfig(config, commandEvent, localeService.getMessageFor(LocaleService.NEW_RAID_CREATED,
localeService.getLocaleForUser(user), raid.toString()));
}
}
| apache-2.0 |
iivalchev/drm-wms | drmaa/src/main/java/org/ggf/drmaa/FileTransferMode.java | 6388 | /*___INFO__MARK_BEGIN__*/
/*************************************************************************
*
* The Contents of this file are made available subject to the terms of
* the Sun Industry Standards Source License Version 1.2
*
* Sun Microsystems Inc., March, 2001
*
*
* Sun Industry Standards Source License Version 1.2
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.2 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://gridengine.sunsource.net/Gridengine_SISSL_license.html
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2001 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
************************************************************************/
/*___INFO__MARK_END__*/
/*
* FileTransferMode.java
*
* Created on October 6, 2004, 6:05 PM
*/
package org.ggf.drmaa;
import java.io.Serializable;
/**
* This class represents the streams which should be used for file transfers.
* For each of the three properties which is set to true, the corresponding
* stream's path property in the job template will be treated as a source or
* destination (depending on the stream) for file tranfers. For example, if the
* inputStream property is set to true, the inputPath property of the
* JobTemplate will be interpreted as a source from which to transfer files.
*
* @author dan.templeton@sun.com
* @version 1.0
* @since 0.5
*/
public class FileTransferMode implements Serializable, Cloneable {
/**
* Whether to transfer error stream files.
*/
private boolean errorStream = false;
/**
* Whether to transfer input stream files.
*/
private boolean inputStream = false;
/**
* Whether to transfer output stream files.
*/
private boolean outputStream = false;
/**
* Creates a new instance of FileTransferMode
*/
public FileTransferMode() {
}
/**
* Create a new instance with the property values preset.
*
* @param inputStream whether to transfer input stream files
* @param outputStream whether to transfer output stream files
* @param errorStream whether to transfer error stream files
*/
public FileTransferMode(boolean inputStream, boolean outputStream, boolean errorStream) {
this.errorStream = errorStream;
this.inputStream = inputStream;
this.outputStream = outputStream;
}
/**
* Set whether to transfer error stream files.
*
* @param errorStream whether to transfer error stream files
*/
public void setErrorStream(boolean errorStream) {
this.errorStream = errorStream;
}
/**
* Whether to transfer error stream files.
*
* @return whether to transfer error stream files
*/
public boolean getErrorStream() {
return errorStream;
}
/**
* Set whether to transfer error stream files.
*
* @param inputStream whether to transfer error stream files
*/
public void setInputStream(boolean inputStream) {
this.inputStream = inputStream;
}
/**
* Whether to transfer error stream files.
*
* @return whether to transfer error stream files
*/
public boolean getInputStream() {
return inputStream;
}
/**
* Set whether to transfer error stream files.
*
* @param outputStream whether to transfer error stream files
*/
public void setOutputStream(boolean outputStream) {
this.outputStream = outputStream;
}
/**
* Whether to transfer error stream files.
*
* @return whether to transfer error stream files
*/
public boolean getOutputStream() {
return outputStream;
}
/**
* Test whether two FileTransferMode objects have the same property
* settings.
*
* @param obj the Object to test for equality
* @return whether the FileTransferMode object has the same property
* settings as this one
*/
public boolean equals(Object obj) {
return ((obj instanceof FileTransferMode) &&
(((FileTransferMode) obj).errorStream == errorStream) &&
(((FileTransferMode) obj).inputStream == inputStream) &&
(((FileTransferMode) obj).outputStream == outputStream));
}
/**
* Returns a hash code based on the file transfer properties.
*
* @return a hash code based on the file transfer properties
*/
public int hashCode() {
int ret = 0;
ret += inputStream ? 1 : 0;
ret += outputStream ? 2 : 0;
ret += errorStream ? 4 : 0;
return ret;
}
/**
* Creates a copy of this FileTransferMode object.
*
* @return a copy of this FileTransferMode object
*/
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
/**
* Returns a string containing the stream settings.
*
* @return a string containing the stream settings
*/
public String toString() {
StringBuffer out = new StringBuffer();
boolean firstProperty = true;
if (inputStream) {
out.append("input");
firstProperty = false;
}
if (outputStream) {
if (firstProperty) {
firstProperty = false;
} else {
out.append(", ");
}
out.append("output");
}
if (errorStream) {
if (!firstProperty) {
out.append(", ");
}
out.append("error");
}
return out.toString();
}
}
| apache-2.0 |
simone-campagna/sheru | packages/sheru/sheru.py | 2222 | # -*- coding: utf-8 -*-
#
# Copyright 2015 Simone Campagna
#
# 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.
#
__author__ = "Simone Campagna"
__all__ = [
'Sheru',
]
from .iterstring import iterstring
from .struct import Struct
from .hosts_config import HostsConfig
from .users_config import UsersConfig
from .commands_config import CommandsConfig
from .options_config import OptionsConfig
from .protocols_config import ProtocolsConfig
from .profiles_config import ProfilesConfig
class Sheru(Struct):
DEFAULTS = (
('protocols', 'protocols.config'),
('options', 'options.config'),
('commands', 'commands.config'),
('hosts', 'hosts.config'),
('users', 'users.config'),
('profiles', 'profiles.config'),
)
def __init__(self, sheru, config, name, description,
hosts,
users,
commands,
options,
protocols,
profiles):
super().__init__(sheru, config, name, description)
# order is relevant!
options = self.abspath(options)
self.options = OptionsConfig(init=options, sheru=self)
hosts = self.abspath(hosts)
self.hosts = HostsConfig(init=hosts, sheru=self)
users = self.abspath(users)
self.users = UsersConfig(init=users, sheru=self)
commands = self.abspath(commands)
self.commands = CommandsConfig(init=commands, sheru=self)
protocols = self.abspath(protocols)
self.protocols = ProtocolsConfig(init=protocols, sheru=self)
profiles = self.abspath(profiles)
self.profiles = ProfilesConfig(init=profiles, sheru=self)
| apache-2.0 |
corbinbs/hapi-fhir | hapi-fhir-structures-hl7org-dstu2/src/main/java/org/hl7/fhir/instance/model/Procedure.java | 83701 | package org.hl7.fhir.instance.model;
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Tue, Jul 21, 2015 10:37-0400 for FHIR v0.5.0
import java.util.*;
import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.instance.model.annotations.ResourceDef;
import org.hl7.fhir.instance.model.annotations.SearchParamDefinition;
import org.hl7.fhir.instance.model.annotations.Child;
import org.hl7.fhir.instance.model.annotations.Description;
import org.hl7.fhir.instance.model.annotations.Block;
import org.hl7.fhir.instance.model.api.*;
/**
* An action that is or was performed on a patient. This can be a physical 'thing' like an operation, or less invasive like counseling or hypnotherapy.
*/
@ResourceDef(name="Procedure", profile="http://hl7.org/fhir/Profile/Procedure")
public class Procedure extends DomainResource {
public enum ProcedureStatus {
/**
* The procedure is still occurring
*/
INPROGRESS,
/**
* The procedure was terminated without completing successfully
*/
ABORTED,
/**
* All actions involved in the procedure have taken place
*/
COMPLETED,
/**
* The statement was entered in error and Is not valid
*/
ENTEREDINERROR,
/**
* added to help the parsers
*/
NULL;
public static ProcedureStatus fromCode(String codeString) throws Exception {
if (codeString == null || "".equals(codeString))
return null;
if ("in-progress".equals(codeString))
return INPROGRESS;
if ("aborted".equals(codeString))
return ABORTED;
if ("completed".equals(codeString))
return COMPLETED;
if ("entered-in-error".equals(codeString))
return ENTEREDINERROR;
throw new Exception("Unknown ProcedureStatus code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case INPROGRESS: return "in-progress";
case ABORTED: return "aborted";
case COMPLETED: return "completed";
case ENTEREDINERROR: return "entered-in-error";
default: return "?";
}
}
public String getSystem() {
switch (this) {
case INPROGRESS: return "http://hl7.org/fhir/procedure-status";
case ABORTED: return "http://hl7.org/fhir/procedure-status";
case COMPLETED: return "http://hl7.org/fhir/procedure-status";
case ENTEREDINERROR: return "http://hl7.org/fhir/procedure-status";
default: return "?";
}
}
public String getDefinition() {
switch (this) {
case INPROGRESS: return "The procedure is still occurring";
case ABORTED: return "The procedure was terminated without completing successfully";
case COMPLETED: return "All actions involved in the procedure have taken place";
case ENTEREDINERROR: return "The statement was entered in error and Is not valid";
default: return "?";
}
}
public String getDisplay() {
switch (this) {
case INPROGRESS: return "In Progress";
case ABORTED: return "Aboted";
case COMPLETED: return "Completed";
case ENTEREDINERROR: return "Entered in Error";
default: return "?";
}
}
}
public static class ProcedureStatusEnumFactory implements EnumFactory<ProcedureStatus> {
public ProcedureStatus fromCode(String codeString) throws IllegalArgumentException {
if (codeString == null || "".equals(codeString))
if (codeString == null || "".equals(codeString))
return null;
if ("in-progress".equals(codeString))
return ProcedureStatus.INPROGRESS;
if ("aborted".equals(codeString))
return ProcedureStatus.ABORTED;
if ("completed".equals(codeString))
return ProcedureStatus.COMPLETED;
if ("entered-in-error".equals(codeString))
return ProcedureStatus.ENTEREDINERROR;
throw new IllegalArgumentException("Unknown ProcedureStatus code '"+codeString+"'");
}
public String toCode(ProcedureStatus code) {
if (code == ProcedureStatus.INPROGRESS)
return "in-progress";
if (code == ProcedureStatus.ABORTED)
return "aborted";
if (code == ProcedureStatus.COMPLETED)
return "completed";
if (code == ProcedureStatus.ENTEREDINERROR)
return "entered-in-error";
return "?";
}
}
public enum ProcedureRelationshipType {
/**
* This procedure had to be performed because of the related one
*/
CAUSEDBY,
/**
* This procedure caused the related one to be performed
*/
BECAUSEOF,
/**
* added to help the parsers
*/
NULL;
public static ProcedureRelationshipType fromCode(String codeString) throws Exception {
if (codeString == null || "".equals(codeString))
return null;
if ("caused-by".equals(codeString))
return CAUSEDBY;
if ("because-of".equals(codeString))
return BECAUSEOF;
throw new Exception("Unknown ProcedureRelationshipType code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case CAUSEDBY: return "caused-by";
case BECAUSEOF: return "because-of";
default: return "?";
}
}
public String getSystem() {
switch (this) {
case CAUSEDBY: return "http://hl7.org/fhir/procedure-relationship-type";
case BECAUSEOF: return "http://hl7.org/fhir/procedure-relationship-type";
default: return "?";
}
}
public String getDefinition() {
switch (this) {
case CAUSEDBY: return "This procedure had to be performed because of the related one";
case BECAUSEOF: return "This procedure caused the related one to be performed";
default: return "?";
}
}
public String getDisplay() {
switch (this) {
case CAUSEDBY: return "Caused By";
case BECAUSEOF: return "Because Of";
default: return "?";
}
}
}
public static class ProcedureRelationshipTypeEnumFactory implements EnumFactory<ProcedureRelationshipType> {
public ProcedureRelationshipType fromCode(String codeString) throws IllegalArgumentException {
if (codeString == null || "".equals(codeString))
if (codeString == null || "".equals(codeString))
return null;
if ("caused-by".equals(codeString))
return ProcedureRelationshipType.CAUSEDBY;
if ("because-of".equals(codeString))
return ProcedureRelationshipType.BECAUSEOF;
throw new IllegalArgumentException("Unknown ProcedureRelationshipType code '"+codeString+"'");
}
public String toCode(ProcedureRelationshipType code) {
if (code == ProcedureRelationshipType.CAUSEDBY)
return "caused-by";
if (code == ProcedureRelationshipType.BECAUSEOF)
return "because-of";
return "?";
}
}
@Block()
public static class ProcedureBodySiteComponent extends BackboneElement implements IBaseBackboneElement {
/**
* Detailed and structured anatomical location information. Multiple locations are allowed - e.g. multiple punch biopsies of a lesion.
*/
@Child(name = "site", type = {CodeableConcept.class, BodySite.class}, order=1, min=1, max=1)
@Description(shortDefinition="Precise location details", formalDefinition="Detailed and structured anatomical location information. Multiple locations are allowed - e.g. multiple punch biopsies of a lesion." )
protected Type site;
private static final long serialVersionUID = 1429072605L;
/*
* Constructor
*/
public ProcedureBodySiteComponent() {
super();
}
/*
* Constructor
*/
public ProcedureBodySiteComponent(Type site) {
super();
this.site = site;
}
/**
* @return {@link #site} (Detailed and structured anatomical location information. Multiple locations are allowed - e.g. multiple punch biopsies of a lesion.)
*/
public Type getSite() {
return this.site;
}
/**
* @return {@link #site} (Detailed and structured anatomical location information. Multiple locations are allowed - e.g. multiple punch biopsies of a lesion.)
*/
public CodeableConcept getSiteCodeableConcept() throws Exception {
if (!(this.site instanceof CodeableConcept))
throw new Exception("Type mismatch: the type CodeableConcept was expected, but "+this.site.getClass().getName()+" was encountered");
return (CodeableConcept) this.site;
}
public boolean hasSiteCodeableConcept() throws Exception {
return this.site instanceof CodeableConcept;
}
/**
* @return {@link #site} (Detailed and structured anatomical location information. Multiple locations are allowed - e.g. multiple punch biopsies of a lesion.)
*/
public Reference getSiteReference() throws Exception {
if (!(this.site instanceof Reference))
throw new Exception("Type mismatch: the type Reference was expected, but "+this.site.getClass().getName()+" was encountered");
return (Reference) this.site;
}
public boolean hasSiteReference() throws Exception {
return this.site instanceof Reference;
}
public boolean hasSite() {
return this.site != null && !this.site.isEmpty();
}
/**
* @param value {@link #site} (Detailed and structured anatomical location information. Multiple locations are allowed - e.g. multiple punch biopsies of a lesion.)
*/
public ProcedureBodySiteComponent setSite(Type value) {
this.site = value;
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("site[x]", "CodeableConcept|Reference(BodySite)", "Detailed and structured anatomical location information. Multiple locations are allowed - e.g. multiple punch biopsies of a lesion.", 0, java.lang.Integer.MAX_VALUE, site));
}
public ProcedureBodySiteComponent copy() {
ProcedureBodySiteComponent dst = new ProcedureBodySiteComponent();
copyValues(dst);
dst.site = site == null ? null : site.copy();
return dst;
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof ProcedureBodySiteComponent))
return false;
ProcedureBodySiteComponent o = (ProcedureBodySiteComponent) other;
return compareDeep(site, o.site, true);
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof ProcedureBodySiteComponent))
return false;
ProcedureBodySiteComponent o = (ProcedureBodySiteComponent) other;
return true;
}
public boolean isEmpty() {
return super.isEmpty() && (site == null || site.isEmpty());
}
}
@Block()
public static class ProcedurePerformerComponent extends BackboneElement implements IBaseBackboneElement {
/**
* The practitioner who was involved in the procedure.
*/
@Child(name = "person", type = {Practitioner.class, Patient.class, RelatedPerson.class}, order=1, min=0, max=1)
@Description(shortDefinition="The reference to the practitioner", formalDefinition="The practitioner who was involved in the procedure." )
protected Reference person;
/**
* The actual object that is the target of the reference (The practitioner who was involved in the procedure.)
*/
protected Resource personTarget;
/**
* E.g. surgeon, anaethetist, endoscopist.
*/
@Child(name = "role", type = {CodeableConcept.class}, order=2, min=0, max=1)
@Description(shortDefinition="The role the person was in", formalDefinition="E.g. surgeon, anaethetist, endoscopist." )
protected CodeableConcept role;
private static final long serialVersionUID = -1975652413L;
/*
* Constructor
*/
public ProcedurePerformerComponent() {
super();
}
/**
* @return {@link #person} (The practitioner who was involved in the procedure.)
*/
public Reference getPerson() {
if (this.person == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ProcedurePerformerComponent.person");
else if (Configuration.doAutoCreate())
this.person = new Reference(); // cc
return this.person;
}
public boolean hasPerson() {
return this.person != null && !this.person.isEmpty();
}
/**
* @param value {@link #person} (The practitioner who was involved in the procedure.)
*/
public ProcedurePerformerComponent setPerson(Reference value) {
this.person = value;
return this;
}
/**
* @return {@link #person} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The practitioner who was involved in the procedure.)
*/
public Resource getPersonTarget() {
return this.personTarget;
}
/**
* @param value {@link #person} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The practitioner who was involved in the procedure.)
*/
public ProcedurePerformerComponent setPersonTarget(Resource value) {
this.personTarget = value;
return this;
}
/**
* @return {@link #role} (E.g. surgeon, anaethetist, endoscopist.)
*/
public CodeableConcept getRole() {
if (this.role == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ProcedurePerformerComponent.role");
else if (Configuration.doAutoCreate())
this.role = new CodeableConcept(); // cc
return this.role;
}
public boolean hasRole() {
return this.role != null && !this.role.isEmpty();
}
/**
* @param value {@link #role} (E.g. surgeon, anaethetist, endoscopist.)
*/
public ProcedurePerformerComponent setRole(CodeableConcept value) {
this.role = value;
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("person", "Reference(Practitioner|Patient|RelatedPerson)", "The practitioner who was involved in the procedure.", 0, java.lang.Integer.MAX_VALUE, person));
childrenList.add(new Property("role", "CodeableConcept", "E.g. surgeon, anaethetist, endoscopist.", 0, java.lang.Integer.MAX_VALUE, role));
}
public ProcedurePerformerComponent copy() {
ProcedurePerformerComponent dst = new ProcedurePerformerComponent();
copyValues(dst);
dst.person = person == null ? null : person.copy();
dst.role = role == null ? null : role.copy();
return dst;
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof ProcedurePerformerComponent))
return false;
ProcedurePerformerComponent o = (ProcedurePerformerComponent) other;
return compareDeep(person, o.person, true) && compareDeep(role, o.role, true);
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof ProcedurePerformerComponent))
return false;
ProcedurePerformerComponent o = (ProcedurePerformerComponent) other;
return true;
}
public boolean isEmpty() {
return super.isEmpty() && (person == null || person.isEmpty()) && (role == null || role.isEmpty())
;
}
}
@Block()
public static class ProcedureRelatedItemComponent extends BackboneElement implements IBaseBackboneElement {
/**
* The nature of the relationship.
*/
@Child(name = "type", type = {CodeType.class}, order=1, min=0, max=1)
@Description(shortDefinition="caused-by | because-of", formalDefinition="The nature of the relationship." )
protected Enumeration<ProcedureRelationshipType> type;
/**
* The related item - e.g. a procedure.
*/
@Child(name = "target", type = {AllergyIntolerance.class, CarePlan.class, Condition.class, DiagnosticReport.class, FamilyMemberHistory.class, ImagingStudy.class, Immunization.class, ImmunizationRecommendation.class, MedicationAdministration.class, MedicationDispense.class, MedicationPrescription.class, MedicationStatement.class, Observation.class, Procedure.class}, order=2, min=0, max=1)
@Description(shortDefinition="The related item - e.g. a procedure", formalDefinition="The related item - e.g. a procedure." )
protected Reference target;
/**
* The actual object that is the target of the reference (The related item - e.g. a procedure.)
*/
protected Resource targetTarget;
private static final long serialVersionUID = 41929784L;
/*
* Constructor
*/
public ProcedureRelatedItemComponent() {
super();
}
/**
* @return {@link #type} (The nature of the relationship.). This is the underlying object with id, value and extensions. The accessor "getType" gives direct access to the value
*/
public Enumeration<ProcedureRelationshipType> getTypeElement() {
if (this.type == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ProcedureRelatedItemComponent.type");
else if (Configuration.doAutoCreate())
this.type = new Enumeration<ProcedureRelationshipType>(new ProcedureRelationshipTypeEnumFactory()); // bb
return this.type;
}
public boolean hasTypeElement() {
return this.type != null && !this.type.isEmpty();
}
public boolean hasType() {
return this.type != null && !this.type.isEmpty();
}
/**
* @param value {@link #type} (The nature of the relationship.). This is the underlying object with id, value and extensions. The accessor "getType" gives direct access to the value
*/
public ProcedureRelatedItemComponent setTypeElement(Enumeration<ProcedureRelationshipType> value) {
this.type = value;
return this;
}
/**
* @return The nature of the relationship.
*/
public ProcedureRelationshipType getType() {
return this.type == null ? null : this.type.getValue();
}
/**
* @param value The nature of the relationship.
*/
public ProcedureRelatedItemComponent setType(ProcedureRelationshipType value) {
if (value == null)
this.type = null;
else {
if (this.type == null)
this.type = new Enumeration<ProcedureRelationshipType>(new ProcedureRelationshipTypeEnumFactory());
this.type.setValue(value);
}
return this;
}
/**
* @return {@link #target} (The related item - e.g. a procedure.)
*/
public Reference getTarget() {
if (this.target == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ProcedureRelatedItemComponent.target");
else if (Configuration.doAutoCreate())
this.target = new Reference(); // cc
return this.target;
}
public boolean hasTarget() {
return this.target != null && !this.target.isEmpty();
}
/**
* @param value {@link #target} (The related item - e.g. a procedure.)
*/
public ProcedureRelatedItemComponent setTarget(Reference value) {
this.target = value;
return this;
}
/**
* @return {@link #target} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The related item - e.g. a procedure.)
*/
public Resource getTargetTarget() {
return this.targetTarget;
}
/**
* @param value {@link #target} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The related item - e.g. a procedure.)
*/
public ProcedureRelatedItemComponent setTargetTarget(Resource value) {
this.targetTarget = value;
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("type", "code", "The nature of the relationship.", 0, java.lang.Integer.MAX_VALUE, type));
childrenList.add(new Property("target", "Reference(AllergyIntolerance|CarePlan|Condition|DiagnosticReport|FamilyMemberHistory|ImagingStudy|Immunization|ImmunizationRecommendation|MedicationAdministration|MedicationDispense|MedicationPrescription|MedicationStatement|Observation|Procedure)", "The related item - e.g. a procedure.", 0, java.lang.Integer.MAX_VALUE, target));
}
public ProcedureRelatedItemComponent copy() {
ProcedureRelatedItemComponent dst = new ProcedureRelatedItemComponent();
copyValues(dst);
dst.type = type == null ? null : type.copy();
dst.target = target == null ? null : target.copy();
return dst;
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof ProcedureRelatedItemComponent))
return false;
ProcedureRelatedItemComponent o = (ProcedureRelatedItemComponent) other;
return compareDeep(type, o.type, true) && compareDeep(target, o.target, true);
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof ProcedureRelatedItemComponent))
return false;
ProcedureRelatedItemComponent o = (ProcedureRelatedItemComponent) other;
return compareValues(type, o.type, true);
}
public boolean isEmpty() {
return super.isEmpty() && (type == null || type.isEmpty()) && (target == null || target.isEmpty())
;
}
}
@Block()
public static class ProcedureDeviceComponent extends BackboneElement implements IBaseBackboneElement {
/**
* The kind of change that happened to the device during the procedure.
*/
@Child(name = "action", type = {CodeableConcept.class}, order=1, min=0, max=1)
@Description(shortDefinition="Kind of change to device", formalDefinition="The kind of change that happened to the device during the procedure." )
protected CodeableConcept action;
/**
* The device that was manipulated (changed) during the procedure.
*/
@Child(name = "manipulated", type = {Device.class}, order=2, min=1, max=1)
@Description(shortDefinition="Device that was changed", formalDefinition="The device that was manipulated (changed) during the procedure." )
protected Reference manipulated;
/**
* The actual object that is the target of the reference (The device that was manipulated (changed) during the procedure.)
*/
protected Device manipulatedTarget;
private static final long serialVersionUID = 1779937807L;
/*
* Constructor
*/
public ProcedureDeviceComponent() {
super();
}
/*
* Constructor
*/
public ProcedureDeviceComponent(Reference manipulated) {
super();
this.manipulated = manipulated;
}
/**
* @return {@link #action} (The kind of change that happened to the device during the procedure.)
*/
public CodeableConcept getAction() {
if (this.action == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ProcedureDeviceComponent.action");
else if (Configuration.doAutoCreate())
this.action = new CodeableConcept(); // cc
return this.action;
}
public boolean hasAction() {
return this.action != null && !this.action.isEmpty();
}
/**
* @param value {@link #action} (The kind of change that happened to the device during the procedure.)
*/
public ProcedureDeviceComponent setAction(CodeableConcept value) {
this.action = value;
return this;
}
/**
* @return {@link #manipulated} (The device that was manipulated (changed) during the procedure.)
*/
public Reference getManipulated() {
if (this.manipulated == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ProcedureDeviceComponent.manipulated");
else if (Configuration.doAutoCreate())
this.manipulated = new Reference(); // cc
return this.manipulated;
}
public boolean hasManipulated() {
return this.manipulated != null && !this.manipulated.isEmpty();
}
/**
* @param value {@link #manipulated} (The device that was manipulated (changed) during the procedure.)
*/
public ProcedureDeviceComponent setManipulated(Reference value) {
this.manipulated = value;
return this;
}
/**
* @return {@link #manipulated} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The device that was manipulated (changed) during the procedure.)
*/
public Device getManipulatedTarget() {
if (this.manipulatedTarget == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ProcedureDeviceComponent.manipulated");
else if (Configuration.doAutoCreate())
this.manipulatedTarget = new Device(); // aa
return this.manipulatedTarget;
}
/**
* @param value {@link #manipulated} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The device that was manipulated (changed) during the procedure.)
*/
public ProcedureDeviceComponent setManipulatedTarget(Device value) {
this.manipulatedTarget = value;
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("action", "CodeableConcept", "The kind of change that happened to the device during the procedure.", 0, java.lang.Integer.MAX_VALUE, action));
childrenList.add(new Property("manipulated", "Reference(Device)", "The device that was manipulated (changed) during the procedure.", 0, java.lang.Integer.MAX_VALUE, manipulated));
}
public ProcedureDeviceComponent copy() {
ProcedureDeviceComponent dst = new ProcedureDeviceComponent();
copyValues(dst);
dst.action = action == null ? null : action.copy();
dst.manipulated = manipulated == null ? null : manipulated.copy();
return dst;
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof ProcedureDeviceComponent))
return false;
ProcedureDeviceComponent o = (ProcedureDeviceComponent) other;
return compareDeep(action, o.action, true) && compareDeep(manipulated, o.manipulated, true);
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof ProcedureDeviceComponent))
return false;
ProcedureDeviceComponent o = (ProcedureDeviceComponent) other;
return true;
}
public boolean isEmpty() {
return super.isEmpty() && (action == null || action.isEmpty()) && (manipulated == null || manipulated.isEmpty())
;
}
}
/**
* This records identifiers associated with this procedure that are defined by business processed and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation).
*/
@Child(name = "identifier", type = {Identifier.class}, order=0, min=0, max=Child.MAX_UNLIMITED)
@Description(shortDefinition="External Ids for this procedure", formalDefinition="This records identifiers associated with this procedure that are defined by business processed and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation)." )
protected List<Identifier> identifier;
/**
* The person on whom the procedure was performed.
*/
@Child(name = "patient", type = {Patient.class}, order=1, min=1, max=1)
@Description(shortDefinition="Who procedure was performed on", formalDefinition="The person on whom the procedure was performed." )
protected Reference patient;
/**
* The actual object that is the target of the reference (The person on whom the procedure was performed.)
*/
protected Patient patientTarget;
/**
* A code specifying the state of the procedure record. Generally this will be in-progress or completed state.
*/
@Child(name = "status", type = {CodeType.class}, order=2, min=1, max=1)
@Description(shortDefinition="in-progress | aborted | completed | entered-in-error", formalDefinition="A code specifying the state of the procedure record. Generally this will be in-progress or completed state." )
protected Enumeration<ProcedureStatus> status;
/**
* A code that classifies the procedure for searching, sorting and display purposes.
*/
@Child(name = "category", type = {CodeableConcept.class}, order=3, min=0, max=1)
@Description(shortDefinition="Classification of the procedure", formalDefinition="A code that classifies the procedure for searching, sorting and display purposes." )
protected CodeableConcept category;
/**
* The specific procedure that is performed. Use text if the exact nature of the procedure can't be coded.
*/
@Child(name = "type", type = {CodeableConcept.class}, order=4, min=1, max=1)
@Description(shortDefinition="Identification of the procedure", formalDefinition="The specific procedure that is performed. Use text if the exact nature of the procedure can't be coded." )
protected CodeableConcept type;
/**
* Detailed and structured anatomical location information. Multiple locations are allowed - e.g. multiple punch biopsies of a lesion.
*/
@Child(name = "bodySite", type = {}, order=5, min=0, max=Child.MAX_UNLIMITED)
@Description(shortDefinition="Precise location details", formalDefinition="Detailed and structured anatomical location information. Multiple locations are allowed - e.g. multiple punch biopsies of a lesion." )
protected List<ProcedureBodySiteComponent> bodySite;
/**
* The reason why the procedure was performed. This may be due to a Condition, may be coded entity of some type, or may simply be present as text.
*/
@Child(name = "indication", type = {CodeableConcept.class}, order=6, min=0, max=Child.MAX_UNLIMITED)
@Description(shortDefinition="Reason procedure performed", formalDefinition="The reason why the procedure was performed. This may be due to a Condition, may be coded entity of some type, or may simply be present as text." )
protected List<CodeableConcept> indication;
/**
* Limited to 'real' people rather than equipment.
*/
@Child(name = "performer", type = {}, order=7, min=0, max=Child.MAX_UNLIMITED)
@Description(shortDefinition="The people who performed the procedure", formalDefinition="Limited to 'real' people rather than equipment." )
protected List<ProcedurePerformerComponent> performer;
/**
* The date(time)/period over which the procedure was performed. Allows a period to support complex procedures that span more than one date, and also allows for the length of the procedure to be captured.
*/
@Child(name = "performed", type = {DateTimeType.class, Period.class}, order=8, min=0, max=1)
@Description(shortDefinition="Date/Period the procedure was performed", formalDefinition="The date(time)/period over which the procedure was performed. Allows a period to support complex procedures that span more than one date, and also allows for the length of the procedure to be captured." )
protected Type performed;
/**
* The encounter during which the procedure was performed.
*/
@Child(name = "encounter", type = {Encounter.class}, order=9, min=0, max=1)
@Description(shortDefinition="The encounter when procedure performed", formalDefinition="The encounter during which the procedure was performed." )
protected Reference encounter;
/**
* The actual object that is the target of the reference (The encounter during which the procedure was performed.)
*/
protected Encounter encounterTarget;
/**
* The location where the procedure actually happened. e.g. a newborn at home, a tracheostomy at a restaurant.
*/
@Child(name = "location", type = {Location.class}, order=10, min=0, max=1)
@Description(shortDefinition="Where the procedure happened", formalDefinition="The location where the procedure actually happened. e.g. a newborn at home, a tracheostomy at a restaurant." )
protected Reference location;
/**
* The actual object that is the target of the reference (The location where the procedure actually happened. e.g. a newborn at home, a tracheostomy at a restaurant.)
*/
protected Location locationTarget;
/**
* What was the outcome of the procedure - did it resolve reasons why the procedure was performed?
*/
@Child(name = "outcome", type = {CodeableConcept.class}, order=11, min=0, max=1)
@Description(shortDefinition="What was result of procedure?", formalDefinition="What was the outcome of the procedure - did it resolve reasons why the procedure was performed?" )
protected CodeableConcept outcome;
/**
* This could be a histology result. There could potentially be multiple reports - e.g. if this was a procedure that made multiple biopsies.
*/
@Child(name = "report", type = {DiagnosticReport.class}, order=12, min=0, max=Child.MAX_UNLIMITED)
@Description(shortDefinition="Any report that results from the procedure", formalDefinition="This could be a histology result. There could potentially be multiple reports - e.g. if this was a procedure that made multiple biopsies." )
protected List<Reference> report;
/**
* The actual objects that are the target of the reference (This could be a histology result. There could potentially be multiple reports - e.g. if this was a procedure that made multiple biopsies.)
*/
protected List<DiagnosticReport> reportTarget;
/**
* Any complications that occurred during the procedure, or in the immediate post-operative period. These are generally tracked separately from the notes, which typically will describe the procedure itself rather than any 'post procedure' issues.
*/
@Child(name = "complication", type = {CodeableConcept.class}, order=13, min=0, max=Child.MAX_UNLIMITED)
@Description(shortDefinition="Complication following the procedure", formalDefinition="Any complications that occurred during the procedure, or in the immediate post-operative period. These are generally tracked separately from the notes, which typically will describe the procedure itself rather than any 'post procedure' issues." )
protected List<CodeableConcept> complication;
/**
* If the procedure required specific follow up - e.g. removal of sutures. The followup may be represented as a simple note, or potentially could be more complex in which case the CarePlan resource can be used.
*/
@Child(name = "followUp", type = {CodeableConcept.class}, order=14, min=0, max=Child.MAX_UNLIMITED)
@Description(shortDefinition="Instructions for follow up", formalDefinition="If the procedure required specific follow up - e.g. removal of sutures. The followup may be represented as a simple note, or potentially could be more complex in which case the CarePlan resource can be used." )
protected List<CodeableConcept> followUp;
/**
* Procedures may be related to other items such as procedures or medications. For example treating wound dehiscence following a previous procedure.
*/
@Child(name = "relatedItem", type = {}, order=15, min=0, max=Child.MAX_UNLIMITED)
@Description(shortDefinition="A procedure that is related to this one", formalDefinition="Procedures may be related to other items such as procedures or medications. For example treating wound dehiscence following a previous procedure." )
protected List<ProcedureRelatedItemComponent> relatedItem;
/**
* Any other notes about the procedure - e.g. the operative notes.
*/
@Child(name = "notes", type = {StringType.class}, order=16, min=0, max=1)
@Description(shortDefinition="Additional information about procedure", formalDefinition="Any other notes about the procedure - e.g. the operative notes." )
protected StringType notes;
/**
* A device change during the procedure.
*/
@Child(name = "device", type = {}, order=17, min=0, max=Child.MAX_UNLIMITED)
@Description(shortDefinition="Device changed in procedure", formalDefinition="A device change during the procedure." )
protected List<ProcedureDeviceComponent> device;
/**
* Identifies medications, devices and other substance used as part of the procedure.
*/
@Child(name = "used", type = {Device.class, Medication.class, Substance.class}, order=18, min=0, max=Child.MAX_UNLIMITED)
@Description(shortDefinition="Items used during procedure", formalDefinition="Identifies medications, devices and other substance used as part of the procedure." )
protected List<Reference> used;
/**
* The actual objects that are the target of the reference (Identifies medications, devices and other substance used as part of the procedure.)
*/
protected List<Resource> usedTarget;
private static final long serialVersionUID = -1258770542L;
/*
* Constructor
*/
public Procedure() {
super();
}
/*
* Constructor
*/
public Procedure(Reference patient, Enumeration<ProcedureStatus> status, CodeableConcept type) {
super();
this.patient = patient;
this.status = status;
this.type = type;
}
/**
* @return {@link #identifier} (This records identifiers associated with this procedure that are defined by business processed and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation).)
*/
public List<Identifier> getIdentifier() {
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
return this.identifier;
}
public boolean hasIdentifier() {
if (this.identifier == null)
return false;
for (Identifier item : this.identifier)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #identifier} (This records identifiers associated with this procedure that are defined by business processed and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation).)
*/
// syntactic sugar
public Identifier addIdentifier() { //3
Identifier t = new Identifier();
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return t;
}
// syntactic sugar
public Procedure addIdentifier(Identifier t) { //3
if (t == null)
return this;
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return this;
}
/**
* @return {@link #patient} (The person on whom the procedure was performed.)
*/
public Reference getPatient() {
if (this.patient == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Procedure.patient");
else if (Configuration.doAutoCreate())
this.patient = new Reference(); // cc
return this.patient;
}
public boolean hasPatient() {
return this.patient != null && !this.patient.isEmpty();
}
/**
* @param value {@link #patient} (The person on whom the procedure was performed.)
*/
public Procedure setPatient(Reference value) {
this.patient = value;
return this;
}
/**
* @return {@link #patient} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The person on whom the procedure was performed.)
*/
public Patient getPatientTarget() {
if (this.patientTarget == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Procedure.patient");
else if (Configuration.doAutoCreate())
this.patientTarget = new Patient(); // aa
return this.patientTarget;
}
/**
* @param value {@link #patient} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The person on whom the procedure was performed.)
*/
public Procedure setPatientTarget(Patient value) {
this.patientTarget = value;
return this;
}
/**
* @return {@link #status} (A code specifying the state of the procedure record. Generally this will be in-progress or completed state.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value
*/
public Enumeration<ProcedureStatus> getStatusElement() {
if (this.status == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Procedure.status");
else if (Configuration.doAutoCreate())
this.status = new Enumeration<ProcedureStatus>(new ProcedureStatusEnumFactory()); // bb
return this.status;
}
public boolean hasStatusElement() {
return this.status != null && !this.status.isEmpty();
}
public boolean hasStatus() {
return this.status != null && !this.status.isEmpty();
}
/**
* @param value {@link #status} (A code specifying the state of the procedure record. Generally this will be in-progress or completed state.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value
*/
public Procedure setStatusElement(Enumeration<ProcedureStatus> value) {
this.status = value;
return this;
}
/**
* @return A code specifying the state of the procedure record. Generally this will be in-progress or completed state.
*/
public ProcedureStatus getStatus() {
return this.status == null ? null : this.status.getValue();
}
/**
* @param value A code specifying the state of the procedure record. Generally this will be in-progress or completed state.
*/
public Procedure setStatus(ProcedureStatus value) {
if (this.status == null)
this.status = new Enumeration<ProcedureStatus>(new ProcedureStatusEnumFactory());
this.status.setValue(value);
return this;
}
/**
* @return {@link #category} (A code that classifies the procedure for searching, sorting and display purposes.)
*/
public CodeableConcept getCategory() {
if (this.category == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Procedure.category");
else if (Configuration.doAutoCreate())
this.category = new CodeableConcept(); // cc
return this.category;
}
public boolean hasCategory() {
return this.category != null && !this.category.isEmpty();
}
/**
* @param value {@link #category} (A code that classifies the procedure for searching, sorting and display purposes.)
*/
public Procedure setCategory(CodeableConcept value) {
this.category = value;
return this;
}
/**
* @return {@link #type} (The specific procedure that is performed. Use text if the exact nature of the procedure can't be coded.)
*/
public CodeableConcept getType() {
if (this.type == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Procedure.type");
else if (Configuration.doAutoCreate())
this.type = new CodeableConcept(); // cc
return this.type;
}
public boolean hasType() {
return this.type != null && !this.type.isEmpty();
}
/**
* @param value {@link #type} (The specific procedure that is performed. Use text if the exact nature of the procedure can't be coded.)
*/
public Procedure setType(CodeableConcept value) {
this.type = value;
return this;
}
/**
* @return {@link #bodySite} (Detailed and structured anatomical location information. Multiple locations are allowed - e.g. multiple punch biopsies of a lesion.)
*/
public List<ProcedureBodySiteComponent> getBodySite() {
if (this.bodySite == null)
this.bodySite = new ArrayList<ProcedureBodySiteComponent>();
return this.bodySite;
}
public boolean hasBodySite() {
if (this.bodySite == null)
return false;
for (ProcedureBodySiteComponent item : this.bodySite)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #bodySite} (Detailed and structured anatomical location information. Multiple locations are allowed - e.g. multiple punch biopsies of a lesion.)
*/
// syntactic sugar
public ProcedureBodySiteComponent addBodySite() { //3
ProcedureBodySiteComponent t = new ProcedureBodySiteComponent();
if (this.bodySite == null)
this.bodySite = new ArrayList<ProcedureBodySiteComponent>();
this.bodySite.add(t);
return t;
}
// syntactic sugar
public Procedure addBodySite(ProcedureBodySiteComponent t) { //3
if (t == null)
return this;
if (this.bodySite == null)
this.bodySite = new ArrayList<ProcedureBodySiteComponent>();
this.bodySite.add(t);
return this;
}
/**
* @return {@link #indication} (The reason why the procedure was performed. This may be due to a Condition, may be coded entity of some type, or may simply be present as text.)
*/
public List<CodeableConcept> getIndication() {
if (this.indication == null)
this.indication = new ArrayList<CodeableConcept>();
return this.indication;
}
public boolean hasIndication() {
if (this.indication == null)
return false;
for (CodeableConcept item : this.indication)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #indication} (The reason why the procedure was performed. This may be due to a Condition, may be coded entity of some type, or may simply be present as text.)
*/
// syntactic sugar
public CodeableConcept addIndication() { //3
CodeableConcept t = new CodeableConcept();
if (this.indication == null)
this.indication = new ArrayList<CodeableConcept>();
this.indication.add(t);
return t;
}
// syntactic sugar
public Procedure addIndication(CodeableConcept t) { //3
if (t == null)
return this;
if (this.indication == null)
this.indication = new ArrayList<CodeableConcept>();
this.indication.add(t);
return this;
}
/**
* @return {@link #performer} (Limited to 'real' people rather than equipment.)
*/
public List<ProcedurePerformerComponent> getPerformer() {
if (this.performer == null)
this.performer = new ArrayList<ProcedurePerformerComponent>();
return this.performer;
}
public boolean hasPerformer() {
if (this.performer == null)
return false;
for (ProcedurePerformerComponent item : this.performer)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #performer} (Limited to 'real' people rather than equipment.)
*/
// syntactic sugar
public ProcedurePerformerComponent addPerformer() { //3
ProcedurePerformerComponent t = new ProcedurePerformerComponent();
if (this.performer == null)
this.performer = new ArrayList<ProcedurePerformerComponent>();
this.performer.add(t);
return t;
}
// syntactic sugar
public Procedure addPerformer(ProcedurePerformerComponent t) { //3
if (t == null)
return this;
if (this.performer == null)
this.performer = new ArrayList<ProcedurePerformerComponent>();
this.performer.add(t);
return this;
}
/**
* @return {@link #performed} (The date(time)/period over which the procedure was performed. Allows a period to support complex procedures that span more than one date, and also allows for the length of the procedure to be captured.)
*/
public Type getPerformed() {
return this.performed;
}
/**
* @return {@link #performed} (The date(time)/period over which the procedure was performed. Allows a period to support complex procedures that span more than one date, and also allows for the length of the procedure to be captured.)
*/
public DateTimeType getPerformedDateTimeType() throws Exception {
if (!(this.performed instanceof DateTimeType))
throw new Exception("Type mismatch: the type DateTimeType was expected, but "+this.performed.getClass().getName()+" was encountered");
return (DateTimeType) this.performed;
}
public boolean hasPerformedDateTimeType() throws Exception {
return this.performed instanceof DateTimeType;
}
/**
* @return {@link #performed} (The date(time)/period over which the procedure was performed. Allows a period to support complex procedures that span more than one date, and also allows for the length of the procedure to be captured.)
*/
public Period getPerformedPeriod() throws Exception {
if (!(this.performed instanceof Period))
throw new Exception("Type mismatch: the type Period was expected, but "+this.performed.getClass().getName()+" was encountered");
return (Period) this.performed;
}
public boolean hasPerformedPeriod() throws Exception {
return this.performed instanceof Period;
}
public boolean hasPerformed() {
return this.performed != null && !this.performed.isEmpty();
}
/**
* @param value {@link #performed} (The date(time)/period over which the procedure was performed. Allows a period to support complex procedures that span more than one date, and also allows for the length of the procedure to be captured.)
*/
public Procedure setPerformed(Type value) {
this.performed = value;
return this;
}
/**
* @return {@link #encounter} (The encounter during which the procedure was performed.)
*/
public Reference getEncounter() {
if (this.encounter == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Procedure.encounter");
else if (Configuration.doAutoCreate())
this.encounter = new Reference(); // cc
return this.encounter;
}
public boolean hasEncounter() {
return this.encounter != null && !this.encounter.isEmpty();
}
/**
* @param value {@link #encounter} (The encounter during which the procedure was performed.)
*/
public Procedure setEncounter(Reference value) {
this.encounter = value;
return this;
}
/**
* @return {@link #encounter} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The encounter during which the procedure was performed.)
*/
public Encounter getEncounterTarget() {
if (this.encounterTarget == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Procedure.encounter");
else if (Configuration.doAutoCreate())
this.encounterTarget = new Encounter(); // aa
return this.encounterTarget;
}
/**
* @param value {@link #encounter} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The encounter during which the procedure was performed.)
*/
public Procedure setEncounterTarget(Encounter value) {
this.encounterTarget = value;
return this;
}
/**
* @return {@link #location} (The location where the procedure actually happened. e.g. a newborn at home, a tracheostomy at a restaurant.)
*/
public Reference getLocation() {
if (this.location == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Procedure.location");
else if (Configuration.doAutoCreate())
this.location = new Reference(); // cc
return this.location;
}
public boolean hasLocation() {
return this.location != null && !this.location.isEmpty();
}
/**
* @param value {@link #location} (The location where the procedure actually happened. e.g. a newborn at home, a tracheostomy at a restaurant.)
*/
public Procedure setLocation(Reference value) {
this.location = value;
return this;
}
/**
* @return {@link #location} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The location where the procedure actually happened. e.g. a newborn at home, a tracheostomy at a restaurant.)
*/
public Location getLocationTarget() {
if (this.locationTarget == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Procedure.location");
else if (Configuration.doAutoCreate())
this.locationTarget = new Location(); // aa
return this.locationTarget;
}
/**
* @param value {@link #location} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The location where the procedure actually happened. e.g. a newborn at home, a tracheostomy at a restaurant.)
*/
public Procedure setLocationTarget(Location value) {
this.locationTarget = value;
return this;
}
/**
* @return {@link #outcome} (What was the outcome of the procedure - did it resolve reasons why the procedure was performed?)
*/
public CodeableConcept getOutcome() {
if (this.outcome == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Procedure.outcome");
else if (Configuration.doAutoCreate())
this.outcome = new CodeableConcept(); // cc
return this.outcome;
}
public boolean hasOutcome() {
return this.outcome != null && !this.outcome.isEmpty();
}
/**
* @param value {@link #outcome} (What was the outcome of the procedure - did it resolve reasons why the procedure was performed?)
*/
public Procedure setOutcome(CodeableConcept value) {
this.outcome = value;
return this;
}
/**
* @return {@link #report} (This could be a histology result. There could potentially be multiple reports - e.g. if this was a procedure that made multiple biopsies.)
*/
public List<Reference> getReport() {
if (this.report == null)
this.report = new ArrayList<Reference>();
return this.report;
}
public boolean hasReport() {
if (this.report == null)
return false;
for (Reference item : this.report)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #report} (This could be a histology result. There could potentially be multiple reports - e.g. if this was a procedure that made multiple biopsies.)
*/
// syntactic sugar
public Reference addReport() { //3
Reference t = new Reference();
if (this.report == null)
this.report = new ArrayList<Reference>();
this.report.add(t);
return t;
}
// syntactic sugar
public Procedure addReport(Reference t) { //3
if (t == null)
return this;
if (this.report == null)
this.report = new ArrayList<Reference>();
this.report.add(t);
return this;
}
/**
* @return {@link #report} (The actual objects that are the target of the reference. The reference library doesn't populate this, but you can use this to hold the resources if you resolvethemt. This could be a histology result. There could potentially be multiple reports - e.g. if this was a procedure that made multiple biopsies.)
*/
public List<DiagnosticReport> getReportTarget() {
if (this.reportTarget == null)
this.reportTarget = new ArrayList<DiagnosticReport>();
return this.reportTarget;
}
// syntactic sugar
/**
* @return {@link #report} (Add an actual object that is the target of the reference. The reference library doesn't use these, but you can use this to hold the resources if you resolvethemt. This could be a histology result. There could potentially be multiple reports - e.g. if this was a procedure that made multiple biopsies.)
*/
public DiagnosticReport addReportTarget() {
DiagnosticReport r = new DiagnosticReport();
if (this.reportTarget == null)
this.reportTarget = new ArrayList<DiagnosticReport>();
this.reportTarget.add(r);
return r;
}
/**
* @return {@link #complication} (Any complications that occurred during the procedure, or in the immediate post-operative period. These are generally tracked separately from the notes, which typically will describe the procedure itself rather than any 'post procedure' issues.)
*/
public List<CodeableConcept> getComplication() {
if (this.complication == null)
this.complication = new ArrayList<CodeableConcept>();
return this.complication;
}
public boolean hasComplication() {
if (this.complication == null)
return false;
for (CodeableConcept item : this.complication)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #complication} (Any complications that occurred during the procedure, or in the immediate post-operative period. These are generally tracked separately from the notes, which typically will describe the procedure itself rather than any 'post procedure' issues.)
*/
// syntactic sugar
public CodeableConcept addComplication() { //3
CodeableConcept t = new CodeableConcept();
if (this.complication == null)
this.complication = new ArrayList<CodeableConcept>();
this.complication.add(t);
return t;
}
// syntactic sugar
public Procedure addComplication(CodeableConcept t) { //3
if (t == null)
return this;
if (this.complication == null)
this.complication = new ArrayList<CodeableConcept>();
this.complication.add(t);
return this;
}
/**
* @return {@link #followUp} (If the procedure required specific follow up - e.g. removal of sutures. The followup may be represented as a simple note, or potentially could be more complex in which case the CarePlan resource can be used.)
*/
public List<CodeableConcept> getFollowUp() {
if (this.followUp == null)
this.followUp = new ArrayList<CodeableConcept>();
return this.followUp;
}
public boolean hasFollowUp() {
if (this.followUp == null)
return false;
for (CodeableConcept item : this.followUp)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #followUp} (If the procedure required specific follow up - e.g. removal of sutures. The followup may be represented as a simple note, or potentially could be more complex in which case the CarePlan resource can be used.)
*/
// syntactic sugar
public CodeableConcept addFollowUp() { //3
CodeableConcept t = new CodeableConcept();
if (this.followUp == null)
this.followUp = new ArrayList<CodeableConcept>();
this.followUp.add(t);
return t;
}
// syntactic sugar
public Procedure addFollowUp(CodeableConcept t) { //3
if (t == null)
return this;
if (this.followUp == null)
this.followUp = new ArrayList<CodeableConcept>();
this.followUp.add(t);
return this;
}
/**
* @return {@link #relatedItem} (Procedures may be related to other items such as procedures or medications. For example treating wound dehiscence following a previous procedure.)
*/
public List<ProcedureRelatedItemComponent> getRelatedItem() {
if (this.relatedItem == null)
this.relatedItem = new ArrayList<ProcedureRelatedItemComponent>();
return this.relatedItem;
}
public boolean hasRelatedItem() {
if (this.relatedItem == null)
return false;
for (ProcedureRelatedItemComponent item : this.relatedItem)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #relatedItem} (Procedures may be related to other items such as procedures or medications. For example treating wound dehiscence following a previous procedure.)
*/
// syntactic sugar
public ProcedureRelatedItemComponent addRelatedItem() { //3
ProcedureRelatedItemComponent t = new ProcedureRelatedItemComponent();
if (this.relatedItem == null)
this.relatedItem = new ArrayList<ProcedureRelatedItemComponent>();
this.relatedItem.add(t);
return t;
}
// syntactic sugar
public Procedure addRelatedItem(ProcedureRelatedItemComponent t) { //3
if (t == null)
return this;
if (this.relatedItem == null)
this.relatedItem = new ArrayList<ProcedureRelatedItemComponent>();
this.relatedItem.add(t);
return this;
}
/**
* @return {@link #notes} (Any other notes about the procedure - e.g. the operative notes.). This is the underlying object with id, value and extensions. The accessor "getNotes" gives direct access to the value
*/
public StringType getNotesElement() {
if (this.notes == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Procedure.notes");
else if (Configuration.doAutoCreate())
this.notes = new StringType(); // bb
return this.notes;
}
public boolean hasNotesElement() {
return this.notes != null && !this.notes.isEmpty();
}
public boolean hasNotes() {
return this.notes != null && !this.notes.isEmpty();
}
/**
* @param value {@link #notes} (Any other notes about the procedure - e.g. the operative notes.). This is the underlying object with id, value and extensions. The accessor "getNotes" gives direct access to the value
*/
public Procedure setNotesElement(StringType value) {
this.notes = value;
return this;
}
/**
* @return Any other notes about the procedure - e.g. the operative notes.
*/
public String getNotes() {
return this.notes == null ? null : this.notes.getValue();
}
/**
* @param value Any other notes about the procedure - e.g. the operative notes.
*/
public Procedure setNotes(String value) {
if (Utilities.noString(value))
this.notes = null;
else {
if (this.notes == null)
this.notes = new StringType();
this.notes.setValue(value);
}
return this;
}
/**
* @return {@link #device} (A device change during the procedure.)
*/
public List<ProcedureDeviceComponent> getDevice() {
if (this.device == null)
this.device = new ArrayList<ProcedureDeviceComponent>();
return this.device;
}
public boolean hasDevice() {
if (this.device == null)
return false;
for (ProcedureDeviceComponent item : this.device)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #device} (A device change during the procedure.)
*/
// syntactic sugar
public ProcedureDeviceComponent addDevice() { //3
ProcedureDeviceComponent t = new ProcedureDeviceComponent();
if (this.device == null)
this.device = new ArrayList<ProcedureDeviceComponent>();
this.device.add(t);
return t;
}
// syntactic sugar
public Procedure addDevice(ProcedureDeviceComponent t) { //3
if (t == null)
return this;
if (this.device == null)
this.device = new ArrayList<ProcedureDeviceComponent>();
this.device.add(t);
return this;
}
/**
* @return {@link #used} (Identifies medications, devices and other substance used as part of the procedure.)
*/
public List<Reference> getUsed() {
if (this.used == null)
this.used = new ArrayList<Reference>();
return this.used;
}
public boolean hasUsed() {
if (this.used == null)
return false;
for (Reference item : this.used)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #used} (Identifies medications, devices and other substance used as part of the procedure.)
*/
// syntactic sugar
public Reference addUsed() { //3
Reference t = new Reference();
if (this.used == null)
this.used = new ArrayList<Reference>();
this.used.add(t);
return t;
}
// syntactic sugar
public Procedure addUsed(Reference t) { //3
if (t == null)
return this;
if (this.used == null)
this.used = new ArrayList<Reference>();
this.used.add(t);
return this;
}
/**
* @return {@link #used} (The actual objects that are the target of the reference. The reference library doesn't populate this, but you can use this to hold the resources if you resolvethemt. Identifies medications, devices and other substance used as part of the procedure.)
*/
public List<Resource> getUsedTarget() {
if (this.usedTarget == null)
this.usedTarget = new ArrayList<Resource>();
return this.usedTarget;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("identifier", "Identifier", "This records identifiers associated with this procedure that are defined by business processed and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation).", 0, java.lang.Integer.MAX_VALUE, identifier));
childrenList.add(new Property("patient", "Reference(Patient)", "The person on whom the procedure was performed.", 0, java.lang.Integer.MAX_VALUE, patient));
childrenList.add(new Property("status", "code", "A code specifying the state of the procedure record. Generally this will be in-progress or completed state.", 0, java.lang.Integer.MAX_VALUE, status));
childrenList.add(new Property("category", "CodeableConcept", "A code that classifies the procedure for searching, sorting and display purposes.", 0, java.lang.Integer.MAX_VALUE, category));
childrenList.add(new Property("type", "CodeableConcept", "The specific procedure that is performed. Use text if the exact nature of the procedure can't be coded.", 0, java.lang.Integer.MAX_VALUE, type));
childrenList.add(new Property("bodySite", "", "Detailed and structured anatomical location information. Multiple locations are allowed - e.g. multiple punch biopsies of a lesion.", 0, java.lang.Integer.MAX_VALUE, bodySite));
childrenList.add(new Property("indication", "CodeableConcept", "The reason why the procedure was performed. This may be due to a Condition, may be coded entity of some type, or may simply be present as text.", 0, java.lang.Integer.MAX_VALUE, indication));
childrenList.add(new Property("performer", "", "Limited to 'real' people rather than equipment.", 0, java.lang.Integer.MAX_VALUE, performer));
childrenList.add(new Property("performed[x]", "dateTime|Period", "The date(time)/period over which the procedure was performed. Allows a period to support complex procedures that span more than one date, and also allows for the length of the procedure to be captured.", 0, java.lang.Integer.MAX_VALUE, performed));
childrenList.add(new Property("encounter", "Reference(Encounter)", "The encounter during which the procedure was performed.", 0, java.lang.Integer.MAX_VALUE, encounter));
childrenList.add(new Property("location", "Reference(Location)", "The location where the procedure actually happened. e.g. a newborn at home, a tracheostomy at a restaurant.", 0, java.lang.Integer.MAX_VALUE, location));
childrenList.add(new Property("outcome", "CodeableConcept", "What was the outcome of the procedure - did it resolve reasons why the procedure was performed?", 0, java.lang.Integer.MAX_VALUE, outcome));
childrenList.add(new Property("report", "Reference(DiagnosticReport)", "This could be a histology result. There could potentially be multiple reports - e.g. if this was a procedure that made multiple biopsies.", 0, java.lang.Integer.MAX_VALUE, report));
childrenList.add(new Property("complication", "CodeableConcept", "Any complications that occurred during the procedure, or in the immediate post-operative period. These are generally tracked separately from the notes, which typically will describe the procedure itself rather than any 'post procedure' issues.", 0, java.lang.Integer.MAX_VALUE, complication));
childrenList.add(new Property("followUp", "CodeableConcept", "If the procedure required specific follow up - e.g. removal of sutures. The followup may be represented as a simple note, or potentially could be more complex in which case the CarePlan resource can be used.", 0, java.lang.Integer.MAX_VALUE, followUp));
childrenList.add(new Property("relatedItem", "", "Procedures may be related to other items such as procedures or medications. For example treating wound dehiscence following a previous procedure.", 0, java.lang.Integer.MAX_VALUE, relatedItem));
childrenList.add(new Property("notes", "string", "Any other notes about the procedure - e.g. the operative notes.", 0, java.lang.Integer.MAX_VALUE, notes));
childrenList.add(new Property("device", "", "A device change during the procedure.", 0, java.lang.Integer.MAX_VALUE, device));
childrenList.add(new Property("used", "Reference(Device|Medication|Substance)", "Identifies medications, devices and other substance used as part of the procedure.", 0, java.lang.Integer.MAX_VALUE, used));
}
public Procedure copy() {
Procedure dst = new Procedure();
copyValues(dst);
if (identifier != null) {
dst.identifier = new ArrayList<Identifier>();
for (Identifier i : identifier)
dst.identifier.add(i.copy());
};
dst.patient = patient == null ? null : patient.copy();
dst.status = status == null ? null : status.copy();
dst.category = category == null ? null : category.copy();
dst.type = type == null ? null : type.copy();
if (bodySite != null) {
dst.bodySite = new ArrayList<ProcedureBodySiteComponent>();
for (ProcedureBodySiteComponent i : bodySite)
dst.bodySite.add(i.copy());
};
if (indication != null) {
dst.indication = new ArrayList<CodeableConcept>();
for (CodeableConcept i : indication)
dst.indication.add(i.copy());
};
if (performer != null) {
dst.performer = new ArrayList<ProcedurePerformerComponent>();
for (ProcedurePerformerComponent i : performer)
dst.performer.add(i.copy());
};
dst.performed = performed == null ? null : performed.copy();
dst.encounter = encounter == null ? null : encounter.copy();
dst.location = location == null ? null : location.copy();
dst.outcome = outcome == null ? null : outcome.copy();
if (report != null) {
dst.report = new ArrayList<Reference>();
for (Reference i : report)
dst.report.add(i.copy());
};
if (complication != null) {
dst.complication = new ArrayList<CodeableConcept>();
for (CodeableConcept i : complication)
dst.complication.add(i.copy());
};
if (followUp != null) {
dst.followUp = new ArrayList<CodeableConcept>();
for (CodeableConcept i : followUp)
dst.followUp.add(i.copy());
};
if (relatedItem != null) {
dst.relatedItem = new ArrayList<ProcedureRelatedItemComponent>();
for (ProcedureRelatedItemComponent i : relatedItem)
dst.relatedItem.add(i.copy());
};
dst.notes = notes == null ? null : notes.copy();
if (device != null) {
dst.device = new ArrayList<ProcedureDeviceComponent>();
for (ProcedureDeviceComponent i : device)
dst.device.add(i.copy());
};
if (used != null) {
dst.used = new ArrayList<Reference>();
for (Reference i : used)
dst.used.add(i.copy());
};
return dst;
}
protected Procedure typedCopy() {
return copy();
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof Procedure))
return false;
Procedure o = (Procedure) other;
return compareDeep(identifier, o.identifier, true) && compareDeep(patient, o.patient, true) && compareDeep(status, o.status, true)
&& compareDeep(category, o.category, true) && compareDeep(type, o.type, true) && compareDeep(bodySite, o.bodySite, true)
&& compareDeep(indication, o.indication, true) && compareDeep(performer, o.performer, true) && compareDeep(performed, o.performed, true)
&& compareDeep(encounter, o.encounter, true) && compareDeep(location, o.location, true) && compareDeep(outcome, o.outcome, true)
&& compareDeep(report, o.report, true) && compareDeep(complication, o.complication, true) && compareDeep(followUp, o.followUp, true)
&& compareDeep(relatedItem, o.relatedItem, true) && compareDeep(notes, o.notes, true) && compareDeep(device, o.device, true)
&& compareDeep(used, o.used, true);
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof Procedure))
return false;
Procedure o = (Procedure) other;
return compareValues(status, o.status, true) && compareValues(notes, o.notes, true);
}
public boolean isEmpty() {
return super.isEmpty() && (identifier == null || identifier.isEmpty()) && (patient == null || patient.isEmpty())
&& (status == null || status.isEmpty()) && (category == null || category.isEmpty()) && (type == null || type.isEmpty())
&& (bodySite == null || bodySite.isEmpty()) && (indication == null || indication.isEmpty())
&& (performer == null || performer.isEmpty()) && (performed == null || performed.isEmpty())
&& (encounter == null || encounter.isEmpty()) && (location == null || location.isEmpty())
&& (outcome == null || outcome.isEmpty()) && (report == null || report.isEmpty()) && (complication == null || complication.isEmpty())
&& (followUp == null || followUp.isEmpty()) && (relatedItem == null || relatedItem.isEmpty())
&& (notes == null || notes.isEmpty()) && (device == null || device.isEmpty()) && (used == null || used.isEmpty())
;
}
@Override
public ResourceType getResourceType() {
return ResourceType.Procedure;
}
@SearchParamDefinition(name="date", path="Procedure.performed[x]", description="Date/Period the procedure was performed", type="date" )
public static final String SP_DATE = "date";
@SearchParamDefinition(name="performer", path="Procedure.performer.person", description="The reference to the practitioner", type="reference" )
public static final String SP_PERFORMER = "performer";
@SearchParamDefinition(name="patient", path="Procedure.patient", description="The identity of a patient to list procedures for", type="reference" )
public static final String SP_PATIENT = "patient";
@SearchParamDefinition(name="location", path="Procedure.location", description="Where the procedure happened", type="reference" )
public static final String SP_LOCATION = "location";
@SearchParamDefinition(name="encounter", path="Procedure.encounter", description="The encounter when procedure performed", type="reference" )
public static final String SP_ENCOUNTER = "encounter";
@SearchParamDefinition(name="type", path="Procedure.type", description="Type of procedure", type="token" )
public static final String SP_TYPE = "type";
}
| apache-2.0 |
vistone/pdf.js | make.js | 32624 | /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* Copyright 2012 Mozilla 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.
*/
/* jshint node:true */
/* globals cat, cd, cp, echo, env, exec, exit, find, ls, mkdir, mv, process, rm,
sed, target, test */
'use strict';
require('./external/shelljs/make');
var builder = require('./external/builder/builder.js');
var crlfchecker = require('./external/crlfchecker/crlfchecker.js');
var path = require('path');
var ROOT_DIR = __dirname + '/', // absolute path to project's root
BUILD_DIR = 'build/',
SRC_DIR = 'src/',
BUILD_TARGET = BUILD_DIR + 'pdf.js',
BUILD_WORKER_TARGET = BUILD_DIR + 'pdf.worker.js',
BUILD_TARGETS = [BUILD_TARGET, BUILD_WORKER_TARGET],
FIREFOX_BUILD_DIR = BUILD_DIR + '/firefox/',
CHROME_BUILD_DIR = BUILD_DIR + '/chrome/',
EXTENSION_SRC_DIR = 'extensions/',
LOCALE_SRC_DIR = 'l10n/',
GH_PAGES_DIR = BUILD_DIR + 'gh-pages/',
GENERIC_DIR = BUILD_DIR + 'generic/',
REPO = 'git@github.com:mozilla/pdf.js.git',
PYTHON_BIN = 'python2.7',
MOZCENTRAL_PREF_PREFIX = 'pdfjs',
FIREFOX_PREF_PREFIX = 'extensions.uriloader@pdf.js',
MOZCENTRAL_STREAM_CONVERTER_ID = 'd0c5195d-e798-49d4-b1d3-9324328b2291',
FIREFOX_STREAM_CONVERTER_ID = '6457a96b-2d68-439a-bcfa-44465fbcdbb1';
var DEFINES = {
PRODUCTION: true,
// The main build targets:
GENERIC: false,
FIREFOX: false,
MOZCENTRAL: false,
B2G: false,
CHROME: false
};
//
// make all
//
target.all = function() {
// Don't do anything by default
echo('Please specify a target. Available targets:');
for (var t in target)
if (t !== 'all') echo(' ' + t);
};
////////////////////////////////////////////////////////////////////////////////
//
// Production stuff
//
// Files that need to be included in every build.
var COMMON_WEB_FILES =
['web/images',
'web/debugger.js'],
COMMON_WEB_FILES_PREPROCESS =
['web/viewer.js',
'web/viewer.html'];
//
// make generic
// Builds the generic production viewer that should be compatible with most
// modern HTML5 browsers.
//
target.generic = function() {
target.bundle({});
target.locale();
cd(ROOT_DIR);
echo();
echo('### Creating generic viewer');
rm('-rf', GENERIC_DIR);
mkdir('-p', GENERIC_DIR);
mkdir('-p', GENERIC_DIR + BUILD_DIR);
mkdir('-p', GENERIC_DIR + '/web');
var defines = builder.merge(DEFINES, {GENERIC: true});
var setup = {
defines: defines,
copy: [
[COMMON_WEB_FILES, GENERIC_DIR + '/web'],
['external/webL10n/l10n.js', GENERIC_DIR + '/web'],
['web/viewer.css', GENERIC_DIR + '/web'],
['web/compatibility.js', GENERIC_DIR + '/web'],
['web/compressed.tracemonkey-pldi-09.pdf', GENERIC_DIR + '/web'],
['web/locale', GENERIC_DIR + '/web']
],
preprocess: [
[BUILD_TARGETS, GENERIC_DIR + BUILD_DIR],
[COMMON_WEB_FILES_PREPROCESS, GENERIC_DIR + '/web']
]
};
builder.build(setup);
cleanupJSSource(GENERIC_DIR + '/web/viewer.js');
};
//
// make web
// Generates the website for the project, by checking out the gh-pages branch
// underneath the build directory, and then moving the various viewer files
// into place.
//
target.web = function() {
target.generic();
target.extension();
echo();
echo('### Creating web site');
if (test('-d', GH_PAGES_DIR))
rm('-rf', GH_PAGES_DIR);
mkdir('-p', GH_PAGES_DIR + '/web');
mkdir('-p', GH_PAGES_DIR + '/web/images');
mkdir('-p', GH_PAGES_DIR + BUILD_DIR);
mkdir('-p', GH_PAGES_DIR + EXTENSION_SRC_DIR + '/firefox');
mkdir('-p', GH_PAGES_DIR + EXTENSION_SRC_DIR + '/chrome');
cp('-R', GENERIC_DIR + '/*', GH_PAGES_DIR);
cp(FIREFOX_BUILD_DIR + '/*.xpi', FIREFOX_BUILD_DIR + '/*.rdf',
GH_PAGES_DIR + EXTENSION_SRC_DIR + 'firefox/');
cp(CHROME_BUILD_DIR + '/*.crx', FIREFOX_BUILD_DIR + '/*.rdf',
GH_PAGES_DIR + EXTENSION_SRC_DIR + 'chrome/');
cp('web/index.html.template', GH_PAGES_DIR + '/index.html');
cp('-R', 'test/features', GH_PAGES_DIR);
cd(GH_PAGES_DIR);
exec('git init');
exec('git remote add origin ' + REPO);
exec('git add -A');
exec('git commit -am "gh-pages site created via make.js script"');
exec('git branch -m gh-pages');
echo();
echo('Website built in ' + GH_PAGES_DIR);
};
//
// make locale
// Creates localized resources for the viewer and extension.
//
target.locale = function() {
var METADATA_OUTPUT = 'extensions/firefox/metadata.inc';
var CHROME_MANIFEST_OUTPUT = 'extensions/firefox/chrome.manifest.inc';
var EXTENSION_LOCALE_OUTPUT = 'extensions/firefox/locale';
var VIEWER_LOCALE_OUTPUT = 'web/locale/';
cd(ROOT_DIR);
echo();
echo('### Building localization files');
rm('-rf', EXTENSION_LOCALE_OUTPUT);
mkdir('-p', EXTENSION_LOCALE_OUTPUT);
rm('-rf', VIEWER_LOCALE_OUTPUT);
mkdir('-p', VIEWER_LOCALE_OUTPUT);
var subfolders = ls(LOCALE_SRC_DIR);
subfolders.sort();
var metadataContent = '';
var chromeManifestContent = '';
var viewerOutput = '';
for (var i = 0; i < subfolders.length; i++) {
var locale = subfolders[i];
var path = LOCALE_SRC_DIR + locale;
if (!test('-d', path))
continue;
if (!/^[a-z][a-z](-[A-Z][A-Z])?$/.test(locale)) {
echo('Skipping invalid locale: ' + locale);
continue;
}
mkdir('-p', EXTENSION_LOCALE_OUTPUT + '/' + locale);
mkdir('-p', VIEWER_LOCALE_OUTPUT + '/' + locale);
chromeManifestContent += 'locale pdf.js ' + locale + ' locale/' +
locale + '/\n';
if (test('-f', path + '/viewer.properties')) {
viewerOutput += '[' + locale + ']\n' +
'@import url(' + locale + '/viewer.properties)\n\n';
cp(path + '/viewer.properties', EXTENSION_LOCALE_OUTPUT + '/' + locale);
cp(path + '/viewer.properties', VIEWER_LOCALE_OUTPUT + '/' + locale);
}
if (test('-f', path + '/chrome.properties')) {
cp(path + '/chrome.properties', EXTENSION_LOCALE_OUTPUT + '/' + locale);
}
if (test('-f', path + '/metadata.inc')) {
var metadata = cat(path + '/metadata.inc');
metadataContent += metadata;
}
}
viewerOutput.to(VIEWER_LOCALE_OUTPUT + 'locale.properties');
metadataContent.to(METADATA_OUTPUT);
chromeManifestContent.to(CHROME_MANIFEST_OUTPUT);
};
//
// make bundle
// Bundles all source files into one wrapper 'pdf.js' file, in the given order.
//
target.bundle = function(args) {
args = args || {};
var defines = args.defines || DEFINES;
var excludes = args.excludes || [];
target.buildnumber();
cd(ROOT_DIR);
echo();
echo('### Bundling files into ' + BUILD_TARGET);
var reg = /\n\/\* -\*- Mode(.|\n)*?Mozilla Foundation(.|\n)*?'use strict';/g;
function bundle(filename, dir, SRC_FILES, EXT_SRC_FILES) {
for (var i = 0, length = excludes.length; i < length; ++i) {
var exclude = excludes[i];
var index = SRC_FILES.indexOf(exclude);
if (index >= 0) {
SRC_FILES.splice(index, 1);
}
}
var bundle = cat(SRC_FILES),
bundleVersion = EXTENSION_VERSION,
bundleBuild = exec('git log --format="%h" -n 1',
{silent: true}).output.replace('\n', '');
crlfchecker.checkIfCrlfIsPresent(SRC_FILES);
// Strip out all the vim/license headers.
bundle = bundle.replace(reg, '');
// Append external files last since we don't want to modify them.
bundle += cat(EXT_SRC_FILES);
// This just preprocesses the empty pdf.js file, we don't actually want to
// preprocess everything yet since other build targets use this file.
builder.preprocess(filename, dir, builder.merge(defines,
{BUNDLE: bundle,
BUNDLE_VERSION: bundleVersion,
BUNDLE_BUILD: bundleBuild}));
}
if (!test('-d', BUILD_DIR))
mkdir(BUILD_DIR);
var MAIN_SRC_FILES = [
'shared/util.js',
'shared/colorspace.js',
'shared/pattern.js',
'shared/function.js',
'shared/annotation.js',
'display/api.js',
'display/metadata.js',
'display/canvas.js',
'display/font_loader.js',
'display/font_renderer.js'
];
var WORKER_SRC_FILES = [
'shared/util.js',
'shared/pattern.js',
'shared/function.js',
'shared/annotation.js',
'core/network.js',
'core/chunked_stream.js',
'core/pdf_manager.js',
'core/core.js',
'core/obj.js',
'core/charsets.js',
'core/cidmaps.js',
'shared/colorspace.js',
'core/crypto.js',
'core/evaluator.js',
'core/fonts.js',
'core/glyphlist.js',
'core/image.js',
'core/metrics.js',
'core/parser.js',
'core/stream.js',
'core/worker.js',
'core/jpx.js',
'core/jbig2.js',
'core/bidi.js'
];
var EXT_SRC_FILES = [
'../external/jpgjs/jpg.js'
];
cd(SRC_DIR);
bundle('pdf.js', ROOT_DIR + BUILD_TARGET, MAIN_SRC_FILES, []);
var srcCopy = ROOT_DIR + BUILD_DIR + 'pdf.worker.js.temp';
cp('pdf.js', srcCopy);
bundle(srcCopy, ROOT_DIR + BUILD_WORKER_TARGET, WORKER_SRC_FILES,
EXT_SRC_FILES);
rm(srcCopy);
};
function cleanupJSSource(file) {
var content = cat(file);
// Strip out all the vim/license headers.
var reg = /\n\/\* -\*- Mode(.|\n)*?Mozilla Foundation(.|\n)*?'use strict';/g;
content = content.replace(reg, '');
content.to(file);
}
////////////////////////////////////////////////////////////////////////////////
//
// Extension stuff
//
var EXTENSION_BASE_VERSION = '0ac55ac879d1c0eea9c0d155d5bbd9b11560f631',
EXTENSION_VERSION_PREFIX = '0.8.',
EXTENSION_BUILD_NUMBER,
EXTENSION_VERSION;
//
// make extension
//
target.extension = function() {
cd(ROOT_DIR);
echo();
echo('### Building extensions');
target.locale();
target.firefox();
target.chrome();
};
target.buildnumber = function() {
cd(ROOT_DIR);
echo();
echo('### Getting extension build number');
var lines = exec('git log --format=oneline ' +
EXTENSION_BASE_VERSION + '..', {silent: true}).output;
// Build number is the number of commits since base version
EXTENSION_BUILD_NUMBER = lines ? lines.match(/\n/g).length : 0;
echo('Extension build number: ' + EXTENSION_BUILD_NUMBER);
EXTENSION_VERSION = EXTENSION_VERSION_PREFIX + EXTENSION_BUILD_NUMBER;
};
//
// make firefox
//
target.firefox = function() {
cd(ROOT_DIR);
echo();
echo('### Building Firefox extension');
var defines = builder.merge(DEFINES, {FIREFOX: true});
var FIREFOX_BUILD_CONTENT_DIR = FIREFOX_BUILD_DIR + '/content/',
FIREFOX_EXTENSION_DIR = 'extensions/firefox/',
FIREFOX_CONTENT_DIR = EXTENSION_SRC_DIR + '/firefox/content/',
FIREFOX_EXTENSION_FILES_TO_COPY =
['*.js',
'*.rdf',
'*.svg',
'*.png',
'*.manifest',
'components',
'locale',
'../../LICENSE'],
FIREFOX_EXTENSION_FILES =
['bootstrap.js',
'install.rdf',
'chrome.manifest',
'icon.png',
'icon64.png',
'components',
'content',
'locale',
'LICENSE'],
FIREFOX_EXTENSION_NAME = 'pdf.js.xpi',
FIREFOX_AMO_EXTENSION_NAME = 'pdf.js.amo.xpi';
target.locale();
target.bundle({ excludes: ['core/network.js'], defines: defines });
cd(ROOT_DIR);
// Clear out everything in the firefox extension build directory
rm('-rf', FIREFOX_BUILD_DIR);
mkdir('-p', FIREFOX_BUILD_CONTENT_DIR);
mkdir('-p', FIREFOX_BUILD_CONTENT_DIR + BUILD_DIR);
mkdir('-p', FIREFOX_BUILD_CONTENT_DIR + '/web');
cp(FIREFOX_CONTENT_DIR + 'PdfJs-stub.jsm',
FIREFOX_BUILD_CONTENT_DIR + 'PdfJs.jsm');
cp(FIREFOX_CONTENT_DIR + 'PdfJsTelemetry-addon.jsm',
FIREFOX_BUILD_CONTENT_DIR + 'PdfJsTelemetry.jsm');
// Copy extension files
cd(FIREFOX_EXTENSION_DIR);
cp('-R', FIREFOX_EXTENSION_FILES_TO_COPY, ROOT_DIR + FIREFOX_BUILD_DIR);
cd(ROOT_DIR);
var setup = {
defines: defines,
copy: [
[COMMON_WEB_FILES, FIREFOX_BUILD_CONTENT_DIR + '/web'],
[FIREFOX_EXTENSION_DIR + 'tools/l10n.js',
FIREFOX_BUILD_CONTENT_DIR + '/web']
],
preprocess: [
[COMMON_WEB_FILES_PREPROCESS, FIREFOX_BUILD_CONTENT_DIR + '/web'],
[BUILD_TARGETS, FIREFOX_BUILD_CONTENT_DIR + BUILD_DIR],
[SRC_DIR + 'core/network.js', FIREFOX_BUILD_CONTENT_DIR]
],
preprocessCSS: [
['firefox', 'web/viewer.css',
FIREFOX_BUILD_CONTENT_DIR + '/web/viewer.css']
]
};
builder.build(setup);
cleanupJSSource(FIREFOX_BUILD_CONTENT_DIR + '/web/viewer.js');
// Remove '.DS_Store' and other hidden files
find(FIREFOX_BUILD_DIR).forEach(function(file) {
if (file.match(/^\./))
rm('-f', file);
});
// Update the build version number
sed('-i', /PDFJSSCRIPT_VERSION/, EXTENSION_VERSION,
FIREFOX_BUILD_DIR + '/install.rdf');
sed('-i', /PDFJSSCRIPT_VERSION/, EXTENSION_VERSION,
FIREFOX_BUILD_DIR + '/update.rdf');
sed('-i', /PDFJSSCRIPT_STREAM_CONVERTER_ID/, FIREFOX_STREAM_CONVERTER_ID,
FIREFOX_BUILD_DIR + 'components/PdfStreamConverter.js');
sed('-i', /PDFJSSCRIPT_PREF_PREFIX/, FIREFOX_PREF_PREFIX,
FIREFOX_BUILD_DIR + 'components/PdfStreamConverter.js');
sed('-i', /PDFJSSCRIPT_MOZ_CENTRAL/, 'false',
FIREFOX_BUILD_DIR + 'components/PdfStreamConverter.js');
// Update localized metadata
var localizedMetadata = cat(EXTENSION_SRC_DIR + '/firefox/metadata.inc');
sed('-i', /.*PDFJS_LOCALIZED_METADATA.*\n/, localizedMetadata,
FIREFOX_BUILD_DIR + '/install.rdf');
var chromeManifest = cat(EXTENSION_SRC_DIR + '/firefox/chrome.manifest.inc');
sed('-i', /.*PDFJS_SUPPORTED_LOCALES.*\n/, chromeManifest,
FIREFOX_BUILD_DIR + '/chrome.manifest');
// Create the xpi
cd(FIREFOX_BUILD_DIR);
exec('zip -r ' + FIREFOX_EXTENSION_NAME + ' ' +
FIREFOX_EXTENSION_FILES.join(' '));
echo('extension created: ' + FIREFOX_EXTENSION_NAME);
cd(ROOT_DIR);
// Build the amo extension too (remove the updateUrl)
cd(FIREFOX_BUILD_DIR);
sed('-i', /.*updateURL.*\n/, '', 'install.rdf');
exec('zip -r ' + FIREFOX_AMO_EXTENSION_NAME + ' ' +
FIREFOX_EXTENSION_FILES.join(' '));
echo('AMO extension created: ' + FIREFOX_AMO_EXTENSION_NAME);
cd(ROOT_DIR);
};
//
// make mozcentral
//
target.mozcentral = function() {
cd(ROOT_DIR);
echo();
echo('### Building mozilla-central extension');
var defines = builder.merge(DEFINES, {MOZCENTRAL: true});
var MOZCENTRAL_DIR = BUILD_DIR + 'mozcentral/',
MOZCENTRAL_EXTENSION_DIR = MOZCENTRAL_DIR + 'browser/extensions/pdfjs/',
MOZCENTRAL_CONTENT_DIR = MOZCENTRAL_EXTENSION_DIR + 'content/',
MOZCENTRAL_L10N_DIR = MOZCENTRAL_DIR + 'browser/locales/en-US/pdfviewer/',
MOZCENTRAL_TEST_DIR = MOZCENTRAL_EXTENSION_DIR + 'test/',
FIREFOX_CONTENT_DIR = EXTENSION_SRC_DIR + '/firefox/content/',
FIREFOX_EXTENSION_FILES_TO_COPY =
['*.svg',
'*.png',
'*.manifest',
'README.mozilla',
'components',
'../../LICENSE'],
DEFAULT_LOCALE_FILES =
[LOCALE_SRC_DIR + 'en-US/viewer.properties',
LOCALE_SRC_DIR + 'en-US/chrome.properties'],
FIREFOX_MC_EXTENSION_FILES =
['chrome.manifest',
'components',
'content',
'LICENSE'];
target.bundle({ excludes: ['core/network.js'], defines: defines });
cd(ROOT_DIR);
// Clear out everything in the firefox extension build directory
rm('-rf', MOZCENTRAL_DIR);
mkdir('-p', MOZCENTRAL_CONTENT_DIR);
mkdir('-p', MOZCENTRAL_L10N_DIR);
mkdir('-p', MOZCENTRAL_CONTENT_DIR + BUILD_DIR);
mkdir('-p', MOZCENTRAL_CONTENT_DIR + '/web');
cp(FIREFOX_CONTENT_DIR + 'PdfJs.jsm', MOZCENTRAL_CONTENT_DIR);
cp(FIREFOX_CONTENT_DIR + 'PdfJsTelemetry.jsm', MOZCENTRAL_CONTENT_DIR);
// Copy extension files
cd('extensions/firefox');
cp('-R', FIREFOX_EXTENSION_FILES_TO_COPY,
ROOT_DIR + MOZCENTRAL_EXTENSION_DIR);
mv('-f', ROOT_DIR + MOZCENTRAL_EXTENSION_DIR + '/chrome-mozcentral.manifest',
ROOT_DIR + MOZCENTRAL_EXTENSION_DIR + '/chrome.manifest');
cd(ROOT_DIR);
var setup = {
defines: defines,
copy: [
[COMMON_WEB_FILES, MOZCENTRAL_CONTENT_DIR + '/web'],
['extensions/firefox/tools/l10n.js', MOZCENTRAL_CONTENT_DIR + '/web']
],
preprocess: [
[COMMON_WEB_FILES_PREPROCESS, MOZCENTRAL_CONTENT_DIR + '/web'],
[BUILD_TARGETS, MOZCENTRAL_CONTENT_DIR + BUILD_DIR],
[SRC_DIR + 'core/network.js', MOZCENTRAL_CONTENT_DIR]
],
preprocessCSS: [
['firefox', 'web/viewer.css', MOZCENTRAL_CONTENT_DIR + '/web/viewer.css']
]
};
builder.build(setup);
cleanupJSSource(MOZCENTRAL_CONTENT_DIR + '/web/viewer.js');
// Remove '.DS_Store' and other hidden files
find(MOZCENTRAL_DIR).forEach(function(file) {
if (file.match(/^\./))
rm('-f', file);
});
// Copy default localization files
cp(DEFAULT_LOCALE_FILES, MOZCENTRAL_L10N_DIR);
// Update the build version number
sed('-i', /PDFJSSCRIPT_VERSION/, EXTENSION_VERSION,
MOZCENTRAL_EXTENSION_DIR + 'README.mozilla');
sed('-i', /PDFJSSCRIPT_STREAM_CONVERTER_ID/, MOZCENTRAL_STREAM_CONVERTER_ID,
MOZCENTRAL_EXTENSION_DIR + 'components/PdfStreamConverter.js');
sed('-i', /PDFJSSCRIPT_PREF_PREFIX/, MOZCENTRAL_PREF_PREFIX,
MOZCENTRAL_EXTENSION_DIR + 'components/PdfStreamConverter.js');
sed('-i', /PDFJSSCRIPT_MOZ_CENTRAL/, 'true',
MOZCENTRAL_EXTENSION_DIR + 'components/PdfStreamConverter.js');
// List all files for mozilla-central
cd(MOZCENTRAL_EXTENSION_DIR);
var extensionFiles = '';
find(FIREFOX_MC_EXTENSION_FILES).forEach(function(file) {
if (test('-f', file))
extensionFiles += file + '\n';
});
extensionFiles.to('extension-files');
cd(ROOT_DIR);
// Copy test files
mkdir('-p', MOZCENTRAL_TEST_DIR);
cp('-Rf', 'test/mozcentral/*', MOZCENTRAL_TEST_DIR);
};
target.b2g = function() {
target.locale();
echo();
echo('### Building B2G (Firefox OS App)');
var B2G_BUILD_DIR = BUILD_DIR + '/b2g/',
B2G_BUILD_CONTENT_DIR = B2G_BUILD_DIR + '/content/';
var defines = builder.merge(DEFINES, { B2G: true });
target.bundle({ defines: defines });
// Clear out everything in the b2g build directory
cd(ROOT_DIR);
rm('-Rf', B2G_BUILD_DIR);
mkdir('-p', B2G_BUILD_CONTENT_DIR);
mkdir('-p', B2G_BUILD_CONTENT_DIR + BUILD_DIR);
mkdir('-p', B2G_BUILD_CONTENT_DIR + '/web');
var setup = {
defines: defines,
copy: [
['extensions/b2g/images', B2G_BUILD_CONTENT_DIR + '/web'],
['extensions/b2g/viewer.html', B2G_BUILD_CONTENT_DIR + '/web'],
['extensions/b2g/viewer.css', B2G_BUILD_CONTENT_DIR + '/web'],
['web/locale', B2G_BUILD_CONTENT_DIR + '/web'],
['external/webL10n/l10n.js', B2G_BUILD_CONTENT_DIR + '/web']
],
preprocess: [
['web/viewer.js', B2G_BUILD_CONTENT_DIR + '/web'],
[BUILD_TARGETS, B2G_BUILD_CONTENT_DIR + BUILD_DIR]
]
};
builder.build(setup);
cleanupJSSource(B2G_BUILD_CONTENT_DIR + '/web/viewer.js');
};
//
// make chrome
//
target.chrome = function() {
cd(ROOT_DIR);
echo();
echo('### Building Chrome extension');
var defines = builder.merge(DEFINES, {CHROME: true});
var CHROME_BUILD_DIR = BUILD_DIR + '/chrome/',
CHROME_BUILD_CONTENT_DIR = CHROME_BUILD_DIR + '/content/';
target.bundle({ defines: defines });
cd(ROOT_DIR);
// Clear out everything in the chrome extension build directory
rm('-Rf', CHROME_BUILD_DIR);
mkdir('-p', CHROME_BUILD_CONTENT_DIR);
mkdir('-p', CHROME_BUILD_CONTENT_DIR + BUILD_DIR);
mkdir('-p', CHROME_BUILD_CONTENT_DIR + '/web');
var setup = {
defines: defines,
copy: [
[COMMON_WEB_FILES, CHROME_BUILD_CONTENT_DIR + '/web'],
[['extensions/chrome/*.json',
'extensions/chrome/*.html',
'extensions/chrome/*.js',
'extensions/chrome/*.css',
'extensions/chrome/icon*.png',],
CHROME_BUILD_DIR],
['external/webL10n/l10n.js', CHROME_BUILD_CONTENT_DIR + '/web'],
['web/viewer.css', CHROME_BUILD_CONTENT_DIR + '/web'],
['web/locale', CHROME_BUILD_CONTENT_DIR + '/web']
],
preprocess: [
[BUILD_TARGETS, CHROME_BUILD_CONTENT_DIR + BUILD_DIR],
[COMMON_WEB_FILES_PREPROCESS, CHROME_BUILD_CONTENT_DIR + '/web']
]
};
builder.build(setup);
cleanupJSSource(CHROME_BUILD_CONTENT_DIR + '/web/viewer.js');
// Update the build version number
sed('-i', /PDFJSSCRIPT_VERSION/, EXTENSION_VERSION,
CHROME_BUILD_DIR + '/manifest.json');
// Allow PDF.js resources to be loaded by adding the files to
// the "web_accessible_resources" section.
var file_list = ls('-RA', CHROME_BUILD_CONTENT_DIR);
var public_chrome_files = file_list.reduce(function(war, file) {
// Exclude directories (naive: Exclude paths without dot)
if (file.indexOf('.') !== -1) {
// Only add a comma after the first file
if (war)
war += ',\n';
war += JSON.stringify('content/' + file);
}
return war;
}, '');
sed('-i', /"content\/\*"/, public_chrome_files,
CHROME_BUILD_DIR + '/manifest.json');
// Bundle the files to a Chrome extension file .crx if path to key is set
var pem = env['PDFJS_CHROME_KEY'];
if (!pem) {
return;
}
echo();
echo('### Bundling .crx extension into ' + CHROME_BUILD_DIR);
if (!test('-f', pem)) {
echo('Incorrect PDFJS_CHROME_KEY path');
exit(1);
}
var browserManifest = env['PDF_BROWSERS'] ||
'test/resources/browser_manifests/browser_manifest.json';
if (!test('-f', browserManifest)) {
echo('Browser manifest file ' + browserManifest + ' does not exist.');
echo('Try copying one of the examples in test/resources/browser_manifests');
exit(1);
}
var manifest;
try {
manifest = JSON.parse(cat(browserManifest));
} catch (e) {
echo('Malformed browser manifest file');
echo(e.message);
exit(1);
}
var executable;
manifest.forEach(function(browser) {
if (browser.name === 'chrome') {
executable = browser.path;
}
});
// If there was no chrome entry in the browser manifest, exit
if (!executable) {
echo('There was no \'chrome\' entry in the browser manifest');
exit(1);
}
// If we're on a Darwin (Mac) OS, then let's check for an .app path
if (process.platform === 'darwin' && executable.indexOf('.app') !== -1) {
executable = executable + '/Contents/MacOS/Google Chrome';
}
// If the chrome executable doesn't exist
if (!test('-f', executable)) {
echo('Incorrect executable path to chrome');
exit(1);
}
// Let chrome pack the extension for us
exec('"' + executable + '"' +
' --no-message-box' +
' "--pack-extension=' + ROOT_DIR + CHROME_BUILD_DIR + '"' +
' "--pack-extension-key=' + pem + '"');
// Rename to pdf.js.crx
mv(BUILD_DIR + 'chrome.crx', CHROME_BUILD_DIR + 'pdf.js.crx');
};
////////////////////////////////////////////////////////////////////////////////
//
// Test stuff
//
//
// make test
//
target.test = function() {
target.unittest({}, function() {
target.browsertest();
});
};
//
// make bottest
// (Special tests for the Github bot)
//
target.bottest = function() {
target.unittest({}, function() {
target.fonttest({}, function() {
target.browsertest({noreftest: true});
});
});
};
//
// make browsertest
//
target.browsertest = function(options) {
cd(ROOT_DIR);
echo();
echo('### Running browser tests');
var PDF_TEST = env['PDF_TEST'] || 'test_manifest.json',
PDF_BROWSERS = env['PDF_BROWSERS'] ||
'resources/browser_manifests/browser_manifest.json';
if (!test('-f', 'test/' + PDF_BROWSERS)) {
echo('Browser manifest file test/' + PDF_BROWSERS + ' does not exist.');
echo('Copy one of the examples in test/resources/browser_manifests/');
exit(1);
}
var reftest = (options && options.noreftest) ? '' : '--reftest';
cd('test');
exec(PYTHON_BIN + ' -u test.py ' + reftest + ' --browserManifestFile=' +
PDF_BROWSERS + ' --manifestFile=' + PDF_TEST, {async: true});
};
//
// make unittest
//
target.unittest = function(options, callback) {
cd(ROOT_DIR);
echo();
echo('### Running unit tests');
var PDF_BROWSERS = env['PDF_BROWSERS'] ||
'resources/browser_manifests/browser_manifest.json';
if (!test('-f', 'test/' + PDF_BROWSERS)) {
echo('Browser manifest file test/' + PDF_BROWSERS + ' does not exist.');
echo('Copy one of the examples in test/resources/browser_manifests/');
exit(1);
}
callback = callback || function() {};
cd('test');
exec(PYTHON_BIN + ' -u test.py --unitTest --browserManifestFile=' +
PDF_BROWSERS, {async: true}, callback);
};
//
// make fonttest
//
target.fonttest = function(options, callback) {
cd(ROOT_DIR);
echo();
echo('### Running font tests');
var PDF_BROWSERS = env['PDF_BROWSERS'] ||
'resources/browser_manifests/browser_manifest.json';
if (!test('-f', 'test/' + PDF_BROWSERS)) {
echo('Browser manifest file test/' + PDF_BROWSERS + ' does not exist.');
echo('Copy one of the examples in test/resources/browser_manifests/');
exit(1);
}
callback = callback || function() {};
cd('test');
exec(PYTHON_BIN + ' -u test.py --fontTest --browserManifestFile=' +
PDF_BROWSERS, {async: true}, callback);
};
//
// make botmakeref
//
target.botmakeref = function() {
cd(ROOT_DIR);
echo();
echo('### Creating reference images');
var PDF_TEST = env['PDF_TEST'] || 'test_manifest.json',
PDF_BROWSERS = env['PDF_BROWSERS'] ||
'resources/browser_manifests/browser_manifest.json';
if (!test('-f', 'test/' + PDF_BROWSERS)) {
echo('Browser manifest file test/' + PDF_BROWSERS + ' does not exist.');
echo('Copy one of the examples in test/resources/browser_manifests/');
exit(1);
}
cd('test');
exec(PYTHON_BIN + ' -u test.py --masterMode --noPrompts ' +
'--browserManifestFile=' + PDF_BROWSERS, {async: true});
};
////////////////////////////////////////////////////////////////////////////////
//
// Baseline operation
//
target.baseline = function() {
cd(ROOT_DIR);
echo();
echo('### Creating baseline environment');
var baselineCommit = env['BASELINE'];
if (!baselineCommit) {
echo('Baseline commit is not provided. Please specify BASELINE variable');
exit(1);
}
if (!test('-d', BUILD_DIR))
mkdir(BUILD_DIR);
var BASELINE_DIR = BUILD_DIR + 'baseline';
if (test('-d', BASELINE_DIR)) {
cd(BASELINE_DIR);
exec('git fetch origin');
} else {
cd(BUILD_DIR);
exec('git clone .. baseline');
cd(ROOT_DIR + BASELINE_DIR);
}
exec('git checkout ' + baselineCommit);
};
target.mozcentralbaseline = function() {
target.baseline();
cd(ROOT_DIR);
echo();
echo('### Creating mozcentral baseline environment');
var BASELINE_DIR = BUILD_DIR + 'baseline';
var MOZCENTRAL_BASELINE_DIR = BUILD_DIR + 'mozcentral.baseline';
if (test('-d', MOZCENTRAL_BASELINE_DIR))
rm('-rf', MOZCENTRAL_BASELINE_DIR);
cd(BASELINE_DIR);
if (test('-d', 'build'))
rm('-rf', 'build');
exec('node make mozcentral');
cd(ROOT_DIR);
mkdir(MOZCENTRAL_BASELINE_DIR);
cp('-Rf', BASELINE_DIR + '/build/mozcentral/*', MOZCENTRAL_BASELINE_DIR);
// fixing baseline
if (test('-f', MOZCENTRAL_BASELINE_DIR +
'/browser/extensions/pdfjs/PdfStreamConverter.js')) {
rm(MOZCENTRAL_BASELINE_DIR +
'/browser/extensions/pdfjs/PdfStreamConverter.js');
}
cd(MOZCENTRAL_BASELINE_DIR);
exec('git init');
exec('git add .');
exec('git commit -m "mozcentral baseline"');
};
target.mozcentraldiff = function() {
target.mozcentral();
cd(ROOT_DIR);
echo();
echo('### Creating mozcentral diff');
var MOZCENTRAL_DIFF = BUILD_DIR + 'mozcentral.diff';
if (test('-f', MOZCENTRAL_DIFF))
rm(MOZCENTRAL_DIFF);
var MOZCENTRAL_BASELINE_DIR = BUILD_DIR + 'mozcentral.baseline';
if (!test('-d', MOZCENTRAL_BASELINE_DIR)) {
echo('mozcentral baseline was not found');
echo('Please build one using "node make mozcentralbaseline"');
exit(1);
}
cd(MOZCENTRAL_BASELINE_DIR);
exec('git reset --hard');
cd(ROOT_DIR); rm('-rf', MOZCENTRAL_BASELINE_DIR + '/*'); // trying to be safe
cd(MOZCENTRAL_BASELINE_DIR);
cp('-Rf', '../mozcentral/*', '.');
exec('git add -A');
exec('git diff --binary --cached --unified=8', {silent: true}).output.
to('../mozcentral.diff');
echo('Result diff can be found at ' + MOZCENTRAL_DIFF);
};
target.mozcentralcheck = function() {
cd(ROOT_DIR);
echo();
echo('### Checking mozcentral changes');
var mcPath = env['MC_PATH'];
if (!mcPath) {
echo('mozilla-central path is not provided.');
echo('Please specify MC_PATH variable');
exit(1);
}
if ((mcPath[0] != '/' && mcPath[0] != '~' && mcPath[1] != ':') ||
!test('-d', mcPath)) {
echo('mozilla-central path is not in absolute form or does not exist.');
exit(1);
}
var MOZCENTRAL_DIFF = BUILD_DIR + 'mozcentral_changes.diff';
if (test('-f', MOZCENTRAL_DIFF)) {
rm(MOZCENTRAL_DIFF);
}
var MOZCENTRAL_BASELINE_DIR = BUILD_DIR + 'mozcentral.baseline';
if (!test('-d', MOZCENTRAL_BASELINE_DIR)) {
echo('mozcentral baseline was not found');
echo('Please build one using "node make mozcentralbaseline"');
exit(1);
}
cd(MOZCENTRAL_BASELINE_DIR);
exec('git reset --hard');
cd(ROOT_DIR); rm('-rf', MOZCENTRAL_BASELINE_DIR + '/*'); // trying to be safe
cd(MOZCENTRAL_BASELINE_DIR);
mkdir('browser');
cd('browser');
mkdir('-p', 'extensions/pdfjs');
cp('-Rf', mcPath + '/browser/extensions/pdfjs/*', 'extensions/pdfjs');
mkdir('-p', 'locales/en-US/pdfviewer');
cp('-Rf', mcPath + '/browser/locales/en-US/pdfviewer/*',
'locales/en-US/pdfviewer');
// Remove '.DS_Store' and other hidden files
find('.').forEach(function(file) {
if (file.match(/^\.\w|~$/)) {
rm('-f', file);
}
});
cd('..');
exec('git add -A');
var diff = exec('git diff --binary --cached --unified=8',
{silent: true}).output;
if (diff) {
echo('There were changes found at mozilla-central.');
diff.to('../mozcentral_changes.diff');
echo('Result diff can be found at ' + MOZCENTRAL_DIFF);
exit(1);
}
echo('Success: there are no changes at mozilla-central');
};
////////////////////////////////////////////////////////////////////////////////
//
// Other
//
//
// make server
//
target.server = function() {
cd(ROOT_DIR);
echo();
echo('### Starting local server');
cd('test');
exec(PYTHON_BIN + ' -u test.py --port=8888 --noDownload', {async: true});
};
//
// make lint
//
target.lint = function() {
cd(ROOT_DIR);
echo();
echo('### Linting JS files');
var LINT_FILES = ['make.js',
'external/builder/',
'external/crlfchecker/',
'src/',
'web/',
'test/driver.js',
'test/reporter.js',
'test/unit/',
'extensions/firefox/',
'extensions/chrome/'
];
var jshintPath = path.normalize('./node_modules/.bin/jshint');
if (!test('-f', jshintPath)) {
echo('jshint is not installed -- installing...');
exec('npm install jshint');
}
exit(exec('"' + jshintPath + '" --reporter test/reporter.js ' +
LINT_FILES.join(' ')).code);
crlfchecker.checkIfCrlfIsPresent(LINT_FILES);
};
//
// make clean
//
target.clean = function() {
cd(ROOT_DIR);
echo();
echo('### Cleaning up project builds');
rm('-rf', BUILD_DIR);
};
//
// make makefile
//
target.makefile = function() {
var makefileContent = 'help:\n\tnode make\n\n';
var targetsNames = [];
for (var i in target) {
makefileContent += i + ':\n\tnode make ' + i + '\n\n';
targetsNames.push(i);
}
makefileContent += '.PHONY: ' + targetsNames.join(' ') + '\n';
makefileContent.to('Makefile');
};
| apache-2.0 |
android/security-certification-resources | niap-cc/Permissions/Companion/app/src/main/java/com/android/certifications/niap/permissions/companion/services/TestBindTelephonyNetworkServiceService.java | 1972 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.certifications.niap.permissions.companion.services;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
/**
* Exported service used to test the BIND_TELEPHONY_NETWORK_SERVICE permission.
*
* This service requires clients are granted the BIND_TELEPHONY_NETWORK_SERVICE
* permission to bind to it. The Permission Test Tool can attempt to bind to this service
* and invoke the {@link TestBindTelephonyNetworkServiceServiceImpl#testMethod()} method
* to verify that the platform properly enforces this permission requirement.
*/
public class TestBindTelephonyNetworkServiceService extends Service {
private static final String TAG = "PermissionTesterBindService";
private TestBindTelephonyNetworkServiceServiceImpl bindService;
@Override
public void onCreate() {
super.onCreate();
bindService = new TestBindTelephonyNetworkServiceServiceImpl();
}
@Override
public IBinder onBind(Intent intent) {
return bindService;
}
static class TestBindTelephonyNetworkServiceServiceImpl extends TestBindService.Stub {
public void testMethod() {
Log.d(TAG, "The caller successfully invoked the test method on service "
+ "TestBindTelephonyNetworkServiceService");
}
}
}
| apache-2.0 |
adligo/fabricate_tests.adligo.org | src/org/adligo/fabricate_tests/routines/implicit/CopyRoutineTrial.java | 370 | package org.adligo.fabricate_tests.routines.implicit;
import org.adligo.fabricate.routines.implicit.CopyRoutine;
import org.adligo.tests4j.system.shared.trials.SourceFileScope;
import org.adligo.tests4j_4mockito.MockitoSourceFileTrial;
@SourceFileScope (sourceClass=CopyRoutine.class,minCoverage=0.00)
public class CopyRoutineTrial extends MockitoSourceFileTrial {
}
| apache-2.0 |
alekseysidorov/exonum | components/merkledb/src/migration/persistent_iter.rs | 18308 | // Copyright 2019 The Exonum Team
//
// 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.
//! Persistent iterators.
use anyhow::{bail, ensure};
use std::{
borrow::{Borrow, Cow},
collections::HashSet,
fmt,
iter::Peekable,
};
use crate::{
access::{Access, AccessExt, RawAccess, RawAccessMut},
indexes::{Entries, IndexIterator},
BinaryKey, BinaryValue, Entry,
};
/// Persistent iterator position.
#[derive(PartialEq)]
enum IteratorPosition<K: BinaryKey + ?Sized> {
/// There is a next key to start iteration from.
NextKey(K::Owned),
/// The iterator has ended.
Ended,
}
impl<K> fmt::Debug for IteratorPosition<K>
where
K: BinaryKey + fmt::Debug + ?Sized,
{
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NextKey(key) => {
let key_ref: &K = key.borrow();
formatter.debug_tuple("NextKey").field(&key_ref).finish()
}
Self::Ended => formatter.debug_tuple("Ended").finish(),
}
}
}
impl<K> BinaryValue for IteratorPosition<K>
where
K: BinaryKey + ?Sized,
{
fn to_bytes(&self) -> Vec<u8> {
match self {
Self::NextKey(key) => {
let key: &K = key.borrow();
let mut buffer = vec![0; 1 + key.size()];
key.write(&mut buffer[1..]);
buffer
}
Self::Ended => vec![1],
}
}
fn from_bytes(bytes: Cow<'_, [u8]>) -> anyhow::Result<Self> {
ensure!(
!bytes.is_empty(),
"`IteratorPosition` serialization cannot be empty"
);
Ok(match bytes[0] {
0 => Self::NextKey(K::read(&bytes[1..])),
1 => Self::Ended,
_ => bail!("Invalid `IteratorPosition` discriminant"),
})
}
}
/// Persistent iterator that stores its position in the database.
///
/// Persistent iterators iterate over an index and automatically persist iteration
/// results in the DB. This allows to build fault-tolerant migration scripts that work correctly
/// after being restarted while merging the intermediate changes to the database.
///
/// Like indexes, persistent iterators are identified by an address. Likewise, they are subject
/// to the borrowing rules (e.g., attempting to create two instances of the same iterator will
/// result in a runtime error). When migrating data, it makes sense to store iterators
/// in the associated [`Scratchpad`]. In this way, iterators will be automatically removed
/// when the migration is over.
///
/// # Examples
///
/// [`MigrationHelper`] offers convenient iterator API via `iter_loop` method, which covers
/// basic use cases. When `iter_loop` is not enough, a persistent iterator can be instantiated
/// independently:
///
/// ```
/// # use exonum_merkledb::{access::{AccessExt, CopyAccessExt}, Database, TemporaryDB};
/// # use exonum_merkledb::migration::{MigrationHelper, PersistentIter};
/// let db = TemporaryDB::new();
/// // Create data for migration.
/// let fork = db.fork();
/// fork.get_proof_list("migration.list").extend((0..123).map(|i| i.to_string()));
/// db.merge(fork.into_patch()).unwrap();
///
/// let helper = MigrationHelper::new(db, "migration");
/// // The old data is here.
/// let list = helper.old_data().get_proof_list::<_, String>("list");
/// // In the context of migration, persistent iterators should use
/// // the scratchpad data access.
/// let iter = PersistentIter::new(&helper.scratchpad(), "list_iter", &list);
/// // Now, we can use `iter` as any other iterator. Persistence is most useful
/// // together with the `take` adapter; it allows to break migrated data
/// // into manageable chunks.
/// for (_, item) in iter.take(100) {
/// // Migrate `item`. The first component of a tuple is the index of the item
/// // in the list, which we ignore.
/// }
///
/// // If we recreate the iterator, it will resume iteration from the last
/// // known position (the element with 0-based index 100, in our case).
/// let mut iter = PersistentIter::new(&helper.scratchpad(), "list_iter", &list);
/// let (i, item) = iter.next().unwrap();
/// assert_eq!(i, 100);
/// assert_eq!(item, "100");
/// assert_eq!(iter.count(), 22); // number of remaining items
/// ```
///
/// [`Scratchpad`]: struct.Scratchpad.html
/// [`MigrationHelper`]: struct.MigrationHelper.html
pub struct PersistentIter<'a, T: RawAccess, I: IndexIterator> {
inner: Inner<'a, T, I>,
}
impl<T, I> fmt::Debug for PersistentIter<'_, T, I>
where
T: RawAccess,
I: IndexIterator,
I::Key: fmt::Debug,
{
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("PersistentIter")
.field("inner", &self.inner)
.finish()
}
}
/// Internal details of a persistent iterator.
enum Inner<'a, T: RawAccess, I: IndexIterator> {
/// The iterator is active: it has an underlying iterator over a database object,
/// and an entry storing the iterator position.
Active {
iter: Peekable<Entries<'a, I::Key, I::Value>>,
position_entry: Entry<T, IteratorPosition<I::Key>>,
},
/// The iterator has ended.
Ended,
}
impl<T, I> fmt::Debug for Inner<'_, T, I>
where
T: RawAccess,
I: IndexIterator,
I::Key: fmt::Debug,
{
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Inner::Active { position_entry, .. } => formatter
.debug_struct("Active")
.field("position", &position_entry.get())
.finish(),
Inner::Ended => formatter.debug_tuple("Ended").finish(),
}
}
}
impl<'a, T, I> PersistentIter<'a, T, I>
where
T: RawAccessMut,
I: IndexIterator,
{
/// Creates a new persistent iterator.
pub fn new<A>(access: &A, name: &str, index: &'a I) -> Self
where
A: Access<Base = T>,
{
let position_entry: Entry<_, IteratorPosition<I::Key>> = access.get_entry(name);
let position = position_entry.get();
let start_key = match position {
None => None,
Some(IteratorPosition::NextKey(key)) => Some(key),
Some(IteratorPosition::Ended) => {
return Self {
inner: Inner::Ended,
};
}
};
Self {
inner: Inner::Active {
iter: index
.index_iter(start_key.as_ref().map(Borrow::borrow))
.peekable(),
position_entry,
},
}
}
/// Skips values in the iterator output without parsing them.
pub fn skip_values(self) -> PersistentKeys<'a, T, I> {
PersistentKeys { base_iter: self }
}
}
impl<T, I> Iterator for PersistentIter<'_, T, I>
where
T: RawAccessMut,
I: IndexIterator,
{
type Item = (<I::Key as ToOwned>::Owned, I::Value);
fn next(&mut self) -> Option<Self::Item> {
if let Inner::Active {
ref mut iter,
ref mut position_entry,
} = self.inner
{
let next = iter.next();
if next.is_some() {
position_entry.set(if let Some((key, _)) = iter.peek() {
// Slightly clumsy way to clone the key.
IteratorPosition::NextKey(key.borrow().to_owned())
} else {
IteratorPosition::Ended
});
} else {
position_entry.set(IteratorPosition::Ended);
self.inner = Inner::Ended;
}
next
} else {
None
}
}
}
/// Persistent iterator over index keys that stores its position in the database.
///
/// This iterator can be used similarly to [`PersistentIter`]; the only difference is the
/// type of items yielded by the iterator.
///
/// [`PersistentIter`]: struct.PersistentIter.html
pub struct PersistentKeys<'a, T: RawAccess, I: IndexIterator> {
base_iter: PersistentIter<'a, T, I>,
}
impl<'a, T, I> PersistentKeys<'a, T, I>
where
T: RawAccessMut,
I: IndexIterator,
{
/// Creates a new persistent iterator.
pub fn new<A>(access: &A, name: &str, index: &'a I) -> Self
where
A: Access<Base = T>,
{
PersistentIter::new(access, name, index).skip_values()
}
}
impl<T, I> fmt::Debug for PersistentKeys<'_, T, I>
where
T: RawAccess,
I: IndexIterator,
I::Key: fmt::Debug,
{
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("PersistentIter")
.field("inner", &self.base_iter.inner)
.finish()
}
}
impl<T, I> Iterator for PersistentKeys<'_, T, I>
where
T: RawAccessMut,
I: IndexIterator,
{
type Item = <I::Key as ToOwned>::Owned;
fn next(&mut self) -> Option<Self::Item> {
self.base_iter.next().map(|(key, _)| key)
}
}
/// Factory for persistent iterators.
#[derive(Debug)]
pub struct PersistentIters<T> {
access: T,
names: HashSet<String>,
}
impl<T> PersistentIters<T>
where
T: Access,
T::Base: RawAccessMut,
{
/// Creates a new factory.
pub fn new(access: T) -> Self {
Self {
access,
names: HashSet::new(),
}
}
/// Creates a persistent iterator identified by the `name`.
pub fn create<'a, I: IndexIterator>(
&mut self,
name: &str,
index: &'a I,
) -> PersistentIter<'a, T::Base, I> {
self.names.insert(name.to_owned());
PersistentIter::new(&self.access, name, index)
}
/// Checks if all iterators instantiated via this instance have ended.
///
/// This method will panic if any of iterators are borrowed and thus should only be called
/// when this is a priori not the case.
pub(super) fn all_ended(&self) -> bool {
for name in &self.names {
let pos = self
.access
.clone()
.get_entry::<_, IteratorPosition<()>>(name.as_str())
.get();
if pos != Some(IteratorPosition::Ended) {
return false;
}
}
true
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
access::CopyAccessExt, migration::Scratchpad, Database, ProofMapIndex, TemporaryDB,
};
use std::{collections::HashSet, iter::FromIterator};
#[test]
fn persistent_iter_for_map() {
let db = TemporaryDB::new();
let fork = db.fork();
let mut map = fork.get_map("map");
for i in 0_u32..10 {
map.put(&i, i.to_string());
}
let scratchpad = Scratchpad::new("iter", &fork);
let iter = PersistentIter::new(&scratchpad, "map", &map);
let mut count = 0;
for (i, (key, value)) in iter.take(5).enumerate() {
assert_eq!(key, i as u32);
assert_eq!(value, i.to_string());
count += 1;
}
assert_eq!(count, 5);
{
let position_entry = scratchpad.get_entry::<_, IteratorPosition<u32>>("map");
assert_eq!(position_entry.get(), Some(IteratorPosition::NextKey(5)));
}
// Resume the iterator.
let iter = PersistentIter::new(&scratchpad, "map", &map);
count = 0;
for (i, (key, value)) in (5..).zip(iter) {
assert_eq!(key, i as u32);
assert_eq!(value, i.to_string());
count += 1;
}
assert_eq!(count, 5);
{
let position_entry = scratchpad.get_entry::<_, IteratorPosition<u32>>("map");
assert_eq!(position_entry.get(), Some(IteratorPosition::Ended));
}
// The iterator is ended now.
let iter = PersistentIter::new(&scratchpad, "map", &map);
assert_eq!(iter.count(), 0);
}
#[test]
fn persistent_iter_with_unsized_keys() {
let db = TemporaryDB::new();
let fork = db.fork();
let mut map: ProofMapIndex<_, str, u64> = fork.get_proof_map("map");
let words = ["How", "many", "letters", "are", "in", "this", "word", "?"];
for &word in &words {
map.put(word, word.len() as u64);
}
let scratchpad = Scratchpad::new("iter", &fork);
let iter = PersistentIter::new(&scratchpad, "map", &map);
for (word, size) in iter.take_while(|(word, _)| word.as_str() < "many") {
assert!(words.contains(&word.as_str()));
assert_eq!(word.len() as u64, size);
}
{
let position_entry = scratchpad.get_entry::<_, IteratorPosition<str>>("map");
// Note that `many` is not included into the values yielded by the iterator,
// but the iterator is advanced past it.
let expected_pos = IteratorPosition::NextKey("this".to_owned());
assert_eq!(position_entry.get(), Some(expected_pos));
}
let iter = PersistentIter::new(&scratchpad, "map", &map);
assert_eq!(
iter.collect::<Vec<_>>(),
vec![("this".to_owned(), 4), ("word".to_owned(), 4)]
);
}
#[test]
fn persistent_iter_for_list() {
let db = TemporaryDB::new();
let fork = db.fork();
let mut list = fork.get_list("list");
list.extend((0_u32..10).map(|i| i.to_string()));
let scratchpad = Scratchpad::new("iter", &fork);
let iter = PersistentIter::new(&scratchpad, "list", &list);
// Test that iterators work with adapters as expected.
let items: Vec<_> = iter.take(5).filter(|(i, _)| i % 2 == 1).collect();
assert_eq!(items, vec![(1, "1".to_owned()), (3, "3".to_owned())]);
{
let position_entry = scratchpad.get_entry::<_, IteratorPosition<u64>>("list");
assert_eq!(position_entry.get(), Some(IteratorPosition::NextKey(5)));
}
let iter = PersistentIter::new(&scratchpad, "list", &list);
for (i, value) in iter.take(3) {
assert_eq!(i.to_string(), value);
}
{
let position_entry = scratchpad.get_entry::<_, IteratorPosition<u64>>("list");
assert_eq!(position_entry.get(), Some(IteratorPosition::NextKey(8)));
}
let iter = PersistentIter::new(&scratchpad, "list", &list);
assert_eq!(iter.count(), 2);
}
#[test]
fn empty_persistent_iter() {
let db = TemporaryDB::new();
let fork = db.fork();
let list = fork.get_list::<_, String>("list");
let scratchpad = Scratchpad::new("iter", &fork);
let iter = PersistentIter::new(&scratchpad, "list", &list);
assert_eq!(iter.count(), 0);
let position_entry = scratchpad.get_entry::<_, IteratorPosition<u64>>("list");
assert_eq!(position_entry.get(), Some(IteratorPosition::Ended));
}
#[test]
fn persistent_iter_for_sparse_list() {
let db = TemporaryDB::new();
let fork = db.fork();
let mut list = fork.get_sparse_list("list");
for &i in &[0, 1, 2, 3, 5, 8, 13, 21] {
list.set(i, i.to_string());
}
let scratchpad = Scratchpad::new("iter", &fork);
let iter = PersistentIter::new(&scratchpad, "list", &list);
let mut count = 0;
for (i, value) in iter.take(5) {
assert_eq!(value, i.to_string());
count += 1;
}
assert_eq!(count, 5);
{
let position_entry = scratchpad.get_entry::<_, IteratorPosition<u64>>("list");
assert_eq!(position_entry.get(), Some(IteratorPosition::NextKey(8)));
}
let iter = PersistentIter::new(&scratchpad, "list", &list);
let indexes: Vec<_> = iter.map(|(i, _)| i).collect();
assert_eq!(indexes, vec![8, 13, 21]);
}
#[test]
fn persistent_iter_for_key_set() {
let db = TemporaryDB::new();
let fork = db.fork();
let mut set = fork.get_key_set("set");
for i in &[0_u16, 1, 2, 3, 5, 8, 13, 21] {
set.insert(i);
}
let scratchpad = Scratchpad::new("iter", &fork);
let iter = PersistentKeys::new(&scratchpad, "set", &set);
let head: Vec<_> = iter.take(3).collect();
assert_eq!(head, vec![0, 1, 2]);
{
let mut iter = PersistentKeys::new(&scratchpad, "set", &set);
assert_eq!(iter.nth(2), Some(8));
}
{
let position_entry = scratchpad.get_entry::<_, IteratorPosition<u16>>("set");
assert_eq!(position_entry.get(), Some(IteratorPosition::NextKey(13)));
}
let iter = PersistentKeys::new(&scratchpad, "set", &set);
let tail: Vec<_> = iter.collect();
assert_eq!(tail, vec![13, 21]);
}
#[test]
fn persistent_iter_for_value_set() {
let db = TemporaryDB::new();
let fork = db.fork();
let mut set = fork.get_value_set("set");
let items = [0_u16, 1, 2, 3, 5, 8, 13, 21];
for &i in &items {
set.insert(i);
}
let scratchpad = Scratchpad::new("iter", &fork);
let iter = PersistentIter::new(&scratchpad, "set", &set);
let head: Vec<_> = iter.take(3).map(|(_, val)| val).collect();
let iter = PersistentIter::new(&scratchpad, "set", &set);
let middle: Vec<_> = iter.take(2).map(|(_, val)| val).collect();
let iter = PersistentIter::new(&scratchpad, "set", &set);
let tail: Vec<_> = iter.map(|(_, val)| val).collect();
let actual_set: HashSet<_> = HashSet::from_iter(head.into_iter().chain(middle).chain(tail));
assert_eq!(actual_set, HashSet::from_iter(items.iter().copied()));
}
}
| apache-2.0 |