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 |
|---|---|---|---|---|---|
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtMultimedia module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists for the convenience
// of other Qt classes. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
#include "qaudioinput_win32_p.h"
QT_BEGIN_NAMESPACE
//#define DEBUG_AUDIO 1
QAudioInputPrivate::QAudioInputPrivate(const QByteArray &device, const QAudioFormat& audioFormat):
settings(audioFormat)
{
bytesAvailable = 0;
buffer_size = 0;
period_size = 0;
m_device = device;
totalTimeValue = 0;
intervalTime = 1000;
errorState = QAudio::NoError;
deviceState = QAudio::StoppedState;
audioSource = 0;
pullMode = true;
resuming = false;
finished = false;
}
QAudioInputPrivate::~QAudioInputPrivate()
{
stop();
}
void QT_WIN_CALLBACK QAudioInputPrivate::waveInProc( HWAVEIN hWaveIn, UINT uMsg,
DWORD dwInstance, DWORD dwParam1, DWORD dwParam2 )
{
Q_UNUSED(dwParam1)
Q_UNUSED(dwParam2)
Q_UNUSED(hWaveIn)
QAudioInputPrivate* qAudio;
qAudio = (QAudioInputPrivate*)(dwInstance);
if(!qAudio)
return;
QMutexLocker(&qAudio->mutex);
switch(uMsg) {
case WIM_OPEN:
break;
case WIM_DATA:
if(qAudio->waveFreeBlockCount > 0)
qAudio->waveFreeBlockCount--;
qAudio->feedback();
break;
case WIM_CLOSE:
qAudio->finished = true;
break;
default:
return;
}
}
WAVEHDR* QAudioInputPrivate::allocateBlocks(int size, int count)
{
int i;
unsigned char* buffer;
WAVEHDR* blocks;
DWORD totalBufferSize = (size + sizeof(WAVEHDR))*count;
if((buffer=(unsigned char*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
totalBufferSize)) == 0) {
qWarning("QAudioInput: Memory allocation error");
return 0;
}
blocks = (WAVEHDR*)buffer;
buffer += sizeof(WAVEHDR)*count;
for(i = 0; i < count; i++) {
blocks[i].dwBufferLength = size;
blocks[i].lpData = (LPSTR)buffer;
blocks[i].dwBytesRecorded=0;
blocks[i].dwUser = 0L;
blocks[i].dwFlags = 0L;
blocks[i].dwLoops = 0L;
result = waveInPrepareHeader(hWaveIn,&blocks[i], sizeof(WAVEHDR));
if(result != MMSYSERR_NOERROR) {
qWarning("QAudioInput: Can't prepare block %d",i);
return 0;
}
buffer += size;
}
return blocks;
}
void QAudioInputPrivate::freeBlocks(WAVEHDR* blockArray)
{
WAVEHDR* blocks = blockArray;
int count = buffer_size/period_size;
for(int i = 0; i < count; i++) {
waveInUnprepareHeader(hWaveIn,blocks, sizeof(WAVEHDR));
blocks++;
}
HeapFree(GetProcessHeap(), 0, blockArray);
}
QAudio::Error QAudioInputPrivate::error() const
{
return errorState;
}
QAudio::State QAudioInputPrivate::state() const
{
return deviceState;
}
QAudioFormat QAudioInputPrivate::format() const
{
return settings;
}
QIODevice* QAudioInputPrivate::start(QIODevice* device)
{
if(deviceState != QAudio::StoppedState)
close();
if(!pullMode && audioSource) {
delete audioSource;
}
if(device) {
//set to pull mode
pullMode = true;
audioSource = device;
deviceState = QAudio::ActiveState;
} else {
//set to push mode
pullMode = false;
deviceState = QAudio::IdleState;
audioSource = new InputPrivate(this);
audioSource->open(QIODevice::ReadOnly | QIODevice::Unbuffered);
}
if( !open() )
return 0;
emit stateChanged(deviceState);
return audioSource;
}
void QAudioInputPrivate::stop()
{
if(deviceState == QAudio::StoppedState)
return;
close();
emit stateChanged(deviceState);
}
bool QAudioInputPrivate::open()
{
#ifdef DEBUG_AUDIO
QTime now(QTime::currentTime());
qDebug()<<now.second()<<"s "<<now.msec()<<"ms :open()";
#endif
header = 0;
period_size = 0;
if (!settings.isValid()) {
qWarning("QAudioInput: open error, invalid format.");
} else if (settings.channels() <= 0) {
qWarning("QAudioInput: open error, invalid number of channels (%d).",
settings.channels());
} else if (settings.sampleSize() <= 0) {
qWarning("QAudioInput: open error, invalid sample size (%d).",
settings.sampleSize());
} else if (settings.frequency() < 8000 || settings.frequency() > 48000) {
qWarning("QAudioInput: open error, frequency out of range (%d).", settings.frequency());
} else if (buffer_size == 0) {
buffer_size
= (settings.frequency()
* settings.channels()
* settings.sampleSize()
#ifndef Q_OS_WINCE // Default buffer size, 200ms, default period size is 40ms
+ 39) / 40;
period_size = buffer_size / 5;
} else {
period_size = buffer_size / 5;
#else // For wince reduce size to 40ms for buffer size and 20ms period
+ 199) / 200;
period_size = buffer_size / 2;
} else {
period_size = buffer_size / 2;
#endif
}
if (period_size == 0) {
errorState = QAudio::OpenError;
deviceState = QAudio::StoppedState;
emit stateChanged(deviceState);
return false;
}
timeStamp.restart();
elapsedTimeOffset = 0;
wfx.nSamplesPerSec = settings.frequency();
wfx.wBitsPerSample = settings.sampleSize();
wfx.nChannels = settings.channels();
wfx.cbSize = 0;
wfx.wFormatTag = WAVE_FORMAT_PCM;
wfx.nBlockAlign = (wfx.wBitsPerSample >> 3) * wfx.nChannels;
wfx.nAvgBytesPerSec = wfx.nBlockAlign * wfx.nSamplesPerSec;
UINT_PTR devId = WAVE_MAPPER;
WAVEINCAPS wic;
unsigned long iNumDevs,ii;
iNumDevs = waveInGetNumDevs();
for(ii=0;ii<iNumDevs;ii++) {
if(waveInGetDevCaps(ii, &wic, sizeof(WAVEINCAPS))
== MMSYSERR_NOERROR) {
QString tmp;
tmp = QString((const QChar *)wic.szPname);
if(tmp.compare(QLatin1String(m_device)) == 0) {
devId = ii;
break;
}
}
}
if(waveInOpen(&hWaveIn, devId, &wfx,
(DWORD_PTR)&waveInProc,
(DWORD_PTR) this,
CALLBACK_FUNCTION) != MMSYSERR_NOERROR) {
errorState = QAudio::OpenError;
deviceState = QAudio::StoppedState;
emit stateChanged(deviceState);
qWarning("QAudioInput: failed to open audio device");
return false;
}
waveBlocks = allocateBlocks(period_size, buffer_size/period_size);
if(waveBlocks == 0) {
errorState = QAudio::OpenError;
deviceState = QAudio::StoppedState;
emit stateChanged(deviceState);
qWarning("QAudioInput: failed to allocate blocks. open failed");
return false;
}
mutex.lock();
waveFreeBlockCount = buffer_size/period_size;
mutex.unlock();
waveCurrentBlock = 0;
for(int i=0; i<buffer_size/period_size; i++) {
result = waveInAddBuffer(hWaveIn, &waveBlocks[i], sizeof(WAVEHDR));
if(result != MMSYSERR_NOERROR) {
qWarning("QAudioInput: failed to setup block %d,err=%d",i,result);
errorState = QAudio::OpenError;
deviceState = QAudio::StoppedState;
emit stateChanged(deviceState);
return false;
}
}
result = waveInStart(hWaveIn);
if(result) {
qWarning("QAudioInput: failed to start audio input");
errorState = QAudio::OpenError;
deviceState = QAudio::StoppedState;
emit stateChanged(deviceState);
return false;
}
timeStampOpened.restart();
elapsedTimeOffset = 0;
totalTimeValue = 0;
errorState = QAudio::NoError;
return true;
}
void QAudioInputPrivate::close()
{
if(deviceState == QAudio::StoppedState)
return;
deviceState = QAudio::StoppedState;
waveInReset(hWaveIn);
waveInClose(hWaveIn);
int count = 0;
while(!finished && count < 500) {
count++;
Sleep(10);
}
mutex.lock();
for(int i=0; i<waveFreeBlockCount; i++)
waveInUnprepareHeader(hWaveIn,&waveBlocks[i],sizeof(WAVEHDR));
freeBlocks(waveBlocks);
mutex.unlock();
}
int QAudioInputPrivate::bytesReady() const
{
if(period_size == 0 || buffer_size == 0)
return 0;
int buf = ((buffer_size/period_size)-waveFreeBlockCount)*period_size;
if(buf < 0)
buf = 0;
return buf;
}
qint64 QAudioInputPrivate::read(char* data, qint64 len)
{
bool done = false;
char* p = data;
qint64 l = 0;
qint64 written = 0;
while(!done) {
// Read in some audio data
if(waveBlocks[header].dwBytesRecorded > 0 && waveBlocks[header].dwFlags & WHDR_DONE) {
if(pullMode) {
l = audioSource->write(waveBlocks[header].lpData,
waveBlocks[header].dwBytesRecorded);
#ifdef DEBUG_AUDIO
qDebug()<<"IN: "<<waveBlocks[header].dwBytesRecorded<<", OUT: "<<l;
#endif
if(l < 0) {
// error
qWarning("QAudioInput: IOError");
errorState = QAudio::IOError;
} else if(l == 0) {
// cant write to IODevice
qWarning("QAudioInput: IOError, can't write to QIODevice");
errorState = QAudio::IOError;
} else {
totalTimeValue += waveBlocks[header].dwBytesRecorded;
errorState = QAudio::NoError;
if (deviceState != QAudio::ActiveState) {
deviceState = QAudio::ActiveState;
emit stateChanged(deviceState);
}
resuming = false;
}
} else {
l = qMin<qint64>(len, waveBlocks[header].dwBytesRecorded);
// push mode
memcpy(p, waveBlocks[header].lpData, l);
len -= l;
#ifdef DEBUG_AUDIO
qDebug()<<"IN: "<<waveBlocks[header].dwBytesRecorded<<", OUT: "<<l;
#endif
totalTimeValue += waveBlocks[header].dwBytesRecorded;
errorState = QAudio::NoError;
if (deviceState != QAudio::ActiveState) {
deviceState = QAudio::ActiveState;
emit stateChanged(deviceState);
}
resuming = false;
}
} else {
//no data, not ready yet, next time
break;
}
waveInUnprepareHeader(hWaveIn,&waveBlocks[header], sizeof(WAVEHDR));
mutex.lock();
waveFreeBlockCount++;
mutex.unlock();
waveBlocks[header].dwBytesRecorded=0;
waveBlocks[header].dwFlags = 0L;
result = waveInPrepareHeader(hWaveIn,&waveBlocks[header], sizeof(WAVEHDR));
if(result != MMSYSERR_NOERROR) {
result = waveInPrepareHeader(hWaveIn,&waveBlocks[header], sizeof(WAVEHDR));
qWarning("QAudioInput: failed to prepare block %d,err=%d",header,result);
errorState = QAudio::IOError;
mutex.lock();
waveFreeBlockCount--;
mutex.unlock();
return 0;
}
result = waveInAddBuffer(hWaveIn, &waveBlocks[header], sizeof(WAVEHDR));
if(result != MMSYSERR_NOERROR) {
qWarning("QAudioInput: failed to setup block %d,err=%d",header,result);
errorState = QAudio::IOError;
mutex.lock();
waveFreeBlockCount--;
mutex.unlock();
return 0;
}
header++;
if(header >= buffer_size/period_size)
header = 0;
p+=l;
mutex.lock();
if(!pullMode) {
if(len < period_size || waveFreeBlockCount == buffer_size/period_size)
done = true;
} else {
if(waveFreeBlockCount == buffer_size/period_size)
done = true;
}
mutex.unlock();
written+=l;
}
#ifdef DEBUG_AUDIO
qDebug()<<"read in len="<<written;
#endif
return written;
}
void QAudioInputPrivate::resume()
{
if(deviceState == QAudio::SuspendedState) {
deviceState = QAudio::ActiveState;
for(int i=0; i<buffer_size/period_size; i++) {
result = waveInAddBuffer(hWaveIn, &waveBlocks[i], sizeof(WAVEHDR));
if(result != MMSYSERR_NOERROR) {
qWarning("QAudioInput: failed to setup block %d,err=%d",i,result);
errorState = QAudio::OpenError;
deviceState = QAudio::StoppedState;
emit stateChanged(deviceState);
return;
}
}
mutex.lock();
waveFreeBlockCount = buffer_size/period_size;
mutex.unlock();
waveCurrentBlock = 0;
header = 0;
resuming = true;
waveInStart(hWaveIn);
QTimer::singleShot(20,this,SLOT(feedback()));
emit stateChanged(deviceState);
}
}
void QAudioInputPrivate::setBufferSize(int value)
{
buffer_size = value;
}
int QAudioInputPrivate::bufferSize() const
{
return buffer_size;
}
int QAudioInputPrivate::periodSize() const
{
return period_size;
}
void QAudioInputPrivate::setNotifyInterval(int ms)
{
intervalTime = qMax(0, ms);
}
int QAudioInputPrivate::notifyInterval() const
{
return intervalTime;
}
qint64 QAudioInputPrivate::processedUSecs() const
{
if (deviceState == QAudio::StoppedState)
return 0;
qint64 result = qint64(1000000) * totalTimeValue /
(settings.channels()*(settings.sampleSize()/8)) /
settings.frequency();
return result;
}
void QAudioInputPrivate::suspend()
{
if(deviceState == QAudio::ActiveState) {
waveInReset(hWaveIn);
deviceState = QAudio::SuspendedState;
emit stateChanged(deviceState);
}
}
void QAudioInputPrivate::feedback()
{
#ifdef DEBUG_AUDIO
QTime now(QTime::currentTime());
qDebug()<<now.second()<<"s "<<now.msec()<<"ms :feedback() INPUT "<<this;
#endif
if(!(deviceState==QAudio::StoppedState||deviceState==QAudio::SuspendedState))
QMetaObject::invokeMethod(this, "deviceReady", Qt::QueuedConnection);
}
bool QAudioInputPrivate::deviceReady()
{
bytesAvailable = bytesReady();
#ifdef DEBUG_AUDIO
QTime now(QTime::currentTime());
qDebug()<<now.second()<<"s "<<now.msec()<<"ms :deviceReady() INPUT";
#endif
if(deviceState != QAudio::ActiveState && deviceState != QAudio::IdleState)
return true;
if(pullMode) {
// reads some audio data and writes it to QIODevice
read(0, buffer_size);
} else {
// emits readyRead() so user will call read() on QIODevice to get some audio data
InputPrivate* a = qobject_cast<InputPrivate*>(audioSource);
a->trigger();
}
if(intervalTime && (timeStamp.elapsed() + elapsedTimeOffset) > intervalTime) {
emit notify();
elapsedTimeOffset = timeStamp.elapsed() + elapsedTimeOffset - intervalTime;
timeStamp.restart();
}
return true;
}
qint64 QAudioInputPrivate::elapsedUSecs() const
{
if (deviceState == QAudio::StoppedState)
return 0;
return timeStampOpened.elapsed()*1000;
}
void QAudioInputPrivate::reset()
{
close();
}
InputPrivate::InputPrivate(QAudioInputPrivate* audio)
{
audioDevice = qobject_cast<QAudioInputPrivate*>(audio);
}
InputPrivate::~InputPrivate() {}
qint64 InputPrivate::readData( char* data, qint64 len)
{
// push mode, user read() called
if(audioDevice->deviceState != QAudio::ActiveState &&
audioDevice->deviceState != QAudio::IdleState)
return 0;
// Read in some audio data
return audioDevice->read(data,len);
}
qint64 InputPrivate::writeData(const char* data, qint64 len)
{
Q_UNUSED(data)
Q_UNUSED(len)
emit readyRead();
return 0;
}
void InputPrivate::trigger()
{
emit readyRead();
}
QT_END_NAMESPACE
| kobolabs/qt-everywhere-4.8.0 | src/multimedia/audio/qaudioinput_win32_p.cpp | C++ | lgpl-2.1 | 17,735 |
package railo.runtime.sql;
public class SQLParserException extends Exception {
public SQLParserException(String message) {
super(message);
}
}
| JordanReiter/railo | railo-java/railo-core/src/railo/runtime/sql/SQLParserException.java | Java | lgpl-2.1 | 150 |
//
// Boost.Process
//
// Copyright (c) 2006 Julio M. Merino Vidal.
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt.)
//
//!
//! \file boost/process/detail/win32_ops.hpp
//!
//! Provides some convenience functions to start processes under Win32
//! operating systems.
//!
#if !defined(BOOST_PROCESS_DETAIL_WIN32_OPS_HPP)
/** \cond */
#define BOOST_PROCESS_DETAIL_WIN32_OPS_HPP
/** \endcond */
#include <boost/process/config.hpp>
#if !defined(BOOST_PROCESS_WIN32_API)
# error "Unsupported platform."
#endif
extern "C" {
#include <tchar.h>
#include <windows.h>
// Added for OpenLieroX - Dev-Cpp workarounds
#if defined(WIN32) && defined(__GNUC__)
#define _tcscpy_s(D,N,S) _tcscpy(D,S)
#define _tcscat_s(D,N,S) _tcscat(D,S)
#endif
}
#include <boost/optional.hpp>
#include <boost/process/detail/file_handle.hpp>
#include <boost/process/detail/pipe.hpp>
#include <boost/process/detail/stream_info.hpp>
#include <boost/process/environment.hpp>
#include <boost/process/exceptions.hpp>
#include <boost/process/stream_behavior.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_array.hpp>
#include <boost/throw_exception.hpp>
namespace boost {
namespace process {
namespace detail {
// ------------------------------------------------------------------------
//!
//! \brief Converts the command line to a plain string.
//!
//! Converts the command line's list of arguments to the format
//! expected by the \a lpCommandLine parameter in the CreateProcess()
//! system call.
//!
//! This operation is only available in Win32 systems.
//!
//! \return A dynamically allocated string holding the command line
//! to be passed to the executable. It is returned in a
//! shared_array object to ensure its release at some point.
//!
template< class Arguments >
inline
boost::shared_array< TCHAR >
collection_to_win32_cmdline(const Arguments& args)
{
typedef std::vector< std::string > arguments_vector;
Arguments args2;
typename Arguments::size_type i = 0;
std::size_t length = 0;
for (typename Arguments::const_iterator iter = args.begin();
iter != args.end(); iter++) {
std::string arg = (*iter);
std::string::size_type pos = 0;
while ((pos = arg.find('"', pos)) != std::string::npos) {
arg.replace(pos, 1, "\\\"");
pos += 2;
}
if (arg.find(' ') != std::string::npos)
arg = '\"' + arg + '\"';
if (i != args.size() - 1)
arg += ' ';
args2.push_back(arg);
length += arg.size() + 1;
i++;
}
boost::shared_array< TCHAR > cmdline(new TCHAR[length]);
::_tcscpy_s(cmdline.get(), length, TEXT(""));
for (arguments_vector::size_type i = 0; i < args2.size(); i++)
::_tcscat_s(cmdline.get(), length, TEXT(args2[i].c_str()));
return cmdline;
}
// ------------------------------------------------------------------------
//!
//! \brief Converts an environment to a string used by CreateProcess().
//!
//! Converts the environment's contents to the format used by the
//! CreateProcess() system call. The returned TCHAR* string is
//! allocated in dynamic memory and the caller must free it when not
//! used any more. This is enforced by the use of a shared pointer.
//! The string is of the form var1=value1\\0var2=value2\\0\\0.
//!
inline
boost::shared_array< TCHAR >
environment_to_win32_strings(const environment& env)
{
boost::shared_array< TCHAR > strs(NULL);
// TODO: Add the "" variable to the returned string; it shouldn't
// be in the environment if the user didn't add it.
if (env.size() == 0) {
strs.reset(new TCHAR[2]);
::ZeroMemory(strs.get(), sizeof(TCHAR) * 2);
} else {
std::string::size_type len = sizeof(TCHAR);
for (environment::const_iterator iter = env.begin();
iter != env.end(); iter++)
len += ((*iter).first.length() + 1 + (*iter).second.length() +
1) * sizeof(TCHAR);
strs.reset(new TCHAR[len]);
TCHAR* ptr = strs.get();
for (environment::const_iterator iter = env.begin();
iter != env.end(); iter++) {
std::string tmp = (*iter).first + "=" + (*iter).second;
_tcscpy_s(ptr, len - (ptr - strs.get()) * sizeof(TCHAR),
TEXT(tmp.c_str()));
ptr += (tmp.length() + 1) * sizeof(TCHAR);
BOOST_ASSERT(static_cast< std::string::size_type >
(ptr - strs.get()) * sizeof(TCHAR) < len);
}
*ptr = '\0';
}
BOOST_ASSERT(strs.get() != NULL);
return strs;
}
// ------------------------------------------------------------------------
//!
//! \brief Helper class to configure a Win32 %child.
//!
//! This helper class is used to hold all the attributes that configure a
//! new Win32 %child process .
//!
//! All its fields are public for simplicity. It is only intended for
//! internal use and it is heavily coupled with the Launcher
//! implementations.
//!
struct win32_setup
{
//!
//! \brief The work directory.
//!
//! This string specifies the directory in which the %child process
//! starts execution. It cannot be empty.
//!
std::string m_work_directory;
//!
//! \brief The process startup properties.
//!
//! This Win32-specific object holds a list of properties that describe
//! how the new process should be started. The STARTF_USESTDHANDLES
//! flag should not be set in it because it is automatically configured
//! by win32_start().
//!
STARTUPINFO* m_startupinfo;
};
// ------------------------------------------------------------------------
//!
//! \brief Starts a new child process in a Win32 operating system.
//!
//! This helper functions is provided to simplify the Launcher's task when
//! it comes to starting up a new process in a Win32 operating system.
//!
//! \param cl The command line used to execute the child process.
//! \param env The environment variables that the new child process
//! receives.
//! \param infoin Information that describes stdin's behavior.
//! \param infoout Information that describes stdout's behavior.
//! \param infoerr Information that describes stderr's behavior.
//! \param setup A helper object holding extra child information.
//! \return The new process' information as returned by the ::CreateProcess
//! system call. The caller is responsible of creating an
//! appropriate Child representation for it.
//! \pre \a setup.m_startupinfo cannot have the \a STARTF_USESTDHANDLES set
//! in the \a dwFlags field.
//!
template< class Executable, class Arguments >
inline
PROCESS_INFORMATION
win32_start(const Executable& exe,
const Arguments& args,
const environment& env,
stream_info& infoin,
stream_info& infoout,
stream_info& infoerr,
const win32_setup& setup)
{
file_handle chin, chout, cherr;
BOOST_ASSERT(setup.m_startupinfo->cb >= sizeof(STARTUPINFO));
BOOST_ASSERT(!(setup.m_startupinfo->dwFlags & STARTF_USESTDHANDLES));
// XXX I'm not sure this usage of scoped_ptr is correct...
boost::scoped_ptr< STARTUPINFO > si
((STARTUPINFO*)new char[setup.m_startupinfo->cb]);
::CopyMemory(si.get(), setup.m_startupinfo, setup.m_startupinfo->cb);
si->dwFlags |= STARTF_USESTDHANDLES;
if (infoin.m_type == stream_info::close) {
} else if (infoin.m_type == stream_info::inherit) {
chin = file_handle::win32_std(STD_INPUT_HANDLE, true);
} else if (infoin.m_type == stream_info::use_file) {
HANDLE h = ::CreateFile(TEXT(infoin.m_file.c_str()), GENERIC_READ,
0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
NULL);
if (h == INVALID_HANDLE_VALUE)
boost::throw_exception
(system_error("boost::process::detail::win32_start",
"CreateFile failed", ::GetLastError()));
chin = file_handle(h);
} else if (infoin.m_type == stream_info::use_handle) {
chin = infoin.m_handle;
chin.win32_set_inheritable(true);
} else if (infoin.m_type == stream_info::use_pipe) {
infoin.m_pipe->rend().win32_set_inheritable(true);
chin = infoin.m_pipe->rend();
} else
BOOST_ASSERT(false);
si->hStdInput = chin.is_valid() ? chin.get() : INVALID_HANDLE_VALUE;
if (infoout.m_type == stream_info::close) {
} else if (infoout.m_type == stream_info::inherit) {
chout = file_handle::win32_std(STD_OUTPUT_HANDLE, true);
} else if (infoout.m_type == stream_info::use_file) {
HANDLE h = ::CreateFile(TEXT(infoout.m_file.c_str()), GENERIC_WRITE,
0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL,
NULL);
if (h == INVALID_HANDLE_VALUE)
boost::throw_exception
(system_error("boost::process::detail::win32_start",
"CreateFile failed", ::GetLastError()));
chout = file_handle(h);
} else if (infoout.m_type == stream_info::use_handle) {
chout = infoout.m_handle;
chout.win32_set_inheritable(true);
} else if (infoout.m_type == stream_info::use_pipe) {
infoout.m_pipe->wend().win32_set_inheritable(true);
chout = infoout.m_pipe->wend();
} else
BOOST_ASSERT(false);
si->hStdOutput = chout.is_valid() ? chout.get() : INVALID_HANDLE_VALUE;
if (infoerr.m_type == stream_info::close) {
} else if (infoerr.m_type == stream_info::inherit) {
cherr = file_handle::win32_std(STD_ERROR_HANDLE, true);
} else if (infoerr.m_type == stream_info::redirect) {
BOOST_ASSERT(infoerr.m_desc_to == 1);
BOOST_ASSERT(chout.is_valid());
cherr = file_handle::win32_dup(chout.get(), true);
} else if (infoerr.m_type == stream_info::use_file) {
HANDLE h = ::CreateFile(TEXT(infoerr.m_file.c_str()), GENERIC_WRITE,
0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL,
NULL);
if (h == INVALID_HANDLE_VALUE)
boost::throw_exception
(system_error("boost::process::detail::win32_start",
"CreateFile failed", ::GetLastError()));
cherr = file_handle(h);
} else if (infoerr.m_type == stream_info::use_handle) {
cherr = infoerr.m_handle;
cherr.win32_set_inheritable(true);
} else if (infoerr.m_type == stream_info::use_pipe) {
infoerr.m_pipe->wend().win32_set_inheritable(true);
cherr = infoerr.m_pipe->wend();
} else
BOOST_ASSERT(false);
si->hStdError = cherr.is_valid() ? cherr.get() : INVALID_HANDLE_VALUE;
PROCESS_INFORMATION pi;
::ZeroMemory(&pi, sizeof(pi));
boost::shared_array< TCHAR > cmdline = collection_to_win32_cmdline(args);
boost::scoped_array< TCHAR > executable(::_tcsdup(TEXT(exe.c_str())));
boost::scoped_array< TCHAR > workdir
(::_tcsdup(TEXT(setup.m_work_directory.c_str())));
boost::shared_array< TCHAR > envstrs = environment_to_win32_strings(env);
if (!::CreateProcess(executable.get(), cmdline.get(), NULL, NULL, TRUE,
0, envstrs.get(), workdir.get(),
si.get(), &pi)) {
boost::throw_exception
(system_error("boost::process::detail::win32_start",
"CreateProcess failed", ::GetLastError()));
}
return pi;
}
// ------------------------------------------------------------------------
} // namespace detail
} // namespace process
} // namespace boost
#endif // !defined(BOOST_PROCESS_DETAIL_WIN32_OPS_HPP)
| ProfessorKaos64/openlierox | libs/boost_process/boost/process/detail/win32_ops.hpp | C++ | lgpl-2.1 | 12,242 |
/*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.ade.containerpage.client.ui;
import org.opencms.ade.containerpage.client.CmsContainerpageHandler;
import org.opencms.gwt.client.ui.A_CmsToolbarButton;
import org.opencms.gwt.client.ui.I_CmsButton;
/**
* The publish button holding all publish related methods.<p>
*
* @since 8.0.0
*/
public class CmsToolbarPublishButton extends A_CmsToolbarButton<CmsContainerpageHandler> {
/**
* Constructor.<p>
*
* @param handler the container-page handler
*/
public CmsToolbarPublishButton(CmsContainerpageHandler handler) {
super(I_CmsButton.ButtonData.PUBLISH, handler);
}
/**
* @see org.opencms.gwt.client.ui.I_CmsToolbarButton#onToolbarActivate()
*/
public void onToolbarActivate() {
setEnabled(false);
getHandler().showPublishDialog();
}
/**
* @see org.opencms.gwt.client.ui.I_CmsToolbarButton#onToolbarDeactivate()
*/
public void onToolbarDeactivate() {
setEnabled(true);
}
}
| mediaworx/opencms-core | src-gwt/org/opencms/ade/containerpage/client/ui/CmsToolbarPublishButton.java | Java | lgpl-2.1 | 2,118 |
/*
* Minecraft Forge
* Copyright (c) 2016.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.relauncher;
public enum Side {
/**
* The client side. Specifically, an environment where rendering capability exists.
* Usually in the game client.
*/
CLIENT,
/**
* The server side. Specifically, an environment where NO rendering capability exists.
* Usually on the dedicated server.
*/
SERVER;
/**
* @return If this is the server environment
*/
public boolean isServer()
{
return !isClient();
}
/**
* @return if this is the Client environment
*/
public boolean isClient()
{
return this == CLIENT;
}
}
| jdpadrnos/MinecraftForge | src/main/java/net/minecraftforge/fml/relauncher/Side.java | Java | lgpl-2.1 | 1,398 |
/*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.gwt.shared;
import java.util.List;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* A bean that holds the upload file infos.<p>
*
* @since 8.0.0
*/
public class CmsUploadFileBean implements IsSerializable {
/** The active upload flag. */
private boolean m_active;
/** The list of resource names that already exist on the VFS. */
private List<String> m_existingFileNames;
/** The list of filenames that are invalid. */
private List<String> m_invalidFileNames;
/** The list of filenames that point to existing but deleted files. */
private List<String> m_existingDeletedFileNames;
/**
* The default constructor.<p>
*/
public CmsUploadFileBean() {
// noop
}
/**
* The constructor with parameters.<p>
*
* @param existingFileNames list of filenames that already exist on the VFS
* @param invalidFileNames list of filenames that are invalid
* @param existingDeleted the list of filenames that point to existing but deleted files
* @param active the upload active flag
*/
public CmsUploadFileBean(
List<String> existingFileNames,
List<String> invalidFileNames,
List<String> existingDeleted,
boolean active) {
m_existingFileNames = existingFileNames;
m_invalidFileNames = invalidFileNames;
m_existingDeletedFileNames = existingDeleted;
m_active = active;
}
/**
* Returns the list of filenames that point to existing but deleted files.<p>
*
* @return the list of filenames that point to existing but deleted files
*/
public List<String> getExistingDeletedFileNames() {
return m_existingDeletedFileNames;
}
/**
* Returns the list of resource names that already exist on the VFS.<p>
*
* @return the list of resource names that already exist on the VFS
*/
public List<String> getExistingResourceNames() {
return m_existingFileNames;
}
/**
* Returns the list of filenames that are invalid.<p>
*
* @return the list of filenames that are invalid
*/
public List<String> getInvalidFileNames() {
return m_invalidFileNames;
}
/**
* Returns the active.<p>
*
* @return the active
*/
public boolean isActive() {
return m_active;
}
/**
* Sets the active.<p>
*
* @param active the active to set
*/
public void setActive(boolean active) {
m_active = active;
}
/**
* Sets the list of filenames that point to existing but deleted files.<p>
*
* @param existingDeletedFileNames list of filenames that point to existing but deleted files
*/
public void setExistingDeletedFileNames(List<String> existingDeletedFileNames) {
m_existingDeletedFileNames = existingDeletedFileNames;
}
/**
* Sets the list of resource names that already exist on the VFS.<p>
*
* @param existingResourceNames the list of resource names that already exist on the VFS to set
*/
public void setExistingResourceNames(List<String> existingResourceNames) {
m_existingFileNames = existingResourceNames;
}
/**
* Sets the list of filenames that are invalid.<p>
*
* @param invalidFileNames the list of filenames that are invalid to set
*/
public void setInvalidFileNames(List<String> invalidFileNames) {
m_invalidFileNames = invalidFileNames;
}
}
| ggiudetti/opencms-core | src/org/opencms/gwt/shared/CmsUploadFileBean.java | Java | lgpl-2.1 | 4,656 |
/*
* OpenRPT report writer and rendering engine
* Copyright (C) 2001-2011 by OpenMFG, LLC
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Please contact info@openmfg.com with any questions on this license.
*/
/*
* This file contains the implementation of the Code 128 barcode renderer.
* All this code assumes a 100dpi rendering surface for it's calculations.
*/
#include <QString>
#include <QVector>
#include <QRect>
#include <QPainter>
#include <QPen>
#include <QBrush>
#include "parsexmlutils.h"
#include "renderobjects.h"
static const int SETA = 0;
static const int SETB = 1;
static const int SETC = 2;
static const char FNC1 = (char)130;
static const char FNC2 = (char)131;
static const char FNC3 = (char)132;
static const char FNC4 = (char)133;
static const char SHIFT = (char)134;
static const char CODEA = (char)135;
static const char CODEB = (char)136;
static const char CODEC = (char)137;
static const char STARTA = (char)138;
static const char STARTB = (char)139;
static const char STARTC = (char)140;
struct code128 {
char codea;
char codeb;
char codec;
int values[6];
bool _null;
};
static const struct code128 _128codes[] = {
// A , B , C , { B S B S B S }, NULL? },
{ ' ', ' ', 0, { 2, 1, 2, 2, 2, 2 }, false },
{ '!', '!', 1, { 2, 2, 2, 1, 2, 2 }, false },
{ '"', '"', 2, { 2, 2, 2, 2, 2, 1 }, false },
{ '#', '#', 3, { 1, 2, 1, 2, 2, 3 }, false },
{ '$', '$', 4, { 1, 2, 1, 3, 2, 2 }, false },
{ '%', '%', 5, { 1, 3, 1, 2, 2, 2 }, false },
{ '&', '&', 6, { 1, 2, 2, 2, 1, 3 }, false },
{ '\'', '\'', 7, { 1, 2, 2, 3, 1, 2 }, false },
{ '(', '(', 8, { 1, 3, 2, 2, 1, 2 }, false },
{ ')', ')', 9, { 2, 2, 1, 2, 1, 3 }, false },
{ '*', '*', 10, { 2, 2, 1, 3, 1, 2 }, false },
{ '+', '+', 11, { 2, 3, 1, 2, 1, 2 }, false },
{ ',', ',', 12, { 1, 1, 2, 2, 3, 2 }, false },
{ '-', '-', 13, { 1, 2, 2, 1, 3, 2 }, false },
{ '.', '.', 14, { 1, 2, 2, 2, 3, 1 }, false },
{ '/', '/', 15, { 1, 1, 3, 2, 2, 2 }, false },
{ '0', '0', 16, { 1, 2, 3, 1, 2, 2 }, false },
{ '1', '1', 17, { 1, 2, 3, 2, 2, 1 }, false },
{ '2', '2', 18, { 2, 2, 3, 2, 1, 1 }, false },
{ '3', '3', 19, { 2, 2, 1, 1, 3, 2 }, false },
{ '4', '4', 20, { 2, 2, 1, 2, 3, 1 }, false },
{ '5', '5', 21, { 2, 1, 3, 2, 1, 2 }, false },
{ '6', '6', 22, { 2, 2, 3, 1, 1, 2 }, false },
{ '7', '7', 23, { 3, 1, 2, 1, 3, 1 }, false },
{ '8', '8', 24, { 3, 1, 1, 2, 2, 2 }, false },
{ '9', '9', 25, { 3, 2, 1, 1, 2, 2 }, false },
{ ':', ':', 26, { 3, 2, 1, 2, 2, 1 }, false },
{ ';', ';', 27, { 3, 1, 2, 2, 1, 2 }, false },
{ '<', '<', 28, { 3, 2, 2, 1, 1, 2 }, false },
{ '=', '=', 29, { 3, 2, 2, 2, 1, 1 }, false },
{ '>', '>', 30, { 2, 1, 2, 1, 2, 3 }, false },
{ '?', '?', 31, { 2, 1, 2, 3, 2, 1 }, false },
{ '@', '@', 32, { 2, 3, 2, 1, 2, 1 }, false },
{ 'A', 'A', 33, { 1, 1, 1, 3, 2, 3 }, false },
{ 'B', 'B', 34, { 1, 3, 1, 1, 2, 3 }, false },
{ 'C', 'C', 35, { 1, 3, 1, 3, 2, 1 }, false },
{ 'D', 'D', 36, { 1, 1, 2, 3, 1, 3 }, false },
{ 'E', 'E', 37, { 1, 3, 2, 1, 1, 3 }, false },
{ 'F', 'F', 38, { 1, 3, 2, 3, 1, 1 }, false },
{ 'G', 'G', 39, { 2, 1, 1, 3, 1, 3 }, false },
{ 'H', 'H', 40, { 2, 3, 1, 1, 1, 3 }, false },
{ 'I', 'I', 41, { 2, 3, 1, 3, 1, 1 }, false },
{ 'J', 'J', 42, { 1, 1, 2, 1, 3, 3 }, false },
{ 'K', 'K', 43, { 1, 1, 2, 3, 3, 1 }, false },
{ 'L', 'L', 44, { 1, 3, 2, 1, 3, 1 }, false },
{ 'M', 'M', 45, { 1, 1, 3, 1, 2, 3 }, false },
{ 'N', 'N', 46, { 1, 1, 3, 3, 2, 1 }, false },
{ 'O', 'O', 47, { 1, 3, 3, 1, 2, 1 }, false },
{ 'P', 'P', 48, { 3, 1, 3, 1, 2, 1 }, false },
{ 'Q', 'Q', 49, { 2, 1, 1, 3, 3, 1 }, false },
{ 'R', 'R', 50, { 2, 3, 1, 1, 3, 1 }, false },
{ 'S', 'S', 51, { 2, 1, 3, 1, 1, 3 }, false },
{ 'T', 'T', 52, { 2, 1, 3, 3, 1, 1 }, false },
{ 'U', 'U', 53, { 2, 1, 3, 1, 3, 1 }, false },
{ 'V', 'V', 54, { 3, 1, 1, 1, 2, 3 }, false },
{ 'W', 'W', 55, { 3, 1, 1, 3, 2, 1 }, false },
{ 'X', 'X', 56, { 3, 3, 1, 1, 2, 1 }, false },
{ 'Y', 'Y', 57, { 3, 1, 2, 1, 1, 3 }, false },
{ 'Z', 'Z', 58, { 3, 1, 2, 3, 1, 1 }, false },
{ '[', '[', 59, { 3, 3, 2, 1, 1, 1 }, false },
{ '\\', '\\', 60, { 3, 1, 4, 1, 1, 1 }, false },
{ ']', ']', 61, { 2, 2, 1, 4, 1, 1 }, false },
{ '^', '^', 62, { 4, 3, 1, 1, 1, 1 }, false },
{ '_', '_', 63, { 1, 1, 1, 2, 2, 4 }, false },
{ 0x00, '`', 64, { 1, 1, 1, 4, 2, 2 }, false }, // NUL
{ 0x01, 'a', 65, { 1, 2, 1, 1, 2, 4 }, false }, // SOH
{ 0x02, 'b', 66, { 1, 2, 1, 4, 2, 1 }, false }, // STX
{ 0x03, 'c', 67, { 1, 4, 1, 1, 2, 2 }, false }, // ETX
{ 0x04, 'd', 68, { 1, 4, 1, 2, 2, 1 }, false }, // EOT
{ 0x05, 'e', 69, { 1, 1, 2, 2, 1, 4 }, false }, // ENQ
{ 0x06, 'f', 70, { 1, 1, 2, 4, 1, 2 }, false }, // ACK
{ 0x07, 'g', 71, { 1, 2, 2, 1, 1, 4 }, false }, // BEL
{ 0x08, 'h', 72, { 1, 2, 2, 4, 1, 1 }, false }, // BS
{ 0x09, 'i', 73, { 1, 4, 2, 1, 1, 2 }, false }, // HT
{ 0x0A, 'j', 74, { 1, 4, 2, 2, 1, 1 }, false }, // LF
{ 0x0B, 'k', 75, { 2, 4, 1, 2, 1, 1 }, false }, // VT
{ 0x0C, 'l', 76, { 2, 2, 1, 1, 1, 4 }, false }, // FF
{ 0x0D, 'm', 77, { 4, 1, 3, 1, 1, 1 }, false }, // CR
{ 0x0E, 'n', 78, { 2, 4, 1, 1, 1, 2 }, false }, // SO
{ 0x0F, 'o', 79, { 1, 3, 4, 1, 1, 1 }, false }, // SI
{ 0x10, 'p', 80, { 1, 1, 1, 2, 4, 2 }, false }, // DLE
{ 0x11, 'q', 81, { 1, 2, 1, 1, 4, 2 }, false }, // DC1
{ 0x12, 'r', 82, { 1, 2, 1, 2, 4, 1 }, false }, // DC2
{ 0x13, 's', 83, { 1, 1, 4, 2, 1, 2 }, false }, // DC3
{ 0x14, 't', 84, { 1, 2, 4, 1, 1, 2 }, false }, // DC4
{ 0x15, 'u', 85, { 1, 2, 4, 2, 1, 1 }, false }, // NAK
{ 0x16, 'v', 86, { 4, 1, 1, 2, 1, 2 }, false }, // SYN
{ 0x17, 'w', 87, { 4, 2, 1, 1, 1, 2 }, false }, // ETB
{ 0x18, 'x', 88, { 4, 2, 1, 2, 1, 1 }, false }, // CAN
{ 0x19, 'y', 89, { 2, 1, 2, 1, 4, 1 }, false }, // EM
{ 0x1A, 'z', 90, { 2, 1, 4, 1, 2, 1 }, false }, // SUB
{ 0x1B, '{', 91, { 4, 1, 2, 1, 2, 1 }, false }, // ESC
{ 0x1C, '|', 92, { 1, 1, 1, 1, 4, 3 }, false }, // FS
{ 0x1D, '}', 93, { 1, 1, 1, 3, 4, 1 }, false }, // GS
{ 0x1E, '~', 94, { 1, 3, 1, 1, 4, 1 }, false }, // RS
{ 0x1F, 0x7F, 95, { 1, 1, 4, 1, 1, 3 }, false }, // US DEL
{ FNC3, FNC3, 96, { 1, 1, 4, 3, 1, 1 }, false }, // FNC3 FNC3
{ FNC2, FNC2, 97, { 4, 1, 1, 1, 1, 3 }, false }, // FNC2 FNC2
{ SHIFT, SHIFT, 98, { 4, 1, 1, 3, 1, 1 }, false }, // SHIFT SHIFT
{ CODEC, CODEC, 99, { 1, 1, 3, 1, 4, 1 }, false }, // CODEC CODEC
{ CODEB, FNC4, CODEB, { 1, 1, 4, 1, 3, 1 }, false }, // CODEB FNC4 CODEB
{ FNC4, CODEA, CODEA, { 3, 1, 1, 1, 4, 1 }, false }, // FNC4 CODEA CODEA
{ FNC1, FNC1, FNC1, { 4, 1, 1, 1, 3, 1 }, false }, // FNC1 FNC1 FNC1
{ STARTA, STARTA, STARTA, { 2, 1, 1, 4, 1, 2 }, false }, // STARTA
{ STARTB, STARTB, STARTB, { 2, 1, 1, 2, 1, 4 }, false }, // STARTB
{ STARTC, STARTC, STARTC, { 2, 1, 1, 2, 3, 2 }, false }, // STARTC
{ '\0', '\0', '\0', { 0, 0, 0, 0, 0, 0 }, true } // null termininator of list
};
// STOP CHARACTER { 2 3 3 1 1 1 2 }
int code128Index(QChar code, int set) {
for(int idx = 0; _128codes[idx]._null == false; idx++) {
if(set == SETA && _128codes[idx].codea == code.toLatin1()) return idx;
if(set == SETB && _128codes[idx].codeb == code.toLatin1()) return idx;
if(set == SETC && _128codes[idx].codec == code.toLatin1()) return idx;
}
return -1; // couldn't find it
}
void renderCode128(OROPage * page, const QRectF & r, const QString & _str, ORBarcodeData * bc)
{
QVector<int> str;
int i = 0;
// create the list.. if the list is empty then just set a start code and move on
if(_str.isEmpty())
str.push_back(104);
else
{
int rank_a = 0;
int rank_b = 0;
int rank_c = 0;
QChar c;
for(i = 0; i < _str.length(); i++)
{
c = _str.at(i);
rank_a += (code128Index(c, SETA) != -1 ? 1 : 0);
rank_b += (code128Index(c, SETB) != -1 ? 1 : 0);
rank_c += (c >= '0' && c <= '9' ? 1 : 0);
}
if(rank_c == _str.length() && ((rank_c % 2) == 0 || rank_c > 4))
{
// every value in the is a digit so we are going to go with mode C
// and we have an even number or we have more than 4 values
i = 0;
if((rank_c % 2) == 1)
{
str.push_back(104); // START B
c = _str.at(0);
str.push_back(code128Index(c, SETB));
str.push_back(99); // MODE C
i = 1;
}
else
str.push_back(105); // START C
for(i = i; i < _str.length(); i+=2)
{
char a, b;
c = _str.at(i);
a = c.toLatin1();
a -= 48;
c = _str.at(i+1);
b = c.toLatin1();
b -= 48;
str.push_back(int((a * 10) + b));
}
}
else
{
// start in the mode that had the higher number of hits and then
// just shift into the opposite mode as needed
int set = ( rank_a > rank_b ? SETA : SETB );
str.push_back(( rank_a > rank_b ? 103 : 104 ));
int v = -1;
for(i = 0; i < _str.length(); i++)
{
c = _str.at(i);
v = code128Index(c, set);
if(v == -1)
{
v = code128Index(c, (set == SETA ? SETB : SETA));
if(v != -1)
{
str.push_back(98); // SHIFT
str.push_back(v);
}
}
else
str.push_back(v);
}
}
}
// calculate and append the checksum value to the list
int checksum = str.at(0);
for(i = 1; i < str.size(); i++)
checksum += (str.at(i) * i);
checksum = checksum % 103;
str.push_back(checksum);
// lets determine some core attributes about this barcode
qreal bar_width = bc->narrowBarWidth;
// this is are mandatory minimum quiet zone
qreal quiet_zone = bar_width * 10;
if(quiet_zone < 0.1)
quiet_zone = 0.1;
// what kind of area do we have to work with
qreal draw_width = r.width();
qreal draw_height = r.height();
// how long is the value we need to encode?
int val_length = str.size() - 2; // we include start and checksum in are list so
// subtract them out for our calculations
// L = (11C + 35)X
// L length of barcode (excluding quite zone) in units same as X and I
// C the number of characters in the value excluding the start/stop and checksum characters
// X the width of a bar (pixels in our case)
qreal L;
qreal C = val_length;
qreal X = bar_width;
L = (((11.0 * C) + 35.0) * X);
// now we have the actual width the barcode will be so can determine the actual
// size of the quiet zone (we assume we center the barcode in the given area
// what should we do if the area is too small????
// At the moment the way the code is written is we will always start at the minimum
// required quiet zone if we don't have enough space.... I guess we'll just have over-run
// to the right
//
// calculate the starting position based on the alignment option
// for left align we don't need to do anything as the values are already setup for it
if(bc->align == 1) // center
{
qreal nqz = (draw_width - L) / 2.0;
if(nqz > quiet_zone)
quiet_zone = nqz;
}
else if(bc->align > 1) // right
quiet_zone = draw_width - (L + quiet_zone);
// else if(align < 1) {} // left : do nothing
qreal pos = r.left() + quiet_zone;
qreal top = r.top();
QPen pen(Qt::NoPen);
QBrush brush(QColor("black"));
bool space = false;
int idx = 0, b = 0;
qreal w = 0.0;
for(i = 0; i < str.size(); i++)
{
// loop through each value and render the barcode
idx = str.at(i);
if(idx < 0 || idx > 105)
{
qDebug("Encountered a non-compliant element while rendering a 3of9 barcode -- skipping");
continue;
}
space = false;
for(b = 0; b < 6; b++, space = !space)
{
w = _128codes[idx].values[b] * bar_width;
if(!space)
{
ORORect * rect = new ORORect(bc);
rect->setPen(pen);
rect->setBrush(brush);
rect->setRect(QRectF(pos,top, w,draw_height));
rect->setRotationAxis(r.topLeft());
page->addPrimitive(rect);
}
pos += w;
}
}
// we have to do the stop character seperatly like this because it has
// 7 elements in it's bar sequence rather than 6 like the others
int STOP_CHARACTER[]={ 2, 3, 3, 1, 1, 1, 2 };
space = false;
for(b = 0; b < 7; b++, space = !space)
{
w = STOP_CHARACTER[b] * bar_width;
if(!space)
{
ORORect * rect = new ORORect(bc);
rect->setPen(pen);
rect->setBrush(brush);
rect->setRect(QRectF(pos,top, w,draw_height));
rect->setRotationAxis(r.topLeft());
page->addPrimitive(rect);
}
pos += w;
}
return;
}
| arcnexus/MayaOpenRPT | OpenRPT/renderer/code128.cpp | C++ | lgpl-2.1 | 14,582 |
#include <mystdlib.h>
#include <myadt.hpp>
#include <linalg.hpp>
#include <gprim.hpp>
#include <meshing.hpp>
#include "stlgeom.hpp"
namespace netgen
{
STLTopology :: STLTopology()
: trias(), topedges(), points(), ht_topedges(NULL),
trigsperpoint(), neighbourtrigs()
{
;
}
STLTopology :: ~STLTopology()
{
;
}
STLGeometry * STLTopology :: LoadBinary (istream & ist)
{
STLGeometry * geom = new STLGeometry();
Array<STLReadTriangle> readtrigs;
PrintMessage(1,"Read STL binary file");
if (sizeof(int) != 4 || sizeof(float) != 4)
{
PrintWarning("for stl-binary compatibility only use 32 bit compilation!!!");
}
//specific settings for stl-binary format
const int namelen = 80; //length of name of header in file
const int nospaces = 2; //number of spaces after a triangle
//read header: name
char buf[namelen+1];
FIOReadStringE(ist,buf,namelen);
PrintMessage(5,"header = ",buf);
//Read Number of facets
int nofacets;
FIOReadInt(ist,nofacets);
PrintMessage(5,"NO facets = ",nofacets);
Point<3> pts[3];
Vec<3> normal;
char spaces[nospaces+1];
for (int cntface = 0; cntface < nofacets; cntface++)
{
if (cntface % 10000 == 0)
// { PrintDot(); }
PrintMessageCR (3, cntface, " triangles loaded\r");
float f;
FIOReadFloat(ist,f); normal(0) = f;
FIOReadFloat(ist,f); normal(1) = f;
FIOReadFloat(ist,f); normal(2) = f;
for (int j = 0; j < 3; j++)
{
FIOReadFloat(ist,f); pts[j](0) = f;
FIOReadFloat(ist,f); pts[j](1) = f;
FIOReadFloat(ist,f); pts[j](2) = f;
}
readtrigs.Append (STLReadTriangle (pts, normal));
FIOReadString(ist,spaces,nospaces);
}
PrintMessage (3, nofacets, " triangles loaded\r");
geom->InitSTLGeometry(readtrigs);
return geom;
}
void STLTopology :: SaveBinary (const char* filename, const char* aname) const
{
ofstream ost(filename);
PrintFnStart("Write STL binary file '",filename,"'");
if (sizeof(int) != 4 || sizeof(float) != 4)
{PrintWarning("for stl-binary compatibility only use 32 bit compilation!!!");}
//specific settings for stl-binary format
const int namelen = 80; //length of name of header in file
const int nospaces = 2; //number of spaces after a triangle
//write header: aname
int i, j;
char buf[namelen+1];
int strend = 0;
for(i = 0; i <= namelen; i++)
{
if (aname[i] == 0) {strend = 1;}
if (!strend) {buf[i] = aname[i];}
else {buf[i] = 0;}
}
FIOWriteString(ost,buf,namelen);
PrintMessage(5,"header = ",buf);
//RWrite Number of facets
int nofacets = GetNT();
FIOWriteInt(ost,nofacets);
PrintMessage(5,"NO facets = ", nofacets);
float f;
char spaces[nospaces+1];
for (i = 0; i < nospaces; i++) {spaces[i] = ' ';}
spaces[nospaces] = 0;
for (i = 1; i <= GetNT(); i++)
{
const STLTriangle & t = GetTriangle(i);
const Vec<3> & n = t.Normal();
f = n(0); FIOWriteFloat(ost,f);
f = n(1); FIOWriteFloat(ost,f);
f = n(2); FIOWriteFloat(ost,f);
for (j = 1; j <= 3; j++)
{
const Point3d p = GetPoint(t.PNum(j));
f = p.X(); FIOWriteFloat(ost,f);
f = p.Y(); FIOWriteFloat(ost,f);
f = p.Z(); FIOWriteFloat(ost,f);
}
FIOWriteString(ost,spaces,nospaces);
}
PrintMessage(5,"done");
}
void STLTopology :: SaveSTLE (const char* filename) const
{
ofstream outf (filename);
int i, j;
outf << GetNT() << endl;
for (i = 1; i <= GetNT(); i++)
{
const STLTriangle & t = GetTriangle(i);
for (j = 1; j <= 3; j++)
{
const Point3d p = GetPoint(t.PNum(j));
outf << p.X() << " " << p.Y() << " " << p.Z() << endl;
}
}
int ned = 0;
for (i = 1; i <= GetNTE(); i++)
{
if (GetTopEdge (i).GetStatus() == ED_CONFIRMED)
ned++;
}
outf << ned << endl;
for (i = 1; i <= GetNTE(); i++)
{
const STLTopEdge & edge = GetTopEdge (i);
if (edge.GetStatus() == ED_CONFIRMED)
for (j = 1; j <= 2; j++)
{
const Point3d p = GetPoint(edge.PNum(j));
outf << p.X() << " " << p.Y() << " " << p.Z() << endl;
}
}
}
STLGeometry * STLTopology :: LoadNaomi (istream & ist)
{
int i;
STLGeometry * geom = new STLGeometry();
Array<STLReadTriangle> readtrigs;
PrintFnStart("read NAOMI file format");
char buf[100];
Vec<3> normal;
//int cntface = 0;
//int cntvertex = 0;
double px, py, pz;
int noface, novertex;
Array<Point<3> > readpoints;
ist >> buf;
if (strcmp (buf, "NODES") == 0)
{
ist >> novertex;
PrintMessage(5,"nuber of vertices = ", novertex);
for (i = 0; i < novertex; i++)
{
ist >> px;
ist >> py;
ist >> pz;
readpoints.Append(Point<3> (px,py,pz));
}
}
else
{
PrintFileError("no node information");
}
ist >> buf;
if (strcmp (buf, "2D_EDGES") == 0)
{
ist >> noface;
PrintMessage(5,"number of faces=",noface);
int dummy, p1, p2, p3;
Point<3> pts[3];
for (i = 0; i < noface; i++)
{
ist >> dummy; //2
ist >> dummy; //1
ist >> p1;
ist >> p2;
ist >> p3;
ist >> dummy; //0
pts[0] = readpoints.Get(p1);
pts[1] = readpoints.Get(p2);
pts[2] = readpoints.Get(p3);
normal = Cross (pts[1]-pts[0], pts[2]-pts[0]) . Normalize();
readtrigs.Append (STLReadTriangle (pts, normal));
}
PrintMessage(5,"read ", readtrigs.Size(), " triangles");
}
else
{
PrintMessage(5,"read='",buf,"'\n");
PrintFileError("ERROR: no Triangle information");
}
geom->InitSTLGeometry(readtrigs);
return geom;
}
void STLTopology :: Save (const char* filename) const
{
PrintFnStart("Write stl-file '",filename, "'");
ofstream fout(filename);
fout << "solid\n";
char buf1[50];
char buf2[50];
char buf3[50];
int i, j;
for (i = 1; i <= GetNT(); i++)
{
const STLTriangle & t = GetTriangle(i);
fout << "facet normal ";
const Vec3d& n = GetTriangle(i).Normal();
sprintf(buf1,"%1.9g",n.X());
sprintf(buf2,"%1.9g",n.Y());
sprintf(buf3,"%1.9g",n.Z());
fout << buf1 << " " << buf2 << " " << buf3 << "\n";
fout << "outer loop\n";
for (j = 1; j <= 3; j++)
{
const Point3d p = GetPoint(t.PNum(j));
sprintf(buf1,"%1.9g",p.X());
sprintf(buf2,"%1.9g",p.Y());
sprintf(buf3,"%1.9g",p.Z());
fout << "vertex " << buf1 << " " << buf2 << " " << buf3 << "\n";
}
fout << "endloop\n";
fout << "endfacet\n";
}
fout << "endsolid\n";
// write also NETGEN surface mesh:
ofstream fout2("geom.surf");
fout2 << "surfacemesh" << endl;
fout2 << GetNP() << endl;
for (i = 1; i <= GetNP(); i++)
{
for (j = 0; j < 3; j++)
{
fout2.width(8);
fout2 << GetPoint(i)(j);
}
fout2 << endl;
}
fout2 << GetNT() << endl;
for (i = 1; i <= GetNT(); i++)
{
const STLTriangle & t = GetTriangle(i);
for (j = 1; j <= 3; j++)
{
fout2.width(8);
fout2 << t.PNum(j);
}
fout2 << endl;
}
}
STLGeometry * STLTopology ::Load (istream & ist)
{
STLGeometry * geom = new STLGeometry();
Array<STLReadTriangle> readtrigs;
char buf[100];
Point<3> pts[3];
Vec<3> normal;
int cntface = 0;
int vertex = 0;
bool badnormals = false;
while (ist.good())
{
ist >> buf;
int n = strlen (buf);
for (int i = 0; i < n; i++)
buf[i] = tolower (buf[i]);
if (strcmp (buf, "facet") == 0)
{
cntface++;
}
if (strcmp (buf, "normal") == 0)
{
ist >> normal(0)
>> normal(1)
>> normal(2);
normal.Normalize();
}
if (strcmp (buf, "vertex") == 0)
{
ist >> pts[vertex](0)
>> pts[vertex](1)
>> pts[vertex](2);
vertex++;
if (vertex == 3)
{
if (normal.Length() <= 1e-5)
{
normal = Cross (pts[1]-pts[0], pts[2]-pts[0]);
normal.Normalize();
}
else
{
Vec<3> hnormal = Cross (pts[1]-pts[0], pts[2]-pts[0]);
hnormal.Normalize();
if (normal * hnormal < 0.5)
badnormals = true;
}
vertex = 0;
if ( (Dist2 (pts[0], pts[1]) > 1e-16) &&
(Dist2 (pts[0], pts[2]) > 1e-16) &&
(Dist2 (pts[1], pts[2]) > 1e-16) )
{
readtrigs.Append (STLReadTriangle (pts, normal));
if (readtrigs.Size() % 100000 == 0)
PrintMessageCR (3, readtrigs.Size(), " triangles loaded\r");
}
else
{
cout << "Skipping flat triangle "
<< "l1 = " << Dist(pts[0], pts[1])
<< ", l2 = " << Dist(pts[0], pts[2])
<< ", l3 = " << Dist(pts[2], pts[1]) << endl;
}
}
}
}
PrintMessage (3, readtrigs.Size(), " triangles loaded");
if (badnormals)
{
PrintWarning("File has normal vectors which differ extremly from geometry->correct with stldoctor!!!");
}
geom->InitSTLGeometry(readtrigs);
return geom;
}
void STLTopology :: InitSTLGeometry(const Array<STLReadTriangle> & readtrigs)
{
// const double geometry_tol_fact = 1E6;
// distances lower than max_box_size/tol are ignored
trias.SetSize(0);
points.SetSize(0);
PrintMessage(3,"number of triangles = ", readtrigs.Size());
if (!readtrigs.Size()) return;
boundingbox.Set (readtrigs[0][0]);
for (int i = 0; i < readtrigs.Size(); i++)
for (int k = 0; k < 3; k++)
boundingbox.Add (readtrigs[i][k]);
PrintMessage(5,"boundingbox: ", Point3d(boundingbox.PMin()), " - ",
Point3d(boundingbox.PMax()));
Box<3> bb = boundingbox;
bb.Increase (1);
pointtree = new Point3dTree (bb.PMin(), bb.PMax());
Array<int> pintersect;
pointtol = boundingbox.Diam() * stldoctor.geom_tol_fact;
PrintMessage(5,"point tolerance = ", pointtol);
PrintMessageCR(5,"identify points ...");
for(int i = 0; i < readtrigs.Size(); i++)
{
const STLReadTriangle & t = readtrigs[i];
STLTriangle st;
st.SetNormal (t.Normal());
for (int k = 0; k < 3; k++)
{
Point<3> p = t[k];
Point<3> pmin = p - Vec<3> (pointtol, pointtol, pointtol);
Point<3> pmax = p + Vec<3> (pointtol, pointtol, pointtol);
pointtree->GetIntersecting (pmin, pmax, pintersect);
if (pintersect.Size() > 1)
PrintError("too many close points");
int foundpos = -1;
if (pintersect.Size())
foundpos = pintersect[0];
if (foundpos == -1)
{
foundpos = AddPoint(p);
pointtree->Insert (p, foundpos);
}
if (Dist(p, points.Get(foundpos)) > 1e-10)
cout << "identify close points: " << p << " " << points.Get(foundpos)
<< ", dist = " << Dist(p, points.Get(foundpos))
<< endl;
st[k] = foundpos;
}
if ( (st[0] == st[1]) ||
(st[0] == st[2]) ||
(st[1] == st[2]) )
{
PrintError("STL Triangle degenerated");
}
else
{
AddTriangle(st);
}
}
PrintMessage(5,"identify points ... done");
FindNeighbourTrigs();
}
int STLTopology :: GetPointNum (const Point<3> & p)
{
Point<3> pmin = p - Vec<3> (pointtol, pointtol, pointtol);
Point<3> pmax = p + Vec<3> (pointtol, pointtol, pointtol);
Array<int> pintersect;
pointtree->GetIntersecting (pmin, pmax, pintersect);
if (pintersect.Size() == 1)
return pintersect[0];
else
return 0;
}
void STLTopology :: FindNeighbourTrigs()
{
// if (topedges.Size()) return;
PushStatusF("Find Neighbour Triangles");
PrintMessage(5,"build topology ...");
// build up topology tables
int nt = GetNT();
INDEX_2_HASHTABLE<int> * oldedges = ht_topedges;
ht_topedges = new INDEX_2_HASHTABLE<int> (GetNP()+1);
topedges.SetSize(0);
for (int i = 1; i <= nt; i++)
{
STLTriangle & trig = GetTriangle(i);
for (int j = 1; j <= 3; j++)
{
int pi1 = trig.PNumMod (j+1);
int pi2 = trig.PNumMod (j+2);
INDEX_2 i2(pi1, pi2);
i2.Sort();
int enr;
int othertn;
if (ht_topedges->Used(i2))
{
enr = ht_topedges->Get(i2);
topedges.Elem(enr).TrigNum(2) = i;
othertn = topedges.Get(enr).TrigNum(1);
STLTriangle & othertrig = GetTriangle(othertn);
trig.NBTrigNum(j) = othertn;
trig.EdgeNum(j) = enr;
for (int k = 1; k <= 3; k++)
if (othertrig.EdgeNum(k) == enr)
othertrig.NBTrigNum(k) = i;
}
else
{
enr = topedges.Append (STLTopEdge (pi1, pi2, i, 0));
ht_topedges->Set (i2, enr);
trig.EdgeNum(j) = enr;
}
}
}
PrintMessage(5,"topology built, checking");
topology_ok = 1;
int ne = GetNTE();
for (int i = 1; i <= nt; i++)
GetTriangle(i).flags.toperror = 0;
for (int i = 1; i <= nt; i++)
for (int j = 1; j <= 3; j++)
{
const STLTopEdge & edge = GetTopEdge (GetTriangle(i).EdgeNum(j));
if (edge.TrigNum(1) != i && edge.TrigNum(2) != i)
{
topology_ok = 0;
GetTriangle(i).flags.toperror = 1;
}
}
for (int i = 1; i <= ne; i++)
{
const STLTopEdge & edge = GetTopEdge (i);
if (!edge.TrigNum(2))
{
topology_ok = 0;
GetTriangle(edge.TrigNum(1)).flags.toperror = 1;
}
}
if (topology_ok)
{
orientation_ok = 1;
for (int i = 1; i <= nt; i++)
{
const STLTriangle & t = GetTriangle (i);
for (int j = 1; j <= 3; j++)
{
const STLTriangle & nbt = GetTriangle (t.NBTrigNum(j));
if (!t.IsNeighbourFrom (nbt))
orientation_ok = 0;
}
}
}
else
orientation_ok = 0;
status = STL_GOOD;
statustext = "";
if (!topology_ok || !orientation_ok)
{
status = STL_ERROR;
if (!topology_ok)
statustext = "Topology not ok";
else
statustext = "Orientation not ok";
}
PrintMessage(3,"topology_ok = ",topology_ok);
PrintMessage(3,"orientation_ok = ",orientation_ok);
PrintMessage(3,"topology found");
// generate point -> trig table
trigsperpoint.SetSize(GetNP());
for (int i = 1; i <= GetNT(); i++)
for (int j = 1; j <= 3; j++)
trigsperpoint.Add1(GetTriangle(i).PNum(j),i);
//check trigs per point:
/*
for (i = 1; i <= GetNP(); i++)
{
if (trigsperpoint.EntrySize(i) < 3)
{
(*testout) << "ERROR: Point " << i << " has " << trigsperpoint.EntrySize(i) << " triangles!!!" << endl;
}
}
*/
topedgesperpoint.SetSize (GetNP());
for (int i = 1; i <= ne; i++)
for (int j = 1; j <= 2; j++)
topedgesperpoint.Add1 (GetTopEdge (i).PNum(j), i);
PrintMessage(5,"point -> trig table generated");
// transfer edge data:
// .. to be done
delete oldedges;
for (STLTrigIndex ti = 0; ti < GetNT(); ti++)
{
STLTriangle & trig = trias[ti];
for (int k = 0; k < 3; k++)
{
STLPointIndex pi = trig[k] - STLBASE;
STLPointIndex pi2 = trig[(k+1)%3] - STLBASE;
STLPointIndex pi3 = trig[(k+2)%3] - STLBASE;
// vector along edge
Vec<3> ve = points[pi2] - points[pi];
ve.Normalize();
// vector along third point
Vec<3> vt = points[pi3] - points[pi];
vt -= (vt * ve) * ve;
vt.Normalize();
Vec<3> vn = trig.GeomNormal (points);
vn.Normalize();
double phimin = 10, phimax = -1; // out of (0, 2 pi)
for (int j = 0; j < trigsperpoint[pi].Size(); j++)
{
STLTrigIndex ti2 = trigsperpoint[pi][j] - STLBASE;
const STLTriangle & trig2 = trias[ti2];
if (ti == ti2) continue;
bool hasboth = 0;
for (int l = 0; l < 3; l++)
if (trig2[l] - STLBASE == pi2)
{
hasboth = 1;
break;
}
if (!hasboth) continue;
STLPointIndex pi4(0);
for (int l = 0; l < 3; l++)
if (trig2[l] - STLBASE != pi && trig2[l] - STLBASE != pi2)
pi4 = trig2[l] - STLBASE;
Vec<3> vt2 = points[pi4] - points[pi];
double phi = atan2 (vt2 * vn, vt2 * vt);
if (phi < 0) phi += 2 * M_PI;
if (phi < phimin)
{
phimin = phi;
trig.NBTrig (0, (k+2)%3) = ti2 + STLBASE;
}
if (phi > phimax)
{
phimax = phi;
trig.NBTrig (1, (k+2)%3) = ti2 + STLBASE;
}
}
}
}
if (status == STL_GOOD)
{
// for compatibility:
neighbourtrigs.SetSize(GetNT());
for (int i = 1; i <= GetNT(); i++)
for (int k = 1; k <= 3; k++)
AddNeighbourTrig (i, GetTriangle(i).NBTrigNum(k));
}
else
{
// assemble neighbourtrigs (should be done only for illegal topology):
neighbourtrigs.SetSize(GetNT());
int tr, found;
int wrongneighbourfound = 0;
for (int i = 1; i <= GetNT(); i++)
{
SetThreadPercent((double)i/(double)GetNT()*100.);
if (multithread.terminate)
{
PopStatus();
return;
}
for (int k = 1; k <= 3; k++)
{
for (int j = 1; j <= trigsperpoint.EntrySize(GetTriangle(i).PNum(k)); j++)
{
tr = trigsperpoint.Get(GetTriangle(i).PNum(k),j);
if (i != tr && (GetTriangle(i).IsNeighbourFrom(GetTriangle(tr))
|| GetTriangle(i).IsWrongNeighbourFrom(GetTriangle(tr))))
{
if (GetTriangle(i).IsWrongNeighbourFrom(GetTriangle(tr)))
{
/*(*testout) << "ERROR: triangle " << i << " has a wrong neighbour triangle!!!" << endl;*/
wrongneighbourfound ++;
}
found = 0;
for (int ii = 1; ii <= NONeighbourTrigs(i); ii++)
{if (NeighbourTrig(i,ii) == tr) {found = 1;break;};}
if (! found) {AddNeighbourTrig(i,tr);}
}
}
}
if (NONeighbourTrigs(i) != 3)
{
PrintError("TRIG ",i," has ",NONeighbourTrigs(i)," neighbours!!!!");
for (int kk=1; kk <= NONeighbourTrigs(i); kk++)
{
PrintMessage(5,"neighbour-trig",kk," = ",NeighbourTrig(i,kk));
}
};
}
if (wrongneighbourfound)
{
PrintError("++++++++++++++++++++\n");
PrintError(wrongneighbourfound, " wrong oriented neighbourtriangles found!");
PrintError("try to correct it (with stldoctor)!");
PrintError("++++++++++++++++++++\n");
status = STL_ERROR;
statustext = "STL Mesh not consistent";
multithread.terminate = 1;
#ifdef STAT_STREAM
(*statout) << "non-conform stl geometry \\hline" << endl;
#endif
}
}
TopologyChanged();
PopStatus();
}
void STLTopology :: GetTrianglesInBox (/*
const Point<3> & pmin,
const Point<3> & pmax,
*/
const Box<3> & box,
Array<int> & btrias) const
{
if (searchtree)
searchtree -> GetIntersecting (box.PMin(), box.PMax(), btrias);
else
{
int i;
Box<3> box1 = box;
box1.Increase (1e-4);
btrias.SetSize(0);
int nt = GetNT();
for (i = 1; i <= nt; i++)
{
if (box1.Intersect (GetTriangle(i).box))
{
btrias.Append (i);
}
}
}
}
void STLTopology :: AddTriangle(const STLTriangle& t)
{
trias.Append(t);
const Point<3> & p1 = GetPoint (t.PNum(1));
const Point<3> & p2 = GetPoint (t.PNum(2));
const Point<3> & p3 = GetPoint (t.PNum(3));
Box<3> box;
box.Set (p1);
box.Add (p2);
box.Add (p3);
/*
// Point<3> pmin(p1), pmax(p1);
pmin.SetToMin (p2);
pmin.SetToMin (p3);
pmax.SetToMax (p2);
pmax.SetToMax (p3);
*/
trias.Last().box = box;
trias.Last().center = Center (p1, p2, p3);
double r1 = Dist (p1, trias.Last().center);
double r2 = Dist (p2, trias.Last().center);
double r3 = Dist (p3, trias.Last().center);
trias.Last().rad = max2 (max2 (r1, r2), r3);
if (geomsearchtreeon)
{searchtree->Insert (box.PMin(), box.PMax(), trias.Size());}
}
int STLTopology :: GetLeftTrig(int p1, int p2) const
{
int i;
for (i = 1; i <= trigsperpoint.EntrySize(p1); i++)
{
if (GetTriangle(trigsperpoint.Get(p1,i)).HasEdge(p1,p2)) {return trigsperpoint.Get(p1,i);}
}
PrintSysError("ERROR in GetLeftTrig !!!");
return 0;
}
int STLTopology :: GetRightTrig(int p1, int p2) const
{
return GetLeftTrig(p2,p1);
}
int STLTopology :: NeighbourTrigSorted(int trig, int edgenum) const
{
int i, p1, p2;
int psearch = GetTriangle(trig).PNum(edgenum);
for (i = 1; i <= 3; i++)
{
GetTriangle(trig).GetNeighbourPoints(GetTriangle(NeighbourTrig(trig,i)),p1,p2);
if (p1 == psearch) {return NeighbourTrig(trig,i);}
}
PrintSysError("ERROR in NeighbourTrigSorted");
return 0;
}
int STLTopology :: GetTopEdgeNum (int pi1, int pi2) const
{
if (!ht_topedges) return 0;
INDEX_2 i2(pi1, pi2);
i2.Sort();
if (!ht_topedges->Used(i2)) return 0;
return ht_topedges->Get(i2);
}
void STLTopology :: InvertTrig (int trig)
{
if (trig >= 1 && trig <= GetNT())
{
GetTriangle(trig).ChangeOrientation();
FindNeighbourTrigs();
}
else
{
PrintUserError("no triangle selected!");
}
}
void STLTopology :: DeleteTrig (int trig)
{
if (trig >= 1 && trig <= GetNT())
{
trias.DeleteElement(trig);
FindNeighbourTrigs();
}
else
{
PrintUserError("no triangle selected!");
}
}
void STLTopology :: OrientAfterTrig (int trig)
{
int starttrig = trig;
if (starttrig >= 1 && starttrig <= GetNT())
{
Array <int> oriented;
oriented.SetSize(GetNT());
int i;
for (i = 1; i <= oriented.Size(); i++)
{
oriented.Elem(i) = 0;
}
oriented.Elem(starttrig) = 1;
int k;
Array <int> list1;
list1.SetSize(0);
Array <int> list2;
list2.SetSize(0);
list1.Append(starttrig);
int cnt = 1;
int end = 0;
int nt;
while (!end)
{
end = 1;
for (i = 1; i <= list1.Size(); i++)
{
const STLTriangle& tt = GetTriangle(list1.Get(i));
for (k = 1; k <= 3; k++)
{
nt = tt.NBTrigNum (k); // NeighbourTrig(list1.Get(i),k);
if (oriented.Get(nt) == 0)
{
if (tt.IsWrongNeighbourFrom(GetTriangle(nt)))
{
GetTriangle(nt).ChangeOrientation();
}
oriented.Elem(nt) = 1;
list2.Append(nt);
cnt++;
end = 0;
}
}
}
list1.SetSize(0);
for (i = 1; i <= list2.Size(); i++)
{
list1.Append(list2.Get(i));
}
list2.SetSize(0);
}
PrintMessage(5,"NO corrected triangles = ",cnt);
if (cnt == GetNT())
{
PrintMessage(5,"ALL triangles oriented in same way!");
}
else
{
PrintWarning("NOT ALL triangles oriented in same way!");
}
// topedges.SetSize(0);
FindNeighbourTrigs();
}
else
{
PrintUserError("no triangle selected!");
}
}
}
| jwpeterson/netgen | libsrc/stlgeom/stltopology.cpp | C++ | lgpl-2.1 | 22,403 |
//
// Copyright (C) 2004-2006 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004-2006 Pingtel Corp. All rights reserved.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
///////////////////////////////////////////////////////////////////////////////
// Includes
#include "rtcp/RTCPHeader.h"
#ifdef INCLUDE_RTCP /* [ */
#ifdef __pingtel_on_posix__
#include <netinet/in.h>
#endif
#ifdef WIN32
# include <winsock2.h>
#endif
// Constants
const int PAD_MASK = 0x20;
const int VERSION_MASK = 0xC0;
const int PAD_SHIFT = 5;
const int VERSION_SHIFT = 6;
/**
*
* Method Name: CRTCPHeader() - Constructor
*
*
* Inputs: unsigned long ulSSRC
* - The the IDentifier for this source
* unsigned long ulVersion
* - Version of the RFC Standard being followed
* unsigned long ulPayload
* - The Payload type associated with this report
*
* Outputs: None
*
* Returns: None
*
* Description: The CRTCPHeader is an abstract class that is initialized by a
* derived object at construction time.
*
* Usage Notes:
*
*/
CRTCPHeader::CRTCPHeader(unsigned long ulSSRC, RTCP_REPORTS_ET etPayloadType,
unsigned long ulVersion)
: m_ulPadding(FALSE), m_ulCount(0), m_ulLength(0)
{
// Assign initial values to attributes
m_ulSSRC = ulSSRC;
m_ulVersion = ulVersion;
m_etPayloadType = etPayloadType;
}
/**
*
* Method Name: ~CRTCPHeader() - Destructor
*
*
* Inputs: None
*
* Outputs: None
*
* Returns: None
*
* Description: Shall deallocated and/or release all resources which was
* acquired over the course of runtime.
*
* Usage Notes:
*
*
*/
CRTCPHeader::~CRTCPHeader(void)
{
// Our reference count must have gone to 0 to get here. We have not allocated
// any memory so we shall now go quietly into that good night!
}
/**
*
* Method Name: GetHeaderLength
*
*
* Inputs: None
*
* Outputs: None
*
* Returns: unsigned long - the size of the RTCP Header
*
* Description: Returns the size of the RTCP Header that preceeds the payload.
*
* Usage Notes:
*
*
*/
unsigned long CRTCPHeader::GetHeaderLength(void)
{
// Load the argument passed with the header length
return(HEADER_LENGTH);
}
/**
*
* Method Name: GetSSRC
*
*
* Inputs: None
*
* Outputs: Bobe
*
* Returns: unsigned long - Return the SSRC ID
*
* Description: Retrieves the SSRC attribute stored within the object.
*
* Usage Notes:
*
*
*/
unsigned long CRTCPHeader::GetSSRC(void)
{
// Return the SSRC in the argument passed
return(m_ulSSRC);
}
/**
*
* Method Name: GetVersion
*
*
* Inputs: None
*
* Outputs: None
*
* Returns: unsigned long - Protocol Version #
*
* Description: Returns the protocol version number from the RTP packet.
*
* Usage Notes:
*
*
*/
unsigned long CRTCPHeader::GetVersion(void)
{
// Return Version Number
return(m_ulVersion);
}
/**
*
* Method Name: GetPadding
*
*
* Inputs: None
*
* Outputs: None
*
* Returns: unsigned long - Padding Flag
*
* Description: Returns the padding flag from the RTP packet.
*
* Usage Notes:
*
*
*/
unsigned long CRTCPHeader::GetPadding(void)
{
// Return Padding Flag
return(m_ulPadding);
}
/**
*
* Method Name: GetReportCount
*
*
* Inputs: None
*
* Outputs: None
*
* Returns: unsigned long - Returns Report Count
*
* Description: Retrieves the report count associated with this RTCP report.
*
* Usage Notes:
*
*
*/
unsigned long CRTCPHeader::GetReportCount(void)
{
// Return Report Count
return(m_ulCount);
}
/**
*
* Method Name: GetReportlength
*
*
* Inputs: None
*
* Outputs: None
*
* Returns: unsigned long - Returns Report Length
*
* Description: Retrieves the report length associated with this RTCP report.
*
* Usage Notes:
*
*
*/
unsigned long CRTCPHeader::GetReportLength(void)
{
// Return Report Length
return(m_ulLength ? m_ulLength + sizeof(long) : m_ulLength);
}
/**
*
* Method Name: GetPayload
*
*
* Inputs: None
*
* Outputs: None
*
* Returns: RTCP_REPORTS_ET - Returns Payload Type
*
* Description: Returns the payload type value from the RTCP packet.
*
* Usage Notes:
*
*
*/
RTCP_REPORTS_ET CRTCPHeader::GetPayload(void)
{
// Return Payload Type
return(m_etPayloadType);
}
/**
*
* Method Name: IsOurSSRC
*
*
* Inputs: None
*
* Outputs: unsigned long ulSSRC - SSRC ID
*
* Returns: boolean - TRUE => match
*
* Description: Compares the SSRC ID passed to that stored as an attribute
* within this object instance. Will return either True or False
* based on the match.
*
* Usage Notes:
*
*
*/
bool CRTCPHeader::IsOurSSRC(unsigned long ulSSRC)
{
// Compare the SSRC passed to the one that we have stored.
return(ulSSRC == m_ulSSRC);
}
/**
*
* Method Name: SetSSRC
*
*
* Inputs: unsigned long ulSSRC - Source ID
*
* Outputs: None
*
* Returns: void
*
* Description: Stores the Source Identifier associated with an RTP connection.
*
* Usage Notes:
*
*
*
*/
void CRTCPHeader::SetSSRC(unsigned long ulSSRC)
{
// Store the modified SSRC as an internal attribute
m_ulSSRC = ulSSRC;
}
/**
*
* Method Name: FormatRTCPHeader
*
*
* Inputs: unsigned long ulPadding - Padding used
* unsigned long ulCount - Report Count
* unsigned long ulReportLength - Report Length
*
* Outputs: unsigned char *puchRTCPBuffer
* - Buffer used to store the RTCP Report Header
*
* Returns: unsigned long - number of octets written into the buffer.
*
* Description: Constructs an RTCP Report report using information stored and
* passed by the caller.
*
* Usage Notes: A buffer of sufficient size should be allocated and passed to
* this formatting method.
*
*
*/
unsigned long CRTCPHeader::FormatRTCPHeader(unsigned char *puchRTCPBuffer,
unsigned long ulPadding,
unsigned long ulCount,
unsigned long ulReportLength)
{
unsigned char *puchRTCPHeader = puchRTCPBuffer;
// Report Count goes into the bits 4 - 8 of the first octet
m_ulCount = ulCount;
*puchRTCPHeader = (unsigned char)ulCount;
// Padding flag goes into the third bit of the first octet
m_ulPadding = ulPadding;
*puchRTCPHeader |= (unsigned char)((ulPadding << PAD_SHIFT) & PAD_MASK);
// Version # goes into the first 2 bits of the first octet
*puchRTCPHeader++ |=
(unsigned char)((m_ulVersion << VERSION_SHIFT) & VERSION_MASK);
// Payload Type goes into the second octet
*puchRTCPHeader++ = (unsigned char)m_etPayloadType;
// RTCP Report length goes into the third and fourth octet. This length
// is expressed in long words.
m_ulLength = ulReportLength;
*((unsigned short *)puchRTCPHeader) =
htons((((unsigned short)ulReportLength) / sizeof(long)) - 1);
puchRTCPHeader += sizeof(short);
// SSRC goes into the next 4 octet
*((unsigned long *)puchRTCPHeader) = htonl(m_ulSSRC);
return(puchRTCPBuffer - puchRTCPBuffer);
}
/**
*
* Method Name: ParseRTCPHeader
*
*
* Inputs: unsigned char *puchRTCPBuffer - Buffer containing the RTCP Report
*
* Outputs: None
*
* Returns: bool
*
* Description: Extracts the header contents of an RTCP report using the
* buffer passed in by the caller. The header will be validated
* to determine whether it has an appropriate version, payload
* type, and SSRC for this object.
*
* Usage Notes:
*
*
*/
bool CRTCPHeader::ParseRTCPHeader(unsigned char *puchRTCPBuffer)
{
unsigned char *puchRTCPHeader = puchRTCPBuffer;
// Extract Report Count
m_ulCount = *puchRTCPHeader & COUNT_MASK;
// Extract Padding
m_ulPadding = ((*puchRTCPHeader & PAD_MASK) >> PAD_SHIFT);
// Check for valid Version #
if (((*puchRTCPHeader++ & VERSION_MASK) >> VERSION_SHIFT) !=
(char)m_ulVersion)
{
osPrintf("**** FAILURE **** CRTCPHeader::ParseRTCPHeader() -"
" Invalid Version\n");
return(FALSE);
}
// Check for valid Payload Type
if(*puchRTCPHeader++ != (unsigned char)m_etPayloadType)
{
osPrintf("**** FAILURE **** CRTCPHeader::ParseRTCPHeader() -"
" Invalid Payload Type\n");
return(FALSE);
}
// Extract RTCP Report length and convert from word count to byte count
m_ulLength = ntohs(*((unsigned short *)puchRTCPHeader)) + 1;
m_ulLength *= sizeof(long);
puchRTCPHeader += sizeof(short);
// Assign SSRC if one hadn't previously existed
if(m_ulSSRC == 0)
m_ulSSRC = ntohl(*((unsigned long *)puchRTCPHeader));
// Check SSRC to be sure that the one received corresponds with the one
// previously established.
else if(ntohl(*((unsigned long *)puchRTCPHeader)) != m_ulSSRC)
{
#if RTCP_DEBUG /* [ */
if(bPingtelDebug)
{
osPrintf(">>>>> CRTCPHeader::ParseRTCPHeader() -"
" SSRC has Changed <<<<<\n");
}
#endif /* RTCP_DEBUG ] */
m_ulSSRC = ntohl(*((unsigned long *)puchRTCPHeader));
}
puchRTCPHeader += sizeof(long);
return(TRUE);
}
#endif /* INCLUDE_RTCP ] */
| litalidev/sipxtapi | sipXmediaLib/src/rtcp/RTCPHeader.cpp | C++ | lgpl-2.1 | 9,935 |
#!/usr/bin/env python3
import sys
from testrunner import run
def testfunc(child):
child.expect("All up, running the shell now")
child.sendline("ifconfig")
child.expect(r"Iface\s+(\d+)\s+HWaddr:")
if __name__ == "__main__":
sys.exit(run(testfunc, timeout=1, echo=False))
| cladmi/RIOT | tests/nordic_softdevice/tests/01-run.py | Python | lgpl-2.1 | 291 |
<?php
namespace wcf\acp\form;
use wcf\data\language\Language;
use wcf\data\language\LanguageEditor;
use wcf\data\package\Package;
use wcf\data\package\PackageCache;
use wcf\form\AbstractForm;
use wcf\system\exception\SystemException;
use wcf\system\exception\UserInputException;
use wcf\system\language\LanguageFactory;
use wcf\system\WCF;
use wcf\util\XML;
/**
* Shows the language import form.
*
* @author Marcel Werk
* @copyright 2001-2021 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\Acp\Form
*/
class LanguageImportForm extends AbstractForm
{
/**
* @inheritDoc
*/
public $activeMenuItem = 'wcf.acp.menu.link.language.import';
/**
* @inheritDoc
*/
public $neededPermissions = ['admin.language.canManageLanguage'];
/**
* file name
* @var string
*/
public $filename = '';
/**
* language object
* @var Language
*/
public $language;
/**
* list of available languages
* @var Language[]
*/
public $languages = [];
/**
* source language object
* @var Language
*/
public $sourceLanguage;
/**
* source language id
* @var int
*/
public $sourceLanguageID = 0;
/**
* @var int
* @since 5.4
*/
public $packageID = 0;
/**
* @inheritDoc
*/
public function readParameters()
{
parent::readParameters();
$this->languages = LanguageFactory::getInstance()->getLanguages();
}
/**
* @inheritDoc
*/
public function readFormParameters()
{
parent::readFormParameters();
if (isset($_FILES['languageUpload']) && !empty($_FILES['languageUpload']['tmp_name'])) {
$this->filename = $_FILES['languageUpload']['tmp_name'];
}
if (isset($_POST['sourceLanguageID'])) {
$this->sourceLanguageID = \intval($_POST['sourceLanguageID']);
}
if (isset($_POST['packageID'])) {
$this->packageID = \intval($_POST['packageID']);
}
}
/**
* @inheritDoc
*/
public function validate()
{
parent::validate();
// check file
if (!\file_exists($this->filename)) {
throw new UserInputException('languageUpload');
}
if (empty($this->sourceLanguageID)) {
throw new UserInputException('sourceLanguageID');
}
// get language
$this->sourceLanguage = LanguageFactory::getInstance()->getLanguage($this->sourceLanguageID);
if (!$this->sourceLanguage->languageID) {
throw new UserInputException('sourceLanguageID');
}
if (!PackageCache::getInstance()->getPackage($this->packageID)) {
throw new UserInputException('packageID');
}
// try to import
try {
// open xml document
$xml = new XML();
$xml->load($this->filename);
// import xml document
$this->language = LanguageEditor::importFromXML($xml, $this->packageID, $this->sourceLanguage);
// copy content
if (!isset($this->languages[$this->language->languageID])) {
LanguageEditor::copyLanguageContent($this->sourceLanguage->languageID, $this->language->languageID);
}
} catch (SystemException $e) {
throw new UserInputException('languageUpload', $e->getMessage());
} catch (\InvalidArgumentException $e) {
throw new UserInputException('languageUpload', $e->getMessage());
}
}
/**
* @inheritDoc
*/
public function save()
{
parent::save();
LanguageFactory::getInstance()->clearCache();
LanguageFactory::getInstance()->deleteLanguageCache();
$this->saved();
// reset fields
$this->sourceLanguageID = 0;
$this->packageID = 0;
// show success message
WCF::getTPL()->assign('success', true);
}
/**
* @inheritDoc
*/
public function assignVariables()
{
parent::assignVariables();
$packages = PackageCache::getInstance()->getPackages();
\usort($packages, static function (Package $a, Package $b) {
return $a->getName() <=> $b->getName();
});
WCF::getTPL()->assign([
'languages' => $this->languages,
'sourceLanguageID' => $this->sourceLanguageID,
'packages' => $packages,
'packageID' => $this->packageID,
]);
}
}
| Cyperghost/WCF | wcfsetup/install/files/lib/acp/form/LanguageImportForm.class.php | PHP | lgpl-2.1 | 4,636 |
//
// System.Web.Compilation.CompilationException
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Specialized;
using System.CodeDom.Compiler;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Web;
namespace System.Web.Compilation
{
[Serializable]
internal class CompilationException : HtmlizedException
{
string filename;
CompilerErrorCollection errors;
CompilerResults results;
string fileText;
string errmsg;
int [] errorLines;
CompilationException (SerializationInfo info, StreamingContext context)
: base (info, context)
{
filename = info.GetString ("filename");
errors = info.GetValue ("errors", typeof (CompilerErrorCollection)) as CompilerErrorCollection;
results = info.GetValue ("results", typeof (CompilerResults)) as CompilerResults;
fileText = info.GetString ("fileText");
errmsg = info.GetString ("errmsg");
errorLines = info.GetValue ("errorLines", typeof (int[])) as int[];
}
public CompilationException (string filename, CompilerErrorCollection errors, string fileText)
{
this.filename = filename;
this.errors = errors;
this.fileText = fileText;
}
public CompilationException (string filename, CompilerResults results, string fileText)
: this (filename, results != null ? results.Errors : null, fileText)
{
this.results = results;
}
[SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData (SerializationInfo info, StreamingContext ctx)
{
base.GetObjectData (info, ctx);
info.AddValue ("filename", filename);
info.AddValue ("errors", errors);
info.AddValue ("results", results);
info.AddValue ("fileText", fileText);
info.AddValue ("errmsg", errmsg);
info.AddValue ("errorLines", errorLines);
}
public override string Message {
get { return ErrorMessage; }
}
public override string SourceFile {
get {
if (errors == null || errors.Count == 0)
return filename;
return errors [0].FileName;
}
}
public override string FileName {
get { return filename; }
}
public override string Title {
get { return "Compilation Error"; }
}
public override string Description {
get {
return "Error compiling a resource required to service this request. " +
"Review your source file and modify it to fix this error.";
}
}
public override string ErrorMessage {
get {
if (errmsg == null && errors != null) {
CompilerError firstError = null;
foreach (CompilerError err in errors) {
if (err.IsWarning)
continue;
firstError = err;
break;
};
if (firstError != null) {
errmsg = firstError.ToString ();
int idx = errmsg.IndexOf (" : error ");
if (idx > -1)
errmsg = errmsg.Substring (idx + 9);
} else
errmsg = String.Empty;
}
return errmsg;
}
}
public override string FileText {
get { return fileText; }
}
public override int [] ErrorLines {
get {
if (errorLines == null && errors != null) {
ArrayList list = new ArrayList ();
foreach (CompilerError err in errors) {
if (err.IsWarning)
continue;
if (err.Line != 0 && !list.Contains (err.Line))
list.Add (err.Line);
}
errorLines = (int []) list.ToArray (typeof (int));
Array.Sort (errorLines);
}
return errorLines;
}
}
public override bool ErrorLinesPaired {
get { return false; }
}
public StringCollection CompilerOutput {
get {
if (results == null)
return null;
return results.Output;
}
}
public CompilerResults Results {
get { return results; }
}
}
}
| edwinspire/VSharp | class/System.Web/System.Web.Compilation/CompilationException.cs | C# | lgpl-3.0 | 4,980 |
<?php
/**
* Part of Windwalker project.
*
* @copyright Copyright (C) 2014 - 2015 LYRASOFT. All rights reserved.
* @license GNU Lesser General Public License version 3 or later.
*/
namespace Windwalker\Filter\Cleaner;
/**
* Interface FilterRuleInterface
*
* @since 2.0
*/
interface CleanerInterface
{
/**
* Method to clean text by rule.
*
* @param string $source The source to be clean.
*
* @return mixed The cleaned value.
*/
public function clean($source);
}
| dstuecken/windwalker | src/Filter/Cleaner/CleanerInterface.php | PHP | lgpl-3.0 | 497 |
/*
* #%L
* Alfresco Data model classes
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.search.impl.querymodel.impl;
import org.alfresco.repo.search.impl.querymodel.Constraint;
public abstract class BaseConstraint implements Constraint
{
private Occur occur = Occur.DEFAULT;
private float boost = 1.0f;
public BaseConstraint()
{
}
public Occur getOccur()
{
return occur;
}
public void setOccur(Occur occur)
{
this.occur = occur;
}
public float getBoost()
{
return boost;
}
public void setBoost(float boost)
{
this.boost = boost;
}
}
| Alfresco/community-edition | projects/data-model/source/java/org/alfresco/repo/search/impl/querymodel/impl/BaseConstraint.java | Java | lgpl-3.0 | 1,672 |
/*
* Project: Sudoku Explainer
* Copyright (C) 2006-2007 Nicolas Juillerat
* Available under the terms of the Lesser General Public License (LGPL)
*/
package diuf.sudoku.solver.rules;
import java.util.*;
import diuf.sudoku.*;
import diuf.sudoku.solver.*;
/**
* Implementation of the Naked Single solving techniques.
*/
public class NakedSingle implements DirectHintProducer {
/**
* Check if a cell has only one potential value, and accumulate
* corresponding hints
*/
public void getHints(Grid grid, HintsAccumulator accu) throws InterruptedException {
Grid.Region[] parts = grid.getRegions(Grid.Row.class);
// Iterate on parts
for (Grid.Region part : parts) {
// Iterate on cells
for (int index = 0; index < 9; index++) {
Cell cell = part.getCell(index);
// Get the cell's potential values
BitSet potentialValues = cell.getPotentialValues();
if (potentialValues.cardinality() == 1) {
// One potential value -> solution found
int uniqueValue = potentialValues.nextSetBit(0);
accu.add(new NakedSingleHint(this, null, cell, uniqueValue));
}
}
}
}
@Override
public String toString() {
return "Naked Singles";
}
}
| blindlf/SudokuExplainer | src/main/java/diuf/sudoku/solver/rules/NakedSingle.java | Java | lgpl-3.0 | 1,378 |
package net.minecraft.src;
public class EnchantmentData extends WeightedRandomItem
{
/** Enchantment object associated with this EnchantmentData */
public final Enchantment enchantmentobj;
/** Enchantment level associated with this EnchantmentData */
public final int enchantmentLevel;
public EnchantmentData(Enchantment par1Enchantment, int par2)
{
super(par1Enchantment.getWeight());
this.enchantmentobj = par1Enchantment;
this.enchantmentLevel = par2;
}
public EnchantmentData(int par1, int par2)
{
this(Enchantment.enchantmentsList[par1], par2);
}
}
| Neil5043/Minetweak | src/main/java/net/minecraft/src/EnchantmentData.java | Java | lgpl-3.0 | 630 |
/* Mesquite source code. Copyright 1997 and onward, W. Maddison and D. Maddison.
Disclaimer: The Mesquite source code is lengthy and we are few. There are no doubt inefficiencies and goofs in this code.
The commenting leaves much to be desired. Please approach this source code with the spirit of helping out.
Perhaps with your help we can be more than a few, and make Mesquite better.
Mesquite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
Mesquite's web site is http://mesquiteproject.org
This source code and its compiled class files are free and modifiable under the terms of
GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html)
*/
package mesquite.trees.ScaleSelBranchLengths;
import java.util.*;
import java.awt.*;
import mesquite.lib.*;
import mesquite.lib.duties.*;
/* ======================================================================== */
public class ScaleSelBranchLengths extends BranchLengthsAlterer {
double resultNum;
double scale = 0;
/*.................................................................................................................*/
public boolean startJob(String arguments, Object condition, boolean hiredByName) {
scale = MesquiteDouble.queryDouble(containerOfModule(), "Scale lengths of selected branches", "Multiply all branch lengths by", 1.0);
return true;
}
/*.................................................................................................................*/
/** returns whether this module is requesting to appear as a primary choice */
public boolean requestPrimaryChoice(){
return true;
}
/*.................................................................................................................*/
public boolean isSubstantive(){
return true;
}
/*.................................................................................................................*/
public boolean isPrerelease(){
return false;
}
/*.................................................................................................................*/
public boolean transformTree(AdjustableTree tree, MesquiteString resultString, boolean notify){
if (MesquiteDouble.isCombinable(scale) && tree instanceof MesquiteTree) {
if (tree.hasBranchLengths()){
((MesquiteTree)tree).doCommand("scaleLengthSelectedBranches", MesquiteDouble.toString(scale), CommandChecker.defaultChecker);
if (notify && tree instanceof Listened) ((Listened)tree).notifyListeners(this, new Notification(MesquiteListener.BRANCHLENGTHS_CHANGED));
return true;
}
else discreetAlert( "Branch lengths of tree are all unassigned. Cannot scale selected branch lengths.");
}
return false;
}
/*.................................................................................................................*/
public String getName() {
return "Scale Selected Branch Lengths";
}
/*.................................................................................................................*/
public String getNameForMenuItem() {
return "Scale Selected Branch Lengths...";
}
/*.................................................................................................................*/
/** returns an explanation of what the module does.*/
public String getExplanation() {
return "Adjusts lengths of a tree's selected branches by multiplying them by an amount." ;
}
}
| MesquiteProject/MesquiteCore | Source/mesquite/trees/ScaleSelBranchLengths/ScaleSelBranchLengths.java | Java | lgpl-3.0 | 3,540 |
/*
This file is part of FaMaTS.
FaMaTS is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
FaMaTS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with FaMaTS. If not, see <http://www.gnu.org/licenses/>.
*/
package es.us.isa.ChocoReasoner.questions;
import java.util.ArrayList;
import java.util.List;
import es.us.isa.ChocoReasoner.ChocoQuestion;
import es.us.isa.ChocoReasoner.ChocoResult;
import es.us.isa.FAMA.Benchmarking.PerformanceResult;
import es.us.isa.FAMA.Exceptions.FAMAException;
import es.us.isa.FAMA.Reasoner.Question;
import es.us.isa.FAMA.Reasoner.Reasoner;
import es.us.isa.FAMA.Reasoner.questions.SetQuestion;
public class ChocoSetQuestion extends ChocoQuestion implements SetQuestion{
private List<ChocoQuestion> questionsList=new ArrayList<ChocoQuestion>();
public void addQuestion(Question q) {
if ( q instanceof ChocoQuestion )
questionsList.add((ChocoQuestion) q);
}
public void preAnswer(Reasoner r) {
for ( int i = questionsList.size() - 1; i >= 0; i--) {
((ChocoQuestion)questionsList.get(i)).preAnswer(r);
}
}
public PerformanceResult answer(Reasoner r) {
if(r==null){
throw new FAMAException("Reasoner not present");
}else{
ChocoResult res = null;
for ( int i = 0; i < questionsList.size(); i++) {
ChocoResult pr = (ChocoResult)((ChocoQuestion)questionsList.get(i)).answer(r);
if (pr != null) {
if (res == null) {
res = pr;
} else {
res.addFields(pr);
}
}
}
return res;
}
}
@Override
public void postAnswer(Reasoner r) {
for ( int i = 0; i < questionsList.size(); i++) {
((ChocoQuestion)questionsList.get(i)).postAnswer(r);
}
}
}
| isa-group/FaMA | reasoner_choco_2/src/es/us/isa/ChocoReasoner/questions/ChocoSetQuestion.java | Java | lgpl-3.0 | 2,214 |
/*
* #%L
* Alfresco Data model classes
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.search.impl.querymodel.impl.functions;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
import org.alfresco.repo.search.impl.querymodel.Argument;
import org.alfresco.repo.search.impl.querymodel.ArgumentDefinition;
import org.alfresco.repo.search.impl.querymodel.FunctionEvaluationContext;
import org.alfresco.repo.search.impl.querymodel.Multiplicity;
import org.alfresco.repo.search.impl.querymodel.impl.BaseArgumentDefinition;
import org.alfresco.repo.search.impl.querymodel.impl.BaseFunction;
import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
public class FTSRange extends BaseFunction
{
public final static String NAME = "FTSRange";
public final static String ARG_FROM_INC = "FromInc";
public final static String ARG_FROM = "From";
public final static String ARG_TO = "To";
public final static String ARG_TO_INC = "ToInc";
public final static String ARG_PROPERTY = "Property";
public static LinkedHashMap<String, ArgumentDefinition> args;
static
{
args = new LinkedHashMap<String, ArgumentDefinition>();
args.put(ARG_FROM_INC, new BaseArgumentDefinition(Multiplicity.SINGLE_VALUED, ARG_FROM_INC, DataTypeDefinition.BOOLEAN, true));
args.put(ARG_FROM, new BaseArgumentDefinition(Multiplicity.SINGLE_VALUED, ARG_FROM, DataTypeDefinition.TEXT, true));
args.put(ARG_TO, new BaseArgumentDefinition(Multiplicity.SINGLE_VALUED, ARG_TO, DataTypeDefinition.TEXT, true));
args.put(ARG_TO_INC, new BaseArgumentDefinition(Multiplicity.SINGLE_VALUED, ARG_TO_INC, DataTypeDefinition.BOOLEAN, true));
args.put(ARG_PROPERTY, new BaseArgumentDefinition(Multiplicity.SINGLE_VALUED, ARG_PROPERTY, DataTypeDefinition.ANY, false));
}
public FTSRange()
{
super(NAME, DataTypeDefinition.BOOLEAN, args);
}
public Serializable getValue(Map<String, Argument> args, FunctionEvaluationContext context)
{
throw new UnsupportedOperationException();
}
}
| Alfresco/community-edition | projects/data-model/source/java/org/alfresco/repo/search/impl/querymodel/impl/functions/FTSRange.java | Java | lgpl-3.0 | 3,154 |
package org.molgenis.data.annotation.impl.datastructures;
/**
* Created by jvelde on 1/30/14.
*/
public class HGNCLocations
{
String hgnc;
Long start;
Long end;
String chrom;
public HGNCLocations(String hgnc, Long start, Long end, String chrom)
{
this.hgnc = hgnc;
this.start = start;
this.end = end;
this.chrom = chrom;
}
@Override
public String toString()
{
return "HgncLoc{" + "hgnc='" + hgnc + '\'' + ", start=" + start + ", end=" + end + ", chrom='" + chrom + '\''
+ '}';
}
public String getHgnc()
{
return hgnc;
}
public Long getStart()
{
return start;
}
public Long getEnd()
{
return end;
}
public String getChrom()
{
return chrom;
}
}
| marijevdgeest/molgenis | molgenis-data-annotators/src/main/java/org/molgenis/data/annotation/impl/datastructures/HGNCLocations.java | Java | lgpl-3.0 | 698 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="description" content="">
<meta name="keywords" content="">
<title>下载中心_汽车转向泵,齿轮泵,叶片泵-绍兴县申达液压机械厂,申达液压机械厂,Shenda Hydraulic Machinery Factory, Power Steering Pump</title>
<link href="/template/default/images/style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="/template/default/images/jquery.js"></script>
<script type="text/javascript" src="/template/default/images/nav.js"></script>
</head>
<body>
<div class="head_login" id="user_login">
<form name="form1" action="/member.php" method="post">
<label>用户名:</label>
<input type="text" id="ajax_user" name="user" style="width:100px" />
<label>登陆密码:</label>
<input type="password" id="ajax_password" name="password" style="width:100px" />
<label>验证码:</label>
<input type="text" name="code" id="ajax_code" style="width:50px" />
<img src="/plus/code.php" name="code" border="0" id="code" style="display:block; float:left;cursor:pointer; margin-left:5px; display:inline"/>
<input type="hidden" id="ajax_lang" value="cn" name="lang" />
<input type="button" style="border:0; margin-left:5px; display:inline; padding:0" src="/template/default/images/login_input2.gif" name="go" id="ajax_login" />
<label>
<a href="/member.php?action=regist&lang=cn">注册会员</a>
</label>
</form>
<div class="head_right">
<a href="#" onclick="javascript:window.external.AddFavorite('http://www.qxzxb.com','')" title="收藏本站到你的收藏夹">加入收藏</a>
<a href="/index.php?lang=cn" class="focus" >简体中文</a>
<a href="/index.php?lang=en" >English</a>
</div>
<div class="clear"></div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#code').click(function(){
$(this).attr('src','/plus/code.php?tag='+new Date().getTime());
});
$.ajax({
type:"POST",
url:"/member.php",
data:"action=is_ajax_login&lang="+"cn",
dataType:"json",
success:function(data){
if(data.login==1){
$('#user_login').html(data.info);
}
}
});
$('#ajax_login').click(function(){
$.ajax({
type:"POST",
url:"/member.php",
data:"action=ajax_login&lang="+$('#ajax_lang').val()+"&password="+$('#ajax_password').val()+"&user="+$('#ajax_user').val()+"&code="+$('#ajax_code').val(),
dataType:"json",
success:function(data){
if(data.login==1){
$('#user_login').html(data.info);
}else{
alert(data.info);
}
}
});
});
});
</script>
<div class="head">
<div class="head_left">
<div class="logo"><a href="/index.php?lang=cn"><img src="/template/default/images/logo.jpg" border="0" /></a></div>
</div>
<div class="clear"></div>
</div>
<div class="head_nav"><!--head-->
<div class="nav_left">
<div class="nav_right">
<ul>
<li>
<div id ='nav_time'>
</div>
<script type="text/javascript">
nav_timer();
setInterval("nav_timer()", 1000);
function nav_timer(){
document.getElementById("nav_time").innerHTML=new Date().toLocaleString()+' '
}
</script>
</li>
<li><a href="/index.php?lang=cn">首页</a></li>
<li class="">
<a href="/show_list.php?id=11" >企业介绍</a>
</li>
<li class="">
<a href="/show_list.php?id=5" >产品展示</a>
</li>
<li class="">
<a href="/show_list.php?id=6" >新闻中心</a>
</li>
<li class="">
<a href="/show_list.php?id=7" >联系我们</a>
</li>
<li class="">
<a href="/book.php?lang=cn" >留言本</a>
</li>
</ul>
</div>
</div>
</div><!--head -->
<div class="div_margin"></div>
<div class="flash">
<script language='javascript'>
linkarr = new Array();
picarr = new Array();
textarr = new Array();
var swf_width=950;
var swf_height=200;
var text_height=0;
var files = "";
var links = "";
var texts = "";
//这里设置调用标记
linkarr[1] = "http://www.qxzxb.com";
picarr[1] = "/upload/img/20110529/20110529223910.jpg";
linkarr[2] = "http://www.qxzxb.com";
picarr[2] = "/upload/img/20110529/20110529223952.JPG";
linkarr[3] = "http://www.qxzxb.com";
picarr[3] = "/upload/img/20110529/20110529224020.JPG";
linkarr[4] = "http://www.qxzxb.com";
picarr[4] = "/upload/img/20110529/20110529224047.JPG";
for(i=1;i<picarr.length;i++){
if(files=="") files = picarr[i];
else files += "|"+picarr[i];
}
for(i=1;i<linkarr.length;i++){
if(links=="") links = linkarr[i];
else links += "|"+linkarr[i];
}
for(i=1;i<textarr.length;i++){
if(texts=="") texts = textarr[i];
else texts += "|"+textarr[i];
}
document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+ swf_width +'" height="'+ swf_height +'">');
document.write('<param name="movie" value="/data/flash_ad/ad_3/bcastr.swf"><param name="quality" value="high">');
document.write('<param name="menu" value="false"><param name=wmode value="opaque">');
document.write('<param name="FlashVars" value="pics='+files+'&links='+links+'&texts='+texts+'&borderwidth='+swf_width+'&borderheight='+swf_height+'&textheight='+text_height+'">');
document.write('<embed src="/data/flash_ad/ad_3/bcastr.swf" wmode="opaque" FlashVars="pics='+files+'&links='+links+'&texts='+texts+'&borderwidth='+swf_width+'&borderheight='+swf_height+'&textheight='+text_height+'" menu="false" quality="high" width="'+ swf_width +'" height="'+ swf_height +'" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />'); document.write('</object>');
</script></div><div class="div_margin"></div>
<div class="contain">
<div class="contain_left">
<div class="box left_width">
<div class="box_left"></div>
<div class="box_right"></div>
<div class="box_title"><h2>产品导航</h2></div>
<div class="box_in">
<ul class="nav_list">
</ul>
</div>
</div><!--容器结束-->
<div class="div_margin"></div>
<div class="box">
<div class="box_left"></div>
<div class="box_right"></div>
<div class="box_title"><h2>联系方式</h2></div>
<div class="box_in">
<div class="contact">
</div>
</div>
</div><!--容器结束-->
<div class="div_margin"></div>
<div class="box">
<div class="box_left"></div>
<div class="box_right"></div>
<div class="box_title"><h2>热门内容</h2></div>
<div class="box_in">
<div class="list_news">
<ul>
</ul>
</div>
</div>
</div><!--容器结束-->
<div class="div_margin"></div>
<div class="box">
<div class="box_left"></div>
<div class="box_right"></div>
<div class="box_title"><h2>推荐产品</h2></div>
<div class="box_in">
<div class="list_product">
<ul>
</ul>
</div>
</div>
</div><!--容器结束-->
</div><!--左边内容-->
<div class="contain_right">
<div class="box">
<div class="box_left"></div>
<div class="box_right"></div>
<div class="box_title"><h2 class="position"><span>当前位置:<a href="/index.php?lang=cn">首页</a> > <a href="/show_list.php?id=9">下载中心</a> > 列表页</span></h2></div>
<div class="box_in">
<ul class="ul_list_article">
<li><span class="time">2011-06-01 10:06:12</span><a href="/show_content.php?id=7" >经典漂浮广告的JS代码</a></li>
</ul>
<div class="list_page">
<ul>
<li><a href="show_list.php?page=1&id=9">首页</a></li><li><a href="#">上一页</a></li><li class="focus"><a href="show_list.php?page=1&id=9">1</a></li><li><a href="#">下一页</a></li><li><a href="show_list.php?page=1&id=9">尾页</a></li><li>转到<select style="width:40px;" onchange="location.href=this.options[this.selectedIndex].value;"><option value="?page=1&id=9" selected="selected">1</option></select></li><li>共1条记录,当前第1/1</li> </ul>
</div>
<div class="clear"></div>
</div>
</div><!--容器结束-->
</div>
<div class="clear"></div>
</div>
<div class="contain foot">
<div class="foot_nav">
<a href="/show_list.php?id=11" title="企业介绍">企业介绍</a>| <a href="/show_list.php?id=5" title="产品展示">产品展示</a>| <a href="/show_list.php?id=6" title="新闻中心">新闻中心</a>| <a href="/show_list.php?id=7" title="联系我们">联系我们</a>| <a href="/show_list.php?id=9" title="下载中心">下载中心</a>| <a href="/sitemap.php?lang=cn" title="网站地图">网站地图</a>| <a href="/book.php?lang=cn" title="留言本">留言本</a> </div>
<p>copyright by 绍兴县申达液压机械厂</p>
<!-- <p>备案号:</p> -->
<!-- <p>powerd by <a href="http://www.beescms.com" target="_blank">BEESCMS</a></p>-->
</div><!--页脚-->
<style type="text/css">
/*浮动QQ在线客服*/
.kf_contain{z-index:99; width:142px; right:0; top:100px; position:absolute}
.kf_contain .kf_list{ width:142px; margin:0 auto; background:#3e3e48}
.kf_contain .kf_list .t{background:url(/template/default/images/kf_top.gif) no-repeat left 0; height:66px; font-size:1px}
.kf_contain .kf_list .b{background:#3e3e48;height:2px}
.kf_contain .kf_list .con{margin:0 auto; background:#fff; margin:0 3px 3px 3px; width:136px; overflow:hidden; text-align:center}
.kf_contain .kf_list .con .title{font-size:12px; margin-bottom:5px; margin-left:5px; text-align:left; height:20px; padding-left:20px; background:url(/template/default/images/kf_icon.gif) no-repeat left center; line-height:20px; color:#000000}
.kf_contain .kf_list .con ul{margin:0 auto; padding:0; width:133px; background-color:#FFFFFF; border:#FFFFFF 1px solid}
.kf_contain .kf_list .con li{font-size:9pt; list-style-type:none; height:25px; padding-right:5px; clear:both; display:block;}
.kf_contain .kf_list .con li span{line-height:25px; margin-left:10px; display:block; vertical-align:middle}
.kf_contain .kf_list .con li span.lf{float:left}
.kf_contain .kf_list .con li span.lr{float:right}
.on_kf{width:25px; height:120px; float:right}
/*浮动QQ在线客服*/
</style>
<form id="form1" runat="server">
<div>
<div class="kf_contain" id="kf_contain">
<div class="on_kf" id="on" onmouseover="kf_on();"><img src="/template/default/images/on.gif" border="0" alt="客服"/></div>
<div >
<div class="kf_list" id="off" onmouseout="kf_off();" onmousemove="kf_on();">
<div class="t"></div>
<div class="con">
<ul>
<li>
<span class="lf">
<a target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin=0575-85182445&site=qq&menu=yes"><img border="0" src="http://wpa.qq.com/pa?p=2:0575-85182445:4" alt="点击这里给我发消息" title="点击这里给我发消息"></a>
</span>
<span class="lf">0575-85182445</span>
</li>
</ul>
</div>
<div class="b"></div>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
<script type="text/javascript">
var tips;
var theTop = 100/*这是默认高度,越大越往下*/;
var old = theTop;
var $on_e= document.getElementById("on");
var $off_e=document.getElementById("off");
function initFloatTips() {
document.getElementById("off").style.display = "none";
tips = document.getElementById("kf_contain");
moveTips();
};
function moveTips() {
var sped = 50;
if (window.innerHeight) {
pos = window.pageYOffset
}
else if (document.documentElement && document.documentElement.scrollTop) {
pos = document.documentElement.scrollTop
}
else if (document.body) {
pos = document.body.scrollTop;
}
pos = pos - tips.offsetTop + theTop;
pos = tips.offsetTop + pos / 10;
if (pos < theTop) pos = theTop;
if (pos != old) {
tips.style.top = pos + "px";
sped = 10;
}
old = pos;
setTimeout(moveTips, sped);
}
initFloatTips();
function kf_on(){
$on_e.style.display = "none";
$off_e.style.display = "block";
}
function kf_off(){
$on_e.style.display = "block";
$off_e.style.display = "none";
}
</script>
</body>
</html> | sdyycn/qxzxb | site/data/cache_template/show_list__page_1&id_9_cn.php | PHP | lgpl-3.0 | 12,657 |
/* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2008-2013 Pelican Mapping
* http://osgearth.org
*
* osgEarth is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include <osgEarthUtil/TileIndexBuilder>
#include <osgEarth/Registry>
#include <osgEarth/FileUtils>
#include <osgEarth/Progress>
#include <osgEarthDrivers/gdal/GDALOptions>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
using namespace osgDB;
using namespace osgEarth;
using namespace osgEarth::Util;
using namespace osgEarth::Drivers;
using namespace osgEarth::Features;
using namespace std;
TileIndexBuilder::TileIndexBuilder()
{
}
void TileIndexBuilder::setProgressCallback( osgEarth::ProgressCallback* progress )
{
_progress = progress;
}
void TileIndexBuilder::build(const std::string& indexFilename, const osgEarth::SpatialReference* srs)
{
expandFilenames();
if (!srs)
{
srs = osgEarth::SpatialReference::create("wgs84");
}
osg::ref_ptr< osgEarth::Util::TileIndex > index = osgEarth::Util::TileIndex::create( indexFilename, srs );
_indexFilename = indexFilename;
std::string indexDir = getFilePath( _indexFilename );
unsigned int total = _expandedFilenames.size();
for (unsigned int i = 0; i < _expandedFilenames.size(); i++)
{
std::string filename = _expandedFilenames[ i ];
GDALOptions opt;
opt.url() = filename;
osg::ref_ptr< ImageLayer > layer = new ImageLayer( ImageLayerOptions("", opt) );
bool ok = false;
if ( layer.valid() )
{
osg::ref_ptr< TileSource > source = layer->getTileSource();
if (source.valid())
{
for (DataExtentList::iterator itr = source->getDataExtents().begin(); itr != source->getDataExtents().end(); ++itr)
{
// We want the filename as it is relative to the index file
std::string relative = getPathRelative( indexDir, filename );
index->add( relative, *itr);
ok = true;
}
}
}
if (_progress.valid())
{
std::stringstream buf;
if (ok)
{
buf << "Processed ";
}
else
{
buf << "Skipped ";
}
buf << filename;
_progress->reportProgress( (double)i+1, (double)total, buf.str() );
}
}
osg::Timer_t end = osg::Timer::instance()->tick();
}
void TileIndexBuilder::expandFilenames()
{
// Expand the filenames since they might contain directories
for (unsigned int i = 0; i < _filenames.size(); i++)
{
std::string filename = _filenames[i];
if (osgDB::fileType(filename) == osgDB::DIRECTORY)
{
CollectFilesVisitor v;
v.traverse( filename );
for (unsigned int j = 0; j < v.filenames.size(); j++)
{
_expandedFilenames.push_back( v.filenames[ j ] );
}
}
else
{
_expandedFilenames.push_back( filename );
}
}
}
| dchristopherfennell/osgEarth_clone | src/osgEarthUtil/TileIndexBuilder.cpp | C++ | lgpl-3.0 | 3,927 |
/* Mesquite source code. Copyright 1997 and onward, W. Maddison and D. Maddison.
Disclaimer: The Mesquite source code is lengthy and we are few. There are no doubt inefficiencies and goofs in this code.
The commenting leaves much to be desired. Please approach this source code with the spirit of helping out.
Perhaps with your help we can be more than a few, and make Mesquite better.
Mesquite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
Mesquite's web site is http://mesquiteproject.org
This source code and its compiled class files are free and modifiable under the terms of
GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html)
*/
package mesquite.distance.PDistance;
/*~~ */
import java.awt.Checkbox;
import mesquite.lib.*;
import mesquite.lib.characters.*;
import mesquite.categ.lib.DNAData;
import mesquite.distance.lib.*;
/* ======================================================================== */
/* incrementable, with each being based on a different matrix */
public class PDistance extends DNATaxaDistFromMatrix {
MesquiteBoolean transversionsOnly = new MesquiteBoolean(false);
MesquiteBoolean transitionsOnly = new MesquiteBoolean(false);
/*.................................................................................................................*/
public boolean startJob(String arguments, Object condition, boolean hiredByName) {
addCheckMenuItemToSubmenu(null, distParamSubmenu, "Transversions Only", MesquiteModule.makeCommand("toggleTransversionsOnly", this), transversionsOnly);
addCheckMenuItemToSubmenu(null, distParamSubmenu, "Transitions Only", MesquiteModule.makeCommand("toggleTransitionsOnly", this), transitionsOnly);
return true;
}
public boolean optionsAdded() {
return true;
}
RadioButtons radios;
public void addOptions(ExtensibleDialog dialog) {
super.addOptions(dialog);
String[] labels = {"all changes", "transversions only", "transitions only"};
int defaultValue= 0;
if (transversionsOnly.getValue())
defaultValue = 1;
else if (transitionsOnly.getValue())
defaultValue = 2;
radios = dialog.addRadioButtons(labels, defaultValue);
}
public void processOptions(ExtensibleDialog dialog) {
super.processOptions(dialog);
if (radios.getValue()==0) {
transversionsOnly.setValue(false);
transitionsOnly.setValue(false);
}
else if (radios.getValue()==1) {
transversionsOnly.setValue(true);
transitionsOnly.setValue(false);
}
else if (radios.getValue()==2) {
transversionsOnly.setValue(false);
transitionsOnly.setValue(true);
}
}
/*.................................................................................................................*/
public Snapshot getSnapshot(MesquiteFile file) {
Snapshot snapshot = new Snapshot();
snapshot.addLine("toggleTransversionsOnly " + transversionsOnly.toOffOnString());
snapshot.addLine("toggleTransitionsOnly " + transitionsOnly.toOffOnString());
return snapshot;
}
/*.................................................................................................................*/
public Object doCommand(String commandName, String arguments, CommandChecker checker) {
if (checker.compare(this.getClass(), "Sets whether only transversions are counted.", "[on; off]", commandName, "toggleTransversionsOnly")) {
transversionsOnly.toggleValue(new Parser().getFirstToken(arguments));
if (transversionsOnly.getValue())
transitionsOnly.setValue(false);
parametersChanged();
}
else if (checker.compare(this.getClass(), "Sets whether only transitions are counted.", "[on; off]", commandName, "toggleTransitionsOnly")) {
transitionsOnly.toggleValue(new Parser().getFirstToken(arguments));
if (transitionsOnly.getValue())
transversionsOnly.setValue(false);
parametersChanged();
}
else
return super.doCommand(commandName, arguments, checker);
return null;
}
/*.................................................................................................................*/
public boolean getTransversionsOnly(){
return transversionsOnly.getValue();
}
/*.................................................................................................................*/
public boolean getTransitionsOnly(){
return transitionsOnly.getValue();
}
/*.................................................................................................................*/
public String getParameters(){
String s = super.getParameters();
if (getTransversionsOnly())
s+= " Transversions only.";
if (getTransitionsOnly())
s+= " Transitions only.";
return s;
}
/*.................................................................................................................*/
public TaxaDistance getTaxaDistance(Taxa taxa, MCharactersDistribution observedStates){
if (observedStates==null) {
MesquiteMessage.warnProgrammer("Observed states null in "+ getName());
return null;
}
if (!(observedStates.getParentData() instanceof DNAData)) {
return null;
}
PTD simpleTD = new PTD( this,taxa, observedStates,getEstimateAmbiguityDifferences(), getCountDifferencesIfGapInPair());
return simpleTD;
}
/*.................................................................................................................*/
public String getName() {
return "Uncorrected (p) distance (DNA)";
}
/*.................................................................................................................*/
/** returns an explanation of what the module does.*/
public String getExplanation() {
return "Uncorrected (p) distance from a DNA matrix." ;
}
public boolean requestPrimaryChoice(){
return true;
}
/*.................................................................................................................*/
/** returns the version number at which this module was first released. If 0, then no version number is claimed. If a POSITIVE integer
* then the number refers to the Mesquite version. This should be used only by modules part of the core release of Mesquite.
* If a NEGATIVE integer, then the number refers to the local version of the package, e.g. a third party package*/
public int getVersionOfFirstRelease(){
return 110;
}
/*.................................................................................................................*/
public boolean isPrerelease(){
return false;
}
/*.................................................................................................................*/
public boolean showCitation(){
return true;
}
}
class PTD extends DNATaxaDistance {
PDistance PD;
public PTD(MesquiteModule ownerModule, Taxa taxa, MCharactersDistribution observedStates, boolean estimateAmbiguityDifferences, boolean countDifferencesIfGapInPair){
super(ownerModule, taxa, observedStates,estimateAmbiguityDifferences, countDifferencesIfGapInPair);
PD = (PDistance)ownerModule;
MesquiteDouble N = new MesquiteDouble();
MesquiteDouble D = new MesquiteDouble();
setEstimateAmbiguityDifferences(((DNATaxaDistFromMatrix)ownerModule).getEstimateAmbiguityDifferences());
for (int taxon1=0; taxon1<getNumTaxa(); taxon1++) {
for (int taxon2=taxon1; taxon2<getNumTaxa(); taxon2++) {
double[][] fxy = calcPairwiseDistance(taxon1, taxon2, N, D);
if (PD.getTransversionsOnly())
distances[taxon1][taxon2]= fxy[0][1] + fxy[1][0] + fxy[0][3] + fxy[3][0] + fxy[1][2] + fxy[2][1] + fxy[2][3] + fxy[3][2]; //trasnversion
else if (PD.getTransitionsOnly())
distances[taxon1][taxon2]= fxy[0][2] + fxy[2][0] + fxy[1][3] + fxy[3][1]; //transitions
else
distances[taxon1][taxon2]= D.getValue();
}
}
copyDistanceTriangle();
logDistancesIfDesired(ownerModule.getName()); }
public String getName() {
return PD.getName();
}
}
| MesquiteProject/MesquiteCore | Source/mesquite/distance/PDistance/PDistance.java | Java | lgpl-3.0 | 7,876 |
"""Windows-specific implementation of process utilities.
This file is only meant to be imported by process.py, not by end-users.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2010-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from __future__ import print_function
# stdlib
import os
import sys
import ctypes
import msvcrt
from ctypes import c_int, POINTER
from ctypes.wintypes import LPCWSTR, HLOCAL
from subprocess import STDOUT
# our own imports
from ._process_common import read_no_interrupt, process_handler, arg_split as py_arg_split
from . import py3compat
from . import text
from .encoding import DEFAULT_ENCODING
#-----------------------------------------------------------------------------
# Function definitions
#-----------------------------------------------------------------------------
class AvoidUNCPath(object):
"""A context manager to protect command execution from UNC paths.
In the Win32 API, commands can't be invoked with the cwd being a UNC path.
This context manager temporarily changes directory to the 'C:' drive on
entering, and restores the original working directory on exit.
The context manager returns the starting working directory *if* it made a
change and None otherwise, so that users can apply the necessary adjustment
to their system calls in the event of a change.
Example
-------
::
cmd = 'dir'
with AvoidUNCPath() as path:
if path is not None:
cmd = '"pushd %s &&"%s' % (path, cmd)
os.system(cmd)
"""
def __enter__(self):
self.path = os.getcwdu()
self.is_unc_path = self.path.startswith(r"\\")
if self.is_unc_path:
# change to c drive (as cmd.exe cannot handle UNC addresses)
os.chdir("C:")
return self.path
else:
# We return None to signal that there was no change in the working
# directory
return None
def __exit__(self, exc_type, exc_value, traceback):
if self.is_unc_path:
os.chdir(self.path)
def _find_cmd(cmd):
"""Find the full path to a .bat or .exe using the win32api module."""
try:
from win32api import SearchPath
except ImportError:
raise ImportError('you need to have pywin32 installed for this to work')
else:
PATH = os.environ['PATH']
extensions = ['.exe', '.com', '.bat', '.py']
path = None
for ext in extensions:
try:
path = SearchPath(PATH, cmd + ext)[0]
except:
pass
if path is None:
raise OSError("command %r not found" % cmd)
else:
return path
def _system_body(p):
"""Callback for _system."""
enc = DEFAULT_ENCODING
for line in read_no_interrupt(p.stdout).splitlines():
line = line.decode(enc, 'replace')
print(line, file=sys.stdout)
for line in read_no_interrupt(p.stderr).splitlines():
line = line.decode(enc, 'replace')
print(line, file=sys.stderr)
# Wait to finish for returncode
return p.wait()
def system(cmd):
"""Win32 version of os.system() that works with network shares.
Note that this implementation returns None, as meant for use in IPython.
Parameters
----------
cmd : str
A command to be executed in the system shell.
Returns
-------
None : we explicitly do NOT return the subprocess status code, as this
utility is meant to be used extensively in IPython, where any return value
would trigger :func:`sys.displayhook` calls.
"""
# The controller provides interactivity with both
# stdin and stdout
#import _process_win32_controller
#_process_win32_controller.system(cmd)
with AvoidUNCPath() as path:
if path is not None:
cmd = '"pushd %s &&"%s' % (path, cmd)
return process_handler(cmd, _system_body)
def getoutput(cmd):
"""Return standard output of executing cmd in a shell.
Accepts the same arguments as os.system().
Parameters
----------
cmd : str
A command to be executed in the system shell.
Returns
-------
stdout : str
"""
with AvoidUNCPath() as path:
if path is not None:
cmd = '"pushd %s &&"%s' % (path, cmd)
out = process_handler(cmd, lambda p: p.communicate()[0], STDOUT)
if out is None:
out = b''
return py3compat.bytes_to_str(out)
try:
CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW
CommandLineToArgvW.arg_types = [LPCWSTR, POINTER(c_int)]
CommandLineToArgvW.restype = POINTER(LPCWSTR)
LocalFree = ctypes.windll.kernel32.LocalFree
LocalFree.res_type = HLOCAL
LocalFree.arg_types = [HLOCAL]
def arg_split(commandline, posix=False, strict=True):
"""Split a command line's arguments in a shell-like manner.
This is a special version for windows that use a ctypes call to CommandLineToArgvW
to do the argv splitting. The posix paramter is ignored.
If strict=False, process_common.arg_split(...strict=False) is used instead.
"""
#CommandLineToArgvW returns path to executable if called with empty string.
if commandline.strip() == "":
return []
if not strict:
# not really a cl-arg, fallback on _process_common
return py_arg_split(commandline, posix=posix, strict=strict)
argvn = c_int()
result_pointer = CommandLineToArgvW(py3compat.cast_unicode(commandline.lstrip()), ctypes.byref(argvn))
result_array_type = LPCWSTR * argvn.value
result = [arg for arg in result_array_type.from_address(ctypes.addressof(result_pointer.contents))]
retval = LocalFree(result_pointer)
return result
except AttributeError:
arg_split = py_arg_split
| cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/utils/_process_win32.py | Python | lgpl-3.0 | 6,316 |
/////////////////////////////////////////////////////////////////////
// Quantum Calculator example (C++ version)
// Copyright (c) 2002 Miro Samek, Palo Alto, CA.
// All Rights Reserved.
/////////////////////////////////////////////////////////////////////
#ifndef calc_h
#define calc_h
#include <windows.h>
#include "qf_win32.h"
struct CalcEvt : public QEvent {
int keyId; // ID of the key depressed
};
class Calc : public QHsm { // calculator state machine
public:
Calc() : QHsm((QPseudoState)initial) {}
static Calc *instance(); // Singleton accessor method
private:
void initial(QEvent const *e);
QSTATE calc(QEvent const *e);
QSTATE ready(QEvent const *e);
QSTATE result(QEvent const *e);
QSTATE begin(QEvent const *e);
QSTATE negated1(QEvent const *e);
QSTATE operand1(QEvent const *e);
QSTATE zero1(QEvent const *e);
QSTATE int1(QEvent const *e);
QSTATE frac1(QEvent const *e);
QSTATE opEntered(QEvent const *e);
QSTATE negated2(QEvent const *e);
QSTATE operand2(QEvent const *e);
QSTATE zero2(QEvent const *e);
QSTATE int2(QEvent const *e);
QSTATE frac2(QEvent const *e);
QSTATE final(QEvent const *e);
// helper methods...
void clear();
void insert(int keyId);
void negate();
void eval();
void dispState(char const *s);
private:
HWND myHwnd; // the calculator window handle
BOOL isHandled;
char myDisplay[40];
char *myIns;
double myOperand1;
double myOperand2;
int myOperator;
friend BOOL CALLBACK calcDlg(HWND hwnd, UINT iEvt,
WPARAM wParam, LPARAM lParam);
};
#endif // calc_h
| hyller/CodeLibrary | QP/v2.2.3/CPP/QCALC/CALC.H | C++ | unlicense | 1,929 |
package com.blundell.quicksand.act;
/**
* An Act is our abstraction away from Animations and Transitions, allowing us to treat them both as equals
*/
public interface Act {
int getId();
boolean isFirst();
boolean isLast(); // TODO smells like I should have a first class collection? (and call monitor once for the collection WAT)
void setDuration(long duration);
long getDuration();
void addListener(StartListener startListener); // Maybe split this into addStartListener and addEndListener
interface StartListener {
void onStart(Act act);
void onFinish(Act act);
}
}
| lstNull/QuickSand | core/src/main/java/com/blundell/quicksand/act/Act.java | Java | apache-2.0 | 627 |
/*
* 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.rya.indexing.pcj.fluo.app;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.apache.rya.indexing.pcj.fluo.app.IncrementalUpdateConstants.NODEID_BS_DELIM;
import org.apache.fluo.api.data.Bytes;
import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
import edu.umd.cs.findbugs.annotations.NonNull;
import net.jcip.annotations.Immutable;
/**
* The values of an Accumulo Row ID for a row that stores a Binding set for
* a specific Node ID of a query.
*/
@Immutable
@DefaultAnnotation(NonNull.class)
public class BindingSetRow {
private final String nodeId;
private final String bindingSetString;
/**
* Constructs an instance of {@link BindingSetRow}.
*
* @param nodeId - The Node ID of a query node. (not null)
* @param bindingSetString - A Binding Set that is part of the node's results. (not null)
*/
public BindingSetRow(final String nodeId, final String bindingSetString) {
this.nodeId = checkNotNull(nodeId);
this.bindingSetString = checkNotNull(bindingSetString);
}
/**
* @return The Node ID of a query node.
*/
public String getNodeId() {
return nodeId;
}
/**
* @return A Binding Set that is part of the node's results.
*/
public String getBindingSetString() {
return bindingSetString;
}
/**
* Parses the {@link Bytes} of an Accumulo Row ID into a {@link BindingSetRow}.
*
* @param row - The Row ID to parse. (not null).
* @return A {@link BindingSetRow} holding the parsed values.
*/
public static BindingSetRow make(final Bytes row) {
checkNotNull(row);
// Read the Node ID from the row's bytes.
final String[] rowArray = row.toString().split(NODEID_BS_DELIM);
final String nodeId = rowArray[0];
final String bindingSetString = rowArray.length == 2 ? rowArray[1] : "";
return new BindingSetRow(nodeId, bindingSetString);
}
} | meiercaleb/incubator-rya | extras/rya.pcj.fluo/pcj.fluo.app/src/main/java/org/apache/rya/indexing/pcj/fluo/app/BindingSetRow.java | Java | apache-2.0 | 2,810 |
<?php
/**
* Run a conduit method in-process, without requiring HTTP requests. Usage:
*
* $call = new ConduitCall('method.name', array('param' => 'value'));
* $call->setUser($user);
* $result = $call->execute();
*
*/
final class ConduitCall {
private $method;
private $request;
private $user;
private $servers;
private $forceLocal;
public function __construct($method, array $params) {
$this->method = $method;
$this->handler = $this->buildMethodHandler($method);
$this->servers = PhabricatorEnv::getEnvConfig('conduit.servers');
$this->forceLocal = false;
$invalid_params = array_diff_key(
$params,
$this->handler->defineParamTypes());
if ($invalid_params) {
throw new ConduitException(
"Method '{$method}' doesn't define these parameters: '".
implode("', '", array_keys($invalid_params))."'.");
}
if ($this->servers) {
$current_host = AphrontRequest::getHTTPHeader('HOST');
foreach ($this->servers as $server) {
if ($current_host === id(new PhutilURI($server))->getDomain()) {
$this->forceLocal = true;
break;
}
}
}
$this->request = new ConduitAPIRequest($params);
}
public function setUser(PhabricatorUser $user) {
$this->user = $user;
return $this;
}
public function getUser() {
return $this->user;
}
public function setForceLocal($force_local) {
$this->forceLocal = $force_local;
return $this;
}
public function shouldForceLocal() {
return $this->forceLocal;
}
public function shouldRequireAuthentication() {
return $this->handler->shouldRequireAuthentication();
}
public function shouldAllowUnguardedWrites() {
return $this->handler->shouldAllowUnguardedWrites();
}
public function getRequiredScope() {
return $this->handler->getRequiredScope();
}
public function getErrorDescription($code) {
return $this->handler->getErrorDescription($code);
}
public function execute() {
$profiler = PhutilServiceProfiler::getInstance();
$call_id = $profiler->beginServiceCall(
array(
'type' => 'conduit',
'method' => $this->method,
));
try {
$result = $this->executeMethod();
} catch (Exception $ex) {
$profiler->endServiceCall($call_id, array());
throw $ex;
}
$profiler->endServiceCall($call_id, array());
return $result;
}
private function executeMethod() {
$user = $this->getUser();
if (!$user) {
$user = new PhabricatorUser();
}
$this->request->setUser($user);
if (!$this->shouldRequireAuthentication()) {
// No auth requirement here.
} else {
$allow_public = $this->handler->shouldAllowPublic() &&
PhabricatorEnv::getEnvConfig('policy.allow-public');
if (!$allow_public) {
if (!$user->isLoggedIn() && !$user->isOmnipotent()) {
// TODO: As per below, this should get centralized and cleaned up.
throw new ConduitException('ERR-INVALID-AUTH');
}
}
// TODO: This would be slightly cleaner by just using a Query, but the
// Conduit auth workflow requires the Call and User be built separately.
// Just do it this way for the moment.
$application = $this->handler->getApplication();
if ($application) {
$can_view = PhabricatorPolicyFilter::hasCapability(
$user,
$application,
PhabricatorPolicyCapability::CAN_VIEW);
if (!$can_view) {
throw new ConduitException(
pht(
'You do not have access to the application which provides this '.
'API method.'));
}
}
}
if (!$this->shouldForceLocal() && $this->servers) {
$server = $this->pickRandomServer($this->servers);
$client = new ConduitClient($server);
$params = $this->request->getAllParameters();
$params['__conduit__']['isProxied'] = true;
if ($this->handler->shouldRequireAuthentication()) {
$client->callMethodSynchronous(
'conduit.connect',
array(
'client' => 'PhabricatorConduit',
'clientVersion' => '1.0',
'user' => $this->getUser()->getUserName(),
'certificate' => $this->getUser()->getConduitCertificate(),
'__conduit__' => $params['__conduit__'],
));
}
return $client->callMethodSynchronous(
$this->method,
$params);
} else {
return $this->handler->executeMethod($this->request);
}
}
protected function pickRandomServer($servers) {
return $servers[array_rand($servers)];
}
protected function buildMethodHandler($method_name) {
$method = ConduitAPIMethod::getConduitMethod($method_name);
if (!$method) {
throw new ConduitMethodDoesNotExistException($method_name);
}
$application = $method->getApplication();
if ($application && !$application->isInstalled()) {
$app_name = $application->getName();
throw new ConduitApplicationNotInstalledException($method, $app_name);
}
return $method;
}
}
| akkakks/phabricator | src/applications/conduit/call/ConduitCall.php | PHP | apache-2.0 | 5,216 |
/* 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.flowable.cmmn.api.runtime;
import java.util.Date;
import java.util.Map;
/**
* @author Joram Barrez
*/
public interface CaseInstance {
String getId();
String getParentId();
String getBusinessKey();
String getName();
String getCaseDefinitionId();
String getState();
Date getStartTime();
String getStartUserId();
String getCallbackId();
String getCallbackType();
boolean isCompleteable();
String getTenantId();
/**
* Returns the case variables if requested in the case instance query
*/
Map<String, Object> getCaseVariables();
}
| lsmall/flowable-engine | modules/flowable-cmmn-api/src/main/java/org/flowable/cmmn/api/runtime/CaseInstance.java | Java | apache-2.0 | 1,171 |
/*
* 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.nifi.controller.swap;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.nifi.controller.queue.FlowFileQueue;
import org.apache.nifi.controller.queue.QueueSize;
import org.apache.nifi.controller.repository.FlowFileRecord;
import org.apache.nifi.controller.repository.IncompleteSwapFileException;
import org.apache.nifi.controller.repository.StandardFlowFileRecord;
import org.apache.nifi.controller.repository.SwapContents;
import org.apache.nifi.controller.repository.SwapSummary;
import org.apache.nifi.controller.repository.claim.ResourceClaim;
import org.apache.nifi.controller.repository.claim.ResourceClaimManager;
import org.apache.nifi.controller.repository.claim.StandardContentClaim;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SimpleSwapDeserializer implements SwapDeserializer {
public static final int SWAP_ENCODING_VERSION = 10;
private static final Logger logger = LoggerFactory.getLogger(SimpleSwapDeserializer.class);
@Override
public SwapSummary getSwapSummary(final DataInputStream in, final String swapLocation, final ResourceClaimManager claimManager) throws IOException {
final int swapEncodingVersion = in.readInt();
if (swapEncodingVersion > SWAP_ENCODING_VERSION) {
final String errMsg = "Cannot swap FlowFiles in from " + swapLocation + " because the encoding version is "
+ swapEncodingVersion + ", which is too new (expecting " + SWAP_ENCODING_VERSION + " or less)";
throw new IOException(errMsg);
}
final int numRecords;
final long contentSize;
Long maxRecordId = null;
try {
in.readUTF(); // ignore Connection ID
numRecords = in.readInt();
contentSize = in.readLong();
if (numRecords == 0) {
return StandardSwapSummary.EMPTY_SUMMARY;
}
if (swapEncodingVersion > 7) {
maxRecordId = in.readLong();
}
} catch (final EOFException eof) {
logger.warn("Found premature End-of-File when reading Swap File {}. EOF occurred before any FlowFiles were encountered", swapLocation);
return StandardSwapSummary.EMPTY_SUMMARY;
}
final QueueSize queueSize = new QueueSize(numRecords, contentSize);
final SwapContents swapContents = deserializeFlowFiles(in, queueSize, maxRecordId, swapEncodingVersion, claimManager, swapLocation);
return swapContents.getSummary();
}
@Override
public SwapContents deserializeFlowFiles(final DataInputStream in, final String swapLocation, final FlowFileQueue queue, final ResourceClaimManager claimManager) throws IOException {
final int swapEncodingVersion = in.readInt();
if (swapEncodingVersion > SWAP_ENCODING_VERSION) {
throw new IOException("Cannot swap FlowFiles in from SwapFile because the encoding version is "
+ swapEncodingVersion + ", which is too new (expecting " + SWAP_ENCODING_VERSION + " or less)");
}
final String connectionId = in.readUTF(); // Connection ID
if (!connectionId.equals(queue.getIdentifier())) {
throw new IllegalArgumentException("Cannot deserialize FlowFiles from Swap File at location " + swapLocation
+ " because those FlowFiles belong to Connection with ID " + connectionId + " and an attempt was made to swap them into a Connection with ID " + queue.getIdentifier());
}
int numRecords = 0;
long contentSize = 0L;
Long maxRecordId = null;
try {
numRecords = in.readInt();
contentSize = in.readLong(); // Content Size
if (swapEncodingVersion > 7) {
maxRecordId = in.readLong(); // Max Record ID
}
} catch (final EOFException eof) {
final QueueSize queueSize = new QueueSize(numRecords, contentSize);
final SwapSummary summary = new StandardSwapSummary(queueSize, maxRecordId, Collections.emptyList(), 0L, 0L);
final SwapContents partialContents = new StandardSwapContents(summary, Collections.emptyList());
throw new IncompleteSwapFileException(swapLocation, partialContents);
}
final QueueSize queueSize = new QueueSize(numRecords, contentSize);
return deserializeFlowFiles(in, queueSize, maxRecordId, swapEncodingVersion, claimManager, swapLocation);
}
private static SwapContents deserializeFlowFiles(final DataInputStream in, final QueueSize queueSize, final Long maxRecordId,
final int serializationVersion, final ResourceClaimManager claimManager, final String location) throws IOException {
final List<FlowFileRecord> flowFiles = new ArrayList<>(queueSize.getObjectCount());
final List<ResourceClaim> resourceClaims = new ArrayList<>(queueSize.getObjectCount());
Long maxId = maxRecordId;
for (int i = 0; i < queueSize.getObjectCount(); i++) {
try {
// legacy encoding had an "action" because it used to be couple with FlowFile Repository code
if (serializationVersion < 3) {
final int action = in.read();
if (action != 1) {
throw new IOException("Swap File is version " + serializationVersion + " but did not contain a 'UPDATE' record type");
}
}
final StandardFlowFileRecord.Builder ffBuilder = new StandardFlowFileRecord.Builder();
final long recordId = in.readLong();
if (maxId == null || recordId > maxId) {
maxId = recordId;
}
ffBuilder.id(recordId);
ffBuilder.entryDate(in.readLong());
if (serializationVersion > 1) {
// Lineage information was added in version 2
if (serializationVersion < 10) {
final int numLineageIdentifiers = in.readInt();
for (int lineageIdIdx = 0; lineageIdIdx < numLineageIdentifiers; lineageIdIdx++) {
in.readUTF(); //skip each identifier
}
}
// version 9 adds in a 'lineage start index'
final long lineageStartDate = in.readLong();
final long lineageStartIndex;
if (serializationVersion > 8) {
lineageStartIndex = in.readLong();
} else {
lineageStartIndex = 0L;
}
ffBuilder.lineageStart(lineageStartDate, lineageStartIndex);
if (serializationVersion > 5) {
// Version 9 adds in a 'queue date index'
final long lastQueueDate = in.readLong();
final long queueDateIndex;
if (serializationVersion > 8) {
queueDateIndex = in.readLong();
} else {
queueDateIndex = 0L;
}
ffBuilder.lastQueued(lastQueueDate, queueDateIndex);
}
}
ffBuilder.size(in.readLong());
if (serializationVersion < 3) {
readString(in); // connection Id
}
final boolean hasClaim = in.readBoolean();
ResourceClaim resourceClaim = null;
if (hasClaim) {
final String claimId;
if (serializationVersion < 5) {
claimId = String.valueOf(in.readLong());
} else {
claimId = in.readUTF();
}
final String container = in.readUTF();
final String section = in.readUTF();
final long resourceOffset;
final long resourceLength;
if (serializationVersion < 6) {
resourceOffset = 0L;
resourceLength = -1L;
} else {
resourceOffset = in.readLong();
resourceLength = in.readLong();
}
final long claimOffset = in.readLong();
final boolean lossTolerant;
if (serializationVersion >= 4) {
lossTolerant = in.readBoolean();
} else {
lossTolerant = false;
}
resourceClaim = claimManager.getResourceClaim(container, section, claimId);
if (resourceClaim == null) {
logger.error("Swap file indicates that FlowFile was referencing Resource Claim at container={}, section={}, claimId={}, "
+ "but this Resource Claim cannot be found! Will create a temporary Resource Claim, but this may affect the framework's "
+ "ability to properly clean up this resource", container, section, claimId);
resourceClaim = claimManager.newResourceClaim(container, section, claimId, lossTolerant, true);
}
final StandardContentClaim claim = new StandardContentClaim(resourceClaim, resourceOffset);
claim.setLength(resourceLength);
ffBuilder.contentClaim(claim);
ffBuilder.contentClaimOffset(claimOffset);
}
boolean attributesChanged = true;
if (serializationVersion < 3) {
attributesChanged = in.readBoolean();
}
if (attributesChanged) {
final int numAttributes = in.readInt();
for (int j = 0; j < numAttributes; j++) {
final String key = readString(in);
final String value = readString(in);
ffBuilder.addAttribute(key, value);
}
}
final FlowFileRecord record = ffBuilder.build();
if (resourceClaim != null) {
resourceClaims.add(resourceClaim);
}
flowFiles.add(record);
} catch (final EOFException eof) {
final SwapSummary swapSummary = new StandardSwapSummary(queueSize, maxId, resourceClaims, 0L, 0L);
final SwapContents partialContents = new StandardSwapContents(swapSummary, flowFiles);
throw new IncompleteSwapFileException(location, partialContents);
}
}
final SwapSummary swapSummary = new StandardSwapSummary(queueSize, maxId, resourceClaims, 0L, 0L);
return new StandardSwapContents(swapSummary, flowFiles);
}
private static String readString(final InputStream in) throws IOException {
final Integer numBytes = readFieldLength(in);
if (numBytes == null) {
throw new EOFException();
}
final byte[] bytes = new byte[numBytes];
fillBuffer(in, bytes, numBytes);
return new String(bytes, StandardCharsets.UTF_8);
}
private static Integer readFieldLength(final InputStream in) throws IOException {
final int firstValue = in.read();
final int secondValue = in.read();
if (firstValue < 0) {
return null;
}
if (secondValue < 0) {
throw new EOFException();
}
if (firstValue == 0xff && secondValue == 0xff) {
final int ch1 = in.read();
final int ch2 = in.read();
final int ch3 = in.read();
final int ch4 = in.read();
if ((ch1 | ch2 | ch3 | ch4) < 0) {
throw new EOFException();
}
return (ch1 << 24) + (ch2 << 16) + (ch3 << 8) + ch4;
} else {
return (firstValue << 8) + secondValue;
}
}
private static void fillBuffer(final InputStream in, final byte[] buffer, final int length) throws IOException {
int bytesRead;
int totalBytesRead = 0;
while ((bytesRead = in.read(buffer, totalBytesRead, length - totalBytesRead)) > 0) {
totalBytesRead += bytesRead;
}
if (totalBytesRead != length) {
throw new EOFException();
}
}
}
| MikeThomsen/nifi | nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/swap/SimpleSwapDeserializer.java | Java | apache-2.0 | 13,651 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/kms/model/KeyManagerType.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace KMS
{
namespace Model
{
namespace KeyManagerTypeMapper
{
static const int AWS_HASH = HashingUtils::HashString("AWS");
static const int CUSTOMER_HASH = HashingUtils::HashString("CUSTOMER");
KeyManagerType GetKeyManagerTypeForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == AWS_HASH)
{
return KeyManagerType::AWS;
}
else if (hashCode == CUSTOMER_HASH)
{
return KeyManagerType::CUSTOMER;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<KeyManagerType>(hashCode);
}
return KeyManagerType::NOT_SET;
}
Aws::String GetNameForKeyManagerType(KeyManagerType enumValue)
{
switch(enumValue)
{
case KeyManagerType::AWS:
return "AWS";
case KeyManagerType::CUSTOMER:
return "CUSTOMER";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace KeyManagerTypeMapper
} // namespace Model
} // namespace KMS
} // namespace Aws
| awslabs/aws-sdk-cpp | aws-cpp-sdk-kms/source/model/KeyManagerType.cpp | C++ | apache-2.0 | 1,933 |
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 25.3.1.3
description: >
When a generator is paused before a `try..catch` statement, `return` should
interrupt control flow as if a `return` statement had appeared at that
location in the function body.
---*/
function* g() {
yield;
try {
$ERROR('This code is unreachable (within `try` block)');
} catch (e) {
throw e;
}
$ERROR('This code is unreachable (following `try` statement)');
}
var iter = g();
var result;
iter.next();
result = iter.return(45);
assert.sameValue(result.value, 45, 'Result `value` following `return`');
assert.sameValue(result.done, true, 'Result `done` flag following `return`');
result = iter.next();
assert.sameValue(result.value,
undefined, 'Result `value` is undefined when complete'
);
assert.sameValue(
result.done, true, 'Result `done` flag is `true` when complete'
);
| m0ppers/arangodb | 3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/GeneratorPrototype/return/try-catch-before-try.js | JavaScript | apache-2.0 | 988 |
/*
* Copyright 2014 CyberVision, 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 org.kaaproject.kaa.common.dto;
import org.kaaproject.avro.ui.shared.RecordField;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties({"schemaForm"})
public abstract class AbstractSchemaDto extends SchemaDto {
private static final long serialVersionUID = 6821310997907855007L;
protected String applicationId;
protected String schema;
protected RecordField schemaForm;
protected String name;
protected String description;
protected String createdUsername;
protected long createdTime;
protected long endpointCount;
public String getApplicationId() {
return applicationId;
}
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
public RecordField getSchemaForm() {
return schemaForm;
}
public void setSchemaForm(RecordField schemaForm) {
this.schemaForm = schemaForm;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCreatedUsername() {
return createdUsername;
}
public void setCreatedUsername(String createdUsername) {
this.createdUsername = createdUsername;
}
public long getCreatedTime() {
return createdTime;
}
public void setCreatedTime(long createdTime) {
this.createdTime = createdTime;
}
public long getEndpointCount() {
return endpointCount;
}
public void setEndpointCount(long endpointCount) {
this.endpointCount = endpointCount;
}
public void editFields(AbstractSchemaDto other) {
this.name = other.name;
this.description = other.description;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof AbstractSchemaDto)) {
return false;
}
AbstractSchemaDto that = (AbstractSchemaDto) o;
if (majorVersion != that.majorVersion) {
return false;
}
if (minorVersion != that.minorVersion) {
return false;
}
if (applicationId != null ? !applicationId.equals(that.applicationId) : that.applicationId != null) {
return false;
}
if (schema != null ? !schema.equals(that.schema) : that.schema != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = applicationId != null ? applicationId.hashCode() : 0;
result = 31 * result + majorVersion;
result = 31 * result + minorVersion;
result = 31 * result + (schema != null ? schema.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "AbstractSchemaDto [id=" + id + ", applicationId="
+ applicationId + ", majorVersion=" + majorVersion
+ ", minorVersion=" + minorVersion
+ ", name=" + name + ", description=" + description
+ ", createdUsername=" + createdUsername + ", createdTime="
+ createdTime + ", endpointCount=" + endpointCount + "]";
}
}
| vzhukovskyi/kaa | server/common/dto/src/main/java/org/kaaproject/kaa/common/dto/AbstractSchemaDto.java | Java | apache-2.0 | 4,172 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.binary.streams;
import org.apache.ignite.internal.util.GridUnsafe;
import static org.apache.ignite.internal.util.GridUnsafe.BIG_ENDIAN;
/**
* Binary heap output stream.
*/
public final class BinaryHeapOutputStream extends BinaryAbstractOutputStream {
/** Allocator. */
private final BinaryMemoryAllocatorChunk chunk;
/** Data. */
private byte[] data;
/**
* Constructor.
*
* @param cap Initial capacity.
*/
public BinaryHeapOutputStream(int cap) {
this(cap, BinaryMemoryAllocator.THREAD_LOCAL.chunk());
}
/**
* Constructor.
*
* @param cap Capacity.
* @param chunk Chunk.
*/
public BinaryHeapOutputStream(int cap, BinaryMemoryAllocatorChunk chunk) {
this.chunk = chunk;
data = chunk.allocate(cap);
}
/** {@inheritDoc} */
@Override public void close() {
chunk.release(data, pos);
}
/** {@inheritDoc} */
@Override public void ensureCapacity(int cnt) {
if (cnt > data.length) {
int newCap = capacity(data.length, cnt);
data = chunk.reallocate(data, newCap);
}
}
/** {@inheritDoc} */
@Override public byte[] array() {
return data;
}
/** {@inheritDoc} */
@Override public byte[] arrayCopy() {
byte[] res = new byte[pos];
System.arraycopy(data, 0, res, 0, pos);
return res;
}
/** {@inheritDoc} */
@Override public boolean hasArray() {
return true;
}
/** {@inheritDoc} */
@Override protected void writeByteAndShift(byte val) {
data[pos++] = val;
}
/** {@inheritDoc} */
@Override protected void copyAndShift(Object src, long off, int len) {
GridUnsafe.copyMemory(src, off, data, GridUnsafe.BYTE_ARR_OFF + pos, len);
shift(len);
}
/** {@inheritDoc} */
@Override protected void writeShortFast(short val) {
long off = GridUnsafe.BYTE_ARR_OFF + pos;
if (BIG_ENDIAN)
GridUnsafe.putShortLE(data, off, val);
else
GridUnsafe.putShort(data, off, val);
}
/** {@inheritDoc} */
@Override protected void writeCharFast(char val) {
long off = GridUnsafe.BYTE_ARR_OFF + pos;
if (BIG_ENDIAN)
GridUnsafe.putCharLE(data, off, val);
else
GridUnsafe.putChar(data, off, val);
}
/** {@inheritDoc} */
@Override protected void writeIntFast(int val) {
long off = GridUnsafe.BYTE_ARR_OFF + pos;
if (BIG_ENDIAN)
GridUnsafe.putIntLE(data, off, val);
else
GridUnsafe.putInt(data, off, val);
}
/** {@inheritDoc} */
@Override protected void writeLongFast(long val) {
long off = GridUnsafe.BYTE_ARR_OFF + pos;
if (BIG_ENDIAN)
GridUnsafe.putLongLE(data, off, val);
else
GridUnsafe.putLong(data, off, val);
}
/** {@inheritDoc} */
@Override public void unsafeWriteByte(byte val) {
GridUnsafe.putByte(data, GridUnsafe.BYTE_ARR_OFF + pos++, val);
}
/** {@inheritDoc} */
@Override public void unsafeWriteShort(short val) {
long off = GridUnsafe.BYTE_ARR_OFF + pos;
if (BIG_ENDIAN)
GridUnsafe.putShortLE(data, off, val);
else
GridUnsafe.putShort(data, off, val);
shift(2);
}
/** {@inheritDoc} */
@Override public void unsafeWriteShort(int pos, short val) {
long off = GridUnsafe.BYTE_ARR_OFF + pos;
if (BIG_ENDIAN)
GridUnsafe.putShortLE(data, off, val);
else
GridUnsafe.putShort(data, off, val);
}
/** {@inheritDoc} */
@Override public void unsafeWriteChar(char val) {
long off = GridUnsafe.BYTE_ARR_OFF + pos;
if (BIG_ENDIAN)
GridUnsafe.putCharLE(data, off, val);
else
GridUnsafe.putChar(data, off, val);
shift(2);
}
/** {@inheritDoc} */
@Override public void unsafeWriteInt(int val) {
long off = GridUnsafe.BYTE_ARR_OFF + pos;
if (BIG_ENDIAN)
GridUnsafe.putIntLE(data, off, val);
else
GridUnsafe.putInt(data, off, val);
shift(4);
}
/** {@inheritDoc} */
@Override public void unsafeWriteInt(int pos, int val) {
long off = GridUnsafe.BYTE_ARR_OFF + pos;
if (BIG_ENDIAN)
GridUnsafe.putIntLE(data, off, val);
else
GridUnsafe.putInt(data, off, val);
}
/** {@inheritDoc} */
@Override public void unsafeWriteLong(long val) {
long off = GridUnsafe.BYTE_ARR_OFF + pos;
if (BIG_ENDIAN)
GridUnsafe.putLongLE(data, off, val);
else
GridUnsafe.putLong(data, off, val);
shift(8);
}
/** {@inheritDoc} */
@Override public int capacity() {
return data.length;
}
}
| samaitra/ignite | modules/core/src/main/java/org/apache/ignite/internal/binary/streams/BinaryHeapOutputStream.java | Java | apache-2.0 | 5,760 |
/*
* Copyright (c) 2011 Yan Pujante
*
* 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.linkedin.glu.orchestration.engine.delta;
/**
* @author yan@pongasoft.com
*/
public interface ValueDelta<T>
{
T getExpectedValue();
T getCurrentValue();
} | qixiaobo/glu | orchestration/org.linkedin.glu.orchestration-engine/src/main/java/org/linkedin/glu/orchestration/engine/delta/ValueDelta.java | Java | apache-2.0 | 768 |
/**
* Copyright 2018 Nikita Koksharov
*
* 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.redisson.spring.data.connection;
import org.redisson.client.protocol.convertor.SingleConvertor;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metric;
/**
*
* @author Nikita Koksharov
*
*/
public class DistanceConvertor extends SingleConvertor<Distance> {
private final Metric metric;
public DistanceConvertor(Metric metric) {
super();
this.metric = metric;
}
@Override
public Distance convert(Object obj) {
return new Distance((Double)obj, metric);
}
}
| jackygurui/redisson | redisson-spring-data/redisson-spring-data-20/src/main/java/org/redisson/spring/data/connection/DistanceConvertor.java | Java | apache-2.0 | 1,164 |
/*
* 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.jena.sparql.algebra;
import org.apache.jena.atlas.junit.BaseTest ;
import org.apache.jena.query.Query ;
import org.apache.jena.query.QueryFactory ;
import org.apache.jena.query.Syntax ;
import org.apache.jena.sparql.algebra.op.OpJoin ;
import org.apache.jena.sparql.algebra.op.OpLeftJoin ;
import org.apache.jena.sparql.engine.main.JoinClassifier ;
import org.apache.jena.sparql.engine.main.LeftJoinClassifier ;
import org.junit.Test ;
public class TestClassify extends BaseTest
{
@Test public void testClassify_Join_01()
{ classifyJ("{?s :p :o . { ?s :p :o FILTER(true) } }", true) ; }
@Test public void testClassify_Join_02()
{ classifyJ("{?s :p :o . { ?s :p :o FILTER(?s) } }", true) ; }
@Test public void testClassify_Join_03()
{ classifyJ("{?s :p :o . { ?s :p ?o FILTER(?o) } }", true) ; }
@Test public void testClassify_Join_04()
{ classifyJ("{?s :p :o . { ?s :p :o FILTER(?o) } }", true) ; }
@Test public void testClassify_Join_05()
{ classifyJ("{?s :p :o . { ?x :p :o FILTER(?s) } }", false) ; }
@Test public void testClassify_Join_06()
{ classifyJ("{ { ?s :p :o FILTER(true) } ?s :p :o }", true) ; }
@Test public void testClassify_Join_07()
{ classifyJ("{ { ?s :p :o FILTER(?s) } ?s :p :o }", true) ; }
@Test public void testClassify_Join_08()
{ classifyJ("{ { ?s :p ?o FILTER(?o) } ?s :p :o }", true) ; }
@Test public void testClassify_Join_09()
{ classifyJ("{ { ?s :p :o FILTER(?o) } ?s :p :o }", true) ; }
// Actually, this is safe IF executed left, then streamed to right.
@Test public void testClassify_Join_10()
{ classifyJ("{ { ?x :p :o FILTER(?s) } ?s :p :o }", true) ; }
// Not safe: ?s
// Other parts of RHS may restrict ?s to things that can't match the LHS.
@Test public void testClassify_Join_11()
{ classifyJ("{?s :p :o . { OPTIONAL { ?s :p :o } } }", false) ; }
// Not safe: ?s
@Test public void testClassify_Join_12()
{ classifyJ("{?s :p :o . { OPTIONAL { ?s :p :o FILTER(?s) } } }", false) ; }
@Test public void testClassify_Join_13()
{ classifyJ("{?s :p :o . { ?x :p :o OPTIONAL { :s :p :o FILTER(?x) } } }", true) ; }
@Test public void testClassify_Join_14()
{ classifyJ("{?s :p :o . { OPTIONAL { :s :p :o FILTER(?o) } } }", true) ; }
@Test public void testClassify_Join_15()
{ classifyJ("{?s :p :o . { OPTIONAL { ?x :p :o FILTER(?s) } } }", false) ; }
@Test public void testClassify_Join_20()
{ classifyJ("{ {?s :p ?x } . { {} OPTIONAL { :s :p ?x } } }", false) ; }
// Assuming left-right execution, this is safe.
@Test public void testClassify_Join_21()
{ classifyJ("{ { {} OPTIONAL { :s :p ?x } } {?s :p ?x } }", true) ; }
@Test public void testClassify_Join_31()
{ classifyJ("{ ?x ?y ?z {SELECT ?s { ?s ?p ?o} } }", true) ; }
// Use of a filter variable not in from the LHS
@Test public void testClassify_Join_32()
{ classifyJ("{ GRAPH ?g { ?x ?y ?z } { FILTER (?a) } }", true) ; }
// Use of a filter variable from the LHS
@Test public void testClassify_Join_33()
{ classifyJ("{ GRAPH ?g { ?x ?y ?z } { FILTER (?z) } }", false) ; }
// Use of a filter variable from the LHS but grounded in RHS
@Test public void testClassify_Join_34()
{ classifyJ("{ GRAPH ?g { ?x ?y ?z } { ?a ?b ?z FILTER (?z) } }", true) ; }
// Use of a filter variable from the LHS but optional in RHS
@Test public void testClassify_Join_35()
{ classifyJ("{ GRAPH ?g { ?x ?y ?z } { OPTIONAL{?a ?b ?z} FILTER (?z) } }", false) ; }
@Test public void testClassify_Join_40()
{ classifyJ("{ ?x ?y ?z { ?x ?y ?z } UNION { ?x1 ?y1 ?z1 }}", true) ; }
@Test public void testClassify_Join_41()
{ classifyJ("{ ?x ?y ?z { ?x1 ?y1 ?z1 BIND(?z+2 AS ?A) } UNION { ?x1 ?y1 ?z1 }}", false) ; }
@Test public void testClassify_Join_42()
{ classifyJ("{ ?x ?y ?z { BIND(?z+2 AS ?A) } UNION { BIND(?z+2 AS ?B) }}", false) ; }
@Test public void testClassify_Join_43()
{ classifyJ("{ ?x ?y ?z { LET(?A := ?z+2) } UNION { }}", false) ; }
@Test public void testClassify_Join_44()
{ classifyJ("{ BIND(<x> AS ?typeX) { BIND(?typeX AS ?type) ?s ?p ?o FILTER(?o=?type) } }", false) ; }
// Unsafe - deep MINUS
// JENA-1021
@Test public void testClassify_Join_50()
{ classifyJ("{ ?x ?y ?z { ?x1 ?y1 ?z1 MINUS { ?a ?b ?c } } UNION {} }", false) ; }
private void classifyJ(String pattern, boolean expected)
{
String qs1 = "PREFIX : <http://example/>\n" ;
String qs = qs1+"SELECT * "+pattern;
Query query = QueryFactory.create(qs, Syntax.syntaxARQ) ;
Op op = Algebra.compile(query.getQueryPattern()) ;
if ( ! ( op instanceof OpJoin ) )
fail("Not a join: "+pattern) ;
boolean nonLinear = JoinClassifier.isLinear((OpJoin)op) ;
assertEquals("Join: "+pattern, expected, nonLinear) ;
}
@Test public void testClassify_LeftJoin_01()
{ classifyLJ("{ ?s ?p ?o OPTIONAL { ?s1 ?p2 ?x} }", true) ; }
@Test public void testClassify_LeftJoin_02()
{ classifyLJ("{ ?s ?p ?o OPTIONAL { ?s1 ?p2 ?o3 OPTIONAL { ?s1 ?p2 ?x} } }", true) ; }
@Test public void testClassify_LeftJoin_03()
{ classifyLJ("{ ?s ?p ?x OPTIONAL { ?s1 ?p2 ?o3 OPTIONAL { ?s1 :p ?o3} } }", true) ; }
@Test public void testClassify_LeftJoin_04()
{ classifyLJ("{ ?s ?p ?x OPTIONAL { ?s1 ?p2 ?o3 OPTIONAL { ?s1 :p ?x} } }", false) ; }
@Test public void testClassify_LeftJoin_05()
{ classifyLJ("{ ?s ?p ?x OPTIONAL { ?s ?p ?x OPTIONAL { ?s ?p ?x } } }", true) ; }
@Test public void testClassify_LeftJoin_06() // Note use of {{ }}
{ classifyLJ("{ ?s ?p ?x OPTIONAL { { ?s ?p ?o FILTER(?x) } } }", false) ; }
@Test public void testClassify_LeftJoin_07()
{ classifyLJ("{ ?s ?p ?x OPTIONAL { ?s ?p ?x1 OPTIONAL { ?s ?p ?x2 FILTER(?x) } } }", false) ; }
// Can't linearize into a projection.
@Test public void testClassify_LeftJoin_10()
{ classifyLJ("{ ?s ?p ?x OPTIONAL { SELECT ?s { ?s ?p ?o } } }", false) ; }
/**
* Can linearize with BIND present provided mentioned vars are also on RHS
*/
@Test public void testClassify_LeftJoin_11()
{ classifyLJ("{ ?s ?p ?x OPTIONAL { ?s1 ?p2 ?x . BIND(?x AS ?test) } }", true) ; }
/**
* Can't linearize with BIND present if any mentioned vars are not on RHS
*/
@Test public void testClassify_LeftJoin_12()
{ classifyLJ("{ ?s ?p ?x OPTIONAL { ?s1 ?p2 ?x . BIND(?s AS ?test) } }", false) ; }
/**
* Can't linearize with BIND present if any mentioned vars are not on RHS
*/
@Test public void testClassify_LeftJoin_13()
{ classifyLJ("{ ?s ?p ?x OPTIONAL { ?s1 ?p2 ?x . BIND(CONCAT(?s, ?x) AS ?test) } }", false) ; }
/**
* Can't linearize with BIND present if any mentioned vars are not on RHS
*/
@Test public void testClassify_LeftJoin_14()
{ classifyLJ("{ ?s ?p ?x OPTIONAL { ?s1 ?p2 ?x . BIND(CONCAT(?s1, ?p1, ?p2, ?x) AS ?test) } }", false) ; }
/**
* Can't linearize with BIND present if any mentioned vars are not fixed on RHS
*/
@Test public void testClassify_LeftJoin_15()
{ classifyLJ("{ ?s ?p ?x OPTIONAL { BIND(?x AS ?test) OPTIONAL { ?x ?p1 ?o1 } } }", false) ; }
/**
* Test left join classification
* @param pattern WHERE clause for the query as a string
* @param expected Whether the join should be classified as linear
*/
private void classifyLJ(String pattern, boolean expected)
{
String qs1 = "PREFIX : <http://example/>\n" ;
String qs = qs1+"SELECT * "+pattern;
Query query = QueryFactory.create(qs, Syntax.syntaxARQ) ;
Op op = Algebra.compile(query.getQueryPattern()) ;
if ( ! ( op instanceof OpLeftJoin ) )
fail("Not a leftjoin: "+pattern) ;
boolean nonLinear = LeftJoinClassifier.isLinear((OpLeftJoin)op) ;
assertEquals("LeftJoin: "+pattern, expected, nonLinear) ;
}
}
| kidaa/jena | jena-arq/src/test/java/org/apache/jena/sparql/algebra/TestClassify.java | Java | apache-2.0 | 8,890 |
package resource
import (
"github.com/docker/infrakit/pkg/spi"
"github.com/docker/infrakit/pkg/types"
)
// InterfaceSpec is the current name and version of the Resource API.
var InterfaceSpec = spi.InterfaceSpec{
Name: "Resource",
Version: "0.1.1",
}
// ID is the unique identifier for a collection of resources.
type ID string
// Spec is a specification of resources to provision.
type Spec struct {
// ID is the unique identifier for the collection of resources.
ID ID
// Properties is the opaque configuration for the resources.
Properties *types.Any
}
// Plugin defines the functions for a Resource plugin.
type Plugin interface {
Commit(spec Spec, pretend bool) (string, error)
Destroy(spec Spec, pretend bool) (string, error)
DescribeResources(spec Spec) (string, error)
}
| kaufers/infrakit | pkg/spi/resource/spi.go | GO | apache-2.0 | 800 |
/*
Copyright 2014 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.
*/
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
/*
GoogleAnalyticsAndroidV4 handles building hits using the Android SDK.
Developers should call the methods in GoogleAnalyticsV4, which will call the
appropriate methods in this class if the application is built for Android.
*/
public class GoogleAnalyticsAndroidV4 : IDisposable {
#if UNITY_ANDROID && !UNITY_EDITOR
private string trackingCode;
private string appVersion;
private string appName;
private string bundleIdentifier;
private int dispatchPeriod;
private int sampleFrequency;
//private GoogleAnalyticsV4.DebugMode logLevel;
private bool anonymizeIP;
private bool adIdCollection;
private bool dryRun;
private int sessionTimeout;
private AndroidJavaObject tracker;
private AndroidJavaObject logger;
private AndroidJavaObject currentActivityObject;
private AndroidJavaObject googleAnalyticsSingleton;
//private bool startSessionOnNextHit = false;
//private bool endSessionOnNextHit = false;
internal void InitializeTracker() {
Debug.Log("Initializing Google Analytics Android Tracker.");
using (AndroidJavaObject googleAnalyticsClass = new AndroidJavaClass("com.google.android.gms.analytics.GoogleAnalytics"))
using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) {
currentActivityObject = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
googleAnalyticsSingleton = googleAnalyticsClass.CallStatic<AndroidJavaObject>("getInstance", currentActivityObject);
tracker = googleAnalyticsSingleton.Call<AndroidJavaObject>("newTracker", trackingCode);
googleAnalyticsSingleton.Call("setLocalDispatchPeriod", dispatchPeriod);
googleAnalyticsSingleton.Call("setDryRun", dryRun);
tracker.Call("setSampleRate", (double)sampleFrequency);
tracker.Call("setAppName", appName);
tracker.Call("setAppId", bundleIdentifier);
tracker.Call("setAppVersion", appVersion);
tracker.Call("setAnonymizeIp", anonymizeIP);
tracker.Call("enableAdvertisingIdCollection", adIdCollection);
}
}
internal void SetTrackerVal(Field fieldName, object value) {
object[] args = new object[] { fieldName.ToString(), value };
tracker.Call("set", args);
}
private void SetSessionOnBuilder(AndroidJavaObject hitBuilder) {
}
internal void StartSession() {
//startSessionOnNextHit = true;
}
internal void StopSession() {
//endSessionOnNextHit = true;
}
public void SetOptOut(bool optOut) {
googleAnalyticsSingleton.Call("setAppOptOut", optOut);
}
internal void LogScreen (AppViewHitBuilder builder) {
tracker.Call("setScreenName", builder.GetScreenName());
AndroidJavaObject eventBuilder = new AndroidJavaObject("com.google.android.gms.analytics.HitBuilders$ScreenViewBuilder");
object[] builtScreenView = new object[] { eventBuilder.Call<AndroidJavaObject>("build") };
tracker.Call("send", builtScreenView);
}
internal void LogEvent(EventHitBuilder builder) {
AndroidJavaObject eventBuilder = new AndroidJavaObject("com.google.android.gms.analytics.HitBuilders$EventBuilder");
eventBuilder.Call<AndroidJavaObject>("setCategory", new object[] { builder.GetEventCategory() });
eventBuilder.Call<AndroidJavaObject>("setAction", new object[] { builder.GetEventAction() });
eventBuilder.Call<AndroidJavaObject>("setLabel", new object[] { builder.GetEventLabel() });
eventBuilder.Call<AndroidJavaObject>("setValue", new object[] { builder.GetEventValue() });
object[] builtEvent = new object[] { eventBuilder.Call<AndroidJavaObject>("build") };
tracker.Call("send", builtEvent);
}
internal void LogTransaction(TransactionHitBuilder builder) {
}
internal void LogItem(ItemHitBuilder builder) {
}
public void LogException(ExceptionHitBuilder builder) {
}
public void LogSocial(SocialHitBuilder builder) {
}
public void LogTiming(TimingHitBuilder builder) {
}
public void DispatchHits() {
}
public void SetSampleFrequency(int sampleFrequency) {
this.sampleFrequency = sampleFrequency;
}
public void ClearUserIDOverride() {
SetTrackerVal(Fields.USER_ID, null);
}
public void SetTrackingCode(string trackingCode) {
this.trackingCode = trackingCode;
}
public void SetAppName(string appName) {
this.appName = appName;
}
public void SetBundleIdentifier(string bundleIdentifier) {
this.bundleIdentifier = bundleIdentifier;
}
public void SetAppVersion(string appVersion) {
this.appVersion = appVersion;
}
public void SetDispatchPeriod(int dispatchPeriod) {
this.dispatchPeriod = dispatchPeriod;
}
public void SetLogLevelValue(GoogleAnalyticsV4.DebugMode logLevel) {
//this.logLevel = logLevel;
}
public void SetAnonymizeIP(bool anonymizeIP) {
this.anonymizeIP = anonymizeIP;
}
public void SetAdIdCollection(bool adIdCollection) {
this.adIdCollection = adIdCollection;
}
public void SetDryRun(bool dryRun) {
this.dryRun = dryRun;
}
#endif
public void Dispose() {
#if UNITY_ANDROID && !UNITY_EDITOR
googleAnalyticsSingleton.Dispose();
tracker.Dispose();
#endif
}
}
| shazow/google-analytics-plugin-for-unity | source/Plugins/GoogleAnalyticsV4/GoogleAnalyticsAndroidV4.cs | C# | apache-2.0 | 5,829 |
/*
* Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
*
* This file is part of the SeaGlass Pluggable Look and Feel.
*
* 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.
*
* $Id$
*/
package com.seaglasslookandfeel.painter;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import javax.swing.JComponent;
import com.seaglasslookandfeel.painter.AbstractRegionPainter.PaintContext.CacheMode;
/**
* ContentPanePainter implementation.
*/
public class ContentPanePainter extends AbstractRegionPainter {
/**
* DOCUMENT ME!
*
* @author $author$
* @version $Revision$, $Date$
*/
public static enum Which {
BACKGROUND_ENABLED, BACKGROUND_ENABLED_WINDOWFOCUSED,
}
private TwoColors rootPaneActive = new TwoColors(decodeColor("seaGlassToolBarActiveTopT"),
decodeColor("seaGlassToolBarActiveBottomB"));
private TwoColors rootPaneInactive = new TwoColors(decodeColor("seaGlassToolBarInactiveTopT"),
decodeColor("seaGlassToolBarInactiveBottomB"));
private Which state;
private PaintContext ctx;
/**
* Creates a new ContentPanePainter object.
*
* @param state DOCUMENT ME!
*/
public ContentPanePainter(Which state) {
super();
this.state = state;
this.ctx = new PaintContext(CacheMode.NO_CACHING);
}
/**
* @see com.seaglasslookandfeel.painter.AbstractRegionPainter#doPaint(java.awt.Graphics2D,
* javax.swing.JComponent, int, int, java.lang.Object[])
*/
protected void doPaint(Graphics2D g, JComponent c, int width, int height, Object[] extendedCacheKeys) {
Shape s = shapeGenerator.createRectangle(0, 0, width, height);
g.setPaint(getRootPaneInteriorPaint(s, state));
g.fill(s);
}
/**
* @see com.seaglasslookandfeel.painter.AbstractRegionPainter#getPaintContext()
*/
protected PaintContext getPaintContext() {
return ctx;
}
/**
* DOCUMENT ME!
*
* @param type DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private TwoColors getRootPaneInteriorColors(Which type) {
switch (type) {
case BACKGROUND_ENABLED_WINDOWFOCUSED:
return rootPaneActive;
case BACKGROUND_ENABLED:
return rootPaneInactive;
}
return null;
}
/**
* DOCUMENT ME!
*
* @param s DOCUMENT ME!
* @param type DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public Paint getRootPaneInteriorPaint(Shape s, Which type) {
return createVerticalGradient(s, getRootPaneInteriorColors(type));
}
}
| khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/painter/ContentPanePainter.java | Java | apache-2.0 | 3,267 |
/*
* 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.asterix.runtime.job.listener;
import org.apache.asterix.common.api.IJobEventListenerFactory;
import org.apache.asterix.common.api.INcApplicationContext;
import org.apache.asterix.common.exceptions.ACIDException;
import org.apache.asterix.common.transactions.ITransactionContext;
import org.apache.asterix.common.transactions.ITransactionManager;
import org.apache.asterix.common.transactions.ITransactionManager.AtomicityLevel;
import org.apache.asterix.common.transactions.TransactionOptions;
import org.apache.asterix.common.transactions.TxnId;
import org.apache.hyracks.api.context.IHyracksJobletContext;
import org.apache.hyracks.api.job.IJobletEventListener;
import org.apache.hyracks.api.job.IJobletEventListenerFactory;
import org.apache.hyracks.api.job.JobParameterByteStore;
import org.apache.hyracks.api.job.JobStatus;
public class JobEventListenerFactory implements IJobEventListenerFactory {
private static final long serialVersionUID = 1L;
private TxnId txnId;
private final boolean transactionalWrite;
//To enable new Asterix TxnId for separate deployed job spec invocations
private static final byte[] TRANSACTION_ID_PARAMETER_NAME = "TxnIdParameter".getBytes();
public JobEventListenerFactory(TxnId txnId, boolean transactionalWrite) {
this.txnId = txnId;
this.transactionalWrite = transactionalWrite;
}
@Override
public TxnId getTxnId(int datasetId) {
return txnId;
}
@Override
public IJobletEventListenerFactory copyFactory() {
return new JobEventListenerFactory(txnId, transactionalWrite);
}
@Override
public void updateListenerJobParameters(JobParameterByteStore jobParameterByteStore) {
String AsterixTransactionIdString = new String(jobParameterByteStore
.getParameterValue(TRANSACTION_ID_PARAMETER_NAME, 0, TRANSACTION_ID_PARAMETER_NAME.length));
if (AsterixTransactionIdString.length() > 0) {
this.txnId = new TxnId(Integer.parseInt(AsterixTransactionIdString));
}
}
@Override
public IJobletEventListener createListener(final IHyracksJobletContext jobletContext) {
return new IJobletEventListener() {
@Override
public void jobletFinish(JobStatus jobStatus) {
try {
ITransactionManager txnManager =
((INcApplicationContext) jobletContext.getServiceContext().getApplicationContext())
.getTransactionSubsystem().getTransactionManager();
ITransactionContext txnContext = txnManager.getTransactionContext(txnId);
txnContext.setWriteTxn(transactionalWrite);
if (jobStatus != JobStatus.FAILURE) {
txnManager.commitTransaction(txnId);
} else {
txnManager.abortTransaction(txnId);
}
} catch (ACIDException e) {
throw new Error(e);
}
}
@Override
public void jobletStart() {
try {
TransactionOptions options = new TransactionOptions(AtomicityLevel.ENTITY_LEVEL);
((INcApplicationContext) jobletContext.getServiceContext().getApplicationContext())
.getTransactionSubsystem().getTransactionManager().beginTransaction(txnId, options);
} catch (ACIDException e) {
throw new Error(e);
}
}
};
}
}
| ecarm002/incubator-asterixdb | asterixdb/asterix-runtime/src/main/java/org/apache/asterix/runtime/job/listener/JobEventListenerFactory.java | Java | apache-2.0 | 4,428 |
// Copyright (C) 2009 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.google.gerrit.sshd.commands;
import com.google.gerrit.common.ChangeHookRunner;
import com.google.gerrit.common.data.ApprovalType;
import com.google.gerrit.common.data.ApprovalTypes;
import com.google.gerrit.common.data.SubmitRecord;
import com.google.gerrit.reviewdb.ApprovalCategory;
import com.google.gerrit.reviewdb.ApprovalCategoryValue;
import com.google.gerrit.reviewdb.Branch;
import com.google.gerrit.reviewdb.Change;
import com.google.gerrit.reviewdb.PatchSet;
import com.google.gerrit.reviewdb.PatchSetApproval;
import com.google.gerrit.reviewdb.RevId;
import com.google.gerrit.reviewdb.ReviewDb;
import com.google.gerrit.server.ChangeUtil;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.git.MergeOp;
import com.google.gerrit.server.git.MergeQueue;
import com.google.gerrit.server.mail.AbandonedSender;
import com.google.gerrit.server.mail.EmailException;
import com.google.gerrit.server.mail.RestoredSender;
import com.google.gerrit.server.patch.PublishComments;
import com.google.gerrit.server.project.ChangeControl;
import com.google.gerrit.server.project.InvalidChangeOperationException;
import com.google.gerrit.server.project.NoSuchChangeException;
import com.google.gerrit.server.project.ProjectControl;
import com.google.gerrit.server.workflow.FunctionState;
import com.google.gerrit.sshd.BaseCommand;
import com.google.gerrit.util.cli.CmdLineParser;
import com.google.gwtorm.client.OrmException;
import com.google.gwtorm.client.ResultSet;
import com.google.inject.Inject;
import org.apache.sshd.server.Environment;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class ReviewCommand extends BaseCommand {
private static final Logger log =
LoggerFactory.getLogger(ReviewCommand.class);
@Override
protected final CmdLineParser newCmdLineParser() {
final CmdLineParser parser = super.newCmdLineParser();
for (ApproveOption c : optionList) {
parser.addOption(c, c);
}
return parser;
}
private final Set<PatchSet.Id> patchSetIds = new HashSet<PatchSet.Id>();
@Argument(index = 0, required = true, multiValued = true, metaVar = "{COMMIT | CHANGE,PATCHSET}", usage = "patch to review")
void addPatchSetId(final String token) {
try {
patchSetIds.addAll(parsePatchSetId(token));
} catch (UnloggedFailure e) {
throw new IllegalArgumentException(e.getMessage(), e);
} catch (OrmException e) {
throw new IllegalArgumentException("database error", e);
}
}
@Option(name = "--project", aliases = "-p", usage = "project containing the patch set")
private ProjectControl projectControl;
@Option(name = "--message", aliases = "-m", usage = "cover message to publish on change", metaVar = "MESSAGE")
private String changeComment;
@Option(name = "--abandon", usage = "abandon the patch set")
private boolean abandonChange;
@Option(name = "--restore", usage = "restore an abandoned the patch set")
private boolean restoreChange;
@Option(name = "--submit", aliases = "-s", usage = "submit the patch set")
private boolean submitChange;
@Inject
private ReviewDb db;
@Inject
private IdentifiedUser currentUser;
@Inject
private MergeQueue merger;
@Inject
private MergeOp.Factory opFactory;
@Inject
private ApprovalTypes approvalTypes;
@Inject
private ChangeControl.Factory changeControlFactory;
@Inject
private AbandonedSender.Factory abandonedSenderFactory;
@Inject
private FunctionState.Factory functionStateFactory;
@Inject
private PublishComments.Factory publishCommentsFactory;
@Inject
private RestoredSender.Factory restoredSenderFactory;
@Inject
private ChangeHookRunner hooks;
private List<ApproveOption> optionList;
private Set<PatchSet.Id> toSubmit = new HashSet<PatchSet.Id>();
@Override
public final void start(final Environment env) {
startThread(new CommandRunnable() {
@Override
public void run() throws Failure {
initOptionList();
parseCommandLine();
if (abandonChange) {
if (restoreChange) {
throw error("abandon and restore actions are mutually exclusive");
}
if (submitChange) {
throw error("abandon and submit actions are mutually exclusive");
}
}
boolean ok = true;
for (final PatchSet.Id patchSetId : patchSetIds) {
try {
approveOne(patchSetId);
} catch (UnloggedFailure e) {
ok = false;
writeError("error: " + e.getMessage() + "\n");
} catch (Exception e) {
ok = false;
writeError("fatal: internal server error while approving "
+ patchSetId + "\n");
log.error("internal error while approving " + patchSetId, e);
}
}
if (!ok) {
throw new UnloggedFailure(1, "one or more approvals failed;"
+ " review output above");
}
if (!toSubmit.isEmpty()) {
final Set<Branch.NameKey> toMerge = new HashSet<Branch.NameKey>();
try {
for (PatchSet.Id patchSetId : toSubmit) {
ChangeUtil.submit(patchSetId, currentUser, db, opFactory,
new MergeQueue() {
@Override
public void merge(MergeOp.Factory mof, Branch.NameKey branch) {
toMerge.add(branch);
}
@Override
public void schedule(Branch.NameKey branch) {
toMerge.add(branch);
}
@Override
public void recheckAfter(Branch.NameKey branch, long delay,
TimeUnit delayUnit) {
toMerge.add(branch);
}
});
}
for (Branch.NameKey branch : toMerge) {
merger.merge(opFactory, branch);
}
} catch (OrmException updateError) {
throw new Failure(1, "one or more submits failed", updateError);
}
}
}
});
}
private void approveOne(final PatchSet.Id patchSetId) throws
NoSuchChangeException, OrmException, EmailException, Failure {
final Change.Id changeId = patchSetId.getParentKey();
ChangeControl changeControl = changeControlFactory.validateFor(changeId);
if (changeComment == null) {
changeComment = "";
}
Set<ApprovalCategoryValue.Id> aps = new HashSet<ApprovalCategoryValue.Id>();
for (ApproveOption ao : optionList) {
Short v = ao.value();
if (v != null) {
assertScoreIsAllowed(patchSetId, changeControl, ao, v);
aps.add(new ApprovalCategoryValue.Id(ao.getCategoryId(), v));
}
}
try {
publishCommentsFactory.create(patchSetId, changeComment, aps).call();
if (abandonChange) {
if (changeControl.canAbandon()) {
ChangeUtil.abandon(patchSetId, currentUser, changeComment, db,
abandonedSenderFactory, hooks);
} else {
throw error("Not permitted to abandon change");
}
}
if (restoreChange) {
if (changeControl.canRestore()) {
ChangeUtil.restore(patchSetId, currentUser, changeComment, db,
restoredSenderFactory, hooks);
} else {
throw error("Not permitted to restore change");
}
if (submitChange) {
changeControl = changeControlFactory.validateFor(changeId);
}
}
} catch (InvalidChangeOperationException e) {
throw error(e.getMessage());
}
if (submitChange) {
List<SubmitRecord> result = changeControl.canSubmit(db, patchSetId);
if (result.isEmpty()) {
throw new Failure(1, "ChangeControl.canSubmit returned empty list");
}
switch (result.get(0).status) {
case OK:
if (changeControl.getRefControl().canSubmit()) {
toSubmit.add(patchSetId);
} else {
throw error("change " + changeId + ": you do not have submit permission");
}
break;
case NOT_READY: {
StringBuilder msg = new StringBuilder();
for (SubmitRecord.Label lbl : result.get(0).labels) {
switch (lbl.status) {
case OK:
break;
case REJECT:
if (msg.length() > 0) msg.append("\n");
msg.append("change " + changeId + ": blocked by " + lbl.label);
break;
case NEED:
if (msg.length() > 0) msg.append("\n");
msg.append("change " + changeId + ": needs " + lbl.label);
break;
case IMPOSSIBLE:
if (msg.length() > 0) msg.append("\n");
msg.append("change " + changeId + ": needs " + lbl.label
+ " (check project access)");
break;
default:
throw new Failure(1, "Unsupported label status " + lbl.status);
}
}
throw error(msg.toString());
}
case CLOSED:
throw error("change " + changeId + " is closed");
case RULE_ERROR:
if (result.get(0).errorMessage != null) {
throw error("change " + changeId + ": " + result.get(0).errorMessage);
} else {
throw error("change " + changeId + ": internal rule error");
}
default:
throw new Failure(1, "Unsupported status " + result.get(0).status);
}
}
}
private Set<PatchSet.Id> parsePatchSetId(final String patchIdentity)
throws UnloggedFailure, OrmException {
// By commit?
//
if (patchIdentity.matches("^([0-9a-fA-F]{4," + RevId.LEN + "})$")) {
final RevId id = new RevId(patchIdentity);
final ResultSet<PatchSet> patches;
if (id.isComplete()) {
patches = db.patchSets().byRevision(id);
} else {
patches = db.patchSets().byRevisionRange(id, id.max());
}
final Set<PatchSet.Id> matches = new HashSet<PatchSet.Id>();
for (final PatchSet ps : patches) {
final Change change = db.changes().get(ps.getId().getParentKey());
if (inProject(change)) {
matches.add(ps.getId());
}
}
switch (matches.size()) {
case 1:
return matches;
case 0:
throw error("\"" + patchIdentity + "\" no such patch set");
default:
throw error("\"" + patchIdentity + "\" matches multiple patch sets");
}
}
// By older style change,patchset?
//
if (patchIdentity.matches("^[1-9][0-9]*,[1-9][0-9]*$")) {
final PatchSet.Id patchSetId;
try {
patchSetId = PatchSet.Id.parse(patchIdentity);
} catch (IllegalArgumentException e) {
throw error("\"" + patchIdentity + "\" is not a valid patch set");
}
if (db.patchSets().get(patchSetId) == null) {
throw error("\"" + patchIdentity + "\" no such patch set");
}
if (projectControl != null) {
final Change change = db.changes().get(patchSetId.getParentKey());
if (!inProject(change)) {
throw error("change " + change.getId() + " not in project "
+ projectControl.getProject().getName());
}
}
return Collections.singleton(patchSetId);
}
throw error("\"" + patchIdentity + "\" is not a valid patch set");
}
private boolean inProject(final Change change) {
if (projectControl == null) {
// No --project option, so they want every project.
return true;
}
return projectControl.getProject().getNameKey().equals(change.getProject());
}
private void assertScoreIsAllowed(final PatchSet.Id patchSetId,
final ChangeControl changeControl, ApproveOption ao, Short v)
throws UnloggedFailure {
final PatchSetApproval psa =
new PatchSetApproval(new PatchSetApproval.Key(patchSetId, currentUser
.getAccountId(), ao.getCategoryId()), v);
final FunctionState fs =
functionStateFactory.create(changeControl, patchSetId,
Collections.<PatchSetApproval> emptyList());
psa.setValue(v);
fs.normalize(approvalTypes.byId(psa.getCategoryId()), psa);
if (v != psa.getValue()) {
throw error(ao.name() + "=" + ao.value() + " not permitted");
}
}
private void initOptionList() {
optionList = new ArrayList<ApproveOption>();
for (ApprovalType type : approvalTypes.getApprovalTypes()) {
String usage = "";
final ApprovalCategory category = type.getCategory();
usage = "score for " + category.getName() + "\n";
for (ApprovalCategoryValue v : type.getValues()) {
usage += v.format() + "\n";
}
final String name =
"--" + category.getName().toLowerCase().replace(' ', '-');
optionList.add(new ApproveOption(name, usage, type));
}
}
private void writeError(final String msg) {
try {
err.write(msg.getBytes(ENC));
} catch (IOException e) {
}
}
private static UnloggedFailure error(final String msg) {
return new UnloggedFailure(1, msg);
}
}
| cjh1/gerrit | gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/ReviewCommand.java | Java | apache-2.0 | 14,120 |
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.restassured.module.mockmvc.http;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
public class HeaderController {
@RequestMapping(value = "/header", method = GET, produces = APPLICATION_JSON_VALUE)
public @ResponseBody String header(@RequestHeader("headerName") String headerValue,
@RequestHeader(value = "User-Agent", required = false) String userAgent) {
return "{\"headerName\" : \""+headerValue+"\", \"user-agent\" : \""+userAgent+"\"}";
}
}
| paweld2/rest-assured | modules/spring-mock-mvc/src/test/java/io/restassured/module/mockmvc/http/HeaderController.java | Java | apache-2.0 | 1,422 |
# Copyright 2014 Juniper Networks. 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.
#
# @author: Hampapur Ajay, Praneet Bachheti, Rudra Rugge, Atul Moghe
from oslo.config import cfg
import requests
from neutron.api.v2 import attributes as attr
from neutron.common import exceptions as exc
from neutron.db import portbindings_base
from neutron.db import quota_db # noqa
from neutron.extensions import external_net
from neutron.extensions import portbindings
from neutron.extensions import securitygroup
from neutron import neutron_plugin_base_v2
from neutron.openstack.common import importutils
from neutron.openstack.common import jsonutils as json
from neutron.openstack.common import log as logging
from simplejson import JSONDecodeError
LOG = logging.getLogger(__name__)
vnc_opts = [
cfg.StrOpt('api_server_ip', default='127.0.0.1',
help='IP address to connect to VNC controller'),
cfg.StrOpt('api_server_port', default='8082',
help='Port to connect to VNC controller'),
cfg.DictOpt('contrail_extensions', default={},
help='Enable Contrail extensions(policy, ipam)'),
]
# ContrailError message have translated already.
# so there is no need to use i18n here.
class ContrailNotFoundError(exc.NotFound):
message = '%(msg)s'
class ContrailConflictError(exc.Conflict):
message = '%(msg)s'
class ContrailBadRequestError(exc.BadRequest):
message = '%(msg)s'
class ContrailServiceUnavailableError(exc.ServiceUnavailable):
message = '%(msg)s'
class ContrailNotAuthorizedError(exc.NotAuthorized):
message = '%(msg)s'
class InvalidContrailExtensionError(exc.ServiceUnavailable):
message = _("Invalid Contrail Extension: %(ext_name) %(ext_class)")
CONTRAIL_EXCEPTION_MAP = {
requests.codes.not_found: ContrailNotFoundError,
requests.codes.conflict: ContrailConflictError,
requests.codes.bad_request: ContrailBadRequestError,
requests.codes.service_unavailable: ContrailServiceUnavailableError,
requests.codes.unauthorized: ContrailNotAuthorizedError,
requests.codes.request_timeout: ContrailServiceUnavailableError,
}
class NeutronPluginContrailCoreV2(neutron_plugin_base_v2.NeutronPluginBaseV2,
securitygroup.SecurityGroupPluginBase,
portbindings_base.PortBindingBaseMixin,
external_net.External_net):
supported_extension_aliases = ["security-group", "router",
"port-security", "binding", "agent",
"quotas", "external-net",
"allowed-address-pairs", "extra_dhcp_opt"]
PLUGIN_URL_PREFIX = '/neutron'
__native_bulk_support = False
# patch VIF_TYPES
portbindings.__dict__['VIF_TYPE_VROUTER'] = 'vrouter'
portbindings.VIF_TYPES.append(portbindings.VIF_TYPE_VROUTER)
def _parse_class_args(self):
"""Parse the contrailplugin.ini file.
Opencontrail supports extension such as ipam, policy, these extensions
can be configured in the plugin configuration file as shown below.
Plugin then loads the specified extensions.
contrail_extensions=ipam:<classpath>,policy:<classpath>
"""
contrail_extensions = cfg.CONF.APISERVER.contrail_extensions
# If multiple class specified for same extension, last one will win
# according to DictOpt behavior
for ext_name, ext_class in contrail_extensions.items():
try:
if not ext_class:
LOG.error(_('Malformed contrail extension...'))
continue
self.supported_extension_aliases.append(ext_name)
ext_class = importutils.import_class(ext_class)
ext_instance = ext_class()
ext_instance.set_core(self)
for method in dir(ext_instance):
for prefix in ['get', 'update', 'delete', 'create']:
if method.startswith('%s_' % prefix):
setattr(self, method,
ext_instance.__getattribute__(method))
except Exception:
LOG.exception(_("Contrail Backend Error"))
# Converting contrail backend error to Neutron Exception
raise InvalidContrailExtensionError(
ext_name=ext_name, ext_class=ext_class)
#keystone
self._authn_token = None
if cfg.CONF.auth_strategy == 'keystone':
kcfg = cfg.CONF.keystone_authtoken
body = '{"auth":{"passwordCredentials":{'
body += ' "username": "%s",' % (kcfg.admin_user)
body += ' "password": "%s"},' % (kcfg.admin_password)
body += ' "tenantName":"%s"}}' % (kcfg.admin_tenant_name)
self._authn_body = body
self._authn_token = cfg.CONF.keystone_authtoken.admin_token
self._keystone_url = "%s://%s:%s%s" % (
cfg.CONF.keystone_authtoken.auth_protocol,
cfg.CONF.keystone_authtoken.auth_host,
cfg.CONF.keystone_authtoken.auth_port,
"/v2.0/tokens")
def __init__(self):
super(NeutronPluginContrailCoreV2, self).__init__()
portbindings_base.register_port_dict_function()
cfg.CONF.register_opts(vnc_opts, 'APISERVER')
self._parse_class_args()
def _get_base_binding_dict(self):
binding = {
portbindings.VIF_TYPE: portbindings.VIF_TYPE_VROUTER,
portbindings.VIF_DETAILS: {
# TODO(praneetb): Replace with new VIF security details
portbindings.CAP_PORT_FILTER:
'security-group' in self.supported_extension_aliases
}
}
return binding
def get_agents(self, context, filters=None, fields=None):
# This method is implemented so that horizon is happy
return []
def _request_api_server(self, url, data=None, headers=None):
# Attempt to post to Api-Server
response = requests.post(url, data=data, headers=headers)
if (response.status_code == requests.codes.unauthorized):
# Get token from keystone and save it for next request
response = requests.post(self._keystone_url,
data=self._authn_body,
headers={'Content-type': 'application/json'})
if (response.status_code == requests.codes.ok):
# plan is to re-issue original request with new token
auth_headers = headers or {}
authn_content = json.loads(response.text)
self._authn_token = authn_content['access']['token']['id']
auth_headers['X-AUTH-TOKEN'] = self._authn_token
response = self._request_api_server(url, data, auth_headers)
else:
raise RuntimeError('Authentication Failure')
return response
def _request_api_server_authn(self, url, data=None, headers=None):
authn_headers = headers or {}
if self._authn_token is not None:
authn_headers['X-AUTH-TOKEN'] = self._authn_token
response = self._request_api_server(url, data, headers=authn_headers)
return response
def _relay_request(self, url_path, data=None):
"""Send received request to api server."""
url = "http://%s:%s%s" % (cfg.CONF.APISERVER.api_server_ip,
cfg.CONF.APISERVER.api_server_port,
url_path)
return self._request_api_server_authn(
url, data=data, headers={'Content-type': 'application/json'})
def _request_backend(self, context, data_dict, obj_name, action):
context_dict = self._encode_context(context, action, obj_name)
data = json.dumps({'context': context_dict, 'data': data_dict})
url_path = "%s/%s" % (self.PLUGIN_URL_PREFIX, obj_name)
response = self._relay_request(url_path, data=data)
try:
return response.status_code, response.json()
except JSONDecodeError:
return response.status_code, response.content
def _encode_context(self, context, operation, apitype):
cdict = {'user_id': getattr(context, 'user_id', ''),
'is_admin': getattr(context, 'is_admin', False),
'operation': operation,
'type': apitype,
'tenant_id': getattr(context, 'tenant_id', None)}
if context.roles:
cdict['roles'] = context.roles
if context.tenant:
cdict['tenant'] = context.tenant
return cdict
def _encode_resource(self, resource_id=None, resource=None, fields=None,
filters=None):
resource_dict = {}
if resource_id:
resource_dict['id'] = resource_id
if resource:
resource_dict['resource'] = resource
resource_dict['filters'] = filters
resource_dict['fields'] = fields
return resource_dict
def _prune(self, resource_dict, fields):
if fields:
return dict(((key, item) for key, item in resource_dict.items()
if key in fields))
return resource_dict
def _transform_response(self, status_code, info=None, obj_name=None,
fields=None):
if status_code == requests.codes.ok:
if not isinstance(info, list):
return self._prune(info, fields)
else:
return [self._prune(items, fields) for items in info]
self._raise_contrail_error(status_code, info, obj_name)
def _raise_contrail_error(self, status_code, info, obj_name):
if status_code == requests.codes.bad_request:
raise ContrailBadRequestError(
msg=info['message'], resource=obj_name)
error_class = CONTRAIL_EXCEPTION_MAP[status_code]
raise error_class(msg=info['message'])
def _create_resource(self, res_type, context, res_data):
"""Create a resource in API server.
This method encodes neutron model, and sends it to the
contrail api server.
"""
for key, value in res_data[res_type].items():
if value == attr.ATTR_NOT_SPECIFIED:
del res_data[res_type][key]
res_dict = self._encode_resource(resource=res_data[res_type])
status_code, res_info = self._request_backend(context, res_dict,
res_type, 'CREATE')
res_dicts = self._transform_response(status_code, info=res_info,
obj_name=res_type)
LOG.debug("create_%(res_type)s(): %(res_dicts)s",
{'res_type': res_type, 'res_dicts': res_dicts})
return res_dicts
def _get_resource(self, res_type, context, id, fields):
"""Get a resource from API server.
This method gets a resource from the contrail api server
"""
res_dict = self._encode_resource(resource_id=id, fields=fields)
status_code, res_info = self._request_backend(context, res_dict,
res_type, 'READ')
res_dicts = self._transform_response(status_code, info=res_info,
fields=fields, obj_name=res_type)
LOG.debug("get_%(res_type)s(): %(res_dicts)s",
{'res_type': res_type, 'res_dicts': res_dicts})
return res_dicts
def _update_resource(self, res_type, context, id, res_data):
"""Update a resource in API server.
This method updates a resource in the contrail api server
"""
res_dict = self._encode_resource(resource_id=id,
resource=res_data[res_type])
status_code, res_info = self._request_backend(context, res_dict,
res_type, 'UPDATE')
res_dicts = self._transform_response(status_code, info=res_info,
obj_name=res_type)
LOG.debug("update_%(res_type)s(): %(res_dicts)s",
{'res_type': res_type, 'res_dicts': res_dicts})
return res_dicts
def _delete_resource(self, res_type, context, id):
"""Delete a resource in API server
This method deletes a resource in the contrail api server
"""
res_dict = self._encode_resource(resource_id=id)
LOG.debug("delete_%(res_type)s(): %(id)s",
{'res_type': res_type, 'id': id})
status_code, res_info = self._request_backend(context, res_dict,
res_type, 'DELETE')
if status_code != requests.codes.ok:
self._raise_contrail_error(status_code, info=res_info,
obj_name=res_type)
def _list_resource(self, res_type, context, filters, fields):
res_dict = self._encode_resource(filters=filters, fields=fields)
status_code, res_info = self._request_backend(context, res_dict,
res_type, 'READALL')
res_dicts = self._transform_response(status_code, info=res_info,
fields=fields, obj_name=res_type)
LOG.debug(
"get_%(res_type)s(): filters: %(filters)r data: %(res_dicts)r",
{'res_type': res_type, 'filters': filters,
'res_dicts': res_dicts})
return res_dicts
def _count_resource(self, res_type, context, filters):
res_dict = self._encode_resource(filters=filters)
status_code, res_count = self._request_backend(context, res_dict,
res_type, 'READCOUNT')
LOG.debug("get_%(res_type)s_count(): %(res_count)r",
{'res_type': res_type, 'res_count': res_count})
return res_count
def _get_network(self, context, id, fields=None):
return self._get_resource('network', context, id, fields)
def create_network(self, context, network):
"""Creates a new Virtual Network."""
return self._create_resource('network', context, network)
def get_network(self, context, network_id, fields=None):
"""Get the attributes of a particular Virtual Network."""
return self._get_network(context, network_id, fields)
def update_network(self, context, network_id, network):
"""Updates the attributes of a particular Virtual Network."""
return self._update_resource('network', context, network_id,
network)
def delete_network(self, context, network_id):
"""Creates a new Virtual Network.
Deletes the network with the specified network identifier
belonging to the specified tenant.
"""
self._delete_resource('network', context, network_id)
def get_networks(self, context, filters=None, fields=None):
"""Get the list of Virtual Networks."""
return self._list_resource('network', context, filters,
fields)
def get_networks_count(self, context, filters=None):
"""Get the count of Virtual Network."""
networks_count = self._count_resource('network', context, filters)
return networks_count['count']
def create_subnet(self, context, subnet):
"""Creates a new subnet, and assigns it a symbolic name."""
if subnet['subnet']['gateway_ip'] is None:
subnet['subnet']['gateway_ip'] = '0.0.0.0'
if subnet['subnet']['host_routes'] != attr.ATTR_NOT_SPECIFIED:
if (len(subnet['subnet']['host_routes']) >
cfg.CONF.max_subnet_host_routes):
raise exc.HostRoutesExhausted(subnet_id=subnet[
'subnet'].get('id', _('new subnet')),
quota=cfg.CONF.max_subnet_host_routes)
subnet_created = self._create_resource('subnet', context, subnet)
return self._make_subnet_dict(subnet_created)
def _make_subnet_dict(self, subnet):
if 'gateway_ip' in subnet and subnet['gateway_ip'] == '0.0.0.0':
subnet['gateway_ip'] = None
return subnet
def _get_subnet(self, context, subnet_id, fields=None):
subnet = self._get_resource('subnet', context, subnet_id, fields)
return self._make_subnet_dict(subnet)
def get_subnet(self, context, subnet_id, fields=None):
"""Get the attributes of a particular subnet."""
return self._get_subnet(context, subnet_id, fields)
def update_subnet(self, context, subnet_id, subnet):
"""Updates the attributes of a particular subnet."""
subnet = self._update_resource('subnet', context, subnet_id, subnet)
return self._make_subnet_dict(subnet)
def delete_subnet(self, context, subnet_id):
"""
Deletes the subnet with the specified subnet identifier
belonging to the specified tenant.
"""
self._delete_resource('subnet', context, subnet_id)
def get_subnets(self, context, filters=None, fields=None):
"""Get the list of subnets."""
return [self._make_subnet_dict(s)
for s in self._list_resource(
'subnet', context, filters, fields)]
def get_subnets_count(self, context, filters=None):
"""Get the count of subnets."""
subnets_count = self._count_resource('subnet', context, filters)
return subnets_count['count']
def _extend_port_dict_security_group(self, port_res, port_db):
# Security group bindings will be retrieved from the sqlalchemy
# model. As they're loaded eagerly with ports because of the
# joined load they will not cause an extra query.
port_res[securitygroup.SECURITYGROUPS] = port_db.get(
'security_groups', []) or []
return port_res
def _make_port_dict(self, port):
return port
def _get_port(self, context, id, fields=None):
port = self._get_resource('port', context, id, fields)
return self._make_port_dict(port)
def _update_ips_for_port(self, context, network_id, port_id, original_ips,
new_ips):
"""Add or remove IPs from the port."""
# These ips are still on the port and haven't been removed
prev_ips = []
# the new_ips contain all of the fixed_ips that are to be updated
if len(new_ips) > cfg.CONF.max_fixed_ips_per_port:
msg = _('Exceeded maximim amount of fixed ips per port')
raise exc.InvalidInput(error_message=msg)
# Remove all of the intersecting elements
for original_ip in original_ips[:]:
for new_ip in new_ips[:]:
if ('ip_address' in new_ip and
original_ip['ip_address'] == new_ip['ip_address']):
original_ips.remove(original_ip)
new_ips.remove(new_ip)
prev_ips.append(original_ip)
return new_ips, prev_ips
def create_port(self, context, port):
"""Creates a port on the specified Virtual Network."""
port = self._create_resource('port', context, port)
return self._make_port_dict(port)
def get_port(self, context, port_id, fields=None):
"""Get the attributes of a particular port."""
return self._get_port(context, port_id, fields)
def update_port(self, context, port_id, port):
"""Updates a port.
Updates the attributes of a port on the specified Virtual
Network.
"""
if 'fixed_ips' in port['port']:
original = self._get_port(context, port_id)
added_ips, prev_ips = self._update_ips_for_port(
context, original['network_id'], port_id,
original['fixed_ips'], port['port']['fixed_ips'])
port['port']['fixed_ips'] = prev_ips + added_ips
port = self._update_resource('port', context, port_id, port)
return self._make_port_dict(port)
def delete_port(self, context, port_id):
"""Deletes a port.
Deletes a port on a specified Virtual Network,
if the port contains a remote interface attachment,
the remote interface is first un-plugged and then the port
is deleted.
"""
self._delete_resource('port', context, port_id)
def get_ports(self, context, filters=None, fields=None):
"""Get all ports.
Retrieves all port identifiers belonging to the
specified Virtual Network with the specfied filter.
"""
return [self._make_port_dict(p)
for p in self._list_resource('port', context, filters, fields)]
def get_ports_count(self, context, filters=None):
"""Get the count of ports."""
ports_count = self._count_resource('port', context, filters)
return ports_count['count']
# Router API handlers
def create_router(self, context, router):
"""Creates a router.
Creates a new Logical Router, and assigns it
a symbolic name.
"""
return self._create_resource('router', context, router)
def get_router(self, context, router_id, fields=None):
"""Get the attributes of a router."""
return self._get_resource('router', context, router_id, fields)
def update_router(self, context, router_id, router):
"""Updates the attributes of a router."""
return self._update_resource('router', context, router_id,
router)
def delete_router(self, context, router_id):
"""Deletes a router."""
self._delete_resource('router', context, router_id)
def get_routers(self, context, filters=None, fields=None):
"""Retrieves all router identifiers."""
return self._list_resource('router', context, filters, fields)
def get_routers_count(self, context, filters=None):
"""Get the count of routers."""
routers_count = self._count_resource('router', context, filters)
return routers_count['count']
def add_router_interface(self, context, router_id, interface_info):
"""Add interface to a router."""
if not interface_info:
msg = _("Either subnet_id or port_id must be specified")
raise exc.BadRequest(resource='router', msg=msg)
if 'port_id' in interface_info:
if 'subnet_id' in interface_info:
msg = _("Cannot specify both subnet-id and port-id")
raise exc.BadRequest(resource='router', msg=msg)
res_dict = self._encode_resource(resource_id=router_id,
resource=interface_info)
status_code, res_info = self._request_backend(context, res_dict,
'router', 'ADDINTERFACE')
if status_code != requests.codes.ok:
self._raise_contrail_error(status_code, info=res_info,
obj_name='add_router_interface')
return res_info
def remove_router_interface(self, context, router_id, interface_info):
"""Delete interface from a router."""
if not interface_info:
msg = _("Either subnet_id or port_id must be specified")
raise exc.BadRequest(resource='router', msg=msg)
res_dict = self._encode_resource(resource_id=router_id,
resource=interface_info)
status_code, res_info = self._request_backend(context, res_dict,
'router', 'DELINTERFACE')
if status_code != requests.codes.ok:
self._raise_contrail_error(status_code, info=res_info,
obj_name='remove_router_interface')
return res_info
# Floating IP API handlers
def create_floatingip(self, context, floatingip):
"""Creates a floating IP."""
return self._create_resource('floatingip', context, floatingip)
def update_floatingip(self, context, fip_id, floatingip):
"""Updates the attributes of a floating IP."""
return self._update_resource('floatingip', context, fip_id,
floatingip)
def get_floatingip(self, context, fip_id, fields=None):
"""Get the attributes of a floating ip."""
return self._get_resource('floatingip', context, fip_id, fields)
def delete_floatingip(self, context, fip_id):
"""Deletes a floating IP."""
self._delete_resource('floatingip', context, fip_id)
def get_floatingips(self, context, filters=None, fields=None):
"""Retrieves all floating ips identifiers."""
return self._list_resource('floatingip', context, filters, fields)
def get_floatingips_count(self, context, filters=None):
"""Get the count of floating IPs."""
fips_count = self._count_resource('floatingip', context, filters)
return fips_count['count']
# Security Group handlers
def create_security_group(self, context, security_group):
"""Creates a Security Group."""
return self._create_resource('security_group', context,
security_group)
def get_security_group(self, context, sg_id, fields=None, tenant_id=None):
"""Get the attributes of a security group."""
return self._get_resource('security_group', context, sg_id, fields)
def update_security_group(self, context, sg_id, security_group):
"""Updates the attributes of a security group."""
return self._update_resource('security_group', context, sg_id,
security_group)
def delete_security_group(self, context, sg_id):
"""Deletes a security group."""
self._delete_resource('security_group', context, sg_id)
def get_security_groups(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None,
page_reverse=False):
"""Retrieves all security group identifiers."""
return self._list_resource('security_group', context,
filters, fields)
def get_security_groups_count(self, context, filters=None):
return 0
def get_security_group_rules_count(self, context, filters=None):
return 0
def create_security_group_rule(self, context, security_group_rule):
"""Creates a security group rule."""
return self._create_resource('security_group_rule', context,
security_group_rule)
def delete_security_group_rule(self, context, sg_rule_id):
"""Deletes a security group rule."""
self._delete_resource('security_group_rule', context, sg_rule_id)
def get_security_group_rule(self, context, sg_rule_id, fields=None):
"""Get the attributes of a security group rule."""
return self._get_resource('security_group_rule', context,
sg_rule_id, fields)
def get_security_group_rules(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None,
page_reverse=False):
"""Retrieves all security group rules."""
return self._list_resource('security_group_rule', context,
filters, fields)
| cloudwatt/contrail-neutron-plugin | neutron_plugin_contrail/plugins/opencontrail/contrail_plugin.py | Python | apache-2.0 | 28,349 |
/*
* 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.camel.component.cmis;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.camel.Consumer;
import org.apache.camel.Endpoint;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.chemistry.opencmis.client.api.Folder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class CMISConsumerTest extends CMISTestSupport {
@EndpointInject("mock:result")
protected MockEndpoint resultEndpoint;
@Test
void getAllContentFromServerOrderedFromRootToLeaves() throws Exception {
resultEndpoint.expectedMessageCount(5);
Consumer treeBasedConsumer = createConsumerFor(getUrl() + "?pageSize=50");
treeBasedConsumer.start();
resultEndpoint.assertIsSatisfied();
treeBasedConsumer.stop();
List<Exchange> exchanges = resultEndpoint.getExchanges();
assertTrue(getNodeNameForIndex(exchanges, 0).equals("RootFolder"));
assertTrue(getNodeNameForIndex(exchanges, 1).equals("Folder1"));
assertTrue(getNodeNameForIndex(exchanges, 2).equals("Folder2"));
assertTrue(getNodeNameForIndex(exchanges, 3).contains(".txt"));
assertTrue(getNodeNameForIndex(exchanges, 4).contains(".txt"));
}
@Test
void consumeDocumentsWithQuery() throws Exception {
resultEndpoint.expectedMessageCount(2);
Consumer queryBasedConsumer = createConsumerFor(
getUrl() + "?query=SELECT * FROM cmis:document");
queryBasedConsumer.start();
resultEndpoint.assertIsSatisfied();
queryBasedConsumer.stop();
}
private Consumer createConsumerFor(String path) throws Exception {
Endpoint endpoint = context.getEndpoint("cmis://" + path);
return endpoint.createConsumer(new Processor() {
public void process(Exchange exchange) {
template.send("mock:result", exchange);
}
});
}
private String getNodeNameForIndex(List<Exchange> exchanges, int index) {
return exchanges.get(index).getIn().getHeader("cmis:name", String.class);
}
private void populateRepositoryRootFolderWithTwoFoldersAndTwoDocuments()
throws UnsupportedEncodingException {
Folder folder1 = createFolderWithName("Folder1");
Folder folder2 = createChildFolderWithName(folder1, "Folder2");
createTextDocument(folder2, "Document2.1", "2.1.txt");
createTextDocument(folder2, "Document2.2", "2.2.txt");
//L0 ROOT
// |
//L1 Folder1
//L2 |_____Folder2
// ||
//L3 Doc2.1___||___Doc2.2
}
@Override
@BeforeEach
public void setUp() throws Exception {
super.setUp();
populateRepositoryRootFolderWithTwoFoldersAndTwoDocuments();
}
}
| adessaigne/camel | components/camel-cmis/src/test/java/org/apache/camel/component/cmis/CMISConsumerTest.java | Java | apache-2.0 | 3,886 |
/*
* Copyright (c) 2010-2018. Axon Framework
*
* 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.axonframework.messaging.annotation;
import org.axonframework.messaging.Message;
/**
* Implementation of a {@link ParameterResolver} that resolves the Message payload as parameter in a handler method.
*/
public class PayloadParameterResolver implements ParameterResolver {
private final Class<?> payloadType;
/**
* Initializes a new {@link PayloadParameterResolver} for a method parameter of given {@code payloadType}. This
* parameter resolver matches with a message if the payload of the message is assignable to the given {@code
* payloadType}.
*
* @param payloadType the parameter type
*/
public PayloadParameterResolver(Class<?> payloadType) {
this.payloadType = payloadType;
}
@Override
public Object resolveParameterValue(Message message) {
return message.getPayload();
}
@Override
public boolean matches(Message message) {
return message.getPayloadType() != null && payloadType.isAssignableFrom(message.getPayloadType());
}
@Override
public Class<?> supportedPayloadType() {
return payloadType;
}
}
| krosenvold/AxonFramework | messaging/src/main/java/org/axonframework/messaging/annotation/PayloadParameterResolver.java | Java | apache-2.0 | 1,749 |
export * from './helpers/ChaiModel';
| zhenwenc/ts-libs | src/helpers.ts | TypeScript | apache-2.0 | 37 |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.saml;
import org.keycloak.dom.saml.v2.assertion.NameIDType;
import org.keycloak.dom.saml.v2.protocol.AuthnRequestType;
import org.keycloak.saml.common.exceptions.ConfigurationException;
import org.keycloak.saml.processing.api.saml.v2.request.SAML2Request;
import org.keycloak.saml.processing.core.saml.v2.common.IDGenerator;
import org.keycloak.saml.processing.core.saml.v2.util.XMLTimeUtil;
import org.w3c.dom.Document;
import java.net.URI;
/**
* @author pedroigor
*/
public class SAML2AuthnRequestBuilder {
private final AuthnRequestType authnRequestType;
protected String destination;
protected String issuer;
public SAML2AuthnRequestBuilder destination(String destination) {
this.destination = destination;
return this;
}
public SAML2AuthnRequestBuilder issuer(String issuer) {
this.issuer = issuer;
return this;
}
public SAML2AuthnRequestBuilder() {
try {
this.authnRequestType = new AuthnRequestType(IDGenerator.create("ID_"), XMLTimeUtil.getIssueInstant());
} catch (ConfigurationException e) {
throw new RuntimeException("Could not create SAML AuthnRequest builder.", e);
}
}
public SAML2AuthnRequestBuilder assertionConsumerUrl(String assertionConsumerUrl) {
this.authnRequestType.setAssertionConsumerServiceURL(URI.create(assertionConsumerUrl));
return this;
}
public SAML2AuthnRequestBuilder forceAuthn(boolean forceAuthn) {
this.authnRequestType.setForceAuthn(forceAuthn);
return this;
}
public SAML2AuthnRequestBuilder isPassive(boolean isPassive) {
this.authnRequestType.setIsPassive(isPassive);
return this;
}
public SAML2AuthnRequestBuilder nameIdPolicy(SAML2NameIDPolicyBuilder nameIDPolicy) {
this.authnRequestType.setNameIDPolicy(nameIDPolicy.build());
return this;
}
public SAML2AuthnRequestBuilder protocolBinding(String protocolBinding) {
this.authnRequestType.setProtocolBinding(URI.create(protocolBinding));
return this;
}
public Document toDocument() {
try {
AuthnRequestType authnRequestType = this.authnRequestType;
NameIDType nameIDType = new NameIDType();
nameIDType.setValue(this.issuer);
authnRequestType.setIssuer(nameIDType);
authnRequestType.setDestination(URI.create(this.destination));
return new SAML2Request().convert(authnRequestType);
} catch (Exception e) {
throw new RuntimeException("Could not convert " + authnRequestType + " to a document.", e);
}
}
} | iperdomo/keycloak | saml-core/src/main/java/org/keycloak/saml/SAML2AuthnRequestBuilder.java | Java | apache-2.0 | 3,364 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/mwaa/model/GetEnvironmentResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::MWAA::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
GetEnvironmentResult::GetEnvironmentResult()
{
}
GetEnvironmentResult::GetEnvironmentResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
GetEnvironmentResult& GetEnvironmentResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("Environment"))
{
m_environment = jsonValue.GetObject("Environment");
}
return *this;
}
| aws/aws-sdk-cpp | aws-cpp-sdk-mwaa/source/model/GetEnvironmentResult.cpp | C++ | apache-2.0 | 950 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.execution.junit;
import com.intellij.openapi.roots.ExternalLibraryDescriptor;
/**
* @author nik
*/
public class JUnitExternalLibraryDescriptor extends ExternalLibraryDescriptor {
public static final ExternalLibraryDescriptor JUNIT3 = new JUnitExternalLibraryDescriptor("3", "3.8.2");
public static final ExternalLibraryDescriptor JUNIT4 = new JUnitExternalLibraryDescriptor("4", "4.12");
public static final ExternalLibraryDescriptor JUNIT5 = new JUnitExternalLibraryDescriptor("org.junit.jupiter", "junit-jupiter-api", "5.2",
null);
private final String myVersion;
private JUnitExternalLibraryDescriptor(String baseVersion, String preferredVersion) {
this("junit", "junit", baseVersion, preferredVersion);
}
private JUnitExternalLibraryDescriptor(final String groupId,
final String artifactId,
final String version,
String preferredVersion) {
super(groupId, artifactId, version + ".0", version + ".999", preferredVersion);
myVersion = version;
}
@Override
public String getPresentableName() {
return "JUnit" + myVersion;
}
}
| goodwinnk/intellij-community | plugins/junit/src/com/intellij/execution/junit/JUnitExternalLibraryDescriptor.java | Java | apache-2.0 | 1,908 |
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: xds/core/v3/context_params.proto
package xds_core_v3
import (
fmt "fmt"
_ "github.com/cncf/udpa/go/udpa/annotations"
proto "github.com/golang/protobuf/proto"
math "math"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
type ContextParams struct {
Params map[string]string `protobuf:"bytes,1,rep,name=params,proto3" json:"params,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *ContextParams) Reset() { *m = ContextParams{} }
func (m *ContextParams) String() string { return proto.CompactTextString(m) }
func (*ContextParams) ProtoMessage() {}
func (*ContextParams) Descriptor() ([]byte, []int) {
return fileDescriptor_a77d5b5f2f15aa7c, []int{0}
}
func (m *ContextParams) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_ContextParams.Unmarshal(m, b)
}
func (m *ContextParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_ContextParams.Marshal(b, m, deterministic)
}
func (m *ContextParams) XXX_Merge(src proto.Message) {
xxx_messageInfo_ContextParams.Merge(m, src)
}
func (m *ContextParams) XXX_Size() int {
return xxx_messageInfo_ContextParams.Size(m)
}
func (m *ContextParams) XXX_DiscardUnknown() {
xxx_messageInfo_ContextParams.DiscardUnknown(m)
}
var xxx_messageInfo_ContextParams proto.InternalMessageInfo
func (m *ContextParams) GetParams() map[string]string {
if m != nil {
return m.Params
}
return nil
}
func init() {
proto.RegisterType((*ContextParams)(nil), "xds.core.v3.ContextParams")
proto.RegisterMapType((map[string]string)(nil), "xds.core.v3.ContextParams.ParamsEntry")
}
func init() { proto.RegisterFile("xds/core/v3/context_params.proto", fileDescriptor_a77d5b5f2f15aa7c) }
var fileDescriptor_a77d5b5f2f15aa7c = []byte{
// 221 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xa8, 0x48, 0x29, 0xd6,
0x4f, 0xce, 0x2f, 0x4a, 0xd5, 0x2f, 0x33, 0xd6, 0x4f, 0xce, 0xcf, 0x2b, 0x49, 0xad, 0x28, 0x89,
0x2f, 0x48, 0x2c, 0x4a, 0xcc, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0xae, 0x48,
0x29, 0xd6, 0x03, 0xa9, 0xd0, 0x2b, 0x33, 0x96, 0x92, 0x2d, 0x4d, 0x29, 0x48, 0xd4, 0x4f, 0xcc,
0xcb, 0xcb, 0x2f, 0x49, 0x2c, 0xc9, 0xcc, 0xcf, 0x2b, 0xd6, 0x2f, 0x2e, 0x49, 0x2c, 0x29, 0x85,
0xaa, 0x55, 0xea, 0x62, 0xe4, 0xe2, 0x75, 0x86, 0x18, 0x12, 0x00, 0x36, 0x43, 0xc8, 0x8e, 0x8b,
0x0d, 0x62, 0x9a, 0x04, 0xa3, 0x02, 0xb3, 0x06, 0xb7, 0x91, 0x9a, 0x1e, 0x92, 0x71, 0x7a, 0x28,
0x6a, 0xf5, 0x20, 0x94, 0x6b, 0x5e, 0x49, 0x51, 0x65, 0x10, 0x54, 0x97, 0x94, 0x25, 0x17, 0x37,
0x92, 0xb0, 0x90, 0x00, 0x17, 0x73, 0x76, 0x6a, 0xa5, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x67, 0x10,
0x88, 0x29, 0x24, 0xc2, 0xc5, 0x5a, 0x96, 0x98, 0x53, 0x9a, 0x2a, 0xc1, 0x04, 0x16, 0x83, 0x70,
0xac, 0x98, 0x2c, 0x18, 0x9d, 0xac, 0x77, 0x35, 0x9c, 0xb8, 0xc8, 0xc6, 0xc4, 0xc1, 0xc8, 0x25,
0x9d, 0x9c, 0x9f, 0xab, 0x97, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x07, 0xf2, 0x00, 0xb2, 0x1b,
0x9c, 0x84, 0x50, 0x1c, 0x11, 0x00, 0xf2, 0x47, 0x00, 0x63, 0x12, 0x1b, 0xd8, 0x43, 0xc6, 0x80,
0x00, 0x00, 0x00, 0xff, 0xff, 0xe6, 0x4e, 0x2e, 0x13, 0x20, 0x01, 0x00, 0x00,
}
| tgraf/cilium | vendor/github.com/cncf/udpa/go/xds/core/v3/context_params.pb.go | GO | apache-2.0 | 3,805 |
// SMSLib for Java v3
// A Java API library for sending and receiving SMS via a GSM modem
// or other supported gateways.
// Web Site: http://www.smslib.org
//
// Copyright (C) 2002-2012, Thanasis Delenikas, Athens/GREECE.
// SMSLib is distributed under the terms of the Apache License version 2.0
//
// 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.smslib.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.smslib.AGateway;
import org.smslib.helper.Logger;
class HTTPGateway extends AGateway
{
public HTTPGateway(String id)
{
super(id);
}
List<String> HttpPost(URL url, List<HttpHeader> requestList) throws IOException
{
List<String> responseList = new ArrayList<String>();
URLConnection con;
BufferedReader in;
OutputStreamWriter out;
StringBuffer req;
String line;
Logger.getInstance().logInfo("HTTP POST: " + url, null, getGatewayId());
con = url.openConnection();
con.setConnectTimeout(20000);
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
out = new OutputStreamWriter(con.getOutputStream());
req = new StringBuffer();
for (int i = 0, n = requestList.size(); i < n; i++)
{
if (i != 0) req.append("&");
req.append(requestList.get(i).key);
req.append("=");
if (requestList.get(i).unicode)
{
StringBuffer tmp = new StringBuffer(200);
byte[] uniBytes = requestList.get(i).value.getBytes("UnicodeBigUnmarked");
for (int j = 0; j < uniBytes.length; j++)
tmp.append(Integer.toHexString(uniBytes[j]).length() == 1 ? "0" + Integer.toHexString(uniBytes[j]) : Integer.toHexString(uniBytes[j]));
req.append(tmp.toString().replaceAll("ff", ""));
}
else req.append(URLEncoder.encode(requestList.get(i).value, "utf-8"));
}
out.write(req.toString());
out.flush();
out.close();
in = new BufferedReader(new InputStreamReader((con.getInputStream())));
while ((line = in.readLine()) != null)
responseList.add(line);
in.close();
return responseList;
}
List<String> HttpGet(URL url) throws IOException
{
List<String> responseList = new ArrayList<String>();
Logger.getInstance().logInfo("HTTP GET: " + url, null, getGatewayId());
URLConnection con = url.openConnection();
con.setConnectTimeout(20000);
con.setAllowUserInteraction(false);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
responseList.add(inputLine);
in.close();
return responseList;
}
String ExpandHttpHeaders(List<HttpHeader> httpHeaderList)
{
StringBuffer buffer = new StringBuffer();
for (HttpHeader h : httpHeaderList)
{
buffer.append(h.key);
buffer.append("=");
buffer.append(h.value);
buffer.append("&");
}
return buffer.toString();
}
class HttpHeader
{
public String key;
public String value;
public boolean unicode;
public HttpHeader()
{
this.key = "";
this.value = "";
this.unicode = false;
}
public HttpHeader(String myKey, String myValue, boolean myUnicode)
{
this.key = myKey;
this.value = myValue;
this.unicode = myUnicode;
}
}
String calculateMD5(String in)
{
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] pre_md5 = md.digest(in.getBytes("LATIN1"));
StringBuilder md5 = new StringBuilder();
for (int i = 0; i < 16; i++)
{
if (pre_md5[i] < 0)
{
md5.append(Integer.toHexString(256 + pre_md5[i]));
}
else if (pre_md5[i] > 15)
{
md5.append(Integer.toHexString(pre_md5[i]));
}
else
{
md5.append("0" + Integer.toHexString(pre_md5[i]));
}
}
return md5.toString();
}
catch (UnsupportedEncodingException ex)
{
Logger.getInstance().logError("Unsupported encoding.", ex, getGatewayId());
return "";
}
catch (NoSuchAlgorithmException ex)
{
Logger.getInstance().logError("No such algorithm.", ex, getGatewayId());
return "";
}
}
@Override
public int getQueueSchedulingInterval()
{
return 500;
}
}
| pioryan/smslib | src/java/org/smslib/http/HTTPGateway.java | Java | apache-2.0 | 4,949 |
namespace NuKeeper.BitBucket.Models
{
public class Author
{
public string raw { get; set; }
public UserShort user { get; set; }
}
} | AnthonySteele/NuKeeper | NuKeeper.BitBucket/Models/Author.cs | C# | apache-2.0 | 162 |
package com.google.api.ads.dfp.jaxws.v201508;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
*
* The action used for activating {@link Placement} objects.
*
*
* <p>Java class for ActivatePlacements complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ActivatePlacements">
* <complexContent>
* <extension base="{https://www.google.com/apis/ads/publisher/v201508}PlacementAction">
* <sequence>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ActivatePlacements")
public class ActivatePlacements
extends PlacementAction
{
}
| raja15792/googleads-java-lib | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201508/ActivatePlacements.java | Java | apache-2.0 | 904 |
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/bigquery/datatransfer/v1/datatransfer.proto
namespace Google\Cloud\BigQuery\DataTransfer\V1\DataSource;
use UnexpectedValueException;
/**
* Represents how the data source supports data auto refresh.
*
* Protobuf type <code>google.cloud.bigquery.datatransfer.v1.DataSource.DataRefreshType</code>
*/
class DataRefreshType
{
/**
* The data source won't support data auto refresh, which is default value.
*
* Generated from protobuf enum <code>DATA_REFRESH_TYPE_UNSPECIFIED = 0;</code>
*/
const DATA_REFRESH_TYPE_UNSPECIFIED = 0;
/**
* The data source supports data auto refresh, and runs will be scheduled
* for the past few days. Does not allow custom values to be set for each
* transfer config.
*
* Generated from protobuf enum <code>SLIDING_WINDOW = 1;</code>
*/
const SLIDING_WINDOW = 1;
/**
* The data source supports data auto refresh, and runs will be scheduled
* for the past few days. Allows custom values to be set for each transfer
* config.
*
* Generated from protobuf enum <code>CUSTOM_SLIDING_WINDOW = 2;</code>
*/
const CUSTOM_SLIDING_WINDOW = 2;
private static $valueToName = [
self::DATA_REFRESH_TYPE_UNSPECIFIED => 'DATA_REFRESH_TYPE_UNSPECIFIED',
self::SLIDING_WINDOW => 'SLIDING_WINDOW',
self::CUSTOM_SLIDING_WINDOW => 'CUSTOM_SLIDING_WINDOW',
];
public static function name($value)
{
if (!isset(self::$valueToName[$value])) {
throw new UnexpectedValueException(sprintf(
'Enum %s has no name defined for value %s', __CLASS__, $value));
}
return self::$valueToName[$value];
}
public static function value($name)
{
$const = __CLASS__ . '::' . strtoupper($name);
if (!defined($const)) {
throw new UnexpectedValueException(sprintf(
'Enum %s has no value defined for name %s', __CLASS__, $name));
}
return constant($const);
}
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(DataRefreshType::class, \Google\Cloud\BigQuery\DataTransfer\V1\DataSource_DataRefreshType::class);
| googleapis/google-cloud-php-bigquerydatatransfer | src/V1/DataSource/DataRefreshType.php | PHP | apache-2.0 | 2,315 |
package handshake
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"github.com/bifurcation/mint"
"github.com/lucas-clemente/quic-go/internal/protocol"
"github.com/lucas-clemente/quic-go/internal/utils"
)
type transportParameterID uint16
const quicTLSExtensionType = 0xff5
const (
initialMaxStreamDataParameterID transportParameterID = 0x0
initialMaxDataParameterID transportParameterID = 0x1
initialMaxBidiStreamsParameterID transportParameterID = 0x2
idleTimeoutParameterID transportParameterID = 0x3
maxPacketSizeParameterID transportParameterID = 0x5
statelessResetTokenParameterID transportParameterID = 0x6
initialMaxUniStreamsParameterID transportParameterID = 0x8
disableMigrationParameterID transportParameterID = 0x9
)
type clientHelloTransportParameters struct {
InitialVersion protocol.VersionNumber
Parameters TransportParameters
}
func (p *clientHelloTransportParameters) Marshal() []byte {
const lenOffset = 4
b := &bytes.Buffer{}
utils.BigEndian.WriteUint32(b, uint32(p.InitialVersion))
b.Write([]byte{0, 0}) // length. Will be replaced later
p.Parameters.marshal(b)
data := b.Bytes()
binary.BigEndian.PutUint16(data[lenOffset:lenOffset+2], uint16(len(data)-lenOffset-2))
return data
}
func (p *clientHelloTransportParameters) Unmarshal(data []byte) error {
if len(data) < 6 {
return errors.New("transport parameter data too short")
}
p.InitialVersion = protocol.VersionNumber(binary.BigEndian.Uint32(data[:4]))
paramsLen := int(binary.BigEndian.Uint16(data[4:6]))
data = data[6:]
if len(data) != paramsLen {
return fmt.Errorf("expected transport parameters to be %d bytes long, have %d", paramsLen, len(data))
}
return p.Parameters.unmarshal(data)
}
type encryptedExtensionsTransportParameters struct {
NegotiatedVersion protocol.VersionNumber
SupportedVersions []protocol.VersionNumber
Parameters TransportParameters
}
func (p *encryptedExtensionsTransportParameters) Marshal() []byte {
b := &bytes.Buffer{}
utils.BigEndian.WriteUint32(b, uint32(p.NegotiatedVersion))
b.WriteByte(uint8(4 * len(p.SupportedVersions)))
for _, v := range p.SupportedVersions {
utils.BigEndian.WriteUint32(b, uint32(v))
}
lenOffset := b.Len()
b.Write([]byte{0, 0}) // length. Will be replaced later
p.Parameters.marshal(b)
data := b.Bytes()
binary.BigEndian.PutUint16(data[lenOffset:lenOffset+2], uint16(len(data)-lenOffset-2))
return data
}
func (p *encryptedExtensionsTransportParameters) Unmarshal(data []byte) error {
if len(data) < 5 {
return errors.New("transport parameter data too short")
}
p.NegotiatedVersion = protocol.VersionNumber(binary.BigEndian.Uint32(data[:4]))
numVersions := int(data[4])
if numVersions%4 != 0 {
return fmt.Errorf("invalid length for version list: %d", numVersions)
}
numVersions /= 4
data = data[5:]
if len(data) < 4*numVersions+2 /*length field for the parameter list */ {
return errors.New("transport parameter data too short")
}
p.SupportedVersions = make([]protocol.VersionNumber, numVersions)
for i := 0; i < numVersions; i++ {
p.SupportedVersions[i] = protocol.VersionNumber(binary.BigEndian.Uint32(data[:4]))
data = data[4:]
}
paramsLen := int(binary.BigEndian.Uint16(data[:2]))
data = data[2:]
if len(data) != paramsLen {
return fmt.Errorf("expected transport parameters to be %d bytes long, have %d", paramsLen, len(data))
}
return p.Parameters.unmarshal(data)
}
type tlsExtensionBody struct {
data []byte
}
var _ mint.ExtensionBody = &tlsExtensionBody{}
func (e *tlsExtensionBody) Type() mint.ExtensionType {
return quicTLSExtensionType
}
func (e *tlsExtensionBody) Marshal() ([]byte, error) {
return e.data, nil
}
func (e *tlsExtensionBody) Unmarshal(data []byte) (int, error) {
e.data = data
return len(data), nil
}
| l3dlp/caddy | vendor/github.com/lucas-clemente/quic-go/internal/handshake/tls_extension.go | GO | apache-2.0 | 3,810 |
/*
* 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.solr.highlight;
import org.apache.lucene.search.vectorhighlight.BoundaryScanner;
import org.apache.lucene.search.vectorhighlight.FragmentsBuilder;
import org.apache.solr.common.params.SolrParams;
public class ScoreOrderFragmentsBuilder extends SolrFragmentsBuilder {
@Override
protected FragmentsBuilder getFragmentsBuilder( SolrParams params,
String[] preTags, String[] postTags, BoundaryScanner bs ) {
org.apache.lucene.search.vectorhighlight.ScoreOrderFragmentsBuilder sofb =
new org.apache.lucene.search.vectorhighlight.ScoreOrderFragmentsBuilder( preTags, postTags, bs );
sofb.setMultiValuedSeparator( getMultiValuedSeparatorChar( params ) );
return sofb;
}
///////////////////////////////////////////////////////////////////////
//////////////////////// SolrInfoMBeans methods ///////////////////////
///////////////////////////////////////////////////////////////////////
@Override
public String getDescription() {
return "ScoreOrderFragmentsBuilder";
}
@Override
public String getSource() {
return "$URL: https://svn.apache.org/repos/asf/lucene/dev/branches/lucene_solr_4_6/solr/core/src/java/org/apache/solr/highlight/ScoreOrderFragmentsBuilder.java $";
}
}
| zhangdian/solr4.6.0 | solr/core/src/java/org/apache/solr/highlight/ScoreOrderFragmentsBuilder.java | Java | apache-2.0 | 2,051 |
/* $Id: InstanceBean.java 1133 2004-06-15 11:13:47Z gunterze $
* Copyright (c) 2002,2003 by TIANI MEDGRAPH AG
*
* This file is part of dcm4che.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.dcm4chex.archive.ejb.entity;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
import javax.ejb.FinderException;
import javax.ejb.RemoveException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.log4j.Logger;
import org.dcm4che.data.Dataset;
import org.dcm4che.data.DcmDecodeParam;
import org.dcm4che.dict.Tags;
import org.dcm4cheri.util.DatasetUtils;
import org.dcm4cheri.util.StringUtils;
import org.dcm4chex.archive.ejb.interfaces.CodeLocal;
import org.dcm4chex.archive.ejb.interfaces.CodeLocalHome;
import org.dcm4chex.archive.ejb.interfaces.SeriesLocal;
/**
* Instance Bean
*
* @author <a href="mailto:gunter@tiani.com">Gunter Zeilinger</a>
* @version $Revision: 1133 $ $Date: 2004-06-15 19:13:47 +0800 (周二, 15 6月 2004) $
*
* @ejb.bean
* name="Instance"
* type="CMP"
* view-type="local"
* primkey-field="pk"
* local-jndi-name="ejb/Instance"
*
* @ejb.transaction
* type="Required"
*
* @ejb.persistence
* table-name="instance"
*
* @jboss.entity-command
* name="hsqldb-fetch-key"
*
* @ejb.finder
* signature="java.util.Collection findAll()"
* query="SELECT OBJECT(a) FROM Instance AS a"
* transaction-type="Supports"
*
* @ejb.finder
* signature="org.dcm4chex.archive.ejb.interfaces.InstanceLocal findBySopIuid(java.lang.String uid)"
* query="SELECT OBJECT(a) FROM Instance AS a WHERE a.sopIuid = ?1"
* transaction-type="Supports"
*
* @ejb.ejb-ref ejb-name="Code" view-type="local" ref-name="ejb/Code"
*
*/
public abstract class InstanceBean implements EntityBean {
private static final Logger log = Logger.getLogger(InstanceBean.class);
private CodeLocalHome codeHome;
private Set retrieveAETSet;
public void setEntityContext(EntityContext ctx) {
Context jndiCtx = null;
try {
jndiCtx = new InitialContext();
codeHome = (CodeLocalHome) jndiCtx.lookup("java:comp/env/ejb/Code");
} catch (NamingException e) {
throw new EJBException(e);
} finally {
if (jndiCtx != null) {
try {
jndiCtx.close();
} catch (NamingException ignore) {
}
}
}
}
public void unsetEntityContext() {
codeHome = null;
}
/**
* Auto-generated Primary Key
*
* @ejb.interface-method
* @ejb.pk-field
* @ejb.persistence
* column-name="pk"
* @jboss.persistence
* auto-increment="true"
*
*/
public abstract Integer getPk();
public abstract void setPk(Integer pk);
/**
* SOP Instance UID
*
* @ejb.persistence
* column-name="sop_iuid"
*
* @ejb.interface-method
*
*/
public abstract String getSopIuid();
public abstract void setSopIuid(String iuid);
/**
* SOP Class UID
*
* @ejb.persistence
* column-name="sop_cuid"
*
* @ejb.interface-method
*
*/
public abstract String getSopCuid();
public abstract void setSopCuid(String cuid);
/**
* Instance Number
*
* @ejb.persistence
* column-name="inst_no"
*
* @ejb.interface-method
*
*/
public abstract String getInstanceNumber();
public abstract void setInstanceNumber(String no);
/**
* SR Completion Flag
*
* @ejb.persistence
* column-name="sr_complete"
*
* @ejb.interface-method
*
*/
public abstract String getSrCompletionFlag();
public abstract void setSrCompletionFlag(String flag);
/**
* SR Verification Flag
*
* @ejb.persistence
* column-name="sr_verified"
*
* @ejb.interface-method
*
*/
public abstract String getSrVerificationFlag();
public abstract void setSrVerificationFlag(String flag);
/**
* Instance DICOM Attributes
*
* @ejb.persistence
* column-name="inst_attrs"
*
*/
public abstract byte[] getEncodedAttributes();
public abstract void setEncodedAttributes(byte[] bytes);
/**
* Retrieve AETs
*
* @ejb.interface-method
* @ejb.persistence
* column-name="retrieve_aets"
*/
public abstract String getRetrieveAETs();
public abstract void setRetrieveAETs(String aets);
/**
* Instance Availability
*
* @ejb.persistence
* column-name="availability"
*/
public abstract int getAvailability();
/**
* @ejb.interface-method
*/
public int getAvailabilitySafe() {
try {
return getAvailability();
} catch (NullPointerException npe) {
return 0;
}
}
public abstract void setAvailability(int availability);
/**
* Storage Commitment
*
* @ejb.persistence
* column-name="commitment"
*/
public abstract boolean getCommitment();
/**
* @ejb.interface-method
*/
public boolean getCommitmentSafe() {
try {
return getCommitment();
} catch (NullPointerException npe) {
return false;
}
}
/**
* @ejb.interface-method
*/
public abstract void setCommitment(boolean commitment);
/**
* @ejb.relation
* name="series-instance"
* role-name="instance-of-series"
* cascade-delete="yes"
*
* @jboss:relation
* fk-column="series_fk"
* related-pk-field="pk"
*
* @param series series of this instance
*/
public abstract void setSeries(SeriesLocal series);
/**
* @ejb.interface-method view-type="local"
*
* @return series of this series
*/
public abstract SeriesLocal getSeries();
/**
* @ejb.relation
* name="instance-files"
* role-name="instance-in-files"
*
* @ejb.interface-method view-type="local"
*
* @return all files of this instance
*/
public abstract java.util.Collection getFiles();
public abstract void setFiles(java.util.Collection files);
/**
* @ejb.relation
* name="instance-srcode"
* role-name="sr-with-title"
* target-ejb="Code"
* target-role-name="title-of-sr"
* target-multiple="yes"
*
* @jboss:relation
* fk-column="srcode_fk"
* related-pk-field="pk"
*
* @param srCode code of SR title
*/
public abstract void setSrCode(CodeLocal srCode);
/**
* @ejb.interface-method view-type="local"
*
* @return code of SR title
*/
public abstract CodeLocal getSrCode();
public void ejbLoad() {
retrieveAETSet = null;
}
/**
* Create Instance.
*
* @ejb.create-method
*/
public Integer ejbCreate(Dataset ds, SeriesLocal series)
throws CreateException {
retrieveAETSet = null;
setAttributes(ds);
return null;
}
public void ejbPostCreate(Dataset ds, SeriesLocal series)
throws CreateException {
try {
setSrCode(CodeBean.valueOf(codeHome, ds
.getItem(Tags.ConceptNameCodeSeq)));
} catch (CreateException e) {
throw new CreateException(e.getMessage());
} catch (FinderException e) {
throw new CreateException(e.getMessage());
}
setSeries(series);
series.incNumberOfSeriesRelatedInstances(1);
log.info("Created " + prompt());
}
public void ejbRemove() throws RemoveException {
log.info("Deleting " + prompt());
SeriesLocal series = getSeries();
if (series != null) {
series.incNumberOfSeriesRelatedInstances(-1);
}
}
/**
* @ejb.interface-method
*/
public boolean updateAvailability(int availability) {
if (availability != getAvailabilitySafe()) {
setAvailability(availability);
return true;
}
return false;
}
/**
* @ejb.interface-method
*/
public Dataset getAttributes() {
return DatasetUtils.fromByteArray(getEncodedAttributes(),
DcmDecodeParam.EVR_LE);
}
/**
*
* @ejb.interface-method
*/
public void setAttributes(Dataset ds) {
setSopIuid(ds.getString(Tags.SOPInstanceUID));
setSopCuid(ds.getString(Tags.SOPClassUID));
setInstanceNumber(ds.getString(Tags.InstanceNumber));
setSrCompletionFlag(ds.getString(Tags.CompletionFlag));
setSrVerificationFlag(ds.getString(Tags.VerificationFlag));
setEncodedAttributes(DatasetUtils
.toByteArray(ds, DcmDecodeParam.EVR_LE));
}
/**
* @ejb.interface-method
*/
public Set getRetrieveAETSet() {
return Collections.unmodifiableSet(retrieveAETSet());
}
private Set retrieveAETSet() {
if (retrieveAETSet == null) {
retrieveAETSet = new HashSet();
String aets = getRetrieveAETs();
if (aets != null)
retrieveAETSet.addAll(Arrays.asList(StringUtils.split(aets,
'\\')));
}
return retrieveAETSet;
}
/**
* @ejb.interface-method
*/
public boolean addRetrieveAETs(String[] aets) {
if (!retrieveAETSet().addAll(Arrays.asList(aets))) return false;
setRetrieveAETs(StringUtils.toString((String[]) retrieveAETSet()
.toArray(new String[retrieveAETSet.size()]), '\\'));
return true;
}
/**
*
* @ejb.interface-method
*/
public String asString() {
return prompt();
}
private String prompt() {
return "Instance[pk=" + getPk() + ", iuid=" + getSopIuid() + ", cuid="
+ getSopCuid() + ", series->" + getSeries() + "]";
}
}
| medicayun/medicayundicom | dcm4jboss-all/tags/dcm4jboss_0_8_5/dcm4jboss-ejb/src/java/org/dcm4chex/archive/ejb/entity/InstanceBean.java | Java | apache-2.0 | 10,940 |
/**
*
*/
package com.manning.sdmia;
/**
* @author acogoluegnes
*
*/
public class SpringDmSample {
public SpringDmSample() {
System.out.println("Spring DM sample created");
}
}
| mykelalvis/springdm-in-action | ch03/springdm-sample/src/main/java/com/manning/sdmia/SpringDmSample.java | Java | apache-2.0 | 206 |
package com.orientechnologies.common.console;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Reader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.orientechnologies.common.log.OLogManager;
public class TTYConsoleReader implements OConsoleReader {
private static final String HISTORY_FILE_NAME = ".orientdb_history";
private static int MAX_HISTORY_ENTRIES = 50;
public static int END_CHAR = 70;
public static int BEGIN_CHAR = 72;
public static int DEL_CHAR = 126;
public static int DOWN_CHAR = 66;
public static int UP_CHAR = 65;
public static int RIGHT_CHAR = 67;
public static int LEFT_CHAR = 68;
public static int HORIZONTAL_TAB_CHAR = 9;
public static int VERTICAL_TAB_CHAR = 11;
public static int BACKSPACE_CHAR = 127;
public static int NEW_LINE_CHAR = 10;
public static int UNIT_SEPARATOR_CHAR = 31;
protected int currentPos = 0;
protected List<String> history = new ArrayList<String>();
protected String historyBuffer;
protected Reader inStream;
protected PrintStream outStream;
public TTYConsoleReader() {
File file = getHistoryFile(true);
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(file));
String historyEntry = reader.readLine();
while (historyEntry != null) {
history.add(historyEntry);
historyEntry = reader.readLine();
}
if (System.getProperty("file.encoding") != null) {
inStream = new InputStreamReader(System.in, System.getProperty("file.encoding"));
outStream = new PrintStream(System.out, false, System.getProperty("file.encoding"));
} else {
inStream = new InputStreamReader(System.in);
outStream = System.out;
}
} catch (FileNotFoundException fnfe) {
OLogManager.instance().error(this, "History file not found", fnfe, "");
} catch (IOException ioe) {
OLogManager.instance().error(this, "Error reading history file.", ioe, "");
}
}
protected OConsoleApplication console;
public String readLine() {
String consoleInput = "";
try {
StringBuffer buffer = new StringBuffer();
currentPos = 0;
historyBuffer = null;
int historyNum = history.size();
boolean hintedHistory = false;
while (true) {
boolean escape = false;
boolean ctrl = false;
int next = inStream.read();
if (next == 27) {
escape = true;
inStream.read();
next = inStream.read();
}
if (escape) {
if (next == 49) {
inStream.read();
next = inStream.read();
}
if (next == 53) {
ctrl = true;
next = inStream.read();
}
if (ctrl) {
if (next == RIGHT_CHAR) {
currentPos = buffer.indexOf(" ", currentPos) + 1;
if (currentPos == 0)
currentPos = buffer.length();
StringBuffer cleaner = new StringBuffer();
for (int i = 0; i < buffer.length(); i++) {
cleaner.append(" ");
}
rewriteConsole(cleaner, true);
rewriteConsole(buffer, false);
} else if (next == LEFT_CHAR) {
if (currentPos > 1 && currentPos < buffer.length() && buffer.charAt(currentPos - 1) == ' ') {
currentPos = buffer.lastIndexOf(" ", (currentPos - 2)) + 1;
} else {
currentPos = buffer.lastIndexOf(" ", currentPos) + 1;
}
if (currentPos < 0)
currentPos = 0;
StringBuffer cleaner = new StringBuffer();
for (int i = 0; i < buffer.length(); i++) {
cleaner.append(" ");
}
rewriteConsole(cleaner, true);
rewriteConsole(buffer, false);
} else {
}
} else {
if (next == UP_CHAR && !history.isEmpty()) {
if (history.size() > 0) { // UP
StringBuffer cleaner = new StringBuffer();
for (int i = 0; i < buffer.length(); i++) {
cleaner.append(" ");
}
rewriteConsole(cleaner, true);
if (!hintedHistory && (historyNum == history.size() || !buffer.toString().equals(history.get(historyNum)))) {
if (buffer.length() > 0) {
hintedHistory = true;
historyBuffer = buffer.toString();
} else {
historyBuffer = null;
}
}
historyNum = getHintedHistoryIndexUp(historyNum);
if (historyNum > -1) {
buffer = new StringBuffer(history.get(historyNum));
} else {
buffer = new StringBuffer(historyBuffer);
}
currentPos = buffer.length();
rewriteConsole(buffer, false);
// writeHistory(historyNum);
}
} else if (next == DOWN_CHAR && !history.isEmpty()) { // DOWN
if (history.size() > 0) {
StringBuffer cleaner = new StringBuffer();
for (int i = 0; i < buffer.length(); i++) {
cleaner.append(" ");
}
rewriteConsole(cleaner, true);
historyNum = getHintedHistoryIndexDown(historyNum);
if (historyNum == history.size()) {
if (historyBuffer != null) {
buffer = new StringBuffer(historyBuffer);
} else {
buffer = new StringBuffer("");
}
} else {
buffer = new StringBuffer(history.get(historyNum));
}
currentPos = buffer.length();
rewriteConsole(buffer, false);
// writeHistory(historyNum);
}
} else if (next == RIGHT_CHAR) {
if (currentPos < buffer.length()) {
currentPos++;
StringBuffer cleaner = new StringBuffer();
for (int i = 0; i < buffer.length(); i++) {
cleaner.append(" ");
}
rewriteConsole(cleaner, true);
rewriteConsole(buffer, false);
}
} else if (next == LEFT_CHAR) {
if (currentPos > 0) {
currentPos--;
StringBuffer cleaner = new StringBuffer();
for (int i = 0; i < buffer.length(); i++) {
cleaner.append(" ");
}
rewriteConsole(cleaner, true);
rewriteConsole(buffer, false);
}
} else if (next == END_CHAR) {
currentPos = buffer.length();
StringBuffer cleaner = new StringBuffer();
for (int i = 0; i < buffer.length(); i++) {
cleaner.append(" ");
}
rewriteConsole(cleaner, true);
rewriteConsole(buffer, false);
} else if (next == BEGIN_CHAR) {
currentPos = 0;
StringBuffer cleaner = new StringBuffer();
for (int i = 0; i < buffer.length(); i++) {
cleaner.append(" ");
}
rewriteConsole(cleaner, true);
rewriteConsole(buffer, false);
} else {
}
}
} else {
if (next == NEW_LINE_CHAR) {
outStream.println();
break;
} else if (next == BACKSPACE_CHAR) {
if (buffer.length() > 0 && currentPos > 0) {
StringBuffer cleaner = new StringBuffer();
for (int i = 0; i < buffer.length(); i++) {
cleaner.append(" ");
}
buffer.deleteCharAt(currentPos - 1);
currentPos--;
rewriteConsole(cleaner, true);
rewriteConsole(buffer, false);
}
} else if (next == DEL_CHAR) {
if (buffer.length() > 0 && currentPos >= 0 && currentPos < buffer.length()) {
StringBuffer cleaner = new StringBuffer();
for (int i = 0; i < buffer.length(); i++) {
cleaner.append(" ");
}
buffer.deleteCharAt(currentPos);
rewriteConsole(cleaner, true);
rewriteConsole(buffer, false);
}
} else if (next == HORIZONTAL_TAB_CHAR) {
StringBuffer cleaner = new StringBuffer();
for (int i = 0; i < buffer.length(); i++) {
cleaner.append(" ");
}
buffer = writeHint(buffer);
rewriteConsole(cleaner, true);
rewriteConsole(buffer, false);
currentPos = buffer.length();
} else {
if ((next > UNIT_SEPARATOR_CHAR && next < BACKSPACE_CHAR) || next > BACKSPACE_CHAR) {
StringBuffer cleaner = new StringBuffer();
for (int i = 0; i < buffer.length(); i++) {
cleaner.append(" ");
}
if (currentPos == buffer.length()) {
buffer.append((char) next);
} else {
buffer.insert(currentPos, (char) next);
}
currentPos++;
rewriteConsole(cleaner, true);
rewriteConsole(buffer, false);
} else {
outStream.println();
outStream.print(buffer);
}
}
historyNum = history.size();
hintedHistory = false;
}
}
consoleInput = buffer.toString();
history.remove(consoleInput);
history.add(consoleInput);
historyNum = history.size();
writeHistory(historyNum);
} catch (IOException e) {
return null;
}
if (consoleInput.equals("clear")) {
outStream.flush();
for (int i = 0; i < 150; i++) {
outStream.println();
}
outStream.print("\r");
outStream.print("> ");
return readLine();
} else {
return consoleInput;
}
}
private void writeHistory(int historyNum) throws IOException {
if (historyNum <= MAX_HISTORY_ENTRIES) {
File historyFile = getHistoryFile(false);
BufferedWriter writer = new BufferedWriter(new FileWriter(historyFile));
try {
for (String historyEntry : history) {
writer.write(historyEntry);
writer.newLine();
}
} finally {
writer.flush();
writer.close();
}
} else {
File historyFile = getHistoryFile(false);
BufferedWriter writer = new BufferedWriter(new FileWriter(historyFile));
try {
for (String historyEntry : history.subList(historyNum - MAX_HISTORY_ENTRIES - 1, historyNum - 1)) {
writer.write(historyEntry);
writer.newLine();
}
} finally {
writer.flush();
writer.close();
}
}
}
private StringBuffer writeHint(StringBuffer buffer) {
List<String> suggestions = new ArrayList<String>();
for (Method method : console.getConsoleMethods()) {
String command = OConsoleApplication.getClearName(method.getName());
if (command.startsWith(buffer.toString())) {
suggestions.add(command);
}
}
if (suggestions.size() > 1) {
StringBuffer hintBuffer = new StringBuffer();
String[] bufferComponents = buffer.toString().split(" ");
String[] suggestionComponents;
Set<String> bufferPart = new HashSet<String>();
String suggestionPart = null;
boolean appendSpace = true;
for (String suggestion : suggestions) {
suggestionComponents = suggestion.split(" ");
hintBuffer.append("* " + suggestion + " ");
hintBuffer.append("\n");
suggestionPart = "";
if (bufferComponents.length == 0 || buffer.length() == 0) {
suggestionPart = null;
} else if (bufferComponents.length == 1) {
bufferPart.add(suggestionComponents[0]);
if (bufferPart.size() > 1) {
suggestionPart = bufferComponents[0];
appendSpace = false;
} else {
suggestionPart = suggestionComponents[0];
}
} else {
bufferPart.add(suggestionComponents[bufferComponents.length - 1]);
if (bufferPart.size() > 1) {
for (int i = 0; i < bufferComponents.length; i++) {
suggestionPart += bufferComponents[i];
if (i < (bufferComponents.length - 1)) {
suggestionPart += " ";
}
appendSpace = false;
}
} else {
for (int i = 0; i < suggestionComponents.length; i++) {
suggestionPart += suggestionComponents[i] + " ";
}
}
}
}
if (suggestionPart != null) {
buffer = new StringBuffer();
buffer.append(suggestionPart);
if (appendSpace) {
buffer.append(" ");
}
}
hintBuffer.append("-----------------------------\n");
rewriteHintConsole(hintBuffer);
} else if (suggestions.size() > 0) {
buffer = new StringBuffer();
buffer.append(suggestions.get(0));
buffer.append(" ");
}
return buffer;
}
public void setConsole(OConsoleApplication iConsole) {
console = iConsole;
}
public OConsoleApplication getConsole() {
return console;
}
private void rewriteConsole(StringBuffer buffer, boolean cleaner) {
outStream.print("\r");
outStream.print("> ");
if (currentPos < buffer.length() && buffer.length() > 0 && !cleaner) {
outStream.print("\033[0m" + buffer.substring(0, currentPos) + "\033[0;30;47m" + buffer.substring(currentPos, currentPos + 1)
+ "\033[0m" + buffer.substring(currentPos + 1) + "\033[0m");
} else {
outStream.print(buffer);
}
}
private void rewriteHintConsole(StringBuffer buffer) {
outStream.print("\r");
outStream.print(buffer);
}
private int getHintedHistoryIndexUp(int historyNum) {
if (historyBuffer != null && !historyBuffer.equals("")) {
for (int i = (historyNum - 1); i >= 0; i--) {
if (history.get(i).startsWith(historyBuffer)) {
return i;
}
}
return -1;
}
return historyNum > 0 ? (historyNum - 1) : 0;
}
private int getHintedHistoryIndexDown(int historyNum) throws IOException {
if (historyBuffer != null && !historyBuffer.equals("")) {
for (int i = historyNum + 1; i < history.size(); i++) {
if (history.get(i).startsWith(historyBuffer)) {
return i;
}
}
return history.size();
}
return historyNum < history.size() ? (historyNum + 1) : history.size();
}
private File getHistoryFile(boolean read) {
File file = new File(HISTORY_FILE_NAME);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException ioe) {
OLogManager.instance().error(this, "Error creating history file.", ioe, "");
}
} else if (!read) {
file.delete();
try {
file.createNewFile();
} catch (IOException ioe) {
OLogManager.instance().error(this, "Error creating history file.", ioe, "");
}
}
return file;
}
}
| fedgehog/Orient | commons/src/main/java/com/orientechnologies/common/console/TTYConsoleReader.java | Java | apache-2.0 | 14,391 |
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/bigquery/connection/v1/connection.proto
namespace Google\Cloud\BigQuery\Connection\V1;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
* The request for [ConnectionService.DeleteConnectionRequest][].
*
* Generated from protobuf message <code>google.cloud.bigquery.connection.v1.DeleteConnectionRequest</code>
*/
class DeleteConnectionRequest extends \Google\Protobuf\Internal\Message
{
/**
* Required. Name of the deleted connection, for example:
* `projects/{project_id}/locations/{location_id}/connections/{connection_id}`
*
* Generated from protobuf field <code>string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {</code>
*/
private $name = '';
/**
* Constructor.
*
* @param array $data {
* Optional. Data for populating the Message object.
*
* @type string $name
* Required. Name of the deleted connection, for example:
* `projects/{project_id}/locations/{location_id}/connections/{connection_id}`
* }
*/
public function __construct($data = NULL) {
\GPBMetadata\Google\Cloud\Bigquery\Connection\V1\Connection::initOnce();
parent::__construct($data);
}
/**
* Required. Name of the deleted connection, for example:
* `projects/{project_id}/locations/{location_id}/connections/{connection_id}`
*
* Generated from protobuf field <code>string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {</code>
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Required. Name of the deleted connection, for example:
* `projects/{project_id}/locations/{location_id}/connections/{connection_id}`
*
* Generated from protobuf field <code>string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {</code>
* @param string $var
* @return $this
*/
public function setName($var)
{
GPBUtil::checkString($var, True);
$this->name = $var;
return $this;
}
}
| googleapis/google-cloud-php-bigquery-connection | src/V1/DeleteConnectionRequest.php | PHP | apache-2.0 | 2,319 |
/**************************************************************************
*
* Gluewine Console Module
*
* Copyright (C) 2013 FKS bvba http://www.fks.be/
*
* 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.gluewine.console;
/**
* A reponse that failed due to a syntax exception.
*
* @author fks/Serge de Schaetzen
*
*/
public class SyntaxResponse extends Response
{
// ===========================================================================
/** The serial uid. */
private static final long serialVersionUID = -7101539852928081970L;
/** The command that failed. */
private CLICommand cmd = null;
// ===========================================================================
/**
* Creates an instance.
*
* @param output The output of the command.
* @param cmd The command that failed.
* @param routed Whether the output is routed or not.
* @param batch Whether the command was entered from batch mode.
* @param interactive Whether the option values were entered interactively.
*/
public SyntaxResponse(String output, CLICommand cmd, boolean routed, boolean batch, boolean interactive)
{
super(output, routed, batch, interactive);
this.cmd = cmd;
}
// ===========================================================================
/**
* Returns the command that failed.
*
* @return The command that failed.
*/
public CLICommand getCommand()
{
return cmd;
}
}
| sergeds/Gluewine | imp/src/java/org/gluewine/console/SyntaxResponse.java | Java | apache-2.0 | 2,122 |
<?php
/**
* File containing the ezcTemplateMinusAssignmentOperatorTstNode class
*
* 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 Template
* @version //autogen//
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @access private
*/
/**
* Fetching of property value in an expression.
*
* @package Template
* @version //autogen//
* @access private
*/
class ezcTemplateMinusAssignmentOperatorTstNode extends ezcTemplateModifyingOperatorTstNode
{
/**
*
* @param ezcTemplateSource $source
* @param ezcTemplateCursor $start
* @param ezcTemplateCursor $end
*/
public function __construct( ezcTemplateSourceCode $source, /*ezcTemplateCursor*/ $start, /*ezcTemplateCursor*/ $end )
{
parent::__construct( $source, $start, $end,
1, 3, self::RIGHT_ASSOCIATIVE,
'-=' );
}
}
?>
| ezpublishlegacy/Template | src/syntax_trees/tst/nodes/minus_assignment_operator.php | PHP | apache-2.0 | 1,686 |
/*
* 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.hyracks.algebricks.core.algebra.operators.physical;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalOperator;
import org.apache.hyracks.algebricks.core.algebra.properties.IPhysicalPropertiesVector;
import org.apache.hyracks.algebricks.core.algebra.properties.PhysicalRequirements;
public abstract class AbstractScanPOperator extends AbstractPhysicalOperator {
@Override
public PhysicalRequirements getRequiredPropertiesForChildren(ILogicalOperator op,
IPhysicalPropertiesVector reqdByParent) {
return emptyUnaryRequirements();
}
@Override
public boolean expensiveThanMaterialization() {
return false;
}
}
| waans11/incubator-asterixdb-hyracks | algebricks/algebricks-core/src/main/java/org/apache/hyracks/algebricks/core/algebra/operators/physical/AbstractScanPOperator.java | Java | apache-2.0 | 1,503 |
using System.ComponentModel.DataAnnotations;
namespace Identity.Models.ManageViewModels
{
public class ChangePasswordViewModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
public string StatusMessage { get; set; }
}
}
| raisr/Indevio | src/indevio.Server/Models/ManageViewModels/ChangePasswordViewModel.cs | C# | apache-2.0 | 871 |
// Copyright 2014 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 com.google.devtools.build.lib.ideinfo;
import static com.google.common.collect.Iterables.transform;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.io.ByteSource;
import com.google.devtools.build.lib.actions.ActionOwner;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.Root;
import com.google.devtools.build.lib.analysis.Aspect;
import com.google.devtools.build.lib.analysis.Aspect.Builder;
import com.google.devtools.build.lib.analysis.ConfiguredAspectFactory;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.actions.BinaryFileWriteAction;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.ideinfo.androidstudio.AndroidStudioIdeInfo.AndroidSdkRuleInfo;
import com.google.devtools.build.lib.ideinfo.androidstudio.AndroidStudioIdeInfo.ArtifactLocation;
import com.google.devtools.build.lib.ideinfo.androidstudio.AndroidStudioIdeInfo.JavaRuleIdeInfo;
import com.google.devtools.build.lib.ideinfo.androidstudio.AndroidStudioIdeInfo.LibraryArtifact;
import com.google.devtools.build.lib.ideinfo.androidstudio.AndroidStudioIdeInfo.RuleIdeInfo;
import com.google.devtools.build.lib.ideinfo.androidstudio.AndroidStudioIdeInfo.RuleIdeInfo.Kind;
import com.google.devtools.build.lib.packages.AspectDefinition;
import com.google.devtools.build.lib.packages.AspectParameters;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.Type;
import com.google.devtools.build.lib.rules.android.AndroidSdkProvider;
import com.google.devtools.build.lib.rules.java.JavaExportsProvider;
import com.google.devtools.build.lib.rules.java.JavaRuleOutputJarsProvider;
import com.google.devtools.build.lib.rules.java.JavaSourceInfoProvider;
import com.google.devtools.build.lib.syntax.Label;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.protobuf.MessageLite;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;
import javax.annotation.Nullable;
/**
* Generates ide-build information for Android Studio.
*/
public class AndroidStudioInfoAspect implements ConfiguredAspectFactory {
public static final String NAME = "AndroidStudioInfoAspect";
// Output groups.
public static final String IDE_RESOLVE = "ide-resolve";
public static final String IDE_BUILD = "ide-build";
// File suffixes.
public static final String ASWB_BUILD_SUFFIX = ".aswb-build";
public static final Function<Label, String> LABEL_TO_STRING = new Function<Label, String>() {
@Nullable
@Override
public String apply(Label label) {
return label.toString();
}
};
@Override
public AspectDefinition getDefinition() {
return new AspectDefinition.Builder(NAME)
.requireProvider(JavaSourceInfoProvider.class)
.attributeAspect("deps", AndroidStudioInfoAspect.class)
.build();
}
@Override
public Aspect create(ConfiguredTarget base, RuleContext ruleContext,
AspectParameters parameters) {
Aspect.Builder builder = new Builder(NAME);
// Collect ide build files and calculate dependencies.
NestedSetBuilder<Label> transitiveDependenciesBuilder = NestedSetBuilder.stableOrder();
NestedSetBuilder<Label> dependenciesBuilder = NestedSetBuilder.stableOrder();
NestedSetBuilder<Artifact> ideBuildFilesBuilder = NestedSetBuilder.stableOrder();
// todo(dslomov,tomlu): following current build info logic, this code enumerates dependencies
// directly by iterating over deps attribute. The more robust way to do this might be
// to iterate classpath as provided to build action.
if (ruleContext.attributes().has("deps", Type.LABEL_LIST)) {
Iterable<AndroidStudioInfoFilesProvider> androidStudioInfoFilesProviders =
ruleContext.getPrerequisites("deps", Mode.TARGET, AndroidStudioInfoFilesProvider.class);
for (AndroidStudioInfoFilesProvider depProvider : androidStudioInfoFilesProviders) {
ideBuildFilesBuilder.addTransitive(depProvider.getIdeBuildFiles());
transitiveDependenciesBuilder.addTransitive(depProvider.getTransitiveDependencies());
}
List<? extends TransitiveInfoCollection> deps =
ruleContext.getPrerequisites("deps", Mode.TARGET);
for (TransitiveInfoCollection dep : deps) {
dependenciesBuilder.add(dep.getLabel());
}
Iterable<JavaExportsProvider> javaExportsProviders = ruleContext
.getPrerequisites("deps", Mode.TARGET, JavaExportsProvider.class);
for (JavaExportsProvider javaExportsProvider : javaExportsProviders) {
dependenciesBuilder.addTransitive(javaExportsProvider.getTransitiveExports());
}
}
NestedSet<Label> directDependencies = dependenciesBuilder.build();
transitiveDependenciesBuilder.addTransitive(directDependencies);
NestedSet<Label> transitiveDependencies = transitiveDependenciesBuilder.build();
RuleIdeInfo.Kind ruleKind = getRuleKind(ruleContext.getRule(), base);
if (ruleKind != RuleIdeInfo.Kind.UNRECOGNIZED) {
Artifact ideBuildFile =
createIdeBuildArtifact(base, ruleContext, ruleKind,
directDependencies,
transitiveDependencies);
ideBuildFilesBuilder.add(ideBuildFile);
}
NestedSet<Artifact> ideBuildFiles = ideBuildFilesBuilder.build();
builder
.addOutputGroup(IDE_BUILD, ideBuildFiles)
.addProvider(
AndroidStudioInfoFilesProvider.class,
new AndroidStudioInfoFilesProvider(ideBuildFiles, transitiveDependencies));
return builder.build();
}
private static AndroidSdkRuleInfo makeAndroidSdkRuleInfo(RuleContext ruleContext,
AndroidSdkProvider provider) {
AndroidSdkRuleInfo.Builder sdkInfoBuilder = AndroidSdkRuleInfo.newBuilder();
Path androidSdkDirectory = provider.getAndroidJar().getPath().getParentDirectory();
sdkInfoBuilder.setAndroidSdkPath(androidSdkDirectory.toString());
Root genfilesDirectory = ruleContext.getConfiguration().getGenfilesDirectory();
sdkInfoBuilder.setGenfilesPath(genfilesDirectory.getPath().toString());
Path binfilesPath = ruleContext.getConfiguration().getBinDirectory().getPath();
sdkInfoBuilder.setBinPath(binfilesPath.toString());
return sdkInfoBuilder.build();
}
private Artifact createIdeBuildArtifact(
ConfiguredTarget base,
RuleContext ruleContext,
Kind ruleKind,
NestedSet<Label> directDependencies, NestedSet<Label> transitiveDependencies) {
PathFragment ideBuildFilePath = getOutputFilePath(base, ruleContext);
Root genfilesDirectory = ruleContext.getConfiguration().getGenfilesDirectory();
Artifact ideBuildFile =
ruleContext
.getAnalysisEnvironment()
.getDerivedArtifact(ideBuildFilePath, genfilesDirectory);
RuleIdeInfo.Builder outputBuilder = RuleIdeInfo.newBuilder();
outputBuilder.setLabel(base.getLabel().toString());
outputBuilder.setBuildFile(
ruleContext
.getRule()
.getPackage()
.getBuildFile()
.getPath()
.toString());
outputBuilder.setKind(ruleKind);
outputBuilder.addAllDependencies(transform(directDependencies, LABEL_TO_STRING));
outputBuilder.addAllTransitiveDependencies(transform(transitiveDependencies, LABEL_TO_STRING));
if (ruleKind == Kind.JAVA_LIBRARY
|| ruleKind == Kind.JAVA_IMPORT
|| ruleKind == Kind.JAVA_TEST
|| ruleKind == Kind.JAVA_BINARY) {
outputBuilder.setJavaRuleIdeInfo(makeJavaRuleIdeInfo(base));
} else if (ruleKind == Kind.ANDROID_SDK) {
outputBuilder.setAndroidSdkRuleInfo(
makeAndroidSdkRuleInfo(ruleContext, base.getProvider(AndroidSdkProvider.class)));
}
final RuleIdeInfo ruleIdeInfo = outputBuilder.build();
ruleContext.registerAction(
makeProtoWriteAction(ruleContext.getActionOwner(), ruleIdeInfo, ideBuildFile));
return ideBuildFile;
}
private static BinaryFileWriteAction makeProtoWriteAction(
ActionOwner actionOwner, final MessageLite message, Artifact artifact) {
return new BinaryFileWriteAction(
actionOwner,
artifact,
new ByteSource() {
@Override
public InputStream openStream() throws IOException {
return message.toByteString().newInput();
}
},
/*makeExecutable =*/ false);
}
private static ArtifactLocation makeArtifactLocation(Artifact artifact) {
return ArtifactLocation.newBuilder()
.setRootPath(artifact.getRoot().getPath().toString())
.setRelativePath(artifact.getRootRelativePathString())
.build();
}
private static JavaRuleIdeInfo makeJavaRuleIdeInfo(ConfiguredTarget base) {
JavaRuleIdeInfo.Builder builder = JavaRuleIdeInfo.newBuilder();
JavaRuleOutputJarsProvider outputJarsProvider =
base.getProvider(JavaRuleOutputJarsProvider.class);
if (outputJarsProvider != null) {
// java_library
collectJarsFromOutputJarsProvider(builder, outputJarsProvider);
} else {
JavaSourceInfoProvider provider = base.getProvider(JavaSourceInfoProvider.class);
if (provider != null) {
// java_import
collectJarsFromSourceInfoProvider(builder, provider);
}
}
Collection<Artifact> sourceFiles = getSources(base);
for (Artifact sourceFile : sourceFiles) {
builder.addSources(makeArtifactLocation(sourceFile));
}
return builder.build();
}
private static void collectJarsFromSourceInfoProvider(
JavaRuleIdeInfo.Builder builder, JavaSourceInfoProvider provider) {
Collection<Artifact> sourceJarsForJarFiles = provider.getSourceJarsForJarFiles();
// For java_import rule, we always have only one source jar specified.
// The intent is that that source jar provides sources for all imported jars,
// so we reflect that intent, adding that jar to all LibraryArtifacts we produce
// for java_import rule. We should consider supporting
// library=<collection of jars>+<collection of srcjars>
// mode in our AndroidStudio plugin (Android Studio itself supports that).
Artifact sourceJar;
if (sourceJarsForJarFiles.size() > 0) {
sourceJar = sourceJarsForJarFiles.iterator().next();
} else {
sourceJar = null;
}
for (Artifact artifact : provider.getJarFiles()) {
LibraryArtifact.Builder libraryBuilder = LibraryArtifact.newBuilder();
libraryBuilder.setJar(makeArtifactLocation(artifact));
if (sourceJar != null) {
libraryBuilder.setSourceJar(makeArtifactLocation(sourceJar));
}
builder.addJars(libraryBuilder.build());
}
}
private static void collectJarsFromOutputJarsProvider(
JavaRuleIdeInfo.Builder builder, JavaRuleOutputJarsProvider outputJarsProvider) {
LibraryArtifact.Builder jarsBuilder = LibraryArtifact.newBuilder();
Artifact classJar = outputJarsProvider.getClassJar();
if (classJar != null) {
jarsBuilder.setJar(makeArtifactLocation(classJar));
}
Artifact srcJar = outputJarsProvider.getSrcJar();
if (srcJar != null) {
jarsBuilder.setSourceJar(makeArtifactLocation(srcJar));
}
if (jarsBuilder.hasJar() || jarsBuilder.hasSourceJar()) {
builder.addJars(jarsBuilder.build());
}
LibraryArtifact.Builder genjarsBuilder = LibraryArtifact.newBuilder();
Artifact genClassJar = outputJarsProvider.getGenClassJar();
if (genClassJar != null) {
genjarsBuilder.setJar(makeArtifactLocation(genClassJar));
}
Artifact gensrcJar = outputJarsProvider.getGensrcJar();
if (gensrcJar != null) {
genjarsBuilder.setSourceJar(makeArtifactLocation(gensrcJar));
}
if (genjarsBuilder.hasJar() || genjarsBuilder.hasSourceJar()) {
builder.addGeneratedJars(genjarsBuilder.build());
}
}
private static Collection<Artifact> getSources(ConfiguredTarget base) {
// Calculate source files.
JavaSourceInfoProvider sourceInfoProvider = base.getProvider(JavaSourceInfoProvider.class);
return sourceInfoProvider != null
? sourceInfoProvider.getSourceFiles()
: ImmutableList.<Artifact>of();
}
private PathFragment getOutputFilePath(ConfiguredTarget base, RuleContext ruleContext) {
PathFragment packagePathFragment =
ruleContext.getLabel().getPackageIdentifier().getPathFragment();
String name = base.getLabel().getName();
return new PathFragment(packagePathFragment, new PathFragment(name + ASWB_BUILD_SUFFIX));
}
private RuleIdeInfo.Kind getRuleKind(Rule rule, ConfiguredTarget base) {
RuleIdeInfo.Kind kind;
String ruleClassName = rule.getRuleClassObject().getName();
if ("java_library".equals(ruleClassName)) {
kind = RuleIdeInfo.Kind.JAVA_LIBRARY;
} else if ("java_import".equals(ruleClassName)) {
kind = Kind.JAVA_IMPORT;
} else if ("java_test".equals(ruleClassName)) {
kind = Kind.JAVA_TEST;
} else if ("java_binary".equals(ruleClassName)) {
kind = Kind.JAVA_BINARY;
} else if (base.getProvider(AndroidSdkProvider.class) != null) {
kind = RuleIdeInfo.Kind.ANDROID_SDK;
} else {
kind = RuleIdeInfo.Kind.UNRECOGNIZED;
}
return kind;
}
}
| joshua0pang/bazel | src/main/java/com/google/devtools/build/lib/ideinfo/AndroidStudioInfoAspect.java | Java | apache-2.0 | 14,348 |
export enum ManifestSource {
TEXT = 'text',
ARTIFACT = 'artifact',
}
| spinnaker/deck | packages/kubernetes/src/manifest/ManifestSource.ts | TypeScript | apache-2.0 | 73 |
/*
* 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.manifoldcf.agents.output.solr;
import org.apache.solr.client.solrj.impl.LBHttpSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.BinaryResponseParser;
import org.apache.solr.client.solrj.request.RequestWriter;
import org.apache.solr.client.solrj.*;
import java.net.MalformedURLException;
import org.apache.http.client.HttpClient;
import java.util.Set;
/** This class overrides and somewhat changes the behavior of the
* SolrJ LBHttpSolrServer class. This is so it instantiates our modified
* HttpSolrServer class, so that multipart forms work.
*/
public class ModifiedLBHttpSolrClient extends LBHttpSolrClient
{
private final HttpClient httpClient;
private final ResponseParser parser;
private final boolean allowCompression;
public ModifiedLBHttpSolrClient(boolean allowCompression, String... solrServerUrls) throws MalformedURLException {
this(null, allowCompression, solrServerUrls);
}
/** The provided httpClient should use a multi-threaded connection manager */
public ModifiedLBHttpSolrClient(HttpClient httpClient, boolean allowCompression, String... solrServerUrl)
throws MalformedURLException {
this(httpClient, new BinaryResponseParser(), allowCompression, solrServerUrl);
}
/** The provided httpClient should use a multi-threaded connection manager */
public ModifiedLBHttpSolrClient(HttpClient httpClient, ResponseParser parser, boolean allowCompression, String... solrServerUrl)
throws MalformedURLException {
super(httpClient, parser, solrServerUrl);
this.httpClient = httpClient;
this.parser = parser;
this.allowCompression = allowCompression;
}
@Override
protected HttpSolrClient makeSolrClient(String server) {
HttpSolrClient client = new ModifiedHttpSolrClient(server, httpClient, parser, allowCompression);
if (getRequestWriter() != null) {
client.setRequestWriter(getRequestWriter());
}
if (getQueryParams() != null) {
client.setQueryParams(getQueryParams());
}
return client;
}
}
| apache/manifoldcf | connectors/solr/connector/src/main/java/org/apache/manifoldcf/agents/output/solr/ModifiedLBHttpSolrClient.java | Java | apache-2.0 | 2,906 |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class NamedAndOptionalTests : CompilingTestBase
{
[Fact]
public void Test13984()
{
string source = @"
using System;
class Program
{
static void Main() { }
static void M(DateTime da = new DateTime(2012, 6, 22),
decimal d = new decimal(5),
int i = new int())
{
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.VerifyDiagnostics(
// (6,33): error CS1736: Default parameter value for 'da' must be a compile-time constant
// static void M(DateTime da = new DateTime(2012, 6, 22),
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new DateTime(2012, 6, 22)").WithArguments("da"),
// (7,31): error CS1736: Default parameter value for 'd' must be a compile-time constant
// decimal d = new decimal(5),
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new decimal(5)").WithArguments("d"));
}
[Fact]
public void Test13861()
{
// * There are two decimal constant attribute constructors; we should honour both of them.
// * Using named arguments to re-order the arguments must not change the value of the constant.
string source = @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
class Program
{
public static void Foo1([Optional][DecimalConstant(0, 0, low: (uint)100, mid: (uint)0, hi: (uint)0)] decimal i)
{
System.Console.Write(i);
}
public static void Foo2([Optional][DecimalConstant(0, 0, 0, 0, 200)] decimal i)
{
System.Console.Write(i);
}
static void Main(string[] args)
{
Foo1();
Foo2();
}
}";
string expected = "100200";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
public void TestNamedAndOptionalParamsInCtors()
{
string source = @"
class Alpha
{
public Alpha(int x = 123) { }
}
class Bravo : Alpha
{ // See bug 7846.
// This should be legal; the generated ctor for Bravo should call base(123)
}
class Charlie : Alpha
{
public Charlie() : base() {}
// This should be legal; should call base(123)
}
class Delta : Alpha
{
public Delta() {}
// This should be legal; should call base(123)
}
abstract class Echo
{
protected Echo(int x = 123) {}
}
abstract class Foxtrot : Echo
{
}
abstract class Hotel : Echo
{
protected Hotel() {}
}
abstract class Golf : Echo
{
protected Golf() : base() {}
}
";
CreateCompilationWithMscorlib(source).VerifyDiagnostics();
}
[Fact]
public void TestNamedAndOptionalParamsErrors()
{
string source = @"
class Base
{
public virtual void Foo(int reqParam1,
int optParam1 = 0,
int optParam2 = default(int),
int optParam3 = new int(),
string optParam4 = null,
double optParam5 = 128L)
{
}
}
class Middle : Base
{
//override and change the parameters names
public override void Foo(int reqChParam1,
int optChParam1 = 0,
int optChParam2 = default(int),
int optChParam3 = new int(),
string optChParam4 = null,
double optChParam5 = 128L)
{
}
}
class C : Middle
{
public void Q(params int[] x) {}
public void M()
{
var c = new C();
// calling child class parameters with base names
// error CS1739: The best overload for 'Foo' does not have a parameter named 'optParam3'
c.Foo(optParam3: 333, reqParam1: 111 , optParam2: 222, optParam1: 1111);
// error CS1738: Named argument specifications must appear after all fixed arguments have been specified
c.Foo(optArg1: 3333, 11111);
}
}";
CreateCompilationWithMscorlib(source).VerifyDiagnostics(
// (37,15): error CS1739: The best overload for 'Foo' does not have a parameter named 'optParam3'
// c.Foo(optParam3: 333, reqParam1: 111 , optParam2: 222, optParam1: 1111);
Diagnostic(ErrorCode.ERR_BadNamedArgument, "optParam3").WithArguments("Foo", "optParam3").WithLocation(37, 15),
// (39,30): error CS1738: Named argument specifications must appear after all fixed arguments have been specified
// c.Foo(optArg1: 3333, 11111);
Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "11111").WithLocation(39, 30));
}
[Fact]
public void TestNamedAndOptionalParamsErrors2()
{
string source = @"
class C
{
//error CS1736
public void M(string s = new string('c',5)) {}
}";
CreateCompilationWithMscorlib(source).VerifyDiagnostics(
// (5,30): error CS1736: Default parameter value for 's' must be a compile-time constant
// public void M(string s = new string('c',5)) {}
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new string('c',5)").WithArguments("s").WithLocation(5, 30));
}
[Fact]
public void TestNamedAndOptionalParamsErrors3()
{
// Here we cannot report that "no overload of M takes two arguments" because of course
// M(1, 2) is legal. We cannot report that any argument does not correspond to a formal;
// all of them do. We cannot report that named arguments precede positional arguments.
// We cannot report that any argument is not convertible to its corresponding formal;
// all of them are convertible. The only error we can report here is that a formal
// parameter has no corresponding argument.
string source = @"
class C
{
// CS7036 (ERR_NoCorrespondingArgument)
delegate void F(int fx, int fg, int fz = 123);
C(int cx, int cy, int cz = 123) {}
public static void M(int mx, int my, int mz = 123)
{
F f = null;
f(0, fz : 456);
M(0, mz : 456);
new C(0, cz : 456);
}
}";
CreateCompilationWithMscorlib(source).VerifyDiagnostics(
// (10,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'fg' of 'C.F'
// f(0, fz : 456);
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "f").WithArguments("fg", "C.F").WithLocation(10, 9),
// (11,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'my' of 'C.M(int, int, int)'
// M(0, mz : 456);
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("my", "C.M(int, int, int)").WithLocation(11, 9),
// (12,13): error CS7036: There is no argument given that corresponds to the required formal parameter 'cy' of 'C.C(int, int, int)'
// new C(0, cz : 456);
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("cy", "C.C(int, int, int)").WithLocation(12, 13));
}
[Fact]
public void TestNamedAndOptionalParamsCrazy()
{
// This was never supposed to work and the spec does not require it, but
// nevertheless, the native compiler allows this:
const string source = @"
class C
{
static void C(int q = 10, params int[] x) {}
static int X() { return 123; }
static int Q() { return 345; }
static void M()
{
C(x:X(), q:Q());
}
}";
// and so Roslyn does too. It seems likely that someone has taken a dependency
// on the bad pattern.
CreateCompilationWithMscorlib(source).VerifyDiagnostics(
// (4,15): error CS0542: 'C': member names cannot be the same as their enclosing type
// static void C(int q = 10, params int[] x) {}
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "C").WithArguments("C").WithLocation(4, 15));
}
[Fact]
public void TestNamedAndOptionalParamsCrazyError()
{
// Fortunately, however, this is still illegal:
const string source = @"
class C
{
static void C(int q = 10, params int[] x) {}
static void M()
{
C(1, 2, 3, x:4);
}
}";
CreateCompilationWithMscorlib(source).VerifyDiagnostics(
// (4,15): error CS0542: 'C': member names cannot be the same as their enclosing type
// static void C(int q = 10, params int[] x) {}
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "C").WithArguments("C").WithLocation(4, 15),
// (7,16): error CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given
// C(1, 2, 3, x:4);
Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "x").WithArguments("x").WithLocation(7, 16));
}
[Fact]
public void TestNamedAndOptionalParamsBasic()
{
string source = @"
using System;
public enum E
{
zero,
one,
two,
three
}
public enum ELong : long
{
zero,
one,
two,
three
}
public class EnumDefaultValues
{
public static void Run()
{
var x = new EnumDefaultValues();
x.M();
}
void M(
E e1 = 0,
E e2 = default(E),
E e3 = E.zero,
E e4 = E.one,
E? ne1 = 0,
E? ne2 = default(E),
E? ne3 = E.zero,
E? ne4 = E.one,
E? ne5 = null,
E? ne6 = default(E?),
ELong el1 = 0,
ELong el2 = default(ELong),
ELong el3 = ELong.zero,
ELong el4 = ELong.one,
ELong? nel1 = 0,
ELong? nel2 = default(ELong),
ELong? nel3 = ELong.zero,
ELong? nel4 = ELong.one,
ELong? nel5 = null,
ELong? nel6 = default(ELong?)
)
{
Show(e1);
Show(e2);
Show(e3);
Show(e4);
Show(ne1);
Show(ne2);
Show(ne3);
Show(ne4);
Show(ne5);
Show(ne6);
Show(el1);
Show(el2);
Show(el3);
Show(el4);
Show(nel1);
Show(nel2);
Show(nel3);
Show(nel4);
Show(nel5);
Show(nel6);
}
static void Show<T>(T t)
{
object o = t;
Console.WriteLine(""{0}: {1}"", typeof(T), o != null ? o : ""<null>"");
}
}
struct Sierra
{
public Alpha alpha;
public Bravo bravo;
public int i;
public Sierra(Alpha alpha, Bravo bravo, int i)
{
this.alpha = alpha;
this.bravo = bravo;
this.i = i;
}
}
class Alpha
{
public virtual int Mike(int xray)
{
return xray;
}
}
class Bravo : Alpha
{
public override int Mike(int yankee)
{
return yankee;
}
}
class Charlie : Bravo
{
void Foxtrot(
int xray = 10,
string yankee = ""sam"")
{
Console.WriteLine(""Foxtrot: xray={0} yankee={1}"", xray, yankee);
}
void Quebec(
int xray,
int yankee = 10,
int zulu = 11)
{
Console.WriteLine(""Quebec: xray={0} yankee={1} zulu={2}"", xray, yankee, zulu);
}
void OutRef(
out int xray,
ref int yankee)
{
xray = 0;
yankee = 0;
}
void ParamArray(params int[] xray)
{
Console.WriteLine(""ParamArray: xray={0}"", string.Join<int>("","", xray));
}
void ParamArray2(
int yankee = 10,
params int[] xray)
{
Console.WriteLine(""ParamArray2: yankee={0} xray={1}"", yankee, string.Join<int>("","", xray));
}
void Zeros(
int xray = 0,
int? yankee = 0,
int? zulu = null,
Charlie charlie = null)
{
Console.WriteLine(""Zeros: xray={0} yankee={1} zulu={2} charlie={3}"",
xray,
yankee == null ? ""null"" : yankee.ToString(),
zulu == null ? ""null"" : zulu.ToString(),
charlie == null ? ""null"" : charlie.ToString() );
}
void OtherDefaults(
string str = default(string),
Alpha alpha = default(Alpha),
Bravo bravo = default(Bravo),
int i = default(int),
Sierra sierra = default(Sierra))
{
Console.WriteLine(""OtherDefaults: str={0} alpha={1} bravo={2} i={3} sierra={4}"",
str == null ? ""null"" : str,
alpha == null ? ""null"" : alpha.ToString(),
bravo == null ? ""null"" : bravo.ToString(),
i,
sierra.alpha == null && sierra.bravo == null && sierra.i == 0 ? ""default(Sierra)"" : sierra.ToString());
}
int Bar()
{
Console.WriteLine(""Bar"");
return 96;
}
string Baz()
{
Console.WriteLine(""Baz"");
return ""Baz"";
}
void BasicOptionalTests()
{
Console.WriteLine(""BasicOptional"");
Foxtrot(0);
Foxtrot();
ParamArray(1, 2, 3);
Zeros();
OtherDefaults();
}
void BasicNamedTests()
{
Console.WriteLine(""BasicNamed"");
// Basic named test.
Foxtrot(yankee: ""test"", xray: 1);
Foxtrot(xray: 1, yankee: ""test"");
// Test to see which execution comes first.
Foxtrot(yankee: Baz(), xray: Bar());
int y = 100;
int x = 100;
OutRef(yankee: ref y, xray: out x);
Console.WriteLine(x);
Console.WriteLine(y);
Charlie c = new Charlie();
ParamArray(xray: 1);
ParamArray(xray: new int[] { 1, 2, 3 });
ParamArray2(xray: 1);
ParamArray2(xray: new int[] { 1, 2, 3 });
ParamArray2(xray: 1, yankee: 20);
ParamArray2(xray: new int[] { 1, 2, 3 }, yankee: 20);
ParamArray2();
}
void BasicNamedAndOptionalTests()
{
Console.WriteLine(""BasicNamedAndOptional"");
Foxtrot(yankee: ""test"");
Foxtrot(xray: 0);
Quebec(1, yankee: 1);
Quebec(1, zulu: 10);
}
void OverrideTest()
{
Console.WriteLine(Mike(yankee: 10));
}
void TypeParamTest<T>() where T : Bravo, new()
{
T t = new T();
Console.WriteLine(t.Mike(yankee: 4));
}
static void Main()
{
Charlie c = new Charlie();
c.BasicOptionalTests();
c.BasicNamedTests();
c.BasicNamedAndOptionalTests();
c.OverrideTest();
c.TypeParamTest<Bravo>();
EnumDefaultValues.Run();
}
}
";
string expected = @"BasicOptional
Foxtrot: xray=0 yankee=sam
Foxtrot: xray=10 yankee=sam
ParamArray: xray=1,2,3
Zeros: xray=0 yankee=0 zulu=null charlie=null
OtherDefaults: str=null alpha=null bravo=null i=0 sierra=default(Sierra)
BasicNamed
Foxtrot: xray=1 yankee=test
Foxtrot: xray=1 yankee=test
Baz
Bar
Foxtrot: xray=96 yankee=Baz
0
0
ParamArray: xray=1
ParamArray: xray=1,2,3
ParamArray2: yankee=10 xray=1
ParamArray2: yankee=10 xray=1,2,3
ParamArray2: yankee=20 xray=1
ParamArray2: yankee=20 xray=1,2,3
ParamArray2: yankee=10 xray=
BasicNamedAndOptional
Foxtrot: xray=10 yankee=test
Foxtrot: xray=0 yankee=sam
Quebec: xray=1 yankee=1 zulu=11
Quebec: xray=1 yankee=10 zulu=10
10
4
E: zero
E: zero
E: zero
E: one
System.Nullable`1[E]: zero
System.Nullable`1[E]: zero
System.Nullable`1[E]: zero
System.Nullable`1[E]: one
System.Nullable`1[E]: <null>
System.Nullable`1[E]: <null>
ELong: zero
ELong: zero
ELong: zero
ELong: one
System.Nullable`1[ELong]: zero
System.Nullable`1[ELong]: zero
System.Nullable`1[ELong]: zero
System.Nullable`1[ELong]: one
System.Nullable`1[ELong]: <null>
System.Nullable`1[ELong]: <null>";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
public void TestNamedAndOptionalParamsOnAttributes()
{
string source = @"
using System;
class MyAttribute : Attribute
{
public MyAttribute(int a = 1, int b = 2, int c = 3)
{
A = a;
B = b;
C = c;
}
public int X;
public int A;
public int B;
public int C;
}
[MyAttribute(4, c:5, X=6)]
class C
{
static void Main()
{
MyAttribute m1 = new MyAttribute();
Console.Write(m1.A); // 1
Console.Write(m1.B); // 2
Console.Write(m1.C); // 3
Console.Write(m1.X); // 0
MyAttribute m2 = new MyAttribute(c: 7);
Console.Write(m2.A); // 1
Console.Write(m2.B); // 2
Console.Write(m2.C); // 7
Console.Write(m2.X); // 0
Type t = typeof(C);
foreach (MyAttribute attr in t.GetCustomAttributes(false))
{
Console.Write(attr.A); // 4
Console.Write(attr.B); // 2
Console.Write(attr.C); // 5
Console.Write(attr.X); // 6
}
}
}";
CompileAndVerify(source, expectedOutput: "123012704256");
}
[Fact]
public void TestNamedAndOptionalParamsOnIndexers()
{
string source = @"
using System;
class D
{
public int this[string s = ""four""] { get { return s.Length; } set { } }
public int this[int x = 2, int y = 5] { get { return x + y; } set { } }
public int this[string str = ""foo"", int i = 13]
{
get { Console.WriteLine(""D.this[str: '{0}', i: {1}].get"", str, i); return i;}
set { Console.WriteLine(""D.this[str: '{0}', i: {1}].set"", str, i); }
}
}
class C
{
int this[int x, int y] { get { return x + y; } set { } }
static void Main()
{
C c = new C();
Console.WriteLine(c[y:10, x:10]);
D d = new D();
Console.WriteLine(d[1]);
Console.WriteLine(d[0,2]);
Console.WriteLine(d[x:2]);
Console.WriteLine(d[x:3, y:0]);
Console.WriteLine(d[y:3, x:2]);
Console.WriteLine(d[""abc""]);
Console.WriteLine(d[s:""12345""]);
d[i:1] = 0;
d[str:""bar""] = 0;
d[i:2, str:""baz""] = 0;
d[str:""bah"", i:3] = 0;
}
}";
string expected = @"20
6
2
7
3
5
3
5
D.this[str: 'foo', i: 1].set
D.this[str: 'bar', i: 13].set
D.this[str: 'baz', i: 2].set
D.this[str: 'bah', i: 3].set";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
public void TestNamedAndOptionalParamsOnPartialMethods()
{
string source = @"
using System;
partial class C
{
static partial void PartialMethod(int x);
}
partial class C
{
static partial void PartialMethod(int y) { Console.WriteLine(y); }
static void Main()
{
// Declaring partial wins.
PartialMethod(x:123);
}
}";
string expected = "123";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
public void TestNamedAndOptionalParamsOnPartialMethodsErrors()
{
string source = @"
using System;
partial class C
{
static partial void PartialMethod(int x);
}
partial class C
{
static partial void PartialMethod(int y) { Console.WriteLine(y); }
static void Main()
{
// Implementing partial loses.
PartialMethod(y:123);
}
}";
CreateCompilationWithMscorlib(source).VerifyDiagnostics(
// (13,23): error CS1739: The best overload for 'PartialMethod' does not have a parameter named 'y'
// PartialMethod(y:123);
Diagnostic(ErrorCode.ERR_BadNamedArgument, "y").WithArguments("PartialMethod", "y")
);
}
[Fact]
public void TestNamedAndOptionalParametersUnsafe()
{
string source = @"
using System;
unsafe class C
{
static void M(
int* x1 = default(int*),
IntPtr x2 = default(IntPtr),
UIntPtr x3 = default(UIntPtr),
int x4 = default(int))
{
}
static void Main()
{
M();
}
}";
// We make an improvement on the native compiler here; we generate default(UIntPtr) and
// default(IntPtr) as "load zero, convert to type", rather than making a stack slot and calling
// init on it.
var c = CompileAndVerify(source, options: TestOptions.UnsafeReleaseDll);
c.VerifyIL("C.Main", @"{
// Code size 13 (0xd)
.maxstack 4
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: ldc.i4.0
IL_0003: conv.i
IL_0004: ldc.i4.0
IL_0005: conv.u
IL_0006: ldc.i4.0
IL_0007: call ""void C.M(int*, System.IntPtr, System.UIntPtr, int)""
IL_000c: ret
}");
}
[WorkItem(528783, "DevDiv")]
[Fact]
public void TestNamedAndOptionalParametersArgumentName()
{
const string text = @"
using System;
namespace NS
{
class Test
{
static void M(sbyte sb = 0, string ss = null) {}
static void Main()
{
M(/*<bind>*/ss/*</bind>*/: ""QC"");
}
}
}
";
var comp = CreateCompilationWithMscorlib(text);
var nodeAndModel = GetBindingNodeAndModel<IdentifierNameSyntax>(comp);
var typeInfo = nodeAndModel.Item2.GetTypeInfo(nodeAndModel.Item1);
// parameter name has no type
Assert.Null(typeInfo.Type);
var symInfo = nodeAndModel.Item2.GetSymbolInfo(nodeAndModel.Item1);
Assert.NotNull(symInfo.Symbol);
Assert.Equal(SymbolKind.Parameter, symInfo.Symbol.Kind);
Assert.Equal("ss", symInfo.Symbol.Name);
}
[WorkItem(542418, "DevDiv")]
[Fact]
public void OptionalValueInvokesInstanceMethod()
{
var source =
@"class C
{
object F() { return null; }
void M1(object value = F()) { }
object M2(object value = M2()) { return null; }
}";
CreateCompilationWithMscorlib(source).VerifyDiagnostics(
// (4,28): error CS1736: Default parameter value for 'value' must be a compile-time constant
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()").WithArguments("value").WithLocation(4, 28),
// (5,30): error CS1736: Default parameter value for 'value' must be a compile-time constant
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M2()").WithArguments("value").WithLocation(5, 30));
}
[Fact]
public void OptionalValueInvokesStaticMethod()
{
var source =
@"class C
{
static object F() { return null; }
static void M1(object value = F()) { }
static object M2(object value = M2()) { return null; }
}";
CreateCompilationWithMscorlib(source).VerifyDiagnostics(
// (4,35): error CS1736: Default parameter value for 'value' must be a compile-time constant
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()").WithArguments("value").WithLocation(4, 35),
// (5,37): error CS1736: Default parameter value for 'value' must be a compile-time constant
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M2()").WithArguments("value").WithLocation(5, 37));
}
[WorkItem(542411, "DevDiv")]
[WorkItem(542365, "DevDiv")]
[Fact]
public void GenericOptionalParameters()
{
var source =
@"class C
{
static void Foo<T>(T t = default(T)) {}
}";
CreateCompilationWithMscorlib(source).VerifyDiagnostics();
}
[WorkItem(542458, "DevDiv")]
[Fact]
public void OptionalValueTypeFromReferencedAssembly()
{
// public struct S{}
// public class C
// {
// public static void Foo(string s, S t = default(S)) {}
// }
string ilSource = @"
// =============== CLASS MEMBERS DECLARATION ===================
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.pack 0
.size 1
} // end of class S
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.method public hidebysig static void Foo(string s,
[opt] valuetype S t) cil managed
{
.param [2] = nullref
// Code size 2 (0x2)
.maxstack 8
IL_0000: nop
IL_0001: ret
} // end of method C::Foo
} // end of class C
";
var source =
@"
public class D
{
public static void Caller()
{
C.Foo("""");
}
}";
CompileWithCustomILSource(source, ilSource);
}
[WorkItem(542867, "DevDiv")]
[Fact]
public void OptionalParameterDeclaredWithAttributes()
{
string source = @"
using System.Runtime.InteropServices;
public class Parent{
public int Foo([Optional]object i = null) {
return 1;
}
public int Bar([DefaultParameterValue(1)]int i = 2) {
return 1;
}
}
class Test{
public static int Main(){
Parent p = new Parent();
return p.Foo();
}
}
";
CreateCompilationWithMscorlib(source, new[] { SystemRef }).VerifyDiagnostics(
// (5,21): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute
Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "Optional"),
// (9,21): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute
Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "DefaultParameterValue"));
}
[WorkItem(10290, "DevDiv_Projects/Roslyn")]
[Fact]
public void OptionalParamOfTypeObject()
{
string source = @"
public class Test
{
public static int M1(object p1 = null) { if (p1 == null) return 0; else return 1; }
public static void Main()
{
System.Console.WriteLine(M1());
}
}
";
CompileAndVerify(source, expectedOutput: "0");
}
[WorkItem(543871, "DevDiv")]
[Fact]
public void RefParameterDeclaredWithOptionalAttribute()
{
// The native compiler produces "CS1501: No overload for method 'Foo' takes 0 arguments."
// Roslyn produces a slightly more informative error message.
string source = @"
using System.Runtime.InteropServices;
public class Parent
{
public static void Foo([Optional] ref int x) {}
static void Main()
{
Foo();
}
}
";
var comp = CreateCompilationWithMscorlib(source, new[] { SystemRef });
comp.VerifyDiagnostics(
// (8,10): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'Parent.Foo(ref int)'
// Foo();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Foo").WithArguments("x", "Parent.Foo(ref int)"));
}
[Fact, WorkItem(544491, "DevDiv")]
public void EnumAsDefaultParameterValue()
{
string source = @"
using System.Runtime.InteropServices;
public enum MyEnum { one, two, three }
public interface IOptionalRef
{
MyEnum MethodRef([In, Out, Optional, DefaultParameterValue(MyEnum.three)] ref MyEnum v);
}
";
CompileAndVerify(source, new[] { SystemRef }).VerifyDiagnostics();
}
[Fact]
public void DefaultParameterValueErrors()
{
string source = @"
using System.Runtime.InteropServices;
public enum I8 : sbyte { v = 1 }
public enum U8 : byte { v = 1 }
public enum I16 : short { v = 1 }
public enum U16 : ushort { v = 1 }
public enum I32 : int { v = 1 }
public enum U32 : uint { v = 1 }
public enum I64 : long { v = 1 }
public enum U64 : ulong { v = 1 }
public class C { }
public delegate void D();
public interface I { }
public struct S {
}
public static class ErrorCases
{
public static void M(
// bool
[Optional][DefaultParameterValue(0)] bool b1,
[Optional][DefaultParameterValue(""hello"")] bool b2,
// integral
[Optional][DefaultParameterValue(12)] sbyte sb1,
[Optional][DefaultParameterValue(""hello"")] byte by1,
// char
[Optional][DefaultParameterValue(""c"")] char ch1,
// float
[Optional][DefaultParameterValue(1.0)] float fl1,
[Optional][DefaultParameterValue(1)] double dbl1,
// enum
[Optional][DefaultParameterValue(0)] I8 i8,
[Optional][DefaultParameterValue(12)] U8 u8,
[Optional][DefaultParameterValue(""hello"")] I16 i16,
// string
[Optional][DefaultParameterValue(5)] string str1,
[Optional][DefaultParameterValue(new int[] { 12 })] string str2,
// reference types
[Optional][DefaultParameterValue(2)] C c1,
[Optional][DefaultParameterValue(""hello"")] C c2,
[DefaultParameterValue(new int[] { 1, 2 })] int[] arr1,
[DefaultParameterValue(null)] int[] arr2,
[DefaultParameterValue(new int[] { 1, 2 })] object arr3,
[DefaultParameterValue(typeof(object))] System.Type type1,
[DefaultParameterValue(null)] System.Type type2,
[DefaultParameterValue(typeof(object))] object type3,
// user defined struct
[DefaultParameterValue(null)] S userStruct1,
[DefaultParameterValue(0)] S userStruct2,
[DefaultParameterValue(""hel"")] S userStruct3,
// null value to non-ref type
[Optional][DefaultParameterValue(null)] bool b3,
// integral
[Optional][DefaultParameterValue(null)] int i2,
// char
[Optional][DefaultParameterValue(null)] char ch2,
// float
[Optional][DefaultParameterValue(null)] float fl2,
// enum
[Optional][DefaultParameterValue(null)] I8 i82
)
{
}
}
";
// NOTE: anywhere dev10 reported CS1909, roslyn reports CS1910.
CreateCompilationWithMscorlib(source, new[] { SystemRef }).VerifyDiagnostics(
// (27,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(0)] bool b1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (28,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue("hello")] bool b2,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (31,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(12)] sbyte sb1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (32,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue("hello")] byte by1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (35,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue("c")] char ch1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (38,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(1.0)] float fl1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (42,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(0)] I8 i8,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (43,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(12)] U8 u8,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (44,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue("hello")] I16 i16,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (47,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(5)] string str1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (48,20): error CS1910: Argument of type 'int[]' is not applicable for the DefaultParameterValue attribute
// [Optional][DefaultParameterValue(new int[] { 12 })] string str2,
Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"),
// (51,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(2)] C c1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (52,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue("hello")] C c2,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (54,10): error CS1910: Argument of type 'int[]' is not applicable for the DefaultParameterValue attribute
// [DefaultParameterValue(new int[] { 1, 2 })] int[] arr1,
Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"),
// NOTE: Roslyn specifically allows this usage (illegal in dev10).
//// (55,10): error CS1909: The DefaultParameterValue attribute is not applicable on parameters of type 'int[]', unless the default value is null
//// [DefaultParameterValue(null)] int[] arr2,
//Diagnostic(ErrorCode.ERR_DefaultValueBadParamType, "DefaultParameterValue").WithArguments("int[]"),
// (56,10): error CS1910: Argument of type 'int[]' is not applicable for the DefaultParameterValue attribute
// [DefaultParameterValue(new int[] { 1, 2 })] object arr3,
Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"),
// (58,10): error CS1910: Argument of type 'System.Type' is not applicable for the DefaultParameterValue attribute
// [DefaultParameterValue(typeof(object))] System.Type type1,
Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("System.Type"),
// NOTE: Roslyn specifically allows this usage (illegal in dev10).
//// (59,10): error CS1909: The DefaultParameterValue attribute is not applicable on parameters of type 'System.Type', unless the default value is null
//// [DefaultParameterValue(null)] System.Type type2,
//Diagnostic(ErrorCode.ERR_DefaultValueBadParamType, "DefaultParameterValue").WithArguments("System.Type"),
// (60,10): error CS1910: Argument of type 'System.Type' is not applicable for the DefaultParameterValue attribute
// [DefaultParameterValue(typeof(object))] object type3,
Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("System.Type"),
// (63,10): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [DefaultParameterValue(null)] S userStruct1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (64,10): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [DefaultParameterValue(0)] S userStruct2,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (65,10): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [DefaultParameterValue("hel")] S userStruct3,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (68,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(null)] bool b3,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (71,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(null)] int i2,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (74,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(null)] char ch2,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (77,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(null)] float fl2,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (80,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(null)] I8 i82
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"));
}
[WorkItem(544440, "DevDiv")]
[ClrOnlyFact]
public void TestBug12768()
{
string sourceDefinitions = @"
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
public class C
{
public static void M1(object x = null)
{
Console.WriteLine(x ?? 1);
}
public static void M2([Optional] object x)
{
Console.WriteLine(x ?? 2);
}
public static void M3([MarshalAs(UnmanagedType.Interface)] object x = null)
{
Console.WriteLine(x ?? 3);
}
public static void M4([MarshalAs(UnmanagedType.Interface)][Optional] object x)
{
Console.WriteLine(x ?? 4);
}
public static void M5([IDispatchConstant] object x = null)
{
Console.WriteLine(x ?? 5);
}
public static void M6([IDispatchConstant] [Optional] object x)
{
Console.WriteLine(x ?? 6);
}
public static void M7([IDispatchConstant] [MarshalAs(UnmanagedType.Interface)] object x = null)
{
Console.WriteLine(x ?? 7);
}
public static void M8([IDispatchConstant] [MarshalAs(UnmanagedType.Interface)][Optional] object x)
{
Console.WriteLine(x ?? 8);
}
public static void M9([IUnknownConstant]object x = null)
{
Console.WriteLine(x ?? 9);
}
public static void M10([IUnknownConstant][Optional] object x)
{
Console.WriteLine(x ?? 10);
}
public static void M11([IUnknownConstant][MarshalAs(UnmanagedType.Interface)] object x = null)
{
Console.WriteLine(x ?? 11);
}
public static void M12([IUnknownConstant][MarshalAs(UnmanagedType.Interface)][Optional] object x)
{
Console.WriteLine(x ?? 12);
}
public static void M13([IUnknownConstant][IDispatchConstant] object x = null)
{
Console.WriteLine(x ?? 13);
}
public static void M14([IDispatchConstant][IUnknownConstant][Optional] object x)
{
Console.WriteLine(x ?? 14);
}
public static void M15([IUnknownConstant][IDispatchConstant] [MarshalAs(UnmanagedType.Interface)] object x = null)
{
Console.WriteLine(x ?? 15);
}
public static void M16([IUnknownConstant][IDispatchConstant] [MarshalAs(UnmanagedType.Interface)][Optional] object x)
{
Console.WriteLine(x ?? 16);
}
public static void M17([MarshalAs(UnmanagedType.Interface)][IDispatchConstant][Optional] object x)
{
Console.WriteLine(x ?? 17);
}
public static void M18([MarshalAs(UnmanagedType.Interface)][IUnknownConstant][Optional] object x)
{
Console.WriteLine(x ?? 18);
}
}
";
string sourceCalls = @"
internal class D
{
static void Main()
{
C.M1(); // null
C.M2(); // Missing
C.M3(); // null
C.M4(); // null
C.M5(); // null
C.M6(); // DispatchWrapper
C.M7(); // null
C.M8(); // null
C.M9(); // null
C.M10(); // UnknownWrapper
C.M11(); // null
C.M12(); // null
C.M13(); // null
C.M14(); // UnknownWrapper
C.M15(); // null
C.M16(); // null
C.M17(); // null
C.M18(); // null
}
}";
string expected = @"1
System.Reflection.Missing
3
4
5
System.Runtime.InteropServices.DispatchWrapper
7
8
9
System.Runtime.InteropServices.UnknownWrapper
11
12
13
System.Runtime.InteropServices.UnknownWrapper
15
16
17
18";
// definitions in source:
var verifier = CompileAndVerify(new[] { sourceDefinitions, sourceCalls }, new[] { SystemRef }, expectedOutput: expected);
// definitions in metadata:
using (var assembly = AssemblyMetadata.CreateFromImage(verifier.EmittedAssemblyData))
{
CompileAndVerify(new[] { sourceCalls }, new[] { SystemRef, assembly.GetReference() }, expectedOutput: expected);
}
}
[WorkItem(545329, "DevDiv")]
[Fact()]
public void ComOptionalRefParameter()
{
string source = @"
using System;
using System.Runtime.InteropServices;
[ComImport, Guid(""00020813-0000-0000-c000-000000000046"")]
interface ComClass
{
void M([Optional]ref object o);
}
class D : ComClass
{
public void M(ref object o)
{
}
}
class C
{
static void Main()
{
D d = new D();
ComClass c = d;
c.M(); //fine
d.M(); //CS1501
}
}
";
CreateCompilationWithMscorlib(source).VerifyDiagnostics(
// (25,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'o' of 'D.M(ref object)'
// d.M(); //CS1501
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("o", "D.M(ref object)").WithLocation(25, 11));
}
[WorkItem(545337, "DevDiv")]
[ClrOnlyFact]
public void TestVbDecimalAndDateTimeDefaultParameters()
{
var vb = @"
Imports System
public Module VBModule
Sub I(Optional ByVal x As System.Int32 = 456)
Console.WriteLine(x)
End Sub
Sub NI(Optional ByVal x As System.Int32? = 457)
Console.WriteLine(x)
End Sub
Sub OI(Optional ByVal x As Object = 458 )
Console.WriteLine(x)
End Sub
Sub DA(Optional ByVal x As DateTime = #1/2/2007#)
Console.WriteLine(x = #1/2/2007#)
End Sub
Sub NDT(Optional ByVal x As DateTime? = #1/2/2007#)
Console.WriteLine(x = #1/2/2007#)
End Sub
Sub ODT(Optional ByVal x As Object = #1/2/2007#)
Console.WriteLine(x = #1/2/2007#)
End Sub
Sub Dec(Optional ByVal x as Decimal = 12.3D)
Console.WriteLine(x.ToString(System.Globalization.CultureInfo.InvariantCulture))
End Sub
Sub NDec(Optional ByVal x as Decimal? = 12.4D)
Console.WriteLine(x.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))
End Sub
Sub ODec(Optional ByVal x as Object = 12.5D)
Console.WriteLine(DirectCast(x, Decimal).ToString(System.Globalization.CultureInfo.InvariantCulture))
End Sub
End Module
";
var csharp = @"
using System;
public class D
{
static void Main()
{
// Ensure suites run in invariant culture across machines
System.Threading.Thread.CurrentThread.CurrentCulture
= System.Globalization.CultureInfo.InvariantCulture;
// Possible in both C# and VB:
VBModule.I();
VBModule.NI();
VBModule.Dec();
VBModule.NDec();
// Not possible in C#, possible in VB, but C# honours the parameter:
VBModule.OI();
VBModule.ODec();
VBModule.DA();
VBModule.NDT();
VBModule.ODT();
}
}
";
string expected = @"456
457
12.3
12.4
458
12.5
True
True
True";
string il = @"{
// Code size 181 (0xb5)
.maxstack 5
IL_0000: call ""System.Threading.Thread System.Threading.Thread.CurrentThread.get""
IL_0005: call ""System.Globalization.CultureInfo System.Globalization.CultureInfo.InvariantCulture.get""
IL_000a: callvirt ""void System.Threading.Thread.CurrentCulture.set""
IL_000f: ldc.i4 0x1c8
IL_0014: call ""void VBModule.I(int)""
IL_0019: ldc.i4 0x1c9
IL_001e: newobj ""int?..ctor(int)""
IL_0023: call ""void VBModule.NI(int?)""
IL_0028: ldc.i4.s 123
IL_002a: ldc.i4.0
IL_002b: ldc.i4.0
IL_002c: ldc.i4.0
IL_002d: ldc.i4.1
IL_002e: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0033: call ""void VBModule.Dec(decimal)""
IL_0038: ldc.i4.s 124
IL_003a: ldc.i4.0
IL_003b: ldc.i4.0
IL_003c: ldc.i4.0
IL_003d: ldc.i4.1
IL_003e: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0043: newobj ""decimal?..ctor(decimal)""
IL_0048: call ""void VBModule.NDec(decimal?)""
IL_004d: ldc.i4 0x1ca
IL_0052: box ""int""
IL_0057: call ""void VBModule.OI(object)""
IL_005c: ldc.i4.s 125
IL_005e: ldc.i4.0
IL_005f: ldc.i4.0
IL_0060: ldc.i4.0
IL_0061: ldc.i4.1
IL_0062: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0067: box ""decimal""
IL_006c: call ""void VBModule.ODec(object)""
IL_0071: ldc.i8 0x8c8fc181490c000
IL_007a: newobj ""System.DateTime..ctor(long)""
IL_007f: call ""void VBModule.DA(System.DateTime)""
IL_0084: ldc.i8 0x8c8fc181490c000
IL_008d: newobj ""System.DateTime..ctor(long)""
IL_0092: newobj ""System.DateTime?..ctor(System.DateTime)""
IL_0097: call ""void VBModule.NDT(System.DateTime?)""
IL_009c: ldc.i8 0x8c8fc181490c000
IL_00a5: newobj ""System.DateTime..ctor(long)""
IL_00aa: box ""System.DateTime""
IL_00af: call ""void VBModule.ODT(object)""
IL_00b4: ret
}";
var vbCompilation = CreateVisualBasicCompilation("VB", vb,
compilationOptions: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
vbCompilation.VerifyDiagnostics();
var csharpCompilation = CreateCSharpCompilation("CS", csharp,
compilationOptions: TestOptions.ReleaseExe,
referencedCompilations: new[] { vbCompilation });
var verifier = CompileAndVerify(csharpCompilation, expectedOutput: expected);
verifier.VerifyIL("D.Main", il);
}
[WorkItem(545337, "DevDiv")]
[Fact]
public void TestCSharpDecimalAndDateTimeDefaultParameters()
{
var library = @"
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
public enum E
{
one,
two,
three
}
public class C
{
public void Foo(
[Optional][DateTimeConstant(100000)]DateTime dateTime,
decimal dec = 12345678901234567890m,
int? x = 0,
int? q = null,
short y = 10,
int z = default(int),
S? s = null)
//S? s2 = default(S))
{
if (dateTime == new DateTime(100000))
{
Console.WriteLine(""DatesMatch"");
}
else
{
Console.WriteLine(""Dates dont match!!"");
}
Write(dec);
Write(x);
Write(q);
Write(y);
Write(z);
Write(s);
//Write(s2);
}
public void Bar(S? s1, S? s2, S? s3)
{
}
public void Baz(E? e1 = E.one, long? x = 0)
{
if (e1.HasValue)
{
Console.WriteLine(e1);
}
else
{
Console.WriteLine(""null"");
}
Console.WriteLine(x);
}
public void Write(object o)
{
if (o == null)
{
Console.WriteLine(""null"");
}
else
{
Console.WriteLine(o);
}
}
}
public struct S
{
}
";
var main = @"
using System;
public class D
{
static void Main()
{
// Ensure suites run in invariant culture across machines
System.Threading.Thread.CurrentThread.CurrentCulture
= System.Globalization.CultureInfo.InvariantCulture;
C c = new C();
c.Foo();
c.Baz();
}
}
";
var libComp = CreateCompilationWithMscorlib(library, options: TestOptions.ReleaseDll, assemblyName: "Library");
libComp.VerifyDiagnostics();
var exeComp = CreateCompilationWithMscorlib(main, new[] { new CSharpCompilationReference(libComp) }, options: TestOptions.ReleaseExe, assemblyName: "Main");
var verifier = CompileAndVerify(exeComp, expectedOutput: @"DatesMatch
12345678901234567890
0
null
10
0
null
one
0");
verifier.VerifyIL("D.Main", @"{
// Code size 97 (0x61)
.maxstack 9
.locals init (int? V_0,
S? V_1)
IL_0000: call ""System.Threading.Thread System.Threading.Thread.CurrentThread.get""
IL_0005: call ""System.Globalization.CultureInfo System.Globalization.CultureInfo.InvariantCulture.get""
IL_000a: callvirt ""void System.Threading.Thread.CurrentCulture.set""
IL_000f: newobj ""C..ctor()""
IL_0014: dup
IL_0015: ldc.i4 0x186a0
IL_001a: conv.i8
IL_001b: newobj ""System.DateTime..ctor(long)""
IL_0020: ldc.i8 0xab54a98ceb1f0ad2
IL_0029: newobj ""decimal..ctor(ulong)""
IL_002e: ldc.i4.0
IL_002f: newobj ""int?..ctor(int)""
IL_0034: ldloca.s V_0
IL_0036: initobj ""int?""
IL_003c: ldloc.0
IL_003d: ldc.i4.s 10
IL_003f: ldc.i4.0
IL_0040: ldloca.s V_1
IL_0042: initobj ""S?""
IL_0048: ldloc.1
IL_0049: callvirt ""void C.Foo(System.DateTime, decimal, int?, int?, short, int, S?)""
IL_004e: ldc.i4.0
IL_004f: newobj ""E?..ctor(E)""
IL_0054: ldc.i4.0
IL_0055: conv.i8
IL_0056: newobj ""long?..ctor(long)""
IL_005b: callvirt ""void C.Baz(E?, long?)""
IL_0060: ret
}");
}
[Fact]
public void OmittedComOutParameter()
{
// We allow omitting optional ref arguments but not optional out arguments.
var source = @"
using System;
using System.Runtime.InteropServices;
[ComImport, Guid(""989FE455-5A6D-4D05-A349-1A221DA05FDA"")]
interface I
{
void M([Optional]out object o);
}
class P
{
static void Q(I i) { i.M(); }
}
";
// Note that the native compiler gives a slightly less informative error message here.
var comp = CreateCompilationWithMscorlib(source);
comp.VerifyDiagnostics(
// (11,26): error CS7036: There is no argument given that corresponds to the required formal parameter 'o' of 'I.M(out object)'
// static void Q(I i) { i.M(); }
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("o", "I.M(out object)")
);
}
[Fact]
public void OmittedComRefParameter()
{
var source = @"
using System;
using System.Runtime.InteropServices;
[ComImport, Guid(""A8FAF53B-F502-4465-9429-CAB2A19B47BE"")]
interface ICom
{
void M(out int w, int x, [Optional]ref object o, int z = 0);
}
class Com : ICom
{
public void M(out int w, int x, ref object o, int z)
{
w = 123;
Console.WriteLine(x);
if (o != null)
{
Console.WriteLine(o.GetType());
}
else
{
Console.WriteLine(""null"");
}
Console.WriteLine(z);
}
static void Main()
{
ICom c = new Com();
int q;
c.M(w: out q, z: 10, x: 100);
Console.WriteLine(q);
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"
100
System.Reflection.Missing
10
123");
verifier.VerifyIL("Com.Main", @"
{
// Code size 31 (0x1f)
.maxstack 5
.locals init (int V_0, //q
object V_1)
IL_0000: newobj ""Com..ctor()""
IL_0005: ldloca.s V_0
IL_0007: ldc.i4.s 100
IL_0009: ldsfld ""object System.Type.Missing""
IL_000e: stloc.1
IL_000f: ldloca.s V_1
IL_0011: ldc.i4.s 10
IL_0013: callvirt ""void ICom.M(out int, int, ref object, int)""
IL_0018: ldloc.0
IL_0019: call ""void System.Console.WriteLine(int)""
IL_001e: ret
}");
}
[Fact]
public void ArrayElementComRefParameter()
{
var source =
@"using System;
using System.Runtime.InteropServices;
[ComImport]
[Guid(""B107A073-4ACE-4057-B4BA-837891E3C274"")]
interface IA
{
void M(ref int i);
}
class A : IA
{
void IA.M(ref int i)
{
i += 2;
}
}
class B
{
static void M(IA a)
{
a.M(F()[0]);
}
static void MByRef(IA a)
{
a.M(ref F()[0]);
}
static int[] i = { 0 };
static int[] F()
{
Console.WriteLine(""F()"");
return i;
}
static void Main()
{
IA a = new A();
M(a);
ReportAndReset();
MByRef(a);
ReportAndReset();
}
static void ReportAndReset()
{
Console.WriteLine(""{0}"", i[0]);
i = new[] { 0 };
}
}";
var verifier = CompileAndVerify(source, expectedOutput:
@"F()
0
F()
2");
verifier.VerifyIL("B.M(IA)",
@"{
// Code size 17 (0x11)
.maxstack 3
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: call ""int[] B.F()""
IL_0006: ldc.i4.0
IL_0007: ldelem.i4
IL_0008: stloc.0
IL_0009: ldloca.s V_0
IL_000b: callvirt ""void IA.M(ref int)""
IL_0010: ret
}");
verifier.VerifyIL("B.MByRef(IA)",
@"{
// Code size 18 (0x12)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call ""int[] B.F()""
IL_0006: ldc.i4.0
IL_0007: ldelema ""int""
IL_000c: callvirt ""void IA.M(ref int)""
IL_0011: ret
}");
}
[Fact]
public void ArrayElementComRefParametersReordered()
{
var source =
@"using System;
using System.Runtime.InteropServices;
[ComImport]
[Guid(""B107A073-4ACE-4057-B4BA-837891E3C274"")]
interface IA
{
void M(ref int x, ref int y);
}
class A : IA
{
void IA.M(ref int x, ref int y)
{
x += 2;
y += 3;
}
}
class B
{
static void M(IA a)
{
a.M(y: ref F2()[0], x: ref F1()[0]);
}
static int[] i1 = { 0 };
static int[] i2 = { 0 };
static int[] F1()
{
Console.WriteLine(""F1()"");
return i1;
}
static int[] F2()
{
Console.WriteLine(""F2()"");
return i2;
}
static void Main()
{
IA a = new A();
M(a);
Console.WriteLine(""{0}, {1}"", i1[0], i2[0]);
}
}";
var verifier = CompileAndVerify(source, expectedOutput:
@"F2()
F1()
2, 3
");
verifier.VerifyIL("B.M(IA)",
@"{
// Code size 31 (0x1f)
.maxstack 3
.locals init (int& V_0)
IL_0000: ldarg.0
IL_0001: call ""int[] B.F2()""
IL_0006: ldc.i4.0
IL_0007: ldelema ""int""
IL_000c: stloc.0
IL_000d: call ""int[] B.F1()""
IL_0012: ldc.i4.0
IL_0013: ldelema ""int""
IL_0018: ldloc.0
IL_0019: callvirt ""void IA.M(ref int, ref int)""
IL_001e: ret
}");
}
[Fact]
[WorkItem(546713, "DevDiv")]
public void Test16631()
{
var source =
@"
public abstract class B
{
protected abstract void E<T>();
}
public class D : B
{
void M()
{
// There are two possible methods to choose here. The static method
// is better because it is declared in a more derived class; the
// virtual method is better because it has exactly the right number
// of parameters. In this case, the static method wins. The virtual
// method is to be treated as though it was a method of the base class,
// and therefore automatically loses. (The bug we are regressing here
// is that Roslyn did not correctly identify the originally-defining
// type B when the method E was generic. The original repro scenario in
// bug 16631 was much more complicated than this, but it boiled down to
// overload resolution choosing the wrong method.)
E<int>();
}
protected override void E<T>()
{
System.Console.WriteLine(1);
}
static void E<T>(int x = 0xBEEF)
{
System.Console.WriteLine(2);
}
static void Main()
{
(new D()).M();
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "2");
verifier.VerifyIL("D.M()",
@"{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldc.i4 0xbeef
IL_0005: call ""void D.E<int>(int)""
IL_000a: ret
}");
}
[Fact]
[WorkItem(529775, "DevDiv")]
public void IsOptionalVsHasDefaultValue_PrimitiveStruct()
{
var source = @"
using System;
using System.Runtime.InteropServices;
public class C
{
public void M0(int p) { }
public void M1(int p = 0) { } // default of type
public void M2(int p = 1) { } // not default of type
public void M3([Optional]int p) { } // no default specified (would be illegal)
public void M4([DefaultParameterValue(0)]int p) { } // default of type, not optional
public void M5([DefaultParameterValue(1)]int p) { } // not default of type, not optional
public void M6([Optional][DefaultParameterValue(0)]int p) { } // default of type, optional
public void M7([Optional][DefaultParameterValue(1)]int p) { } // not default of type, optional
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray();
Assert.Equal(8, methods.Length);
var parameters = methods.Select(m => m.Parameters.Single()).ToArray();
Assert.False(parameters[0].IsOptional);
Assert.False(parameters[0].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue);
Assert.Null(parameters[0].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[0].GetAttributes().Length);
Assert.True(parameters[1].IsOptional);
Assert.True(parameters[1].HasExplicitDefaultValue);
Assert.Equal(0, parameters[1].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(0), parameters[1].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[1].GetAttributes().Length);
Assert.True(parameters[2].IsOptional);
Assert.True(parameters[2].HasExplicitDefaultValue);
Assert.Equal(1, parameters[2].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(1), parameters[2].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[2].GetAttributes().Length);
Assert.True(parameters[3].IsOptional);
Assert.False(parameters[3].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue);
Assert.Null(parameters[3].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[3].GetAttributes().Length);
Assert.False(parameters[4].IsOptional);
Assert.False(parameters[4].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue);
Assert.True(parameters[4].HasMetadataConstantValue);
Assert.Equal(ConstantValue.Create(0), parameters[4].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[4].GetAttributes().Length);
Assert.False(parameters[5].IsOptional);
Assert.False(parameters[5].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[5].ExplicitDefaultValue);
Assert.True(parameters[5].HasMetadataConstantValue);
Assert.Equal(ConstantValue.Create(1), parameters[5].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[5].GetAttributes().Length);
Assert.True(parameters[6].IsOptional);
Assert.True(parameters[6].HasExplicitDefaultValue);
Assert.Equal(0, parameters[6].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(0), parameters[6].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[6].GetAttributes().Length);
Assert.True(parameters[7].IsOptional);
Assert.True(parameters[7].HasExplicitDefaultValue);
Assert.Equal(1, parameters[7].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(1), parameters[7].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[7].GetAttributes().Length);
};
CompileAndVerify(source, new[] { SystemRef }, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
[WorkItem(529775, "DevDiv")]
public void IsOptionalVsHasDefaultValue_UserDefinedStruct()
{
var source = @"
using System;
using System.Runtime.InteropServices;
public class C
{
public void M0(S p) { }
public void M1(S p = default(S)) { }
public void M2([Optional]S p) { } // no default specified (would be illegal)
}
public struct S
{
public int x;
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray();
Assert.Equal(3, methods.Length);
var parameters = methods.Select(m => m.Parameters.Single()).ToArray();
Assert.False(parameters[0].IsOptional);
Assert.False(parameters[0].HasExplicitDefaultValue);
Assert.Null(parameters[0].ExplicitDefaultConstantValue);
Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue);
Assert.Equal(0, parameters[0].GetAttributes().Length);
Assert.True(parameters[1].IsOptional);
Assert.True(parameters[1].HasExplicitDefaultValue);
Assert.Null(parameters[1].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Null, parameters[1].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[1].GetAttributes().Length);
Assert.True(parameters[2].IsOptional);
Assert.False(parameters[2].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[2].ExplicitDefaultValue);
Assert.Null(parameters[2].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[2].GetAttributes().Length);
};
// TODO: RefEmit doesn't emit the default value of M1's parameter.
CompileAndVerify(source, new[] { SystemRef }, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
[WorkItem(529775, "DevDiv")]
public void IsOptionalVsHasDefaultValue_String()
{
var source = @"
using System;
using System.Runtime.InteropServices;
public class C
{
public void M0(string p) { }
public void M1(string p = null) { }
public void M2(string p = ""A"") { }
public void M3([Optional]string p) { } // no default specified (would be illegal)
public void M4([DefaultParameterValue(null)]string p) { }
public void M5([Optional][DefaultParameterValue(null)]string p) { }
public void M6([DefaultParameterValue(""A"")]string p) { }
public void M7([Optional][DefaultParameterValue(""A"")]string p) { }
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray();
Assert.Equal(8, methods.Length);
var parameters = methods.Select(m => m.Parameters.Single()).ToArray();
Assert.False(parameters[0].IsOptional);
Assert.False(parameters[0].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue);
Assert.Null(parameters[0].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[0].GetAttributes().Length);
Assert.True(parameters[1].IsOptional);
Assert.True(parameters[1].HasExplicitDefaultValue);
Assert.Null(parameters[1].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Null, parameters[1].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[1].GetAttributes().Length);
Assert.True(parameters[2].IsOptional);
Assert.True(parameters[2].HasExplicitDefaultValue);
Assert.Equal("A", parameters[2].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create("A"), parameters[2].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[2].GetAttributes().Length);
Assert.True(parameters[3].IsOptional);
Assert.False(parameters[3].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue);
Assert.Null(parameters[3].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[3].GetAttributes().Length);
Assert.False(parameters[4].IsOptional);
Assert.False(parameters[4].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue);
Assert.True(parameters[4].HasMetadataConstantValue);
Assert.Equal(ConstantValue.Null, parameters[4].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[4].GetAttributes().Length);
Assert.True(parameters[5].IsOptional);
Assert.True(parameters[5].HasExplicitDefaultValue);
Assert.Null(parameters[5].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Null, parameters[5].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[5].GetAttributes().Length);
Assert.False(parameters[6].IsOptional);
Assert.False(parameters[6].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[6].ExplicitDefaultValue);
Assert.True(parameters[6].HasMetadataConstantValue);
Assert.Equal(ConstantValue.Create("A"), parameters[6].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[6].GetAttributes().Length);
Assert.True(parameters[7].IsOptional);
Assert.True(parameters[7].HasExplicitDefaultValue);
Assert.Equal("A", parameters[7].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create("A"), parameters[7].ExplicitDefaultConstantValue); // not imported for non-optional parameter
Assert.Equal(isFromSource ? 2 : 0, parameters[7].GetAttributes().Length);
};
CompileAndVerify(source, new[] { SystemRef }, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
[WorkItem(529775, "DevDiv")]
public void IsOptionalVsHasDefaultValue_Decimal()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public class C
{
public void M0(decimal p) { }
public void M1(decimal p = 0) { } // default of type
public void M2(decimal p = 1) { } // not default of type
public void M3([Optional]decimal p) { } // no default specified (would be illegal)
public void M4([DecimalConstant(0,0,0,0,0)]decimal p) { } // default of type, not optional
public void M5([DecimalConstant(0,0,0,0,1)]decimal p) { } // not default of type, not optional
public void M6([Optional][DecimalConstant(0,0,0,0,0)]decimal p) { } // default of type, optional
public void M7([Optional][DecimalConstant(0,0,0,0,1)]decimal p) { } // not default of type, optional
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray();
Assert.Equal(8, methods.Length);
var parameters = methods.Select(m => m.Parameters.Single()).ToArray();
Assert.False(parameters[0].IsOptional);
Assert.False(parameters[0].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue);
Assert.Null(parameters[0].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[0].GetAttributes().Length);
Assert.True(parameters[1].IsOptional);
Assert.True(parameters[1].HasExplicitDefaultValue);
Assert.Equal(0M, parameters[1].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(0M), parameters[1].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[1].GetAttributes().Length);
Assert.True(parameters[2].IsOptional);
Assert.True(parameters[2].HasExplicitDefaultValue);
Assert.Equal(1M, parameters[2].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(1M), parameters[2].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[2].GetAttributes().Length);
Assert.True(parameters[3].IsOptional);
Assert.False(parameters[3].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue);
Assert.Null(parameters[3].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[3].GetAttributes().Length);
Assert.False(parameters[4].IsOptional);
Assert.False(parameters[4].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue);
Assert.False(parameters[4].HasMetadataConstantValue);
Assert.Equal(isFromSource ? ConstantValue.Create(0M) : null, parameters[4].ExplicitDefaultConstantValue); // not imported for non-optional parameter
Assert.Equal(1, parameters[4].GetAttributes().Length); // DecimalConstantAttribute
Assert.False(parameters[5].IsOptional);
Assert.False(parameters[5].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[5].ExplicitDefaultValue);
Assert.False(parameters[5].HasMetadataConstantValue);
Assert.Equal(isFromSource ? ConstantValue.Create(1M) : null, parameters[5].ExplicitDefaultConstantValue); // not imported for non-optional parameter
Assert.Equal(1, parameters[5].GetAttributes().Length); // DecimalConstantAttribute
Assert.True(parameters[6].IsOptional);
Assert.True(parameters[6].HasExplicitDefaultValue);
Assert.Equal(0M, parameters[6].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(0M), parameters[6].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[6].GetAttributes().Length); // Optional+DecimalConstantAttribute / DecimalConstantAttribute
Assert.True(parameters[7].IsOptional);
Assert.True(parameters[7].HasExplicitDefaultValue);
Assert.Equal(1M, parameters[7].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(1M), parameters[7].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[7].GetAttributes().Length); // Optional+DecimalConstantAttribute / DecimalConstantAttribute
};
CompileAndVerify(source, new[] { SystemRef }, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
[WorkItem(529775, "DevDiv")]
public void IsOptionalVsHasDefaultValue_DateTime()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public class C
{
public void M0(DateTime p) { }
public void M1(DateTime p = default(DateTime)) { }
public void M2([Optional]DateTime p) { } // no default specified (would be illegal)
public void M3([DateTimeConstant(0)]DateTime p) { } // default of type, not optional
public void M4([DateTimeConstant(1)]DateTime p) { } // not default of type, not optional
public void M5([Optional][DateTimeConstant(0)]DateTime p) { } // default of type, optional
public void M6([Optional][DateTimeConstant(1)]DateTime p) { } // not default of type, optional
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray();
Assert.Equal(7, methods.Length);
var parameters = methods.Select(m => m.Parameters.Single()).ToArray();
Assert.False(parameters[0].IsOptional);
Assert.False(parameters[0].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue);
Assert.Null(parameters[0].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[0].GetAttributes().Length);
Assert.True(parameters[1].IsOptional);
Assert.True(parameters[1].HasExplicitDefaultValue);
Assert.Null(parameters[1].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Null, parameters[1].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[1].GetAttributes().Length); // As in dev11, [DateTimeConstant] is not emitted in this case.
Assert.True(parameters[2].IsOptional);
Assert.False(parameters[2].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[2].ExplicitDefaultValue);
Assert.Null(parameters[2].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[2].GetAttributes().Length);
Assert.False(parameters[3].IsOptional);
Assert.False(parameters[3].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue);
Assert.False(parameters[3].HasMetadataConstantValue);
Assert.Equal(isFromSource ? ConstantValue.Create(new DateTime(0)) : null, parameters[3].ExplicitDefaultConstantValue); // not imported for non-optional parameter
Assert.Equal(1, parameters[3].GetAttributes().Length); // DateTimeConstant
Assert.False(parameters[4].IsOptional);
Assert.False(parameters[4].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue);
Assert.False(parameters[4].HasMetadataConstantValue);
Assert.Equal(isFromSource ? ConstantValue.Create(new DateTime(1)) : null, parameters[4].ExplicitDefaultConstantValue); // not imported for non-optional parameter
Assert.Equal(1, parameters[4].GetAttributes().Length); // DateTimeConstant
Assert.True(parameters[5].IsOptional);
Assert.True(parameters[5].HasExplicitDefaultValue);
Assert.Equal(new DateTime(0), parameters[5].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(new DateTime(0)), parameters[5].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[5].GetAttributes().Length); // Optional+DateTimeConstant / DateTimeConstant
Assert.True(parameters[6].IsOptional);
Assert.True(parameters[6].HasExplicitDefaultValue);
Assert.Equal(new DateTime(1), parameters[6].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(new DateTime(1)), parameters[6].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[6].GetAttributes().Length); // Optional+DateTimeConstant / DateTimeConstant
};
// TODO: Guess - RefEmit doesn't like DateTime constants.
CompileAndVerify(source, new[] { SystemRef }, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
}
}
| VPashkov/roslyn | src/Compilers/CSharp/Test/Semantic/Semantics/NamedAndOptionalTests.cs | C# | apache-2.0 | 81,400 |
package com.github.markusbernhardt.xmldoclet.simpledata;
/**
* Class2
*/
public class Class2 {
/**
* Constructor1
*/
public Class2() {
}
} | riptano/xml-doclet | src/test/java/com/github/markusbernhardt/xmldoclet/simpledata/Class2.java | Java | apache-2.0 | 149 |
/*
* Copyright 2010-2016 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.autoscaling.model;
import java.io.Serializable;
/**
*
*/
public class DescribeTagsResult implements Serializable, Cloneable {
/**
* <p>
* One or more tags.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<TagDescription> tags;
/**
* <p>
* The token to use when requesting the next set of items. If there are no
* additional items to return, the string is empty.
* </p>
*/
private String nextToken;
/**
* <p>
* One or more tags.
* </p>
*
* @return One or more tags.
*/
public java.util.List<TagDescription> getTags() {
if (tags == null) {
tags = new com.amazonaws.internal.SdkInternalList<TagDescription>();
}
return tags;
}
/**
* <p>
* One or more tags.
* </p>
*
* @param tags
* One or more tags.
*/
public void setTags(java.util.Collection<TagDescription> tags) {
if (tags == null) {
this.tags = null;
return;
}
this.tags = new com.amazonaws.internal.SdkInternalList<TagDescription>(
tags);
}
/**
* <p>
* One or more tags.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setTags(java.util.Collection)} or
* {@link #withTags(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param tags
* One or more tags.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public DescribeTagsResult withTags(TagDescription... tags) {
if (this.tags == null) {
setTags(new com.amazonaws.internal.SdkInternalList<TagDescription>(
tags.length));
}
for (TagDescription ele : tags) {
this.tags.add(ele);
}
return this;
}
/**
* <p>
* One or more tags.
* </p>
*
* @param tags
* One or more tags.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public DescribeTagsResult withTags(java.util.Collection<TagDescription> tags) {
setTags(tags);
return this;
}
/**
* <p>
* The token to use when requesting the next set of items. If there are no
* additional items to return, the string is empty.
* </p>
*
* @param nextToken
* The token to use when requesting the next set of items. If there
* are no additional items to return, the string is empty.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* The token to use when requesting the next set of items. If there are no
* additional items to return, the string is empty.
* </p>
*
* @return The token to use when requesting the next set of items. If there
* are no additional items to return, the string is empty.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* The token to use when requesting the next set of items. If there are no
* additional items to return, the string is empty.
* </p>
*
* @param nextToken
* The token to use when requesting the next set of items. If there
* are no additional items to return, the string is empty.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public DescribeTagsResult withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getTags() != null)
sb.append("Tags: " + getTags() + ",");
if (getNextToken() != null)
sb.append("NextToken: " + getNextToken());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeTagsResult == false)
return false;
DescribeTagsResult other = (DescribeTagsResult) obj;
if (other.getTags() == null ^ this.getTags() == null)
return false;
if (other.getTags() != null
&& other.getTags().equals(this.getTags()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null
&& other.getNextToken().equals(this.getNextToken()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getTags() == null) ? 0 : getTags().hashCode());
hashCode = prime * hashCode
+ ((getNextToken() == null) ? 0 : getNextToken().hashCode());
return hashCode;
}
@Override
public DescribeTagsResult clone() {
try {
return (DescribeTagsResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
}
| flofreud/aws-sdk-java | aws-java-sdk-autoscaling/src/main/java/com/amazonaws/services/autoscaling/model/DescribeTagsResult.java | Java | apache-2.0 | 6,523 |
"""Support for NX584 alarm control panels."""
import logging
from nx584 import client
import requests
import voluptuous as vol
import homeassistant.components.alarm_control_panel as alarm
from homeassistant.components.alarm_control_panel import PLATFORM_SCHEMA
from homeassistant.components.alarm_control_panel.const import (
SUPPORT_ALARM_ARM_AWAY,
SUPPORT_ALARM_ARM_HOME,
)
from homeassistant.const import (
CONF_HOST,
CONF_NAME,
CONF_PORT,
STATE_ALARM_ARMED_AWAY,
STATE_ALARM_ARMED_HOME,
STATE_ALARM_DISARMED,
STATE_ALARM_TRIGGERED,
)
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
DEFAULT_HOST = "localhost"
DEFAULT_NAME = "NX584"
DEFAULT_PORT = 5007
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the NX584 platform."""
name = config.get(CONF_NAME)
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
url = f"http://{host}:{port}"
try:
add_entities([NX584Alarm(hass, url, name)])
except requests.exceptions.ConnectionError as ex:
_LOGGER.error("Unable to connect to NX584: %s", str(ex))
return
class NX584Alarm(alarm.AlarmControlPanel):
"""Representation of a NX584-based alarm panel."""
def __init__(self, hass, url, name):
"""Init the nx584 alarm panel."""
self._hass = hass
self._name = name
self._url = url
self._alarm = client.Client(self._url)
# Do an initial list operation so that we will try to actually
# talk to the API and trigger a requests exception for setup_platform()
# to catch
self._alarm.list_zones()
self._state = None
@property
def name(self):
"""Return the name of the device."""
return self._name
@property
def code_format(self):
"""Return one or more digits/characters."""
return alarm.FORMAT_NUMBER
@property
def state(self):
"""Return the state of the device."""
return self._state
@property
def supported_features(self) -> int:
"""Return the list of supported features."""
return SUPPORT_ALARM_ARM_HOME | SUPPORT_ALARM_ARM_AWAY
def update(self):
"""Process new events from panel."""
try:
part = self._alarm.list_partitions()[0]
zones = self._alarm.list_zones()
except requests.exceptions.ConnectionError as ex:
_LOGGER.error(
"Unable to connect to %(host)s: %(reason)s",
dict(host=self._url, reason=ex),
)
self._state = None
zones = []
except IndexError:
_LOGGER.error("NX584 reports no partitions")
self._state = None
zones = []
bypassed = False
for zone in zones:
if zone["bypassed"]:
_LOGGER.debug(
"Zone %(zone)s is bypassed, assuming HOME",
dict(zone=zone["number"]),
)
bypassed = True
break
if not part["armed"]:
self._state = STATE_ALARM_DISARMED
elif bypassed:
self._state = STATE_ALARM_ARMED_HOME
else:
self._state = STATE_ALARM_ARMED_AWAY
for flag in part["condition_flags"]:
if flag == "Siren on":
self._state = STATE_ALARM_TRIGGERED
def alarm_disarm(self, code=None):
"""Send disarm command."""
self._alarm.disarm(code)
def alarm_arm_home(self, code=None):
"""Send arm home command."""
self._alarm.arm("stay")
def alarm_arm_away(self, code=None):
"""Send arm away command."""
self._alarm.arm("exit")
| leppa/home-assistant | homeassistant/components/nx584/alarm_control_panel.py | Python | apache-2.0 | 4,039 |
/*
* 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.ode.bpel.engine;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.wsdl.OperationType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.ode.bpel.common.CorrelationKeySet;
import org.apache.ode.bpel.runtime.PartnerLinkInstance;
import org.apache.ode.bpel.runtime.Selector;
import org.apache.ode.utils.ObjectPrinter;
/**
* <p>
* This class handles behaviour of IMAs (Inbound Message Activities) as specified in WS BPEL.
* This includes detecting conflictingReceive and conflictingRequest faults.
* </p>
*/
public class IMAManager2 implements Serializable {
private static final long serialVersionUID = -5556374398943757951L;
private static final Logger __log = LoggerFactory.getLogger(IMAManager2.class);
// holds rid for registered IMAs
public final Map<RequestIdTuple, Entry> _byRid = new HashMap<RequestIdTuple, Entry>();
// holds outstanding rid that are now waiting to reply (Open IMAs)
public final Map<OutstandingRequestIdTuple, String> _byOrid = new HashMap<OutstandingRequestIdTuple, String>();
public final Map<String, Entry> _byChannel = new HashMap<String, Entry>();
/**
* finds conflictingReceive
*
* @param selectors
* @return
*/
int findConflict(Selector selectors[]) {
if (__log.isTraceEnabled()) {
__log.trace(ObjectPrinter.stringifyMethodEnter("findConflict", new Object[] { "selectors", selectors }));
}
Set<RequestIdTuple> workingSet = new HashSet<RequestIdTuple>(_byRid.keySet());
for (int i = 0; i < selectors.length; ++i) {
final RequestIdTuple rid = new RequestIdTuple(selectors[i].plinkInstance, selectors[i].opName, selectors[i].correlationKeySet);
if (workingSet.contains(rid)) {
return i;
}
workingSet.add(rid);
}
return -1;
}
/**
* Register IMA
*
* @param pickResponseChannel
* response channel associated with this receive/pick
* @param selectors
* selectors for this receive/pick
*/
void register(String pickResponseChannel, Selector selectors[]) {
if (__log.isTraceEnabled()) {
__log.trace(ObjectPrinter.stringifyMethodEnter("register", new Object[] { "pickResponseChannel", pickResponseChannel, "selectors", selectors }));
}
if (_byChannel.containsKey(pickResponseChannel)) {
String errmsg = "INTERNAL ERROR: Duplicate ENTRY for RESPONSE CHANNEL " + pickResponseChannel;
__log.error(errmsg);
throw new IllegalArgumentException(errmsg);
}
Entry entry = new Entry(pickResponseChannel, selectors);
for (int i = 0; i < selectors.length; ++i) {
final RequestIdTuple rid = new RequestIdTuple(selectors[i].plinkInstance, selectors[i].opName, selectors[i].correlationKeySet);
if (_byRid.containsKey(rid)) {
String errmsg = "INTERNAL ERROR: Duplicate ENTRY for RID " + rid;
__log.error(errmsg);
throw new IllegalStateException(errmsg);
}
_byRid.put(rid, entry);
}
_byChannel.put(pickResponseChannel, entry);
}
/**
* Registers Open IMA.
* It doesn't open IMA for non two way operations.
*
* @param partnerLink
* @param opName
* @param mexId
* @param mexRef
* @return
*/
String processOutstandingRequest(PartnerLinkInstance partnerLink, String opName, String mexId, String mexRef) {
if (__log.isTraceEnabled()) {
__log.trace(ObjectPrinter.stringifyMethodEnter("process", new Object[] { "partnerLinkInstance", partnerLink, "operationName", opName, "messageExchangeId", mexId, "mexRef", mexRef }));
}
final OutstandingRequestIdTuple orid = new OutstandingRequestIdTuple(partnerLink, opName, mexId);
if (_byOrid.containsKey(orid)) {
//conflictingRequest found
return mexRef;
}
// We convert into outstanding request only for in-out operations (pending release operation)
if (partnerLink.partnerLink.getMyRoleOperation(opName).getStyle().equals(OperationType.REQUEST_RESPONSE)) {
_byOrid.put(orid, mexRef);
}
return null;
}
/**
* This is used to remove IMA from registered state.
*
* @see #register(String, Selector[])
* @param pickResponseChannel
*/
void cancel(String pickResponseChannel, boolean isTimer) {
if (__log.isTraceEnabled())
__log.trace(ObjectPrinter.stringifyMethodEnter("cancel", new Object[] { "pickResponseChannel", pickResponseChannel }));
Entry entry = _byChannel.remove(pickResponseChannel);
if (entry != null) {
while (_byRid.values().remove(entry));
} else if (!isTimer){
String errmsg = "INTERNAL ERROR: No ENTRY for RESPONSE CHANNEL " + pickResponseChannel;
__log.error(errmsg);
throw new IllegalArgumentException(errmsg);
}
}
/**
* Release Open IMA.
*
* @param plinkInstnace
* partner link
* @param opName
* operation
* @param mexId
* message exchange identifier IN THE BPEL SENSE OF THE TERM (i.e. a receive/reply disambiguator).
* @return message exchange identifier associated with the registration that matches the parameters
*/
public String release(PartnerLinkInstance plinkInstnace, String opName, String mexId) {
if (__log.isTraceEnabled())
__log.trace(ObjectPrinter.stringifyMethodEnter("release", new Object[] { "plinkInstance", plinkInstnace, "opName", opName, "mexId", mexId }));
final OutstandingRequestIdTuple orid = new OutstandingRequestIdTuple(plinkInstnace, opName, mexId);
String mexRef = _byOrid.remove(orid);
if (mexRef == null) {
if (__log.isDebugEnabled()) {
__log.debug("==release: ORID " + orid + " not found in " + _byOrid);
}
return null;
}
return mexRef;
}
/**
* "Release" all Open IMAs
*
* @return a list of message exchange identifiers for message exchanges that were begun (receive/pick got a message) but not yet completed (reply not yet sent)
*/
public String[] releaseAll() {
if (__log.isTraceEnabled())
__log.trace(ObjectPrinter.stringifyMethodEnter("releaseAll", null));
ArrayList<String> mexRefs = new ArrayList<String>();
while (!_byOrid.isEmpty()) {
String mexRef = _byOrid.entrySet().iterator().next().getValue();
mexRefs.add(mexRef);
_byOrid.values().remove(mexRef);
}
return mexRefs.toArray(new String[mexRefs.size()]);
}
public String toString() {
return ObjectPrinter.toString(this, new Object[] { "byRid", _byRid, "byOrid", _byOrid, "byChannel", _byChannel });
}
public static class RequestIdTuple implements Serializable {
private static final long serialVersionUID = -1059389611839777482L;
/** On which partner link it was received. */
PartnerLinkInstance partnerLink;
/** Name of the operation. */
String opName;
/** cset */
CorrelationKeySet ckeySet;
/** Constructor. */
RequestIdTuple(PartnerLinkInstance partnerLink, String opName, CorrelationKeySet ckeySet) {
this.partnerLink = partnerLink;
this.opName = opName;
this.ckeySet = ckeySet;
}
public String toString() {
return ObjectPrinter.toString(this, new Object[] { "partnerLink", partnerLink, "opName", opName, "cSet", ckeySet});
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((ckeySet == null) ? 0 : ckeySet.hashCode());
result = prime * result
+ ((opName == null) ? 0 : opName.hashCode());
result = prime * result
+ ((partnerLink == null) ? 0 : partnerLink.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof RequestIdTuple)) {
return false;
}
RequestIdTuple other = (RequestIdTuple) obj;
if (ckeySet == null) {
if (other.ckeySet != null) {
return false;
}
} else if (!ckeySet.equals(other.ckeySet)) {
return false;
}
if (opName == null) {
if (other.opName != null) {
return false;
}
} else if (!opName.equals(other.opName)) {
return false;
}
if (partnerLink == null) {
if (other.partnerLink != null) {
return false;
}
} else if (!partnerLink.equals(other.partnerLink)) {
return false;
}
return true;
}
}
public static class OutstandingRequestIdTuple implements Serializable {
private static final long serialVersionUID = -1059389611839777482L;
/** On which partner link it was received. */
PartnerLinkInstance partnerLink;
/** Name of the operation. */
String opName;
/** Message exchange identifier. */
String mexId;
/** Constructor. */
OutstandingRequestIdTuple(PartnerLinkInstance partnerLink, String opName, String mexId) {
this.partnerLink = partnerLink;
this.opName = opName;
this.mexId = mexId == null ? "" : mexId;
}
public int hashCode() {
return this.partnerLink.hashCode() ^ this.opName.hashCode() ^ this.mexId.hashCode();
}
public boolean equals(Object obj) {
OutstandingRequestIdTuple other = (OutstandingRequestIdTuple) obj;
return other.partnerLink.equals(partnerLink) && other.opName.equals(opName) && other.mexId.equals(mexId);
}
public String toString() {
return ObjectPrinter.toString(this, new Object[] { "partnerLink", partnerLink, "opName", opName, "mexId", mexId });
}
}
public static class Entry implements Serializable {
private static final long serialVersionUID = -583743124656582887L;
final String pickResponseChannel;
public Selector[] selectors;
Entry(String pickResponseChannel, Selector[] selectors) {
this.pickResponseChannel = pickResponseChannel;
this.selectors = selectors;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((pickResponseChannel == null) ? 0 : pickResponseChannel
.hashCode());
result = prime * result + Arrays.hashCode(selectors);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Entry other = (Entry) obj;
if (pickResponseChannel == null) {
if (other.pickResponseChannel != null)
return false;
} else if (!pickResponseChannel.equals(other.pickResponseChannel))
return false;
if (!Arrays.equals(selectors, other.selectors))
return false;
return true;
}
public String toString() {
return ObjectPrinter.toString(this, new Object[] { "pickResponseChannel", pickResponseChannel, "selectors", selectors });
}
}
}
| Subasinghe/ode | bpel-runtime/src/main/java/org/apache/ode/bpel/engine/IMAManager2.java | Java | apache-2.0 | 13,206 |
/*
* 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.ode.utils.fs;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Various file system utilities.
*/
public class FileUtils {
private static final Logger __log = LoggerFactory.getLogger(FileUtils.class);
/**
* Test if the given path is absolute or not.
* @param path
* @return true is absolute
* @see java.io.File#isAbsolute()
*/
public static boolean isAbsolute(String path){
return new File(path).isAbsolute();
}
/**
* Test if the given path is relative or absolute.
* @param path
* @return true is relative
* @see java.io.File#isAbsolute()
*/
public static boolean isRelative(String path){
return !isAbsolute(path);
}
/**
* Delete a file/directory, recursively.
*
* @param file
* file/directory to delete
* @return <code>true</code> if successful
*/
public static boolean deepDelete(File file) {
if (file.exists()) {
if (__log.isDebugEnabled()) {
__log.debug("deleting: " + file.getAbsolutePath());
}
if (file.delete()) {
return true;
}
if (file.isDirectory()) {
boolean success = true;
File[] files = file.listFiles();
for (int i = 0; i < files.length; ++i) {
success &= deepDelete(files[i]);
}
return success ? file.delete() : false;
}
else {
__log.error("Unable to deepDelete file " + file.getAbsolutePath()
+ "; this may be caused by a descriptor leak and should be reported.");
return false;
}
}
else {
// file seems to be gone already?! anyway nothing to do for us.
return true;
}
}
/**
* Recursively collect all Files in the given directory and all its
* subdirectories.
*
* @param rootDirectory
* the top level directory used for the search
* @return a List of found Files
*/
public static List<File> directoryEntriesInPath(File rootDirectory) {
return FileUtils.directoryEntriesInPath(rootDirectory, null);
}
/**
* Recursively collect all Files in the given directory and all its
* subdirectories, applying the given FileFilter. The FileFilter is also applied to the given rootDirectory.
* As a result the rootDirectory might be in the returned list.
* <p>
* Returned files are ordered lexicographically but for each directory, files come before its sudirectories.
* For instance:<br/>
* test<br/>
* test/alpha.txt<br/>
* test/zulu.txt<br/>
* test/a<br/>
* test/a/alpha.txt<br/>
* test/z<br/>
* test/z/zulu.txt<br/>
* <p>
* instead of:<br/>
* test<br/>
* test/a<br/>
* test/a/alpha.txt<br/>
* test/alpha.txt<br/>
* test/z<br/>
* test/z/zulu.txt<br/>
* test/zulu.txt<br/>
*
* @param rootDirectory
* the top level directory used for the search
* @param filter
* a FileFilter used for accepting/rejecting individual entries
* @return a List of found Files
*/
public static List<File> directoryEntriesInPath(File rootDirectory, FileFilter filter) {
if (rootDirectory == null) {
throw new IllegalArgumentException("File must not be null!");
}
if (!rootDirectory.exists()) {
throw new IllegalArgumentException("File does not exist!");
}
ArrayList<File> collectedFiles = new ArrayList<File>(32);
if (rootDirectory.isFile()) {
if ((filter == null) || ((filter != null) && (filter.accept(rootDirectory)))) {
collectedFiles.add(rootDirectory);
}
return collectedFiles;
}
FileUtils.directoryEntriesInPath(collectedFiles, rootDirectory, filter);
return collectedFiles;
}
private static void directoryEntriesInPath(List<File> collectedFiles, File parentDir, FileFilter filter) {
if ((filter == null) || ((filter != null) && (filter.accept(parentDir)))) {
collectedFiles.add(parentDir);
}
File[] allFiles = parentDir.listFiles();
if (allFiles != null) {
TreeSet<File> dirs = new TreeSet<File>();
TreeSet<File> acceptedFiles = new TreeSet<File>();
for (File f : allFiles) {
if (f.isDirectory()) {
dirs.add(f);
} else {
if ((filter == null) || ((filter != null) && (filter.accept(f)))) {
acceptedFiles.add(f);
}
}
}
collectedFiles.addAll(acceptedFiles);
for (File currentFile : dirs) {
FileUtils.directoryEntriesInPath(collectedFiles, currentFile, filter);
}
}
}
public static String encodePath(String path) {
return path.replaceAll(" ", "%20");
}
public static void main(String[] args) {
List<File> l = directoryEntriesInPath(new File("/tmp/test"));
for(File f : l) System.out.println(f);
System.out.println("########");
TreeSet<File> s= new TreeSet(l);
for(File f : s) System.out.println(f);
}
}
| Subasinghe/ode | utils/src/main/java/org/apache/ode/utils/fs/FileUtils.java | Java | apache-2.0 | 6,403 |
/**
* 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.xml.security.stax.impl.securityToken;
import org.apache.xml.security.binding.xmldsig.DSAKeyValueType;
import org.apache.xml.security.exceptions.XMLSecurityException;
import org.apache.xml.security.stax.ext.InboundSecurityContext;
import org.apache.xml.security.stax.impl.util.IDGenerator;
import org.apache.xml.security.stax.securityToken.SecurityTokenConstants;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.DSAPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
/**
*/
public class DsaKeyValueSecurityToken extends AbstractInboundSecurityToken {
private DSAKeyValueType dsaKeyValueType;
public DsaKeyValueSecurityToken(DSAKeyValueType dsaKeyValueType, InboundSecurityContext inboundSecurityContext) {
super(inboundSecurityContext, IDGenerator.generateID(null), SecurityTokenConstants.KeyIdentifier_KeyValue, true);
this.dsaKeyValueType = dsaKeyValueType;
}
private PublicKey buildPublicKey(DSAKeyValueType dsaKeyValueType) throws InvalidKeySpecException, NoSuchAlgorithmException {
DSAPublicKeySpec dsaPublicKeySpec = new DSAPublicKeySpec(
new BigInteger(1, dsaKeyValueType.getY()),
new BigInteger(1, dsaKeyValueType.getP()),
new BigInteger(1, dsaKeyValueType.getQ()),
new BigInteger(1, dsaKeyValueType.getG()));
KeyFactory keyFactory = KeyFactory.getInstance("DSA");
return keyFactory.generatePublic(dsaPublicKeySpec);
}
@Override
public PublicKey getPublicKey() throws XMLSecurityException {
if (super.getPublicKey() == null) {
try {
setPublicKey(buildPublicKey(this.dsaKeyValueType));
} catch (InvalidKeySpecException e) {
throw new XMLSecurityException(e);
} catch (NoSuchAlgorithmException e) {
throw new XMLSecurityException(e);
}
}
return super.getPublicKey();
}
@Override
public boolean isAsymmetric() {
return true;
}
@Override
public SecurityTokenConstants.TokenType getTokenType() {
return SecurityTokenConstants.KeyValueToken;
}
}
| apache/santuario-java | src/main/java/org/apache/xml/security/stax/impl/securityToken/DsaKeyValueSecurityToken.java | Java | apache-2.0 | 3,108 |
<?php
/**
* log4php is a PHP port of the log4j java logging package.
*
* <p>This framework is based on log4j (see {@link http://jakarta.apache.org/log4j log4j} for details).</p>
* <p>Design, strategies and part of the methods documentation are developed by log4j team
* (Ceki Gülcü as log4j project founder and
* {@link http://jakarta.apache.org/log4j/docs/contributors.html contributors}).</p>
*
* <p>PHP port, extensions and modifications by VxR. All rights reserved.<br>
* For more information, please see {@link http://www.vxr.it/log4php/}.</p>
*
* <p>This software is published under the terms of the LGPL License
* a copy of which has been included with this distribution in the LICENSE file.</p>
*
* @package log4php
* @subpackage helpers
*/
/**
* @ignore
*/
if (!defined('LOG4PHP_DIR')) define('LOG4PHP_DIR', dirname(__FILE__) . '/..');
define('LOG4PHP_LOGGER_TRANSFORM_CDATA_START', '<![CDATA[');
define('LOG4PHP_LOGGER_TRANSFORM_CDATA_END', ']]>');
define('LOG4PHP_LOGGER_TRANSFORM_CDATA_PSEUDO_END', ']]>');
define('LOG4PHP_LOGGER_TRANSFORM_CDATA_EMBEDDED_END',
LOG4PHP_LOGGER_TRANSFORM_CDATA_END .
LOG4PHP_LOGGER_TRANSFORM_CDATA_PSEUDO_END .
LOG4PHP_LOGGER_TRANSFORM_CDATA_START
);
/**
* Utility class for transforming strings.
*
* @log4j-class org.apache.log4j.helpers.Transform
*
* @author VxR <vxr@vxr.it>
* @package log4php
* @subpackage helpers
* @since 0.7
*/
class LoggerTransform {
/**
* This method takes a string which may contain HTML tags (ie,
* <b>, <table>, etc) and replaces any '<' and '>'
* characters with respective predefined entity references.
*
* @param string $input The text to be converted.
* @return string The input string with the characters '<' and '>' replaced with
* &lt; and &gt; respectively.
* @static
*/
function escapeTags($input)
{
//Check if the string is null or zero length -- if so, return
//what was sent in.
if(empty($input))
return $input;
//Use a StringBuffer in lieu of String concatenation -- it is
//much more efficient this way.
return htmlspecialchars($input, ENT_NOQUOTES);
}
/**
* Ensures that embeded CDEnd strings (]]>) are handled properly
* within message, NDC and throwable tag text.
*
* @param string $buf String holding the XML data to this point. The
* initial CDStart (<![CDATA[) and final CDEnd (]]>)
* of the CDATA section are the responsibility of
* the calling method.
* @param string &str The String that is inserted into an existing
* CDATA Section within buf.
* @static
*/
function appendEscapingCDATA(&$buf, $str)
{
if(empty($str))
return;
$rStr = str_replace(
LOG4PHP_LOGGER_TRANSFORM_CDATA_END,
LOG4PHP_LOGGER_TRANSFORM_CDATA_EMBEDDED_END,
$str
);
$buf .= $rStr;
}
}
?> | basiljose1/byjcrm | libraries/log4php.debug/helpers/LoggerTransform.php | PHP | apache-2.0 | 3,145 |
// <copyright file="ZipStorer.cs" company="Jaime Olivares">
//
// ZipStorer, by Jaime Olivares
// Website: zipstorer.codeplex.com
// Version: 2.35 (March 14, 2010)
//
// Used under the provisions of the Microsoft Public License (Ms-PL).
// You may obtain a copy of the License at
//
// https://zipstorer.codeplex.com/license
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Text;
namespace System.IO.Compression
{
/// <summary>
/// Unique class for compression/decompression file. Represents a Zip file.
/// </summary>
internal sealed class ZipStorer : IDisposable
{
// Static CRC32 Table
private static uint[] crcTable = GenerateCrc32Table();
// Default filename encoder
private static Encoding defaultEncoding = Encoding.GetEncoding(437);
// List of files to store
private List<ZipFileEntry> files = new List<ZipFileEntry>();
// Stream object of storage file
private Stream zipFileStream;
// General comment
private string comment = string.Empty;
// Central dir image
private byte[] centralDirectoryImage = null;
// Existing files in zip
private ushort existingFileCount = 0;
// File access for Open method
private FileAccess access;
// True if UTF8 encoding for filename and comments, false if default (CP 437)
private bool encodeUtf8 = false;
// Force deflate algotithm even if it inflates the stored file. Off by default.
private bool forceDeflating = false;
/// <summary>
/// Compression method enumeration.
/// </summary>
public enum CompressionMethod : ushort
{
/// <summary>Uncompressed storage.</summary>
Store = 0,
/// <summary>Deflate compression method.</summary>
Deflate = 8
}
/// <summary>
/// Gets or sets a value indicating whether file names and comments should be encoded using UTF-8.
/// </summary>
public bool EncodeUtf8
{
get { return this.encodeUtf8; }
}
/// <summary>
/// Gets or sets a value indicating whether to force using the deflate algorithm,
/// even if doing so inflates the stored file.
/// </summary>
public bool ForceDeflating
{
get { return this.forceDeflating; }
}
/// <summary>
/// Create a new zip storage in a stream.
/// </summary>
/// <param name="zipStream">The stream to use to create the Zip file.</param>
/// <param name="fileComment">General comment for Zip file.</param>
/// <returns>A valid ZipStorer object.</returns>
public static ZipStorer Create(Stream zipStream, string fileComment)
{
ZipStorer zip = new ZipStorer();
zip.comment = fileComment;
zip.zipFileStream = zipStream;
zip.access = FileAccess.Write;
return zip;
}
/// <summary>
/// Open the existing Zip storage in a stream.
/// </summary>
/// <param name="stream">Already opened stream with zip contents.</param>
/// <param name="access">File access mode for stream operations.</param>
/// <returns>A valid ZipStorer object.</returns>
[Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Factory method. Caller assumes ownership of returned object")]
public static ZipStorer Open(Stream stream, FileAccess access)
{
if (!stream.CanSeek && access != FileAccess.Read)
{
throw new InvalidOperationException("Stream cannot seek");
}
ZipStorer zip = new ZipStorer();
zip.zipFileStream = stream;
zip.access = access;
if (zip.ReadFileInfo())
{
return zip;
}
throw new System.IO.InvalidDataException();
}
/// <summary>
/// Add full contents of a file into the Zip storage.
/// </summary>
/// <param name="compressionMethod">Compression method used to store the file.</param>
/// <param name="sourceFile">Full path of file to add to Zip storage.</param>
/// <param name="fileNameInZip">File name and path as desired in Zip directory.</param>
/// <param name="fileEntryComment">Comment for stored file.</param>
public void AddFile(CompressionMethod compressionMethod, string sourceFile, string fileNameInZip, string fileEntryComment)
{
if (this.access == FileAccess.Read)
{
throw new InvalidOperationException("Writing is not allowed");
}
using (FileStream stream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
{
this.AddStream(compressionMethod, stream, fileNameInZip, File.GetLastWriteTime(sourceFile), fileEntryComment);
}
}
/// <summary>
/// Add full contents of a stream into the Zip storage.
/// </summary>
/// <param name="compressionMethod">Compression method used to store the stream.</param>
/// <param name="sourceStream">Stream object containing the data to store in Zip.</param>
/// <param name="fileNameInZip">File name and path as desired in Zip directory.</param>
/// <param name="modificationTimeStamp">Modification time of the data to store.</param>
/// <param name="fileEntryComment">Comment for stored file.</param>
public void AddStream(CompressionMethod compressionMethod, Stream sourceStream, string fileNameInZip, DateTime modificationTimeStamp, string fileEntryComment)
{
if (this.access == FileAccess.Read)
{
throw new InvalidOperationException("Writing is not allowed");
}
// Prepare the fileinfo
ZipFileEntry zipFileEntry = default(ZipFileEntry);
zipFileEntry.Method = compressionMethod;
zipFileEntry.EncodeUTF8 = this.EncodeUtf8;
zipFileEntry.FilenameInZip = NormalizeFileName(fileNameInZip);
zipFileEntry.Comment = fileEntryComment == null ? string.Empty : fileEntryComment;
// Even though we write the header now, it will have to be rewritten, since we don't know compressed size or crc.
zipFileEntry.Crc32 = 0; // to be updated later
zipFileEntry.HeaderOffset = (uint)this.zipFileStream.Position; // offset within file of the start of this local record
zipFileEntry.ModifyTime = modificationTimeStamp;
// Write local header
this.WriteLocalHeader(ref zipFileEntry);
zipFileEntry.FileOffset = (uint)this.zipFileStream.Position;
// Write file to zip (store)
this.Store(ref zipFileEntry, sourceStream);
sourceStream.Close();
this.UpdateCrcAndSizes(ref zipFileEntry);
this.files.Add(zipFileEntry);
}
/// <summary>
/// Updates central directory (if needed) and close the Zip storage.
/// </summary>
/// <remarks>This is a required step, unless automatic dispose is used.</remarks>
public void Close()
{
if (this.access != FileAccess.Read)
{
uint centralOffset = (uint)this.zipFileStream.Position;
uint centralSize = 0;
if (this.centralDirectoryImage != null)
{
this.zipFileStream.Write(this.centralDirectoryImage, 0, this.centralDirectoryImage.Length);
}
for (int i = 0; i < this.files.Count; i++)
{
long pos = this.zipFileStream.Position;
this.WriteCentralDirRecord(this.files[i]);
centralSize += (uint)(this.zipFileStream.Position - pos);
}
if (this.centralDirectoryImage != null)
{
this.WriteEndRecord(centralSize + (uint)this.centralDirectoryImage.Length, centralOffset);
}
else
{
this.WriteEndRecord(centralSize, centralOffset);
}
}
if (this.zipFileStream != null)
{
this.zipFileStream.Flush();
this.zipFileStream.Dispose();
this.zipFileStream = null;
}
}
/// <summary>
/// Read all the file records in the central directory.
/// </summary>
/// <returns>List of all entries in directory.</returns>
public List<ZipFileEntry> ReadCentralDirectory()
{
if (this.centralDirectoryImage == null)
{
throw new InvalidOperationException("Central directory currently does not exist");
}
List<ZipFileEntry> result = new List<ZipFileEntry>();
int pointer = 0;
while (pointer < this.centralDirectoryImage.Length)
{
uint signature = BitConverter.ToUInt32(this.centralDirectoryImage, pointer);
if (signature != 0x02014b50)
{
break;
}
bool isUTF8Encoded = (BitConverter.ToUInt16(this.centralDirectoryImage, pointer + 8) & 0x0800) != 0;
ushort method = BitConverter.ToUInt16(this.centralDirectoryImage, pointer + 10);
uint modifyTime = BitConverter.ToUInt32(this.centralDirectoryImage, pointer + 12);
uint crc32 = BitConverter.ToUInt32(this.centralDirectoryImage, pointer + 16);
uint comprSize = BitConverter.ToUInt32(this.centralDirectoryImage, pointer + 20);
uint fileSize = BitConverter.ToUInt32(this.centralDirectoryImage, pointer + 24);
ushort filenameSize = BitConverter.ToUInt16(this.centralDirectoryImage, pointer + 28);
ushort extraSize = BitConverter.ToUInt16(this.centralDirectoryImage, pointer + 30);
ushort commentSize = BitConverter.ToUInt16(this.centralDirectoryImage, pointer + 32);
uint headerOffset = BitConverter.ToUInt32(this.centralDirectoryImage, pointer + 42);
uint headerSize = (uint)(46 + filenameSize + extraSize + commentSize);
Encoding encoder = isUTF8Encoded ? Encoding.UTF8 : defaultEncoding;
ZipFileEntry zfe = default(ZipFileEntry);
zfe.Method = (CompressionMethod)method;
zfe.FilenameInZip = encoder.GetString(this.centralDirectoryImage, pointer + 46, filenameSize);
zfe.FileOffset = this.GetFileOffset(headerOffset);
zfe.FileSize = fileSize;
zfe.CompressedSize = comprSize;
zfe.HeaderOffset = headerOffset;
zfe.HeaderSize = headerSize;
zfe.Crc32 = crc32;
zfe.ModifyTime = DosTimeToDateTime(modifyTime);
if (commentSize > 0)
{
zfe.Comment = encoder.GetString(this.centralDirectoryImage, pointer + 46 + filenameSize + extraSize, commentSize);
}
result.Add(zfe);
pointer += 46 + filenameSize + extraSize + commentSize;
}
return result;
}
/// <summary>
/// Copy the contents of a stored file into a physical file.
/// </summary>
/// <param name="zipFileEntry">Entry information of file to extract.</param>
/// <param name="destinationFileName">Name of file to store uncompressed data.</param>
/// <returns><see langword="true"/> if the file is successfully extracted; otherwise, <see langword="false"/>.</returns>
/// <remarks>Unique compression methods are Store and Deflate.</remarks>
public bool ExtractFile(ZipFileEntry zipFileEntry, string destinationFileName)
{
// Make sure the parent directory exist
string path = System.IO.Path.GetDirectoryName(destinationFileName);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
// Check it is directory. If so, do nothing
if (Directory.Exists(destinationFileName))
{
return true;
}
bool result = false;
using (Stream output = new FileStream(destinationFileName, FileMode.Create, FileAccess.Write))
{
result = this.ExtractFile(zipFileEntry, output);
}
File.SetCreationTime(destinationFileName, zipFileEntry.ModifyTime);
File.SetLastWriteTime(destinationFileName, zipFileEntry.ModifyTime);
return result;
}
/// <summary>
/// Copy the contents of a stored file into an open stream.
/// </summary>
/// <param name="zipFileEntry">Entry information of file to extract.</param>
/// <param name="destinationStream">Stream to store the uncompressed data.</param>
/// <returns><see langword="true"/> if the file is successfully extracted; otherwise, <see langword="false"/>.</returns>
/// <remarks>Unique compression methods are Store and Deflate.</remarks>
public bool ExtractFile(ZipFileEntry zipFileEntry, Stream destinationStream)
{
if (!destinationStream.CanWrite)
{
throw new InvalidOperationException("Stream cannot be written");
}
// check signature
byte[] signature = new byte[4];
this.zipFileStream.Seek(zipFileEntry.HeaderOffset, SeekOrigin.Begin);
this.zipFileStream.Read(signature, 0, 4);
if (BitConverter.ToUInt32(signature, 0) != 0x04034b50)
{
return false;
}
// Select input stream for inflating or just reading
Stream inStream;
if (zipFileEntry.Method == CompressionMethod.Store)
{
inStream = this.zipFileStream;
}
else if (zipFileEntry.Method == CompressionMethod.Deflate)
{
inStream = new DeflateStream(this.zipFileStream, CompressionMode.Decompress, true);
}
else
{
return false;
}
// Buffered copy
byte[] buffer = new byte[16384];
this.zipFileStream.Seek(zipFileEntry.FileOffset, SeekOrigin.Begin);
uint bytesPending = zipFileEntry.FileSize;
while (bytesPending > 0)
{
int bytesRead = inStream.Read(buffer, 0, (int)Math.Min(bytesPending, buffer.Length));
destinationStream.Write(buffer, 0, bytesRead);
bytesPending -= (uint)bytesRead;
}
destinationStream.Flush();
if (zipFileEntry.Method == CompressionMethod.Deflate)
{
inStream.Dispose();
}
return true;
}
/// <summary>
/// Closes the Zip file stream.
/// </summary>
public void Dispose()
{
this.Close();
}
private static uint[] GenerateCrc32Table()
{
// Generate CRC32 table
uint[] table = new uint[256];
for (int i = 0; i < table.Length; i++)
{
uint c = (uint)i;
for (int j = 0; j < 8; j++)
{
if ((c & 1) != 0)
{
c = 3988292384 ^ (c >> 1);
}
else
{
c >>= 1;
}
}
table[i] = c;
}
return table;
}
/* DOS Date and time:
MS-DOS date. The date is a packed value with the following format. Bits Description
0-4 Day of the month (131)
5-8 Month (1 = January, 2 = February, and so on)
9-15 Year offset from 1980 (add 1980 to get actual year)
MS-DOS time. The time is a packed value with the following format. Bits Description
0-4 Second divided by 2
5-10 Minute (059)
11-15 Hour (023 on a 24-hour clock)
*/
private static uint DateTimeToDosTime(DateTime dateTime)
{
return (uint)(
(dateTime.Second / 2) | (dateTime.Minute << 5) | (dateTime.Hour << 11) |
(dateTime.Day << 16) | (dateTime.Month << 21) | ((dateTime.Year - 1980) << 25));
}
private static DateTime DosTimeToDateTime(uint dosTime)
{
return new DateTime(
(int)(dosTime >> 25) + 1980,
(int)(dosTime >> 21) & 15,
(int)(dosTime >> 16) & 31,
(int)(dosTime >> 11) & 31,
(int)(dosTime >> 5) & 63,
(int)(dosTime & 31) * 2);
}
// Replaces backslashes with slashes to store in zip header
private static string NormalizeFileName(string fileNameToNormalize)
{
string normalizedFileName = fileNameToNormalize.Replace('\\', '/');
int pos = normalizedFileName.IndexOf(':');
if (pos >= 0)
{
normalizedFileName = normalizedFileName.Remove(0, pos + 1);
}
return normalizedFileName.Trim('/');
}
// Calculate the file offset by reading the corresponding local header
private uint GetFileOffset(uint headerOffset)
{
byte[] buffer = new byte[2];
this.zipFileStream.Seek(headerOffset + 26, SeekOrigin.Begin);
this.zipFileStream.Read(buffer, 0, 2);
ushort filenameSize = BitConverter.ToUInt16(buffer, 0);
this.zipFileStream.Read(buffer, 0, 2);
ushort extraSize = BitConverter.ToUInt16(buffer, 0);
return (uint)(30 + filenameSize + extraSize + headerOffset);
}
/* Local file header:
local file header signature 4 bytes (0x04034b50)
version needed to extract 2 bytes
general purpose bit flag 2 bytes
compression method 2 bytes
last mod file time 2 bytes
last mod file date 2 bytes
crc-32 4 bytes
compressed size 4 bytes
uncompressed size 4 bytes
filename length 2 bytes
extra field length 2 bytes
filename (variable size)
extra field (variable size)
*/
private void WriteLocalHeader(ref ZipFileEntry zipFileEntry)
{
long pos = this.zipFileStream.Position;
Encoding encoder = zipFileEntry.EncodeUTF8 ? Encoding.UTF8 : defaultEncoding;
byte[] encodedFilename = encoder.GetBytes(zipFileEntry.FilenameInZip);
this.zipFileStream.Write(new byte[] { 80, 75, 3, 4, 20, 0 }, 0, 6); // No extra header
this.zipFileStream.Write(BitConverter.GetBytes((ushort)(zipFileEntry.EncodeUTF8 ? 0x0800 : 0)), 0, 2); // filename and comment encoding
this.zipFileStream.Write(BitConverter.GetBytes((ushort)zipFileEntry.Method), 0, 2); // zipping method
this.zipFileStream.Write(BitConverter.GetBytes(DateTimeToDosTime(zipFileEntry.ModifyTime)), 0, 4); // zipping date and time
this.zipFileStream.Write(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0, 12); // unused CRC, un/compressed size, updated later
this.zipFileStream.Write(BitConverter.GetBytes((ushort)encodedFilename.Length), 0, 2); // filename length
this.zipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // extra length
this.zipFileStream.Write(encodedFilename, 0, encodedFilename.Length);
zipFileEntry.HeaderSize = (uint)(this.zipFileStream.Position - pos);
}
/* Central directory's File header:
central file header signature 4 bytes (0x02014b50)
version made by 2 bytes
version needed to extract 2 bytes
general purpose bit flag 2 bytes
compression method 2 bytes
last mod file time 2 bytes
last mod file date 2 bytes
crc-32 4 bytes
compressed size 4 bytes
uncompressed size 4 bytes
filename length 2 bytes
extra field length 2 bytes
file comment length 2 bytes
disk number start 2 bytes
internal file attributes 2 bytes
external file attributes 4 bytes
relative offset of local header 4 bytes
filename (variable size)
extra field (variable size)
file comment (variable size)
*/
private void WriteCentralDirRecord(ZipFileEntry zipFileEntry)
{
Encoding encoder = zipFileEntry.EncodeUTF8 ? Encoding.UTF8 : defaultEncoding;
byte[] encodedFilename = encoder.GetBytes(zipFileEntry.FilenameInZip);
byte[] encodedComment = encoder.GetBytes(zipFileEntry.Comment);
this.zipFileStream.Write(new byte[] { 80, 75, 1, 2, 23, 0xB, 20, 0 }, 0, 8);
this.zipFileStream.Write(BitConverter.GetBytes((ushort)(zipFileEntry.EncodeUTF8 ? 0x0800 : 0)), 0, 2); // filename and comment encoding
this.zipFileStream.Write(BitConverter.GetBytes((ushort)zipFileEntry.Method), 0, 2); // zipping method
this.zipFileStream.Write(BitConverter.GetBytes(DateTimeToDosTime(zipFileEntry.ModifyTime)), 0, 4); // zipping date and time
this.zipFileStream.Write(BitConverter.GetBytes(zipFileEntry.Crc32), 0, 4); // file CRC
this.zipFileStream.Write(BitConverter.GetBytes(zipFileEntry.CompressedSize), 0, 4); // compressed file size
this.zipFileStream.Write(BitConverter.GetBytes(zipFileEntry.FileSize), 0, 4); // uncompressed file size
this.zipFileStream.Write(BitConverter.GetBytes((ushort)encodedFilename.Length), 0, 2); // Filename in zip
this.zipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // extra length
this.zipFileStream.Write(BitConverter.GetBytes((ushort)encodedComment.Length), 0, 2);
this.zipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // disk=0
this.zipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // file type: binary
this.zipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // Internal file attributes
this.zipFileStream.Write(BitConverter.GetBytes((ushort)0x8100), 0, 2); // External file attributes (normal/readable)
this.zipFileStream.Write(BitConverter.GetBytes(zipFileEntry.HeaderOffset), 0, 4); // Offset of header
this.zipFileStream.Write(encodedFilename, 0, encodedFilename.Length);
this.zipFileStream.Write(encodedComment, 0, encodedComment.Length);
}
/* End of central dir record:
end of central dir signature 4 bytes (0x06054b50)
number of this disk 2 bytes
number of the disk with the
start of the central directory 2 bytes
total number of entries in
the central dir on this disk 2 bytes
total number of entries in
the central dir 2 bytes
size of the central directory 4 bytes
offset of start of central
directory with respect to
the starting disk number 4 bytes
zipfile comment length 2 bytes
zipfile comment (variable size)
*/
private void WriteEndRecord(uint size, uint offset)
{
Encoding encoder = this.EncodeUtf8 ? Encoding.UTF8 : defaultEncoding;
byte[] encodedComment = encoder.GetBytes(this.comment);
this.zipFileStream.Write(new byte[] { 80, 75, 5, 6, 0, 0, 0, 0 }, 0, 8);
this.zipFileStream.Write(BitConverter.GetBytes((ushort)this.files.Count + this.existingFileCount), 0, 2);
this.zipFileStream.Write(BitConverter.GetBytes((ushort)this.files.Count + this.existingFileCount), 0, 2);
this.zipFileStream.Write(BitConverter.GetBytes(size), 0, 4);
this.zipFileStream.Write(BitConverter.GetBytes(offset), 0, 4);
this.zipFileStream.Write(BitConverter.GetBytes((ushort)encodedComment.Length), 0, 2);
this.zipFileStream.Write(encodedComment, 0, encodedComment.Length);
}
// Copies all source file into storage file
private void Store(ref ZipFileEntry zipFileEntry, Stream sourceStream)
{
byte[] buffer = new byte[16384];
int bytesRead;
uint totalRead = 0;
Stream outStream;
long posStart = this.zipFileStream.Position;
long sourceStart = sourceStream.Position;
if (zipFileEntry.Method == CompressionMethod.Store)
{
outStream = this.zipFileStream;
}
else
{
outStream = new DeflateStream(this.zipFileStream, CompressionMode.Compress, true);
}
zipFileEntry.Crc32 = 0 ^ 0xffffffff;
do
{
bytesRead = sourceStream.Read(buffer, 0, buffer.Length);
totalRead += (uint)bytesRead;
if (bytesRead > 0)
{
outStream.Write(buffer, 0, bytesRead);
for (uint i = 0; i < bytesRead; i++)
{
zipFileEntry.Crc32 = ZipStorer.crcTable[(zipFileEntry.Crc32 ^ buffer[i]) & 0xFF] ^ (zipFileEntry.Crc32 >> 8);
}
}
}
while (bytesRead == buffer.Length);
outStream.Flush();
if (zipFileEntry.Method == CompressionMethod.Deflate)
{
outStream.Dispose();
}
zipFileEntry.Crc32 ^= 0xffffffff;
zipFileEntry.FileSize = totalRead;
zipFileEntry.CompressedSize = (uint)(this.zipFileStream.Position - posStart);
// Verify for real compression
if (zipFileEntry.Method == CompressionMethod.Deflate && !this.ForceDeflating && sourceStream.CanSeek && zipFileEntry.CompressedSize > zipFileEntry.FileSize)
{
// Start operation again with Store algorithm
zipFileEntry.Method = CompressionMethod.Store;
this.zipFileStream.Position = posStart;
this.zipFileStream.SetLength(posStart);
sourceStream.Position = sourceStart;
this.Store(ref zipFileEntry, sourceStream);
}
}
/* CRC32 algorithm
The 'magic number' for the CRC is 0xdebb20e3.
The proper CRC pre and post conditioning
is used, meaning that the CRC register is
pre-conditioned with all ones (a starting value
of 0xffffffff) and the value is post-conditioned by
taking the one's complement of the CRC residual.
If bit 3 of the general purpose flag is set, this
field is set to zero in the local header and the correct
value is put in the data descriptor and in the central
directory.
*/
private void UpdateCrcAndSizes(ref ZipFileEntry zipFileEntry)
{
long lastPos = this.zipFileStream.Position; // remember position
this.zipFileStream.Position = zipFileEntry.HeaderOffset + 8;
this.zipFileStream.Write(BitConverter.GetBytes((ushort)zipFileEntry.Method), 0, 2); // zipping method
this.zipFileStream.Position = zipFileEntry.HeaderOffset + 14;
this.zipFileStream.Write(BitConverter.GetBytes(zipFileEntry.Crc32), 0, 4); // Update CRC
this.zipFileStream.Write(BitConverter.GetBytes(zipFileEntry.CompressedSize), 0, 4); // Compressed size
this.zipFileStream.Write(BitConverter.GetBytes(zipFileEntry.FileSize), 0, 4); // Uncompressed size
this.zipFileStream.Position = lastPos; // restore position
}
// Reads the end-of-central-directory record
private bool ReadFileInfo()
{
if (this.zipFileStream.Length < 22)
{
return false;
}
try
{
this.zipFileStream.Seek(-17, SeekOrigin.End);
BinaryReader br = new BinaryReader(this.zipFileStream);
do
{
this.zipFileStream.Seek(-5, SeekOrigin.Current);
uint sig = br.ReadUInt32();
if (sig == 0x06054b50)
{
this.zipFileStream.Seek(6, SeekOrigin.Current);
ushort entries = br.ReadUInt16();
int centralSize = br.ReadInt32();
uint centralDirOffset = br.ReadUInt32();
ushort commentSize = br.ReadUInt16();
// check if comment field is the very last data in file
if (this.zipFileStream.Position + commentSize != this.zipFileStream.Length)
{
return false;
}
// Copy entire central directory to a memory buffer
this.existingFileCount = entries;
this.centralDirectoryImage = new byte[centralSize];
this.zipFileStream.Seek(centralDirOffset, SeekOrigin.Begin);
this.zipFileStream.Read(this.centralDirectoryImage, 0, centralSize);
// Leave the pointer at the begining of central dir, to append new files
this.zipFileStream.Seek(centralDirOffset, SeekOrigin.Begin);
return true;
}
}
while (this.zipFileStream.Position > 0);
}
catch (IOException)
{
}
return false;
}
/// <summary>
/// Represents an entry in Zip file directory
/// </summary>
public struct ZipFileEntry
{
/// <summary>Compression method</summary>
public CompressionMethod Method;
/// <summary>Full path and filename as stored in Zip</summary>
public string FilenameInZip;
/// <summary>Original file size</summary>
public uint FileSize;
/// <summary>Compressed file size</summary>
public uint CompressedSize;
/// <summary>Offset of header information inside Zip storage</summary>
public uint HeaderOffset;
/// <summary>Offset of file inside Zip storage</summary>
public uint FileOffset;
/// <summary>Size of header information</summary>
public uint HeaderSize;
/// <summary>32-bit checksum of entire file</summary>
public uint Crc32;
/// <summary>Last modification time of file</summary>
public DateTime ModifyTime;
/// <summary>User comment for file</summary>
public string Comment;
/// <summary>True if UTF8 encoding for filename and comments, false if default (CP 437)</summary>
public bool EncodeUTF8;
/// <summary>Overriden method</summary>
/// <returns>Filename in Zip</returns>
public override string ToString()
{
return this.FilenameInZip;
}
}
}
}
| anshumanchatterji/selenium | dotnet/src/webdriver/Internal/ZipStorer.cs | C# | apache-2.0 | 32,875 |
/*
* Copyright 2017 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.gradle.api.internal.artifacts.dependencies;
import com.google.common.base.Objects;
import com.google.common.base.Strings;
import org.gradle.api.Action;
import org.gradle.api.artifacts.DependencyConstraint;
import org.gradle.api.artifacts.ModuleIdentifier;
import org.gradle.api.artifacts.ModuleVersionIdentifier;
import org.gradle.api.artifacts.MutableVersionConstraint;
import org.gradle.api.artifacts.VersionConstraint;
import org.gradle.api.attributes.AttributeContainer;
import org.gradle.api.internal.artifacts.DefaultModuleIdentifier;
import org.gradle.api.internal.artifacts.ModuleVersionSelectorStrictSpec;
import org.gradle.api.internal.attributes.AttributeContainerInternal;
import org.gradle.api.internal.attributes.ImmutableAttributes;
import org.gradle.api.internal.attributes.ImmutableAttributesFactory;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import javax.annotation.Nullable;
public class DefaultDependencyConstraint implements DependencyConstraintInternal {
private final static Logger LOG = Logging.getLogger(DefaultDependencyConstraint.class);
private final ModuleIdentifier moduleIdentifier;
private final MutableVersionConstraint versionConstraint;
private String reason;
private ImmutableAttributesFactory attributesFactory;
private AttributeContainerInternal attributes;
private boolean force;
public DefaultDependencyConstraint(String group, String name, String version) {
this.moduleIdentifier = DefaultModuleIdentifier.newId(group, name);
this.versionConstraint = new DefaultMutableVersionConstraint(version);
}
public static DefaultDependencyConstraint strictly(String group, String name, String strictVersion) {
DefaultMutableVersionConstraint versionConstraint = new DefaultMutableVersionConstraint((String) null);
versionConstraint.strictly(strictVersion);
return new DefaultDependencyConstraint(DefaultModuleIdentifier.newId(group, name), versionConstraint);
}
public DefaultDependencyConstraint(ModuleIdentifier module, VersionConstraint versionConstraint) {
this(module, new DefaultMutableVersionConstraint(versionConstraint));
}
private DefaultDependencyConstraint(ModuleIdentifier module, MutableVersionConstraint versionConstraint) {
this.moduleIdentifier = module;
this.versionConstraint = versionConstraint;
}
@Nullable
@Override
public String getGroup() {
return moduleIdentifier.getGroup();
}
@Override
public String getName() {
return moduleIdentifier.getName();
}
@Override
public String getVersion() {
return Strings.emptyToNull(versionConstraint.getRequiredVersion());
}
@Override
public AttributeContainer getAttributes() {
return attributes == null ? ImmutableAttributes.EMPTY : attributes.asImmutable();
}
@Override
public DependencyConstraint attributes(Action<? super AttributeContainer> configureAction) {
if (attributesFactory == null) {
warnAboutInternalApiUse();
return this;
}
if (attributes == null) {
attributes = attributesFactory.mutable();
}
configureAction.execute(attributes);
return this;
}
private void warnAboutInternalApiUse() {
LOG.warn("Cannot set attributes for constraint \"" + this.getGroup() + ":" + this.getName() + ":" + this.getVersion() + "\": it was probably created by a plugin using internal APIs");
}
public void setAttributesFactory(ImmutableAttributesFactory attributesFactory) {
this.attributesFactory = attributesFactory;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultDependencyConstraint that = (DefaultDependencyConstraint) o;
return Objects.equal(moduleIdentifier, that.moduleIdentifier) &&
Objects.equal(versionConstraint, that.versionConstraint) &&
Objects.equal(attributes, that.attributes) &&
force == that.force;
}
@Override
public int hashCode() {
return Objects.hashCode(moduleIdentifier, versionConstraint, attributes);
}
@Override
public void version(Action<? super MutableVersionConstraint> configureAction) {
configureAction.execute(versionConstraint);
}
@Override
public VersionConstraint getVersionConstraint() {
return versionConstraint;
}
@Override
public boolean matchesStrictly(ModuleVersionIdentifier identifier) {
return new ModuleVersionSelectorStrictSpec(this).isSatisfiedBy(identifier);
}
@Override
public ModuleIdentifier getModule() {
return moduleIdentifier;
}
@Override
public String getReason() {
return reason;
}
@Override
public void because(String reason) {
this.reason = reason;
}
@Override
public DependencyConstraint copy() {
DefaultDependencyConstraint constraint = new DefaultDependencyConstraint(moduleIdentifier, versionConstraint);
constraint.reason = reason;
constraint.attributes = attributes;
constraint.attributesFactory = attributesFactory;
constraint.force = force;
return constraint;
}
@Override
public String toString() {
return "constraint " +
moduleIdentifier + ":" + versionConstraint +
", attributes=" + attributes;
}
@Override
public void setForce(boolean force) {
this.force = force;
}
@Override
public boolean isForce() {
return force;
}
}
| gradle/gradle | subprojects/dependency-management/src/main/java/org/gradle/api/internal/artifacts/dependencies/DefaultDependencyConstraint.java | Java | apache-2.0 | 6,416 |
<?php
/*
|--------------------|
| SORTING |
|--------------------|
*/
$equal_search = array('visibility');
$default_sort_by = "category_name";
$pgdata = page_init($equal_search,$default_sort_by); // static/general.php
$page = $pgdata['page'];
$query_per_page = $pgdata['query_per_page'];
$sort_by = $pgdata['sort_by'];
$first_record = $pgdata['first_record'];
$search_parameter = $pgdata['search_parameter'];
$search_value = $pgdata['search_value'];
$search_query = $pgdata['search_query'];
$search = $pgdata['search'];
$full_order = count_city($search_query, $sort_by, $query_per_page);
$total_query = $full_order['total_query'];
$total_page = ceil($full_order['total_query'] / $query_per_page);
// CALL FUNCTION
$listing_order = get_city($search_query, $sort_by, $first_record, $query_per_page);
// HANDLING ARROW SORTING
if($_REQUEST['srt'] == "category_name DESC"){
$arr_order_number = "<span class=\"sort-arrow-up\"></span>";
}else if($_REQUEST['srt'] == "category_name"){
$arr_order_number = "<span class=\"sort-arrow-down\"></span>";
}else{
$arr_order_number = "<span class=\"sort-arrow-down\"></span>";
}
// STORED VALUE
echo "<input type=\"hidden\" name=\"url\" id=\"url\" class=\"hidden\" value=\"http://".$_SERVER['HTTP_HOST'].get_dirname($_SERVER['PHP_SELF'])."/career-city-view\">\n";
echo "<input type=\"hidden\" name=\"page\" id=\"page\" class=\"hidden\" value=\"".$page."\" /> \n";
echo "<input type=\"hidden\" name=\"query_per_page\" id=\"query_per_page\" class=\"hidden\" value=\"".$query_per_page."\" /> \n";
echo "<input type=\"hidden\" name=\"total_page\" id=\"total_page\" class=\"hidden\" value=\"".ceil($full_order['total_query'] / $query_per_page)."\" /> \n";
echo "<input type=\"hidden\" name=\"sort_by\" id=\"sort_by\" class=\"hidden\" value=\"".$sort_by."\" /> \n";
echo "<input type=\"hidden\" name=\"search\" id=\"search\" class=\"hidden\" value=\"".$search_parameter."-".$search_value."\" /> \n";
if(isset($_POST['btn_add_store_city'])){
// DEFINED VARIABLE
$active = '1';
$visibility = $_POST['visibility_status'];
$city_name = stripslashes($_POST['category_name']);
insert($city_name, $active, $visibility);
$_SESSION['alert'] = 'success';
$_SESSION['msg'] = 'Item has been successfully saved.';
}
?> | masmomo/wanderlust-v3 | admin/custom/store/add/control.php | PHP | apache-2.0 | 2,359 |
/*
Copyright 2014 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package apiserver
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"reflect"
"regexp"
"strings"
"sync"
"testing"
"time"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/errors"
"k8s.io/kubernetes/pkg/api/testapi"
)
type fakeRL bool
func (fakeRL) Stop() {}
func (f fakeRL) CanAccept() bool { return bool(f) }
func (f fakeRL) Accept() {}
func expectHTTP(url string, code int, t *testing.T) {
r, err := http.Get(url)
if err != nil {
t.Errorf("unexpected error: %v", err)
return
}
if r.StatusCode != code {
t.Errorf("unexpected response: %v", r.StatusCode)
}
}
func getPath(resource, namespace, name string) string {
return testapi.Default.ResourcePath(resource, namespace, name)
}
func pathWithPrefix(prefix, resource, namespace, name string) string {
return testapi.Default.ResourcePathWithPrefix(prefix, resource, namespace, name)
}
func TestMaxInFlight(t *testing.T) {
const Iterations = 3
block := sync.WaitGroup{}
block.Add(1)
oneFinished := sync.WaitGroup{}
oneFinished.Add(1)
var once sync.Once
sem := make(chan bool, Iterations)
re := regexp.MustCompile("[.*\\/watch][^\\/proxy.*]")
// Calls verifies that the server is actually blocked up before running the rest of the test
calls := &sync.WaitGroup{}
calls.Add(Iterations * 3)
server := httptest.NewServer(MaxInFlightLimit(sem, re, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "dontwait") {
return
}
if calls != nil {
calls.Done()
}
block.Wait()
})))
defer server.Close()
// These should hang, but not affect accounting.
for i := 0; i < Iterations; i++ {
// These should hang waiting on block...
go func() {
expectHTTP(server.URL+"/foo/bar/watch", http.StatusOK, t)
once.Do(oneFinished.Done)
}()
}
for i := 0; i < Iterations; i++ {
// These should hang waiting on block...
go func() {
expectHTTP(server.URL+"/proxy/foo/bar", http.StatusOK, t)
once.Do(oneFinished.Done)
}()
}
expectHTTP(server.URL+"/dontwait", http.StatusOK, t)
for i := 0; i < Iterations; i++ {
// These should hang waiting on block...
go func() {
expectHTTP(server.URL, http.StatusOK, t)
once.Do(oneFinished.Done)
}()
}
calls.Wait()
calls = nil
// Do this multiple times to show that it rate limit rejected requests don't block.
for i := 0; i < 2; i++ {
expectHTTP(server.URL, errors.StatusTooManyRequests, t)
}
// Validate that non-accounted URLs still work
expectHTTP(server.URL+"/dontwait/watch", http.StatusOK, t)
block.Done()
// Show that we recover from being blocked up.
// However, we should until at least one of the requests really finishes.
oneFinished.Wait()
expectHTTP(server.URL, http.StatusOK, t)
}
func TestReadOnly(t *testing.T) {
server := httptest.NewServer(ReadOnly(http.HandlerFunc(
func(w http.ResponseWriter, req *http.Request) {
if req.Method != "GET" {
t.Errorf("Unexpected call: %v", req.Method)
}
},
)))
defer server.Close()
for _, verb := range []string{"GET", "POST", "PUT", "DELETE", "CREATE"} {
req, err := http.NewRequest(verb, server.URL, nil)
if err != nil {
t.Fatalf("Couldn't make request: %v", err)
}
http.DefaultClient.Do(req)
}
}
func TestTimeout(t *testing.T) {
sendResponse := make(chan struct{}, 1)
writeErrors := make(chan error, 1)
timeout := make(chan time.Time, 1)
resp := "test response"
timeoutResp := "test timeout"
ts := httptest.NewServer(TimeoutHandler(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
<-sendResponse
_, err := w.Write([]byte(resp))
writeErrors <- err
}),
func(*http.Request) (<-chan time.Time, string) {
return timeout, timeoutResp
}))
defer ts.Close()
// No timeouts
sendResponse <- struct{}{}
res, err := http.Get(ts.URL)
if err != nil {
t.Error(err)
}
if res.StatusCode != http.StatusOK {
t.Errorf("got res.StatusCode %d; expected %d", res.StatusCode, http.StatusOK)
}
body, _ := ioutil.ReadAll(res.Body)
if string(body) != resp {
t.Errorf("got body %q; expected %q", string(body), resp)
}
if err := <-writeErrors; err != nil {
t.Errorf("got unexpected Write error on first request: %v", err)
}
// Times out
timeout <- time.Time{}
res, err = http.Get(ts.URL)
if err != nil {
t.Error(err)
}
if res.StatusCode != http.StatusGatewayTimeout {
t.Errorf("got res.StatusCode %d; expected %d", res.StatusCode, http.StatusServiceUnavailable)
}
body, _ = ioutil.ReadAll(res.Body)
if string(body) != timeoutResp {
t.Errorf("got body %q; expected %q", string(body), timeoutResp)
}
// Now try to send a response
sendResponse <- struct{}{}
if err := <-writeErrors; err != http.ErrHandlerTimeout {
t.Errorf("got Write error of %v; expected %v", err, http.ErrHandlerTimeout)
}
}
func TestGetAPIRequestInfo(t *testing.T) {
successCases := []struct {
method string
url string
expectedVerb string
expectedAPIPrefix string
expectedAPIGroup string
expectedAPIVersion string
expectedNamespace string
expectedResource string
expectedSubresource string
expectedName string
expectedParts []string
}{
// resource paths
{"GET", "/api/v1/namespaces", "list", "api", "", "v1", "", "namespaces", "", "", []string{"namespaces"}},
{"GET", "/api/v1/namespaces/other", "get", "api", "", "v1", "other", "namespaces", "", "other", []string{"namespaces", "other"}},
{"GET", "/api/v1/namespaces/other/pods", "list", "api", "", "v1", "other", "pods", "", "", []string{"pods"}},
{"GET", "/api/v1/namespaces/other/pods/foo", "get", "api", "", "v1", "other", "pods", "", "foo", []string{"pods", "foo"}},
{"GET", "/api/v1/pods", "list", "api", "", "v1", api.NamespaceAll, "pods", "", "", []string{"pods"}},
{"GET", "/api/v1/namespaces/other/pods/foo", "get", "api", "", "v1", "other", "pods", "", "foo", []string{"pods", "foo"}},
{"GET", "/api/v1/namespaces/other/pods", "list", "api", "", "v1", "other", "pods", "", "", []string{"pods"}},
// special verbs
{"GET", "/api/v1/proxy/namespaces/other/pods/foo", "proxy", "api", "", "v1", "other", "pods", "", "foo", []string{"pods", "foo"}},
{"GET", "/api/v1/redirect/namespaces/other/pods/foo", "redirect", "api", "", "v1", "other", "pods", "", "foo", []string{"pods", "foo"}},
{"GET", "/api/v1/watch/pods", "watch", "api", "", "v1", api.NamespaceAll, "pods", "", "", []string{"pods"}},
{"GET", "/api/v1/watch/namespaces/other/pods", "watch", "api", "", "v1", "other", "pods", "", "", []string{"pods"}},
// subresource identification
{"GET", "/api/v1/namespaces/other/pods/foo/status", "get", "api", "", "v1", "other", "pods", "status", "foo", []string{"pods", "foo", "status"}},
{"PUT", "/api/v1/namespaces/other/finalize", "update", "api", "", "v1", "other", "finalize", "", "", []string{"finalize"}},
// verb identification
{"PATCH", "/api/v1/namespaces/other/pods/foo", "patch", "api", "", "v1", "other", "pods", "", "foo", []string{"pods", "foo"}},
{"DELETE", "/api/v1/namespaces/other/pods/foo", "delete", "api", "", "v1", "other", "pods", "", "foo", []string{"pods", "foo"}},
{"POST", "/api/v1/namespaces/other/pods", "create", "api", "", "v1", "other", "pods", "", "", []string{"pods"}},
// api group identification
{"POST", "/apis/experimental/v1/namespaces/other/pods", "create", "api", "experimental", "v1", "other", "pods", "", "", []string{"pods"}},
// api version identification
{"POST", "/apis/experimental/v1beta3/namespaces/other/pods", "create", "api", "experimental", "v1beta3", "other", "pods", "", "", []string{"pods"}},
}
apiRequestInfoResolver := newTestAPIRequestInfoResolver()
for _, successCase := range successCases {
req, _ := http.NewRequest(successCase.method, successCase.url, nil)
apiRequestInfo, err := apiRequestInfoResolver.GetAPIRequestInfo(req)
if err != nil {
t.Errorf("Unexpected error for url: %s %v", successCase.url, err)
}
if successCase.expectedVerb != apiRequestInfo.Verb {
t.Errorf("Unexpected verb for url: %s, expected: %s, actual: %s", successCase.url, successCase.expectedVerb, apiRequestInfo.Verb)
}
if successCase.expectedAPIVersion != apiRequestInfo.APIVersion {
t.Errorf("Unexpected apiVersion for url: %s, expected: %s, actual: %s", successCase.url, successCase.expectedAPIVersion, apiRequestInfo.APIVersion)
}
if successCase.expectedNamespace != apiRequestInfo.Namespace {
t.Errorf("Unexpected namespace for url: %s, expected: %s, actual: %s", successCase.url, successCase.expectedNamespace, apiRequestInfo.Namespace)
}
if successCase.expectedResource != apiRequestInfo.Resource {
t.Errorf("Unexpected resource for url: %s, expected: %s, actual: %s", successCase.url, successCase.expectedResource, apiRequestInfo.Resource)
}
if successCase.expectedSubresource != apiRequestInfo.Subresource {
t.Errorf("Unexpected resource for url: %s, expected: %s, actual: %s", successCase.url, successCase.expectedSubresource, apiRequestInfo.Subresource)
}
if successCase.expectedName != apiRequestInfo.Name {
t.Errorf("Unexpected name for url: %s, expected: %s, actual: %s", successCase.url, successCase.expectedName, apiRequestInfo.Name)
}
if !reflect.DeepEqual(successCase.expectedParts, apiRequestInfo.Parts) {
t.Errorf("Unexpected parts for url: %s, expected: %v, actual: %v", successCase.url, successCase.expectedParts, apiRequestInfo.Parts)
}
}
errorCases := map[string]string{
"no resource path": "/",
"just apiversion": "/api/version/",
"just prefix, group, version": "/apis/group/version/",
"apiversion with no resource": "/api/version/",
"bad prefix": "/badprefix/version/resource",
"missing api group": "/apis/version/resource",
}
for k, v := range errorCases {
req, err := http.NewRequest("GET", v, nil)
if err != nil {
t.Errorf("Unexpected error %v", err)
}
_, err = apiRequestInfoResolver.GetAPIRequestInfo(req)
if err == nil {
t.Errorf("Expected error for key: %s", k)
}
}
}
| chiefy/kubernetes | pkg/apiserver/handlers_test.go | GO | apache-2.0 | 10,648 |
#!/usr/bin/python
import sys
def tokens(nodes):
for i in range(0, nodes):
print (i * (2 ** 127 - 1) / nodes)
tokens(int(sys.argv[1]))
| aglne/Solandra | scripts/get_initial_tokens.py | Python | apache-2.0 | 148 |
// Copyright (c) 2016 Google
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and/or associated documentation files (the
// "Materials"), to deal in the Materials without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Materials, and to
// permit persons to whom the Materials are furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Materials.
//
// MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS
// KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS
// SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT
// https://www.khronos.org/registry/
//
// THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
#include "TestFixture.h"
#include "gmock/gmock.h"
namespace {
using ::spvtest::MakeInstruction;
using ::testing::Eq;
using OpTypePipeStorageTest = spvtest::TextToBinaryTest;
TEST_F(OpTypePipeStorageTest, OpcodeUnrecognizedInV10) {
EXPECT_THAT(CompileFailure("%res = OpTypePipeStorage", SPV_ENV_UNIVERSAL_1_0),
Eq("Invalid Opcode name 'OpTypePipeStorage'"));
}
TEST_F(OpTypePipeStorageTest, ArgumentCount) {
EXPECT_THAT(
CompileFailure("OpTypePipeStorage", SPV_ENV_UNIVERSAL_1_1),
Eq("Expected <result-id> at the beginning of an instruction, found "
"'OpTypePipeStorage'."));
EXPECT_THAT(
CompiledInstructions("%res = OpTypePipeStorage", SPV_ENV_UNIVERSAL_1_1),
Eq(MakeInstruction(SpvOpTypePipeStorage, {1})));
EXPECT_THAT(CompileFailure("%res = OpTypePipeStorage %1 %2 %3 %4 %5",
SPV_ENV_UNIVERSAL_1_1),
Eq("'=' expected after result id."));
}
using OpConstantPipeStorageTest = spvtest::TextToBinaryTest;
TEST_F(OpConstantPipeStorageTest, OpcodeUnrecognizedInV10) {
EXPECT_THAT(CompileFailure("%1 = OpConstantPipeStorage %2 3 4 5",
SPV_ENV_UNIVERSAL_1_0),
Eq("Invalid Opcode name 'OpConstantPipeStorage'"));
}
TEST_F(OpConstantPipeStorageTest, ArgumentCount) {
EXPECT_THAT(
CompileFailure("OpConstantPipeStorage", SPV_ENV_UNIVERSAL_1_1),
Eq("Expected <result-id> at the beginning of an instruction, found "
"'OpConstantPipeStorage'."));
EXPECT_THAT(
CompileFailure("%1 = OpConstantPipeStorage", SPV_ENV_UNIVERSAL_1_1),
Eq("Expected operand, found end of stream."));
EXPECT_THAT(CompileFailure("%1 = OpConstantPipeStorage %2 3 4",
SPV_ENV_UNIVERSAL_1_1),
Eq("Expected operand, found end of stream."));
EXPECT_THAT(CompiledInstructions("%1 = OpConstantPipeStorage %2 3 4 5",
SPV_ENV_UNIVERSAL_1_1),
Eq(MakeInstruction(SpvOpConstantPipeStorage, {1, 2, 3, 4, 5})));
EXPECT_THAT(CompileFailure("%1 = OpConstantPipeStorage %2 3 4 5 %6 %7",
SPV_ENV_UNIVERSAL_1_1),
Eq("'=' expected after result id."));
}
TEST_F(OpConstantPipeStorageTest, ArgumentTypes) {
EXPECT_THAT(CompileFailure("%1 = OpConstantPipeStorage %2 %3 4 5",
SPV_ENV_UNIVERSAL_1_1),
Eq("Invalid unsigned integer literal: %3"));
EXPECT_THAT(CompileFailure("%1 = OpConstantPipeStorage %2 3 %4 5",
SPV_ENV_UNIVERSAL_1_1),
Eq("Invalid unsigned integer literal: %4"));
EXPECT_THAT(CompileFailure("%1 = OpConstantPipeStorage 2 3 4 5",
SPV_ENV_UNIVERSAL_1_1),
Eq("Expected id to start with %."));
EXPECT_THAT(CompileFailure("%1 = OpConstantPipeStorage %2 3 4 \"ab\"",
SPV_ENV_UNIVERSAL_1_1),
Eq("Invalid unsigned integer literal: \"ab\""));
}
using OpCreatePipeFromPipeStorageTest = spvtest::TextToBinaryTest;
TEST_F(OpCreatePipeFromPipeStorageTest, OpcodeUnrecognizedInV10) {
EXPECT_THAT(CompileFailure("%1 = OpCreatePipeFromPipeStorage %2 %3",
SPV_ENV_UNIVERSAL_1_0),
Eq("Invalid Opcode name 'OpCreatePipeFromPipeStorage'"));
}
TEST_F(OpCreatePipeFromPipeStorageTest, ArgumentCount) {
EXPECT_THAT(
CompileFailure("OpCreatePipeFromPipeStorage", SPV_ENV_UNIVERSAL_1_1),
Eq("Expected <result-id> at the beginning of an instruction, found "
"'OpCreatePipeFromPipeStorage'."));
EXPECT_THAT(
CompileFailure("%1 = OpCreatePipeFromPipeStorage", SPV_ENV_UNIVERSAL_1_1),
Eq("Expected operand, found end of stream."));
EXPECT_THAT(CompileFailure("%1 = OpCreatePipeFromPipeStorage %2 OpNop",
SPV_ENV_UNIVERSAL_1_1),
Eq("Expected operand, found next instruction instead."));
EXPECT_THAT(CompiledInstructions("%1 = OpCreatePipeFromPipeStorage %2 %3",
SPV_ENV_UNIVERSAL_1_1),
Eq(MakeInstruction(SpvOpCreatePipeFromPipeStorage, {1, 2, 3})));
EXPECT_THAT(CompileFailure("%1 = OpCreatePipeFromPipeStorage %2 %3 %4 %5",
SPV_ENV_UNIVERSAL_1_1),
Eq("'=' expected after result id."));
}
TEST_F(OpCreatePipeFromPipeStorageTest, ArgumentTypes) {
EXPECT_THAT(CompileFailure("%1 = OpCreatePipeFromPipeStorage \"\" %3",
SPV_ENV_UNIVERSAL_1_1),
Eq("Expected id to start with %."));
EXPECT_THAT(CompileFailure("%1 = OpCreatePipeFromPipeStorage %2 3",
SPV_ENV_UNIVERSAL_1_1),
Eq("Expected id to start with %."));
}
} // anonymous namespace
| ben-clayton/gapid | third_party/khronos/SPIRV-Tools/test/TextToBinary.PipeStorage.cpp | C++ | apache-2.0 | 6,151 |
/**
*
* Copyright 2003-2007 Jive Software.
*
* 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.jivesoftware.smackx.xhtmlim;
import org.jivesoftware.smack.ConnectionCreationListener;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPConnectionRegistry;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import org.jivesoftware.smackx.xhtmlim.packet.XHTMLExtension;
import java.util.List;
/**
* Manages XHTML formatted texts within messages. A XHTMLManager provides a high level access to
* get and set XHTML bodies to messages, enable and disable XHTML support and check if remote XMPP
* clients support XHTML.
*
* @author Gaston Dombiak
*/
public class XHTMLManager {
static {
XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
public void connectionCreated(XMPPConnection connection) {
// Enable the XHTML support on every established connection
XHTMLManager.setServiceEnabled(connection, true);
}
});
}
/**
* Returns an Iterator for the XHTML bodies in the message. Returns null if
* the message does not contain an XHTML extension.
*
* @param message an XHTML message
* @return an Iterator for the bodies in the message or null if none.
*/
public static List<CharSequence> getBodies(Message message) {
XHTMLExtension xhtmlExtension = XHTMLExtension.from(message);
if (xhtmlExtension != null)
return xhtmlExtension.getBodies();
else
return null;
}
/**
* Adds an XHTML body to the message.
*
* @param message the message that will receive the XHTML body
* @param xhtmlText the string to add as an XHTML body to the message
*/
public static void addBody(Message message, XHTMLText xhtmlText) {
XHTMLExtension xhtmlExtension = XHTMLExtension.from(message);
if (xhtmlExtension == null) {
// Create an XHTMLExtension and add it to the message
xhtmlExtension = new XHTMLExtension();
message.addExtension(xhtmlExtension);
}
// Add the required bodies to the message
xhtmlExtension.addBody(xhtmlText.toXML());
}
/**
* Returns true if the message contains an XHTML extension.
*
* @param message the message to check if contains an XHTML extentsion or not
* @return a boolean indicating whether the message is an XHTML message
*/
public static boolean isXHTMLMessage(Message message) {
return message.getExtension(XHTMLExtension.ELEMENT, XHTMLExtension.NAMESPACE) != null;
}
/**
* Enables or disables the XHTML support on a given connection.<p>
*
* Before starting to send XHTML messages to a user, check that the user can handle XHTML
* messages. Enable the XHTML support to indicate that this client handles XHTML messages.
*
* @param connection the connection where the service will be enabled or disabled
* @param enabled indicates if the service will be enabled or disabled
*/
public synchronized static void setServiceEnabled(XMPPConnection connection, boolean enabled) {
if (isServiceEnabled(connection) == enabled)
return;
if (enabled) {
ServiceDiscoveryManager.getInstanceFor(connection).addFeature(XHTMLExtension.NAMESPACE);
}
else {
ServiceDiscoveryManager.getInstanceFor(connection).removeFeature(XHTMLExtension.NAMESPACE);
}
}
/**
* Returns true if the XHTML support is enabled for the given connection.
*
* @param connection the connection to look for XHTML support
* @return a boolean indicating if the XHTML support is enabled for the given connection
*/
public static boolean isServiceEnabled(XMPPConnection connection) {
return ServiceDiscoveryManager.getInstanceFor(connection).includesFeature(XHTMLExtension.NAMESPACE);
}
/**
* Returns true if the specified user handles XHTML messages.
*
* @param connection the connection to use to perform the service discovery
* @param userID the user to check. A fully qualified xmpp ID, e.g. jdoe@example.com
* @return a boolean indicating whether the specified user handles XHTML messages
* @throws XMPPErrorException
* @throws NoResponseException
* @throws NotConnectedException
*/
public static boolean isServiceEnabled(XMPPConnection connection, String userID)
throws NoResponseException, XMPPErrorException, NotConnectedException {
return ServiceDiscoveryManager.getInstanceFor(connection).supportsFeature(userID, XHTMLExtension.NAMESPACE);
}
}
| Soo000/SooChat | src/org/jivesoftware/smackx/xhtmlim/XHTMLManager.java | Java | apache-2.0 | 5,565 |
package com.maximos.mobile.challengeapp.feedpageproject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.maximos.mobile.challengeapp.FetchFriends.FriendPickerSampleActivity;
import com.maximos.mobile.challengeapp.R;
import com.maximos.mobile.challengeapp.constants.App_Constants;
import com.maximos.mobile.challengeapp.dao.ChallengeDao;
import com.maximos.mobile.challengeapp.model.Challenge;
import com.maximos.mobile.challengeapp.util.RecordAudio;
import com.maximos.mobile.challengeapp.util.UploadFile;
import com.maximos.mobile.challengeapp.util.VideoCapture;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CreateChallengeActivity extends Activity {
private static final int SELECT_AUDIO = 2;
private static final int SELECT_VIDEO = 3;
private static final int SELECT_IMAGE = 1;
String selectedPath = "";
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_TAKE_PHOTO = 1;
String mCurrentPhotoPath;
ImageView mImageView;
private static int responseCode = 0;
String fileOnServer = "";
public Logger logger = Logger.getLogger(CreateChallengeActivity.class.getName());
private static final String TAG_NAME = CreateChallengeActivity.class.getName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_challenge);
((Button) findViewById(R.id.recordAudio)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Audio "), SELECT_AUDIO);
*/
Intent intent;
intent = new Intent(CreateChallengeActivity.this, RecordAudio.class);
startActivity(intent);
}
});
((Button) findViewById(R.id.takePicture)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
});
((Button) findViewById(R.id.uploadVideo)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Video "), SELECT_VIDEO);
*/
Intent intent;
intent = new Intent(CreateChallengeActivity.this, VideoCapture.class);
startActivity(intent);
}
});
((Button) findViewById(R.id.selectFriend)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent;
intent = new Intent(CreateChallengeActivity.this, FriendPickerSampleActivity.class);
startActivity(intent);
}
});
((Button) findViewById(R.id.upload_audio)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Audio "), SELECT_AUDIO);
}
});
((Button) findViewById(R.id.upload_video)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Video "), SELECT_VIDEO);
}
});
((Button) findViewById(R.id.upload_image)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image "), SELECT_IMAGE);
}
});
((Button) findViewById(R.id.location)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
((Button) findViewById(R.id.create_challenge)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CreateChallengeTask createChallengeAsyncTask = new CreateChallengeTask();
createChallengeAsyncTask.execute((Void) null);
}
});
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
@Override
protected void onPause() {
logger.log(Level.INFO, "Inside onPause of Create Challenge class Activity");
super.onPause();
}
@Override
protected void onStop() {
logger.log(Level.INFO, "Inside OnStop in Create Challenge Class Activity ");
super.onStop();
}
@Override
protected void onStart() {
logger.log(Level.INFO, "Inside Onstart in Create challenge class activity");
super.onStart();
}
@Override
protected void onDestroy() {
logger.log(Level.INFO, "Inside OnDestroy in create challenge class activity");
super.onDestroy();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_VIDEO) {
logger.log(Level.INFO, TAG_NAME + ": Upload Video with Uri" + data.getData());
Uri selectedVideoUri = data.getData();
selectedPath = getPath(selectedVideoUri);
logger.log(Level.INFO, TAG_NAME + ": path selected" + selectedPath);
FileUploadAsyncTask fileUploadAsyncTask = new FileUploadAsyncTask(selectedPath);
fileUploadAsyncTask.execute((Void) null);
} else if (requestCode == SELECT_AUDIO) {
logger.log(Level.INFO, TAG_NAME + ": Upload Audio with Uri" + data.getData());
Uri selectedAudioUri = data.getData();
selectedPath = getPath(selectedAudioUri);
logger.log(Level.INFO, TAG_NAME + ": path selected" + selectedPath);
FileUploadAsyncTask fileUploadAsyncTask = new FileUploadAsyncTask(selectedPath);
fileUploadAsyncTask.execute((Void) null);
} else if (requestCode == SELECT_IMAGE) {
logger.log(Level.INFO, TAG_NAME + ": Upload Image with Uri" + data.getData());
Uri selectedImageUri = data.getData();
selectedPath = getPath(selectedImageUri);
logger.log(Level.INFO, TAG_NAME + ": path selected" + selectedPath);
FileUploadAsyncTask fileUploadAsyncTask = new FileUploadAsyncTask(selectedPath);
fileUploadAsyncTask.execute((Void) null);
}
if (requestCode == 200) {
TextView textView = (TextView) findViewById(R.id.uploadTextResult);
textView.setText(App_Constants.DATA_UPLOADED);
}
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
setPic();
galleryAddPic();
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
super.onActivityResult(requestCode, resultCode, data);
}
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private void setPic() {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
mImageView.setImageBitmap(bitmap);
}
public String getPath(Uri uri) {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
logger.log(Level.INFO, TAG_NAME + " : cursor" + cursor);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.create_challenge, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class FileUploadAsyncTask extends AsyncTask<Void, Void, Object> {
private String selectedPath;
private ProgressDialog pd;
FileUploadAsyncTask(String selectedPath) {
this.selectedPath = selectedPath;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(CreateChallengeActivity.this);
pd.setTitle("Uploading File..");
pd.setMessage("Please wait,File is getting sent");
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.show();
}
@Override
protected Object doInBackground(Void... params) {
UploadFile uploadFile = new UploadFile();
responseCode = uploadFile.uploadVideo(selectedPath);
fileOnServer = uploadFile.fileOnServer;
logger.log(Level.INFO, TAG_NAME + " : file on server " + fileOnServer);
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
pd.dismiss();
}
}
public class CreateChallengeTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog pd;
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(CreateChallengeActivity.this);
pd.setTitle("Creating Challenge..");
pd.setMessage("Please wait, Creating Challenge ");
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.show();
}
@Override
protected Void doInBackground(Void... voids) {
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
}
String creatorId = "";
EditText titleEditText = (EditText) findViewById(R.id.title);
String title = titleEditText.getText().toString();
EditText descEditText = (EditText) findViewById(R.id.challenge_desc);
String desc = titleEditText.getText().toString();
SharedPreferences prefs = getSharedPreferences(App_Constants.USER_PREFERENCE_FILE, getApplicationContext().MODE_PRIVATE);
Boolean isLoggedIn = prefs.getBoolean(App_Constants.IS_USER_LOGGED_IN, false);
logger.log(Level.INFO, " : " + isLoggedIn);
if (isLoggedIn) {
creatorId = prefs.getString(App_Constants.LOGGED_USER_ID, "none");
Challenge challenge = new Challenge(title, desc, 1, fileOnServer, null, null, creatorId);
ChallengeDao.createChallenge(challenge);
}
pd.dismiss();
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
} | xjbhenry/ChallengeApp | src/main/java/com/maximos/mobile/challengeapp/feedpageproject/CreateChallengeActivity.java | Java | apache-2.0 | 15,867 |
package com.planet_ink.coffee_mud.Locales;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2001-2015 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class MountainsMaze extends StdMaze
{
@Override public String ID(){return "MountainsMaze";}
public MountainsMaze()
{
super();
basePhyStats.setWeight(5);
recoverPhyStats();
}
@Override public int domainType(){return Room.DOMAIN_OUTDOORS_MOUNTAINS;}
@Override public String getGridChildLocaleID(){return "Mountains";}
@Override public List<Integer> resourceChoices(){return Mountains.roomResources;}
}
| Tycheo/coffeemud | com/planet_ink/coffee_mud/Locales/MountainsMaze.java | Java | apache-2.0 | 1,932 |
package nameserver
import (
"encoding/json"
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/miekg/dns"
"github.com/weaveworks/weave/common/docker"
"github.com/weaveworks/weave/net/address"
)
func (n *Nameserver) badRequest(w http.ResponseWriter, err error) {
http.Error(w, err.Error(), http.StatusBadRequest)
n.infof("%v", err)
}
func (n *Nameserver) HandleHTTP(router *mux.Router, dockerCli *docker.Client) {
router.Methods("GET").Path("/domain").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, n.domain)
})
router.Methods("PUT").Path("/name/{container}/{ip}").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var (
vars = mux.Vars(r)
container = vars["container"]
ipStr = vars["ip"]
hostname = dns.Fqdn(r.FormValue("fqdn"))
ip, err = address.ParseIP(ipStr)
)
if err != nil {
n.badRequest(w, err)
return
}
if !dns.IsSubDomain(n.domain, hostname) {
n.infof("Ignoring registration %s %s %s (not a subdomain of %s)", hostname, ipStr, container, n.domain)
return
}
n.AddEntry(hostname, container, n.ourName, ip)
if r.FormValue("check-alive") == "true" && dockerCli != nil && dockerCli.IsContainerNotRunning(container) {
n.infof("container '%s' is not running: removing", container)
n.Delete(hostname, container, ipStr, ip)
}
w.WriteHeader(204)
})
deleteHandler := func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
hostname := r.FormValue("fqdn")
if hostname == "" {
hostname = "*"
} else {
hostname = dns.Fqdn(hostname)
}
container, ok := vars["container"]
if !ok {
container = "*"
}
ipStr, ok := vars["ip"]
ip, err := address.ParseIP(ipStr)
if ok && err != nil {
n.badRequest(w, err)
return
} else if !ok {
ipStr = "*"
}
n.Delete(hostname, container, ipStr, ip)
w.WriteHeader(204)
}
router.Methods("DELETE").Path("/name/{container}/{ip}").HandlerFunc(deleteHandler)
router.Methods("DELETE").Path("/name/{container}").HandlerFunc(deleteHandler)
router.Methods("DELETE").Path("/name").HandlerFunc(deleteHandler)
router.Methods("GET").Path("/name").Headers("Accept", "application/json").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
n.RLock()
defer n.RUnlock()
if err := json.NewEncoder(w).Encode(n.entries); err != nil {
n.badRequest(w, fmt.Errorf("Error marshalling response: %v", err))
}
})
}
| n054/weave | nameserver/http.go | GO | apache-2.0 | 2,424 |
/*
* Copyright (c) OSGi Alliance (2012). 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.
*/
/**
* OSGi JMX Framework Wiring Package Version 1.1.
*
* <p>
* Bundles wishing to use this package must list the package in the
* Import-Package header of the bundle's manifest. This package has two types of
* users: the consumers that use the API in this package and the providers that
* implement the API in this package.
*
* <p>
* Example import for consumers using the API in this package:
* <p>
* {@code Import-Package: org.osgi.jmx.framework.wiring; version="[1.1,2.0)"}
* <p>
* Example import for providers implementing the API in this package:
* <p>
* {@code Import-Package: org.osgi.jmx.framework.wiring; version="[1.1,1.2)"}
*
* @version $Id: 9710af79a8da06986298af0dede257cbcbb6c487 $
*/
package org.osgi.jmx.framework.wiring;
| eclipse/gemini.managment | org.eclipse.gemini.management/src/main/java/org/osgi/jmx/framework/wiring/package-info.java | Java | apache-2.0 | 1,392 |
# Copyright (c) 2010-2011 OpenStack, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Tests for swift.common.compressing_file_reader """
import unittest
import cStringIO
from slogging.compressing_file_reader import CompressingFileReader
class TestCompressingFileReader(unittest.TestCase):
def test_read(self):
plain = 'obj\ndata'
s = cStringIO.StringIO(plain)
expected = '\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xff\xcaO\xca\xe2JI,'\
'I\x04\x00\x00\x00\xff\xff\x03\x00P(\xa8\x1f\x08\x00\x00'\
'\x00'
x = CompressingFileReader(s)
compressed = ''.join(iter(lambda: x.read(), ''))
self.assertEquals(compressed, expected)
self.assertEquals(x.read(), '')
| rackerlabs/sloggingo | test_slogging/unit/test_compressing_file_reader.py | Python | apache-2.0 | 1,258 |
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Common")
AddReference("QuantConnect.Indicators")
from System import *
from QuantConnect import *
from QuantConnect.Indicators import *
from QuantConnect.Data import *
from QuantConnect.Data.Market import *
from QuantConnect.Data.Custom import *
from QuantConnect.Algorithm import *
from QuantConnect.Python import PythonQuandl
### <summary>
### The algorithm creates new indicator value with the existing indicator method by Indicator Extensions
### Demonstration of using the external custom datasource Quandl to request the VIX and VXV daily data
### </summary>
### <meta name="tag" content="using data" />
### <meta name="tag" content="using quantconnect" />
### <meta name="tag" content="custom data" />
### <meta name="tag" content="indicators" />
### <meta name="tag" content="indicator classes" />
### <meta name="tag" content="plotting indicators" />
### <meta name="tag" content="charting" />
class CustomDataIndicatorExtensionsAlgorithm(QCAlgorithm):
# Initialize the data and resolution you require for your strategy
def Initialize(self):
self.SetStartDate(2014,1,1)
self.SetEndDate(2018,1,1)
self.SetCash(25000)
self.vix = 'CBOE/VIX'
self.vxv = 'CBOE/VXV'
# Define the symbol and "type" of our generic data
self.AddData(QuandlVix, self.vix, Resolution.Daily)
self.AddData(Quandl, self.vxv, Resolution.Daily)
# Set up default Indicators, these are just 'identities' of the closing price
self.vix_sma = self.SMA(self.vix, 1, Resolution.Daily)
self.vxv_sma = self.SMA(self.vxv, 1, Resolution.Daily)
# This will create a new indicator whose value is smaVXV / smaVIX
self.ratio = IndicatorExtensions.Over(self.vxv_sma, self.vix_sma)
# Plot indicators each time they update using the PlotIndicator function
self.PlotIndicator("Ratio", self.ratio)
self.PlotIndicator("Data", self.vix_sma, self.vxv_sma)
# OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
def OnData(self, data):
# Wait for all indicators to fully initialize
if not (self.vix_sma.IsReady and self.vxv_sma.IsReady and self.ratio.IsReady): return
if not self.Portfolio.Invested and self.ratio.Current.Value > 1:
self.MarketOrder(self.vix, 100)
elif self.ratio.Current.Value < 1:
self.Liquidate()
# In CBOE/VIX data, there is a "vix close" column instead of "close" which is the
# default column namein LEAN Quandl custom data implementation.
# This class assigns new column name to match the the external datasource setting.
class QuandlVix(PythonQuandl):
def __init__(self):
self.ValueColumnName = "VIX Close" | AnshulYADAV007/Lean | Algorithm.Python/CustomDataIndicatorExtensionsAlgorithm.py | Python | apache-2.0 | 3,632 |
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.util.projectWizard;
import com.intellij.ide.util.frameworkSupport.FrameworkSupportUtil;
import com.intellij.ide.util.newProjectWizard.AddModuleWizard;
import com.intellij.ide.util.newProjectWizard.SourcePathsStep;
import com.intellij.ide.util.newProjectWizard.SupportForFrameworksStep;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.SdkType;
import com.intellij.openapi.projectRoots.SdkTypeId;
import com.intellij.openapi.roots.ui.configuration.ModulesProvider;
import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainer;
import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainerFactory;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Key;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.Map;
/**
* @author Eugene Zhuravlev
* Date: Oct 6, 2004
*/
public class ProjectWizardStepFactoryImpl extends ProjectWizardStepFactory {
private static final Key<ProjectJdkStep> PROJECT_JDK_STEP_KEY = Key.create("ProjectJdkStep");
public ModuleWizardStep createNameAndLocationStep(WizardContext wizardContext, JavaModuleBuilder builder, ModulesProvider modulesProvider, Icon icon, String helpId) {
return new NameLocationStep(wizardContext, builder, modulesProvider, icon, helpId);
}
public ModuleWizardStep createNameAndLocationStep(final WizardContext wizardContext) {
return new ProjectNameStep(wizardContext);
}
/**
* @deprecated
*/
public ModuleWizardStep createOutputPathPathsStep(ModuleWizardStep nameAndLocationStep, JavaModuleBuilder builder, Icon icon, String helpId) {
return new OutputPathsStep((NameLocationStep)nameAndLocationStep, builder, icon, helpId);
}
public ModuleWizardStep createSourcePathsStep(ModuleWizardStep nameAndLocationStep, SourcePathsBuilder builder, Icon icon, String helpId) {
return null;
}
public ModuleWizardStep createSourcePathsStep(final WizardContext context, final SourcePathsBuilder builder, final Icon icon, @NonNls final String helpId) {
return new SourcePathsStep(builder, icon, helpId);
}
/**
* @deprecated
*/
public ModuleWizardStep createProjectJdkStep(WizardContext context,
final JavaModuleBuilder builder,
final Computable<Boolean> isVisible,
final Icon icon,
final String helpId) {
return createProjectJdkStep(context, null, builder, isVisible, icon, helpId);
}
public ModuleWizardStep createProjectJdkStep(WizardContext context,
SdkType type,
final JavaModuleBuilder builder,
final Computable<Boolean> isVisible,
final Icon icon,
@NonNls final String helpId) {
return new ProjectJdkForModuleStep(context, type){
public void updateDataModel() {
super.updateDataModel();
builder.setModuleJdk(getJdk());
}
public boolean isStepVisible() {
return isVisible.compute().booleanValue();
}
public Icon getIcon() {
return icon;
}
@Override
public String getName() {
return "Specify JDK";
}
public String getHelpId() {
return helpId;
}
};
}
public ModuleWizardStep createProjectJdkStep(final WizardContext wizardContext) {
ProjectJdkStep projectSdkStep = wizardContext.getUserData(PROJECT_JDK_STEP_KEY);
if (projectSdkStep != null) {
return projectSdkStep;
}
projectSdkStep = new ProjectJdkStep(wizardContext) {
public boolean isStepVisible() {
final Sdk newProjectJdk = AddModuleWizard.getProjectSdkByDefault(wizardContext);
if (newProjectJdk == null) return true;
final ProjectBuilder projectBuilder = wizardContext.getProjectBuilder();
return projectBuilder != null && !projectBuilder.isSuitableSdk(newProjectJdk);
}
};
wizardContext.putUserData(PROJECT_JDK_STEP_KEY, projectSdkStep);
return projectSdkStep;
}
@Nullable
@Override
public Sdk getNewProjectSdk(WizardContext wizardContext) {
return AddModuleWizard.getNewProjectJdk(wizardContext);
}
@Override
public ModuleWizardStep createSupportForFrameworksStep(WizardContext wizardContext, ModuleBuilder moduleBuilder) {
return createSupportForFrameworksStep(wizardContext, moduleBuilder, ModulesProvider.EMPTY_MODULES_PROVIDER);
}
@Override
public ModuleWizardStep createSupportForFrameworksStep(@NotNull WizardContext context, @NotNull ModuleBuilder builder, @NotNull ModulesProvider modulesProvider) {
Map<String,Boolean> availableFrameworks = builder.getAvailableFrameworks();
if (FrameworkSupportUtil.getProviders(builder).isEmpty() || availableFrameworks != null && availableFrameworks.isEmpty()) {
return null;
}
final LibrariesContainer container = LibrariesContainerFactory.createContainer(context, modulesProvider);
return new SupportForFrameworksStep(context, builder, container);
}
@Override
public ModuleWizardStep createJavaSettingsStep(@NotNull SettingsStep settingsStep, @NotNull ModuleBuilder moduleBuilder, @NotNull Condition<SdkTypeId> sdkFilter) {
return new JavaSettingsStep(settingsStep, moduleBuilder, sdkFilter);
}
}
| liveqmock/platform-tools-idea | java/idea-ui/src/com/intellij/ide/util/projectWizard/ProjectWizardStepFactoryImpl.java | Java | apache-2.0 | 6,321 |
angular.module('breadcrumbs', []); | caguillen214/directive-director | demoApp/components/breadcrumbs/breadcrumbs.js | JavaScript | apache-2.0 | 34 |
/*
* Copyright (c) 2008-2017, 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.mapreduce.aggregation.impl;
import com.hazelcast.mapreduce.CombinerFactory;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.IdentifiedDataSerializable;
import com.hazelcast.nio.serialization.BinaryInterface;
import java.io.IOException;
/**
* Base class for all internal aggregation CombinerFactories to easy the implementation of
* {@link com.hazelcast.nio.serialization.IdentifiedDataSerializable}.
*
* @param <KeyIn> the input key type
* @param <ValueIn> the input value type
* @param <ValueOut> the output value type
*/
@BinaryInterface
abstract class AbstractAggregationCombinerFactory<KeyIn, ValueIn, ValueOut>
implements CombinerFactory<KeyIn, ValueIn, ValueOut>, IdentifiedDataSerializable {
@Override
public int getFactoryId() {
return AggregationsDataSerializerHook.F_ID;
}
@Override
public void writeData(ObjectDataOutput out)
throws IOException {
}
@Override
public void readData(ObjectDataInput in)
throws IOException {
}
}
| dbrimley/hazelcast | hazelcast/src/main/java/com/hazelcast/mapreduce/aggregation/impl/AbstractAggregationCombinerFactory.java | Java | apache-2.0 | 1,754 |
/*
* Copyright 2009 Phil Burk, Mobileer Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jsyn.util;
public class JavaTools {
@SuppressWarnings("rawtypes")
public static Class loadClass(String className, boolean verbose) {
Class newClass = null;
try {
newClass = Class.forName(className);
} catch (Throwable e) {
if (verbose)
System.out.println("Caught " + e);
}
if (newClass == null) {
try {
ClassLoader systemLoader = ClassLoader.getSystemClassLoader();
newClass = Class.forName(className, true, systemLoader);
} catch (Throwable e) {
if (verbose)
System.out.println("Caught " + e);
}
}
return newClass;
}
/**
* First try Class.forName(). If this fails, try Class.forName() using
* ClassLoader.getSystemClassLoader().
*
* @return Class or null
*/
@SuppressWarnings("rawtypes")
public static Class loadClass(String className) {
/**
* First try Class.forName(). If this fails, try Class.forName() using
* ClassLoader.getSystemClassLoader().
*
* @return Class or null
*/
return loadClass(className, true);
}
}
| UIKit0/jsyn | src/com/jsyn/util/JavaTools.java | Java | apache-2.0 | 1,861 |
/**********************************************************************
// @@@ START COPYRIGHT @@@
//
// 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.
//
// @@@ END COPYRIGHT @@@
//
**********************************************************************/
/* -*-C++-*-
******************************************************************************
*
* File: RuDupElimLogRecord.cpp
* Description: Implementation of class CRUIUDLogRecord
*
* Created: 06/12/2000
* Language: C++
*
*
******************************************************************************
*/
#include "dmprepstatement.h"
#include "ddobject.h"
#include "RuDupElimLogRecord.h"
#include "RuDeltaDef.h"
#include "RuException.h"
//--------------------------------------------------------------------------//
// CLASS CRUIUDLogRecord - PUBLIC AREA
//--------------------------------------------------------------------------//
//--------------------------------------------------------------------------//
// Constructors and destructor
//--------------------------------------------------------------------------//
CRUIUDLogRecord::
CRUIUDLogRecord(CDMSqlTupleDesc &ckDesc, Int32 updateBmpSize) :
// Persistent data members
ckTuple_(ckDesc),
syskey_(0),
epoch_(0),
opType_(0),
ignore_(0),
rangeSize_(0),
pUpdateBitmap_(NULL),
// Non-persistent data members
ckTag_(0),
action_(0)
{
if (0 != updateBmpSize)
{
pUpdateBitmap_ = new CRUUpdateBitmap(updateBmpSize);
}
}
CRUIUDLogRecord::CRUIUDLogRecord(const CRUIUDLogRecord &other) :
// Persistent data members
ckTuple_(other.ckTuple_),
syskey_(other.syskey_),
epoch_(other.epoch_),
opType_(other.opType_),
ignore_(other.ignore_),
rangeSize_(other.rangeSize_),
pUpdateBitmap_(NULL),
// Non-persistent data members
ckTag_(other.ckTag_)
{
CRUUpdateBitmap *pOtherUpdateBitmap = other.pUpdateBitmap_;
if (NULL != pOtherUpdateBitmap)
{
pUpdateBitmap_ = new CRUUpdateBitmap(*pOtherUpdateBitmap);
}
}
CRUIUDLogRecord::~CRUIUDLogRecord()
{
delete pUpdateBitmap_;
}
//--------------------------------------------------------------------------//
// CRUIUDLogRecord::CopyCKTupleValuesToParams()
//
// Copy the tuple's values to N consecutive parameters
// of the statement: firstParam, ... firstParam + N - 1.
//
//--------------------------------------------------------------------------//
void CRUIUDLogRecord::
CopyCKTupleValuesToParams(CDMPreparedStatement &stmt,
Int32 firstParam) const
{
Lng32 len = GetCKLength();
for (Int32 i=0; i<len; i++)
{
ckTuple_.GetItem(i).SetStatementParam(stmt, firstParam+i);
}
}
//--------------------------------------------------------------------------//
// CRUIUDLogRecord::Build()
//
// Retrieve the tuple's data from the result set and store it.
// The tuple's columns are contiguous in the result set,
// starting from the *startCKColumn* parameter.
//
//--------------------------------------------------------------------------//
void CRUIUDLogRecord::Build(CDMResultSet &rs, Int32 startCKColumn)
{
ReadControlColumns(rs, startCKColumn);
ReadCKColumns(rs, startCKColumn);
}
//--------------------------------------------------------------------------//
// CLASS CRUIUDLogRecord - PRIVATE AREA
//--------------------------------------------------------------------------//
//--------------------------------------------------------------------------//
// CRUIUDLogRecord::ReadControlColumns()
//
// Get the control columns from the result set (epoch, syskey etc).
// The operation_type column is stored as a bitmap, and hence
// requires decoding.
//
//--------------------------------------------------------------------------//
void CRUIUDLogRecord::ReadControlColumns(CDMResultSet &rs, Int32 startCKColumn)
{
// Performance optimization - switch the IsNull check off!
rs.PresetNotNullable(TRUE);
// Read the mandatory columns
epoch_ = rs.GetInt(CRUDupElimConst::OFS_EPOCH+1);
opType_ = rs.GetInt(CRUDupElimConst::OFS_OPTYPE+1);
if (FALSE == IsSingleRowOp())
{
// The range records are logged in the negative epochs.
// Logically, however, they belong to the positive epochs.
epoch_ = -epoch_;
}
if (FALSE == IsSingleRowOp() && FALSE == IsBeginRange())
{
// End-range record
rangeSize_ = rs.GetInt(CRUDupElimConst::OFS_RNGSIZE+1);
}
else
{
rangeSize_ = 0;
}
Int32 numCKCols = startCKColumn-2; // Count from 1 + syskey
if (CRUDupElimConst::NUM_IUD_LOG_CONTROL_COLS_EXTEND == numCKCols)
{
// This is DE level 3, read the optional columns
ignore_ = rs.GetInt(CRUDupElimConst::OFS_IGNORE+1);
// The update bitmap buffer must be setup
RUASSERT(NULL != pUpdateBitmap_);
// The update bitmap can be a null
rs.PresetNotNullable(FALSE);
rs.GetString(CRUDupElimConst::OFS_UPD_BMP+1,
pUpdateBitmap_->GetBuffer(),
pUpdateBitmap_->GetSize());
}
// Syskey is always the last column before the CK
syskey_ = rs.GetLargeInt(startCKColumn-1);
}
//--------------------------------------------------------------------------//
// CRUIUDLogRecord::ReadCKColumns()
//
// Retrieve the values of the clustering key columns and store
// them in an SQL tuple.
//
//--------------------------------------------------------------------------//
void CRUIUDLogRecord::
ReadCKColumns(CDMResultSet &rs, Int32 startCKColumn)
{
// Performance optimization - switch the IsNull check off!
rs.PresetNotNullable(TRUE);
Lng32 len = GetCKLength();
for (Int32 i=0; i<len; i++)
{
Int32 colIndex = i + startCKColumn;
ckTuple_.GetItem(i).Build(rs, colIndex);
}
rs.PresetNotNullable(FALSE);
}
// Define the class CRUIUDLogRecordList with this macro
DEFINE_PTRLIST(CRUIUDLogRecord);
| apache/incubator-trafodion | core/sql/refresh/RuDupElimLogRecord.cpp | C++ | apache-2.0 | 6,408 |
# text.rb
#
# This demonstration script creates a text widget that describes
# the basic editing functions.
#
# text (basic facilities) widget demo (called by 'widget')
#
# toplevel widget
if defined?($text_demo) && $text_demo
$text_demo.destroy
$text_demo = nil
end
# demo toplevel widget
$text_demo = TkToplevel.new {|w|
title("Text Demonstration - Basic Facilities")
iconname("text")
positionWindow(w)
}
base_frame = TkFrame.new($text_demo).pack(:fill=>:both, :expand=>true)
# version check
if ((Tk::TK_VERSION.split('.').collect{|n| n.to_i} <=> [8,4]) < 0)
undo_support = false
else
undo_support = true
end
# frame
TkFrame.new(base_frame) {|frame|
TkButton.new(frame) {
text 'Dismiss'
command proc{
tmppath = $text_demo
$text_demo = nil
tmppath.destroy
}
}.pack('side'=>'left', 'expand'=>'yes')
TkButton.new(frame) {
text 'Show Code'
command proc{showCode 'text'}
}.pack('side'=>'left', 'expand'=>'yes')
}.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m')
# text
TkText.new(base_frame){|t|
relief 'sunken'
bd 2
setgrid 1
height 30
if undo_support
undo true
autoseparators true
end
TkScrollbar.new(base_frame) {|s|
pack('side'=>'right', 'fill'=>'y')
command proc{|*args| t.yview(*args)}
t.yscrollcommand proc{|first,last| s.set first,last}
}
pack('expand'=>'yes', 'fill'=>'both')
#
insert('0.0', <<EOT)
This window is a text widget. It displays one or more lines of text
and allows you to edit the text. Here is a summary of the things you
can do to a text widget:
1. Scrolling. Use the scrollbar to adjust the view in the text window.
2. Scanning. Press mouse button 2 in the text window and drag up or down.
This will drag the text at high speed to allow you to scan its contents.
3. Insert text. Press mouse button 1 to set the insertion cursor, then
type text. What you type will be added to the widget.
4. Select. Press mouse button 1 and drag to select a range of characters.
Once you've released the button, you can adjust the selection by pressing
button 1 with the shift key down. This will reset the end of the
selection nearest the mouse cursor and you can drag that end of the
selection by dragging the mouse before releasing the mouse button.
You can double-click to select whole words or triple-click to select
whole lines.
5. Delete and replace. To delete text, select the characters you'd like
to delete and type Backspace or Delete. Alternatively, you can type new
text, in which case it will replace the selected text.
6. Copy the selection. To copy the selection into this window, select
what you want to copy (either here or in another application), then
click button 2 to copy the selection to the point of the mouse cursor.
7. Edit. Text widgets support the standard Motif editing characters
plus many Emacs editing characters. Backspace and Control-h erase the
character to the left of the insertion cursor. Delete and Control-d
erase the character to the right of the insertion cursor. Meta-backspace
deletes the word to the left of the insertion cursor, and Meta-d deletes
the word to the right of the insertion cursor. Control-k deletes from
the insertion cursor to the end of the line, or it deletes the newline
character if that is the only thing left on the line. Control-o opens
a new line by inserting a newline character to the right of the insertion
cursor. Control-t transposes the two characters on either side of the
insertion cursor. #{
if undo_support
undo_text = "Control-z undoes the last editing action performed,\nand "
case $tk_platform['platform']
when "unix", "macintosh"
undo_text << "Control-Shift-z"
else # 'windows'
undo_text << "Control-y"
end
undo_text << "redoes undone edits."
else
""
end
}
7. Resize the window. This widget has been configured with the "setGrid"
option on, so that if you resize the window it will always resize to an
even number of characters high and wide. Also, if you make the window
narrow you can see that long lines automatically wrap around onto
additional lines so that all the information is always visible.
EOT
set_insert('0.0')
}
| racker/omnibus | source/ruby-enterprise-1.8.7-2011.01/source/ext/tk/sample/demos-en/text.rb | Ruby | apache-2.0 | 4,248 |
/*
* 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.kafka.common.header.internals;
import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.header.Headers;
import org.apache.kafka.common.record.Record;
import org.apache.kafka.common.utils.AbstractIterator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
public class RecordHeaders implements Headers {
private final List<Header> headers;
private volatile boolean isReadOnly;
public RecordHeaders() {
this((Iterable<Header>) null);
}
public RecordHeaders(Header[] headers) {
if (headers == null) {
this.headers = new ArrayList<>();
} else {
this.headers = new ArrayList<>(Arrays.asList(headers));
}
}
public RecordHeaders(Iterable<Header> headers) {
//Use efficient copy constructor if possible, fallback to iteration otherwise
if (headers == null) {
this.headers = new ArrayList<>();
} else if (headers instanceof RecordHeaders) {
this.headers = new ArrayList<>(((RecordHeaders) headers).headers);
} else if (headers instanceof Collection) {
this.headers = new ArrayList<>((Collection<Header>) headers);
} else {
this.headers = new ArrayList<>();
for (Header header : headers)
this.headers.add(header);
}
}
@Override
public Headers add(Header header) throws IllegalStateException {
Objects.requireNonNull(header, "Header cannot be null.");
canWrite();
headers.add(header);
return this;
}
@Override
public Headers add(String key, byte[] value) throws IllegalStateException {
return add(new RecordHeader(key, value));
}
@Override
public Headers remove(String key) throws IllegalStateException {
canWrite();
checkKey(key);
Iterator<Header> iterator = iterator();
while (iterator.hasNext()) {
if (iterator.next().key().equals(key)) {
iterator.remove();
}
}
return this;
}
@Override
public Header lastHeader(String key) {
checkKey(key);
for (int i = headers.size() - 1; i >= 0; i--) {
Header header = headers.get(i);
if (header.key().equals(key)) {
return header;
}
}
return null;
}
@Override
public Iterable<Header> headers(final String key) {
checkKey(key);
return () -> new FilterByKeyIterator(headers.iterator(), key);
}
@Override
public Iterator<Header> iterator() {
return closeAware(headers.iterator());
}
public void setReadOnly() {
this.isReadOnly = true;
}
public Header[] toArray() {
return headers.isEmpty() ? Record.EMPTY_HEADERS : headers.toArray(new Header[headers.size()]);
}
private void checkKey(String key) {
if (key == null)
throw new IllegalArgumentException("key cannot be null.");
}
private void canWrite() {
if (isReadOnly)
throw new IllegalStateException("RecordHeaders has been closed.");
}
private Iterator<Header> closeAware(final Iterator<Header> original) {
return new Iterator<Header>() {
@Override
public boolean hasNext() {
return original.hasNext();
}
public Header next() {
return original.next();
}
@Override
public void remove() {
canWrite();
original.remove();
}
};
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RecordHeaders headers1 = (RecordHeaders) o;
return Objects.equals(headers, headers1.headers);
}
@Override
public int hashCode() {
return headers != null ? headers.hashCode() : 0;
}
@Override
public String toString() {
return "RecordHeaders(" +
"headers = " + headers +
", isReadOnly = " + isReadOnly +
')';
}
private static final class FilterByKeyIterator extends AbstractIterator<Header> {
private final Iterator<Header> original;
private final String key;
private FilterByKeyIterator(Iterator<Header> original, String key) {
this.original = original;
this.key = key;
}
protected Header makeNext() {
while (true) {
if (original.hasNext()) {
Header header = original.next();
if (!header.key().equals(key))
continue;
return header;
}
return this.allDone();
}
}
}
}
| KevinLiLu/kafka | clients/src/main/java/org/apache/kafka/common/header/internals/RecordHeaders.java | Java | apache-2.0 | 5,878 |
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++03, c++11, c++14, c++17
// XFAIL: *
// <chrono>
// class year_month_day;
// template<class charT, class traits>
// basic_ostream<charT, traits>&
// operator<<(basic_ostream<charT, traits>& os, const year_month_day& ym);
//
// Returns: os << ym.year() << '/' << ym.month().
//
//
// template<class charT, class traits>
// basic_ostream<charT, traits>&
// to_stream(basic_ostream<charT, traits>& os, const charT* fmt, const year_month_day& ym);
//
// Effects: Streams ym into os using the format specified by the NTCTS fmt. fmt encoding follows the rules specified in 25.11.
//
// template<class charT, class traits, class Alloc = allocator<charT>>
// basic_istream<charT, traits>&
// from_stream(basic_istream<charT, traits>& is, const charT* fmt,
// year_month_day& ym, basic_string<charT, traits, Alloc>* abbrev = nullptr,
// minutes* offset = nullptr);
//
// Effects: Attempts to parse the input stream is into the year_month_day ym using the format
// flags given in the NTCTS fmt as specified in 25.12. If the parse fails to decode
// a valid year_month_day, is.setstate(ios_- base::failbit) shall be called and ym shall
// not be modified. If %Z is used and successfully parsed, that value will be assigned
// to *abbrev if abbrev is non-null. If %z (or a modified variant) is used and
// successfully parsed, that value will be assigned to *offset if offset is non-null.
#include <chrono>
#include <type_traits>
#include <cassert>
#include <iostream>
#include "test_macros.h"
int main(int, char**)
{
using year_month_day = std::chrono::year_month_day;
using year = std::chrono::year;
using month = std::chrono::month;
using day = std::chrono::day;
std::cout << year_month_day{year{2018}, month{3}, day{12}};
return 0;
}
| google/llvm-propeller | libcxx/test/std/utilities/time/time.cal/time.cal.ymd/time.cal.ymd.nonmembers/streaming.pass.cpp | C++ | apache-2.0 | 2,265 |
/*
* 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.
*/
'use strict';
angular.module('zeppelinWebApp').controller('MainCtrl', function($scope, $rootScope, $window) {
$scope.looknfeel = 'default';
var init = function() {
$scope.asIframe = (($window.location.href.indexOf('asIframe') > -1) ? true : false);
};
init();
$rootScope.$on('setIframe', function(event, data) {
if (!event.defaultPrevented) {
$scope.asIframe = data;
event.preventDefault();
}
});
$rootScope.$on('setLookAndFeel', function(event, data) {
if (!event.defaultPrevented && data && data !== '' && data !== $scope.looknfeel) {
$scope.looknfeel = data;
event.preventDefault();
}
});
// Set The lookAndFeel to default on every page
$rootScope.$on('$routeChangeStart', function(event, next, current) {
$rootScope.$broadcast('setLookAndFeel', 'default');
});
BootstrapDialog.defaultOptions.onshown = function() {
angular.element('#' + this.id).find('.btn:last').focus();
};
// Remove BootstrapDialog animation
BootstrapDialog.configDefaultOptions({animate: false});
});
| optimizely/incubator-zeppelin | zeppelin-web/src/app/app.controller.js | JavaScript | apache-2.0 | 1,628 |
/*
Copyright (c) 2016 VMware, 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 storage
import (
"flag"
"fmt"
"golang.org/x/net/context"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type mark struct {
*flags.HostSystemFlag
ssd *bool
local *bool
}
func init() {
cli.Register("host.storage.mark", &mark{})
}
func (cmd *mark) Register(ctx context.Context, f *flag.FlagSet) {
cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
cmd.HostSystemFlag.Register(ctx, f)
f.Var(flags.NewOptionalBool(&cmd.ssd), "ssd", "Mark as SSD")
f.Var(flags.NewOptionalBool(&cmd.local), "local", "Mark as local")
}
func (cmd *mark) Process(ctx context.Context) error {
if err := cmd.HostSystemFlag.Process(ctx); err != nil {
return err
}
return nil
}
func (cmd *mark) Usage() string {
return "DEVICE_PATH"
}
func (cmd *mark) Description() string {
return `Mark device at DEVICE_PATH.`
}
func (cmd *mark) Mark(ctx context.Context, ss *object.HostStorageSystem, uuid string) error {
var err error
var task *object.Task
if cmd.ssd != nil {
if *cmd.ssd {
task, err = ss.MarkAsSsd(ctx, uuid)
} else {
task, err = ss.MarkAsNonSsd(ctx, uuid)
}
if err != nil {
return err
}
err = task.Wait(ctx)
if err != nil {
return err
}
}
if cmd.local != nil {
if *cmd.local {
task, err = ss.MarkAsLocal(ctx, uuid)
} else {
task, err = ss.MarkAsNonLocal(ctx, uuid)
}
if err != nil {
return err
}
err = task.Wait(ctx)
if err != nil {
return err
}
}
return nil
}
func (cmd *mark) Run(ctx context.Context, f *flag.FlagSet) error {
if f.NArg() != 1 {
return fmt.Errorf("specify device path")
}
path := f.Args()[0]
host, err := cmd.HostSystem()
if err != nil {
return err
}
ss, err := host.ConfigManager().StorageSystem(ctx)
if err != nil {
return err
}
var hss mo.HostStorageSystem
err = ss.Properties(ctx, ss.Reference(), nil, &hss)
if err != nil {
return nil
}
for _, e := range hss.StorageDeviceInfo.ScsiLun {
disk, ok := e.(*types.HostScsiDisk)
if !ok {
continue
}
if disk.DevicePath == path {
return cmd.Mark(ctx, ss, disk.Uuid)
}
}
return fmt.Errorf("%s not found", path)
}
| austinlparker/govmomi | govc/host/storage/mark.go | GO | apache-2.0 | 2,846 |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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.
*/
'use strict';
/**
* Returns the y-scale function.
*
* @private
* @returns {Function} scale function
*/
function get() {
/* eslint-disable no-invalid-this */
return this._yScale;
}
// EXPORTS //
module.exports = get;
| stdlib-js/stdlib | lib/node_modules/@stdlib/plot/components/svg/symbols/lib/props/y-scale/get.js | JavaScript | apache-2.0 | 840 |