code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
package gui;
//: gui/SubmitLabelManipulationTask.java
import javax.swing.*;
import java.util.concurrent.*;
public class SubmitLabelManipulationTask {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Hello Swing");
final JLabel label = new JLabel("A Label");
frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 100);
frame.setVisible(true);
TimeUnit.SECONDS.sleep(1);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
label.setText("Hey! This is Different!");
}
});
}
} ///:~
| vowovrz/thinkinj | thinkinj/src/main/java/gui/SubmitLabelManipulationTask.java | Java | apache-2.0 | 646 |
/**
* Copyright 2006-2015 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.mybatis.generator.codegen.ibatis2.dao.elements;
import java.util.Set;
import java.util.TreeSet;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
/**
*
* @author Jeff Butler
*
*/
public class UpdateByExampleWithoutBLOBsMethodGenerator extends
AbstractDAOElementGenerator {
public UpdateByExampleWithoutBLOBsMethodGenerator() {
super();
}
@Override
public void addImplementationElements(TopLevelClass topLevelClass) {
Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
Method method = getMethodShell(importedTypes);
method
.addBodyLine("UpdateByExampleParms parms = new UpdateByExampleParms(record, example);"); //$NON-NLS-1$
StringBuilder sb = new StringBuilder();
sb.append("int rows = "); //$NON-NLS-1$
sb.append(daoTemplate.getUpdateMethod(introspectedTable
.getIbatis2SqlMapNamespace(), introspectedTable
.getUpdateByExampleStatementId(), "parms")); //$NON-NLS-1$
method.addBodyLine(sb.toString());
method.addBodyLine("return rows;"); //$NON-NLS-1$
if (context.getPlugins()
.clientUpdateByExampleWithoutBLOBsMethodGenerated(method,
topLevelClass, introspectedTable)) {
topLevelClass.addImportedTypes(importedTypes);
topLevelClass.addMethod(method);
}
}
@Override
public void addInterfaceElements(Interface interfaze) {
if (getExampleMethodVisibility() == JavaVisibility.PUBLIC) {
Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
Method method = getMethodShell(importedTypes);
if (context.getPlugins()
.clientUpdateByExampleWithoutBLOBsMethodGenerated(method,
interfaze, introspectedTable)) {
interfaze.addImportedTypes(importedTypes);
interfaze.addMethod(method);
}
}
}
private Method getMethodShell(Set<FullyQualifiedJavaType> importedTypes) {
FullyQualifiedJavaType parameterType;
if (introspectedTable.getRules().generateBaseRecordClass()) {
parameterType = new FullyQualifiedJavaType(introspectedTable
.getBaseRecordType());
} else {
parameterType = new FullyQualifiedJavaType(introspectedTable
.getPrimaryKeyType());
}
importedTypes.add(parameterType);
Method method = new Method();
method.setVisibility(getExampleMethodVisibility());
method.setReturnType(FullyQualifiedJavaType.getIntInstance());
method.setName(getDAOMethodNameCalculator()
.getUpdateByExampleWithoutBLOBsMethodName(introspectedTable));
method.addParameter(new Parameter(parameterType, "record")); //$NON-NLS-1$
method.addParameter(new Parameter(new FullyQualifiedJavaType(
introspectedTable.getExampleType()), "example")); //$NON-NLS-1$
for (FullyQualifiedJavaType fqjt : daoTemplate.getCheckedExceptions()) {
method.addException(fqjt);
importedTypes.add(fqjt);
}
context.getCommentGenerator().addGeneralMethodComment(method,
introspectedTable);
return method;
}
}
| li24361/mybatis-generator-core | src/main/java/org/mybatis/generator/codegen/ibatis2/dao/elements/UpdateByExampleWithoutBLOBsMethodGenerator.java | Java | apache-2.0 | 4,329 |
package jp.teraparser.transition;
import java.util.Arrays;
/**
* Resizable-array implementation of Deque which works like java.util.ArrayDeque
*
* jp.teraparser.util
*
* @author Hiroki Teranishi
*/
public class Stack implements Cloneable {
private static final int MIN_INITIAL_CAPACITY = 8;
private int[] elements;
private int head;
private int tail;
/**
* Allocates empty array to hold the given number of elements.
*/
private void allocateElements(int numElements) {
int initialCapacity = MIN_INITIAL_CAPACITY;
// Find the best power of two to hold elements.
// Tests "<=" because arrays aren't kept full.
if (numElements >= initialCapacity) {
initialCapacity = numElements;
initialCapacity |= (initialCapacity >>> 1);
initialCapacity |= (initialCapacity >>> 2);
initialCapacity |= (initialCapacity >>> 4);
initialCapacity |= (initialCapacity >>> 8);
initialCapacity |= (initialCapacity >>> 16);
initialCapacity++;
if (initialCapacity < 0) { // Too many elements, must back off
initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
}
}
elements = new int[initialCapacity];
}
/**
* Doubles the capacity of this deque. Call only when full, i.e.,
* when head and tail have wrapped around to become equal.
*/
private void doubleCapacity() {
assert head == tail;
int p = head;
int n = elements.length;
int r = n - p; // number of elements to the right of p
int newCapacity = n << 1;
if (newCapacity < 0) {
throw new IllegalStateException("Sorry, deque too big");
}
int[] a = new int[newCapacity];
System.arraycopy(elements, p, a, 0, r);
System.arraycopy(elements, 0, a, r, p);
elements = a;
head = 0;
tail = n;
}
public Stack() {
elements = new int[16];
}
public Stack(int numElements) {
allocateElements(numElements);
}
public void push(int e) {
elements[head = (head - 1) & (elements.length - 1)] = e;
if (head == tail) {
doubleCapacity();
}
}
public int pop() {
int h = head;
int result = elements[h];
elements[h] = 0;
head = (h + 1) & (elements.length - 1);
return result;
}
public int top() {
return elements[head];
}
public int getFirst() {
return top();
}
public int get(int position, int defaultValue) {
if (position < 0 || position >= size()) {
return defaultValue;
}
int mask = elements.length - 1;
int h = head;
for (int i = 0; i < position; i++) {
h = (h + 1) & mask;
}
return elements[h];
}
public int size() {
return (tail - head) & (elements.length - 1);
}
public boolean isEmpty() {
return head == tail;
}
public Stack clone() {
try {
Stack result = (Stack) super.clone();
result.elements = Arrays.copyOf(elements, elements.length);
return result;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
| chantera/teraparser | src/jp/teraparser/transition/Stack.java | Java | apache-2.0 | 3,381 |
/*
* 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.
*/
/*
* PdxObject.cpp
*
* Created on: Sep 29, 2011
* Author: npatel
*/
#include "PdxType.hpp"
using namespace apache::geode::client;
using namespace PdxTests;
template <typename T1, typename T2>
bool PdxTests::PdxType::genericValCompare(T1 value1, T2 value2) const {
if (value1 != value2) return false;
LOGINFO("PdxObject::genericValCompare Line_19");
return true;
}
template <typename T1, typename T2>
bool PdxTests::PdxType::genericCompare(T1* value1, T2* value2,
int length) const {
int i = 0;
while (i < length) {
if (value1[i] != value2[i]) {
return false;
} else {
i++;
}
}
LOGINFO("PdxObject::genericCompare Line_34");
return true;
}
template <typename T1, typename T2>
bool PdxTests::PdxType::generic2DCompare(T1** value1, T2** value2, int length,
int* arrLengths) const {
LOGINFO("generic2DCompare length = %d ", length);
LOGINFO("generic2DCompare value1 = %d \t value2", value1[0][0], value2[0][0]);
LOGINFO("generic2DCompare value1 = %d \t value2", value1[1][0], value2[1][0]);
LOGINFO("generic2DCompare value1 = %d \t value2", value1[1][1], value2[1][1]);
for (int j = 0; j < length; j++) {
LOGINFO("generic2DCompare arrlength0 = %d ", arrLengths[j]);
for (int k = 0; k < arrLengths[j]; k++) {
LOGINFO("generic2DCompare arrlength = %d ", arrLengths[j]);
LOGINFO("generic2DCompare value1 = %d \t value2 = %d ", value1[j][k],
value2[j][k]);
if (value1[j][k] != value2[j][k]) return false;
}
}
LOGINFO("PdxObject::genericCompare Line_34");
return true;
}
// PdxType::~PdxObject() {
//}
void PdxTests::PdxType::toData(PdxWriterPtr pw) /*const*/ {
// TODO:delete it later
int* lengthArr = new int[2];
lengthArr[0] = 1;
lengthArr[1] = 2;
pw->writeArrayOfByteArrays("m_byteByteArray", m_byteByteArray, 2, lengthArr);
pw->writeWideChar("m_char", m_char);
pw->markIdentityField("m_char");
pw->writeBoolean("m_bool", m_bool); // 1
pw->markIdentityField("m_bool");
pw->writeBooleanArray("m_boolArray", m_boolArray, 3);
pw->markIdentityField("m_boolArray");
pw->writeByte("m_byte", m_byte);
pw->markIdentityField("m_byte");
pw->writeByteArray("m_byteArray", m_byteArray, 2);
pw->markIdentityField("m_byteArray");
pw->writeWideCharArray("m_charArray", m_charArray, 2);
pw->markIdentityField("m_charArray");
pw->writeObject("m_arraylist", m_arraylist);
pw->writeObject("m_linkedlist", m_linkedlist);
pw->markIdentityField("m_arraylist");
pw->writeObject("m_map", m_map);
pw->markIdentityField("m_map");
pw->writeObject("m_hashtable", m_hashtable);
pw->markIdentityField("m_hashtable");
pw->writeObject("m_vector", m_vector);
pw->markIdentityField("m_vector");
pw->writeObject("m_chs", m_chs);
pw->markIdentityField("m_chs");
pw->writeObject("m_clhs", m_clhs);
pw->markIdentityField("m_clhs");
pw->writeString("m_string", m_string);
pw->markIdentityField("m_string");
pw->writeDate("m_dateTime", m_date);
pw->markIdentityField("m_dateTime");
pw->writeDouble("m_double", m_double);
pw->markIdentityField("m_double");
pw->writeDoubleArray("m_doubleArray", m_doubleArray, 2);
pw->markIdentityField("m_doubleArray");
pw->writeFloat("m_float", m_float);
pw->markIdentityField("m_float");
pw->writeFloatArray("m_floatArray", m_floatArray, 2);
pw->markIdentityField("m_floatArray");
pw->writeShort("m_int16", m_int16);
pw->markIdentityField("m_int16");
pw->writeInt("m_int32", m_int32);
pw->markIdentityField("m_int32");
pw->writeLong("m_long", m_long);
pw->markIdentityField("m_long");
pw->writeIntArray("m_int32Array", m_int32Array, 4);
pw->markIdentityField("m_int32Array");
pw->writeLongArray("m_longArray", m_longArray, 2);
pw->markIdentityField("m_longArray");
pw->writeShortArray("m_int16Array", m_int16Array, 2);
pw->markIdentityField("m_int16Array");
pw->writeByte("m_sbyte", m_sbyte);
pw->markIdentityField("m_sbyte");
pw->writeByteArray("m_sbyteArray", m_sbyteArray, 2);
pw->markIdentityField("m_sbyteArray");
// int* strlengthArr = new int[2];
// strlengthArr[0] = 5;
// strlengthArr[1] = 5;
pw->writeStringArray("m_stringArray", m_stringArray, 2);
pw->markIdentityField("m_stringArray");
pw->writeShort("m_uint16", m_uint16);
pw->markIdentityField("m_uint16");
pw->writeInt("m_uint32", m_uint32);
pw->markIdentityField("m_uint32");
pw->writeLong("m_ulong", m_ulong);
pw->markIdentityField("m_ulong");
pw->writeIntArray("m_uint32Array", m_uint32Array, 4);
pw->markIdentityField("m_uint32Array");
pw->writeLongArray("m_ulongArray", m_ulongArray, 2);
pw->markIdentityField("m_ulongArray");
pw->writeShortArray("m_uint16Array", m_uint16Array, 2);
pw->markIdentityField("m_uint16Array");
pw->writeByteArray("m_byte252", m_byte252, 252);
pw->markIdentityField("m_byte252");
pw->writeByteArray("m_byte253", m_byte253, 253);
pw->markIdentityField("m_byte253");
pw->writeByteArray("m_byte65535", m_byte65535, 65535);
pw->markIdentityField("m_byte65535");
pw->writeByteArray("m_byte65536", m_byte65536, 65536);
pw->markIdentityField("m_byte65536");
pw->writeObject("m_pdxEnum", m_pdxEnum);
pw->markIdentityField("m_pdxEnum");
pw->writeObject("m_address", m_objectArray);
pw->writeObjectArray("m_objectArray", m_objectArray);
pw->writeObjectArray("", m_objectArrayEmptyPdxFieldName);
LOGDEBUG("PdxObject::writeObject() for enum Done......");
LOGDEBUG("PdxObject::toData() Done......");
// TODO:delete it later
}
void PdxTests::PdxType::fromData(PdxReaderPtr pr) {
// TODO:temp added, delete later
int32_t* Lengtharr;
GF_NEW(Lengtharr, int32_t[2]);
int32_t arrLen = 0;
m_byteByteArray =
pr->readArrayOfByteArrays("m_byteByteArray", arrLen, &Lengtharr);
// TODO::need to write compareByteByteArray() and check for m_byteByteArray
// elements
m_char = pr->readWideChar("m_char");
// GenericValCompare
m_bool = pr->readBoolean("m_bool");
// GenericValCompare
m_boolArray = pr->readBooleanArray("m_boolArray", boolArrayLen);
m_byte = pr->readByte("m_byte");
m_byteArray = pr->readByteArray("m_byteArray", byteArrayLen);
m_charArray = pr->readWideCharArray("m_charArray", charArrayLen);
m_arraylist = pr->readObject("m_arraylist");
m_linkedlist =
dynCast<CacheableLinkedListPtr>(pr->readObject("m_linkedlist"));
m_map = dynCast<CacheableHashMapPtr>(pr->readObject("m_map"));
// TODO:Check for the size
m_hashtable = pr->readObject("m_hashtable");
// TODO:Check for the size
m_vector = pr->readObject("m_vector");
// TODO::Check for size
m_chs = pr->readObject("m_chs");
// TODO::Size check
m_clhs = pr->readObject("m_clhs");
// TODO:Size check
m_string = pr->readString("m_string"); // GenericValCompare
m_date = pr->readDate("m_dateTime"); // compareData
m_double = pr->readDouble("m_double");
m_doubleArray = pr->readDoubleArray("m_doubleArray", doubleArrayLen);
m_float = pr->readFloat("m_float");
m_floatArray = pr->readFloatArray("m_floatArray", floatArrayLen);
m_int16 = pr->readShort("m_int16");
m_int32 = pr->readInt("m_int32");
m_long = pr->readLong("m_long");
m_int32Array = pr->readIntArray("m_int32Array", intArrayLen);
m_longArray = pr->readLongArray("m_longArray", longArrayLen);
m_int16Array = pr->readShortArray("m_int16Array", shortArrayLen);
m_sbyte = pr->readByte("m_sbyte");
m_sbyteArray = pr->readByteArray("m_sbyteArray", byteArrayLen);
m_stringArray = pr->readStringArray("m_stringArray", strLenArray);
m_uint16 = pr->readShort("m_uint16");
m_uint32 = pr->readInt("m_uint32");
m_ulong = pr->readLong("m_ulong");
m_uint32Array = pr->readIntArray("m_uint32Array", intArrayLen);
m_ulongArray = pr->readLongArray("m_ulongArray", longArrayLen);
m_uint16Array = pr->readShortArray("m_uint16Array", shortArrayLen);
// LOGINFO("PdxType::readInt() start...");
m_byte252 = pr->readByteArray("m_byte252", m_byte252Len);
m_byte253 = pr->readByteArray("m_byte253", m_byte253Len);
m_byte65535 = pr->readByteArray("m_byte65535", m_byte65535Len);
m_byte65536 = pr->readByteArray("m_byte65536", m_byte65536Len);
// TODO:Check for size
m_pdxEnum = pr->readObject("m_pdxEnum");
m_address = pr->readObject("m_address");
// size chaeck
m_objectArray = pr->readObjectArray("m_objectArray");
m_objectArrayEmptyPdxFieldName = pr->readObjectArray("");
// Check for individual elements
// TODO:temp added delete it later
LOGINFO("PdxObject::readObject() for enum Done...");
}
CacheableStringPtr PdxTests::PdxType::toString() const {
char idbuf[1024];
// sprintf(idbuf,"PdxObject: [ m_bool=%d ] [m_byte=%d] [m_int16=%d]
// [m_int32=%d] [m_float=%f] [m_double=%lf] [ m_string=%s ]",m_bool, m_byte,
// m_int16, m_int32, m_float, m_double, m_string);
sprintf(idbuf, "PdxObject:[m_int32=%d]", m_int32);
return CacheableString::create(idbuf);
}
bool PdxTests::PdxType::equals(PdxTests::PdxType& other,
bool isPdxReadSerialized) const {
PdxType* ot = dynamic_cast<PdxType*>(&other);
if (ot == NULL) {
return false;
}
if (ot == this) {
return true;
}
genericValCompare(ot->m_int32, m_int32);
genericValCompare(ot->m_bool, m_bool);
genericValCompare(ot->m_byte, m_byte);
genericValCompare(ot->m_int16, m_int16);
genericValCompare(ot->m_long, m_long);
genericValCompare(ot->m_float, m_float);
genericValCompare(ot->m_double, m_double);
genericValCompare(ot->m_sbyte, m_sbyte);
genericValCompare(ot->m_uint16, m_uint16);
genericValCompare(ot->m_uint32, m_uint32);
genericValCompare(ot->m_ulong, m_ulong);
genericValCompare(ot->m_char, m_char);
if (strcmp(ot->m_string, m_string) != 0) {
return false;
}
genericCompare(ot->m_byteArray, m_byteArray, byteArrayLen);
genericCompare(ot->m_int16Array, m_int16Array, shortArrayLen);
genericCompare(ot->m_int32Array, m_int32Array, intArrayLen);
genericCompare(ot->m_longArray, m_longArray, longArrayLen);
genericCompare(ot->m_doubleArray, m_doubleArray, doubleArrayLen);
genericCompare(ot->m_floatArray, m_floatArray, floatArrayLen);
genericCompare(ot->m_uint32Array, m_uint32Array, intArrayLen);
genericCompare(ot->m_ulongArray, m_ulongArray, longArrayLen);
genericCompare(ot->m_uint16Array, m_uint16Array, shortArrayLen);
genericCompare(ot->m_sbyteArray, m_sbyteArray, shortArrayLen);
genericCompare(ot->m_charArray, m_charArray, charArrayLen);
// generic2DCompare(ot->m_byteByteArray, m_byteByteArray, byteByteArrayLen,
// lengthArr);
if (!isPdxReadSerialized) {
for (int i = 0; i < m_objectArray->size(); i++) {
Address* otherAddr1 =
dynamic_cast<Address*>(ot->m_objectArray->at(i).ptr());
Address* myAddr1 = dynamic_cast<Address*>(m_objectArray->at(i).ptr());
if (!otherAddr1->equals(*myAddr1)) return false;
}
LOGINFO("PdxObject::equals isPdxReadSerialized = %d", isPdxReadSerialized);
}
// m_objectArrayEmptyPdxFieldName
if (!isPdxReadSerialized) {
for (int i = 0; i < m_objectArrayEmptyPdxFieldName->size(); i++) {
Address* otherAddr1 =
dynamic_cast<Address*>(ot->m_objectArray->at(i).ptr());
Address* myAddr1 = dynamic_cast<Address*>(m_objectArray->at(i).ptr());
if (!otherAddr1->equals(*myAddr1)) return false;
}
LOGINFO("PdxObject::equals Empty Field Name isPdxReadSerialized = %d",
isPdxReadSerialized);
}
CacheableEnumPtr myenum = dynCast<CacheableEnumPtr>(m_pdxEnum);
CacheableEnumPtr otenum = dynCast<CacheableEnumPtr>(ot->m_pdxEnum);
if (myenum->getEnumOrdinal() != otenum->getEnumOrdinal()) return false;
if (strcmp(myenum->getEnumClassName(), otenum->getEnumClassName()) != 0) {
return false;
}
if (strcmp(myenum->getEnumName(), otenum->getEnumName()) != 0) return false;
genericValCompare(ot->m_arraylist->size(), m_arraylist->size());
for (int k = 0; k < m_arraylist->size(); k++) {
genericValCompare(ot->m_arraylist->at(k), m_arraylist->at(k));
}
LOGINFO("Equals Linked List Starts");
genericValCompare(ot->m_linkedlist->size(), m_linkedlist->size());
for (int k = 0; k < m_linkedlist->size(); k++) {
genericValCompare(ot->m_linkedlist->at(k), m_linkedlist->at(k));
}
LOGINFO("Equals Linked List Finished");
genericValCompare(ot->m_vector->size(), m_vector->size());
for (int j = 0; j < m_vector->size(); j++) {
genericValCompare(ot->m_vector->at(j), m_vector->at(j));
}
LOGINFO("PdxObject::equals DOne Line_201");
return true;
}
| PivotalSarge/geode-native | src/tests/cpp/testobject/PdxType.cpp | C++ | apache-2.0 | 13,394 |
package ppp.menu;
import java.awt.image.BufferedImage;
public abstract interface Menu {
public abstract void up();
public abstract void down();
public abstract void enter();
public abstract void escape();
public abstract BufferedImage getImage();
}
| mzijlstra/java-games | ppp/menu/Menu.java | Java | apache-2.0 | 256 |
require File.join(File.dirname(__FILE__), '..', 'cloudstack_rest')
Puppet::Type.type(:cloudstack_network_provider).provide :rest, :parent => Puppet::Provider::CloudstackRest do
desc "REST provider for Cloudstack Network Service Provider"
mk_resource_methods
def flush
if @property_flush[:ensure] == :absent
deleteNetworkServiceProvider
return
end
if @property_flush[:ensure] != :absent
return if createNetworkServiceProvider
end
if @property_flush[:ensure] == :enabled
enableNetworkServiceProvider
return
end
if @property_flush[:ensure] == :shutdown
shutdownNetworkServiceProvider
return
end
if @property_flush[:ensure] == :disabled
disableNetworkServiceProvider
return
end
updateNetworkServiceProvider
end
def self.instances
result = Array.new
list = get_objects(:listNetworkServiceProviders, "networkserviceprovider")
if list != nil
list.each do |object|
map = getNetworkServiceProvider(object)
if map != nil
#Puppet.debug "Network Service Provider: "+map.inspect
result.push(new(map))
end
end
end
result
end
def self.getNetworkServiceProvider(object)
if object["name"] != nil
physicalnetwork = genericLookup(:listPhysicalNetworks, "physicalnetwork", 'id', object["physicalnetworkid"], {}, 'name')
{
:id => object["id"],
:name => physicalnetwork+'_'+object["name"],
:service_provider => object["name"],
:physicalnetworkid => object["physicalnetworkid"],
:physicalnetwork => physicalnetwork,
:state => object["state"].downcase,
:ensure => :present
}
end
end
# TYPE SPECIFIC
def setState(state)
@property_flush[:ensure] = state
end
def getState
@property_hash[:state]
end
private
def createNetworkServiceProvider
if @property_hash.empty?
Puppet.debug "Create Network Service Provider "+resource[:name]
physicalnetworkid = self.class.genericLookup(:listPhysicalNetworks, "physicalnetwork", 'name', resource[:physicalnetwork], {}, 'id')
params = {
:name => resource[:service_provider],
:physicalnetworkid => physicalnetworkid,
}
Puppet.debug "addNetworkServiceProvider PARAMS = "+params.inspect
response = self.class.http_get('addNetworkServiceProvider', params)
self.class.wait_for_async_call(response["jobid"])
return true
end
false
end
def deleteNetworkServiceProvider
Puppet.debug "Delete Network Service Provider "+resource[:name]
id = lookupId
params = {
:id => id,
}
Puppet.debug "deleteNetworkServiceProvider PARAMS = "+params.inspect
# response = self.class.http_get('deleteNetworkServiceProvider', params)
# self.class.wait_for_async_call(response["jobid"])
end
def updateNetwork
Puppet.debug "Update Network Service Provider "+resource[:name]
raise "Network Service Provider only allows update for servicelist, which is currently not supported by this Puppet Module"
end
def updateState(state)
id = lookupId
params = {
:id => id,
:state => state,
}
Puppet.debug "updateNetworkServiceProvider PARAMS = "+params.inspect
response = self.class.http_get('updateNetworkServiceProvider', params)
self.class.wait_for_async_call(response["jobid"])
end
def enableNetworkServiceProvider
Puppet.debug "Enable Network Service Provider "+resource[:name]
updateState('Enabled')
end
def disableNetworkServiceProvider
Puppet.debug "Disable Network Service Provider "+resource[:name]
updateState('Disabled')
end
def shutdownNetworkServiceProvider
Puppet.debug "Shutdown Network Service Provider "+resource[:name]
updateState('Shutdown')
end
def lookupId
physicalnetworkid = self.class.genericLookup(:listPhysicalNetworks, "physicalnetwork", 'name', resource[:physicalnetwork], {}, 'id')
params = { :physicalnetworkid => physicalnetworkid }
return self.class.genericLookup(:listNetworkServiceProviders, "networkserviceprovider", 'name', resource[:service_provider], {}, 'id')
end
end | Lavaburn/puppet-cloudstack | lib/puppet/provider/cloudstack_network_provider/rest.rb | Ruby | apache-2.0 | 4,563 |
/*
*
*/
package org.utilities;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
// TODO: Auto-generated Javadoc
/**
* The Class CUtils.
*/
public class CUtils {
/**
* Work.
*
* @param task
* the task
* @return the object
*/
public static Object work(Callable<?> task) {
Future<?> futureTask = es.submit(task);
return futureTask;
}
/**
* Gets the random string.
*
* @param rndSeed the rnd seed
* @return the random string
*/
public static String getRandomString(double rndSeed) {
MessageDigest m;
try {
m = MessageDigest.getInstance("MD5");
byte[] data = ("" + rndSeed).getBytes();
m.update(data, 0, data.length);
BigInteger i = new BigInteger(1, m.digest());
return String.format("%1$032X", i);
} catch (NoSuchAlgorithmException e) {
}
return "" + rndSeed;
}
/**
* Gets the random number.
*
* @param s the s
* @return the random number
* @throws Exception the exception
*/
public static int getRandomNumber(String s) throws Exception {
MessageDigest m;
try {
m = MessageDigest.getInstance("MD5");
byte[] data = s.getBytes();
m.update(data, 0, data.length);
BigInteger i = new BigInteger(1, m.digest());
return i.intValue();
} catch (NoSuchAlgorithmException e) {
}
throw new Exception("Cannot generate random number");
}
/** The Constant es. */
private final static ExecutorService es = Executors.newCachedThreadPool();
/**
* Instantiates a new c utils.
*/
private CUtils() {
}
}
| sarathrami/Chain-Replication | src/org/utilities/CUtils.java | Java | apache-2.0 | 1,735 |
/* Copyright 2020 Telstra Open Source
*
* 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.openkilda.floodlight.switchmanager;
import static java.util.Collections.singletonList;
import static org.projectfloodlight.openflow.protocol.OFVersion.OF_12;
import static org.projectfloodlight.openflow.protocol.OFVersion.OF_13;
import net.floodlightcontroller.core.IOFSwitch;
import net.floodlightcontroller.util.FlowModUtils;
import org.projectfloodlight.openflow.protocol.OFFactory;
import org.projectfloodlight.openflow.protocol.OFFlowMod;
import org.projectfloodlight.openflow.protocol.OFMeterFlags;
import org.projectfloodlight.openflow.protocol.OFMeterMod;
import org.projectfloodlight.openflow.protocol.OFMeterModCommand;
import org.projectfloodlight.openflow.protocol.action.OFAction;
import org.projectfloodlight.openflow.protocol.action.OFActions;
import org.projectfloodlight.openflow.protocol.instruction.OFInstruction;
import org.projectfloodlight.openflow.protocol.instruction.OFInstructionApplyActions;
import org.projectfloodlight.openflow.protocol.meterband.OFMeterBandDrop;
import org.projectfloodlight.openflow.protocol.oxm.OFOxms;
import org.projectfloodlight.openflow.types.DatapathId;
import org.projectfloodlight.openflow.types.EthType;
import org.projectfloodlight.openflow.types.MacAddress;
import org.projectfloodlight.openflow.types.OFBufferId;
import org.projectfloodlight.openflow.types.OFPort;
import org.projectfloodlight.openflow.types.OFVlanVidMatch;
import org.projectfloodlight.openflow.types.TableId;
import org.projectfloodlight.openflow.types.TransportPort;
import org.projectfloodlight.openflow.types.U64;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
/**
* Utils for switch flow generation.
*/
public final class SwitchFlowUtils {
/**
* OVS software switch manufacturer constant value.
*/
public static final String OVS_MANUFACTURER = "Nicira, Inc.";
/**
* Indicates the maximum size in bytes for a packet which will be send from switch to the controller.
*/
private static final int MAX_PACKET_LEN = 0xFFFFFFFF;
private SwitchFlowUtils() {
}
/**
* Create a MAC address based on the DPID.
*
* @param dpId switch object
* @return {@link MacAddress}
*/
public static MacAddress convertDpIdToMac(DatapathId dpId) {
return MacAddress.of(Arrays.copyOfRange(dpId.getBytes(), 2, 8));
}
/**
* Create sent to controller OpenFlow action.
*
* @param ofFactory OpenFlow factory
* @return OpenFlow Action
*/
public static OFAction actionSendToController(OFFactory ofFactory) {
OFActions actions = ofFactory.actions();
return actions.buildOutput().setMaxLen(MAX_PACKET_LEN).setPort(OFPort.CONTROLLER)
.build();
}
/**
* Create an OFAction which sets the output port.
*
* @param ofFactory OF factory for the switch
* @param outputPort port to set in the action
* @return {@link OFAction}
*/
public static OFAction actionSetOutputPort(final OFFactory ofFactory, final OFPort outputPort) {
OFActions actions = ofFactory.actions();
return actions.buildOutput().setMaxLen(MAX_PACKET_LEN).setPort(outputPort).build();
}
/**
* Create go to table OFInstruction.
*
* @param ofFactory OF factory for the switch
* @param tableId tableId to go
* @return {@link OFAction}
*/
public static OFInstruction instructionGoToTable(final OFFactory ofFactory, final TableId tableId) {
return ofFactory.instructions().gotoTable(tableId);
}
/**
* Create an OFInstructionApplyActions which applies actions.
*
* @param ofFactory OF factory for the switch
* @param actionList OFAction list to apply
* @return {@link OFInstructionApplyActions}
*/
public static OFInstructionApplyActions buildInstructionApplyActions(OFFactory ofFactory,
List<OFAction> actionList) {
return ofFactory.instructions().applyActions(actionList).createBuilder().build();
}
/**
* Create set destination MAC address OpenFlow action.
*
* @param ofFactory OpenFlow factory
* @param macAddress MAC address to set
* @return OpenFlow Action
*/
public static OFAction actionSetDstMac(OFFactory ofFactory, final MacAddress macAddress) {
OFOxms oxms = ofFactory.oxms();
OFActions actions = ofFactory.actions();
return actions.buildSetField()
.setField(oxms.buildEthDst().setValue(macAddress).build()).build();
}
/**
* Create set source MAC address OpenFlow action.
*
* @param ofFactory OpenFlow factory
* @param macAddress MAC address to set
* @return OpenFlow Action
*/
public static OFAction actionSetSrcMac(OFFactory ofFactory, final MacAddress macAddress) {
return ofFactory.actions().buildSetField()
.setField(ofFactory.oxms().ethSrc(macAddress)).build();
}
/**
* Create set UDP source port OpenFlow action.
*
* @param ofFactory OpenFlow factory
* @param srcPort UDP src port to set
* @return OpenFlow Action
*/
public static OFAction actionSetUdpSrcAction(OFFactory ofFactory, TransportPort srcPort) {
OFOxms oxms = ofFactory.oxms();
return ofFactory.actions().setField(oxms.udpSrc(srcPort));
}
/**
* Create set UDP destination port OpenFlow action.
*
* @param ofFactory OpenFlow factory
* @param dstPort UDP dst port to set
* @return OpenFlow Action
*/
public static OFAction actionSetUdpDstAction(OFFactory ofFactory, TransportPort dstPort) {
OFOxms oxms = ofFactory.oxms();
return ofFactory.actions().setField(oxms.udpDst(dstPort));
}
/**
* Create OpenFlow flow modification command builder.
*
* @param ofFactory OpenFlow factory
* @param cookie cookie
* @param priority priority
* @param tableId table id
* @return OpenFlow command builder
*/
public static OFFlowMod.Builder prepareFlowModBuilder(OFFactory ofFactory, long cookie, int priority,
int tableId) {
OFFlowMod.Builder fmb = ofFactory.buildFlowAdd();
fmb.setIdleTimeout(FlowModUtils.INFINITE_TIMEOUT);
fmb.setHardTimeout(FlowModUtils.INFINITE_TIMEOUT);
fmb.setBufferId(OFBufferId.NO_BUFFER);
fmb.setCookie(U64.of(cookie));
fmb.setPriority(priority);
fmb.setTableId(TableId.of(tableId));
return fmb;
}
/**
* Create OpenFlow meter modification command.
*
* @param ofFactory OpenFlow factory
* @param bandwidth bandwidth
* @param burstSize burst size
* @param meterId meter id
* @param flags flags
* @param commandType ADD, MODIFY or DELETE
* @return OpenFlow command
*/
public static OFMeterMod buildMeterMod(OFFactory ofFactory, long bandwidth, long burstSize,
long meterId, Set<OFMeterFlags> flags, OFMeterModCommand commandType) {
OFMeterBandDrop.Builder bandBuilder = ofFactory.meterBands()
.buildDrop()
.setRate(bandwidth)
.setBurstSize(burstSize);
OFMeterMod.Builder meterModBuilder = ofFactory.buildMeterMod()
.setMeterId(meterId)
.setCommand(commandType)
.setFlags(flags);
if (ofFactory.getVersion().compareTo(OF_13) > 0) {
meterModBuilder.setBands(singletonList(bandBuilder.build()));
} else {
meterModBuilder.setMeters(singletonList(bandBuilder.build()));
}
return meterModBuilder.build();
}
/**
* Create an OFAction to add a VLAN header.
*
* @param ofFactory OF factory for the switch
* @param etherType ethernet type of the new VLAN header
* @return {@link OFAction}
*/
public static OFAction actionPushVlan(final OFFactory ofFactory, final int etherType) {
OFActions actions = ofFactory.actions();
return actions.buildPushVlan().setEthertype(EthType.of(etherType)).build();
}
/**
* Create an OFAction to change the outer most vlan.
*
* @param factory OF factory for the switch
* @param newVlan final VLAN to be set on the packet
* @return {@link OFAction}
*/
public static OFAction actionReplaceVlan(final OFFactory factory, final int newVlan) {
OFOxms oxms = factory.oxms();
OFActions actions = factory.actions();
if (OF_12.compareTo(factory.getVersion()) == 0) {
return actions.buildSetField().setField(oxms.buildVlanVid()
.setValue(OFVlanVidMatch.ofRawVid((short) newVlan))
.build()).build();
} else {
return actions.buildSetField().setField(oxms.buildVlanVid()
.setValue(OFVlanVidMatch.ofVlan(newVlan))
.build()).build();
}
}
/**
* Check switch is OVS.
*
* @param sw switch
* @return true if switch is OVS
*/
public static boolean isOvs(IOFSwitch sw) {
return OVS_MANUFACTURER.equals(sw.getSwitchDescription().getManufacturerDescription());
}
}
| telstra/open-kilda | src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/switchmanager/SwitchFlowUtils.java | Java | apache-2.0 | 9,966 |
from typing import List
class Solution:
def partitionLabels(self, S: str) -> List[int]:
lastPos, seen, currMax = {}, set(), -1
res = []
for i in range(0, 26):
c = chr(97+i)
lastPos[c] = S.rfind(c)
for i, c in enumerate(S):
# Encounter new index higher than currMax
if i > currMax:
res.append(currMax+1)
currMax = max(currMax, lastPos[c])
res.append(len(S))
ans = [res[i]-res[i-1] for i in range(1, len(res))]
return ans | saisankargochhayat/algo_quest | leetcode/763. Partition Labels/soln.py | Python | apache-2.0 | 555 |
package ruboweb.pushetta.back.model;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.jpa.domain.AbstractPersistable;
@Entity
@Table(name = "user")
public class User extends AbstractPersistable<Long> {
private static final Logger logger = LoggerFactory.getLogger(User.class);
private static final long serialVersionUID = 6088280461151862299L;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String token;
public User() {
}
public User(String name) {
this.name = name;
this.token = this.generateToken();
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the token
*/
public String getToken() {
return token;
}
/**
* @param token
* the token to set
*/
public void setToken(String token) {
this.token = token;
}
private String generateToken() {
try {
SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
String randomNum = new Integer(prng.nextInt()).toString();
MessageDigest sha = MessageDigest.getInstance("SHA-1");
byte[] bytes = sha.digest(randomNum.getBytes());
StringBuilder result = new StringBuilder();
char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
byte b;
for (int idx = 0; idx < bytes.length; ++idx) {
b = bytes[idx];
result.append(digits[(b & 240) >> 4]);
result.append(digits[b & 15]);
}
return result.toString();
} catch (NoSuchAlgorithmException ex) {
logger.error("generateToken() -- " + ex.getMessage());
}
return null;
}
}
| ruboweb/pushetta | src/main/java/ruboweb/pushetta/back/model/User.java | Java | apache-2.0 | 2,054 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.10.09 at 10:10:23 AM CST
//
package com.elong.nb.model.elong;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import java.util.List;
import com.alibaba.fastjson.annotation.JSONField;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for CommentResult complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="CommentResult">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Count" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="Comments" type="{}ArrayOfCommentInfo" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CommentResult", propOrder = {
"count",
"comments"
})
public class CommentResult {
@JSONField(name = "Count")
protected int count;
@JSONField(name = "Comments")
protected List<CommentInfo> comments;
/**
* Gets the value of the count property.
*
*/
public int getCount() {
return count;
}
/**
* Sets the value of the count property.
*
*/
public void setCount(int value) {
this.count = value;
}
/**
* Gets the value of the comments property.
*
* @return
* possible object is
* {@link List<CommentInfo> }
*
*/
public List<CommentInfo> getComments() {
return comments;
}
/**
* Sets the value of the comments property.
*
* @param value
* allowed object is
* {@link List<CommentInfo> }
*
*/
public void setComments(List<CommentInfo> value) {
this.comments = value;
}
}
| Gaonaifeng/eLong-OpenAPI-H5-demo | nb_demo_h5/src/main/java/com/elong/nb/model/elong/CommentResult.java | Java | apache-2.0 | 2,314 |
<?php
include_once 'functionCheckLogin.php';
$code_login = login_check($mysqli);
if($code_login <0) {
header('Location: /index.php');
}
?>
<html>
<head>
<meta name='viewport' content='width=device-width'>
<title>Impostazioni generali</title>
<link rel='stylesheet' href='css/style_general_settings.css'>
</head>
<body>
<div class='container'>
<div id='settings-div'>
<h3>Impostazioni generali</h3>
<fieldset>
<table align=center cellpadding=5>
<tr><td><button onClick="location.assign('formChangePassword.php')">Cambia Password</button></td></tr>
<tr><td><button onClick="location.assign('<?php if($code_login==1){echo "firstAdmin.php";} else{echo "firstUser.php";}?>')">Torna a Schede</button></td></tr>
<?php if($code_login==1){echo "<tr><td><button onClick='location.assign(\"reboot.php\")'>Riavvia dispositivo</button></td></tr>";}?>
<?php if($code_login==1){echo "<tr><td><button onClick='location.assign(\"shutdown.php\")'>Spegni dispositivo</button></td></tr>";}?>
</table>
</fieldset>
</div>
</div>
</body>
</html>
| antonyflour/RaspuinoRCS | generalSettings.php | PHP | apache-2.0 | 1,084 |
// Copyright 2014 The Serviced 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.zenoss.app.annotations;
import org.springframework.stereotype.Component;
/**
* Mark an object as an API implementation.
*/
@Component
public @interface API {
}
| zenoss/zenoss-zapp | java/zenoss-app/src/main/java/org/zenoss/app/annotations/API.java | Java | apache-2.0 | 773 |
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.ads.googleads.v9.services;
import com.google.ads.googleads.v9.resources.OperatingSystemVersionConstant;
import com.google.ads.googleads.v9.services.stub.OperatingSystemVersionConstantServiceStubSettings;
import com.google.api.core.ApiFunction;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.ClientSettings;
import com.google.api.gax.rpc.StubSettings;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import java.io.IOException;
import java.util.List;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Settings class to configure an instance of {@link OperatingSystemVersionConstantServiceClient}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li> The default service address (googleads.googleapis.com) and default port (443) are used.
* <li> Credentials are acquired automatically through Application Default Credentials.
* <li> Retries are configured for idempotent methods but not for non-idempotent methods.
* </ul>
*
* <p>The builder of this class is recursive, so contained classes are themselves builders. When
* build() is called, the tree of builders is called to create the complete settings object.
*
* <p>For example, to set the total timeout of getOperatingSystemVersionConstant to 30 seconds:
*
* <pre>{@code
* OperatingSystemVersionConstantServiceSettings.Builder
* operatingSystemVersionConstantServiceSettingsBuilder =
* OperatingSystemVersionConstantServiceSettings.newBuilder();
* operatingSystemVersionConstantServiceSettingsBuilder
* .getOperatingSystemVersionConstantSettings()
* .setRetrySettings(
* operatingSystemVersionConstantServiceSettingsBuilder
* .getOperatingSystemVersionConstantSettings()
* .getRetrySettings()
* .toBuilder()
* .setTotalTimeout(Duration.ofSeconds(30))
* .build());
* OperatingSystemVersionConstantServiceSettings operatingSystemVersionConstantServiceSettings =
* operatingSystemVersionConstantServiceSettingsBuilder.build();
* }</pre>
*/
@Generated("by gapic-generator-java")
public class OperatingSystemVersionConstantServiceSettings
extends ClientSettings<OperatingSystemVersionConstantServiceSettings> {
/** Returns the object with the settings used for calls to getOperatingSystemVersionConstant. */
public UnaryCallSettings<GetOperatingSystemVersionConstantRequest, OperatingSystemVersionConstant>
getOperatingSystemVersionConstantSettings() {
return ((OperatingSystemVersionConstantServiceStubSettings) getStubSettings())
.getOperatingSystemVersionConstantSettings();
}
public static final OperatingSystemVersionConstantServiceSettings create(
OperatingSystemVersionConstantServiceStubSettings stub) throws IOException {
return new OperatingSystemVersionConstantServiceSettings.Builder(stub.toBuilder()).build();
}
/** Returns a builder for the default ExecutorProvider for this service. */
public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
return OperatingSystemVersionConstantServiceStubSettings.defaultExecutorProviderBuilder();
}
/** Returns the default service endpoint. */
public static String getDefaultEndpoint() {
return OperatingSystemVersionConstantServiceStubSettings.getDefaultEndpoint();
}
/** Returns the default service scopes. */
public static List<String> getDefaultServiceScopes() {
return OperatingSystemVersionConstantServiceStubSettings.getDefaultServiceScopes();
}
/** Returns a builder for the default credentials for this service. */
public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
return OperatingSystemVersionConstantServiceStubSettings.defaultCredentialsProviderBuilder();
}
/** Returns a builder for the default ChannelProvider for this service. */
public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() {
return OperatingSystemVersionConstantServiceStubSettings.defaultGrpcTransportProviderBuilder();
}
public static TransportChannelProvider defaultTransportChannelProvider() {
return OperatingSystemVersionConstantServiceStubSettings.defaultTransportChannelProvider();
}
@BetaApi("The surface for customizing headers is not stable yet and may change in the future.")
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return OperatingSystemVersionConstantServiceStubSettings
.defaultApiClientHeaderProviderBuilder();
}
/** Returns a new builder for this class. */
public static Builder newBuilder() {
return Builder.createDefault();
}
/** Returns a new builder for this class. */
public static Builder newBuilder(ClientContext clientContext) {
return new Builder(clientContext);
}
/** Returns a builder containing all the values of this settings class. */
public Builder toBuilder() {
return new Builder(this);
}
protected OperatingSystemVersionConstantServiceSettings(Builder settingsBuilder)
throws IOException {
super(settingsBuilder);
}
/** Builder for OperatingSystemVersionConstantServiceSettings. */
public static class Builder
extends ClientSettings.Builder<OperatingSystemVersionConstantServiceSettings, Builder> {
protected Builder() throws IOException {
this(((ClientContext) null));
}
protected Builder(ClientContext clientContext) {
super(OperatingSystemVersionConstantServiceStubSettings.newBuilder(clientContext));
}
protected Builder(OperatingSystemVersionConstantServiceSettings settings) {
super(settings.getStubSettings().toBuilder());
}
protected Builder(OperatingSystemVersionConstantServiceStubSettings.Builder stubSettings) {
super(stubSettings);
}
private static Builder createDefault() {
return new Builder(OperatingSystemVersionConstantServiceStubSettings.newBuilder());
}
public OperatingSystemVersionConstantServiceStubSettings.Builder getStubSettingsBuilder() {
return ((OperatingSystemVersionConstantServiceStubSettings.Builder) getStubSettings());
}
/**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) {
super.applyToAllUnaryMethods(
getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater);
return this;
}
/** Returns the builder for the settings used for calls to getOperatingSystemVersionConstant. */
public UnaryCallSettings.Builder<
GetOperatingSystemVersionConstantRequest, OperatingSystemVersionConstant>
getOperatingSystemVersionConstantSettings() {
return getStubSettingsBuilder().getOperatingSystemVersionConstantSettings();
}
@Override
public OperatingSystemVersionConstantServiceSettings build() throws IOException {
return new OperatingSystemVersionConstantServiceSettings(this);
}
}
}
| googleads/google-ads-java | google-ads-stubs-v9/src/main/java/com/google/ads/googleads/v9/services/OperatingSystemVersionConstantServiceSettings.java | Java | apache-2.0 | 8,198 |
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
/** git.cc
Jeremy Barnes, 14 November 2015
Copyright (c) mldb.ai inc. All rights reserved.
*/
#include "mldb/core/procedure.h"
#include "mldb/core/dataset.h"
#include "mldb/base/per_thread_accumulator.h"
#include "mldb/types/url.h"
#include "mldb/types/structure_description.h"
#include "mldb/types/vector_description.h"
#include "mldb/types/any_impl.h"
#include "mldb/vfs/fs_utils.h"
#include "mldb/base/scope.h"
#include "mldb/utils/distribution.h"
#include "mldb/base/parallel.h"
#include <boost/algorithm/string.hpp>
#include "mldb/types/annotated_exception.h"
#include "mldb/utils/log.h"
#include "mldb/ext/libgit2/include/git2.h"
#include "mldb/ext/libgit2/include/git2/revwalk.h"
#include "mldb/ext/libgit2/include/git2/commit.h"
#include "mldb/ext/libgit2/include/git2/diff.h"
struct GitFileOperation {
GitFileOperation()
: insertions(0), deletions(0)
{
}
int insertions;
int deletions;
std::string op;
};
struct GitFileStats {
GitFileStats()
: insertions(0), deletions(0)
{
}
std::map<std::string, GitFileOperation> files;
int insertions;
int deletions;
};
int stats_by_file_each_file_cb(const git_diff_delta *delta,
float progress,
void *payload)
{
GitFileStats & stats = *((GitFileStats *)payload);
GitFileOperation op;
switch (delta->status) {
case GIT_DELTA_UNMODIFIED: /** no changes */
return 0;
case GIT_DELTA_ADDED: /** entry does not exist in old version */
op.op = "added";
break;
case GIT_DELTA_DELETED: /** entry does not exist in new version */
op.op = "deleted";
break;
case GIT_DELTA_MODIFIED: /** entry content changed between old and new */
op.op = "modified";
break;
case GIT_DELTA_RENAMED: /** entry was renamed between old and new */
op.op = "renamed";
break;
case GIT_DELTA_COPIED: /** entry was copied from another old entry */
op.op = "copied";
break;
case GIT_DELTA_IGNORED: /** entry is ignored item in workdir */
return 0;
case GIT_DELTA_UNTRACKED: /** entry is untracked item in workdir */
return 0;
case GIT_DELTA_TYPECHANGE: /** type of entry changed between old and new */
return 0;
default:
throw std::logic_error("git status");
}
if (delta->old_file.path)
stats.files[delta->old_file.path] = op;
return 0;
}
int stats_by_file_each_hunk_cb(const git_diff_delta *delta,
const git_diff_hunk * hunk,
void *payload)
{
GitFileStats & stats = *((GitFileStats *)payload);
if (delta->old_file.path)
stats.files[delta->old_file.path].deletions += hunk->old_lines;
if (delta->new_file.path)
stats.files[delta->new_file.path].insertions += hunk->new_lines;
stats.insertions += hunk->new_lines;
stats.deletions += hunk->old_lines;
return 0;
}
GitFileStats git_diff_by_file(git_diff *diff)
{
GitFileStats result;
int error = git_diff_foreach(diff,
stats_by_file_each_file_cb,
nullptr, /* binary callback */
stats_by_file_each_hunk_cb,
nullptr, /* line callback */
&result);
if (error < 0) {
throw MLDB::AnnotatedException(400, "Error traversing diff: "
+ std::string(giterr_last()->message));
}
return result;
}
using namespace std;
namespace MLDB {
/*****************************************************************************/
/* GIT IMPORTER */
/*****************************************************************************/
struct GitImporterConfig : ProcedureConfig {
static constexpr const char * name = "import.git";
GitImporterConfig()
: revisions({"HEAD"}), importStats(false), importTree(false),
ignoreUnknownEncodings(true)
{
outputDataset.withType("sparse.mutable");
}
Url repository;
PolyConfigT<Dataset> outputDataset;
std::vector<std::string> revisions;
bool importStats;
bool importTree;
bool ignoreUnknownEncodings;
// TODO
// when
// where
// limit
// offset
// select (instead of importStats, importTree)
};
DECLARE_STRUCTURE_DESCRIPTION(GitImporterConfig);
DEFINE_STRUCTURE_DESCRIPTION(GitImporterConfig);
GitImporterConfigDescription::
GitImporterConfigDescription()
{
addField("repository", &GitImporterConfig::repository,
"Git repository to load from. This is currently limited to "
"file:// urls which point to an already cloned repository on "
"local disk. Remote repositories will need to be checked out "
"beforehand using the git command line tools.");
addField("outputDataset", &GitImporterConfig::outputDataset,
"Output dataset for result. One row will be produced per commit. "
"See the documentation for the output format.",
PolyConfigT<Dataset>().withType("sparse.mutable"));
std::vector<std::string> defaultRevisions = { "HEAD" };
addField("revisions", &GitImporterConfig::revisions,
"Revisions to load from Git (eg, HEAD, HEAD~20..HEAD, tags/*). "
"See the gitrevisions (7) documentation. Default is all revisions "
"reachable from HEAD", defaultRevisions);
addField("importStats", &GitImporterConfig::importStats,
"If true, then import the stats (number of files "
"changed, lines added and lines deleted)", false);
addField("importTree", &GitImporterConfig::importTree,
"If true, then import the tree (names of files changed)", false);
addField("ignoreUnknownEncodings",
&GitImporterConfig::ignoreUnknownEncodings,
"If true (default), ignore commit messages with unknown encodings "
"(supported are ISO-8859-1 and UTF-8) and replace with a "
"placeholder. If false, messages with unknown encodings will "
"cause the commit to abort.");
addParent<ProcedureConfig>();
}
struct GitImporter: public Procedure {
GitImporter(MldbEngine * owner,
PolyConfig config_,
const std::function<bool (const Json::Value &)> & onProgress)
: Procedure(owner)
{
config = config_.params.convert<GitImporterConfig>();
}
GitImporterConfig config;
std::string encodeOid(const git_oid & oid) const
{
char shortsha[10] = {0};
git_oid_tostr(shortsha, 9, &oid);
return string(shortsha);
};
// Process an individual commit
std::vector<std::tuple<ColumnPath, CellValue, Date> >
processCommit(git_repository * repo, const git_oid & oid) const
{
string sha = encodeOid(oid);
auto checkError = [&] (int error, const char * msg)
{
if (error < 0)
throw AnnotatedException(500, string(msg) + ": "
+ giterr_last()->message,
"repository", config.repository,
"commit", string(sha));
};
git_commit *commit;
int error = git_commit_lookup(&commit, repo, &oid);
checkError(error, "Error getting commit");
Scope_Exit(git_commit_free(commit));
const char *encoding = git_commit_message_encoding(commit);
const char *messageStr = git_commit_message(commit);
git_time_t time = git_commit_time(commit);
int offset_in_min = git_commit_time_offset(commit);
const git_signature *committer = git_commit_committer(commit);
const git_signature *author = git_commit_author(commit);
//const git_oid *tree_id = git_commit_tree_id(commit);
git_diff *diff = nullptr;
Scope_Exit(git_diff_free(diff));
Utf8String message;
if (!encoding || strcmp(encoding, "UTF-8") == 0) {
message = Utf8String(messageStr);
}
else if (strcmp(encoding,"ISO-8859-1") == 0) {
message = Utf8String::fromLatin1(messageStr);
}
else if (config.ignoreUnknownEncodings) {
message = "<<<couldn't decode message in "
+ string(encoding) + " character set>>>";
}
else {
throw AnnotatedException(500,
"Can't decode unknown commit message encoding",
"repository", config.repository,
"commit", string(sha),
"encoding", encoding);
}
vector<string> parents;
unsigned int parentCount = git_commit_parentcount(commit);
for (unsigned i = 0; i < parentCount; ++i) {
const git_oid *nth_parent_id = git_commit_parent_id(commit, i);
git_commit *nth_parent = nullptr;
int error = git_commit_parent(&nth_parent, commit, i);
checkError(error, "Error getting commit parent");
Scope_Exit(git_commit_free(nth_parent));
parents.emplace_back(encodeOid(*nth_parent_id));
if (i == 0 && parentCount == 1
&& (config.importStats || config.importTree)) {
const git_oid * parent_tree_id = git_commit_tree_id(nth_parent);
if (parent_tree_id) {
git_tree * tree = nullptr;
git_tree * parentTree = nullptr;
error = git_commit_tree(&tree, commit);
checkError(error, "Error getting commit tree");
Scope_Exit(git_tree_free(tree));
error = git_commit_tree(&parentTree, nth_parent);
checkError(error, "Error getting parent tree");
Scope_Exit(git_tree_free(parentTree));
error = git_diff_tree_to_tree(&diff, repo, tree, parentTree, NULL);
checkError(error, "Error diffing commits");
git_diff_find_options opts = GIT_DIFF_FIND_OPTIONS_INIT;
opts.flags = GIT_DIFF_FIND_RENAMES |
GIT_DIFF_FIND_COPIES |
GIT_DIFF_FIND_FOR_UNTRACKED;
error = git_diff_find_similar(diff, &opts);
checkError(error, "Error detecting renames");
}
}
}
Date timestamp = Date::fromSecondsSinceEpoch(time + 60 * offset_in_min);
Utf8String committerName(committer->name);
Utf8String committerEmail(committer->email);
Utf8String authorName(author->name);
Utf8String authorEmail(author->email);
std::vector<std::tuple<ColumnPath, CellValue, Date> > row;
row.emplace_back(ColumnPath("committer"), committerName, timestamp);
row.emplace_back(ColumnPath("committerEmail"), committerEmail, timestamp);
row.emplace_back(ColumnPath("author"), authorName, timestamp);
row.emplace_back(ColumnPath("authorEmail"), authorEmail, timestamp);
row.emplace_back(ColumnPath("message"), message, timestamp);
row.emplace_back(ColumnPath("parentCount"), parentCount, timestamp);
for (auto & p: parents)
row.emplace_back(ColumnPath("parent"), p, timestamp);
int filesChanged = 0;
int insertions = 0;
int deletions = 0;
if (diff) {
GitFileStats stats = git_diff_by_file(diff);
filesChanged = stats.files.size();
insertions = stats.insertions;
deletions = stats.deletions;
row.emplace_back(ColumnPath("insertions"), insertions, timestamp);
row.emplace_back(ColumnPath("deletions"), deletions, timestamp);
row.emplace_back(ColumnPath("filesChanged"), filesChanged, timestamp);
for (auto & f: stats.files) {
if (!config.importTree) break;
Utf8String filename(f.first);
row.emplace_back(ColumnPath("file"), filename, timestamp);
if (f.second.insertions > 0)
row.emplace_back(ColumnPath("file." + filename + ".insertions"),
f.second.insertions, timestamp);
if (f.second.deletions > 0)
row.emplace_back(ColumnPath("file." + filename + ".deletions"),
f.second.deletions, timestamp);
if (!f.second.op.empty())
row.emplace_back(ColumnPath("file." + filename + ".op"),
f.second.op, timestamp);
}
}
DEBUG_MSG(logger)
<< "id " << sha << " had " << filesChanged << " changes, "
<< insertions << " insertions and " << deletions << " deletions "
<< message << " parents " << parentCount;
return row;
}
virtual RunOutput run(const ProcedureRunConfig & run,
const std::function<bool (const Json::Value &)> & onProgress) const
{
auto runProcConf = applyRunConfOverProcConf(config, run);
auto checkError = [&] (int error, const char * msg)
{
if (error < 0)
throw AnnotatedException(500, string(msg) + ": "
+ giterr_last()->message,
"repository", runProcConf.repository);
};
git_libgit2_init();
Scope_Exit(git_libgit2_shutdown());
git_repository * repo;
Utf8String repoName(runProcConf.repository.toString());
repoName.removePrefix("file://");
int error = git_repository_open(&repo, repoName.rawData());
checkError(error, "Error opening git repository");
Scope_Exit(git_repository_free(repo));
// Create the output dataset
std::shared_ptr<Dataset> output;
if (!runProcConf.outputDataset.type.empty()
|| !runProcConf.outputDataset.id.empty()) {
output = createDataset(engine, runProcConf.outputDataset,
nullptr, true /*overwrite*/);
}
git_revwalk *walker;
error = git_revwalk_new(&walker, repo);
checkError(error, "Error creating commit walker");
Scope_Exit(git_revwalk_free(walker));
for (auto & r: runProcConf.revisions) {
if (r.find("*") != string::npos)
error = git_revwalk_push_glob(walker, r.c_str());
else if (r.find("..") != string::npos)
error = git_revwalk_push_range(walker, r.c_str());
else error = git_revwalk_push_ref(walker, r.c_str());
if (error < 0)
throw AnnotatedException(500, "Error adding revision: "
+ string(giterr_last()->message),
"repository", runProcConf.repository,
"revision", r);
}
vector<git_oid> oids;
git_oid oid;
while (!git_revwalk_next(&oid, walker)) {
oids.push_back(oid);
}
struct Accum {
Accum(const Utf8String & filename)
{
rows.reserve(1000);
int error = git_repository_open(&repo, filename.rawData());
if (error < 0)
throw AnnotatedException(400, "Error opening Git repo: "
+ string(giterr_last()->message));
}
~Accum()
{
git_repository_free(repo);
}
std::vector<std::pair<RowPath, std::vector<std::tuple<ColumnPath, CellValue, Date> > > > rows;
git_repository * repo;
};
PerThreadAccumulator<Accum> accum([&] () { return new Accum(repoName); });
INFO_MSG(logger) << "processing " << oids.size() << " commits";
auto doProcessCommit = [&] (int i)
{
if (i && i % 100 == 0)
INFO_MSG(logger)
<< "imported commit " << i << " of " << oids.size();
Accum & threadAccum = accum.get();
auto row = processCommit(repo, oids[i]);
threadAccum.rows.emplace_back(RowPath(encodeOid(oids[i])),
std::move(row));
if (threadAccum.rows.size() == 1000) {
output->recordRows(threadAccum.rows);
threadAccum.rows.clear();
}
};
parallelMap(0, oids.size(), doProcessCommit);
for (auto & t: accum.threads) {
output->recordRows(t->rows);
}
output->commit();
RunOutput result;
return result;
}
virtual Any getStatus() const
{
return Any();
}
GitImporterConfig procConfig;
};
RegisterProcedureType<GitImporter, GitImporterConfig>
regGit(builtinPackage(),
"Import a Git repository's metadata into MLDB",
"procedures/GitImporter.md.html");
} // namespace MLDB
| mldbai/mldb | plugins/git/git.cc | C++ | apache-2.0 | 17,692 |
/*
* Copyright 2006-2016 Edward Smith
*
* 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 root.json;
import root.lang.StringExtractor;
/**
*
* @author Edward Smith
* @version 0.5
* @since 0.5
*/
final class JSONBoolean extends JSONValue {
// <><><><><><><><><><><><><>< Class Attributes ><><><><><><><><><><><><><>
private final boolean value;
// <><><><><><><><><><><><><><>< Constructors ><><><><><><><><><><><><><><>
JSONBoolean(final boolean value) {
this.value = value;
}
// <><><><><><><><><><><><><><> Public Methods <><><><><><><><><><><><><><>
@Override
public final void extract(final StringExtractor chars) {
chars.append(this.value);
}
} // End JSONBoolean
| macvelli/RootFramework | src/root/json/JSONBoolean.java | Java | apache-2.0 | 1,215 |
package uk.co.listpoint.context;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Context6Type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="Context6Type">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="Data Standard"/>
* <enumeration value="Application"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "Context6Type", namespace = "http://www.listpoint.co.uk/schemas/v6")
@XmlEnum
public enum Context6Type {
@XmlEnumValue("Data Standard")
DATA_STANDARD("Data Standard"),
@XmlEnumValue("Application")
APPLICATION("Application");
private final String value;
Context6Type(String v) {
value = v;
}
public String value() {
return value;
}
public static Context6Type fromValue(String v) {
for (Context6Type c: Context6Type.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| davidcarboni/listpoint-ws | src/main/java/uk/co/listpoint/context/Context6Type.java | Java | apache-2.0 | 1,238 |
package com.example.customviewdemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class DragViewActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drag_view);
}
}
| jianghang/CustomViewDemo | src/com/example/customviewdemo/DragViewActivity.java | Java | apache-2.0 | 354 |
/*
* 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 redis.common.container;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.common.config.FlinkJedisClusterConfig;
import redis.common.config.FlinkJedisConfigBase;
import redis.common.config.FlinkJedisPoolConfig;
import redis.common.config.FlinkJedisSentinelConfig;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisSentinelPool;
import redis.common.container.*;
import redis.common.container.RedisCommandsContainer;
import redis.common.container.RedisContainer;
import java.util.Objects;
/**
* The builder for {@link redis.common.container.RedisCommandsContainer}.
*/
public class RedisCommandsContainerBuilder {
/**
* Initialize the {@link redis.common.container.RedisCommandsContainer} based on the instance type.
* @param flinkJedisConfigBase configuration base
* @return @throws IllegalArgumentException if jedisPoolConfig, jedisClusterConfig and jedisSentinelConfig are all null
*/
public static redis.common.container.RedisCommandsContainer build(FlinkJedisConfigBase flinkJedisConfigBase){
if(flinkJedisConfigBase instanceof FlinkJedisPoolConfig){
FlinkJedisPoolConfig flinkJedisPoolConfig = (FlinkJedisPoolConfig) flinkJedisConfigBase;
return RedisCommandsContainerBuilder.build(flinkJedisPoolConfig);
} else if (flinkJedisConfigBase instanceof FlinkJedisClusterConfig) {
FlinkJedisClusterConfig flinkJedisClusterConfig = (FlinkJedisClusterConfig) flinkJedisConfigBase;
return RedisCommandsContainerBuilder.build(flinkJedisClusterConfig);
} else if (flinkJedisConfigBase instanceof FlinkJedisSentinelConfig) {
FlinkJedisSentinelConfig flinkJedisSentinelConfig = (FlinkJedisSentinelConfig) flinkJedisConfigBase;
return RedisCommandsContainerBuilder.build(flinkJedisSentinelConfig);
} else {
throw new IllegalArgumentException("Jedis configuration not found");
}
}
/**
* Builds container for single Redis environment.
*
* @param jedisPoolConfig configuration for JedisPool
* @return container for single Redis environment
* @throws NullPointerException if jedisPoolConfig is null
*/
public static redis.common.container.RedisCommandsContainer build(FlinkJedisPoolConfig jedisPoolConfig) {
Objects.requireNonNull(jedisPoolConfig, "Redis pool config should not be Null");
GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
genericObjectPoolConfig.setMaxIdle(jedisPoolConfig.getMaxIdle());
genericObjectPoolConfig.setMaxTotal(jedisPoolConfig.getMaxTotal());
genericObjectPoolConfig.setMinIdle(jedisPoolConfig.getMinIdle());
JedisPool jedisPool = new JedisPool(genericObjectPoolConfig, jedisPoolConfig.getHost(),
jedisPoolConfig.getPort(), jedisPoolConfig.getConnectionTimeout(), jedisPoolConfig.getPassword(),
jedisPoolConfig.getDatabase());
return new redis.common.container.RedisContainer(jedisPool);
}
/**
* Builds container for Redis Cluster environment.
*
* @param jedisClusterConfig configuration for JedisCluster
* @return container for Redis Cluster environment
* @throws NullPointerException if jedisClusterConfig is null
*/
public static redis.common.container.RedisCommandsContainer build(FlinkJedisClusterConfig jedisClusterConfig) {
Objects.requireNonNull(jedisClusterConfig, "Redis cluster config should not be Null");
GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
genericObjectPoolConfig.setMaxIdle(jedisClusterConfig.getMaxIdle());
genericObjectPoolConfig.setMaxTotal(jedisClusterConfig.getMaxTotal());
genericObjectPoolConfig.setMinIdle(jedisClusterConfig.getMinIdle());
JedisCluster jedisCluster = new JedisCluster(jedisClusterConfig.getNodes(), jedisClusterConfig.getConnectionTimeout(),
jedisClusterConfig.getMaxRedirections(), genericObjectPoolConfig);
return new redis.common.container.RedisClusterContainer(jedisCluster);
}
/**
* Builds container for Redis Sentinel environment.
*
* @param jedisSentinelConfig configuration for JedisSentinel
* @return container for Redis sentinel environment
* @throws NullPointerException if jedisSentinelConfig is null
*/
public static RedisCommandsContainer build(FlinkJedisSentinelConfig jedisSentinelConfig) {
Objects.requireNonNull(jedisSentinelConfig, "Redis sentinel config should not be Null");
GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
genericObjectPoolConfig.setMaxIdle(jedisSentinelConfig.getMaxIdle());
genericObjectPoolConfig.setMaxTotal(jedisSentinelConfig.getMaxTotal());
genericObjectPoolConfig.setMinIdle(jedisSentinelConfig.getMinIdle());
JedisSentinelPool jedisSentinelPool = new JedisSentinelPool(jedisSentinelConfig.getMasterName(),
jedisSentinelConfig.getSentinels(), genericObjectPoolConfig,
jedisSentinelConfig.getConnectionTimeout(), jedisSentinelConfig.getSoTimeout(),
jedisSentinelConfig.getPassword(), jedisSentinelConfig.getDatabase());
return new RedisContainer(jedisSentinelPool);
}
}
| eltitopera/TFM | manager/src/src/main/java/redis/common/container/RedisCommandsContainerBuilder.java | Java | apache-2.0 | 6,212 |
package fundamental.games.metropolis.connection.bluetooth;
import android.bluetooth.BluetoothSocket;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.UUID;
import fundamental.games.metropolis.connection.global.MessagesQueue;
import fundamental.games.metropolis.connection.serializable.PlayerInitData;
import fundamental.games.metropolis.global.WidgetsData;
/**
* Created by regair on 27.05.15.
*/
public class BluetoothServerConnection extends BluetoothConnection
{
private ObjectOutputStream writer;
private ObjectInputStream reader;
//********************************
public BluetoothServerConnection(BluetoothSocket socket, MessagesQueue<Serializable> queue, UUID uuid)
{
super(socket, queue, uuid);
this.queue = new MessagesQueue<>();
deviceName = "SERVER";
}
//********************************
@Override
public void run()
{
working = true;
}
//********************************
@Override
public void stopConnection()
{
super.stopConnection();
BluetoothServer.getInstance().removeConnection(this);
}
public MessagesQueue<Serializable> getQueue()
{
return queue;
}
//**********************************
public void sendMessage(Serializable message)
{
if(message instanceof PlayerInitData)
{
setID(((PlayerInitData)message).ID);
//ID = ((PlayerInitData)message).ID;
BluetoothServer.getInstance().getIncomingQueue().addMessage(new PlayerInitData(WidgetsData.playerName, ID));
return;
}
queue.addMessage(message);
}
@Override
public void setID(int id)
{
super.setID(id);
BluetoothConnection.humanID = id;
}
}
| Ragnarokma/metropolis | src/main/java/fundamental/games/metropolis/connection/bluetooth/BluetoothServerConnection.java | Java | apache-2.0 | 1,850 |
// Reset
$('.touch .client-wrap').click(function(event){
var target = $( event.target );
if ( target.hasClass( "client-close" ) ) {
$('.client-wrap div.client').addClass('reset');
}
else{
$('.client-wrap div.client').removeClass('reset');
}
});
// David Walsh simple lazy loading
[].forEach.call(document.querySelectorAll('img[data-src]'), function(img) {
img.setAttribute('src', img.getAttribute('data-src'));
img.onload = function() {
img.removeAttribute('data-src');
};
}); | urban-knight/dmcc-website | public/js/clients.js | JavaScript | apache-2.0 | 512 |
package bookshop2.client.paymentService;
import java.util.List;
import org.aries.message.Message;
import org.aries.message.MessageInterceptor;
import org.aries.util.ExceptionUtil;
import bookshop2.Payment;
@SuppressWarnings("serial")
public class PaymentServiceInterceptor extends MessageInterceptor<PaymentService> implements PaymentService {
@Override
public List<Payment> getAllPaymentRecords() {
try {
log.info("#### [admin]: getAllPaymentRecords() sending...");
Message request = createMessage("getAllPaymentRecords");
Message response = getProxy().invoke(request);
List<Payment> result = response.getPart("result");
return result;
} catch (Exception e) {
throw ExceptionUtil.rewrap(e);
}
}
@Override
public Payment getPaymentRecordById(Long id) {
try {
log.info("#### [admin]: getPaymentRecordById() sending...");
Message request = createMessage("getPaymentRecordById");
request.addPart("id", id);
Message response = getProxy().invoke(request);
Payment result = response.getPart("result");
return result;
} catch (Exception e) {
throw ExceptionUtil.rewrap(e);
}
}
@Override
public List<Payment> getPaymentRecordsByPage(int pageIndex, int pageSize) {
try {
log.info("#### [admin]: getPaymentRecordsByPage() sending...");
Message request = createMessage("getPaymentRecordsByPage");
request.addPart("pageIndex", pageIndex);
request.addPart("pageSize", pageSize);
Message response = getProxy().invoke(request);
List<Payment> result = response.getPart("result");
return result;
} catch (Exception e) {
throw ExceptionUtil.rewrap(e);
}
}
@Override
public Long addPaymentRecord(Payment payment) {
try {
log.info("#### [admin]: addPaymentRecord() sending...");
Message request = createMessage("addPaymentRecord");
request.addPart("payment", payment);
Message response = getProxy().invoke(request);
Long result = response.getPart("result");
return result;
} catch (Exception e) {
throw ExceptionUtil.rewrap(e);
}
}
@Override
public void savePaymentRecord(Payment payment) {
try {
log.info("#### [admin]: savePaymentRecord() sending...");
Message request = createMessage("savePaymentRecord");
request.addPart("payment", payment);
getProxy().invoke(request);
} catch (Exception e) {
throw ExceptionUtil.rewrap(e);
}
}
@Override
public void removeAllPaymentRecords() {
try {
log.info("#### [admin]: removeAllPaymentRecords() sending...");
Message request = createMessage("removeAllPaymentRecords");
getProxy().invoke(request);
} catch (Exception e) {
throw ExceptionUtil.rewrap(e);
}
}
@Override
public void removePaymentRecord(Payment payment) {
try {
log.info("#### [admin]: removePaymentRecord() sending...");
Message request = createMessage("removePaymentRecord");
request.addPart("payment", payment);
getProxy().invoke(request);
} catch (Exception e) {
throw ExceptionUtil.rewrap(e);
}
}
@Override
public void importPaymentRecords() {
try {
log.info("#### [admin]: importPaymentRecords() sending...");
Message request = createMessage("importPaymentRecords");
getProxy().invoke(request);
} catch (Exception e) {
throw ExceptionUtil.rewrap(e);
}
}
}
| tfisher1226/ARIES | bookshop2/bookshop2-client/src/main/java/bookshop2/client/paymentService/PaymentServiceInterceptor.java | Java | apache-2.0 | 3,276 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.redshift.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DeleteAuthenticationProfile"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteAuthenticationProfileRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The name of the authentication profile to delete.
* </p>
*/
private String authenticationProfileName;
/**
* <p>
* The name of the authentication profile to delete.
* </p>
*
* @param authenticationProfileName
* The name of the authentication profile to delete.
*/
public void setAuthenticationProfileName(String authenticationProfileName) {
this.authenticationProfileName = authenticationProfileName;
}
/**
* <p>
* The name of the authentication profile to delete.
* </p>
*
* @return The name of the authentication profile to delete.
*/
public String getAuthenticationProfileName() {
return this.authenticationProfileName;
}
/**
* <p>
* The name of the authentication profile to delete.
* </p>
*
* @param authenticationProfileName
* The name of the authentication profile to delete.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DeleteAuthenticationProfileRequest withAuthenticationProfileName(String authenticationProfileName) {
setAuthenticationProfileName(authenticationProfileName);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAuthenticationProfileName() != null)
sb.append("AuthenticationProfileName: ").append(getAuthenticationProfileName());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DeleteAuthenticationProfileRequest == false)
return false;
DeleteAuthenticationProfileRequest other = (DeleteAuthenticationProfileRequest) obj;
if (other.getAuthenticationProfileName() == null ^ this.getAuthenticationProfileName() == null)
return false;
if (other.getAuthenticationProfileName() != null && other.getAuthenticationProfileName().equals(this.getAuthenticationProfileName()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAuthenticationProfileName() == null) ? 0 : getAuthenticationProfileName().hashCode());
return hashCode;
}
@Override
public DeleteAuthenticationProfileRequest clone() {
return (DeleteAuthenticationProfileRequest) super.clone();
}
}
| aws/aws-sdk-java | aws-java-sdk-redshift/src/main/java/com/amazonaws/services/redshift/model/DeleteAuthenticationProfileRequest.java | Java | apache-2.0 | 4,104 |
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using tracktor.app.Models;
namespace tracktor.app
{
[Produces("application/json")]
[Route("api/account")]
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger _logger;
private readonly IConfiguration _config;
private readonly IAntiforgery _antiForgery;
private readonly IEmailSender _emailSender;
private readonly ITracktorService _client;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
ILoggerFactory loggerFactory,
IAntiforgery antiForgery,
IConfiguration config,
IEmailSender emailSender,
ITracktorService client)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = loggerFactory.CreateLogger<AccountController>();
_antiForgery = antiForgery;
_config = config;
_emailSender = emailSender;
_client = client;
}
private async Task<LoginDTO> CreateResponse(ApplicationUser user)
{
HttpContext.User = user != null ? await _signInManager.CreateUserPrincipalAsync(user) : null;
var roles = user != null ? await _userManager.GetRolesAsync(user) : null;
var afTokenSet = _antiForgery.GetAndStoreTokens(Request.HttpContext);
return new LoginDTO
{
id = user?.Id,
afToken = afTokenSet.RequestToken,
afHeader = afTokenSet.HeaderName,
email = user?.Email,
roles = roles,
timeZone = user?.TimeZone
};
}
private static bool IsPopulated(string v)
{
return !string.IsNullOrWhiteSpace(v);
}
/// <summary>
/// Registers a new user
/// </summary>
/// <param name="dto">Required fields: email, password</param>
/// <returns>LoginDTO</returns>
[HttpPost("register")]
[AllowAnonymous]
public async Task<IActionResult> Register([FromBody]AccountDTO dto)
{
if(!IsPopulated(dto?.email) || !IsPopulated(dto?.password))
{
return BadRequest();
}
if(!EmailHelpers.Validate(dto.Username))
{
return BadRequest();
}
if(!Boolean.Parse(_config["Tracktor:RegistrationEnabled"]))
{
return BadRequest("@RegistrationDisabled");
}
if (_config["Tracktor:RegistrationCode"] != dto.code)
{
return BadRequest("@BadCode");
}
var user = new ApplicationUser { UserName = dto.Username, Email = dto.Username };
var result = await _userManager.CreateAsync(user, dto.password);
if (result.Succeeded)
{
user = await _userManager.FindByEmailAsync(dto.Username);
await _userManager.AddToRoleAsync(user, "User");
await _signInManager.SignInAsync(user, isPersistent: true);
_logger.LogInformation(3, $"User {dto.Username} created a new account with a password");
// create user in tracktor
user.TUserID = await _client.CreateUserAsync(user.Id);
user.TimeZone = dto.timezone;
await _userManager.UpdateAsync(user);
return Ok(await CreateResponse(user));
}
else if(result.Errors != null && result.Errors.Any(e => e.Code == "DuplicateUserName"))
{
return BadRequest("@UsernameTaken");
}
else
{
_logger.LogWarning($"Unable to register user {dto.Username}: {string.Join(", ", result.Errors.Select(e => e.Description))}");
}
return BadRequest("@UnableToRegister");
}
/// <summary>
/// Creates or logs in a user using external provider
/// </summary>
/// <param name="dto">Required fields: provider, code</param>
/// <returns>LoginDTO</returns>
[HttpPost("external")]
[AllowAnonymous]
public async Task<IActionResult> ExternalLogin([FromBody]AccountDTO dto)
{
if (!IsPopulated(dto?.code) || !IsPopulated(dto?.provider))
{
return BadRequest();
}
var appVerified = false;
var emailVerified = false;
switch (dto.provider)
{
case "Facebook":
{
try
{
var hc = new HttpClient();
var verifyUrl = _config["Facebook:VerifyUrl"];
var appId = _config["Facebook:AppId"];
var userUrl = _config["Facebook:UserUrl"];
if (string.IsNullOrWhiteSpace(verifyUrl) || string.IsNullOrWhiteSpace(userUrl))
{
return BadRequest("@ProviderNotEnabled");
}
var appString = await hc.GetStringAsync(verifyUrl + dto.code);
var userString = await hc.GetStringAsync(userUrl + dto.code);
if (!string.IsNullOrWhiteSpace(appString) && !string.IsNullOrWhiteSpace(userString))
{
var appResult = Newtonsoft.Json.JsonConvert.DeserializeObject(appString) as JObject;
var userResult = Newtonsoft.Json.JsonConvert.DeserializeObject(userString) as JObject;
if (userResult["email"] != null)
{
dto.email = userResult["email"].ToString();
emailVerified = true;
}
if (appResult["id"] != null && appResult["id"].ToString() == appId)
{
appVerified = true;
}
}
} catch(Exception ex)
{
_logger.LogError($"Unable to log via {dto.provider}: {ex.Message}");
return BadRequest("@UnableToLogin" + dto.provider);
}
}
break;
default:
return BadRequest("@UnknownLoginProvider");
}
if(string.IsNullOrWhiteSpace(dto.Username) || !emailVerified || !appVerified)
{
return BadRequest("@UnableToLogin" + dto.provider);
}
if (!EmailHelpers.Validate(dto.Username))
{
return BadRequest();
}
// create user if necessary
var user = await _userManager.FindByEmailAsync(dto.Username);
if (user == null)
{
if (!Boolean.Parse(_config["Tracktor:RegistrationEnabled"]))
{
return BadRequest("@RegistrationDisabled");
}
user = new ApplicationUser { Email = dto.Username, UserName = dto.Username };
await _userManager.CreateAsync(user);
await _userManager.AddToRoleAsync(user, "User");
}
if (await _signInManager.CanSignInAsync(user))
{
await _signInManager.SignInAsync(user, true);
_logger.LogInformation(1, $"User {dto.Username} logged in from {Request.HttpContext.Connection.RemoteIpAddress} via Facebook");
return Ok(await CreateResponse(user));
}
else
{
_logger.LogWarning(2, $"Invalid login attempt for user {dto.Username} from {Request.HttpContext.Connection.RemoteIpAddress}.");
return BadRequest("@UnableToLogin" + dto.provider);
}
}
/// <summary>
/// Logs in a user using password
/// </summary>
/// <param name="dto">Required fields: email, password</param>
/// <returns>LoginDTO</returns>
[HttpPost("login")]
[AllowAnonymous]
public async Task<IActionResult> Login([FromBody]AccountDTO dto)
{
if (!IsPopulated(dto?.email) || !IsPopulated(dto?.password))
{
return BadRequest();
}
var result = await _signInManager.PasswordSignInAsync(dto.Username, dto.password, dto.remember, lockoutOnFailure: true);
if (result.Succeeded)
{
var user = await _userManager.FindByEmailAsync(dto.Username);
_logger.LogInformation(1, $"User {dto.Username} logged in from {Request.HttpContext.Connection.RemoteIpAddress}");
return Ok(await CreateResponse(user));
}
if (result.IsLockedOut || result.IsNotAllowed)
{
_logger.LogWarning(2, $"User {dto.Username} is locked out.");
return BadRequest("@LockedOut");
}
else
{
_logger.LogWarning(2, $"Invalid login attempt for user {dto.Username} from {Request.HttpContext.Connection.RemoteIpAddress}.");
return BadRequest("@InvalidAttempt");
}
}
/// <summary>
/// Logs out current user
/// </summary>
/// <returns>LoginDTO</returns>
[HttpPost("logout")]
[IgnoreAntiforgeryToken]
[Authorize]
public async Task<IActionResult> Logout()
{
var userName = User.Identity.Name;
await _signInManager.SignOutAsync();
_logger.LogInformation(4, $"User {userName} logged out");
return Ok(await CreateResponse(null));
}
/// <summary>
/// Requests a password reset email
/// </summary>
/// <param name="dto">Required fields: email</param>
[HttpPost("forgot")]
[AllowAnonymous]
public async Task<IActionResult> Forgot([FromBody]AccountDTO dto)
{
if (!IsPopulated(dto?.email))
{
return BadRequest();
}
var user = await _userManager.FindByEmailAsync(dto.Username);
if (user == null)
{
return BadRequest("@UnknownUser");
}
var code = await _userManager.GeneratePasswordResetTokenAsync(user);
var callbackUrl = UrlHelperExtensions.Action(Url, "Index", "Home", new { reset = dto.Username, code = code }, HttpContext.Request.Scheme);
_logger.LogInformation(5, $"User {dto.Username} requested a password reset link.");
var subject = dto.messages != null && dto.messages.Length > 0 && !string.IsNullOrWhiteSpace(dto.messages[0]) ? dto.messages[0] : "Tracktor - password reset";
var body = dto.messages != null && dto.messages.Length > 1 && !string.IsNullOrWhiteSpace(dto.messages[1]) ? dto.messages[1] : "Please click the link below to reset your password.";
await _emailSender.SendEmailAsync(dto.Username, subject, body, callbackUrl);
return Ok();
}
/// <summary>
/// Changes current user's password
/// </summary>
/// <param name="dto">Required fields: password, newPassword</param>
/// <returns>LoginDTO</returns>
[HttpPost("change")]
[Authorize]
public async Task<IActionResult> Change([FromBody]AccountDTO dto)
{
if (!IsPopulated(dto?.password) || !IsPopulated(dto?.newPassword))
{
return BadRequest();
}
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
// don't reveal anything
return BadRequest("@UnknownUser");
}
var result = await _userManager.ChangePasswordAsync(user, dto.password, dto.newPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, true);
_logger.LogInformation(6, $"User {user.Email} has successfully changed password.");
return Ok(await CreateResponse(user));
}
return BadRequest("@InvalidChangeAttempt");
}
/// <summary>
/// Resets current user's password using a reset code
/// </summary>
/// <param name="dto">Required fields: email, password, code</param>
/// <returns>LoginDTO</returns>
[HttpPost("reset")]
[AllowAnonymous]
public async Task<IActionResult> Reset([FromBody]AccountDTO dto)
{
if (!IsPopulated(dto?.email) || !IsPopulated(dto?.password) || !IsPopulated(dto?.code))
{
return BadRequest();
}
var user = await _userManager.FindByEmailAsync(dto.Username);
if (user == null)
{
// don't reveal anything
return Ok();
}
if (_signInManager.IsSignedIn(User))
{
await _signInManager.SignOutAsync();
}
var result = await _userManager.ResetPasswordAsync(user, dto.code, dto.password);
_logger.LogInformation(6, $"User {dto.Username} has successfully reset password.");
await _signInManager.SignInAsync(user, true);
return Ok(await CreateResponse(user));
}
/// <summary>
/// Deletes current user and all their data
/// </summary>
/// <returns>LoginDTO</returns>
[HttpPost("delete")]
[Authorize]
public async Task<IActionResult> Delete()
{
var user = await _userManager.GetUserAsync(User);
await _signInManager.SignOutAsync();
var result = await _userManager.DeleteAsync(user);
if (result.Succeeded)
{
_logger.LogInformation(6, $"User {user.Email} has been removed.");
}
return Ok(await CreateResponse(null));
}
/// <summary>
/// Initiate a new session
/// </summary>
/// <returns>LoginDTO</returns>
[HttpGet("handshake")]
[AllowAnonymous]
public async Task<IActionResult> Handshake()
{
if (User.Identity?.IsAuthenticated ?? false)
{
var user = await _userManager.GetUserAsync(User);
return Ok(await CreateResponse(user));
}
return Ok(await CreateResponse(null));
}
}
} | rohatsu/tracktor | tracktor.app/Controllers/AccountController.cs | C# | apache-2.0 | 15,547 |
using System;
using System.Runtime.CompilerServices;
namespace De.Osthus.Ambeth.Mapping
{
public class CompositIdentityClassKey
{
private readonly Object entity;
private readonly Type type;
private int hash;
public CompositIdentityClassKey(Object entity, Type type)
{
this.entity = entity;
this.type = type;
hash = RuntimeHelpers.GetHashCode(entity) * 13;
if (type != null)
{
hash += type.GetHashCode() * 23;
}
}
public override bool Equals(Object obj)
{
if (!(obj is CompositIdentityClassKey))
{
return false;
}
CompositIdentityClassKey otherKey = (CompositIdentityClassKey)obj;
bool ee = entity == otherKey.entity;
bool te = type == otherKey.type;
return ee && te;
}
public override int GetHashCode()
{
return hash;
}
}
} | Dennis-Koch/ambeth | ambeth/Ambeth.Mapping/ambeth/mapping/CompositIdentityClassKey.cs | C# | apache-2.0 | 1,038 |
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package codeu.chat.client.core;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collection;
import codeu.chat.common.BasicView;
import codeu.chat.common.User;
import codeu.chat.util.Uuid;
import codeu.chat.util.connections.ConnectionSource;
public final class Context {
private final BasicView view;
private final Controller controller;
public Context(ConnectionSource source) {
this.view = new View(source);
this.controller = new Controller(source);
}
public UserContext create(String name) {
final User user = controller.newUser(name);
return user == null ?
null :
new UserContext(user, view, controller);
}
public Iterable<UserContext> allUsers() {
final Collection<UserContext> users = new ArrayList<>();
for (final User user : view.getUsers()) {
users.add(new UserContext(user, view, controller));
}
return users;
}
}
| crepric/codeu_mirrored_test_1 | src/codeu/chat/client/core/Context.java | Java | apache-2.0 | 1,510 |
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.2 generiert
// Siehe <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2020.03.13 um 12:48:52 PM CET
//
package net.opengis.ows._1;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
/**
* Complete reference to a remote or local resource, allowing including metadata about that resource.
*
* <p>Java-Klasse für ReferenceType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="ReferenceType">
* <complexContent>
* <extension base="{http://www.opengis.net/ows/1.1}AbstractReferenceBaseType">
* <sequence>
* <element ref="{http://www.opengis.net/ows/1.1}Identifier" minOccurs="0"/>
* <element ref="{http://www.opengis.net/ows/1.1}Abstract" maxOccurs="unbounded" minOccurs="0"/>
* <element name="Format" type="{http://www.opengis.net/ows/1.1}MimeType" minOccurs="0"/>
* <element ref="{http://www.opengis.net/ows/1.1}Metadata" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ReferenceType", propOrder = {
"identifier",
"_abstract",
"format",
"metadata"
})
@XmlSeeAlso({
ServiceReferenceType.class
})
public class ReferenceType
extends AbstractReferenceBaseType
{
@XmlElement(name = "Identifier")
protected CodeType identifier;
@XmlElement(name = "Abstract")
protected List<LanguageStringType> _abstract;
@XmlElement(name = "Format")
protected String format;
@XmlElement(name = "Metadata")
protected List<MetadataType> metadata;
/**
* Optional unique identifier of the referenced resource.
*
* @return
* possible object is
* {@link CodeType }
*
*/
public CodeType getIdentifier() {
return identifier;
}
/**
* Legt den Wert der identifier-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link CodeType }
*
*/
public void setIdentifier(CodeType value) {
this.identifier = value;
}
public boolean isSetIdentifier() {
return (this.identifier!= null);
}
/**
* Gets the value of the abstract property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the abstract property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAbstract().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link LanguageStringType }
*
*
*/
public List<LanguageStringType> getAbstract() {
if (_abstract == null) {
_abstract = new ArrayList<LanguageStringType>();
}
return this._abstract;
}
public boolean isSetAbstract() {
return ((this._abstract!= null)&&(!this._abstract.isEmpty()));
}
public void unsetAbstract() {
this._abstract = null;
}
/**
* Ruft den Wert der format-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFormat() {
return format;
}
/**
* Legt den Wert der format-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFormat(String value) {
this.format = value;
}
public boolean isSetFormat() {
return (this.format!= null);
}
/**
* Optional unordered list of additional metadata about this resource. A list of optional metadata elements for this ReferenceType could be specified in the Implementation Specification for each use of this type in a specific OWS. Gets the value of the metadata property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the metadata property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getMetadata().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link MetadataType }
*
*
*/
public List<MetadataType> getMetadata() {
if (metadata == null) {
metadata = new ArrayList<MetadataType>();
}
return this.metadata;
}
public boolean isSetMetadata() {
return ((this.metadata!= null)&&(!this.metadata.isEmpty()));
}
public void unsetMetadata() {
this.metadata = null;
}
public void setAbstract(List<LanguageStringType> value) {
this._abstract = value;
}
public void setMetadata(List<MetadataType> value) {
this.metadata = value;
}
}
| 3dcitydb/web-feature-service | src-gen/main/java/net/opengis/ows/_1/ReferenceType.java | Java | apache-2.0 | 5,813 |
package io.github.varvelworld.var.ioc.core.annotation.meta.factory;
import io.github.varvelworld.var.ioc.core.annotation.Resource;
import io.github.varvelworld.var.ioc.core.meta.ParamResourceMeta;
import io.github.varvelworld.var.ioc.core.meta.factory.ParamResourceMetaFactory;
import java.lang.reflect.Parameter;
/**
* Created by luzhonghao on 2016/12/4.
*/
public class AnnotationParamResourceMetaFactoryImpl implements ParamResourceMetaFactory {
private final ParamResourceMeta paramResourceMeta;
public AnnotationParamResourceMetaFactoryImpl(Parameter parameter) {
this(parameter, parameter.getAnnotation(Resource.class));
}
public AnnotationParamResourceMetaFactoryImpl(Parameter parameter, Resource annotation) {
String id = annotation.value();
if(id.isEmpty()) {
if(parameter.isNamePresent()){
id = parameter.getName();
}
else {
throw new RuntimeException("id is empty");
}
}
this.paramResourceMeta = new ParamResourceMeta(id);
}
@Override
public ParamResourceMeta paramResourceMeta() {
return paramResourceMeta;
}
}
| varvelworld/var-ioc | src/main/java/io/github/varvelworld/var/ioc/core/annotation/meta/factory/AnnotationParamResourceMetaFactoryImpl.java | Java | apache-2.0 | 1,193 |
package com.stf.bj.app.game.players;
import java.util.Random;
import com.stf.bj.app.game.bj.Spot;
import com.stf.bj.app.game.server.Event;
import com.stf.bj.app.game.server.EventType;
import com.stf.bj.app.settings.AppSettings;
import com.stf.bj.app.strategy.FullStrategy;
public class RealisticBot extends BasicBot {
private enum InsuranceStrategy {
NEVER, EVEN_MONEY_ONLY, GOOD_HANDS_ONLY, RARELY, OFTEN;
}
private enum PlayAbility {
PERFECT, NOOB, RANDOM;
}
private enum BetChanging {
NEVER, RANDOM;
}
private final InsuranceStrategy insuranceStrategy;
private final PlayAbility playAbility;
private final Random r;
private double wager = -1.0;
private final BetChanging betChanging;
private boolean insurancePlay = false;
private boolean calculatedInsurancePlay = false;
private boolean messUpNextPlay = false;
public RealisticBot(AppSettings settings, FullStrategy strategy, Random r, Spot s) {
super(settings, strategy, r, s);
if (r == null) {
r = new Random(System.currentTimeMillis());
}
this.r = r;
insuranceStrategy = InsuranceStrategy.values()[r.nextInt(InsuranceStrategy.values().length)];
playAbility = PlayAbility.values()[r.nextInt(PlayAbility.values().length)];
setBaseBet();
betChanging = BetChanging.RANDOM;
}
@Override
public void sendEvent(Event e) {
super.sendEvent(e);
if (e.getType() == EventType.DECK_SHUFFLED) {
if (betChanging == BetChanging.RANDOM && r.nextInt(2) == 0) {
wager = 5;
}
}
}
@Override
public double getWager() {
if (delay > 0) {
delay--;
return -1;
}
return wager;
}
private void setBaseBet() {
int rInt = r.nextInt(12);
if (rInt < 6) {
wager = 5.0 * (1 + rInt);
} else if (rInt < 9) {
wager = 10.0;
} else {
wager = 5.0;
}
}
@Override
public boolean getInsurancePlay() {
if (insuranceStrategy == InsuranceStrategy.NEVER) {
return false;
}
if (!calculatedInsurancePlay) {
insurancePlay = calculateInsurancePlay();
calculatedInsurancePlay = true;
}
return insurancePlay;
}
private boolean calculateInsurancePlay() {
switch (insuranceStrategy) {
case EVEN_MONEY_ONLY:
return getHandSoftTotal(0) == 21;
case GOOD_HANDS_ONLY:
return getHandSoftTotal(0) > 16 + r.nextInt(3);
case OFTEN:
return r.nextInt(2) == 0;
case RARELY:
return r.nextInt(5) == 0;
default:
throw new IllegalStateException();
}
}
@Override
public Play getMove(int handIndex, boolean canDouble, boolean canSplit, boolean canSurrender) {
if (delay > 0) {
delay--;
return null;
}
Play play = super.getMove(handIndex, canDouble, canSplit, canSurrender);
if (messUpNextPlay) {
if (play != Play.SPLIT && canSplit) {
play = Play.SPLIT;
} else if (play != Play.DOUBLEDOWN && canSplit) {
play = Play.DOUBLEDOWN;
} else if (play == Play.STAND) {
play = Play.HIT;
} else {
play = Play.STAND;
}
}
return play;
}
@Override
protected void reset() {
super.reset();
calculatedInsurancePlay = false;
int random = r.nextInt(10);
if (playAbility == PlayAbility.RANDOM) {
messUpNextPlay = (random < 2);
}
if ((random == 2 || random == 3) && betChanging == BetChanging.RANDOM) {
wager += 5;
} else if (random == 4 && betChanging == BetChanging.RANDOM) {
if (wager > 6) {
wager -= 5;
}
}
}
}
| Boxxy/Blackjack | core/src/com/stf/bj/app/game/players/RealisticBot.java | Java | apache-2.0 | 3,337 |
package me.marcosassuncao.servsim.job;
import me.marcosassuncao.servsim.profile.RangeList;
import com.google.common.base.MoreObjects;
/**
* {@link Reservation} represents a resource reservation request
* made by a customer to reserve a given number of resources
* from a provider.
*
* @see WorkUnit
* @see DefaultWorkUnit
*
* @author Marcos Dias de Assuncao
*/
public class Reservation extends DefaultWorkUnit {
private long reqStartTime = WorkUnit.TIME_NOT_SET;
private RangeList rangeList;
/**
* Creates a reservation request to start at
* <code>startTime</code> and with the given duration.
* @param startTime the requested start time for the reservation
* @param duration the duration of the reservation
* @param numResources number of required resources
*/
public Reservation(long startTime,
long duration, int numResources) {
super(duration);
super.setNumReqResources(numResources);
this.reqStartTime = startTime;
}
/**
* Creates a reservation request to start at
* <code>startTime</code> and with the given duration and priority
* @param startTime the requested start time for the reservation
* @param duration the duration of the reservation
* @param numResources the number of resources to be reserved
* @param priority the reservation priority
*/
public Reservation(long startTime,
long duration, int numResources, int priority) {
super(duration, priority);
super.setNumReqResources(numResources);
this.reqStartTime = startTime;
}
/**
* Returns the start time requested by this reservation
* @return the requested start time
*/
public long getRequestedStartTime() {
return reqStartTime;
}
/**
* Sets the ranges of reserved resources
* @param ranges the ranges of resources allocated for the reservation
* @return <code>true</code> if the ranges have been set correctly,
* <code>false</code> otherwise.
*/
public boolean setResourceRanges(RangeList ranges) {
if (this.rangeList != null) {
return false;
}
this.rangeList = ranges;
return true;
}
/**
* Gets the ranges of reserved resources
* @return the ranges of reserved resources
*/
public RangeList getResourceRanges() {
return rangeList;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("id", getId())
.add("submission time", getSubmitTime())
.add("start time", getStartTime())
.add("finish time", getFinishTime())
.add("duration", getDuration())
.add("priority", getPriority())
.add("status", getStatus())
.add("resources", rangeList)
.toString();
}
} | assuncaomarcos/servsim | src/main/java/me/marcosassuncao/servsim/job/Reservation.java | Java | apache-2.0 | 2,646 |
/*
* Copyright (c) 2016, baihw (javakf@163.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 com.yoya.rdf.router;
/**
* Created by baihw on 16-6-13.
*
* 统一的服务请求处理器规范接口,此接口用于标识类文件为请求处理器实现类,无必须实现的方法。
*
* 实现类中所有符合public void xxx( IRequest request, IResponse response )签名规则的方法都将被自动注册到对应的请求处理器中。
*
* 如下所示:
*
* public void login( IRequest request, IResponse response ){};
*
* public void logout( IRequest request, IResponse response ){} ;
*
* 上边的login, logout将被自动注册到请求处理器路径中。
*
* 假如类名为LoginHnadler, 则注册的处理路径为:/Loginhandler/login, /Loginhandler/logout.
*
* 注意:大小写敏感。
*
*/
public interface IRequestHandler{
/**
* 当请求中没有明确指定处理方法时,默认执行的请求处理方法。
*
* @param request 请求对象
* @param response 响应对象
*/
void handle( IRequest request, IResponse response );
} // end class
| javakf/rdf | src/main/java/com/yoya/rdf/router/IRequestHandler.java | Java | apache-2.0 | 1,692 |
(function() {
'use strict';
angular
.module('sentryApp')
.controller('TimeFrameController', TimeFrameController);
TimeFrameController.$inject = ['$scope', '$state', 'TimeFrame', 'ParseLinks', 'AlertService', 'paginationConstants', 'pagingParams'];
function TimeFrameController ($scope, $state, TimeFrame, ParseLinks, AlertService, paginationConstants, pagingParams) {
var vm = this;
vm.loadPage = loadPage;
vm.predicate = pagingParams.predicate;
vm.reverse = pagingParams.ascending;
vm.transition = transition;
vm.itemsPerPage = paginationConstants.itemsPerPage;
loadAll();
function loadAll () {
TimeFrame.query({
page: pagingParams.page - 1,
size: vm.itemsPerPage,
sort: sort()
}, onSuccess, onError);
function sort() {
var result = [vm.predicate + ',' + (vm.reverse ? 'asc' : 'desc')];
if (vm.predicate !== 'id') {
result.push('id');
}
return result;
}
function onSuccess(data, headers) {
vm.links = ParseLinks.parse(headers('link'));
vm.totalItems = headers('X-Total-Count');
vm.queryCount = vm.totalItems;
vm.timeFrames = data;
vm.page = pagingParams.page;
}
function onError(error) {
AlertService.error(error.data.message);
}
}
function loadPage(page) {
vm.page = page;
vm.transition();
}
function transition() {
$state.transitionTo($state.$current, {
page: vm.page,
sort: vm.predicate + ',' + (vm.reverse ? 'asc' : 'desc'),
search: vm.currentSearch
});
}
}
})();
| quanticc/sentry | src/main/webapp/app/entities/time-frame/time-frame.controller.js | JavaScript | apache-2.0 | 1,937 |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.Cpu_usage;
import de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.Sys_info_systeminfoPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Cpu usage</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getEContainer_cpu_usage <em>EContainer cpu usage</em>}</li>
* <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getReal <em>Real</em>}</li>
* <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getUser <em>User</em>}</li>
* <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getSys <em>Sys</em>}</li>
* <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getUnit <em>Unit</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class Cpu_usageImpl extends EObjectImpl implements Cpu_usage {
/**
* The default value of the '{@link #getReal() <em>Real</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getReal()
* @generated
* @ordered
*/
protected static final double REAL_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getReal() <em>Real</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getReal()
* @generated
* @ordered
*/
protected double real = REAL_EDEFAULT;
/**
* The default value of the '{@link #getUser() <em>User</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getUser()
* @generated
* @ordered
*/
protected static final double USER_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getUser() <em>User</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getUser()
* @generated
* @ordered
*/
protected double user = USER_EDEFAULT;
/**
* The default value of the '{@link #getSys() <em>Sys</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSys()
* @generated
* @ordered
*/
protected static final double SYS_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getSys() <em>Sys</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSys()
* @generated
* @ordered
*/
protected double sys = SYS_EDEFAULT;
/**
* The default value of the '{@link #getUnit() <em>Unit</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getUnit()
* @generated
* @ordered
*/
protected static final String UNIT_EDEFAULT = null;
/**
* The cached value of the '{@link #getUnit() <em>Unit</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getUnit()
* @generated
* @ordered
*/
protected String unit = UNIT_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Cpu_usageImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Sys_info_systeminfoPackage.Literals.CPU_USAGE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System getEContainer_cpu_usage() {
if (eContainerFeatureID() != Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE) return null;
return (de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System)eContainer();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetEContainer_cpu_usage(de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System newEContainer_cpu_usage, NotificationChain msgs) {
msgs = eBasicSetContainer((InternalEObject)newEContainer_cpu_usage, Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE, msgs);
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setEContainer_cpu_usage(de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System newEContainer_cpu_usage) {
if (newEContainer_cpu_usage != eInternalContainer() || (eContainerFeatureID() != Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE && newEContainer_cpu_usage != null)) {
if (EcoreUtil.isAncestor(this, newEContainer_cpu_usage))
throw new IllegalArgumentException("Recursive containment not allowed for " + toString());
NotificationChain msgs = null;
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
if (newEContainer_cpu_usage != null)
msgs = ((InternalEObject)newEContainer_cpu_usage).eInverseAdd(this, Sys_info_systeminfoPackage.SYSTEM__CPU_USAGE, de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System.class, msgs);
msgs = basicSetEContainer_cpu_usage(newEContainer_cpu_usage, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE, newEContainer_cpu_usage, newEContainer_cpu_usage));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getReal() {
return real;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setReal(double newReal) {
double oldReal = real;
real = newReal;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__REAL, oldReal, real));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getUser() {
return user;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setUser(double newUser) {
double oldUser = user;
user = newUser;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__USER, oldUser, user));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getSys() {
return sys;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setSys(double newSys) {
double oldSys = sys;
sys = newSys;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__SYS, oldSys, sys));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getUnit() {
return unit;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setUnit(String newUnit) {
String oldUnit = unit;
unit = newUnit;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__UNIT, oldUnit, unit));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE:
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
return basicSetEContainer_cpu_usage((de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System)otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE:
return basicSetEContainer_cpu_usage(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) {
switch (eContainerFeatureID()) {
case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE:
return eInternalContainer().eInverseRemove(this, Sys_info_systeminfoPackage.SYSTEM__CPU_USAGE, de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System.class, msgs);
}
return super.eBasicRemoveFromContainerFeature(msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE:
return getEContainer_cpu_usage();
case Sys_info_systeminfoPackage.CPU_USAGE__REAL:
return getReal();
case Sys_info_systeminfoPackage.CPU_USAGE__USER:
return getUser();
case Sys_info_systeminfoPackage.CPU_USAGE__SYS:
return getSys();
case Sys_info_systeminfoPackage.CPU_USAGE__UNIT:
return getUnit();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE:
setEContainer_cpu_usage((de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System)newValue);
return;
case Sys_info_systeminfoPackage.CPU_USAGE__REAL:
setReal((Double)newValue);
return;
case Sys_info_systeminfoPackage.CPU_USAGE__USER:
setUser((Double)newValue);
return;
case Sys_info_systeminfoPackage.CPU_USAGE__SYS:
setSys((Double)newValue);
return;
case Sys_info_systeminfoPackage.CPU_USAGE__UNIT:
setUnit((String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE:
setEContainer_cpu_usage((de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System)null);
return;
case Sys_info_systeminfoPackage.CPU_USAGE__REAL:
setReal(REAL_EDEFAULT);
return;
case Sys_info_systeminfoPackage.CPU_USAGE__USER:
setUser(USER_EDEFAULT);
return;
case Sys_info_systeminfoPackage.CPU_USAGE__SYS:
setSys(SYS_EDEFAULT);
return;
case Sys_info_systeminfoPackage.CPU_USAGE__UNIT:
setUnit(UNIT_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE:
return getEContainer_cpu_usage() != null;
case Sys_info_systeminfoPackage.CPU_USAGE__REAL:
return real != REAL_EDEFAULT;
case Sys_info_systeminfoPackage.CPU_USAGE__USER:
return user != USER_EDEFAULT;
case Sys_info_systeminfoPackage.CPU_USAGE__SYS:
return sys != SYS_EDEFAULT;
case Sys_info_systeminfoPackage.CPU_USAGE__UNIT:
return UNIT_EDEFAULT == null ? unit != null : !UNIT_EDEFAULT.equals(unit);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (real: ");
result.append(real);
result.append(", user: ");
result.append(user);
result.append(", sys: ");
result.append(sys);
result.append(", unit: ");
result.append(unit);
result.append(')');
return result.toString();
}
} //Cpu_usageImpl
| markus1978/clickwatch | analysis/de.hub.clickwatch.specificmodels.brn/src/de/hub/clickwatch/specificmodels/brn/sys_info_systeminfo/impl/Cpu_usageImpl.java | Java | apache-2.0 | 14,073 |
#include "pmlc/dialect/pxa/analysis/affine_expr.h"
namespace mlir {
AffineValueExpr::AffineValueExpr(AffineExpr expr, ValueRange operands)
: expr(expr), operands(operands.begin(), operands.end()) {}
AffineValueExpr::AffineValueExpr(MLIRContext *ctx, int64_t v) {
expr = getAffineConstantExpr(v, ctx);
}
AffineValueExpr::AffineValueExpr(Value v) {
operands.push_back(v);
expr = getAffineDimExpr(0, v.getContext());
}
AffineValueExpr::AffineValueExpr(AffineValueMap map, unsigned idx)
: expr(map.getResult(idx)),
operands(map.getOperands().begin(), map.getOperands().end()) {}
AffineValueExpr AffineValueExpr::operator*(const AffineValueExpr &rhs) const {
return AffineValueExpr(AffineExprKind::Mul, *this, rhs);
}
AffineValueExpr AffineValueExpr::operator*(int64_t rhs) const {
auto cst = AffineValueExpr(expr.getContext(), rhs);
return AffineValueExpr(AffineExprKind::Mul, *this, cst);
}
AffineValueExpr AffineValueExpr::operator+(const AffineValueExpr &rhs) const {
return AffineValueExpr(AffineExprKind::Add, *this, rhs);
}
AffineValueExpr AffineValueExpr::operator+(int64_t rhs) const {
auto cst = AffineValueExpr(expr.getContext(), rhs);
return AffineValueExpr(AffineExprKind::Add, *this, cst);
}
AffineValueExpr AffineValueExpr::operator-(const AffineValueExpr &rhs) const {
return *this + (rhs * -1);
}
AffineValueExpr AffineValueExpr::operator-(int64_t rhs) const {
return *this - AffineValueExpr(expr.getContext(), rhs);
}
AffineExpr AffineValueExpr::getExpr() const { return expr; }
ArrayRef<Value> AffineValueExpr::getOperands() const { return operands; }
AffineValueExpr::AffineValueExpr(AffineExprKind kind, AffineValueExpr a,
AffineValueExpr b)
: operands(a.operands.begin(), a.operands.end()) {
SmallVector<AffineExpr, 4> repl_b;
for (auto v : b.operands) {
auto it = std::find(operands.begin(), operands.end(), v);
unsigned idx;
if (it == operands.end()) {
idx = operands.size();
operands.push_back(v);
} else {
idx = it - operands.begin();
}
repl_b.push_back(getAffineDimExpr(idx, a.expr.getContext()));
}
auto new_b = b.expr.replaceDimsAndSymbols(repl_b, {});
expr = getAffineBinaryOpExpr(kind, a.expr, new_b);
}
AffineValueMap jointValueMap(MLIRContext *ctx,
ArrayRef<AffineValueExpr> exprs) {
DenseMap<Value, unsigned> jointSpace;
for (const auto &expr : exprs) {
for (Value v : expr.getOperands()) {
if (!jointSpace.count(v)) {
unsigned idx = jointSpace.size();
jointSpace[v] = idx;
}
}
}
SmallVector<AffineExpr, 4> jointExprs;
for (const auto &expr : exprs) {
SmallVector<AffineExpr, 4> repl;
for (Value v : expr.getOperands()) {
repl.push_back(getAffineDimExpr(jointSpace[v], ctx));
}
jointExprs.push_back(expr.getExpr().replaceDimsAndSymbols(repl, {}));
}
SmallVector<Value, 4> jointOperands(jointSpace.size());
for (const auto &kvp : jointSpace) {
jointOperands[kvp.second] = kvp.first;
}
auto map = AffineMap::get(jointSpace.size(), 0, jointExprs, ctx);
return AffineValueMap(map, jointOperands);
}
} // End namespace mlir
| plaidml/plaidml | pmlc/dialect/pxa/analysis/affine_expr.cc | C++ | apache-2.0 | 3,202 |
/**
*
* Copyright 2016 David Strawn
*
* 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 strawn.longleaf.relay.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
*
* @author David Strawn
*
* This class loads configuration from the file system.
*
*/
public class RelayConfigLoader {
private static final String serverConfigLocation = "./resources/serverconfig.properties";
private static final String clientConfigLocation = "./resources/clientconfig.properties";
private final Properties properties;
public RelayConfigLoader() {
properties = new Properties();
}
public void loadServerConfig() throws IOException {
loadConfigFromPath(serverConfigLocation);
}
public void loadClientConfig() throws IOException {
loadConfigFromPath(clientConfigLocation);
}
/**
* Use this method if you want to use a different location for the configuration.
* @param configFileLocation - location of the configuration file
* @throws IOException
*/
public void loadConfigFromPath(String configFileLocation) throws IOException {
FileInputStream fileInputStream = new FileInputStream(configFileLocation);
properties.load(fileInputStream);
fileInputStream.close();
}
public int getPort() {
return Integer.parseInt(properties.getProperty("port"));
}
public String getHost() {
return properties.getProperty("host");
}
}
| strontian/longleaf-relay | src/main/java/strawn/longleaf/relay/util/RelayConfigLoader.java | Java | apache-2.0 | 2,074 |
// Modifications copyright (C) 2017, Baidu.com, Inc.
// Copyright 2017 The Apache Software Foundation
// 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 "util/palo_metrics.h"
#include "util/debug_util.h"
namespace palo {
// Naming convention: Components should be separated by '.' and words should
// be separated by '-'.
const char* PALO_BE_START_TIME = "palo_be.start_time";
const char* PALO_BE_VERSION = "palo_be.version";
const char* PALO_BE_READY = "palo_be.ready";
const char* PALO_BE_NUM_FRAGMENTS = "palo_be.num_fragments";
const char* TOTAL_SCAN_RANGES_PROCESSED = "palo_be.scan_ranges.total";
const char* NUM_SCAN_RANGES_MISSING_VOLUME_ID = "palo_be.scan_ranges.num_missing_volume_id";
const char* MEM_POOL_TOTAL_BYTES = "palo_be.mem_pool.total_bytes";
const char* HASH_TABLE_TOTAL_BYTES = "palo_be.hash_table.total_bytes";
const char* OLAP_LRU_CACHE_LOOKUP_COUNT = "palo_be.olap.lru_cache.lookup_count";
const char* OLAP_LRU_CACHE_HIT_COUNT = "palo_be.olap.lru_cache.hit_count";
const char* PALO_PUSH_COUNT = "palo_be.olap.push_count";
const char* PALO_FETCH_COUNT = "palo_be.olap.fetch_count";
const char* PALO_REQUEST_COUNT = "palo_be.olap.request_count";
const char* BE_MERGE_DELTA_NUM = "palo_be.olap.be_merge.delta_num";
const char* BE_MERGE_SIZE = "palo_be.olap.be_merge_size";
const char* CE_MERGE_DELTA_NUM = "palo_be.olap.ce_merge.delta_num";
const char* CE_MERGE_SIZE = "palo_be.olap.ce_merge_size";
const char* IO_MGR_NUM_BUFFERS = "palo_be.io_mgr.num_buffers";
const char* IO_MGR_NUM_OPEN_FILES = "palo_be.io_mgr.num_open_files";
const char* IO_MGR_NUM_UNUSED_BUFFERS = "palo_be.io_mgr.num_unused_buffers";
// const char* IO_MGR_NUM_CACHED_FILE_HANDLES = "palo_be.io_mgr_num_cached_file_handles";
const char* IO_MGR_NUM_FILE_HANDLES_OUTSTANDING = "palo_be.io_mgr.num_file_handles_outstanding";
// const char* IO_MGR_CACHED_FILE_HANDLES_HIT_COUNT = "palo_be.io_mgr_cached_file_handles_hit_count";
// const char* IO_MGR_CACHED_FILE_HANDLES_MISS_COUNT = "palo_be.io_mgr_cached_file_handles_miss_count";
const char* IO_MGR_TOTAL_BYTES = "palo_be.io_mgr.total_bytes";
// const char* IO_MGR_BYTES_READ = "palo_be.io_mgr_bytes_read";
// const char* IO_MGR_LOCAL_BYTES_READ = "palo_be.io_mgr_local_bytes_read";
// const char* IO_MGR_CACHED_BYTES_READ = "palo_be.io_mgr_cached_bytes_read";
// const char* IO_MGR_SHORT_CIRCUIT_BYTES_READ = "palo_be.io_mgr_short_circuit_bytes_read";
const char* IO_MGR_BYTES_WRITTEN = "palo_be.io_mgr.bytes_written";
const char* NUM_QUERIES_SPILLED = "palo_be.num_queries_spilled";
// These are created by palo_be during startup.
StringProperty* PaloMetrics::_s_palo_be_start_time = NULL;
StringProperty* PaloMetrics::_s_palo_be_version = NULL;
BooleanProperty* PaloMetrics::_s_palo_be_ready = NULL;
IntCounter* PaloMetrics::_s_palo_be_num_fragments = NULL;
IntCounter* PaloMetrics::_s_num_ranges_processed = NULL;
IntCounter* PaloMetrics::_s_num_ranges_missing_volume_id = NULL;
IntGauge* PaloMetrics::_s_mem_pool_total_bytes = NULL;
IntGauge* PaloMetrics::_s_hash_table_total_bytes = NULL;
IntCounter* PaloMetrics::_s_olap_lru_cache_lookup_count = NULL;
IntCounter* PaloMetrics::_s_olap_lru_cache_hit_count = NULL;
IntCounter* PaloMetrics::_s_palo_push_count = NULL;
IntCounter* PaloMetrics::_s_palo_fetch_count = NULL;
IntCounter* PaloMetrics::_s_palo_request_count = NULL;
IntCounter* PaloMetrics::_s_be_merge_delta_num = NULL;
IntCounter* PaloMetrics::_s_be_merge_size = NULL;
IntCounter* PaloMetrics::_s_ce_merge_delta_num = NULL;
IntCounter* PaloMetrics::_s_ce_merge_size = NULL;
IntGauge* PaloMetrics::_s_io_mgr_num_buffers = NULL;
IntGauge* PaloMetrics::_s_io_mgr_num_open_files = NULL;
IntGauge* PaloMetrics::_s_io_mgr_num_unused_buffers = NULL;
// IntGauge* PaloMetrics::_s_io_mgr_num_cached_file_handles = NULL;
IntGauge* PaloMetrics::_s_io_mgr_num_file_handles_outstanding = NULL;
// IntGauge* PaloMetrics::_s_io_mgr_cached_file_handles_hit_count = NULL;
// IntGauge* PaloMetrics::_s_io_mgr_cached_file_handles_miss_count = NULL;
IntGauge* PaloMetrics::_s_io_mgr_total_bytes = NULL;
// IntGauge* PaloMetrics::_s_io_mgr_bytes_read = NULL;
// IntGauge* PaloMetrics::_s_io_mgr_local_bytes_read = NULL;
// IntGauge* PaloMetrics::_s_io_mgr_cached_bytes_read = NULL;
// IntGauge* PaloMetrics::_s_io_mgr_short_circuit_bytes_read = NULL;
IntCounter* PaloMetrics::_s_io_mgr_bytes_written = NULL;
IntCounter* PaloMetrics::_s_num_queries_spilled = NULL;
void PaloMetrics::create_metrics(MetricGroup* m) {
// Initialize impalad metrics
_s_palo_be_start_time = m->AddProperty<std::string>(
PALO_BE_START_TIME, "");
_s_palo_be_version = m->AddProperty<std::string>(
PALO_BE_VERSION, get_version_string(true));
_s_palo_be_ready = m->AddProperty(PALO_BE_READY, false);
_s_palo_be_num_fragments = m->AddCounter(PALO_BE_NUM_FRAGMENTS, 0L);
// Initialize scan node metrics
_s_num_ranges_processed = m->AddCounter(TOTAL_SCAN_RANGES_PROCESSED, 0L);
_s_num_ranges_missing_volume_id = m->AddCounter(NUM_SCAN_RANGES_MISSING_VOLUME_ID, 0L);
// Initialize memory usage metrics
_s_mem_pool_total_bytes = m->AddGauge(MEM_POOL_TOTAL_BYTES, 0L);
_s_hash_table_total_bytes = m->AddGauge(HASH_TABLE_TOTAL_BYTES, 0L);
// Initialize olap metrics
_s_olap_lru_cache_lookup_count = m->AddCounter(OLAP_LRU_CACHE_LOOKUP_COUNT, 0L);
_s_olap_lru_cache_hit_count = m->AddCounter(OLAP_LRU_CACHE_HIT_COUNT, 0L);
// Initialize push_count, fetch_count, request_count metrics
_s_palo_push_count = m->AddCounter(PALO_PUSH_COUNT, 0L);
_s_palo_fetch_count = m->AddCounter(PALO_FETCH_COUNT, 0L);
_s_palo_request_count = m->AddCounter(PALO_REQUEST_COUNT, 0L);
// Initialize be/ce merge metrics
_s_be_merge_delta_num = m->AddCounter(BE_MERGE_DELTA_NUM, 0L);
_s_be_merge_size = m->AddCounter(BE_MERGE_SIZE, 0L);
_s_ce_merge_delta_num = m->AddCounter(CE_MERGE_DELTA_NUM, 0L);
_s_ce_merge_size = m->AddCounter(CE_MERGE_SIZE, 0L);
// Initialize metrics relate to spilling to disk
// _s_io_mgr_bytes_read
// = m->AddGauge(IO_MGR_BYTES_READ, 0L);
// _s_io_mgr_local_bytes_read
// = m->AddGauge(IO_MGR_LOCAL_BYTES_READ, 0L);
// _s_io_mgr_cached_bytes_read
// = m->AddGauge(IO_MGR_CACHED_BYTES_READ, 0L);
// _s_io_mgr_short_circuit_bytes_read
// = m->AddGauge(IO_MGR_SHORT_CIRCUIT_BYTES_READ, 0L);
_s_io_mgr_bytes_written = m->AddCounter(IO_MGR_BYTES_WRITTEN, 0L);
_s_io_mgr_num_buffers
= m->AddGauge(IO_MGR_NUM_BUFFERS, 0L);
_s_io_mgr_num_open_files
= m->AddGauge(IO_MGR_NUM_OPEN_FILES, 0L);
_s_io_mgr_num_unused_buffers
= m->AddGauge(IO_MGR_NUM_UNUSED_BUFFERS, 0L);
_s_io_mgr_num_file_handles_outstanding
= m->AddGauge(IO_MGR_NUM_FILE_HANDLES_OUTSTANDING, 0L);
_s_io_mgr_total_bytes
= m->AddGauge(IO_MGR_TOTAL_BYTES, 0L);
_s_num_queries_spilled = m->AddCounter(NUM_QUERIES_SPILLED, 0L);
}
}
| lingbin/palo | be/src/util/palo_metrics.cpp | C++ | apache-2.0 | 7,788 |
package leetcode.reverse_linked_list_ii;
import common.ListNode;
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head == null) return null;
ListNode curRight = head;
for(int len = 0; len < n - m; len++){
curRight = curRight.next;
}
ListNode prevLeft = null;
ListNode curLeft = head;
for(int len = 0; len < m - 1; len++){
prevLeft = curLeft;
curLeft = curLeft.next;
curRight = curRight.next;
}
if(prevLeft == null){
head = curRight;
}else{
prevLeft.next = curRight;
}
for(int len = 0; len < n - m; len++){
ListNode next = curLeft.next;
curLeft.next = curRight.next;
curRight.next = curLeft;
curLeft = next;
}
return head;
}
public static void dump(ListNode node){
while(node != null){
System.err.print(node.val + "->");
node = node.next;
}
System.err.println("null");
}
public static void main(String[] args){
final int N = 10;
ListNode[] list = new ListNode[N];
for(int m = 1; m <= N; m++){
for(int n = m; n <= N; n++){
for(int i = 0; i < N; i++){
list[i] = new ListNode(i);
if(i > 0) list[i - 1].next = list[i];
}
dump(new Solution().reverseBetween(list[0], m, n));
}
}
}
}
| ckclark/leetcode | java/leetcode/reverse_linked_list_ii/Solution.java | Java | apache-2.0 | 1,378 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.giraph.examples.io.formats;
import com.google.common.collect.Lists;
import org.apache.giraph.edge.Edge;
import org.apache.giraph.edge.EdgeFactory;
import org.apache.giraph.examples.utils.BrachaTouegDeadlockVertexValue;
import org.apache.giraph.graph.Vertex;
import org.apache.giraph.io.formats.TextVertexInputFormat;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
import java.util.List;
/**
* VertexInputFormat for the Bracha Toueg Deadlock Detection algorithm
* specified in JSON format.
*/
public class LongLongLongLongVertexInputFormat extends
TextVertexInputFormat<LongWritable, LongWritable,
LongWritable> {
@Override
public TextVertexReader createVertexReader(InputSplit split,
TaskAttemptContext context) {
return new JsonLongLongLongLongVertexReader();
}
/**
* VertexReader use for the Bracha Toueg Deadlock Detection Algorithm.
* The files should be in the following JSON format:
* JSONArray(<vertex id>,
* JSONArray(JSONArray(<dest vertex id>, <edge tag>), ...))
* The tag is use for the N-out-of-M semantics. Two edges with the same tag
* are considered to be combined and, hence, represent to combined requests
* that need to be both satisfied to continue execution.
* Here is an example with vertex id 1, and three edges (requests).
* First edge has a destination vertex 2 with tag 0.
* Second and third edge have a destination vertex respectively of 3 and 4
* with tag 1.
* [1,[[2,0], [3,1], [4,1]]]
*/
class JsonLongLongLongLongVertexReader
extends TextVertexReaderFromEachLineProcessedHandlingExceptions<JSONArray,
JSONException> {
@Override
protected JSONArray preprocessLine(Text line) throws JSONException {
return new JSONArray(line.toString());
}
@Override
protected LongWritable getId(JSONArray jsonVertex) throws JSONException,
IOException {
return new LongWritable(jsonVertex.getLong(0));
}
@Override
protected LongWritable getValue(JSONArray jsonVertex)
throws JSONException, IOException {
return new LongWritable();
}
@Override
protected Iterable<Edge<LongWritable, LongWritable>>
getEdges(JSONArray jsonVertex) throws JSONException, IOException {
JSONArray jsonEdgeArray = jsonVertex.getJSONArray(1);
/* get the edges */
List<Edge<LongWritable, LongWritable>> edges =
Lists.newArrayListWithCapacity(jsonEdgeArray.length());
for (int i = 0; i < jsonEdgeArray.length(); ++i) {
LongWritable targetId;
LongWritable tag;
JSONArray jsonEdge = jsonEdgeArray.getJSONArray(i);
targetId = new LongWritable(jsonEdge.getLong(0));
tag = new LongWritable((long) jsonEdge.getLong(1));
edges.add(EdgeFactory.create(targetId, tag));
}
return edges;
}
@Override
protected Vertex<LongWritable, LongWritable,
LongWritable> handleException(Text line, JSONArray jsonVertex,
JSONException e) {
throw new IllegalArgumentException(
"Couldn't get vertex from line " + line, e);
}
}
}
| KidEinstein/giraph | giraph-examples/src/main/java/org/apache/giraph/examples/io/formats/LongLongLongLongVertexInputFormat.java | Java | apache-2.0 | 4,147 |
//============================================================================
//
// Copyright (C) 2006-2022 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
//============================================================================
package org.talend.components.google.drive.connection;
import java.util.EnumSet;
import java.util.Set;
import org.talend.components.api.component.ConnectorTopology;
import org.talend.components.api.component.runtime.ExecutionEngine;
import org.talend.components.api.properties.ComponentProperties;
import org.talend.components.google.drive.GoogleDriveComponentDefinition;
import org.talend.daikon.runtime.RuntimeInfo;
public class GoogleDriveConnectionDefinition extends GoogleDriveComponentDefinition {
public static final String COMPONENT_NAME = "tGoogleDriveConnection"; //$NON-NLS-1$
public GoogleDriveConnectionDefinition() {
super(COMPONENT_NAME);
}
@Override
public Class<? extends ComponentProperties> getPropertyClass() {
return GoogleDriveConnectionProperties.class;
}
@Override
public Set<ConnectorTopology> getSupportedConnectorTopologies() {
return EnumSet.of(ConnectorTopology.NONE);
}
@Override
public RuntimeInfo getRuntimeInfo(ExecutionEngine engine, ComponentProperties properties,
ConnectorTopology connectorTopology) {
assertEngineCompatibility(engine);
assertConnectorTopologyCompatibility(connectorTopology);
return getRuntimeInfo(GoogleDriveConnectionDefinition.SOURCE_OR_SINK_CLASS);
}
@Override
public boolean isStartable() {
return true;
}
}
| Talend/components | components/components-googledrive/components-googledrive-definition/src/main/java/org/talend/components/google/drive/connection/GoogleDriveConnectionDefinition.java | Java | apache-2.0 | 1,926 |
import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { InAppBrowser } from '@ionic-native/in-app-browser';
@Component({
selector: 'page-apuntes',
templateUrl: 'apuntes.html'
})
export class ApuntesPage {
constructor(public platform: Platform, private theInAppBrowser: InAppBrowser){}
launch() {
this.platform.ready().then(() => {
this.theInAppBrowser.create("http://apuntes.lafuenteunlp.com.ar", '_self', 'location=yes');
});
}
/*
ionViewDidLoad() {
this.confData.getMap().subscribe((mapData: any) => {
let mapEle = this.mapElement.nativeElement;
let map = new google.maps.Map(mapEle, {
center: mapData.find((d: any) => d.center),
zoom: 16
});
mapData.forEach((markerData: any) => {
let infoWindow = new google.maps.InfoWindow({
content: `<h5>${markerData.name}</h5>`
});
let marker = new google.maps.Marker({
position: markerData,
map: map,
title: markerData.name
});
marker.addListener('click', () => {
infoWindow.open(map, marker);
});
});
google.maps.event.addListenerOnce(map, 'idle', () => {
mapEle.classList.add('show-map');
});
});
}
*/
}
| tomibarbieri/lafuente | src/pages/apuntes/apuntes.ts | TypeScript | apache-2.0 | 1,350 |
/*price range*/
$('#sl2').slider();
var RGBChange = function() {
$('#RGB').css('background', 'rgb('+r.getValue()+','+g.getValue()+','+b.getValue()+')')
};
/*scroll to top*/
$(document).ready(function(){
$(function () {
$.scrollUp({
scrollName: 'scrollUp', // Element ID
scrollDistance: 300, // Distance from top/bottom before showing element (px)
scrollFrom: 'top', // 'top' or 'bottom'
scrollSpeed: 300, // Speed back to top (ms)
easingType: 'linear', // Scroll to top easing (see http://easings.net/)
animation: 'fade', // Fade, slide, none
animationSpeed: 200, // Animation in speed (ms)
scrollTrigger: false, // Set a custom triggering element. Can be an HTML string or jQuery object
//scrollTarget: false, // Set a custom target element for scrolling to the top
scrollText: '<i class="fa fa-angle-up"></i>', // Text for element, can contain HTML
scrollTitle: false, // Set a custom <a> title if required.
scrollImg: false, // Set true to use image
activeOverlay: false, // Set CSS color to display scrollUp active point, e.g '#00FFFF'
zIndex: 2147483647 // Z-Index for the overlay
});
});
});
// Returns a random integer between min and max
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Replace url parameter - WishlistItems
function replaceUrlParam(url, paramName, paramValue) {
var pattern = new RegExp('(' + paramName + '=).*?(&|$)')
var newUrl = url
if (url.search(pattern) >= 0) {
newUrl = url.replace(pattern, '$1' + paramValue + '$2');
}
else {
newUrl = newUrl + (newUrl.indexOf('?') > 0 ? '&' : '?') + paramName + '=' + paramValue
}
return newUrl
}
// Scroll back to selected wishlist item
if (window.location.hash != '') {
var target = window.location.hash;
//var $target = $(target);
$('html, body').stop().animate({
//'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
} | ReinID/ReinID | Samples/.Net/.Netproperty4u/Property4U/Scripts/main.js | JavaScript | apache-2.0 | 2,179 |
<?php
namespace Google\AdsApi\AdWords\v201809\cm;
/**
* This file was generated from WSDL. DO NOT EDIT.
*/
class IdErrorReason
{
const NOT_FOUND = 'NOT_FOUND';
}
| googleads/googleads-php-lib | src/Google/AdsApi/AdWords/v201809/cm/IdErrorReason.php | PHP | apache-2.0 | 173 |
/*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH 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 com.graphhopper.jsprit.core.algorithm;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Random;
import org.junit.Test;
import com.graphhopper.jsprit.core.algorithm.acceptor.SolutionAcceptor;
import com.graphhopper.jsprit.core.algorithm.listener.SearchStrategyModuleListener;
import com.graphhopper.jsprit.core.algorithm.selector.SolutionSelector;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem;
import com.graphhopper.jsprit.core.problem.solution.SolutionCostCalculator;
import com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution;
public class SearchStrategyTest {
@Test(expected = IllegalStateException.class)
public void whenANullModule_IsAdded_throwException() {
SolutionSelector select = mock(SolutionSelector.class);
SolutionAcceptor accept = mock(SolutionAcceptor.class);
SolutionCostCalculator calc = mock(SolutionCostCalculator.class);
SearchStrategy strat = new SearchStrategy("strat", select, accept, calc);
strat.addModule(null);
}
@Test
public void whenStratRunsWithOneModule_runItOnes() {
SolutionSelector select = mock(SolutionSelector.class);
SolutionAcceptor accept = mock(SolutionAcceptor.class);
SolutionCostCalculator calc = mock(SolutionCostCalculator.class);
final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class);
final VehicleRoutingProblemSolution newSol = mock(VehicleRoutingProblemSolution.class);
when(select.selectSolution(null)).thenReturn(newSol);
final Collection<Integer> runs = new ArrayList<Integer>();
SearchStrategy strat = new SearchStrategy("strat", select, accept, calc);
SearchStrategyModule mod = new SearchStrategyModule() {
@Override
public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) {
runs.add(1);
return vrpSolution;
}
@Override
public String getName() {
return null;
}
@Override
public void addModuleListener(
SearchStrategyModuleListener moduleListener) {
}
};
strat.addModule(mod);
strat.run(vrp, null);
assertEquals(runs.size(), 1);
}
@Test
public void whenStratRunsWithTwoModule_runItTwice() {
SolutionSelector select = mock(SolutionSelector.class);
SolutionAcceptor accept = mock(SolutionAcceptor.class);
SolutionCostCalculator calc = mock(SolutionCostCalculator.class);
final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class);
final VehicleRoutingProblemSolution newSol = mock(VehicleRoutingProblemSolution.class);
when(select.selectSolution(null)).thenReturn(newSol);
final Collection<Integer> runs = new ArrayList<Integer>();
SearchStrategy strat = new SearchStrategy("strat", select, accept, calc);
SearchStrategyModule mod = new SearchStrategyModule() {
@Override
public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) {
runs.add(1);
return vrpSolution;
}
@Override
public String getName() {
return null;
}
@Override
public void addModuleListener(
SearchStrategyModuleListener moduleListener) {
}
};
SearchStrategyModule mod2 = new SearchStrategyModule() {
@Override
public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) {
runs.add(1);
return vrpSolution;
}
@Override
public String getName() {
return null;
}
@Override
public void addModuleListener(
SearchStrategyModuleListener moduleListener) {
}
};
strat.addModule(mod);
strat.addModule(mod2);
strat.run(vrp, null);
assertEquals(runs.size(), 2);
}
@Test
public void whenStratRunsWithNModule_runItNTimes() {
SolutionSelector select = mock(SolutionSelector.class);
SolutionAcceptor accept = mock(SolutionAcceptor.class);
SolutionCostCalculator calc = mock(SolutionCostCalculator.class);
final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class);
final VehicleRoutingProblemSolution newSol = mock(VehicleRoutingProblemSolution.class);
when(select.selectSolution(null)).thenReturn(newSol);
int N = new Random().nextInt(1000);
final Collection<Integer> runs = new ArrayList<Integer>();
SearchStrategy strat = new SearchStrategy("strat", select, accept, calc);
for (int i = 0; i < N; i++) {
SearchStrategyModule mod = new SearchStrategyModule() {
@Override
public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) {
runs.add(1);
return vrpSolution;
}
@Override
public String getName() {
return null;
}
@Override
public void addModuleListener(
SearchStrategyModuleListener moduleListener) {
}
};
strat.addModule(mod);
}
strat.run(vrp, null);
assertEquals(runs.size(), N);
}
@Test(expected = IllegalStateException.class)
public void whenSelectorDeliversNullSolution_throwException() {
SolutionSelector select = mock(SolutionSelector.class);
SolutionAcceptor accept = mock(SolutionAcceptor.class);
SolutionCostCalculator calc = mock(SolutionCostCalculator.class);
final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class);
when(select.selectSolution(null)).thenReturn(null);
int N = new Random().nextInt(1000);
final Collection<Integer> runs = new ArrayList<Integer>();
SearchStrategy strat = new SearchStrategy("strat", select, accept, calc);
for (int i = 0; i < N; i++) {
SearchStrategyModule mod = new SearchStrategyModule() {
@Override
public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) {
runs.add(1);
return vrpSolution;
}
@Override
public String getName() {
return null;
}
@Override
public void addModuleListener(
SearchStrategyModuleListener moduleListener) {
}
};
strat.addModule(mod);
}
strat.run(vrp, null);
assertEquals(runs.size(), N);
}
}
| balage1551/jsprit | jsprit-core/src/test/java/com/graphhopper/jsprit/core/algorithm/SearchStrategyTest.java | Java | apache-2.0 | 8,039 |
import { extend } from 'flarum/extend';
import PermissionGrid from 'flarum/components/PermissionGrid';
export default function() {
extend(PermissionGrid.prototype, 'moderateItems', items => {
items.add('tag', {
icon: 'fas fa-tag',
label: app.translator.trans('flarum-tags.admin.permissions.tag_discussions_label'),
permission: 'discussion.tag'
}, 95);
});
}
| drthomas21/WordPress_Tutorial | community_htdocs/vendor/flarum/tags/js/src/admin/addTagPermission.js | JavaScript | apache-2.0 | 389 |
#!/Users/wuga/Documents/website/wuga/env/bin/python2.7
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
# --------------------------------------------------------------------
# an image animation player
class UI(tkinter.Label):
def __init__(self, master, im):
if isinstance(im, list):
# list of images
self.im = im[1:]
im = self.im[0]
else:
# sequence
self.im = im
if im.mode == "1":
self.image = ImageTk.BitmapImage(im, foreground="white")
else:
self.image = ImageTk.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bg="black", bd=0)
self.update()
duration = im.info.get("duration", 100)
self.after(duration, self.next)
def next(self):
if isinstance(self.im, list):
try:
im = self.im[0]
del self.im[0]
self.image.paste(im)
except IndexError:
return # end of list
else:
try:
im = self.im
im.seek(im.tell() + 1)
self.image.paste(im)
except EOFError:
return # end of file
duration = im.info.get("duration", 100)
self.after(duration, self.next)
self.update_idletasks()
# --------------------------------------------------------------------
# script interface
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)")
sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for filename in sys.argv[1:]:
im.append(Image.open(filename))
else:
# sequence
im = Image.open(filename)
UI(root, im).pack()
root.mainloop()
| wuga214/Django-Wuga | env/bin/player.py | Python | apache-2.0 | 2,120 |
package com.apixandru.rummikub.api;
/**
* @author Alexandru-Constantin Bledea
* @since Sep 16, 2015
*/
public enum Rank {
ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, ELEVEN, TWELVE, THIRTEEN;
public int asNumber() {
return ordinal() + 1;
}
@Override
public String toString() {
return String.format("%2d", asNumber());
}
}
| apixandru/rummikub-java | rummikub-model/src/main/java/com/apixandru/rummikub/api/Rank.java | Java | apache-2.0 | 405 |
/*
* Copyright (c) 2008-2015, Hazelcast, 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 com.hazelcast.simulator.provisioner;
import com.hazelcast.simulator.common.AgentsFile;
import com.hazelcast.simulator.common.SimulatorProperties;
import com.hazelcast.simulator.utils.Bash;
import com.hazelcast.simulator.utils.jars.HazelcastJARs;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import org.jclouds.compute.ComputeService;
import static com.hazelcast.simulator.common.SimulatorProperties.PROPERTIES_FILE_NAME;
import static com.hazelcast.simulator.utils.CliUtils.initOptionsWithHelp;
import static com.hazelcast.simulator.utils.CliUtils.printHelpAndExit;
import static com.hazelcast.simulator.utils.CloudProviderUtils.isStatic;
import static com.hazelcast.simulator.utils.SimulatorUtils.loadSimulatorProperties;
import static com.hazelcast.simulator.utils.jars.HazelcastJARs.isPrepareRequired;
import static com.hazelcast.simulator.utils.jars.HazelcastJARs.newInstance;
import static java.util.Collections.singleton;
final class ProvisionerCli {
private final OptionParser parser = new OptionParser();
private final OptionSpec<Integer> scaleSpec = parser.accepts("scale",
"Number of Simulator machines to scale to. If the number of machines already exists, the call is ignored. If the"
+ " desired number of machines is smaller than the actual number of machines, machines are terminated.")
.withRequiredArg().ofType(Integer.class);
private final OptionSpec installSpec = parser.accepts("install",
"Installs Simulator on all provisioned machines.");
private final OptionSpec uploadHazelcastSpec = parser.accepts("uploadHazelcast",
"If defined --install will upload the Hazelcast JARs as well.");
private final OptionSpec<Boolean> enterpriseEnabledSpec = parser.accepts("enterpriseEnabled",
"Use JARs of Hazelcast Enterprise Edition.")
.withRequiredArg().ofType(Boolean.class).defaultsTo(false);
private final OptionSpec listAgentsSpec = parser.accepts("list",
"Lists the provisioned machines (from " + AgentsFile.NAME + " file).");
private final OptionSpec<String> downloadSpec = parser.accepts("download",
"Download all files from the remote Worker directories. Use --clean to delete all Worker directories.")
.withOptionalArg().ofType(String.class).defaultsTo("workers");
private final OptionSpec cleanSpec = parser.accepts("clean",
"Cleans the remote Worker directories on the provisioned machines.");
private final OptionSpec killSpec = parser.accepts("kill",
"Kills the Java processes on all provisioned machines (via killall -9 java).");
private final OptionSpec terminateSpec = parser.accepts("terminate",
"Terminates all provisioned machines.");
private final OptionSpec<String> propertiesFileSpec = parser.accepts("propertiesFile",
"The file containing the Simulator properties. If no file is explicitly configured, first the local working directory"
+ " is checked for a file '" + PROPERTIES_FILE_NAME + "'. All missing properties are always loaded from"
+ " '$SIMULATOR_HOME/conf/" + PROPERTIES_FILE_NAME + "'.")
.withRequiredArg().ofType(String.class);
private ProvisionerCli() {
}
static Provisioner init(String[] args) {
ProvisionerCli cli = new ProvisionerCli();
OptionSet options = initOptionsWithHelp(cli.parser, args);
SimulatorProperties properties = loadSimulatorProperties(options, cli.propertiesFileSpec);
ComputeService computeService = isStatic(properties) ? null : new ComputeServiceBuilder(properties).build();
Bash bash = new Bash(properties);
HazelcastJARs hazelcastJARs = null;
boolean enterpriseEnabled = options.valueOf(cli.enterpriseEnabledSpec);
if (options.has(cli.uploadHazelcastSpec)) {
String hazelcastVersionSpec = properties.getHazelcastVersionSpec();
if (isPrepareRequired(hazelcastVersionSpec) || !enterpriseEnabled) {
hazelcastJARs = newInstance(bash, properties, singleton(hazelcastVersionSpec));
}
}
return new Provisioner(properties, computeService, bash, hazelcastJARs, enterpriseEnabled);
}
static void run(String[] args, Provisioner provisioner) {
ProvisionerCli cli = new ProvisionerCli();
OptionSet options = initOptionsWithHelp(cli.parser, args);
try {
if (options.has(cli.scaleSpec)) {
int size = options.valueOf(cli.scaleSpec);
provisioner.scale(size);
} else if (options.has(cli.installSpec)) {
provisioner.installSimulator();
} else if (options.has(cli.listAgentsSpec)) {
provisioner.listMachines();
} else if (options.has(cli.downloadSpec)) {
String dir = options.valueOf(cli.downloadSpec);
provisioner.download(dir);
} else if (options.has(cli.cleanSpec)) {
provisioner.clean();
} else if (options.has(cli.killSpec)) {
provisioner.killJavaProcesses();
} else if (options.has(cli.terminateSpec)) {
provisioner.terminate();
} else {
printHelpAndExit(cli.parser);
}
} finally {
provisioner.shutdown();
}
}
}
| Danny-Hazelcast/hazelcast-stabilizer | simulator/src/main/java/com/hazelcast/simulator/provisioner/ProvisionerCli.java | Java | apache-2.0 | 6,122 |
package com.cognizant.cognizantits.qcconnection.qcupdation;
import com4j.DISPID;
import com4j.IID;
import com4j.VTID;
@IID("{B739B750-BFE1-43AF-8DD7-E8E8EFBBED7D}")
public abstract interface IDashboardFolderFactory
extends IBaseFactoryEx
{
@DISPID(9)
@VTID(17)
public abstract IList getChildPagesWithPrivateItems(IList paramIList);
}
/* Location: D:\Prabu\jars\QC.jar
* Qualified Name: qcupdation.IDashboardFolderFactory
* JD-Core Version: 0.7.0.1
*/ | CognizantQAHub/Cognizant-Intelligent-Test-Scripter | QcConnection/src/main/java/com/cognizant/cognizantits/qcconnection/qcupdation/IDashboardFolderFactory.java | Java | apache-2.0 | 482 |
/*
* Copyright (C) 2016 QAware GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.qaware.chronix.timeseries.dt;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.io.Serializable;
import java.util.Arrays;
import static de.qaware.chronix.timeseries.dt.ListUtil.*;
/**
* Implementation of a list with primitive doubles.
*
* @author f.lautenschlager
*/
public class DoubleList implements Serializable {
private static final long serialVersionUID = -1275724597860546074L;
/**
* Shared empty array instance used for empty instances.
*/
private static final double[] EMPTY_ELEMENT_DATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENT_DATA to know how much to inflate when
* first element is added.
*/
private static final double[] DEFAULT_CAPACITY_EMPTY_ELEMENT_DATA = {};
private double[] doubles;
private int size;
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public DoubleList(int initialCapacity) {
if (initialCapacity > 0) {
this.doubles = new double[initialCapacity];
} else if (initialCapacity == 0) {
this.doubles = EMPTY_ELEMENT_DATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
}
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public DoubleList() {
this.doubles = DEFAULT_CAPACITY_EMPTY_ELEMENT_DATA;
}
/**
* Constructs a double list from the given values by simple assigning them.
*
* @param longs the values of the double list.
* @param size the index of the last value in the array.
*/
@SuppressWarnings("all")
public DoubleList(double[] longs, int size) {
if (longs == null) {
throw new IllegalArgumentException("Illegal initial array 'null'");
}
if (size < 0) {
throw new IllegalArgumentException("Size if negative.");
}
this.doubles = longs;
this.size = size;
}
/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list
*/
public int size() {
return size;
}
/**
* Returns <tt>true</tt> if this list contains no elements.
*
* @return <tt>true</tt> if this list contains no elements
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Returns <tt>true</tt> if this list contains the specified element.
* More formally, returns <tt>true</tt> if and only if this list contains
* at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o element whose presence in this list is to be tested
* @return <tt>true</tt> if this list contains the specified element
*/
public boolean contains(double o) {
return indexOf(o) >= 0;
}
/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* @param o the double value
* @return the index of the given double element
*/
public int indexOf(double o) {
for (int i = 0; i < size; i++) {
if (o == doubles[i]) {
return i;
}
}
return -1;
}
/**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* @param o the double value
* @return the last index of the given double element
*/
public int lastIndexOf(double o) {
for (int i = size - 1; i >= 0; i--) {
if (o == doubles[i]) {
return i;
}
}
return -1;
}
/**
* Returns a shallow copy of this <tt>LongList</tt> instance. (The
* elements themselves are not copied.)
*
* @return a clone of this <tt>LongList</tt> instance
*/
public DoubleList copy() {
DoubleList v = new DoubleList(size);
v.doubles = Arrays.copyOf(doubles, size);
v.size = size;
return v;
}
/**
* Returns an array containing all of the elements in this list
* in proper sequence (from first to last element).
* <p>
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
* <p>
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this list in
* proper sequence
*/
public double[] toArray() {
return Arrays.copyOf(doubles, size);
}
private void growIfNeeded(int newCapacity) {
if (newCapacity != -1) {
doubles = Arrays.copyOf(doubles, newCapacity);
}
}
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException
*/
public double get(int index) {
rangeCheck(index, size);
return doubles[index];
}
/**
* Replaces the element at the specified position in this list with
* the specified element.
*
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException
*/
public double set(int index, double element) {
rangeCheck(index, size);
double oldValue = doubles[index];
doubles[index] = element;
return oldValue;
}
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by Collection#add)
*/
public boolean add(double e) {
int newCapacity = calculateNewCapacity(doubles.length, size + 1);
growIfNeeded(newCapacity);
doubles[size++] = e;
return true;
}
/**
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException
*/
public void add(int index, double element) {
rangeCheckForAdd(index, size);
int newCapacity = calculateNewCapacity(doubles.length, size + 1);
growIfNeeded(newCapacity);
System.arraycopy(doubles, index, doubles, index + 1, size - index);
doubles[index] = element;
size++;
}
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException
*/
public double remove(int index) {
rangeCheck(index, size);
double oldValue = doubles[index];
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(doubles, index + 1, doubles, index, numMoved);
}
--size;
return oldValue;
}
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If the list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns <tt>true</tt> if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* @return <tt>true</tt> if this list contained the specified element
*/
public boolean remove(double o) {
for (int index = 0; index < size; index++) {
if (o == doubles[index]) {
fastRemove(index);
return true;
}
}
return false;
}
private void fastRemove(int index) {
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(doubles, index + 1, doubles, index, numMoved);
}
--size;
}
/**
* Removes all of the elements from this list. The list will
* be empty after this call returns.
*/
public void clear() {
doubles = DEFAULT_CAPACITY_EMPTY_ELEMENT_DATA;
size = 0;
}
/**
* Appends all of the elements in the specified collection to the end of
* this list, in the order that they are returned by the
* specified collection's Iterator. The behavior of this operation is
* undefined if the specified collection is modified while the operation
* is in progress. (This implies that the behavior of this call is
* undefined if the specified collection is this list, and this
* list is nonempty.)
*
* @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(DoubleList c) {
double[] a = c.toArray();
int numNew = a.length;
int newCapacity = calculateNewCapacity(doubles.length, size + numNew);
growIfNeeded(newCapacity);
System.arraycopy(a, 0, doubles, size, numNew);
size += numNew;
return numNew != 0;
}
/**
* Appends the long[] at the end of this long list.
*
* @param otherDoubles the other double[] that is appended
* @return <tt>true</tt> if this list changed as a result of the call
* @throws NullPointerException if the specified array is null
*/
public boolean addAll(double[] otherDoubles) {
int numNew = otherDoubles.length;
int newCapacity = calculateNewCapacity(doubles.length, size + numNew);
growIfNeeded(newCapacity);
System.arraycopy(otherDoubles, 0, doubles, size, numNew);
size += numNew;
return numNew != 0;
}
/**
* Inserts all of the elements in the specified collection into this
* list, starting at the specified position. Shifts the element
* currently at that position (if any) and any subsequent elements to
* the right (increases their indices). The new elements will appear
* in the list in the order that they are returned by the
* specified collection's iterator.
*
* @param index index at which to insert the first element from the
* specified collection
* @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws IndexOutOfBoundsException
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(int index, DoubleList c) {
rangeCheckForAdd(index, size);
double[] a = c.toArray();
int numNew = a.length;
int newCapacity = calculateNewCapacity(doubles.length, size + numNew);
growIfNeeded(newCapacity);
int numMoved = size - index;
if (numMoved > 0) {
System.arraycopy(doubles, index, doubles, index + numNew, numMoved);
}
System.arraycopy(a, 0, doubles, index, numNew);
size += numNew;
return numNew != 0;
}
/**
* Removes from this list all of the elements whose index is between
* {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
* Shifts any succeeding elements to the left (reduces their index).
* This call shortens the list by {@code (toIndex - fromIndex)} elements.
* (If {@code toIndex==fromIndex}, this operation has no effect.)
*
* @throws IndexOutOfBoundsException if {@code fromIndex} or
* {@code toIndex} is out of range
* ({@code fromIndex < 0 ||
* fromIndex >= size() ||
* toIndex > size() ||
* toIndex < fromIndex})
*/
public void removeRange(int fromIndex, int toIndex) {
int numMoved = size - toIndex;
System.arraycopy(doubles, toIndex, doubles, fromIndex, numMoved);
size = size - (toIndex - fromIndex);
}
/**
* Trims the capacity of this <tt>ArrayList</tt> instance to be the
* list's current size. An application can use this operation to minimize
* the storage of an <tt>ArrayList</tt> instance.
*/
private double[] trimToSize(int size, double[] elements) {
double[] copy = Arrays.copyOf(elements, elements.length);
if (size < elements.length) {
copy = (size == 0) ? EMPTY_ELEMENT_DATA : Arrays.copyOf(elements, size);
}
return copy;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
DoubleList rhs = (DoubleList) obj;
double[] thisTrimmed = trimToSize(this.size, this.doubles);
double[] otherTrimmed = trimToSize(rhs.size, rhs.doubles);
return new EqualsBuilder()
.append(thisTrimmed, otherTrimmed)
.append(this.size, rhs.size)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(doubles)
.append(size)
.toHashCode();
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("doubles", trimToSize(this.size, doubles))
.append("size", size)
.toString();
}
/**
* @return maximum of the values of the list
*/
public double max() {
if (size <= 0) {
return Double.NaN;
}
double max = Double.MIN_VALUE;
for (int i = 0; i < size; i++) {
max = doubles[i] > max ? doubles[i] : max;
}
return max;
}
/**
* @return minimum of the values of the list
*/
public double min() {
if (size <= 0) {
return Double.NaN;
}
double min = Double.MAX_VALUE;
for (int i = 0; i < size; i++) {
min = doubles[i] < min ? doubles[i] : min;
}
return min;
}
/**
* @return average of the values of the list
*/
public double avg() {
if (size <= 0) {
return Double.NaN;
}
double current = 0;
for (int i = 0; i < size; i++) {
current += doubles[i];
}
return current / size;
}
/**
* @param scale to be applied to the values of this list
* @return a new instance scaled with the given parameter
*/
public DoubleList scale(double scale) {
DoubleList scaled = new DoubleList(size);
for (int i = 0; i < size; i++) {
scaled.add(doubles[i] * scale);
}
return scaled;
}
/**
* Calculates the standard deviation
*
* @return the standard deviation
*/
public double stdDeviation() {
if (isEmpty()) {
return Double.NaN;
}
return Math.sqrt(variance());
}
private double mean() {
double sum = 0.0;
for (int i = 0; i < size(); i++) {
sum = sum + get(i);
}
return sum / size();
}
private double variance() {
double avg = mean();
double sum = 0.0;
for (int i = 0; i < size(); i++) {
double value = get(i);
sum += (value - avg) * (value - avg);
}
return sum / (size() - 1);
}
/**
* Implemented the quantile type 7 referred to
* http://tolstoy.newcastle.edu.au/R/e17/help/att-1067/Quartiles_in_R.pdf
* and
* http://stat.ethz.ch/R-manual/R-patched/library/stats/html/quantile.html
* as its the default quantile implementation
* <p>
* <code>
* QuantileType7 = function (v, p) {
* v = sort(v)
* h = ((length(v)-1)*p)+1
* v[floor(h)]+((h-floor(h))*(v[floor(h)+1]- v[floor(h)]))
* }
* </code>
*
* @param percentile - the percentile (0 - 1), e.g. 0.25
* @return the value of the n-th percentile
*/
public double percentile(double percentile) {
double[] copy = toArray();
Arrays.sort(copy);// Attention: this is only necessary because this list is not restricted to non-descending values
return evaluateForDoubles(copy, percentile);
}
private static double evaluateForDoubles(double[] points, double percentile) {
//For example:
//values = [1,2,2,3,3,3,4,5,6], size = 9, percentile (e.g. 0.25)
// size - 1 = 8 * 0.25 = 2 (~ 25% from 9) + 1 = 3 => values[3] => 2
double percentileIndex = ((points.length - 1) * percentile) + 1;
double rawMedian = points[floor(percentileIndex - 1)];
double weight = percentileIndex - floor(percentileIndex);
if (weight > 0) {
double pointDistance = points[floor(percentileIndex - 1) + 1] - points[floor(percentileIndex - 1)];
return rawMedian + weight * pointDistance;
} else {
return rawMedian;
}
}
/**
* Wraps the Math.floor function and casts it to an integer
*
* @param value - the evaluatedValue
* @return the floored evaluatedValue
*/
private static int floor(double value) {
return (int) Math.floor(value);
}
}
| 0xhansdampf/chronix.kassiopeia | chronix-kassiopeia-simple/src/main/java/de/qaware/chronix/timeseries/dt/DoubleList.java | Java | apache-2.0 | 19,873 |
# Copyright 2018 Huawei Technologies 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 copy
from oslo_log import log as logging
from oslo_versionedobjects import base as object_base
from cyborg.common import exception
from cyborg.db import api as dbapi
from cyborg.objects import base
from cyborg.objects import fields as object_fields
from cyborg.objects.deployable import Deployable
from cyborg.objects.virtual_function import VirtualFunction
LOG = logging.getLogger(__name__)
@base.CyborgObjectRegistry.register
class PhysicalFunction(Deployable):
# Version 1.0: Initial version
VERSION = '1.0'
virtual_function_list = []
def create(self, context):
# To ensure the creating type is PF
if self.type != 'pf':
raise exception.InvalidDeployType()
super(PhysicalFunction, self).create(context)
def save(self, context):
"""In addition to save the pf, it should also save the
vfs associated with this pf
"""
# To ensure the saving type is PF
if self.type != 'pf':
raise exception.InvalidDeployType()
for exist_vf in self.virtual_function_list:
exist_vf.save(context)
super(PhysicalFunction, self).save(context)
def add_vf(self, vf):
"""add a vf object to the virtual_function_list.
If the vf already exists, it will ignore,
otherwise, the vf will be appended to the list
"""
if not isinstance(vf, VirtualFunction) or vf.type != 'vf':
raise exception.InvalidDeployType()
for exist_vf in self.virtual_function_list:
if base.obj_equal_prims(vf, exist_vf):
LOG.warning("The vf already exists")
return None
vf.parent_uuid = self.uuid
vf.root_uuid = self.root_uuid
vf_copy = copy.deepcopy(vf)
self.virtual_function_list.append(vf_copy)
def delete_vf(self, context, vf):
"""remove a vf from the virtual_function_list
if the vf does not exist, ignore it
"""
for idx, exist_vf in self.virtual_function_list:
if base.obj_equal_prims(vf, exist_vf):
removed_vf = self.virtual_function_list.pop(idx)
removed_vf.destroy(context)
return
LOG.warning("The removing vf does not exist!")
def destroy(self, context):
"""Delete a the pf from the DB."""
del self.virtual_function_list[:]
super(PhysicalFunction, self).destroy(context)
@classmethod
def get(cls, context, uuid):
"""Find a DB Physical Function and return an Obj Physical Function.
In addition, it will also finds all the Virtual Functions associated
with this Physical Function and place them in virtual_function_list
"""
db_pf = cls.dbapi.deployable_get(context, uuid)
obj_pf = cls._from_db_object(cls(context), db_pf)
pf_uuid = obj_pf.uuid
query = {"parent_uuid": pf_uuid, "type": "vf"}
db_vf_list = cls.dbapi.deployable_get_by_filters(context, query)
for db_vf in db_vf_list:
obj_vf = VirtualFunction.get(context, db_vf.uuid)
obj_pf.virtual_function_list.append(obj_vf)
return obj_pf
@classmethod
def get_by_filter(cls, context,
filters, sort_key='created_at',
sort_dir='desc', limit=None,
marker=None, join=None):
obj_dpl_list = []
filters['type'] = 'pf'
db_dpl_list = cls.dbapi.deployable_get_by_filters(context, filters,
sort_key=sort_key,
sort_dir=sort_dir,
limit=limit,
marker=marker,
join_columns=join)
for db_dpl in db_dpl_list:
obj_dpl = cls._from_db_object(cls(context), db_dpl)
query = {"parent_uuid": obj_dpl.uuid}
vf_get_list = VirtualFunction.get_by_filter(context,
query)
obj_dpl.virtual_function_list = vf_get_list
obj_dpl_list.append(obj_dpl)
return obj_dpl_list
@classmethod
def _from_db_object(cls, obj, db_obj):
"""Converts a physical function to a formal object.
:param obj: An object of the class.
:param db_obj: A DB model of the object
:return: The object of the class with the database entity added
"""
obj = Deployable._from_db_object(obj, db_obj)
if cls is PhysicalFunction:
obj.virtual_function_list = []
return obj
| openstack/nomad | cyborg/objects/physical_function.py | Python | apache-2.0 | 5,396 |
/*
Copyright 2020 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package events
import (
"archive/tar"
"bufio"
"compress/gzip"
"context"
"encoding/binary"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"github.com/gravitational/teleport"
apievents "github.com/gravitational/teleport/api/types/events"
"github.com/gravitational/teleport/lib/session"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/trace"
log "github.com/sirupsen/logrus"
)
// Header returns information about playback
type Header struct {
// Tar detected tar format
Tar bool
// Proto is for proto format
Proto bool
// ProtoVersion is a version of the format, valid if Proto is true
ProtoVersion int64
}
// DetectFormat detects format by reading first bytes
// of the header. Callers should call Seek()
// to reuse reader after calling this function.
func DetectFormat(r io.ReadSeeker) (*Header, error) {
version := make([]byte, Int64Size)
_, err := io.ReadFull(r, version)
if err != nil {
return nil, trace.ConvertSystemError(err)
}
protocolVersion := binary.BigEndian.Uint64(version)
if protocolVersion == ProtoStreamV1 {
return &Header{
Proto: true,
ProtoVersion: int64(protocolVersion),
}, nil
}
_, err = r.Seek(0, 0)
if err != nil {
return nil, trace.ConvertSystemError(err)
}
tr := tar.NewReader(r)
_, err = tr.Next()
if err != nil {
return nil, trace.ConvertSystemError(err)
}
return &Header{Tar: true}, nil
}
// Export converts session files from binary/protobuf to text/JSON.
func Export(ctx context.Context, rs io.ReadSeeker, w io.Writer, exportFormat string) error {
switch exportFormat {
case teleport.JSON:
default:
return trace.BadParameter("unsupported format %q, %q is the only supported format", exportFormat, teleport.JSON)
}
format, err := DetectFormat(rs)
if err != nil {
return trace.Wrap(err)
}
_, err = rs.Seek(0, 0)
if err != nil {
return trace.ConvertSystemError(err)
}
switch {
case format.Proto:
protoReader := NewProtoReader(rs)
for {
event, err := protoReader.Read(ctx)
if err != nil {
if err == io.EOF {
return nil
}
return trace.Wrap(err)
}
switch exportFormat {
case teleport.JSON:
data, err := utils.FastMarshal(event)
if err != nil {
return trace.ConvertSystemError(err)
}
_, err = fmt.Fprintln(w, string(data))
if err != nil {
return trace.ConvertSystemError(err)
}
default:
return trace.BadParameter("unsupported format %q, %q is the only supported format", exportFormat, teleport.JSON)
}
}
case format.Tar:
return trace.BadParameter(
"to review the events in format of teleport before version 4.4, extract the tarball and look inside")
default:
return trace.BadParameter("unsupported format %v", format)
}
}
// WriteForPlayback reads events from audit reader and writes them to the format optimized for playback
// this function returns *PlaybackWriter and error
func WriteForPlayback(ctx context.Context, sid session.ID, reader AuditReader, dir string) (*PlaybackWriter, error) {
w := &PlaybackWriter{
sid: sid,
reader: reader,
dir: dir,
eventIndex: -1,
}
defer func() {
if err := w.Close(); err != nil {
log.WithError(err).Warningf("Failed to close writer.")
}
}()
return w, w.Write(ctx)
}
// SessionEvents returns slice of event fields from gzipped events file.
func (w *PlaybackWriter) SessionEvents() ([]EventFields, error) {
var sessionEvents []EventFields
//events
eventFile, err := os.Open(w.EventsPath)
if err != nil {
return nil, trace.Wrap(err)
}
defer eventFile.Close()
grEvents, err := gzip.NewReader(eventFile)
if err != nil {
return nil, trace.Wrap(err)
}
defer grEvents.Close()
scanner := bufio.NewScanner(grEvents)
for scanner.Scan() {
var f EventFields
err := utils.FastUnmarshal(scanner.Bytes(), &f)
if err != nil {
if err == io.EOF {
return sessionEvents, nil
}
return nil, trace.Wrap(err)
}
sessionEvents = append(sessionEvents, f)
}
if err := scanner.Err(); err != nil {
return nil, trace.Wrap(err)
}
return sessionEvents, nil
}
// SessionChunks interprets the file at the given path as gzip-compressed list of session events and returns
// the uncompressed contents as a result.
func (w *PlaybackWriter) SessionChunks() ([]byte, error) {
var stream []byte
chunkFile, err := os.Open(w.ChunksPath)
if err != nil {
return nil, trace.Wrap(err)
}
defer chunkFile.Close()
grChunk, err := gzip.NewReader(chunkFile)
if err != nil {
return nil, trace.Wrap(err)
}
defer grChunk.Close()
stream, err = ioutil.ReadAll(grChunk)
if err != nil {
return nil, trace.Wrap(err)
}
return stream, nil
}
// PlaybackWriter reads messages from an AuditReader and writes them
// to disk in a format suitable for SSH session playback.
type PlaybackWriter struct {
sid session.ID
dir string
reader AuditReader
indexFile *os.File
eventsFile *gzipWriter
chunksFile *gzipWriter
eventIndex int64
EventsPath string
ChunksPath string
}
// Close closes all files
func (w *PlaybackWriter) Close() error {
if w.indexFile != nil {
if err := w.indexFile.Close(); err != nil {
log.Warningf("Failed to close index file: %v.", err)
}
w.indexFile = nil
}
if w.chunksFile != nil {
if err := w.chunksFile.Flush(); err != nil {
log.Warningf("Failed to flush chunks file: %v.", err)
}
if err := w.chunksFile.Close(); err != nil {
log.Warningf("Failed closing chunks file: %v.", err)
}
}
if w.eventsFile != nil {
if err := w.eventsFile.Flush(); err != nil {
log.Warningf("Failed to flush events file: %v.", err)
}
if err := w.eventsFile.Close(); err != nil {
log.Warningf("Failed closing events file: %v.", err)
}
}
return nil
}
// Write writes all events from the AuditReader and writes
// files to disk in the format optimized for playback.
func (w *PlaybackWriter) Write(ctx context.Context) error {
if err := w.openIndexFile(); err != nil {
return trace.Wrap(err)
}
for {
event, err := w.reader.Read(ctx)
if err != nil {
if err == io.EOF {
return nil
}
return trace.Wrap(err)
}
if err := w.writeEvent(event); err != nil {
return trace.Wrap(err)
}
}
}
func (w *PlaybackWriter) writeEvent(event apievents.AuditEvent) error {
switch event.GetType() {
// Timing events for TTY playback go to both a chunks file (the raw bytes) as
// well as well as the events file (structured events).
case SessionPrintEvent:
return trace.Wrap(w.writeSessionPrintEvent(event))
// Playback does not use enhanced events at the moment,
// so they are skipped
case SessionCommandEvent, SessionDiskEvent, SessionNetworkEvent:
return nil
// PlaybackWriter is not used for desktop playback, so we should never see
// these events, but skip them if a user or developer somehow tries to playback
// a desktop session using this TTY PlaybackWriter
case DesktopRecordingEvent:
return nil
// All other events get put into the general events file. These are events like
// session.join, session.end, etc.
default:
return trace.Wrap(w.writeRegularEvent(event))
}
}
func (w *PlaybackWriter) writeSessionPrintEvent(event apievents.AuditEvent) error {
print, ok := event.(*apievents.SessionPrint)
if !ok {
return trace.BadParameter("expected session print event, got %T", event)
}
w.eventIndex++
event.SetIndex(w.eventIndex)
if err := w.openEventsFile(0); err != nil {
return trace.Wrap(err)
}
if err := w.openChunksFile(0); err != nil {
return trace.Wrap(err)
}
data := print.Data
print.Data = nil
bytes, err := utils.FastMarshal(event)
if err != nil {
return trace.Wrap(err)
}
_, err = w.eventsFile.Write(append(bytes, '\n'))
if err != nil {
return trace.Wrap(err)
}
_, err = w.chunksFile.Write(data)
if err != nil {
return trace.Wrap(err)
}
return nil
}
func (w *PlaybackWriter) writeRegularEvent(event apievents.AuditEvent) error {
w.eventIndex++
event.SetIndex(w.eventIndex)
if err := w.openEventsFile(0); err != nil {
return trace.Wrap(err)
}
bytes, err := utils.FastMarshal(event)
if err != nil {
return trace.Wrap(err)
}
_, err = w.eventsFile.Write(append(bytes, '\n'))
if err != nil {
return trace.Wrap(err)
}
return nil
}
func (w *PlaybackWriter) openIndexFile() error {
if w.indexFile != nil {
return nil
}
var err error
w.indexFile, err = os.OpenFile(
filepath.Join(w.dir, fmt.Sprintf("%v.index", w.sid.String())), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640)
if err != nil {
return trace.Wrap(err)
}
return nil
}
func (w *PlaybackWriter) openEventsFile(eventIndex int64) error {
if w.eventsFile != nil {
return nil
}
w.EventsPath = eventsFileName(w.dir, w.sid, "", eventIndex)
// update the index file to write down that new events file has been created
data, err := utils.FastMarshal(indexEntry{
FileName: filepath.Base(w.EventsPath),
Type: fileTypeEvents,
Index: eventIndex,
})
if err != nil {
return trace.Wrap(err)
}
_, err = fmt.Fprintf(w.indexFile, "%v\n", string(data))
if err != nil {
return trace.Wrap(err)
}
// open new events file for writing
file, err := os.OpenFile(w.EventsPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640)
if err != nil {
return trace.Wrap(err)
}
w.eventsFile = newGzipWriter(file)
return nil
}
func (w *PlaybackWriter) openChunksFile(offset int64) error {
if w.chunksFile != nil {
return nil
}
w.ChunksPath = chunksFileName(w.dir, w.sid, offset)
// Update the index file to write down that new chunks file has been created.
data, err := utils.FastMarshal(indexEntry{
FileName: filepath.Base(w.ChunksPath),
Type: fileTypeChunks,
Offset: offset,
})
if err != nil {
return trace.Wrap(err)
}
// index file will contain file name with extension .gz (assuming it was gzipped)
_, err = fmt.Fprintf(w.indexFile, "%v\n", string(data))
if err != nil {
return trace.Wrap(err)
}
// open the chunks file for writing, but because the file is written without
// compression, remove the .gz
file, err := os.OpenFile(w.ChunksPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640)
if err != nil {
return trace.Wrap(err)
}
w.chunksFile = newGzipWriter(file)
return nil
}
| gravitational/teleport | lib/events/playback.go | GO | apache-2.0 | 10,730 |
package de.devisnik.mine.robot.test;
import de.devisnik.mine.robot.AutoPlayerTest;
import de.devisnik.mine.robot.ConfigurationTest;
import junit.framework.Test;
import junit.framework.TestSuite;
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("Tests for de.devisnik.mine.robot");
//$JUnit-BEGIN$
suite.addTestSuite(AutoPlayerTest.class);
suite.addTestSuite(ConfigurationTest.class);
//$JUnit-END$
return suite;
}
}
| devisnik/mines | robot/src/test/java/de/devisnik/mine/robot/test/AllTests.java | Java | apache-2.0 | 470 |
package com.beanu.l2_shareutil.share;
import androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Created by shaohui on 2016/11/18.
*/
public class SharePlatform {
@IntDef({ DEFAULT, QQ, QZONE, WEIBO, WX, WX_TIMELINE })
@Retention(RetentionPolicy.SOURCE)
public @interface Platform{}
public static final int DEFAULT = 0;
public static final int QQ = 1;
public static final int QZONE = 2;
public static final int WX = 3;
public static final int WX_TIMELINE = 4;
public static final int WEIBO = 5;
}
| beanu/smart-farmer-android | l2_shareutil/src/main/java/com/beanu/l2_shareutil/share/SharePlatform.java | Java | apache-2.0 | 608 |
<?php
/**
* Contains all client objects for the ExchangeRateService
* service.
*
* PHP version 5
*
* Copyright 2016, Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @package GoogleApiAdsDfp
* @subpackage v201605
* @category WebServices
* @copyright 2016, Google Inc. All Rights Reserved.
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License,
* Version 2.0
*/
require_once "Google/Api/Ads/Dfp/Lib/DfpSoapClient.php";
if (!class_exists("ApiError", false)) {
/**
* The API error base class that provides details about an error that occurred
* while processing a service request.
*
* <p>The OGNL field path is provided for parsers to identify the request data
* element that may have caused the error.</p>
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "ApiError";
/**
* @access public
* @var string
*/
public $fieldPath;
/**
* @access public
* @var string
*/
public $trigger;
/**
* @access public
* @var string
*/
public $errorString;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($fieldPath = null, $trigger = null, $errorString = null) {
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("ApiVersionError", false)) {
/**
* Errors related to the usage of API versions.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class ApiVersionError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "ApiVersionError";
/**
* @access public
* @var tnsApiVersionErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("ApplicationException", false)) {
/**
* Base class for exceptions.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class ApplicationException {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "ApplicationException";
/**
* @access public
* @var string
*/
public $message;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($message = null) {
$this->message = $message;
}
}
}
if (!class_exists("AuthenticationError", false)) {
/**
* An error for an exception that occurred when authenticating.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class AuthenticationError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "AuthenticationError";
/**
* @access public
* @var tnsAuthenticationErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("CollectionSizeError", false)) {
/**
* Error for the size of the collection being too large
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class CollectionSizeError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "CollectionSizeError";
/**
* @access public
* @var tnsCollectionSizeErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("CommonError", false)) {
/**
* A place for common errors that can be used across services.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class CommonError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "CommonError";
/**
* @access public
* @var tnsCommonErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("Date", false)) {
/**
* Represents a date.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class Date {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "Date";
/**
* @access public
* @var integer
*/
public $year;
/**
* @access public
* @var integer
*/
public $month;
/**
* @access public
* @var integer
*/
public $day;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($year = null, $month = null, $day = null) {
$this->year = $year;
$this->month = $month;
$this->day = $day;
}
}
}
if (!class_exists("DfpDateTime", false)) {
/**
* Represents a date combined with the time of day.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class DfpDateTime {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "DateTime";
/**
* @access public
* @var Date
*/
public $date;
/**
* @access public
* @var integer
*/
public $hour;
/**
* @access public
* @var integer
*/
public $minute;
/**
* @access public
* @var integer
*/
public $second;
/**
* @access public
* @var string
*/
public $timeZoneID;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($date = null, $hour = null, $minute = null, $second = null, $timeZoneID = null) {
$this->date = $date;
$this->hour = $hour;
$this->minute = $minute;
$this->second = $second;
$this->timeZoneID = $timeZoneID;
}
}
}
if (!class_exists("ExchangeRateAction", false)) {
/**
* Represents the actions that can be performed on {@link ExchangeRate} objects.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class ExchangeRateAction {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "ExchangeRateAction";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("ExchangeRate", false)) {
/**
* An {@code ExchangeRate} represents a currency which is one of the
* {@link Network#secondaryCurrencyCodes}, and the latest exchange rate between this currency and
* {@link Network#currencyCode}.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class ExchangeRate {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "ExchangeRate";
/**
* @access public
* @var integer
*/
public $id;
/**
* @access public
* @var string
*/
public $currencyCode;
/**
* @access public
* @var tnsExchangeRateRefreshRate
*/
public $refreshRate;
/**
* @access public
* @var tnsExchangeRateDirection
*/
public $direction;
/**
* @access public
* @var integer
*/
public $exchangeRate;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($id = null, $currencyCode = null, $refreshRate = null, $direction = null, $exchangeRate = null) {
$this->id = $id;
$this->currencyCode = $currencyCode;
$this->refreshRate = $refreshRate;
$this->direction = $direction;
$this->exchangeRate = $exchangeRate;
}
}
}
if (!class_exists("ExchangeRateError", false)) {
/**
* Lists all errors associated with {@link ExchangeRate} objects.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class ExchangeRateError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "ExchangeRateError";
/**
* @access public
* @var tnsExchangeRateErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("ExchangeRatePage", false)) {
/**
* Captures a page of {@link ExchangeRate} objects.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class ExchangeRatePage {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "ExchangeRatePage";
/**
* @access public
* @var ExchangeRate[]
*/
public $results;
/**
* @access public
* @var integer
*/
public $startIndex;
/**
* @access public
* @var integer
*/
public $totalResultSetSize;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($results = null, $startIndex = null, $totalResultSetSize = null) {
$this->results = $results;
$this->startIndex = $startIndex;
$this->totalResultSetSize = $totalResultSetSize;
}
}
}
if (!class_exists("FeatureError", false)) {
/**
* Errors related to feature management. If you attempt using a feature that is not available to
* the current network you'll receive a FeatureError with the missing feature as the trigger.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class FeatureError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "FeatureError";
/**
* @access public
* @var tnsFeatureErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("InternalApiError", false)) {
/**
* Indicates that a server-side error has occured. {@code InternalApiError}s
* are generally not the result of an invalid request or message sent by the
* client.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class InternalApiError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "InternalApiError";
/**
* @access public
* @var tnsInternalApiErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("NotNullError", false)) {
/**
* Caused by supplying a null value for an attribute that cannot be null.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class NotNullError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "NotNullError";
/**
* @access public
* @var tnsNotNullErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("ParseError", false)) {
/**
* Lists errors related to parsing.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class ParseError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "ParseError";
/**
* @access public
* @var tnsParseErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("PermissionError", false)) {
/**
* Errors related to incorrect permission.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class PermissionError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "PermissionError";
/**
* @access public
* @var tnsPermissionErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("PublisherQueryLanguageContextError", false)) {
/**
* An error that occurs while executing a PQL query contained in
* a {@link Statement} object.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class PublisherQueryLanguageContextError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "PublisherQueryLanguageContextError";
/**
* @access public
* @var tnsPublisherQueryLanguageContextErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("PublisherQueryLanguageSyntaxError", false)) {
/**
* An error that occurs while parsing a PQL query contained in a
* {@link Statement} object.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class PublisherQueryLanguageSyntaxError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "PublisherQueryLanguageSyntaxError";
/**
* @access public
* @var tnsPublisherQueryLanguageSyntaxErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("QuotaError", false)) {
/**
* Describes a client-side error on which a user is attempting
* to perform an action to which they have no quota remaining.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class QuotaError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "QuotaError";
/**
* @access public
* @var tnsQuotaErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("RequiredCollectionError", false)) {
/**
* A list of all errors to be used for validating sizes of collections.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class RequiredCollectionError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "RequiredCollectionError";
/**
* @access public
* @var tnsRequiredCollectionErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("RequiredError", false)) {
/**
* Errors due to missing required field.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class RequiredError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "RequiredError";
/**
* @access public
* @var tnsRequiredErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("RequiredNumberError", false)) {
/**
* A list of all errors to be used in conjunction with required number
* validators.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class RequiredNumberError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "RequiredNumberError";
/**
* @access public
* @var tnsRequiredNumberErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("ServerError", false)) {
/**
* Errors related to the server.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class ServerError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "ServerError";
/**
* @access public
* @var tnsServerErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("SoapRequestHeader", false)) {
/**
* Represents the SOAP request header used by API requests.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class SoapRequestHeader {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "SoapRequestHeader";
/**
* @access public
* @var string
*/
public $networkCode;
/**
* @access public
* @var string
*/
public $applicationName;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($networkCode = null, $applicationName = null) {
$this->networkCode = $networkCode;
$this->applicationName = $applicationName;
}
}
}
if (!class_exists("SoapResponseHeader", false)) {
/**
* Represents the SOAP request header used by API responses.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class SoapResponseHeader {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "SoapResponseHeader";
/**
* @access public
* @var string
*/
public $requestId;
/**
* @access public
* @var integer
*/
public $responseTime;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($requestId = null, $responseTime = null) {
$this->requestId = $requestId;
$this->responseTime = $responseTime;
}
}
}
if (!class_exists("Statement", false)) {
/**
* Captures the {@code WHERE}, {@code ORDER BY} and {@code LIMIT} clauses of a
* PQL query. Statements are typically used to retrieve objects of a predefined
* domain type, which makes SELECT clause unnecessary.
* <p>
* An example query text might be {@code "WHERE status = 'ACTIVE' ORDER BY id
* LIMIT 30"}.
* </p>
* <p>
* Statements support bind variables. These are substitutes for literals
* and can be thought of as input parameters to a PQL query.
* </p>
* <p>
* An example of such a query might be {@code "WHERE id = :idValue"}.
* </p>
* <p>
* Statements also support use of the LIKE keyword. This provides partial and
* wildcard string matching.
* </p>
* <p>
* An example of such a query might be {@code "WHERE name LIKE 'startswith%'"}.
* </p>
* The value for the variable idValue must then be set with an object of type
* {@link Value}, e.g., {@link NumberValue}, {@link TextValue} or
* {@link BooleanValue}.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class Statement {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "Statement";
/**
* @access public
* @var string
*/
public $query;
/**
* @access public
* @var String_ValueMapEntry[]
*/
public $values;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($query = null, $values = null) {
$this->query = $query;
$this->values = $values;
}
}
}
if (!class_exists("StatementError", false)) {
/**
* An error that occurs while parsing {@link Statement} objects.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class StatementError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "StatementError";
/**
* @access public
* @var tnsStatementErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("StringLengthError", false)) {
/**
* Errors for Strings which do not meet given length constraints.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class StringLengthError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "StringLengthError";
/**
* @access public
* @var tnsStringLengthErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("String_ValueMapEntry", false)) {
/**
* This represents an entry in a map with a key of type String
* and value of type Value.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class String_ValueMapEntry {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "String_ValueMapEntry";
/**
* @access public
* @var string
*/
public $key;
/**
* @access public
* @var Value
*/
public $value;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($key = null, $value = null) {
$this->key = $key;
$this->value = $value;
}
}
}
if (!class_exists("UniqueError", false)) {
/**
* An error for a field which must satisfy a uniqueness constraint
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class UniqueError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "UniqueError";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($fieldPath = null, $trigger = null, $errorString = null) {
parent::__construct();
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
}
}
}
if (!class_exists("UpdateResult", false)) {
/**
* Represents the result of performing an action on objects.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class UpdateResult {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "UpdateResult";
/**
* @access public
* @var integer
*/
public $numChanges;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($numChanges = null) {
$this->numChanges = $numChanges;
}
}
}
if (!class_exists("Value", false)) {
/**
* {@code Value} represents a value.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class Value {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "Value";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("ApiVersionErrorReason", false)) {
/**
* Indicates that the operation is not allowed in the version the request
* was made in.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class ApiVersionErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "ApiVersionError.Reason";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("AuthenticationErrorReason", false)) {
/**
* The SOAP message contains a request header with an ambiguous definition
* of the authentication header fields. This means either the {@code
* authToken} and {@code oAuthToken} fields were both null or both were
* specified. Exactly one value should be specified with each request.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class AuthenticationErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "AuthenticationError.Reason";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("CollectionSizeErrorReason", false)) {
/**
* The value returned if the actual value is not exposed by the requested API version.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class CollectionSizeErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "CollectionSizeError.Reason";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("CommonErrorReason", false)) {
/**
* Describes reasons for common errors
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class CommonErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "CommonError.Reason";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("ExchangeRateDirection", false)) {
/**
* Determines which direction (from which currency to which currency) the exchange rate is in.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class ExchangeRateDirection {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "ExchangeRateDirection";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("ExchangeRateErrorReason", false)) {
/**
* The reasons for the target error.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class ExchangeRateErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "ExchangeRateError.Reason";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("ExchangeRateRefreshRate", false)) {
/**
* Determines at which rate the exchange rate is refreshed.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class ExchangeRateRefreshRate {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "ExchangeRateRefreshRate";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("FeatureErrorReason", false)) {
/**
* A feature is being used that is not enabled on the current network.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class FeatureErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "FeatureError.Reason";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("InternalApiErrorReason", false)) {
/**
* The single reason for the internal API error.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class InternalApiErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "InternalApiError.Reason";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("NotNullErrorReason", false)) {
/**
* The reasons for the target error.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class NotNullErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "NotNullError.Reason";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("ParseErrorReason", false)) {
/**
* The reasons for the target error.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class ParseErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "ParseError.Reason";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("PermissionErrorReason", false)) {
/**
* Describes reasons for permission errors.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class PermissionErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "PermissionError.Reason";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("PublisherQueryLanguageContextErrorReason", false)) {
/**
* The reasons for the target error.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class PublisherQueryLanguageContextErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "PublisherQueryLanguageContextError.Reason";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("PublisherQueryLanguageSyntaxErrorReason", false)) {
/**
* The reasons for the target error.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class PublisherQueryLanguageSyntaxErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "PublisherQueryLanguageSyntaxError.Reason";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("QuotaErrorReason", false)) {
/**
* The number of requests made per second is too high and has exceeded the
* allowable limit. The recommended approach to handle this error is to wait
* about 5 seconds and then retry the request. Note that this does not
* guarantee the request will succeed. If it fails again, try increasing the
* wait time.
* <p>
* Another way to mitigate this error is to limit requests to 2 per second for
* Small Business networks, or 8 per second for Premium networks. Once again
* this does not guarantee that every request will succeed, but may help
* reduce the number of times you receive this error.
* </p>
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class QuotaErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "QuotaError.Reason";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("RequiredCollectionErrorReason", false)) {
/**
* A required collection is missing.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class RequiredCollectionErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "RequiredCollectionError.Reason";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("RequiredErrorReason", false)) {
/**
* The reasons for the target error.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class RequiredErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "RequiredError.Reason";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("RequiredNumberErrorReason", false)) {
/**
* Describes reasons for a number to be invalid.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class RequiredNumberErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "RequiredNumberError.Reason";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("ServerErrorReason", false)) {
/**
* Describes reasons for server errors
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class ServerErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "ServerError.Reason";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("StatementErrorReason", false)) {
/**
* A bind variable has not been bound to a value.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class StatementErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "StatementError.Reason";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("StringLengthErrorReason", false)) {
/**
* The value returned if the actual value is not exposed by the requested API version.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class StringLengthErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "StringLengthError.Reason";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("CreateExchangeRates", false)) {
/**
* Creates new {@link ExchangeRate} objects.
*
* For each exchange rate, the following fields are required:
* <ul>
* <li>{@link ExchangeRate#currencyCode}</li>
* <li>{@link ExchangeRate#exchangeRate} when {@link ExchangeRate#refreshRate} is
* {@link ExchangeRateRefreshRate#FIXED}</li>
* </ul>
*
* @param exchangeRates the exchange rates to create
* @return the created exchange rates with their exchange rate values filled in
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class CreateExchangeRates {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "";
/**
* @access public
* @var ExchangeRate[]
*/
public $exchangeRates;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($exchangeRates = null) {
$this->exchangeRates = $exchangeRates;
}
}
}
if (!class_exists("CreateExchangeRatesResponse", false)) {
/**
*
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class CreateExchangeRatesResponse {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "";
/**
* @access public
* @var ExchangeRate[]
*/
public $rval;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($rval = null) {
$this->rval = $rval;
}
}
}
if (!class_exists("GetExchangeRatesByStatement", false)) {
/**
* Gets a {@link ExchangeRatePage} of {@link ExchangeRate} objects that satisfy the given
* {@link Statement#query}. The following fields are supported for filtering:
*
* <table>
* <tr>
* <th scope="col">PQL Property</th> <th scope="col">Object Property</th>
* </tr>
* <tr>
* <td>{@code id}</td>
* <td>{@link ExchangeRate#id}</td>
* </tr>
* <tr>
* <td>{@code currencyCode}</td>
* <td>{@link ExchangeRate#currencyCode}</td>
* </tr>
* <tr>
* <td>{@code refreshRate}</td>
* <td>{@link ExchangeRate#refreshRate}</td>
* </tr>
* <tr>
* <td>{@code direction}</td>
* <td>{@link ExchangeRate#direction}</td>
* </tr>
* <tr>
* <td>{@code exchangeRate}</td>
* <td>{@link ExchangeRate#exchangeRate}</td>
* </tr>
* </table>
*
* @param filterStatement a Publisher Query Language statement used to filter
* a set of exchange rates
* @return the exchange rates that match the given filter
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class GetExchangeRatesByStatement {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "";
/**
* @access public
* @var Statement
*/
public $filterStatement;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($filterStatement = null) {
$this->filterStatement = $filterStatement;
}
}
}
if (!class_exists("GetExchangeRatesByStatementResponse", false)) {
/**
*
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class GetExchangeRatesByStatementResponse {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "";
/**
* @access public
* @var ExchangeRatePage
*/
public $rval;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($rval = null) {
$this->rval = $rval;
}
}
}
if (!class_exists("PerformExchangeRateAction", false)) {
/**
* Performs an action on {@link ExchangeRate} objects that satisfy the given
* {@link Statement#query}. The following fields are supported for filtering:
*
* <table>
* <tr>
* <th scope="col">PQL Property</th> <th scope="col">Object Property</th>
* </tr>
* <tr>
* <td>{@code id}</td>
* <td>{@link ExchangeRate#id}</td>
* </tr>
* <tr>
* <td>{@code currencyCode}</td>
* <td>{@link ExchangeRate#currencyCode}</td>
* </tr>
* <tr>
* <td>{@code refreshRate}</td>
* <td>{@link ExchangeRate#refreshRate}</td>
* </tr>
* <tr>
* <td>{@code direction}</td>
* <td>{@link ExchangeRate#direction}</td>
* </tr>
* <tr>
* <td>{@code exchangeRate}</td>
* <td>{@link ExchangeRate#exchangeRate}</td>
* </tr>
* </table>
*
* @param exchangeRateAction the action to perform
* @param filterStatement a Publisher Query Language statement used to filter
* a set of exchange rates
* @return the result of the action performed
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class PerformExchangeRateAction {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "";
/**
* @access public
* @var ExchangeRateAction
*/
public $exchangeRateAction;
/**
* @access public
* @var Statement
*/
public $filterStatement;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($exchangeRateAction = null, $filterStatement = null) {
$this->exchangeRateAction = $exchangeRateAction;
$this->filterStatement = $filterStatement;
}
}
}
if (!class_exists("PerformExchangeRateActionResponse", false)) {
/**
*
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class PerformExchangeRateActionResponse {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "";
/**
* @access public
* @var UpdateResult
*/
public $rval;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($rval = null) {
$this->rval = $rval;
}
}
}
if (!class_exists("UpdateExchangeRates", false)) {
/**
* Updates the specified {@link ExchangeRate} objects.
*
* @param exchangeRates the exchange rates to update
* @return the updated exchange rates
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class UpdateExchangeRates {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "";
/**
* @access public
* @var ExchangeRate[]
*/
public $exchangeRates;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($exchangeRates = null) {
$this->exchangeRates = $exchangeRates;
}
}
}
if (!class_exists("UpdateExchangeRatesResponse", false)) {
/**
*
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class UpdateExchangeRatesResponse {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "";
/**
* @access public
* @var ExchangeRate[]
*/
public $rval;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($rval = null) {
$this->rval = $rval;
}
}
}
if (!class_exists("ObjectValue", false)) {
/**
* Contains an object value.
* <p>
* <b>This object is experimental!
* <code>ObjectValue</code> is an experimental, innovative, and rapidly
* changing new feature for DFP. Unfortunately, being on the bleeding edge means that we may make
* backwards-incompatible changes to
* <code>ObjectValue</code>. We will inform the community when this feature
* is no longer experimental.</b>
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class ObjectValue extends Value {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "ObjectValue";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
parent::__construct();
}
}
}
if (!class_exists("ApiException", false)) {
/**
* Exception class for holding a list of service errors.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class ApiException extends ApplicationException {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "ApiException";
/**
* @access public
* @var ApiError[]
*/
public $errors;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($errors = null, $message = null) {
parent::__construct();
$this->errors = $errors;
$this->message = $message;
}
}
}
if (!class_exists("BooleanValue", false)) {
/**
* Contains a boolean value.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class BooleanValue extends Value {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "BooleanValue";
/**
* @access public
* @var boolean
*/
public $value;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($value = null) {
parent::__construct();
$this->value = $value;
}
}
}
if (!class_exists("DateTimeValue", false)) {
/**
* Contains a date-time value.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class DateTimeValue extends Value {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "DateTimeValue";
/**
* @access public
* @var DateTime
*/
public $value;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($value = null) {
parent::__construct();
$this->value = $value;
}
}
}
if (!class_exists("DateValue", false)) {
/**
* Contains a date value.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class DateValue extends Value {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "DateValue";
/**
* @access public
* @var Date
*/
public $value;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($value = null) {
parent::__construct();
$this->value = $value;
}
}
}
if (!class_exists("DeleteExchangeRates", false)) {
/**
* The action used to delete {@link ExchangeRate} objects.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class DeleteExchangeRates extends ExchangeRateAction {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "DeleteExchangeRates";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
parent::__construct();
}
}
}
if (!class_exists("NumberValue", false)) {
/**
* Contains a numeric value.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class NumberValue extends Value {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "NumberValue";
/**
* @access public
* @var string
*/
public $value;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($value = null) {
parent::__construct();
$this->value = $value;
}
}
}
if (!class_exists("SetValue", false)) {
/**
* Contains a set of {@link Value Values}. May not contain duplicates.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class SetValue extends Value {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "SetValue";
/**
* @access public
* @var Value[]
*/
public $values;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($values = null) {
parent::__construct();
$this->values = $values;
}
}
}
if (!class_exists("TextValue", false)) {
/**
* Contains a string value.
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class TextValue extends Value {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const XSI_TYPE = "TextValue";
/**
* @access public
* @var string
*/
public $value;
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($value = null) {
parent::__construct();
$this->value = $value;
}
}
}
if (!class_exists("ExchangeRateService", false)) {
/**
* ExchangeRateService
* @package GoogleApiAdsDfp
* @subpackage v201605
*/
class ExchangeRateService extends DfpSoapClient {
const SERVICE_NAME = "ExchangeRateService";
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201605";
const ENDPOINT = "https://ads.google.com/apis/ads/publisher/v201605/ExchangeRateService";
/**
* The endpoint of the service
* @var string
*/
public static $endpoint = "https://ads.google.com/apis/ads/publisher/v201605/ExchangeRateService";
/**
* Default class map for wsdl=>php
* @access private
* @var array
*/
public static $classmap = array(
"ObjectValue" => "ObjectValue",
"ApiError" => "ApiError",
"ApiException" => "ApiException",
"ApiVersionError" => "ApiVersionError",
"ApplicationException" => "ApplicationException",
"AuthenticationError" => "AuthenticationError",
"BooleanValue" => "BooleanValue",
"CollectionSizeError" => "CollectionSizeError",
"CommonError" => "CommonError",
"Date" => "Date",
"DateTime" => "DfpDateTime",
"DateTimeValue" => "DateTimeValue",
"DateValue" => "DateValue",
"DeleteExchangeRates" => "DeleteExchangeRates",
"ExchangeRateAction" => "ExchangeRateAction",
"ExchangeRate" => "ExchangeRate",
"ExchangeRateError" => "ExchangeRateError",
"ExchangeRatePage" => "ExchangeRatePage",
"FeatureError" => "FeatureError",
"InternalApiError" => "InternalApiError",
"NotNullError" => "NotNullError",
"NumberValue" => "NumberValue",
"ParseError" => "ParseError",
"PermissionError" => "PermissionError",
"PublisherQueryLanguageContextError" => "PublisherQueryLanguageContextError",
"PublisherQueryLanguageSyntaxError" => "PublisherQueryLanguageSyntaxError",
"QuotaError" => "QuotaError",
"RequiredCollectionError" => "RequiredCollectionError",
"RequiredError" => "RequiredError",
"RequiredNumberError" => "RequiredNumberError",
"ServerError" => "ServerError",
"SetValue" => "SetValue",
"SoapRequestHeader" => "SoapRequestHeader",
"SoapResponseHeader" => "SoapResponseHeader",
"Statement" => "Statement",
"StatementError" => "StatementError",
"StringLengthError" => "StringLengthError",
"String_ValueMapEntry" => "String_ValueMapEntry",
"TextValue" => "TextValue",
"UniqueError" => "UniqueError",
"UpdateResult" => "UpdateResult",
"Value" => "Value",
"ApiVersionError.Reason" => "ApiVersionErrorReason",
"AuthenticationError.Reason" => "AuthenticationErrorReason",
"CollectionSizeError.Reason" => "CollectionSizeErrorReason",
"CommonError.Reason" => "CommonErrorReason",
"ExchangeRateDirection" => "ExchangeRateDirection",
"ExchangeRateError.Reason" => "ExchangeRateErrorReason",
"ExchangeRateRefreshRate" => "ExchangeRateRefreshRate",
"FeatureError.Reason" => "FeatureErrorReason",
"InternalApiError.Reason" => "InternalApiErrorReason",
"NotNullError.Reason" => "NotNullErrorReason",
"ParseError.Reason" => "ParseErrorReason",
"PermissionError.Reason" => "PermissionErrorReason",
"PublisherQueryLanguageContextError.Reason" => "PublisherQueryLanguageContextErrorReason",
"PublisherQueryLanguageSyntaxError.Reason" => "PublisherQueryLanguageSyntaxErrorReason",
"QuotaError.Reason" => "QuotaErrorReason",
"RequiredCollectionError.Reason" => "RequiredCollectionErrorReason",
"RequiredError.Reason" => "RequiredErrorReason",
"RequiredNumberError.Reason" => "RequiredNumberErrorReason",
"ServerError.Reason" => "ServerErrorReason",
"StatementError.Reason" => "StatementErrorReason",
"StringLengthError.Reason" => "StringLengthErrorReason",
"createExchangeRates" => "CreateExchangeRates",
"createExchangeRatesResponse" => "CreateExchangeRatesResponse",
"getExchangeRatesByStatement" => "GetExchangeRatesByStatement",
"getExchangeRatesByStatementResponse" => "GetExchangeRatesByStatementResponse",
"performExchangeRateAction" => "PerformExchangeRateAction",
"performExchangeRateActionResponse" => "PerformExchangeRateActionResponse",
"updateExchangeRates" => "UpdateExchangeRates",
"updateExchangeRatesResponse" => "UpdateExchangeRatesResponse",
);
/**
* Constructor using wsdl location and options array
* @param string $wsdl WSDL location for this service
* @param array $options Options for the SoapClient
*/
public function __construct($wsdl, $options, $user) {
$options["classmap"] = self::$classmap;
parent::__construct($wsdl, $options, $user, self::SERVICE_NAME,
self::WSDL_NAMESPACE);
}
/**
* Creates new {@link ExchangeRate} objects.
*
* For each exchange rate, the following fields are required:
* <ul>
* <li>{@link ExchangeRate#currencyCode}</li>
* <li>{@link ExchangeRate#exchangeRate} when {@link ExchangeRate#refreshRate} is
* {@link ExchangeRateRefreshRate#FIXED}</li>
* </ul>
*
* @param exchangeRates the exchange rates to create
* @return the created exchange rates with their exchange rate values filled in
*/
public function createExchangeRates($exchangeRates) {
$args = new CreateExchangeRates($exchangeRates);
$result = $this->__soapCall("createExchangeRates", array($args));
return $result->rval;
}
/**
* Gets a {@link ExchangeRatePage} of {@link ExchangeRate} objects that satisfy the given
* {@link Statement#query}. The following fields are supported for filtering:
*
* <table>
* <tr>
* <th scope="col">PQL Property</th> <th scope="col">Object Property</th>
* </tr>
* <tr>
* <td>{@code id}</td>
* <td>{@link ExchangeRate#id}</td>
* </tr>
* <tr>
* <td>{@code currencyCode}</td>
* <td>{@link ExchangeRate#currencyCode}</td>
* </tr>
* <tr>
* <td>{@code refreshRate}</td>
* <td>{@link ExchangeRate#refreshRate}</td>
* </tr>
* <tr>
* <td>{@code direction}</td>
* <td>{@link ExchangeRate#direction}</td>
* </tr>
* <tr>
* <td>{@code exchangeRate}</td>
* <td>{@link ExchangeRate#exchangeRate}</td>
* </tr>
* </table>
*
* @param filterStatement a Publisher Query Language statement used to filter
* a set of exchange rates
* @return the exchange rates that match the given filter
*/
public function getExchangeRatesByStatement($filterStatement) {
$args = new GetExchangeRatesByStatement($filterStatement);
$result = $this->__soapCall("getExchangeRatesByStatement", array($args));
return $result->rval;
}
/**
* Performs an action on {@link ExchangeRate} objects that satisfy the given
* {@link Statement#query}. The following fields are supported for filtering:
*
* <table>
* <tr>
* <th scope="col">PQL Property</th> <th scope="col">Object Property</th>
* </tr>
* <tr>
* <td>{@code id}</td>
* <td>{@link ExchangeRate#id}</td>
* </tr>
* <tr>
* <td>{@code currencyCode}</td>
* <td>{@link ExchangeRate#currencyCode}</td>
* </tr>
* <tr>
* <td>{@code refreshRate}</td>
* <td>{@link ExchangeRate#refreshRate}</td>
* </tr>
* <tr>
* <td>{@code direction}</td>
* <td>{@link ExchangeRate#direction}</td>
* </tr>
* <tr>
* <td>{@code exchangeRate}</td>
* <td>{@link ExchangeRate#exchangeRate}</td>
* </tr>
* </table>
*
* @param exchangeRateAction the action to perform
* @param filterStatement a Publisher Query Language statement used to filter
* a set of exchange rates
* @return the result of the action performed
*/
public function performExchangeRateAction($exchangeRateAction, $filterStatement) {
$args = new PerformExchangeRateAction($exchangeRateAction, $filterStatement);
$result = $this->__soapCall("performExchangeRateAction", array($args));
return $result->rval;
}
/**
* Updates the specified {@link ExchangeRate} objects.
*
* @param exchangeRates the exchange rates to update
* @return the updated exchange rates
*/
public function updateExchangeRates($exchangeRates) {
$args = new UpdateExchangeRates($exchangeRates);
$result = $this->__soapCall("updateExchangeRates", array($args));
return $result->rval;
}
}
}
| gamejolt/googleads-php-lib | src/Google/Api/Ads/Dfp/v201605/ExchangeRateService.php | PHP | apache-2.0 | 81,385 |
# This migration comes from grocer (originally 20170119220038)
class CreateGrocerExports < ActiveRecord::Migration[5.0]
def change
create_table :grocer_exports do |t|
t.string :pid
t.integer :job
t.string :status
t.datetime :last_error
t.datetime :last_success
t.string :logfile
t.timestamps
end
add_index :grocer_exports, :pid, unique: true
end
end
| pulibrary/plum | db/migrate/20170127153850_create_grocer_exports.grocer.rb | Ruby | apache-2.0 | 409 |
class TreeBuilderTenants < TreeBuilder
has_kids_for Tenant, [:x_get_tree_tenant_kids]
def initialize(name, sandbox, build, **params)
@additional_tenants = params[:additional_tenants]
@selectable = params[:selectable]
@ansible_playbook = params[:ansible_playbook]
@catalog_bundle = params[:catalog_bundle]
super(name, sandbox, build)
end
private
def tree_init_options
{
:checkboxes => true,
:check_url => "/catalog/#{cat_item_or_bundle}/",
:open_all => false,
:oncheck => @selectable ? tenant_tree_or_generic : nil,
:post_check => true,
:three_checks => true
}.compact
end
def tenant_tree_or_generic
if @ansible_playbook
'miqOnCheckTenantTree'
else
'miqOnCheckGeneric'
end
end
def cat_item_or_bundle
if @catalog_bundle
'st_form_field_changed'
else
'atomic_form_field_changed'
end
end
def root_options
text = _('All Tenants')
{
:text => text,
:tooltip => text,
:icon => 'pficon pficon-tenant',
:hideCheckbox => true
}
end
def x_get_tree_roots
if ApplicationHelper.role_allows?(:feature => 'rbac_tenant_view')
Tenant.with_current_tenant
end
end
def x_get_tree_tenant_kids(object, count_only)
count_only_or_objects(count_only, object.children, 'name')
end
def override(node, object)
node.checked = @additional_tenants.try(:include?, object)
node.checkable = @selectable
end
end
| ManageIQ/manageiq-ui-classic | app/presenters/tree_builder_tenants.rb | Ruby | apache-2.0 | 1,530 |
import {NgModule} from '@angular/core';
import {TestimonialService} from "./testimonial.service";
import {TestimonialEditorComponent} from "./testimonial-editor.component";
import {TestimonialComponent} from "./testimonial-list.component";
import {TestimonialRouting} from './testimonial.route';
import {SharedModule} from '../../../shared/shared.module';
import { XhrService } from '../../../shared/services/xhr.service';
@NgModule({
imports: [SharedModule.forRoot(),TestimonialRouting],
declarations: [TestimonialComponent, TestimonialEditorComponent],
providers: [TestimonialService, XhrService]
})
export class TestimonialModule {
} | nodebeats/nodebeats | admin/src/admin-app/dashboard-app/components/testimonial/testimonial.module.ts | TypeScript | apache-2.0 | 655 |
class Solution:
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
"""
arr_pre_order = preorder.split(',')
stack = []
for node in arr_pre_order:
stack.append(node)
while len(stack) > 1 and stack[-1] == '#' and stack[-2] == '#':
stack.pop()
stack.pop()
if len(stack) < 1:
return False
stack[-1] = '#'
if len(stack) == 1 and stack[0] == '#':
return True
return False
| MingfeiPan/leetcode | stack/331.py | Python | apache-2.0 | 615 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: violinsolo
# Created on 08/03/2018
import tensorflow as tf
import numpy as np
x_shape = [5, 3, 3, 2]
x = np.arange(reduce(lambda t, s: t*s, list(x_shape), 1))
print x
x = x.reshape([5, 3, 3, -1])
print x.shape
X = tf.Variable(x)
with tf.Session() as sess:
m = tf.nn.moments(X, axes=[0])
# m = tf.nn.moments(X, axes=[0,1])
# m = tf.nn.moments(X, axes=np.arange(len(x_shape)-1))
mean, variance = m
print(sess.run(m, feed_dict={X: x}))
# print(sess.run(m, feed_dict={X: x})) | iViolinSolo/DeepLearning-GetStarted | TF-Persion-ReID/test/test_tf_nn_moments.py | Python | apache-2.0 | 557 |
package com.blp.minotaurus.utils;
import com.blp.minotaurus.Minotaurus;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.plugin.RegisteredServiceProvider;
/**
* @author TheJeterLP
*/
public class EconomyManager {
private static Economy econ = null;
public static boolean setupEconomy() {
if (!Minotaurus.getInstance().getServer().getPluginManager().isPluginEnabled("Vault")) return false;
RegisteredServiceProvider<Economy> rsp = Bukkit.getServicesManager().getRegistration(Economy.class);
if (rsp == null || rsp.getProvider() == null) return false;
econ = rsp.getProvider();
return true;
}
public static Economy getEcon() {
return econ;
}
}
| BossLetsPlays/Minotaurus | src/main/java/com/blp/minotaurus/utils/EconomyManager.java | Java | apache-2.0 | 756 |
package eas.com;
public interface SomeInterface {
String someMethod(String param1, String param2, String param3, String param4);
}
| xalfonso/res_java | java-reflection-method/src/main/java/eas/com/SomeInterface.java | Java | apache-2.0 | 137 |
'use strict';
angular.module('donetexampleApp')
.service('ParseLinks', function () {
this.parse = function (header) {
if (header.length == 0) {
throw new Error("input must not be of zero length");
}
// Split parts by comma
var parts = header.split(',');
var links = {};
// Parse each part into a named link
angular.forEach(parts, function (p) {
var section = p.split(';');
if (section.length != 2) {
throw new Error("section could not be split on ';'");
}
var url = section[0].replace(/<(.*)>/, '$1').trim();
var queryString = {};
url.replace(
new RegExp("([^?=&]+)(=([^&]*))?", "g"),
function($0, $1, $2, $3) { queryString[$1] = $3; }
);
var page = queryString['page'];
if( angular.isString(page) ) {
page = parseInt(page);
}
var name = section[1].replace(/rel="(.*)"/, '$1').trim();
links[name] = page;
});
return links;
}
});
| CyberCastle/DoNetExample | DoNetExample.Gui/scripts/components/util/parse-links.service.js | JavaScript | apache-2.0 | 1,252 |
package com.mobisys.musicplayer.model;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by Govinda P on 6/3/2016.
*/
public class MusicFile implements Parcelable {
private String title;
private String album;
private String id;
private String singer;
private String path;
public MusicFile() {
}
public MusicFile(String title, String album, String id, String singer, String path) {
this.title = title;
this.album = album;
this.id = id;
this.singer = singer;
this.path = path;
}
protected MusicFile(Parcel in) {
title = in.readString();
album = in.readString();
id = in.readString();
singer = in.readString();
path=in.readString();
}
public static final Creator<MusicFile> CREATOR = new Creator<MusicFile>() {
@Override
public MusicFile createFromParcel(Parcel in) {
return new MusicFile(in);
}
@Override
public MusicFile[] newArray(int size) {
return new MusicFile[size];
}
};
public String getTitle() {
return title;
}
public String getAlbum() {
return album;
}
public String getId() {
return id;
}
public String getSinger() {
return singer;
}
public void setTitle(String title) {
this.title = title;
}
public void setAlbum(String album) {
this.album = album;
}
public void setId(String id) {
this.id = id;
}
public void setSinger(String singer) {
this.singer = singer;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
@Override
public String toString() {
return "MusicFile{" +
"title='" + title + '\'' +
", album='" + album + '\'' +
", id='" + id + '\'' +
", singer='" + singer + '\'' +
", path='" + path + '\'' +
'}';
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(album);
dest.writeString(id);
dest.writeString(singer);
dest.writeString(path);
}
}
| GovindaPaliwal/android-constraint-Layout | app/src/main/java/com/mobisys/musicplayer/model/MusicFile.java | Java | apache-2.0 | 2,408 |
<?php
/**********************************************************************************************************************************
*
* Ajax Payment System
*
* Author: Webbu Design
*
***********************************************************************************************************************************/
add_action( 'PF_AJAX_HANDLER_pfget_itemsystem', 'pf_ajax_itemsystem' );
add_action( 'PF_AJAX_HANDLER_nopriv_pfget_itemsystem', 'pf_ajax_itemsystem' );
function pf_ajax_itemsystem(){
check_ajax_referer( 'pfget_itemsystem', 'security');
header('Content-Type: application/json; charset=UTF-8;');
/* Get form variables */
if(isset($_POST['formtype']) && $_POST['formtype']!=''){
$formtype = $processname = esc_attr($_POST['formtype']);
}
/* Get data*/
$vars = array();
if(isset($_POST['dt']) && $_POST['dt']!=''){
if ($formtype == 'delete') {
$pid = sanitize_text_field($_POST['dt']);
}else{
$vars = array();
parse_str($_POST['dt'], $vars);
if (is_array($vars)) {
$vars = PFCleanArrayAttr('PFCleanFilters',$vars);
} else {
$vars = esc_attr($vars);
}
}
}
/* WPML Fix */
$lang_c = '';
if(isset($_POST['lang']) && $_POST['lang']!=''){
$lang_c = sanitize_text_field($_POST['lang']);
}
if(function_exists('icl_object_id')) {
global $sitepress;
if (isset($sitepress) && !empty($lang_c)) {
$sitepress->switch_lang($lang_c);
}
}
$current_user = wp_get_current_user();
$user_id = $current_user->ID;
$returnval = $errorval = $pfreturn_url = $msg_output = $overlay_add = $sccval = '';
$icon_processout = 62;
$setup3_pointposttype_pt1 = PFSAIssetControl('setup3_pointposttype_pt1','','pfitemfinder');
if ($formtype == 'delete') {
/**
*Start: Delete Item for PPP/Membership
**/
if($user_id != 0){
$delete_postid = (is_numeric($pid))? $pid:'';
if ($delete_postid != '') {
$old_status_featured = false;
$setup4_membersettings_paymentsystem = PFSAIssetControl('setup4_membersettings_paymentsystem','','1');
if ($setup4_membersettings_paymentsystem == 2) {
/*Check if item user s item*/
global $wpdb;
$result = $wpdb->get_results( $wpdb->prepare(
"SELECT ID, post_author FROM $wpdb->posts WHERE ID = %s and post_author = %s and post_type = %s",
$delete_postid,
$user_id,
$setup3_pointposttype_pt1
) );
if (is_array($result) && count($result)>0) {
if ($result[0]->ID == $delete_postid) {
$delete_item_images = get_post_meta($delete_postid, 'webbupointfinder_item_images');
if (!empty($delete_item_images)) {
foreach ($delete_item_images as $item_image) {
wp_delete_attachment(esc_attr($item_image),true);
}
}
wp_delete_attachment(get_post_thumbnail_id( $delete_postid ),true);
$old_status_featured = get_post_meta( $delete_postid, 'webbupointfinder_item_featuredmarker', true );
wp_delete_post($delete_postid);
$membership_user_activeorder = get_user_meta( $user_id, 'membership_user_activeorder', true );
/* - Creating record for process system. */
PFCreateProcessRecord(
array(
'user_id' => $user_id,
'item_post_id' => $membership_user_activeorder,
'processname' => esc_html__('Item deleted by USER.','pointfindert2d'),
'membership' => 1
)
);
/* - Create a record for payment system. */
$sccval .= esc_html__('Item successfully deleted. Refreshing...','pointfindert2d');
}
}else{
$icon_processout = 485;
$errorval .= esc_html__('Wrong item ID or already deleted. Item can not delete.','pointfindert2d');
}
/*Membership limits for item /featured limit*/
$membership_user_item_limit = get_user_meta( $user_id, 'membership_user_item_limit', true );
$membership_user_featureditem_limit = get_user_meta( $user_id, 'membership_user_featureditem_limit', true );
$membership_user_package_id = get_user_meta( $user_id, 'membership_user_package_id', true );
$packageinfox = pointfinder_membership_package_details_get($membership_user_package_id);
if ($membership_user_item_limit == -1) {
/* Do nothing... */
}else{
if ($membership_user_item_limit >= 0) {
$membership_user_item_limit = $membership_user_item_limit + 1;
if ($membership_user_item_limit <= $packageinfox['webbupointfinder_mp_itemnumber']) {
update_user_meta( $user_id, 'membership_user_item_limit', $membership_user_item_limit);
}
}
}
if($old_status_featured != false && $old_status_featured != 0){
$membership_user_featureditem_limit = $membership_user_featureditem_limit + 1;
if ($membership_user_featureditem_limit <= $packageinfox['webbupointfinder_mp_fitemnumber']) {
update_user_meta( $user_id, 'membership_user_featureditem_limit', $membership_user_featureditem_limit);
}
}
} else {
/*Check if item user s item*/
global $wpdb;
$result = $wpdb->get_results( $wpdb->prepare(
"SELECT ID, post_author FROM $wpdb->posts WHERE ID = %s and post_author = %s and post_type = %s",
$delete_postid,
$user_id,
$setup3_pointposttype_pt1
) );
$result_id = $wpdb->get_var( $wpdb->prepare(
"SELECT post_id FROM $wpdb->postmeta WHERE meta_key = %s and meta_value = %s",
'pointfinder_order_itemid',
$delete_postid
) );
$pointfinder_order_recurring = esc_attr(get_post_meta( $result_id, 'pointfinder_order_recurring', true ));
if($pointfinder_order_recurring == 1){
$pointfinder_order_recurringid = esc_attr(get_post_meta( $result_id, 'pointfinder_order_recurringid', true ));
PF_Cancel_recurring_payment(
array(
'user_id' => $user_id,
'profile_id' => $pointfinder_order_recurringid,
'item_post_id' => $delete_postid,
'order_post_id' => $result_id,
)
);
}
if (is_array($result) && count($result)>0) {
if ($result[0]->ID == $delete_postid) {
$delete_item_images = get_post_meta($delete_postid, 'webbupointfinder_item_images');
if (!empty($delete_item_images)) {
foreach ($delete_item_images as $item_image) {
wp_delete_attachment(esc_attr($item_image),true);
}
}
wp_delete_attachment(get_post_thumbnail_id( $delete_postid ),true);
wp_delete_post($delete_postid);
/* - Creating record for process system. */
PFCreateProcessRecord(
array(
'user_id' => $user_id,
'item_post_id' => $delete_postid,
'processname' => esc_html__('Item deleted by USER.','pointfindert2d')
)
);
/* - Create a record for payment system. */
$sccval .= esc_html__('Item successfully deleted. Refreshing...','pointfindert2d');
}
}else{
$icon_processout = 485;
$errorval .= esc_html__('Wrong item ID (Not your item!). Item can not delete.','pointfindert2d');
}
}
}else{
$icon_processout = 485;
$errorval .= esc_html__('Wrong item ID.','pointfindert2d');
}
}else{
$icon_processout = 485;
$errorval .= esc_html__('Please login again to upload/edit item (Invalid UserID).','pointfindert2d');
}
if (!empty($sccval)) {
$msg_output .= $sccval;
$overlay_add = ' pfoverlayapprove';
}elseif (!empty($errorval)) {
$msg_output .= $errorval;
}
/**
*End: Delete Item for PPP/Membership
**/
} else {
/**
*Start: New/Edit Item Form Request
**/
if(isset($_POST) && $_POST!='' && count($_POST)>0){
if($user_id != 0){
if($vars['action'] == 'pfget_edititem'){
if (isset($vars['edit_pid']) && !empty($vars['edit_pid'])) {
$edit_postid = $vars['edit_pid'];
global $wpdb;
$result = $wpdb->get_results( $wpdb->prepare(
"
SELECT ID, post_author
FROM $wpdb->posts
WHERE ID = %s and post_author = %s and post_type = %s
",
$edit_postid,
$user_id,
$setup3_pointposttype_pt1
) );
if (is_array($result) && count($result)>0) {
if ($result[0]->ID == $edit_postid) {
$returnval = PFU_AddorUpdateRecord(
array(
'post_id' => $edit_postid,
'order_post_id' => PFU_GetOrderID($edit_postid,1),
'order_title' => PFU_GetOrderID($edit_postid,0),
'vars' => $vars,
'user_id' => $user_id
)
);
}else{
$icon_processout = 485;
$errorval .= esc_html__('This is not your item.','pointfindert2d');
}
}else{
$icon_processout = 485;
$errorval .= esc_html__('Wrong Item ID','pointfindert2d');
}
}else{
$icon_processout = 485;
$errorval .= esc_html__('There is no item ID to edit.','pointfindert2d');
}
}elseif ($vars['action'] == 'pfget_uploaditem') {
$returnval = PFU_AddorUpdateRecord(
array(
'post_id' => '',
'order_post_id' => '',
'order_title' => '',
'vars' => $vars,
'user_id' => $user_id
)
);
}
}else{
$icon_processout = 485;
$errorval .= esc_html__('Please login again to upload/edit item (Invalid UserID).','pointfindert2d');
}
}
if (is_array($returnval) && !empty($returnval)) {
if (isset($returnval['sccval'])) {
$msg_output .= $returnval['sccval'];
$overlay_add = ' pfoverlayapprove';
}elseif (isset($returnval['errorval'])) {
$msg_output .= $returnval['errorval'];
}
}else{
$msg_output .= $errorval;
}
/**
*End: New/Edit Item Form Request
**/
}
$setup4_membersettings_dashboard = PFSAIssetControl('setup4_membersettings_dashboard','','');
$setup4_membersettings_dashboard_link = get_permalink($setup4_membersettings_dashboard);
$pfmenu_perout = PFPermalinkCheck();
$pfreturn_url = $setup4_membersettings_dashboard_link.$pfmenu_perout.'ua=myitems';
$output_html = '';
$output_html .= '<div class="golden-forms wrapper mini" style="height:200px">';
$output_html .= '<div id="pfmdcontainer-overlay" class="pftrwcontainer-overlay">';
$output_html .= "<div class='pf-overlay-close'><i class='pfadmicon-glyph-707'></i></div>";
$output_html .= "<div class='pfrevoverlaytext".$overlay_add."'><i class='pfadmicon-glyph-".$icon_processout."'></i><span>".$msg_output."</span></div>";
$output_html .= '</div>';
$output_html .= '</div>';
if (!empty($errorval)) {
echo json_encode(
array(
'process'=>false,
'processname'=>$processname,
'mes'=>$output_html,
'returnurl' => $pfreturn_url
)
);
}else{
echo json_encode(
array(
'process'=>true,
'processname'=>$processname,
'returnval'=>$returnval,
'mes'=>$output_html,
'returnurl' => $pfreturn_url
)
);
}
die();
}
?> | fedebalderas/esm_wordpress | wp-content/themes/pointfinder/admin/estatemanagement/includes/ajax/ajax-itemsystem.php | PHP | apache-2.0 | 12,874 |
//
// 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.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;
using NetworkCommsDotNet.DPSBase;
using NetworkCommsDotNet.Tools;
#if NETFX_CORE
using NetworkCommsDotNet.Tools.XPlatformHelper;
#else
using System.Net.Sockets;
#endif
#if WINDOWS_PHONE || NETFX_CORE
using Windows.Networking.Sockets;
using Windows.Networking;
using System.Runtime.InteropServices.WindowsRuntime;
#endif
namespace NetworkCommsDotNet.Connections.UDP
{
/// <summary>
/// A connection object which utilises <see href="http://en.wikipedia.org/wiki/User_Datagram_Protocol">UDP</see> to communicate between peers.
/// </summary>
public sealed partial class UDPConnection : IPConnection
{
#if WINDOWS_PHONE || NETFX_CORE
internal DatagramSocket socket;
#else
internal UdpClientWrapper udpClient;
#endif
/// <summary>
/// Options associated with this UDPConnection
/// </summary>
public UDPOptions ConnectionUDPOptions { get; private set; }
/// <summary>
/// An isolated UDP connection will only accept incoming packets coming from a specific RemoteEndPoint.
/// </summary>
bool isIsolatedUDPConnection = false;
/// <summary>
/// Internal constructor for UDP connections
/// </summary>
/// <param name="connectionInfo"></param>
/// <param name="defaultSendReceiveOptions"></param>
/// <param name="level"></param>
/// <param name="listenForIncomingPackets"></param>
/// <param name="existingConnection"></param>
internal UDPConnection(ConnectionInfo connectionInfo, SendReceiveOptions defaultSendReceiveOptions, UDPOptions level, bool listenForIncomingPackets, UDPConnection existingConnection = null)
: base(connectionInfo, defaultSendReceiveOptions)
{
if (connectionInfo.ConnectionType != ConnectionType.UDP)
throw new ArgumentException("Provided connectionType must be UDP.", "connectionInfo");
if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Creating new UDPConnection with " + connectionInfo);
if (connectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Disabled && level != UDPOptions.None)
throw new ArgumentException("If the application layer protocol has been disabled the provided UDPOptions can only be UDPOptions.None.");
ConnectionUDPOptions = level;
if (listenForIncomingPackets && existingConnection != null)
throw new Exception("Unable to listen for incoming packets if an existing client has been provided. This is to prevent possible multiple accidently listens on the same client.");
if (existingConnection == null)
{
if (connectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any) || connectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.IPv6Any))
{
#if WINDOWS_PHONE || NETFX_CORE
//We are creating an unbound endPoint, this is currently the rogue UDP sender and listeners only
socket = new DatagramSocket();
if (listenForIncomingPackets)
socket.MessageReceived += socket_MessageReceived;
socket.BindEndpointAsync(new HostName(ConnectionInfo.LocalIPEndPoint.Address.ToString()), ConnectionInfo.LocalIPEndPoint.Port.ToString()).AsTask().Wait();
#else
//We are creating an unbound endPoint, this is currently the rogue UDP sender and listeners only
udpClient = new UdpClientWrapper(new UdpClient(ConnectionInfo.LocalIPEndPoint));
#endif
}
else
{
//If this is a specific connection we link to a default end point here
isIsolatedUDPConnection = true;
#if WINDOWS_PHONE || NETFX_CORE
if (ConnectionInfo.LocalEndPoint == null ||
(ConnectionInfo.LocalIPEndPoint.Address == IPAddress.Any && connectionInfo.LocalIPEndPoint.Port == 0) ||
(ConnectionInfo.LocalIPEndPoint.Address == IPAddress.IPv6Any && connectionInfo.LocalIPEndPoint.Port == 0))
{
socket = new DatagramSocket();
if (listenForIncomingPackets)
socket.MessageReceived += socket_MessageReceived;
socket.ConnectAsync(new HostName(ConnectionInfo.RemoteIPEndPoint.Address.ToString()), ConnectionInfo.RemoteIPEndPoint.Port.ToString()).AsTask().Wait();
}
else
{
socket = new DatagramSocket();
if (listenForIncomingPackets)
socket.MessageReceived += socket_MessageReceived;
EndpointPair pair = new EndpointPair(new HostName(ConnectionInfo.LocalIPEndPoint.Address.ToString()), ConnectionInfo.LocalIPEndPoint.Port.ToString(),
new HostName(ConnectionInfo.RemoteIPEndPoint.Address.ToString()), ConnectionInfo.RemoteIPEndPoint.Port.ToString());
socket.ConnectAsync(pair).AsTask().Wait();
}
#else
if (ConnectionInfo.LocalEndPoint == null)
udpClient = new UdpClientWrapper(new UdpClient(ConnectionInfo.RemoteEndPoint.AddressFamily));
else
udpClient = new UdpClientWrapper(new UdpClient(ConnectionInfo.LocalIPEndPoint));
//By calling connect we discard packets from anything other then the provided remoteEndPoint on our localEndPoint
udpClient.Connect(ConnectionInfo.RemoteIPEndPoint);
#endif
}
#if !WINDOWS_PHONE && !NETFX_CORE
//NAT traversal does not work in .net 2.0
//Mono does not seem to have implemented AllowNatTraversal method and attempting the below method call will throw an exception
//if (Type.GetType("Mono.Runtime") == null)
//Allow NAT traversal by default for all udp clients
// udpClientThreadSafe.AllowNatTraversal(true);
if (listenForIncomingPackets)
StartIncomingDataListen();
#endif
}
else
{
if (!existingConnection.ConnectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any))
throw new Exception("If an existing udpClient is provided it must be unbound to a specific remoteEndPoint");
#if WINDOWS_PHONE || NETFX_CORE
//Using an exiting client allows us to send from the same port as for the provided existing connection
this.socket = existingConnection.socket;
#else
//Using an exiting client allows us to send from the same port as for the provided existing connection
this.udpClient = existingConnection.udpClient;
#endif
}
IPEndPoint localEndPoint;
#if WINDOWS_PHONE || NETFX_CORE
localEndPoint = new IPEndPoint(IPAddress.Parse(socket.Information.LocalAddress.DisplayName.ToString()), int.Parse(socket.Information.LocalPort));
#else
localEndPoint = udpClient.LocalIPEndPoint;
#endif
//We can update the localEndPoint so that it is correct
if (!ConnectionInfo.LocalEndPoint.Equals(localEndPoint))
{
//We should now be able to set the connectionInfo localEndPoint
NetworkComms.UpdateConnectionReferenceByEndPoint(this, ConnectionInfo.RemoteIPEndPoint, localEndPoint);
ConnectionInfo.UpdateLocalEndPointInfo(localEndPoint);
}
}
/// <inheritdoc />
protected override void EstablishConnectionSpecific()
{
//If the application layer protocol is enabled and the UDP option is set
if (ConnectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled &&
(ConnectionUDPOptions & UDPOptions.Handshake) == UDPOptions.Handshake)
ConnectionHandshake();
else
{
//If there is no handshake we can now consider the connection established
TriggerConnectionEstablishDelegates();
//Trigger any connection setup waits
connectionSetupWait.Set();
}
}
/// <inheritdoc />
protected override void CloseConnectionSpecific(bool closeDueToError, int logLocation = 0)
{
#if WINDOWS_PHONE || NETFX_CORE
//We only call close on the udpClient if this is a specific UDP connection or we are calling close from the parent UDP connection
if (socket != null && (isIsolatedUDPConnection || (ConnectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any))))
socket.Dispose();
#else
//We only call close on the udpClient if this is a specific UDP connection or we are calling close from the parent UDP connection
if (udpClient != null && (isIsolatedUDPConnection || (ConnectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any))))
udpClient.CloseClient();
#endif
}
/// <summary>
/// Send a packet to the specified ipEndPoint. This feature is unique to UDP because of its connectionless structure.
/// </summary>
/// <param name="packet">Packet to send</param>
/// <param name="ipEndPoint">The target ipEndPoint</param>
private void SendPacketSpecific<packetObjectType>(IPacket packet, IPEndPoint ipEndPoint)
{
#if FREETRIAL
if (ipEndPoint.Address == IPAddress.Broadcast)
throw new NotSupportedException("Unable to send UDP broadcast datagram using this version of NetworkComms.Net. Please purchase a commercial license from www.networkcomms.net which supports UDP broadcast datagrams.");
#endif
byte[] headerBytes = new byte[0];
if (ConnectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled)
{
long packetSequenceNumber;
lock (sendLocker)
{
//Set packet sequence number inside sendLocker
//Increment the global counter as well to ensure future connections with the same host can not create duplicates
Interlocked.Increment(ref NetworkComms.totalPacketSendCount);
packetSequenceNumber = packetSequenceCounter++;
packet.PacketHeader.SetOption(PacketHeaderLongItems.PacketSequenceNumber, packetSequenceNumber);
}
headerBytes = packet.SerialiseHeader(NetworkComms.InternalFixedSendReceiveOptions);
}
else
{
if (packet.PacketHeader.PacketType != Enum.GetName(typeof(ReservedPacketType), ReservedPacketType.Unmanaged))
throw new UnexpectedPacketTypeException("Only 'Unmanaged' packet types can be used if the NetworkComms.Net application layer protocol is disabled.");
if (packet.PacketData.Length == 0)
throw new NotSupportedException("Sending a zero length array if the NetworkComms.Net application layer protocol is disabled is not supported.");
}
//We are limited in size for the isolated send
if (headerBytes.Length + packet.PacketData.Length > maximumSingleDatagramSizeBytes)
throw new CommunicationException("Attempted to send a UDP packet whose serialised size was " + (headerBytes.Length + packet.PacketData.Length).ToString() + " bytes. The maximum size for a single UDP send is " + maximumSingleDatagramSizeBytes.ToString() + ". Consider using a TCP connection to send this object.");
if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Debug("Sending a UDP packet of type '" + packet.PacketHeader.PacketType + "' from " + ConnectionInfo.LocalIPEndPoint.Address + ":" + ConnectionInfo.LocalIPEndPoint.Port.ToString() + " to " + ipEndPoint.Address + ":" + ipEndPoint.Port.ToString() + " containing " + headerBytes.Length.ToString() + " header bytes and " + packet.PacketData.Length.ToString() + " payload bytes.");
//Prepare the single byte array to send
byte[] udpDatagram;
if (ConnectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled)
{
udpDatagram = packet.PacketData.ThreadSafeStream.ToArray(headerBytes.Length);
//Copy the header bytes into the datagram
Buffer.BlockCopy(headerBytes, 0, udpDatagram, 0, headerBytes.Length);
}
else
udpDatagram = packet.PacketData.ThreadSafeStream.ToArray();
#if WINDOWS_PHONE || NETFX_CORE
var getStreamTask = socket.GetOutputStreamAsync(new HostName(ipEndPoint.Address.ToString()), ipEndPoint.Port.ToString()).AsTask();
getStreamTask.Wait();
var outputStream = getStreamTask.Result;
outputStream.WriteAsync(WindowsRuntimeBufferExtensions.AsBuffer(udpDatagram)).AsTask().Wait();
outputStream.FlushAsync().AsTask().Wait();
#else
udpClient.Send(udpDatagram, udpDatagram.Length, ipEndPoint);
#endif
if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Completed send of a UDP packet of type '" + packet.PacketHeader.PacketType + "' from " + ConnectionInfo.LocalIPEndPoint.Address + ":" + ConnectionInfo.LocalIPEndPoint.Port.ToString() + " to " + ipEndPoint.Address + ":" + ipEndPoint.Port.ToString() + ".");
}
/// <inheritdoc />
protected override double[] SendStreams(StreamTools.StreamSendWrapper[] streamsToSend, double maxSendTimePerKB, long totalBytesToSend)
{
#if FREETRIAL
if (this.ConnectionInfo.RemoteEndPoint.Address == IPAddress.Broadcast)
throw new NotSupportedException("Unable to send UDP broadcast datagram using this version of NetworkComms.Net. Please purchase a commercial license from www.networkcomms.net which supports UDP broadcast datagrams.");
#endif
if (ConnectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any))
throw new CommunicationException("Unable to send packet using this method as remoteEndPoint equals IPAddress.Any");
if (totalBytesToSend > maximumSingleDatagramSizeBytes)
throw new CommunicationException("Attempted to send a UDP packet whose length is " + totalBytesToSend.ToString() + " bytes. The maximum size for a single UDP send is " + maximumSingleDatagramSizeBytes.ToString() + ". Consider using a TCP connection to send this object.");
byte[] udpDatagram = new byte[totalBytesToSend];
MemoryStream udpDatagramStream = new MemoryStream(udpDatagram, 0, udpDatagram.Length, true);
for (int i = 0; i < streamsToSend.Length; i++)
{
if (streamsToSend[i].Length > 0)
{
//Write each stream
streamsToSend[i].ThreadSafeStream.CopyTo(udpDatagramStream, streamsToSend[i].Start, streamsToSend[i].Length, NetworkComms.SendBufferSizeBytes, maxSendTimePerKB, MinSendTimeoutMS);
streamsToSend[i].ThreadSafeStream.Dispose();
}
}
DateTime startTime = DateTime.Now;
#if WINDOWS_PHONE || NETFX_CORE
var getStreamTask = socket.GetOutputStreamAsync(new HostName(ConnectionInfo.RemoteIPEndPoint.Address.ToString()), ConnectionInfo.RemoteIPEndPoint.Port.ToString()).AsTask();
getStreamTask.Wait();
var outputStream = getStreamTask.Result;
outputStream.WriteAsync(WindowsRuntimeBufferExtensions.AsBuffer(udpDatagram)).AsTask().Wait();
outputStream.FlushAsync().AsTask().Wait();
#else
udpClient.Send(udpDatagram, udpDatagram.Length, ConnectionInfo.RemoteIPEndPoint);
#endif
udpDatagramStream.Dispose();
//Calculate timings based on fractional byte length
double[] timings = new double[streamsToSend.Length];
double elapsedMS = (DateTime.Now - startTime).TotalMilliseconds;
for (int i = 0; i < streamsToSend.Length; i++)
timings[i] = elapsedMS * (streamsToSend[i].Length / (double)totalBytesToSend);
return timings;
}
/// <inheritdoc />
protected override void StartIncomingDataListen()
{
#if WINDOWS_PHONE || NETFX_CORE
throw new NotImplementedException("Not needed for UDP connections on Windows Phone 8");
#else
if (NetworkComms.ConnectionListenModeUseSync)
{
if (incomingDataListenThread == null)
{
incomingDataListenThread = new Thread(IncomingUDPPacketWorker);
incomingDataListenThread.Priority = NetworkComms.timeCriticalThreadPriority;
incomingDataListenThread.Name = "UDP_IncomingDataListener";
incomingDataListenThread.IsBackground = true;
incomingDataListenThread.Start();
}
}
else
{
if (asyncListenStarted) throw new ConnectionSetupException("Async listen already started. Why has this been called twice?.");
udpClient.BeginReceive(new AsyncCallback(IncomingUDPPacketHandler), udpClient);
asyncListenStarted = true;
}
#endif
}
#if WINDOWS_PHONE || NETFX_CORE
void socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
try
{
var stream = args.GetDataStream().AsStreamForRead();
var dataLength = args.GetDataReader().UnconsumedBufferLength;
byte[] receivedBytes = new byte[dataLength];
using (MemoryStream mem = new MemoryStream(receivedBytes))
stream.CopyTo(mem);
//Received data after comms shutdown initiated. We should just close the connection
if (NetworkComms.commsShutdown) CloseConnection(false, -15);
stream = null;
if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Received " + receivedBytes.Length + " bytes via UDP from " + args.RemoteAddress + ":" + args.RemotePort + ".");
UDPConnection connection;
HandshakeUDPDatagram possibleHandshakeUDPDatagram = new HandshakeUDPDatagram(receivedBytes);
if (isIsolatedUDPConnection)
//This connection was created for a specific remoteEndPoint so we can handle the data internally
connection = this;
else
{
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(args.RemoteAddress.DisplayName.ToString()), int.Parse(args.RemotePort));
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse(sender.Information.LocalAddress.DisplayName.ToString()), int.Parse(sender.Information.LocalPort));
ConnectionInfo desiredConnection = new ConnectionInfo(ConnectionType.UDP, remoteEndPoint, localEndPoint, ConnectionInfo.ApplicationLayerProtocol, ConnectionInfo.ConnectionListener);
try
{
//Look for an existing connection, if one does not exist we will create it
//This ensures that all further processing knows about the correct endPoint
connection = GetConnection(desiredConnection, ConnectionUDPOptions, ConnectionDefaultSendReceiveOptions, false, this, possibleHandshakeUDPDatagram);
}
catch (ConnectionShutdownException)
{
if ((ConnectionUDPOptions & UDPOptions.Handshake) == UDPOptions.Handshake)
{
if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Attempted to get connection " + desiredConnection + " but this caused a ConnectionShutdownException. Exception caught and ignored as should only happen if the connection was closed shortly after being created.");
connection = null;
}
else
throw;
}
}
if (connection != null && !possibleHandshakeUDPDatagram.DatagramHandled)
{
//We pass the data off to the specific connection
//Lock on the packetbuilder locker as we may receive UDP packets in parallel from this host
lock (connection.packetBuilder.Locker)
{
connection.packetBuilder.AddPartialPacket(receivedBytes.Length, receivedBytes);
if (connection.packetBuilder.TotalBytesCached > 0) connection.IncomingPacketHandleHandOff(connection.packetBuilder);
if (connection.packetBuilder.TotalPartialPacketCount > 0)
LogTools.LogException(new Exception("Packet builder had " + connection.packetBuilder.TotalBytesCached + " bytes remaining after a call to IncomingPacketHandleHandOff with connection " + connection.ConnectionInfo + ". Until sequenced packets are implemented this indicates a possible error."), "UDPConnectionError");
}
}
}
//On any error here we close the connection
catch (NullReferenceException)
{
CloseConnection(true, 25);
}
catch (ArgumentNullException)
{
CloseConnection(true, 38);
}
catch (IOException)
{
CloseConnection(true, 26);
}
catch (ObjectDisposedException)
{
CloseConnection(true, 27);
}
catch (SocketException)
{
//Receive may throw a SocketException ErrorCode=10054 after attempting to send a datagram to an unreachable target.
//We will try to get around this by ignoring the ICMP packet causing these problems on client creation
CloseConnection(true, 28);
}
catch (InvalidOperationException)
{
CloseConnection(true, 29);
}
catch (ConnectionSetupException)
{
//Can occur if data is received as comms is being shutdown.
//Method will attempt to create new connection which will throw ConnectionSetupException.
CloseConnection(true, 50);
}
catch (Exception ex)
{
LogTools.LogException(ex, "Error_UDPConnectionIncomingPacketHandler");
CloseConnection(true, 30);
}
}
#else
/// <summary>
/// Incoming data listen async method
/// </summary>
/// <param name="ar">Call back state data</param>
private void IncomingUDPPacketHandler(IAsyncResult ar)
{
try
{
UdpClientWrapper client = (UdpClientWrapper)ar.AsyncState;
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.None, 0);
byte[] receivedBytes = client.EndReceive(ar, ref remoteEndPoint);
//Received data after comms shutdown initiated. We should just close the connection
if (NetworkComms.commsShutdown) CloseConnection(false, -13);
if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Received " + receivedBytes.Length.ToString() + " bytes via UDP from " + remoteEndPoint.Address + ":" + remoteEndPoint.Port.ToString() + ".");
UDPConnection connection;
HandshakeUDPDatagram possibleHandshakeUDPDatagram = new HandshakeUDPDatagram(receivedBytes);
if (isIsolatedUDPConnection)
//This connection was created for a specific remoteEndPoint so we can handle the data internally
connection = this;
else
{
ConnectionInfo desiredConnection = new ConnectionInfo(ConnectionType.UDP, remoteEndPoint, udpClient.LocalIPEndPoint, ConnectionInfo.ApplicationLayerProtocol, ConnectionInfo.ConnectionListener);
try
{
//Look for an existing connection, if one does not exist we will create it
//This ensures that all further processing knows about the correct endPoint
connection = GetConnection(desiredConnection, ConnectionUDPOptions, ConnectionDefaultSendReceiveOptions, false, this, possibleHandshakeUDPDatagram);
}
catch (ConnectionShutdownException)
{
if ((ConnectionUDPOptions & UDPOptions.Handshake) == UDPOptions.Handshake)
{
if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Attempted to get connection " + desiredConnection + " but this caused a ConnectionShutdownException. Exception caught and ignored as should only happen if the connection was closed shortly after being created.");
connection = null;
}
else
throw;
}
}
if (connection != null && !possibleHandshakeUDPDatagram.DatagramHandled)
{
//We pass the data off to the specific connection
//Lock on the packetbuilder locker as we may receive UDP packets in parallel from this host
lock (connection.packetBuilder.Locker)
{
if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace(" ... " + receivedBytes.Length.ToString() + " bytes added to packetBuilder for " + connection.ConnectionInfo + ". Cached " + connection.packetBuilder.TotalBytesCached.ToString() + " bytes, expecting " + connection.packetBuilder.TotalBytesExpected.ToString() + " bytes.");
connection.packetBuilder.AddPartialPacket(receivedBytes.Length, receivedBytes);
if (connection.packetBuilder.TotalBytesCached > 0) connection.IncomingPacketHandleHandOff(connection.packetBuilder);
if (connection.packetBuilder.TotalPartialPacketCount > 0)
LogTools.LogException(new Exception("Packet builder had " + connection.packetBuilder.TotalBytesCached + " bytes remaining after a call to IncomingPacketHandleHandOff with connection " + connection.ConnectionInfo + ". Until sequenced packets are implemented this indicates a possible error."), "UDPConnectionError");
}
}
client.BeginReceive(new AsyncCallback(IncomingUDPPacketHandler), client);
}
//On any error here we close the connection
catch (NullReferenceException)
{
CloseConnection(true, 25);
}
catch (ArgumentNullException)
{
CloseConnection(true, 36);
}
catch (IOException)
{
CloseConnection(true, 26);
}
catch (ObjectDisposedException)
{
CloseConnection(true, 27);
}
catch (SocketException)
{
//Receive may throw a SocketException ErrorCode=10054 after attempting to send a datagram to an unreachable target.
//We will try to get around this by ignoring the ICMP packet causing these problems on client creation
CloseConnection(true, 28);
}
catch (InvalidOperationException)
{
CloseConnection(true, 29);
}
catch (ConnectionSetupException)
{
//Can occur if data is received as comms is being shutdown.
//Method will attempt to create new connection which will throw ConnectionSetupException.
CloseConnection(true, 50);
}
catch (Exception ex)
{
LogTools.LogException(ex, "Error_UDPConnectionIncomingPacketHandler");
CloseConnection(true, 30);
}
}
/// <summary>
/// Incoming data listen sync method
/// </summary>
private void IncomingUDPPacketWorker()
{
try
{
while (true)
{
if (ConnectionInfo.ConnectionState == ConnectionState.Shutdown)
break;
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.None, 0);
byte[] receivedBytes = udpClient.Receive(ref remoteEndPoint);
//Received data after comms shutdown initiated. We should just close the connection
if (NetworkComms.commsShutdown) CloseConnection(false, -14);
if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Received " + receivedBytes.Length.ToString() + " bytes via UDP from " + remoteEndPoint.Address + ":" + remoteEndPoint.Port.ToString() + ".");
UDPConnection connection;
HandshakeUDPDatagram possibleHandshakeUDPDatagram = new HandshakeUDPDatagram(receivedBytes);
if (isIsolatedUDPConnection)
//This connection was created for a specific remoteEndPoint so we can handle the data internally
connection = this;
else
{
ConnectionInfo desiredConnection = new ConnectionInfo(ConnectionType.UDP, remoteEndPoint, udpClient.LocalIPEndPoint, ConnectionInfo.ApplicationLayerProtocol, ConnectionInfo.ConnectionListener);
try
{
//Look for an existing connection, if one does not exist we will create it
//This ensures that all further processing knows about the correct endPoint
connection = GetConnection(desiredConnection, ConnectionUDPOptions, ConnectionDefaultSendReceiveOptions, false, this, possibleHandshakeUDPDatagram);
}
catch (ConnectionShutdownException)
{
if ((ConnectionUDPOptions & UDPOptions.Handshake) == UDPOptions.Handshake)
{
if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Attempted to get connection " + desiredConnection + " but this caused a ConnectionShutdownException. Exception caught and ignored as should only happen if the connection was closed shortly after being created.");
connection = null;
}
else
throw;
}
}
if (connection != null && !possibleHandshakeUDPDatagram.DatagramHandled)
{
//We pass the data off to the specific connection
//Lock on the packetbuilder locker as we may receive UDP packets in parallel from this host
lock (connection.packetBuilder.Locker)
{
if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace(" ... " + receivedBytes.Length.ToString() + " bytes added to packetBuilder for " + connection.ConnectionInfo + ". Cached " + connection.packetBuilder.TotalBytesCached.ToString() + " bytes, expecting " + connection.packetBuilder.TotalBytesExpected.ToString() + " bytes.");
connection.packetBuilder.AddPartialPacket(receivedBytes.Length, receivedBytes);
if (connection.packetBuilder.TotalBytesCached > 0) connection.IncomingPacketHandleHandOff(connection.packetBuilder);
if (connection.packetBuilder.TotalPartialPacketCount > 0)
LogTools.LogException(new Exception("Packet builder had " + connection.packetBuilder.TotalBytesCached + " bytes remaining after a call to IncomingPacketHandleHandOff with connection " + connection.ConnectionInfo + ". Until sequenced packets are implemented this indicates a possible error."), "UDPConnectionError");
}
}
}
}
//On any error here we close the connection
catch (NullReferenceException)
{
CloseConnection(true, 20);
}
catch (ArgumentNullException)
{
CloseConnection(true, 37);
}
catch (IOException)
{
CloseConnection(true, 21);
}
catch (ObjectDisposedException)
{
CloseConnection(true, 22);
}
catch (SocketException)
{
//Receive may throw a SocketException ErrorCode=10054 after attempting to send a datagram to an unreachable target.
//We will try to get around this by ignoring the ICMP packet causing these problems on client creation
CloseConnection(true, 23);
}
catch (InvalidOperationException)
{
CloseConnection(true, 24);
}
catch (ConnectionSetupException)
{
//Can occur if data is received as comms is being shutdown.
//Method will attempt to create new connection which will throw ConnectionSetupException.
CloseConnection(true, 50);
}
catch (Exception ex)
{
LogTools.LogException(ex, "Error_UDPConnectionIncomingPacketHandler");
CloseConnection(true, 41);
}
//Clear the listen thread object because the thread is about to end
incomingDataListenThread = null;
if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Trace("Incoming data listen thread ending for " + ConnectionInfo);
}
#endif
}
} | MarcFletcher/NetworkComms.Net | NetworkCommsDotNet/Connection/UDP/UDPConnection.cs | C# | apache-2.0 | 36,508 |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.cognitoidp.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.cognitoidp.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* AnalyticsMetadataType JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AnalyticsMetadataTypeJsonUnmarshaller implements Unmarshaller<AnalyticsMetadataType, JsonUnmarshallerContext> {
public AnalyticsMetadataType unmarshall(JsonUnmarshallerContext context) throws Exception {
AnalyticsMetadataType analyticsMetadataType = new AnalyticsMetadataType();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("AnalyticsEndpointId", targetDepth)) {
context.nextToken();
analyticsMetadataType.setAnalyticsEndpointId(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return analyticsMetadataType;
}
private static AnalyticsMetadataTypeJsonUnmarshaller instance;
public static AnalyticsMetadataTypeJsonUnmarshaller getInstance() {
if (instance == null)
instance = new AnalyticsMetadataTypeJsonUnmarshaller();
return instance;
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-cognitoidp/src/main/java/com/amazonaws/services/cognitoidp/model/transform/AnalyticsMetadataTypeJsonUnmarshaller.java | Java | apache-2.0 | 2,836 |
/*
* Copyright (C) 2017 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.seongil.mvplife.fragment;
import android.os.Bundle;
import android.view.View;
import com.seongil.mvplife.base.MvpPresenter;
import com.seongil.mvplife.base.MvpView;
import com.seongil.mvplife.delegate.MvpDelegateCallback;
import com.seongil.mvplife.delegate.fragment.MvpFragmentDelegate;
import com.seongil.mvplife.delegate.fragment.MvpFragmentDelegateImpl;
/**
* Abstract class for the fragment which is holding a reference of the {@link MvpPresenter}
* Also, holding a {@link MvpFragmentDelegate} which is handling the lifecycle of the fragment.
*
* @param <V> The type of {@link MvpView}
* @param <P> The type of {@link MvpPresenter}
*
* @author seong-il, kim
* @since 17. 1. 6
*/
public abstract class BaseMvpFragment<V extends MvpView, P extends MvpPresenter<V>>
extends CoreFragment implements MvpView, MvpDelegateCallback<V, P> {
// ========================================================================
// Constants
// ========================================================================
// ========================================================================
// Fields
// ========================================================================
private MvpFragmentDelegate mFragmentDelegate;
private P mPresenter;
// ========================================================================
// Constructors
// ========================================================================
// ========================================================================
// Getter & Setter
// ========================================================================
// ========================================================================
// Methods for/from SuperClass/Interfaces
// ========================================================================
@Override
public abstract P createPresenter();
@Override
public P getPresenter() {
return mPresenter;
}
@Override
public void setPresenter(P presenter) {
mPresenter = presenter;
}
@Override
@SuppressWarnings("unchecked")
public V getMvpView() {
return (V) this;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getMvpDelegate().onViewCreated(view, savedInstanceState);
}
@Override
public void onDestroyView() {
getMvpDelegate().onDestroyView();
super.onDestroyView();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getMvpDelegate().onCreate(savedInstanceState);
}
@Override
public void onDestroy() {
super.onDestroy();
getMvpDelegate().onDestroy();
}
// ========================================================================
// Methods
// ========================================================================
protected MvpFragmentDelegate getMvpDelegate() {
if (mFragmentDelegate == null) {
mFragmentDelegate = new MvpFragmentDelegateImpl<>(this);
}
return mFragmentDelegate;
}
// ========================================================================
// Inner and Anonymous Classes
// ========================================================================
} | allsoft777/MVP-with-Firebase | mvplife/src/main/java/com/seongil/mvplife/fragment/BaseMvpFragment.java | Java | apache-2.0 | 4,046 |
import React from 'react'
import {
StyleSheet,
View,
processColor
} from 'react-native'
import { BubbleChart } from 'react-native-charts-wrapper'
class BubbleChartScreen extends React.Component<any, any> {
constructor(props) {
super(props)
const { modeInfo } = props
const temp = props.value.weekLoc.sort((a, b) => {
const day = a.x - b.x
return day || (a.y - b.y)
})
const valueFormatter = props.value.daysMapper.slice()
valueFormatter.unshift()
valueFormatter.push(props.value.daysMapper[0])
const isX = item => item.x === 6
const values = [...temp.filter(isX), ...temp.filter(item => item.x !== 6)]
this.state = {
data: {
dataSets: [{
values,
label: '奖杯数比例',
config: {
color: processColor(modeInfo.deepColor),
highlightCircleWidth: 2,
drawValues: false,
valueTextColor: processColor(modeInfo.titleTextColor)
}
}]
},
legend: {
enabled: true,
textSize: 14,
form: 'CIRCLE',
wordWrapEnabled: true,
textColor: processColor(props.modeInfo.standardTextColor)
},
xAxis: {
valueFormatter,
position: 'BOTTOM',
drawGridLines: false,
granularityEnabled: true,
granularity: 1,
textColor: processColor(props.modeInfo.standardTextColor)
// avoidFirstLastClipping: true
// labelCountForce: true,
// labelCount: 12
},
yAxis: {
left: {
axisMinimum: 0,
axisMaximum: 23,
textColor: processColor(props.modeInfo.standardTextColor)
},
right: {
axisMinimum: 0,
axisMaximum: 23,
textColor: processColor(props.modeInfo.standardTextColor)
}
}
}
}
handleSelect = () => {
}
render() {
// console.log(this.state.data.dataSets[0].values.filter(item => item.x === 6))
return (
<View style={{ height: 250 }}>
<BubbleChart
style={styles.chart}
data={this.state.data}
legend={this.state.legend}
chartDescription={{text: ''}}
xAxis={this.state.xAxis}
yAxis={this.state.yAxis}
entryLabelColor={processColor(this.props.modeInfo.titleTextColor)}
onSelect={this.handleSelect}
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF'
},
chart: {
flex: 1
}
})
export default BubbleChartScreen | Smallpath/Psnine | psnine/container/statistics/BubbleChart.tsx | TypeScript | apache-2.0 | 2,584 |
# -*- coding: utf-8 -*-
"""Template shortcut & filters"""
import os
import datetime
from jinja2 import Environment, FileSystemLoader
from uwsgi_sloth.settings import ROOT
from uwsgi_sloth import settings, __VERSION__
template_path = os.path.join(ROOT, 'templates')
env = Environment(loader=FileSystemLoader(template_path))
# Template filters
def friendly_time(msecs):
secs, msecs = divmod(msecs, 1000)
mins, secs = divmod(secs, 60)
hours, mins = divmod(mins, 60)
if hours:
return '%dh%dm%ds' % (hours, mins, secs)
elif mins:
return '%dm%ds' % (mins, secs)
elif secs:
return '%ds%dms' % (secs, msecs)
else:
return '%.2fms' % msecs
env.filters['friendly_time'] = friendly_time
def render_template(template_name, context={}):
template = env.get_template(template_name)
context.update(
SETTINGS=settings,
now=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
version='.'.join(map(str, __VERSION__)))
return template.render(**context)
| piglei/uwsgi-sloth | uwsgi_sloth/template.py | Python | apache-2.0 | 1,040 |
package org.openstack.atlas.service.domain.exception;
public class UniqueLbPortViolationException extends PersistenceServiceException {
private final String message;
public UniqueLbPortViolationException(final String message) {
this.message = message;
}
@Override
public String getMessage() {
return message;
}
}
| openstack-atlas/atlas-lb | core-persistence/src/main/java/org/openstack/atlas/service/domain/exception/UniqueLbPortViolationException.java | Java | apache-2.0 | 356 |
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_class.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver13;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import org.jboss.netty.buffer.ChannelBuffer;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;
class OFOxmBsnUdf4MaskedVer13 implements OFOxmBsnUdf4Masked {
private static final Logger logger = LoggerFactory.getLogger(OFOxmBsnUdf4MaskedVer13.class);
// version: 1.3
final static byte WIRE_VERSION = 4;
final static int LENGTH = 12;
private final static UDF DEFAULT_VALUE = UDF.ZERO;
private final static UDF DEFAULT_VALUE_MASK = UDF.ZERO;
// OF message fields
private final UDF value;
private final UDF mask;
//
// Immutable default instance
final static OFOxmBsnUdf4MaskedVer13 DEFAULT = new OFOxmBsnUdf4MaskedVer13(
DEFAULT_VALUE, DEFAULT_VALUE_MASK
);
// package private constructor - used by readers, builders, and factory
OFOxmBsnUdf4MaskedVer13(UDF value, UDF mask) {
if(value == null) {
throw new NullPointerException("OFOxmBsnUdf4MaskedVer13: property value cannot be null");
}
if(mask == null) {
throw new NullPointerException("OFOxmBsnUdf4MaskedVer13: property mask cannot be null");
}
this.value = value;
this.mask = mask;
}
// Accessors for OF message fields
@Override
public long getTypeLen() {
return 0x31908L;
}
@Override
public UDF getValue() {
return value;
}
@Override
public UDF getMask() {
return mask;
}
@Override
public MatchField<UDF> getMatchField() {
return MatchField.BSN_UDF4;
}
@Override
public boolean isMasked() {
return true;
}
public OFOxm<UDF> getCanonical() {
if (UDF.NO_MASK.equals(mask)) {
return new OFOxmBsnUdf4Ver13(value);
} else if(UDF.FULL_MASK.equals(mask)) {
return null;
} else {
return this;
}
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_13;
}
public OFOxmBsnUdf4Masked.Builder createBuilder() {
return new BuilderWithParent(this);
}
static class BuilderWithParent implements OFOxmBsnUdf4Masked.Builder {
final OFOxmBsnUdf4MaskedVer13 parentMessage;
// OF message fields
private boolean valueSet;
private UDF value;
private boolean maskSet;
private UDF mask;
BuilderWithParent(OFOxmBsnUdf4MaskedVer13 parentMessage) {
this.parentMessage = parentMessage;
}
@Override
public long getTypeLen() {
return 0x31908L;
}
@Override
public UDF getValue() {
return value;
}
@Override
public OFOxmBsnUdf4Masked.Builder setValue(UDF value) {
this.value = value;
this.valueSet = true;
return this;
}
@Override
public UDF getMask() {
return mask;
}
@Override
public OFOxmBsnUdf4Masked.Builder setMask(UDF mask) {
this.mask = mask;
this.maskSet = true;
return this;
}
@Override
public MatchField<UDF> getMatchField() {
return MatchField.BSN_UDF4;
}
@Override
public boolean isMasked() {
return true;
}
@Override
public OFOxm<UDF> getCanonical()throws UnsupportedOperationException {
throw new UnsupportedOperationException("Property canonical not supported in version 1.3");
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_13;
}
@Override
public OFOxmBsnUdf4Masked build() {
UDF value = this.valueSet ? this.value : parentMessage.value;
if(value == null)
throw new NullPointerException("Property value must not be null");
UDF mask = this.maskSet ? this.mask : parentMessage.mask;
if(mask == null)
throw new NullPointerException("Property mask must not be null");
//
return new OFOxmBsnUdf4MaskedVer13(
value,
mask
);
}
}
static class Builder implements OFOxmBsnUdf4Masked.Builder {
// OF message fields
private boolean valueSet;
private UDF value;
private boolean maskSet;
private UDF mask;
@Override
public long getTypeLen() {
return 0x31908L;
}
@Override
public UDF getValue() {
return value;
}
@Override
public OFOxmBsnUdf4Masked.Builder setValue(UDF value) {
this.value = value;
this.valueSet = true;
return this;
}
@Override
public UDF getMask() {
return mask;
}
@Override
public OFOxmBsnUdf4Masked.Builder setMask(UDF mask) {
this.mask = mask;
this.maskSet = true;
return this;
}
@Override
public MatchField<UDF> getMatchField() {
return MatchField.BSN_UDF4;
}
@Override
public boolean isMasked() {
return true;
}
@Override
public OFOxm<UDF> getCanonical()throws UnsupportedOperationException {
throw new UnsupportedOperationException("Property canonical not supported in version 1.3");
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_13;
}
//
@Override
public OFOxmBsnUdf4Masked build() {
UDF value = this.valueSet ? this.value : DEFAULT_VALUE;
if(value == null)
throw new NullPointerException("Property value must not be null");
UDF mask = this.maskSet ? this.mask : DEFAULT_VALUE_MASK;
if(mask == null)
throw new NullPointerException("Property mask must not be null");
return new OFOxmBsnUdf4MaskedVer13(
value,
mask
);
}
}
final static Reader READER = new Reader();
static class Reader implements OFMessageReader<OFOxmBsnUdf4Masked> {
@Override
public OFOxmBsnUdf4Masked readFrom(ChannelBuffer bb) throws OFParseError {
// fixed value property typeLen == 0x31908L
int typeLen = bb.readInt();
if(typeLen != 0x31908)
throw new OFParseError("Wrong typeLen: Expected=0x31908L(0x31908L), got="+typeLen);
UDF value = UDF.read4Bytes(bb);
UDF mask = UDF.read4Bytes(bb);
OFOxmBsnUdf4MaskedVer13 oxmBsnUdf4MaskedVer13 = new OFOxmBsnUdf4MaskedVer13(
value,
mask
);
if(logger.isTraceEnabled())
logger.trace("readFrom - read={}", oxmBsnUdf4MaskedVer13);
return oxmBsnUdf4MaskedVer13;
}
}
public void putTo(PrimitiveSink sink) {
FUNNEL.funnel(this, sink);
}
final static OFOxmBsnUdf4MaskedVer13Funnel FUNNEL = new OFOxmBsnUdf4MaskedVer13Funnel();
static class OFOxmBsnUdf4MaskedVer13Funnel implements Funnel<OFOxmBsnUdf4MaskedVer13> {
private static final long serialVersionUID = 1L;
@Override
public void funnel(OFOxmBsnUdf4MaskedVer13 message, PrimitiveSink sink) {
// fixed value property typeLen = 0x31908L
sink.putInt(0x31908);
message.value.putTo(sink);
message.mask.putTo(sink);
}
}
public void writeTo(ChannelBuffer bb) {
WRITER.write(bb, this);
}
final static Writer WRITER = new Writer();
static class Writer implements OFMessageWriter<OFOxmBsnUdf4MaskedVer13> {
@Override
public void write(ChannelBuffer bb, OFOxmBsnUdf4MaskedVer13 message) {
// fixed value property typeLen = 0x31908L
bb.writeInt(0x31908);
message.value.write4Bytes(bb);
message.mask.write4Bytes(bb);
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("OFOxmBsnUdf4MaskedVer13(");
b.append("value=").append(value);
b.append(", ");
b.append("mask=").append(mask);
b.append(")");
return b.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OFOxmBsnUdf4MaskedVer13 other = (OFOxmBsnUdf4MaskedVer13) obj;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
if (mask == null) {
if (other.mask != null)
return false;
} else if (!mask.equals(other.mask))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((value == null) ? 0 : value.hashCode());
result = prime * result + ((mask == null) ? 0 : mask.hashCode());
return result;
}
}
| o3project/openflowj-otn | src/main/java/org/projectfloodlight/openflow/protocol/ver13/OFOxmBsnUdf4MaskedVer13.java | Java | apache-2.0 | 10,443 |
package com.tamirhassan.pdfxtk.comparators;
/**
* pdfXtk - PDF Extraction Toolkit
* Copyright (c) by the authors/contributors. All rights reserved.
* This project includes code from PDFBox and TouchGraph.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the names pdfXtk or PDF Extraction Toolkit; 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 REGENTS 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.
*
* http://pdfxtk.sourceforge.net
*
*/
import java.util.Comparator;
import com.tamirhassan.pdfxtk.model.GenericSegment;
/**
* @author Tamir Hassan, pdfanalyser@tamirhassan.com
* @version PDF Analyser 0.9
*
* Sorts on Xmid coordinate ((x1+x2)/2)
*/
public class XmidComparator implements Comparator<GenericSegment>
{
public int compare(GenericSegment obj1, GenericSegment obj2)
{
// sorts in x order
double x1 = obj1.getXmid();
double x2 = obj2.getXmid();
// causes a contract violation (rounding?)
// return (int) (x1 - x2);
if (x2 > x1) return -1;
else if (x2 == x1) return 0;
else return 1;
}
public boolean equals(Object obj)
{
return obj.equals(this);
}
} | tamirhassan/pdfxtk | src/com/tamirhassan/pdfxtk/comparators/XmidComparator.java | Java | apache-2.0 | 2,438 |
/**
* Copyright (C) 2015 meltmedia (christian.trimble@meltmedia.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 com.meltmedia.dropwizard.etcd.json;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Function;
import java.util.function.Supplier;
import com.codahale.metrics.MetricRegistry;
import mousio.etcd4j.EtcdClient;
import io.dropwizard.Configuration;
import io.dropwizard.ConfiguredBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
public class EtcdJsonBundle<C extends Configuration> implements ConfiguredBundle<C> {
public static class Builder<C extends Configuration> {
private Supplier<EtcdClient> client;
private Supplier<ScheduledExecutorService> executor;
private Function<C, String> directoryAccessor;
public Builder<C> withClient(Supplier<EtcdClient> client) {
this.client = client;
return this;
}
public Builder<C> withExecutor(Supplier<ScheduledExecutorService> executor) {
this.executor = executor;
return this;
}
public Builder<C> withDirectory(Function<C, String> directoryAccessor) {
this.directoryAccessor = directoryAccessor;
return this;
}
public EtcdJsonBundle<C> build() {
return new EtcdJsonBundle<C>(client, executor, directoryAccessor);
}
}
public static <C extends Configuration> Builder<C> builder() {
return new Builder<C>();
}
Supplier<EtcdClient> clientSupplier;
EtcdJson factory;
private Supplier<ScheduledExecutorService> executor;
private Function<C, String> directoryAccessor;
public EtcdJsonBundle(Supplier<EtcdClient> client, Supplier<ScheduledExecutorService> executor,
Function<C, String> directoryAccessor) {
this.clientSupplier = client;
this.executor = executor;
this.directoryAccessor = directoryAccessor;
}
@Override
public void initialize(Bootstrap<?> bootstrap) {
}
@Override
public void run(C configuration, Environment environment) throws Exception {
factory =
EtcdJson.builder().withClient(clientSupplier).withExecutor(executor.get())
.withBaseDirectory(directoryAccessor.apply(configuration))
.withMapper(environment.getObjectMapper())
.withMetricRegistry(environment.metrics()).build();
environment.lifecycle().manage(new EtcdJsonManager(factory));
environment.healthChecks().register("etcd-watch", new WatchServiceHealthCheck(factory.getWatchService()));
}
public EtcdJson getFactory() {
return this.factory;
}
}
| meltmedia/dropwizard-etcd | bundle/src/main/java/com/meltmedia/dropwizard/etcd/json/EtcdJsonBundle.java | Java | apache-2.0 | 3,068 |
import com.google.common.base.Function;
import javax.annotation.Nullable;
/**
* Created by ckale on 10/29/14.
*/
public class DateValueSortFunction implements Function<PojoDTO, Long>{
@Nullable
@Override
public Long apply(@Nullable final PojoDTO input) {
return input.getDateTime().getMillis();
}
}
| chax0r/PlayGround | playGround/src/main/java/DateValueSortFunction.java | Java | apache-2.0 | 329 |
package ru.stqa.javacourse.mantis.tests;
import org.testng.annotations.Test;
import ru.stqa.javacourse.mantis.model.Issue;
import ru.stqa.javacourse.mantis.model.Project;
import javax.xml.rpc.ServiceException;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import java.util.Set;
import static org.testng.Assert.assertEquals;
public class SoapTest extends TestBase {
@Test
public void testGetProjects() throws MalformedURLException, ServiceException, RemoteException {
Set<Project> projects = app.soap().getProjects();
System.out.println(projects.size());
for (Project project : projects) {
System.out.println(project.getName());
}
}
@Test
public void testCreateIssue() throws RemoteException, ServiceException, MalformedURLException {
Set<Project> projects = app.soap().getProjects();
Issue issue=new Issue().withSummary("test issue")
.withDescription("test issue description").withProject(projects.iterator().next());
Issue created = app.soap().addIssue(issue);
assertEquals(issue.getSummary(),created.getSummary());
}
}
| Olbar/courseJava | mantis-tests/src/test/java/ru/stqa/javacourse/mantis/tests/SoapTest.java | Java | apache-2.0 | 1,172 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v10/services/customer_conversion_goal_service.proto
package com.google.ads.googleads.v10.services;
/**
* <pre>
* A single operation (update) on a customer conversion goal.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v10.services.CustomerConversionGoalOperation}
*/
public final class CustomerConversionGoalOperation extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v10.services.CustomerConversionGoalOperation)
CustomerConversionGoalOperationOrBuilder {
private static final long serialVersionUID = 0L;
// Use CustomerConversionGoalOperation.newBuilder() to construct.
private CustomerConversionGoalOperation(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CustomerConversionGoalOperation() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new CustomerConversionGoalOperation();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private CustomerConversionGoalOperation(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder subBuilder = null;
if (operationCase_ == 1) {
subBuilder = ((com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_).toBuilder();
}
operation_ =
input.readMessage(com.google.ads.googleads.v10.resources.CustomerConversionGoal.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom((com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_);
operation_ = subBuilder.buildPartial();
}
operationCase_ = 1;
break;
}
case 18: {
com.google.protobuf.FieldMask.Builder subBuilder = null;
if (updateMask_ != null) {
subBuilder = updateMask_.toBuilder();
}
updateMask_ = input.readMessage(com.google.protobuf.FieldMask.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(updateMask_);
updateMask_ = subBuilder.buildPartial();
}
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.class, com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.Builder.class);
}
private int operationCase_ = 0;
private java.lang.Object operation_;
public enum OperationCase
implements com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
UPDATE(1),
OPERATION_NOT_SET(0);
private final int value;
private OperationCase(int value) {
this.value = value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static OperationCase valueOf(int value) {
return forNumber(value);
}
public static OperationCase forNumber(int value) {
switch (value) {
case 1: return UPDATE;
case 0: return OPERATION_NOT_SET;
default: return null;
}
}
public int getNumber() {
return this.value;
}
};
public OperationCase
getOperationCase() {
return OperationCase.forNumber(
operationCase_);
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return updateMask_ != null;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return getUpdateMask();
}
public static final int UPDATE_FIELD_NUMBER = 1;
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
* @return Whether the update field is set.
*/
@java.lang.Override
public boolean hasUpdate() {
return operationCase_ == 1;
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
* @return The update.
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CustomerConversionGoal getUpdate() {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_;
}
return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance();
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder getUpdateOrBuilder() {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_;
}
return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (operationCase_ == 1) {
output.writeMessage(1, (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_);
}
if (updateMask_ != null) {
output.writeMessage(2, getUpdateMask());
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (operationCase_ == 1) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_);
}
if (updateMask_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, getUpdateMask());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v10.services.CustomerConversionGoalOperation)) {
return super.equals(obj);
}
com.google.ads.googleads.v10.services.CustomerConversionGoalOperation other = (com.google.ads.googleads.v10.services.CustomerConversionGoalOperation) obj;
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask()
.equals(other.getUpdateMask())) return false;
}
if (!getOperationCase().equals(other.getOperationCase())) return false;
switch (operationCase_) {
case 1:
if (!getUpdate()
.equals(other.getUpdate())) return false;
break;
case 0:
default:
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
switch (operationCase_) {
case 1:
hash = (37 * hash) + UPDATE_FIELD_NUMBER;
hash = (53 * hash) + getUpdate().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v10.services.CustomerConversionGoalOperation prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* A single operation (update) on a customer conversion goal.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v10.services.CustomerConversionGoalOperation}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v10.services.CustomerConversionGoalOperation)
com.google.ads.googleads.v10.services.CustomerConversionGoalOperationOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.class, com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.Builder.class);
}
// Construct using com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (updateMaskBuilder_ == null) {
updateMask_ = null;
} else {
updateMask_ = null;
updateMaskBuilder_ = null;
}
operationCase_ = 0;
operation_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v10.services.CustomerConversionGoalOperation getDefaultInstanceForType() {
return com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v10.services.CustomerConversionGoalOperation build() {
com.google.ads.googleads.v10.services.CustomerConversionGoalOperation result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v10.services.CustomerConversionGoalOperation buildPartial() {
com.google.ads.googleads.v10.services.CustomerConversionGoalOperation result = new com.google.ads.googleads.v10.services.CustomerConversionGoalOperation(this);
if (updateMaskBuilder_ == null) {
result.updateMask_ = updateMask_;
} else {
result.updateMask_ = updateMaskBuilder_.build();
}
if (operationCase_ == 1) {
if (updateBuilder_ == null) {
result.operation_ = operation_;
} else {
result.operation_ = updateBuilder_.build();
}
}
result.operationCase_ = operationCase_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v10.services.CustomerConversionGoalOperation) {
return mergeFrom((com.google.ads.googleads.v10.services.CustomerConversionGoalOperation)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v10.services.CustomerConversionGoalOperation other) {
if (other == com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.getDefaultInstance()) return this;
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
switch (other.getOperationCase()) {
case UPDATE: {
mergeUpdate(other.getUpdate());
break;
}
case OPERATION_NOT_SET: {
break;
}
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.ads.googleads.v10.services.CustomerConversionGoalOperation) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int operationCase_ = 0;
private java.lang.Object operation_;
public OperationCase
getOperationCase() {
return OperationCase.forNumber(
operationCase_);
}
public Builder clearOperation() {
operationCase_ = 0;
operation_ = null;
onChanged();
return this;
}
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_;
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return updateMaskBuilder_ != null || updateMask_ != null;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
onChanged();
} else {
updateMaskBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(
com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
onChanged();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (updateMask_ != null) {
updateMask_ =
com.google.protobuf.FieldMask.newBuilder(updateMask_).mergeFrom(value).buildPartial();
} else {
updateMask_ = value;
}
onChanged();
} else {
updateMaskBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder clearUpdateMask() {
if (updateMaskBuilder_ == null) {
updateMask_ = null;
onChanged();
} else {
updateMask_ = null;
updateMaskBuilder_ = null;
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null ?
com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(),
getParentForChildren(),
isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.CustomerConversionGoal, com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder, com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder> updateBuilder_;
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
* @return Whether the update field is set.
*/
@java.lang.Override
public boolean hasUpdate() {
return operationCase_ == 1;
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
* @return The update.
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CustomerConversionGoal getUpdate() {
if (updateBuilder_ == null) {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_;
}
return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance();
} else {
if (operationCase_ == 1) {
return updateBuilder_.getMessage();
}
return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance();
}
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
*/
public Builder setUpdate(com.google.ads.googleads.v10.resources.CustomerConversionGoal value) {
if (updateBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
operation_ = value;
onChanged();
} else {
updateBuilder_.setMessage(value);
}
operationCase_ = 1;
return this;
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
*/
public Builder setUpdate(
com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder builderForValue) {
if (updateBuilder_ == null) {
operation_ = builderForValue.build();
onChanged();
} else {
updateBuilder_.setMessage(builderForValue.build());
}
operationCase_ = 1;
return this;
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
*/
public Builder mergeUpdate(com.google.ads.googleads.v10.resources.CustomerConversionGoal value) {
if (updateBuilder_ == null) {
if (operationCase_ == 1 &&
operation_ != com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance()) {
operation_ = com.google.ads.googleads.v10.resources.CustomerConversionGoal.newBuilder((com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_)
.mergeFrom(value).buildPartial();
} else {
operation_ = value;
}
onChanged();
} else {
if (operationCase_ == 1) {
updateBuilder_.mergeFrom(value);
}
updateBuilder_.setMessage(value);
}
operationCase_ = 1;
return this;
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
*/
public Builder clearUpdate() {
if (updateBuilder_ == null) {
if (operationCase_ == 1) {
operationCase_ = 0;
operation_ = null;
onChanged();
}
} else {
if (operationCase_ == 1) {
operationCase_ = 0;
operation_ = null;
}
updateBuilder_.clear();
}
return this;
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
*/
public com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder getUpdateBuilder() {
return getUpdateFieldBuilder().getBuilder();
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder getUpdateOrBuilder() {
if ((operationCase_ == 1) && (updateBuilder_ != null)) {
return updateBuilder_.getMessageOrBuilder();
} else {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_;
}
return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance();
}
}
/**
* <pre>
* Update operation: The customer conversion goal is expected to have a
* valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.CustomerConversionGoal, com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder, com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder>
getUpdateFieldBuilder() {
if (updateBuilder_ == null) {
if (!(operationCase_ == 1)) {
operation_ = com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance();
}
updateBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.CustomerConversionGoal, com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder, com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder>(
(com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_,
getParentForChildren(),
isClean());
operation_ = null;
}
operationCase_ = 1;
onChanged();;
return updateBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v10.services.CustomerConversionGoalOperation)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v10.services.CustomerConversionGoalOperation)
private static final com.google.ads.googleads.v10.services.CustomerConversionGoalOperation DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v10.services.CustomerConversionGoalOperation();
}
public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CustomerConversionGoalOperation>
PARSER = new com.google.protobuf.AbstractParser<CustomerConversionGoalOperation>() {
@java.lang.Override
public CustomerConversionGoalOperation parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new CustomerConversionGoalOperation(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<CustomerConversionGoalOperation> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CustomerConversionGoalOperation> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v10.services.CustomerConversionGoalOperation getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| googleads/google-ads-java | google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/services/CustomerConversionGoalOperation.java | Java | apache-2.0 | 36,172 |
package org.openjava.upay.web.domain;
import java.util.List;
public class TablePage<T>
{
private long start;
private int length;
private long recordsTotal;
private long recordsFiltered;
private List<T> data;
public TablePage()
{
}
public long getStart()
{
return start;
}
public void setStart(long start)
{
this.start = start;
}
public int getLength()
{
return length;
}
public void setLength(int length)
{
this.length = length;
}
public long getRecordsTotal()
{
return recordsTotal;
}
public void setRecordsTotal(long recordsTotal)
{
this.recordsTotal = recordsTotal;
}
public long getRecordsFiltered()
{
return recordsFiltered;
}
public void setRecordsFiltered(long recordsFiltered)
{
this.recordsFiltered = recordsFiltered;
}
public List<T> getData()
{
return data;
}
public void setData(List<T> data)
{
this.data = data;
}
public TablePage wrapData(long total, List<T> data)
{
this.recordsTotal = total;
this.recordsFiltered = total;
this.data = data;
return this;
}
} | openjava2017/openjava-upay | upay-server/src/main/java/org/openjava/upay/web/domain/TablePage.java | Java | apache-2.0 | 1,263 |
package com.jy.controller.workflow.online.apply;
import com.jy.common.ajax.AjaxRes;
import com.jy.common.utils.DateUtils;
import com.jy.common.utils.base.Const;
import com.jy.common.utils.security.AccountShiroUtil;
import com.jy.controller.base.BaseController;
import com.jy.entity.attendance.WorkRecord;
import com.jy.entity.oa.overtime.Overtime;
import com.jy.entity.oa.patch.Patch;
import com.jy.entity.oa.task.TaskInfo;
import com.jy.service.oa.activiti.ActivitiDeployService;
import com.jy.service.oa.overtime.OvertimeService;
import com.jy.service.oa.patch.PatchService;
import com.jy.service.oa.task.TaskInfoService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 补卡页面
*/
@Controller
@RequestMapping(value = "/backstage/workflow/online/patch/")
public class PatchController extends BaseController<Object> {
private static final String SECURITY_URL = "/backstage/workflow/online/patch/index";
@Autowired
private RuntimeService runtimeService;
@Autowired
private TaskService taskService;
@Autowired
private TaskInfoService taskInfoService;
@Autowired
private IdentityService identityService;
@Autowired
private PatchService patchService;
@Autowired
private ActivitiDeployService activitiDeployService;
/**
* 补卡列表
*/
@RequestMapping(value = "index")
public String index(org.springframework.ui.Model model) {
if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) {
model.addAttribute("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
return "/system/workflow/online/apply/patch";
}
return Const.NO_AUTHORIZED_URL;
}
/**
* 启动流程
*/
@RequestMapping(value = "start", method = RequestMethod.POST)
@ResponseBody
public AjaxRes startWorkflow(Patch o) {
AjaxRes ar = getAjaxRes();
if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_MENU, SECURITY_URL))) {
try {
String currentUserId = AccountShiroUtil.getCurrentUser().getAccountId();
String[] approvers = o.getApprover().split(",");
Map<String, Object> variables = new HashMap<String, Object>();
for (int i = 0; i < approvers.length; i++) {
variables.put("approver" + (i + 1), approvers[i]);
}
String workflowKey = "patch";
identityService.setAuthenticatedUserId(currentUserId);
Date now = new Date();
ProcessInstance processInstance = runtimeService.startProcessInstanceByKeyAndTenantId(workflowKey, variables, getCompany());
String pId = processInstance.getId();
String leaveID = get32UUID();
o.setPid(pId);
o.setAccountId(currentUserId);
o.setCreatetime(now);
o.setIsvalid(0);
o.setName(AccountShiroUtil.getCurrentUser().getName());
o.setId(leaveID);
patchService.insert(o);
Task task = taskService.createTaskQuery().processInstanceId(pId).singleResult();
String processDefinitionName = ((ExecutionEntity) processInstance).getProcessInstance().getProcessDefinition().getName();
String subkect = processDefinitionName + "-"
+ AccountShiroUtil.getCurrentUser().getName() + "-" + DateUtils.formatDate(now, "yyyy-MM-dd HH:mm");
//开始流程
TaskInfo taskInfo = new TaskInfo();
taskInfo.setId(get32UUID());
taskInfo.setBusinesskey(leaveID);
taskInfo.setCode("start");
taskInfo.setName("发起申请");
taskInfo.setStatus(0);
taskInfo.setPresentationsubject(subkect);
taskInfo.setAttr1(processDefinitionName);
taskInfo.setCreatetime(DateUtils.addSeconds(now, -1));
taskInfo.setCompletetime(DateUtils.addSeconds(now, -1));
taskInfo.setCreator(currentUserId);
taskInfo.setAssignee(currentUserId);
taskInfo.setTaskid("0");
taskInfo.setPkey(workflowKey);
taskInfo.setExecutionid("0");
taskInfo.setProcessinstanceid(processInstance.getId());
taskInfo.setProcessdefinitionid(processInstance.getProcessDefinitionId());
taskInfoService.insert(taskInfo);
//第一级审批流程
taskInfo.setId(get32UUID());
taskInfo.setCode(processInstance.getActivityId());
taskInfo.setName(task.getName());
taskInfo.setStatus(1);
taskInfo.setTaskid(task.getId());
taskInfo.setCreatetime(now);
taskInfo.setCompletetime(null);
taskInfo.setAssignee(approvers[0]);
taskInfoService.insert(taskInfo);
ar.setSucceedMsg("发起补卡申请成功!");
} catch (Exception e) {
logger.error(e.toString(), e);
ar.setFailMsg("启动流程失败");
} finally {
identityService.setAuthenticatedUserId(null);
}
}
return ar;
}
}
| futureskywei/whale | src/main/java/com/jy/controller/workflow/online/apply/PatchController.java | Java | apache-2.0 | 5,402 |
var searchData=
[
['interactiontype',['InteractionType',['../class_student_record.html#a00e060bc8aa9829e5db087e2cba21009',1,'StudentRecord']]]
];
| rstals/Unity-SCORM-Integration-Kit | Documentation/search/enums_2.js | JavaScript | apache-2.0 | 148 |
// Copyright (c) 2008, Google 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <base.h>
#include "client/windows/crash_generation/minidump_generator.h"
#include <cassert>
#include "client/windows/common/auto_critical_section.h"
#include "common/windows/guid_string.h"
using std::wstring;
namespace google_breakpad {
MinidumpGenerator::MinidumpGenerator(const wstring& dump_path)
: dbghelp_module_(NULL),
rpcrt4_module_(NULL),
dump_path_(dump_path),
write_dump_(NULL),
create_uuid_(NULL) {
InitializeCriticalSection(&module_load_sync_);
InitializeCriticalSection(&get_proc_address_sync_);
}
MinidumpGenerator::~MinidumpGenerator() {
if (dbghelp_module_) {
FreeLibrary(dbghelp_module_);
}
if (rpcrt4_module_) {
FreeLibrary(rpcrt4_module_);
}
DeleteCriticalSection(&get_proc_address_sync_);
DeleteCriticalSection(&module_load_sync_);
}
bool MinidumpGenerator::WriteMinidump(HANDLE process_handle,
DWORD process_id,
DWORD thread_id,
DWORD requesting_thread_id,
EXCEPTION_POINTERS* exception_pointers,
MDRawAssertionInfo* assert_info,
MINIDUMP_TYPE dump_type,
bool is_client_pointers,
wstring* dump_path) {
MiniDumpWriteDumpType write_dump = GetWriteDump();
if (!write_dump) {
return false;
}
wstring dump_file_path;
if (!GenerateDumpFilePath(&dump_file_path)) {
return false;
}
// If the client requests a full memory dump, we will write a normal mini
// dump and a full memory dump. Both dump files use the same uuid as file
// name prefix.
bool full_memory_dump = (dump_type & MiniDumpWithFullMemory) != 0;
wstring full_dump_file_path;
if (full_memory_dump) {
full_dump_file_path.assign(dump_file_path);
full_dump_file_path.resize(full_dump_file_path.size() - 4); // strip .dmp
full_dump_file_path.append(TEXT("-full.dmp"));
}
HANDLE dump_file = CreateFile(dump_file_path.c_str(),
GENERIC_WRITE,
0,
NULL,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (dump_file == INVALID_HANDLE_VALUE) {
return false;
}
HANDLE full_dump_file = INVALID_HANDLE_VALUE;
if (full_memory_dump) {
full_dump_file = CreateFile(full_dump_file_path.c_str(),
GENERIC_WRITE,
0,
NULL,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (full_dump_file == INVALID_HANDLE_VALUE) {
CloseHandle(dump_file);
return false;
}
}
MINIDUMP_EXCEPTION_INFORMATION* dump_exception_pointers = NULL;
MINIDUMP_EXCEPTION_INFORMATION dump_exception_info;
// Setup the exception information object only if it's a dump
// due to an exception.
if (exception_pointers) {
dump_exception_pointers = &dump_exception_info;
dump_exception_info.ThreadId = thread_id;
dump_exception_info.ExceptionPointers = exception_pointers;
dump_exception_info.ClientPointers = is_client_pointers;
}
// Add an MDRawBreakpadInfo stream to the minidump, to provide additional
// information about the exception handler to the Breakpad processor.
// The information will help the processor determine which threads are
// relevant. The Breakpad processor does not require this information but
// can function better with Breakpad-generated dumps when it is present.
// The native debugger is not harmed by the presence of this information.
MDRawBreakpadInfo breakpad_info = {0};
if (!is_client_pointers) {
// Set the dump thread id and requesting thread id only in case of
// in-process dump generation.
breakpad_info.validity = MD_BREAKPAD_INFO_VALID_DUMP_THREAD_ID |
MD_BREAKPAD_INFO_VALID_REQUESTING_THREAD_ID;
breakpad_info.dump_thread_id = thread_id;
breakpad_info.requesting_thread_id = requesting_thread_id;
}
// Leave room in user_stream_array for a possible assertion info stream.
MINIDUMP_USER_STREAM user_stream_array[2];
user_stream_array[0].Type = MD_BREAKPAD_INFO_STREAM;
user_stream_array[0].BufferSize = sizeof(breakpad_info);
user_stream_array[0].Buffer = &breakpad_info;
MINIDUMP_USER_STREAM_INFORMATION user_streams;
user_streams.UserStreamCount = 1;
user_streams.UserStreamArray = user_stream_array;
MDRawAssertionInfo* actual_assert_info = assert_info;
MDRawAssertionInfo client_assert_info = {0};
if (assert_info) {
// If the assertion info object lives in the client process,
// read the memory of the client process.
if (is_client_pointers) {
SIZE_T bytes_read = 0;
if (!ReadProcessMemory(process_handle,
assert_info,
&client_assert_info,
sizeof(client_assert_info),
&bytes_read)) {
CloseHandle(dump_file);
if (full_dump_file != INVALID_HANDLE_VALUE)
CloseHandle(full_dump_file);
return false;
}
if (bytes_read != sizeof(client_assert_info)) {
CloseHandle(dump_file);
if (full_dump_file != INVALID_HANDLE_VALUE)
CloseHandle(full_dump_file);
return false;
}
actual_assert_info = &client_assert_info;
}
user_stream_array[1].Type = MD_ASSERTION_INFO_STREAM;
user_stream_array[1].BufferSize = sizeof(MDRawAssertionInfo);
user_stream_array[1].Buffer = actual_assert_info;
++user_streams.UserStreamCount;
}
bool result_minidump = write_dump(
process_handle,
process_id,
dump_file,
static_cast<MINIDUMP_TYPE>((dump_type & (~MiniDumpWithFullMemory))
| MiniDumpNormal),
exception_pointers ? &dump_exception_info : NULL,
&user_streams,
NULL) != FALSE;
bool result_full_memory = true;
if (full_memory_dump) {
result_full_memory = write_dump(
process_handle,
process_id,
full_dump_file,
static_cast<MINIDUMP_TYPE>(dump_type & (~MiniDumpNormal)),
exception_pointers ? &dump_exception_info : NULL,
&user_streams,
NULL) != FALSE;
}
bool result = result_minidump && result_full_memory;
CloseHandle(dump_file);
if (full_dump_file != INVALID_HANDLE_VALUE)
CloseHandle(full_dump_file);
// Store the path of the dump file in the out parameter if dump generation
// succeeded.
if (result && dump_path) {
*dump_path = dump_file_path;
}
return result;
}
HMODULE MinidumpGenerator::GetDbghelpModule() {
AutoCriticalSection lock(&module_load_sync_);
if (!dbghelp_module_) {
dbghelp_module_ = LoadLibrary(TEXT("dbghelp.dll"));
}
return dbghelp_module_;
}
MinidumpGenerator::MiniDumpWriteDumpType MinidumpGenerator::GetWriteDump() {
AutoCriticalSection lock(&get_proc_address_sync_);
if (!write_dump_) {
HMODULE module = GetDbghelpModule();
if (module) {
FARPROC proc = GetProcAddress(module, "MiniDumpWriteDump");
write_dump_ = reinterpret_cast<MiniDumpWriteDumpType>(proc);
}
}
return write_dump_;
}
HMODULE MinidumpGenerator::GetRpcrt4Module() {
AutoCriticalSection lock(&module_load_sync_);
if (!rpcrt4_module_) {
rpcrt4_module_ = LoadLibrary(TEXT("rpcrt4.dll"));
}
return rpcrt4_module_;
}
MinidumpGenerator::UuidCreateType MinidumpGenerator::GetCreateUuid() {
AutoCriticalSection lock(&module_load_sync_);
if (!create_uuid_) {
HMODULE module = GetRpcrt4Module();
if (module) {
FARPROC proc = GetProcAddress(module, "UuidCreate");
create_uuid_ = reinterpret_cast<UuidCreateType>(proc);
}
}
return create_uuid_;
}
bool MinidumpGenerator::GenerateDumpFilePath(wstring* file_path) {
UUID id = {0};
UuidCreateType create_uuid = GetCreateUuid();
if(!create_uuid) {
return false;
}
create_uuid(&id);
wstring id_str = GUIDString::GUIDToWString(&id);
*file_path = dump_path_ + TEXT("\\") + id_str + TEXT(".dmp");
return true;
}
} // namespace google_breakpad
| mital/kroll | boot/breakpad/client/windows/crash_generation/minidump_generator.cc | C++ | apache-2.0 | 9,978 |
package com.nosolojava.fsm.impl.runtime.executable.basic;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.nosolojava.fsm.runtime.Context;
import com.nosolojava.fsm.runtime.executable.Elif;
import com.nosolojava.fsm.runtime.executable.Else;
import com.nosolojava.fsm.runtime.executable.Executable;
import com.nosolojava.fsm.runtime.executable.If;
public class BasicIf extends BasicConditional implements If {
private static final long serialVersionUID = -415238773021486012L;
private final List<Elif> elifs = new ArrayList<Elif>();
private final Else elseOperation;
public BasicIf(String condition) {
this(condition, null, null, null);
}
public BasicIf(String condition, List<Executable> executables) {
this(condition, null, null, executables);
}
public BasicIf(String condition, Else elseOperation, List<Executable> executables) {
this(condition, null, elseOperation, executables);
}
public BasicIf(String condition, List<Elif> elifs, Else elseOperation, List<Executable> executables) {
super(condition, executables);
if (elifs != null) {
this.elifs.addAll(elifs);
}
this.elseOperation = elseOperation;
}
@Override
public boolean runIf(Context context) {
boolean result = false;
// if condition fails
if (super.runIf(context)) {
result = true;
} else {
// try with elifs
boolean enterElif = false;
Iterator<Elif> iterElif = elifs.iterator();
Elif elif;
while (!enterElif && iterElif.hasNext()) {
elif = iterElif.next();
enterElif = elif.runIf(context);
}
// if no elif and else
if (!enterElif && this.elseOperation != null) {
elseOperation.run(context);
}
}
return result;
}
public List<Elif> getElifs() {
return this.elifs;
}
public void addElif(Elif elif) {
this.elifs.add(elif);
}
public void addElifs(List<Elif> elifs) {
this.elifs.addAll(elifs);
}
public void clearAndSetElifs(List<Elif> elifs) {
this.elifs.clear();
addElifs(elifs);
}
}
| nosolojava/scxml-java | scxml-java-implementation/src/main/java/com/nosolojava/fsm/impl/runtime/executable/basic/BasicIf.java | Java | apache-2.0 | 2,082 |
/**
* Copyright 2015 Santhosh Kumar Tekuri
*
* The JLibs authors license 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 jlibs.wamp4j.spi;
import java.io.InputStream;
public interface Listener{
public void onMessage(WAMPSocket socket, MessageType type, InputStream is);
public void onReadComplete(WAMPSocket socket);
public void readyToWrite(WAMPSocket socket);
public void onError(WAMPSocket socket, Throwable error);
public void onClose(WAMPSocket socket);
}
| santhosh-tekuri/jlibs | wamp4j-core/src/main/java/jlibs/wamp4j/spi/Listener.java | Java | apache-2.0 | 1,010 |
package me.littlepanda.dadbear.core.queue;
import java.util.Queue;
/**
* @author 张静波 myplaylife@icloud.com
*
*/
public interface DistributedQueue<T> extends Queue<T> {
/**
* <p>如果使用无参构造函数,需要先调用这个方法,队列才能使用</p>
* @param queue_name
* @param clazz
*/
abstract public void init(String queue_name, Class<T> clazz);
}
| myplaylife/dadbear | framework/core/src/main/java/me/littlepanda/dadbear/core/queue/DistributedQueue.java | Java | apache-2.0 | 402 |
/*
* Copyright 2013 Gunnar Kappei.
*
* 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.opengis.gml;
/**
* An XML MultiSurfaceType(@http://www.opengis.net/gml).
*
* This is a complex type.
*/
public interface MultiSurfaceType extends net.opengis.gml.AbstractGeometricAggregateType
{
public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)
org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(MultiSurfaceType.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s6E28D279B6C224D74769DB8B98AF1665").resolveHandle("multisurfacetypeb44dtype");
/**
* Gets a List of "surfaceMember" elements
*/
java.util.List<net.opengis.gml.SurfacePropertyType> getSurfaceMemberList();
/**
* Gets array of all "surfaceMember" elements
* @deprecated
*/
@Deprecated
net.opengis.gml.SurfacePropertyType[] getSurfaceMemberArray();
/**
* Gets ith "surfaceMember" element
*/
net.opengis.gml.SurfacePropertyType getSurfaceMemberArray(int i);
/**
* Returns number of "surfaceMember" element
*/
int sizeOfSurfaceMemberArray();
/**
* Sets array of all "surfaceMember" element
*/
void setSurfaceMemberArray(net.opengis.gml.SurfacePropertyType[] surfaceMemberArray);
/**
* Sets ith "surfaceMember" element
*/
void setSurfaceMemberArray(int i, net.opengis.gml.SurfacePropertyType surfaceMember);
/**
* Inserts and returns a new empty value (as xml) as the ith "surfaceMember" element
*/
net.opengis.gml.SurfacePropertyType insertNewSurfaceMember(int i);
/**
* Appends and returns a new empty value (as xml) as the last "surfaceMember" element
*/
net.opengis.gml.SurfacePropertyType addNewSurfaceMember();
/**
* Removes the ith "surfaceMember" element
*/
void removeSurfaceMember(int i);
/**
* Gets the "surfaceMembers" element
*/
net.opengis.gml.SurfaceArrayPropertyType getSurfaceMembers();
/**
* True if has "surfaceMembers" element
*/
boolean isSetSurfaceMembers();
/**
* Sets the "surfaceMembers" element
*/
void setSurfaceMembers(net.opengis.gml.SurfaceArrayPropertyType surfaceMembers);
/**
* Appends and returns a new empty "surfaceMembers" element
*/
net.opengis.gml.SurfaceArrayPropertyType addNewSurfaceMembers();
/**
* Unsets the "surfaceMembers" element
*/
void unsetSurfaceMembers();
/**
* A factory class with static methods for creating instances
* of this type.
*/
public static final class Factory
{
public static net.opengis.gml.MultiSurfaceType newInstance() {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); }
public static net.opengis.gml.MultiSurfaceType newInstance(org.apache.xmlbeans.XmlOptions options) {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); }
/** @param xmlAsString the string value to parse */
public static net.opengis.gml.MultiSurfaceType parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); }
public static net.opengis.gml.MultiSurfaceType parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); }
/** @param file the file from which to load an xml document */
public static net.opengis.gml.MultiSurfaceType parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); }
public static net.opengis.gml.MultiSurfaceType parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); }
public static net.opengis.gml.MultiSurfaceType parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); }
public static net.opengis.gml.MultiSurfaceType parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); }
public static net.opengis.gml.MultiSurfaceType parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); }
public static net.opengis.gml.MultiSurfaceType parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); }
public static net.opengis.gml.MultiSurfaceType parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); }
public static net.opengis.gml.MultiSurfaceType parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); }
public static net.opengis.gml.MultiSurfaceType parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); }
public static net.opengis.gml.MultiSurfaceType parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); }
public static net.opengis.gml.MultiSurfaceType parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); }
public static net.opengis.gml.MultiSurfaceType parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static net.opengis.gml.MultiSurfaceType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static net.opengis.gml.MultiSurfaceType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); }
private Factory() { } // No instance of this class allowed
}
}
| moosbusch/xbLIDO | src/net/opengis/gml/MultiSurfaceType.java | Java | apache-2.0 | 10,068 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.redshift.model.transform;
import org.w3c.dom.Node;
import javax.annotation.Generated;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.transform.StandardErrorUnmarshaller;
import com.amazonaws.services.redshift.model.AuthenticationProfileNotFoundException;
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AuthenticationProfileNotFoundExceptionUnmarshaller extends StandardErrorUnmarshaller {
public AuthenticationProfileNotFoundExceptionUnmarshaller() {
super(AuthenticationProfileNotFoundException.class);
}
@Override
public AmazonServiceException unmarshall(Node node) throws Exception {
// Bail out if this isn't the right error code that this
// marshaller understands
String errorCode = parseErrorCode(node);
if (errorCode == null || !errorCode.equals("AuthenticationProfileNotFoundFault"))
return null;
AuthenticationProfileNotFoundException e = (AuthenticationProfileNotFoundException) super.unmarshall(node);
return e;
}
}
| aws/aws-sdk-java | aws-java-sdk-redshift/src/main/java/com/amazonaws/services/redshift/model/transform/AuthenticationProfileNotFoundExceptionUnmarshaller.java | Java | apache-2.0 | 1,678 |
'use strict';
/**
* @ngdoc function
* @name lubriApp.controller:MembersCtrl
* @description
* # MembersCtrl
* Controller of the lubriApp
*/
angular.module('lubriApp')
.config(function($stateProvider) {
$stateProvider.state('app.members', {
abstract: true,
url: '/members',
templateUrl: 'views/members/main.html',
controller: 'MembersCtrl'
})
.state('app.members.list', {
url: '',
templateUrl: 'views/members/list.html',
controller: 'MembersCtrl'
})
.state('app.members.add', {
url: '/add',
templateUrl: 'views/members/form.html',
controller: 'MembersCtrl'
})
.state('app.members.import', {
url: '/import',
templateUrl: 'views/members/import.html',
controller: 'MembersCtrl'
})
.state('app.members.edit', {
url: '/:id/edit',
templateUrl: 'views/members/form.html',
controller: 'MembersCtrl'
})
.state('app.members.view', {
url: '/:id',
templateUrl: 'views/members/view.html',
controller: 'MembersCtrl'
});
})
.controller('MembersCtrl', function($scope, $state, $stateParams, $q, $interval, toasty, Member, SweetAlert, i18nService) {
var memberId = $stateParams.id;
i18nService.setCurrentLang('zh-cn');
$scope.importData = [];
$scope.gridImportOptions = {
enableGridMenu: true,
importerDataAddCallback: function( grid, newObjects ) {
$scope.importData = $scope.importData.concat( newObjects );
},
onRegisterApi: function(gridApi){
$scope.gridImportApi = gridApi;
gridApi.rowEdit.on.saveRow($scope, $scope.saveRow);
},
data: 'importData'
};
$scope.saveRow = function( rowEntity ) {
// create a fake promise - normally you'd use the promise returned by $http or $resource
var promise = $q.defer();
$scope.gridImportApi.rowEdit.setSavePromise( $scope.gridImportApi.grid, rowEntity, promise.promise );
$interval( function() {
promise.resolve();
}, 1000, 1);
};
$scope.saveImport = function () {
if ($scope.importData.length > 0) {
var members = $scope.importData;
for (var i=0;i<members.length;i++) {
var member = members[i];
member.created = new Date();
delete member.$$hashKey;
Member.upsert(member, function() {
}, function(err) {
console.log(err);
});
};
toasty.pop.success({title: '组员导入成功', msg: members.length + '个组员成功导入到系统中!', sound: false});
loadItems();
$state.go('^.list');
};
};
if (memberId) {
$scope.member = Member.findById({
id: memberId
}, function() {}, function(err) {
console.log(err);
});
} else {
$scope.member = {};
}
$scope.gridOptions = {
data: 'members',
enableFiltering: true,
paginationPageSizes: [5, 10, 15],
paginationPageSize: 10,
headerRowHeight: 39,
rowHeight: 39,
columnFooterHeight: 39,
gridFooterHeight: 39,
selectionRowHeaderWidth: 39,
columnDefs: [
{
name: 'Edit', width: 80, displayName: '编辑', enableSorting: false, enableFiltering: false, cellTemplate: '<a href="" class="ui-state-hover" ui-sref="^.edit({id: row.entity.id})"> <i class="fa fa-pencil fa-lg blue"></i></a> <a href="" class="ui-state-hover" style="margin-left:5px;" ng-click="getExternalScopes().delete({id: row.entity.id})"><i class="fa fa-trash-o fa-lg red"></i></a>'
},
{
name: 'name', displayName: '全称', cellTemplate: '<div class="ui-grid-cell-contents"><a href="" ui-sref="^.view({id: row.entity.id})"> {{ COL_FIELD }} </a></div>'}
,{
name: 'firstName', displayName: '姓'
}
,{
name: 'lastName', displayName: '名'
}
,{
name: 'displayName', displayName: '显示名'
}
,{
name: 'position', displayName: '职位'
}
, {
name: 'priority', displayName: '排序号'
}
],
enableGridMenu: true,
enableSelectAll: true,
exporterCsvFilename: 'members.csv',
exporterSuppressColumns: ['Edit'],
exporterPdfDefaultStyle: {fontSize: 9},
exporterPdfTableStyle: {margin: [30, 30, 30, 30]},
exporterPdfTableHeaderStyle: {fontSize: 10, bold: true, italics: true, color: 'red'},
exporterPdfHeader: { text: "Meeting Member Information", style: 'headerStyle' },
exporterPdfFooter: function ( currentPage, pageCount ) {
return { text: currentPage.toString() + ' of ' + pageCount.toString(), style: 'footerStyle' };
},
exporterPdfCustomFormatter: function ( docDefinition ) {
docDefinition.styles.headerStyle = { fontSize: 22, bold: true };
docDefinition.styles.footerStyle = { fontSize: 10, bold: true };
return docDefinition;
},
exporterPdfOrientation: 'portrait',
exporterPdfPageSize: 'LETTER',
exporterPdfMaxGridWidth: 500,
exporterCsvLinkElement: angular.element(document.querySelectorAll(".custom-csv-link-location"))
};
$scope.gridOptions.onRegisterApi = function (gridApi) {
$scope.gridApi = gridApi;
};
function loadItems() {
$scope.members = Member.find();
}
loadItems();
$scope.viewActions = {
delete : $scope.delete
};
$scope.delete = function(id) {
SweetAlert.swal({
title: '您确定要删除吗?',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#DD6B55'
}, function(isConfirm){
if (isConfirm) {
Member.deleteById(id, function() {
toasty.pop.success({title: '组员被删除', msg: '您成功删除了组员!', sound: false});
loadItems();
$state.go($state.current, {}, {reload: true});
//$state.go('app.members.list');
}, function(err) {
toasty.pop.error({title: '删除组员出错', msg: '删除组员发生错误:' + err, sound: false});
});
} else {
return false;
}
});
};
$scope.formFields = [{
key: 'name',
type: 'text',
label: '全名',
required: true
}, {
key: 'firstName',
type: 'text',
label: '姓',
required: true
}, {
key: 'lastName',
type: 'text',
label: '名',
required: true
}, {
key: 'displayName',
type: 'text',
label: '显示名',
required: true
}, {
key: 'position',
type: 'text',
label: '职位',
required: true
}, {
key: 'priority',
type: 'number',
label: '排序号',
required: true
}];
$scope.formOptions = {
uniqueFormId: true,
hideSubmit: false,
submitCopy: '保存'
};
$scope.onSubmit = function() {
if (($scope.member.created === null) || ($scope.member.created === undefined)){
$scope.member.created = new Date();
};
Member.upsert($scope.member, function() {
toasty.pop.success({title: '组员保存成功', msg: '组员已成功保存到系统中!', sound: false});
loadItems();
$state.go('^.list');
}, function(err) {
console.log(err);
});
};
});
| g8te/lubri | client/app/scripts/controllers/members.js | JavaScript | apache-2.0 | 7,033 |
package com.thinkgem.jeesite.modules.purifier.dao;
import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.thinkgem.jeesite.modules.purifier.entity.Ware;
/**
* 仓库管理dao
*
* @author addison
* @since 2017年03月02日
*/
@MyBatisDao
public interface WareDao extends CrudDao<Ware> {
int deleteByWare(Ware ware);
}
| cuiqunhao/jeesite | src/main/java/com/thinkgem/jeesite/modules/purifier/dao/WareDao.java | Java | apache-2.0 | 411 |
function buildName(firstName = "Will", lastName: string) {
return firstName + " " + lastName;
}
let result1 = buildName("Bob"); // error, too few parameters
let result2 = buildName("Bob", "Adams", "Sr."); // error, too many parameters
let result3 = buildName("Bob", "Adams"); // okay and returns "Bob Adams"
let result4 = buildName(undefined, "Adams"); // okay and returns "Will Adams" | XNSystemsStudy/Modern-Web-Development | src/170109-optional.ts | TypeScript | apache-2.0 | 420 |
#!/usr/bin/env ruby
require 'erb'
require 'json'
require 'optparse'
@target = nil
@users = 1
@concurrency = 1
@maxrate = 10
@maxhits = nil
OptionParser.new do | opts |
opts.banner = "Usage: generate.rb [options] target"
opts.on('--target [string]', "Specify the target server for requests (required)") do | v |
@target = v.split(':')
end
opts.on('--virtual-users [int]', Integer, "Specify the number of virtual users (default: #{@users})") do | v |
@users = v
end
opts.on('--virtual-user-clones [int]', Integer, "Specify the number of each virtual user clones (default: #{@concurrency})") do | v |
@concurrency = v
end
opts.on('--max-request-rate [float]', Float, "Specify the maximum requests per minute (default: #{@maxrate})") do | v |
@maxrate = v
end
opts.on('--max-hits [int]', Integer, "Maximum number of hits to generate jmeter requests (default: #{@maxhits})") do | v |
@maxhits = v
end
opts.on('-h', '--help', 'Display this help') do
puts opts
exit
end
end.parse!
raise OptionParser::InvalidOption if @target.nil?
json = JSON.parse ARGF.read
@buckets = Array.new(@users) { Array.new }
json['hits']['hits'].each_with_index do | hit, i |
next if not @maxhits.nil? and i > @maxhits
source = hit['_source']
next if '/_bulk' == source['path']
@buckets[i % @users].push(
{
:id => hit['_index'] + ':' + hit['_id'],
:method => source['method'],
:path => source['path'],
:querydata => source['querystr'],
:requestdata => source['data'],
}
)
end
template = ERB.new File.new("jmeter.jmx.erb").read, nil, "%"
puts template.result(binding)
| cityindex-attic/logsearch | example/jmeter-loadtest/generate.rb | Ruby | apache-2.0 | 1,659 |
/*
* @(#)TIFFHeader.java
*
* $Date: 2014-03-13 04:15:48 -0400 (Thu, 13 Mar 2014) $
*
* Copyright (c) 2011 by Jeremy Wood.
* All rights reserved.
*
* The copyright of this software is owned by Jeremy Wood.
* You may not use, copy or modify this software, except in
* accordance with the license agreement you entered into with
* Jeremy Wood. For details see accompanying license terms.
*
* This software is probably, but not necessarily, discussed here:
* https://javagraphics.java.net/
*
* That site should also contain the most recent official version
* of this software. (See the SVN repository for more details.)
*
Modified BSD License
Copyright (c) 2015, Jeremy Wood.
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.
* The name of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package gr.iti.mklab.reveal.forensics.util.ThumbnailExtractor.image.jpeg;
import java.io.IOException;
import java.io.InputStream;
class TIFFHeader {
boolean bigEndian;
int ifdOffset;
TIFFHeader(InputStream in) throws IOException {
byte[] array = new byte[4];
if(JPEGMarkerInputStream.readFully(in, array, 2, false)!=2) {
throw new IOException("Incomplete TIFF Header");
}
if(array[0]==73 && array[1]==73) { //little endian
bigEndian = false;
} else if(array[0]==77 && array[1]==77) { //big endian
bigEndian = true;
} else {
throw new IOException("Unrecognized endian encoding.");
}
if(JPEGMarkerInputStream.readFully(in, array, 2, !bigEndian)!=2) {
throw new IOException("Incomplete TIFF Header");
}
if(!(array[0]==0 && array[1]==42)) { //required byte in TIFF header
throw new IOException("Missing required identifier 0x002A.");
}
if(JPEGMarkerInputStream.readFully(in, array, 4, !bigEndian)!=4) {
throw new IOException("Incomplete TIFF Header");
}
ifdOffset = ((array[0] & 0xff) << 24) + ((array[1] & 0xff) << 16) +
((array[2] & 0xff) << 8) + ((array[3] & 0xff) << 0) ;
}
/** The length of this TIFF header. */
int getLength() {
return 8;
}
}
| MKLab-ITI/image-forensics | java_service/src/main/java/gr/iti/mklab/reveal/forensics/util/ThumbnailExtractor/image/jpeg/TIFFHeader.java | Java | apache-2.0 | 3,339 |
<?php
use App\Models\Post;
use Illuminate\Support\Facades\DB;
use Test\Factory;
use Test\TestCase;
class PostControllerTest extends TestCase {
public function setUp() {
parent::setUp();
DB::table('posts')->delete();
$this->user = Factory::create('user');
$this->be($this->user);
}
public function testIndex()
{
$this->call('GET', 'posts');
$this->assertResponseOk();
$this->assertViewHas('posts');
}
public function testCreate()
{
$this->call('GET', 'posts/create');
$this->assertResponseOk();
}
public function testStore()
{
$countPosts = Post::count();
$inputs = [
'title' => 'title POst',
'content' => 'Content posts'
];
$this->call('POST', 'posts', $inputs);
$this->assertEquals($countPosts + 1, Post::count());
$this->assertRedirectedTo('/posts');
}
public function testEdit()
{
$post = Factory::create('post');
$this->call('GET', 'posts/'.$post->id.'/edit');
$this->assertResponseOk();
}
public function testUpdate()
{
$oldTitle = 'Old title';
$newTitle = 'New title';
$post = Factory::create('post', ['title' => $oldTitle]);
$inputs = [
'title' => $newTitle,
];
$this->shouldRedirectBack();
$this->call('PUT', 'posts/'.$post->id, $inputs);
$freshPost = Post::find($post->id);
$this->assertEquals($newTitle, $freshPost->title);
}
public function testDestroy()
{
$post = Factory::create('post');
$countPosts = Post::count();
$this->shouldRedirectBack();
$this->call('DELETE', 'posts/'.$post->id);
$this->assertEquals($countPosts - 1, Post::count());
}
}
| pinnackl/cabrette-dev | tests/Http/Controllers/PostControllerTest.php | PHP | apache-2.0 | 1,851 |
/**
*
*/
/**
* @author root
*
*/
package com.amanaje.activities; | damico/amanaje | source-code/Amanaje/src/com/amanaje/activities/package-info.java | Java | apache-2.0 | 70 |
package eu.ailao.hub.dialog;
import eu.ailao.hub.corefresol.answers.ClueMemorizer;
import eu.ailao.hub.corefresol.concepts.ConceptMemorizer;
import eu.ailao.hub.questions.Question;
import java.util.ArrayList;
/**
* Created by Petr Marek on 24.02.2016.
* Dialog class represents dialog. It contains id of dialog and ids of questions in this dialog.
*/
public class Dialog {
private int id;
private ArrayList<Question> questionsOfDialogue;
private ConceptMemorizer conceptMemorizer;
private ClueMemorizer clueMemorizer;
public Dialog(int id) {
this.id = id;
this.questionsOfDialogue = new ArrayList<>();
this.conceptMemorizer = new ConceptMemorizer();
this.clueMemorizer = new ClueMemorizer();
}
/**
* Adds question to dialog
* @param questionID id of question
*/
public void addQuestion(Question questionID) {
questionsOfDialogue.add(questionID);
}
public ArrayList<Question> getQuestions() {
return questionsOfDialogue;
}
/**
* Gets all question's ids of dialog
* @return array list of question's ids in dialog
*/
public ArrayList<Integer> getQuestionsIDs() {
ArrayList<Integer> questionIDs = new ArrayList<Integer>();
for (int i = 0; i < questionsOfDialogue.size(); i++) {
questionIDs.add(questionsOfDialogue.get(i).getYodaQuestionID());
}
return questionIDs;
}
public int getId() {
return id;
}
public ConceptMemorizer getConceptMemorizer() {
return conceptMemorizer;
}
public ClueMemorizer getClueMemorizer() {
return clueMemorizer;
}
public boolean hasQuestionWithId(int id) {
for (Question question : questionsOfDialogue) {
if (question.getYodaQuestionID() == id) {
return true;
}
}
return false;
}
}
| brmson/hub | src/main/java/eu/ailao/hub/dialog/Dialog.java | Java | apache-2.0 | 1,699 |
// Copyright 2016 Yahoo Inc.
// Licensed under the terms of the Apache license. Please see LICENSE.md file distributed with this work for terms.
package com.yahoo.bard.webservice.data.metric;
/**
* LogicalMetricColumn.
*/
public class LogicalMetricColumn extends MetricColumn {
private final LogicalMetric metric;
/**
* Constructor.
*
* @param name The column name
* @param metric The logical metric
*
* @deprecated because LogicalMetricColumn is really only a thing for LogicalTable, so there's no reason for there
* to be an alias on the LogicalMetric inside the LogicalTableSchema.
*/
@Deprecated
public LogicalMetricColumn(String name, LogicalMetric metric) {
super(name);
this.metric = metric;
}
/**
* Constructor.
*
* @param metric The logical metric
*/
public LogicalMetricColumn(LogicalMetric metric) {
super(metric.getName());
this.metric = metric;
}
/**
* Getter for a logical metric.
*
* @return logical metric
*/
public LogicalMetric getLogicalMetric() {
return this.metric;
}
@Override
public String toString() {
return "{logicalMetric:'" + getName() + "'}";
}
}
| yahoo/fili | fili-core/src/main/java/com/yahoo/bard/webservice/data/metric/LogicalMetricColumn.java | Java | apache-2.0 | 1,271 |
package esidev
import (
"net/http"
"time"
"github.com/gorilla/mux"
)
var _ time.Time
var _ = mux.NewRouter
func GetIncursions(w http.ResponseWriter, r *http.Request) {
var (
localV interface{}
err error
datasource string
)
// shut up warnings
localV = localV
err = err
j := `[ {
"constellation_id" : 20000607,
"faction_id" : 500019,
"has_boss" : true,
"infested_solar_systems" : [ 30004148, 30004149, 30004150, 30004151, 30004152, 30004153, 30004154 ],
"influence" : 0.9,
"staging_solar_system_id" : 30004154,
"state" : "mobilizing",
"type" : "Incursion"
} ]`
if err := r.ParseForm(); err != nil {
errorOut(w, r, err)
return
}
if r.Form.Get("datasource") != "" {
localV, err = processParameters(datasource, r.Form.Get("datasource"))
if err != nil {
errorOut(w, r, err)
return
}
datasource = localV.(string)
}
if r.Form.Get("page") != "" {
var (
localPage int32
localIntPage interface{}
)
localIntPage, err := processParameters(localPage, r.Form.Get("page"))
if err != nil {
errorOut(w, r, err)
return
}
localPage = localIntPage.(int32)
if localPage > 1 {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte("[]"))
return
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(j))
}
| antihax/mock-esi | dev/go/api_incursions.go | GO | apache-2.0 | 1,390 |
using System.Collections.Generic;
using RestSharp;
using SimpleJson;
namespace MoneySharp.Internal.Model
{
public class SalesInvoicePost : SalesInvoice
{
public IList<SalesInvoiceDetail> details_attributes { get; set; }
public JsonObject custom_fields_attributes { get; set; }
}
} | SpringIT/moneysharp | src/MoneySharp/Internal/Model/SalesInvoicePost.cs | C# | apache-2.0 | 322 |
package coop.ekologia.presentation.controller.user;
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import coop.ekologia.presentation.EkologiaServlet;
import coop.ekologia.presentation.session.LoginSession;
/**
* Servlet implementation class LoginConnectionServlet
*/
@WebServlet(LoginDeconnectionServlet.routing)
public class LoginDeconnectionServlet extends EkologiaServlet {
private static final long serialVersionUID = 1L;
public static final String routing = "/login/deconnection";
public static final String routing(HttpServletRequest request) {
return getUrl(request, routing);
}
@Inject
LoginSession loginSession;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginDeconnectionServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
loginSession.setUser(null);
response.sendRedirect(request.getHeader("referer"));
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
| imie-source/Ekologia | EkologiaGUI/src/coop/ekologia/presentation/controller/user/LoginDeconnectionServlet.java | Java | apache-2.0 | 1,605 |
/*
* Copyright 2010-2020 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.engine.impl.cmd;
import java.io.InputStream;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.delegate.event.impl.ActivitiEventBuilder;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.AttachmentEntity;
import org.activiti.engine.impl.persistence.entity.ByteArrayEntity;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.util.IoUtil;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Attachment;
import org.activiti.engine.task.Task;
/**
*/
// Not Serializable
public class CreateAttachmentCmd implements Command<Attachment> {
protected String attachmentType;
protected String taskId;
protected String processInstanceId;
protected String attachmentName;
protected String attachmentDescription;
protected InputStream content;
protected String url;
public CreateAttachmentCmd(String attachmentType, String taskId, String processInstanceId, String attachmentName, String attachmentDescription, InputStream content, String url) {
this.attachmentType = attachmentType;
this.taskId = taskId;
this.processInstanceId = processInstanceId;
this.attachmentName = attachmentName;
this.attachmentDescription = attachmentDescription;
this.content = content;
this.url = url;
}
public Attachment execute(CommandContext commandContext) {
if (taskId != null) {
verifyTaskParameters(commandContext);
}
if (processInstanceId != null) {
verifyExecutionParameters(commandContext);
}
return executeInternal(commandContext);
}
protected Attachment executeInternal(CommandContext commandContext) {
AttachmentEntity attachment = commandContext.getAttachmentEntityManager().create();
attachment.setName(attachmentName);
attachment.setProcessInstanceId(processInstanceId);
attachment.setTaskId(taskId);
attachment.setDescription(attachmentDescription);
attachment.setType(attachmentType);
attachment.setUrl(url);
attachment.setUserId(Authentication.getAuthenticatedUserId());
attachment.setTime(commandContext.getProcessEngineConfiguration().getClock().getCurrentTime());
commandContext.getAttachmentEntityManager().insert(attachment, false);
if (content != null) {
byte[] bytes = IoUtil.readInputStream(content, attachmentName);
ByteArrayEntity byteArray = commandContext.getByteArrayEntityManager().create();
byteArray.setBytes(bytes);
commandContext.getByteArrayEntityManager().insert(byteArray);
attachment.setContentId(byteArray.getId());
attachment.setContent(byteArray);
}
commandContext.getHistoryManager().createAttachmentComment(taskId, processInstanceId, attachmentName, true);
if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
// Forced to fetch the process-instance to associate the right
// process definition
String processDefinitionId = null;
if (attachment.getProcessInstanceId() != null) {
ExecutionEntity process = commandContext.getExecutionEntityManager().findById(processInstanceId);
if (process != null) {
processDefinitionId = process.getProcessDefinitionId();
}
}
commandContext.getProcessEngineConfiguration().getEventDispatcher()
.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_CREATED, attachment, processInstanceId, processInstanceId, processDefinitionId));
commandContext.getProcessEngineConfiguration().getEventDispatcher()
.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_INITIALIZED, attachment, processInstanceId, processInstanceId, processDefinitionId));
}
return attachment;
}
protected TaskEntity verifyTaskParameters(CommandContext commandContext) {
TaskEntity task = commandContext.getTaskEntityManager().findById(taskId);
if (task == null) {
throw new ActivitiObjectNotFoundException("Cannot find task with id " + taskId, Task.class);
}
if (task.isSuspended()) {
throw new ActivitiException("It is not allowed to add an attachment to a suspended task");
}
return task;
}
protected ExecutionEntity verifyExecutionParameters(CommandContext commandContext) {
ExecutionEntity execution = commandContext.getExecutionEntityManager().findById(processInstanceId);
if (execution == null) {
throw new ActivitiObjectNotFoundException("Process instance " + processInstanceId + " doesn't exist", ProcessInstance.class);
}
if (execution.isSuspended()) {
throw new ActivitiException("It is not allowed to add an attachment to a suspended process instance");
}
return execution;
}
}
| Activiti/Activiti | activiti-core/activiti-engine/src/main/java/org/activiti/engine/impl/cmd/CreateAttachmentCmd.java | Java | apache-2.0 | 5,884 |
package org.seasar.doma.internal.jdbc.dialect;
import org.seasar.doma.internal.jdbc.sql.SimpleSqlNodeVisitor;
import org.seasar.doma.internal.jdbc.sql.node.AnonymousNode;
import org.seasar.doma.jdbc.SqlNode;
public class StandardCountCalculatingTransformer extends SimpleSqlNodeVisitor<SqlNode, Void> {
protected boolean processed;
public SqlNode transform(SqlNode sqlNode) {
AnonymousNode result = new AnonymousNode();
for (SqlNode child : sqlNode.getChildren()) {
result.appendNode(child.accept(this, null));
}
return result;
}
@Override
protected SqlNode defaultAction(SqlNode node, Void p) {
return node;
}
}
| domaframework/doma | doma-core/src/main/java/org/seasar/doma/internal/jdbc/dialect/StandardCountCalculatingTransformer.java | Java | apache-2.0 | 656 |
package marcin_szyszka.mobileseconndhand.models;
/**
* Created by marcianno on 2016-03-02.
*/
public class RegisterUserModel {
public String Email;
public String Password;
public String ConfirmPassword;
public RegisterUserModel(){
}
}
| MarcinSzyszka/MobileSecondHand | AndroidStudio_Android/MobileSeconndHand/app/src/main/java/marcin_szyszka/mobileseconndhand/models/RegisterUserModel.java | Java | apache-2.0 | 260 |