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 |
|---|---|---|---|---|---|
/*
* libjingle
* Copyright 2004 Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "talk/session/media/channelmanager.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <algorithm>
#include "talk/media/base/capturemanager.h"
#include "talk/media/base/hybriddataengine.h"
#include "talk/media/base/rtpdataengine.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/devices/devicemanager.h"
#ifdef HAVE_SCTP
#include "talk/media/sctp/sctpdataengine.h"
#endif
#include "talk/session/media/srtpfilter.h"
#include "webrtc/base/bind.h"
#include "webrtc/base/common.h"
#include "webrtc/base/logging.h"
#include "webrtc/base/sigslotrepeater.h"
#include "webrtc/base/stringencode.h"
#include "webrtc/base/stringutils.h"
namespace cricket {
enum {
MSG_VIDEOCAPTURESTATE = 1,
};
using rtc::Bind;
static const int kNotSetOutputVolume = -1;
struct CaptureStateParams : public rtc::MessageData {
CaptureStateParams(cricket::VideoCapturer* c, cricket::CaptureState s)
: capturer(c),
state(s) {}
cricket::VideoCapturer* capturer;
cricket::CaptureState state;
};
static DataEngineInterface* ConstructDataEngine() {
#ifdef HAVE_SCTP
return new HybridDataEngine(new RtpDataEngine(), new SctpDataEngine());
#else
return new RtpDataEngine();
#endif
}
ChannelManager::ChannelManager(MediaEngineInterface* me,
DataEngineInterface* dme,
DeviceManagerInterface* dm,
CaptureManager* cm,
rtc::Thread* worker_thread) {
Construct(me, dme, dm, cm, worker_thread);
}
ChannelManager::ChannelManager(MediaEngineInterface* me,
DeviceManagerInterface* dm,
rtc::Thread* worker_thread) {
Construct(me,
ConstructDataEngine(),
dm,
new CaptureManager(),
worker_thread);
}
void ChannelManager::Construct(MediaEngineInterface* me,
DataEngineInterface* dme,
DeviceManagerInterface* dm,
CaptureManager* cm,
rtc::Thread* worker_thread) {
media_engine_.reset(me);
data_media_engine_.reset(dme);
device_manager_.reset(dm);
capture_manager_.reset(cm);
initialized_ = false;
main_thread_ = rtc::Thread::Current();
worker_thread_ = worker_thread;
// Get the default audio options from the media engine.
audio_options_ = media_engine_->GetAudioOptions();
audio_in_device_ = DeviceManagerInterface::kDefaultDeviceName;
audio_out_device_ = DeviceManagerInterface::kDefaultDeviceName;
audio_delay_offset_ = kDefaultAudioDelayOffset;
audio_output_volume_ = kNotSetOutputVolume;
local_renderer_ = NULL;
capturing_ = false;
monitoring_ = false;
enable_rtx_ = false;
// Init the device manager immediately, and set up our default video device.
SignalDevicesChange.repeat(device_manager_->SignalDevicesChange);
device_manager_->Init();
capture_manager_->SignalCapturerStateChange.connect(
this, &ChannelManager::OnVideoCaptureStateChange);
}
ChannelManager::~ChannelManager() {
if (initialized_) {
Terminate();
// If srtp is initialized (done by the Channel) then we must call
// srtp_shutdown to free all crypto kernel lists. But we need to make sure
// shutdown always called at the end, after channels are destroyed.
// ChannelManager d'tor is always called last, it's safe place to call
// shutdown.
ShutdownSrtp();
}
// Some deletes need to be on the worker thread for thread safe destruction,
// this includes the media engine and capture manager.
worker_thread_->Invoke<void>(Bind(
&ChannelManager::DestructorDeletes_w, this));
}
bool ChannelManager::SetVideoRtxEnabled(bool enable) {
// To be safe, this call is only allowed before initialization. Apps like
// Flute only have a singleton ChannelManager and we don't want this flag to
// be toggled between calls or when there's concurrent calls. We expect apps
// to enable this at startup and retain that setting for the lifetime of the
// app.
if (!initialized_) {
enable_rtx_ = enable;
return true;
} else {
LOG(LS_WARNING) << "Cannot toggle rtx after initialization!";
return false;
}
}
int ChannelManager::GetCapabilities() {
return media_engine_->GetCapabilities() & device_manager_->GetCapabilities();
}
void ChannelManager::GetSupportedAudioCodecs(
std::vector<AudioCodec>* codecs) const {
codecs->clear();
for (std::vector<AudioCodec>::const_iterator it =
media_engine_->audio_codecs().begin();
it != media_engine_->audio_codecs().end(); ++it) {
codecs->push_back(*it);
}
}
void ChannelManager::GetSupportedAudioRtpHeaderExtensions(
RtpHeaderExtensions* ext) const {
*ext = media_engine_->audio_rtp_header_extensions();
}
void ChannelManager::GetSupportedVideoCodecs(
std::vector<VideoCodec>* codecs) const {
codecs->clear();
std::vector<VideoCodec>::const_iterator it;
for (it = media_engine_->video_codecs().begin();
it != media_engine_->video_codecs().end(); ++it) {
if (!enable_rtx_ && _stricmp(kRtxCodecName, it->name.c_str()) == 0) {
continue;
}
codecs->push_back(*it);
}
}
void ChannelManager::GetSupportedVideoRtpHeaderExtensions(
RtpHeaderExtensions* ext) const {
*ext = media_engine_->video_rtp_header_extensions();
}
void ChannelManager::GetSupportedDataCodecs(
std::vector<DataCodec>* codecs) const {
*codecs = data_media_engine_->data_codecs();
}
bool ChannelManager::Init() {
ASSERT(!initialized_);
if (initialized_) {
return false;
}
ASSERT(worker_thread_ != NULL);
if (!worker_thread_) {
return false;
}
if (worker_thread_ != rtc::Thread::Current()) {
// Do not allow invoking calls to other threads on the worker thread.
worker_thread_->Invoke<bool>(rtc::Bind(
&rtc::Thread::SetAllowBlockingCalls, worker_thread_, false));
}
initialized_ = worker_thread_->Invoke<bool>(Bind(
&ChannelManager::InitMediaEngine_w, this));
ASSERT(initialized_);
if (!initialized_) {
return false;
}
// Now that we're initialized, apply any stored preferences. A preferred
// device might have been unplugged. In this case, we fallback to the
// default device but keep the user preferences. The preferences are
// changed only when the Javascript FE changes them.
const std::string preferred_audio_in_device = audio_in_device_;
const std::string preferred_audio_out_device = audio_out_device_;
const std::string preferred_camera_device = camera_device_;
Device device;
if (!device_manager_->GetAudioInputDevice(audio_in_device_, &device)) {
LOG(LS_WARNING) << "The preferred microphone '" << audio_in_device_
<< "' is unavailable. Fall back to the default.";
audio_in_device_ = DeviceManagerInterface::kDefaultDeviceName;
}
if (!device_manager_->GetAudioOutputDevice(audio_out_device_, &device)) {
LOG(LS_WARNING) << "The preferred speaker '" << audio_out_device_
<< "' is unavailable. Fall back to the default.";
audio_out_device_ = DeviceManagerInterface::kDefaultDeviceName;
}
if (!device_manager_->GetVideoCaptureDevice(camera_device_, &device)) {
if (!camera_device_.empty()) {
LOG(LS_WARNING) << "The preferred camera '" << camera_device_
<< "' is unavailable. Fall back to the default.";
}
camera_device_ = DeviceManagerInterface::kDefaultDeviceName;
}
if (!SetAudioOptions(audio_in_device_, audio_out_device_,
audio_options_, audio_delay_offset_)) {
LOG(LS_WARNING) << "Failed to SetAudioOptions with"
<< " microphone: " << audio_in_device_
<< " speaker: " << audio_out_device_
<< " options: " << audio_options_.ToString()
<< " delay: " << audio_delay_offset_;
}
// If audio_output_volume_ has been set via SetOutputVolume(), set the
// audio output volume of the engine.
if (kNotSetOutputVolume != audio_output_volume_ &&
!SetOutputVolume(audio_output_volume_)) {
LOG(LS_WARNING) << "Failed to SetOutputVolume to "
<< audio_output_volume_;
}
if (!SetCaptureDevice(camera_device_) && !camera_device_.empty()) {
LOG(LS_WARNING) << "Failed to SetCaptureDevice with camera: "
<< camera_device_;
}
// Restore the user preferences.
audio_in_device_ = preferred_audio_in_device;
audio_out_device_ = preferred_audio_out_device;
camera_device_ = preferred_camera_device;
// Now apply the default video codec that has been set earlier.
if (default_video_encoder_config_.max_codec.id != 0) {
SetDefaultVideoEncoderConfig(default_video_encoder_config_);
}
return initialized_;
}
bool ChannelManager::InitMediaEngine_w() {
ASSERT(worker_thread_ == rtc::Thread::Current());
return (media_engine_->Init(worker_thread_));
}
void ChannelManager::Terminate() {
ASSERT(initialized_);
if (!initialized_) {
return;
}
worker_thread_->Invoke<void>(Bind(&ChannelManager::Terminate_w, this));
initialized_ = false;
}
void ChannelManager::DestructorDeletes_w() {
ASSERT(worker_thread_ == rtc::Thread::Current());
media_engine_.reset(NULL);
capture_manager_.reset(NULL);
}
void ChannelManager::Terminate_w() {
ASSERT(worker_thread_ == rtc::Thread::Current());
// Need to destroy the voice/video channels
while (!video_channels_.empty()) {
DestroyVideoChannel_w(video_channels_.back());
}
while (!voice_channels_.empty()) {
DestroyVoiceChannel_w(voice_channels_.back(), nullptr);
}
if (!SetCaptureDevice_w(NULL)) {
LOG(LS_WARNING) << "failed to delete video capturer";
}
media_engine_->Terminate();
}
VoiceChannel* ChannelManager::CreateVoiceChannel(
BaseSession* session,
const std::string& content_name,
bool rtcp,
const AudioOptions& options) {
return worker_thread_->Invoke<VoiceChannel*>(
Bind(&ChannelManager::CreateVoiceChannel_w, this, session, content_name,
rtcp, options));
}
VoiceChannel* ChannelManager::CreateVoiceChannel_w(
BaseSession* session,
const std::string& content_name,
bool rtcp,
const AudioOptions& options) {
ASSERT(initialized_);
ASSERT(worker_thread_ == rtc::Thread::Current());
VoiceMediaChannel* media_channel = media_engine_->CreateChannel(options);
if (!media_channel)
return nullptr;
VoiceChannel* voice_channel = new VoiceChannel(
worker_thread_, media_engine_.get(), media_channel,
session, content_name, rtcp);
if (!voice_channel->Init()) {
delete voice_channel;
return nullptr;
}
voice_channels_.push_back(voice_channel);
return voice_channel;
}
void ChannelManager::DestroyVoiceChannel(VoiceChannel* voice_channel,
VideoChannel* video_channel) {
if (voice_channel) {
worker_thread_->Invoke<void>(
Bind(&ChannelManager::DestroyVoiceChannel_w, this, voice_channel,
video_channel));
}
}
void ChannelManager::DestroyVoiceChannel_w(VoiceChannel* voice_channel,
VideoChannel* video_channel) {
// Destroy voice channel.
ASSERT(initialized_);
ASSERT(worker_thread_ == rtc::Thread::Current());
VoiceChannels::iterator it = std::find(voice_channels_.begin(),
voice_channels_.end(), voice_channel);
ASSERT(it != voice_channels_.end());
if (it == voice_channels_.end())
return;
if (video_channel) {
video_channel->media_channel()->DetachVoiceChannel();
}
voice_channels_.erase(it);
delete voice_channel;
}
VideoChannel* ChannelManager::CreateVideoChannel(
BaseSession* session,
const std::string& content_name,
bool rtcp,
VoiceChannel* voice_channel) {
return worker_thread_->Invoke<VideoChannel*>(
Bind(&ChannelManager::CreateVideoChannel_w,
this,
session,
content_name,
rtcp,
VideoOptions(),
voice_channel));
}
VideoChannel* ChannelManager::CreateVideoChannel(
BaseSession* session,
const std::string& content_name,
bool rtcp,
const VideoOptions& options,
VoiceChannel* voice_channel) {
return worker_thread_->Invoke<VideoChannel*>(
Bind(&ChannelManager::CreateVideoChannel_w,
this,
session,
content_name,
rtcp,
options,
voice_channel));
}
VideoChannel* ChannelManager::CreateVideoChannel_w(
BaseSession* session,
const std::string& content_name,
bool rtcp,
const VideoOptions& options,
VoiceChannel* voice_channel) {
ASSERT(initialized_);
ASSERT(worker_thread_ == rtc::Thread::Current());
VideoMediaChannel* media_channel =
// voice_channel can be NULL in case of NullVoiceEngine.
media_engine_->CreateVideoChannel(
options, voice_channel ? voice_channel->media_channel() : NULL);
if (media_channel == NULL)
return NULL;
VideoChannel* video_channel = new VideoChannel(
worker_thread_, media_channel,
session, content_name, rtcp);
if (!video_channel->Init()) {
delete video_channel;
return NULL;
}
video_channels_.push_back(video_channel);
return video_channel;
}
void ChannelManager::DestroyVideoChannel(VideoChannel* video_channel) {
if (video_channel) {
worker_thread_->Invoke<void>(
Bind(&ChannelManager::DestroyVideoChannel_w, this, video_channel));
}
}
void ChannelManager::DestroyVideoChannel_w(VideoChannel* video_channel) {
// Destroy video channel.
ASSERT(initialized_);
ASSERT(worker_thread_ == rtc::Thread::Current());
VideoChannels::iterator it = std::find(video_channels_.begin(),
video_channels_.end(), video_channel);
ASSERT(it != video_channels_.end());
if (it == video_channels_.end())
return;
video_channels_.erase(it);
delete video_channel;
}
DataChannel* ChannelManager::CreateDataChannel(
BaseSession* session, const std::string& content_name,
bool rtcp, DataChannelType channel_type) {
return worker_thread_->Invoke<DataChannel*>(
Bind(&ChannelManager::CreateDataChannel_w, this, session, content_name,
rtcp, channel_type));
}
DataChannel* ChannelManager::CreateDataChannel_w(
BaseSession* session, const std::string& content_name,
bool rtcp, DataChannelType data_channel_type) {
// This is ok to alloc from a thread other than the worker thread.
ASSERT(initialized_);
DataMediaChannel* media_channel = data_media_engine_->CreateChannel(
data_channel_type);
if (!media_channel) {
LOG(LS_WARNING) << "Failed to create data channel of type "
<< data_channel_type;
return NULL;
}
DataChannel* data_channel = new DataChannel(
worker_thread_, media_channel,
session, content_name, rtcp);
if (!data_channel->Init()) {
LOG(LS_WARNING) << "Failed to init data channel.";
delete data_channel;
return NULL;
}
data_channels_.push_back(data_channel);
return data_channel;
}
void ChannelManager::DestroyDataChannel(DataChannel* data_channel) {
if (data_channel) {
worker_thread_->Invoke<void>(
Bind(&ChannelManager::DestroyDataChannel_w, this, data_channel));
}
}
void ChannelManager::DestroyDataChannel_w(DataChannel* data_channel) {
// Destroy data channel.
ASSERT(initialized_);
DataChannels::iterator it = std::find(data_channels_.begin(),
data_channels_.end(), data_channel);
ASSERT(it != data_channels_.end());
if (it == data_channels_.end())
return;
data_channels_.erase(it);
delete data_channel;
}
bool ChannelManager::GetAudioOptions(std::string* in_name,
std::string* out_name,
AudioOptions* options) {
if (in_name)
*in_name = audio_in_device_;
if (out_name)
*out_name = audio_out_device_;
if (options)
*options = audio_options_;
return true;
}
bool ChannelManager::SetAudioOptions(const std::string& in_name,
const std::string& out_name,
const AudioOptions& options) {
return SetAudioOptions(in_name, out_name, options, audio_delay_offset_);
}
bool ChannelManager::SetAudioOptions(const std::string& in_name,
const std::string& out_name,
const AudioOptions& options,
int delay_offset) {
// Get device ids from DeviceManager.
Device in_dev, out_dev;
if (!device_manager_->GetAudioInputDevice(in_name, &in_dev)) {
LOG(LS_WARNING) << "Failed to GetAudioInputDevice: " << in_name;
return false;
}
if (!device_manager_->GetAudioOutputDevice(out_name, &out_dev)) {
LOG(LS_WARNING) << "Failed to GetAudioOutputDevice: " << out_name;
return false;
}
// If we're initialized, pass the settings to the media engine.
bool ret = true;
if (initialized_) {
ret = worker_thread_->Invoke<bool>(
Bind(&ChannelManager::SetAudioOptions_w, this,
options, delay_offset, &in_dev, &out_dev));
}
// If all worked well, save the values for use in GetAudioOptions.
if (ret) {
audio_options_ = options;
audio_in_device_ = in_name;
audio_out_device_ = out_name;
audio_delay_offset_ = delay_offset;
}
return ret;
}
bool ChannelManager::SetAudioOptions_w(
const AudioOptions& options, int delay_offset,
const Device* in_dev, const Device* out_dev) {
ASSERT(worker_thread_ == rtc::Thread::Current());
ASSERT(initialized_);
// Set audio options
bool ret = media_engine_->SetAudioOptions(options);
if (ret) {
ret = media_engine_->SetAudioDelayOffset(delay_offset);
}
// Set the audio devices
if (ret) {
ret = media_engine_->SetSoundDevices(in_dev, out_dev);
}
return ret;
}
bool ChannelManager::GetOutputVolume(int* level) {
if (!initialized_) {
return false;
}
return worker_thread_->Invoke<bool>(
Bind(&MediaEngineInterface::GetOutputVolume, media_engine_.get(), level));
}
bool ChannelManager::SetOutputVolume(int level) {
bool ret = level >= 0 && level <= 255;
if (initialized_) {
ret &= worker_thread_->Invoke<bool>(
Bind(&MediaEngineInterface::SetOutputVolume,
media_engine_.get(), level));
}
if (ret) {
audio_output_volume_ = level;
}
return ret;
}
bool ChannelManager::IsSameCapturer(const std::string& capturer_name,
VideoCapturer* capturer) {
if (capturer == NULL) {
return false;
}
Device device;
if (!device_manager_->GetVideoCaptureDevice(capturer_name, &device)) {
return false;
}
return capturer->GetId() == device.id;
}
bool ChannelManager::GetVideoCaptureDevice(Device* device) {
std::string device_name;
if (!GetCaptureDevice(&device_name)) {
return false;
}
return device_manager_->GetVideoCaptureDevice(device_name, device);
}
bool ChannelManager::GetCaptureDevice(std::string* cam_name) {
if (camera_device_.empty()) {
// Initialize camera_device_ with default.
Device device;
if (!device_manager_->GetVideoCaptureDevice(
DeviceManagerInterface::kDefaultDeviceName, &device)) {
LOG(LS_WARNING) << "Device manager can't find default camera: " <<
DeviceManagerInterface::kDefaultDeviceName;
return false;
}
camera_device_ = device.name;
}
*cam_name = camera_device_;
return true;
}
bool ChannelManager::SetCaptureDevice(const std::string& cam_name) {
Device device;
bool ret = true;
if (!device_manager_->GetVideoCaptureDevice(cam_name, &device)) {
if (!cam_name.empty()) {
LOG(LS_WARNING) << "Device manager can't find camera: " << cam_name;
}
ret = false;
}
// If we're running, tell the media engine about it.
if (initialized_ && ret) {
ret = worker_thread_->Invoke<bool>(
Bind(&ChannelManager::SetCaptureDevice_w, this, &device));
}
// If everything worked, retain the name of the selected camera.
if (ret) {
camera_device_ = device.name;
} else if (camera_device_.empty()) {
// When video option setting fails, we still want camera_device_ to be in a
// good state, so we initialize it with default if it's empty.
Device default_device;
if (!device_manager_->GetVideoCaptureDevice(
DeviceManagerInterface::kDefaultDeviceName, &default_device)) {
LOG(LS_WARNING) << "Device manager can't find default camera: " <<
DeviceManagerInterface::kDefaultDeviceName;
}
camera_device_ = default_device.name;
}
return ret;
}
VideoCapturer* ChannelManager::CreateVideoCapturer() {
Device device;
if (!device_manager_->GetVideoCaptureDevice(camera_device_, &device)) {
if (!camera_device_.empty()) {
LOG(LS_WARNING) << "Device manager can't find camera: " << camera_device_;
}
return NULL;
}
VideoCapturer* capturer = device_manager_->CreateVideoCapturer(device);
if (capturer && default_video_encoder_config_.max_codec.id != 0) {
// For now, use the aspect ratio of the default_video_encoder_config_,
// which may be different than the native aspect ratio of the start
// format the camera may use.
capturer->UpdateAspectRatio(
default_video_encoder_config_.max_codec.width,
default_video_encoder_config_.max_codec.height);
}
return capturer;
}
VideoCapturer* ChannelManager::CreateScreenCapturer(
const ScreencastId& screenid) {
return device_manager_->CreateScreenCapturer(screenid);
}
bool ChannelManager::SetCaptureDevice_w(const Device* cam_device) {
ASSERT(worker_thread_ == rtc::Thread::Current());
ASSERT(initialized_);
if (!cam_device) {
video_device_name_.clear();
return true;
}
video_device_name_ = cam_device->name;
return true;
}
bool ChannelManager::SetDefaultVideoEncoderConfig(const VideoEncoderConfig& c) {
bool ret = true;
if (initialized_) {
ret = worker_thread_->Invoke<bool>(
Bind(&MediaEngineInterface::SetDefaultVideoEncoderConfig,
media_engine_.get(), c));
}
if (ret) {
default_video_encoder_config_ = c;
}
return ret;
}
bool ChannelManager::SetLocalMonitor(bool enable) {
bool ret = initialized_ && worker_thread_->Invoke<bool>(
Bind(&MediaEngineInterface::SetLocalMonitor,
media_engine_.get(), enable));
if (ret) {
monitoring_ = enable;
}
return ret;
}
void ChannelManager::SetVoiceLogging(int level, const char* filter) {
if (initialized_) {
worker_thread_->Invoke<void>(
Bind(&MediaEngineInterface::SetVoiceLogging,
media_engine_.get(), level, filter));
} else {
media_engine_->SetVoiceLogging(level, filter);
}
}
void ChannelManager::SetVideoLogging(int level, const char* filter) {
if (initialized_) {
worker_thread_->Invoke<void>(
Bind(&MediaEngineInterface::SetVideoLogging,
media_engine_.get(), level, filter));
} else {
media_engine_->SetVideoLogging(level, filter);
}
}
std::vector<cricket::VideoFormat> ChannelManager::GetSupportedFormats(
VideoCapturer* capturer) const {
ASSERT(capturer != NULL);
std::vector<VideoFormat> formats;
worker_thread_->Invoke<void>(rtc::Bind(&ChannelManager::GetSupportedFormats_w,
this, capturer, &formats));
return formats;
}
void ChannelManager::GetSupportedFormats_w(
VideoCapturer* capturer,
std::vector<cricket::VideoFormat>* out_formats) const {
const std::vector<VideoFormat>* formats = capturer->GetSupportedFormats();
if (formats != NULL)
*out_formats = *formats;
}
bool ChannelManager::RegisterVoiceProcessor(
uint32 ssrc,
VoiceProcessor* processor,
MediaProcessorDirection direction) {
return initialized_ && worker_thread_->Invoke<bool>(
Bind(&MediaEngineInterface::RegisterVoiceProcessor, media_engine_.get(),
ssrc, processor, direction));
}
bool ChannelManager::UnregisterVoiceProcessor(
uint32 ssrc,
VoiceProcessor* processor,
MediaProcessorDirection direction) {
return initialized_ && worker_thread_->Invoke<bool>(
Bind(&MediaEngineInterface::UnregisterVoiceProcessor,
media_engine_.get(), ssrc, processor, direction));
}
// The following are done in the new "CaptureManager" style that
// all local video capturers, processors, and managers should move
// to.
// TODO(pthatcher): Add more of the CaptureManager interface.
bool ChannelManager::StartVideoCapture(
VideoCapturer* capturer, const VideoFormat& video_format) {
return initialized_ && worker_thread_->Invoke<bool>(
Bind(&CaptureManager::StartVideoCapture,
capture_manager_.get(), capturer, video_format));
}
bool ChannelManager::MuteToBlackThenPause(
VideoCapturer* video_capturer, bool muted) {
if (!initialized_) {
return false;
}
worker_thread_->Invoke<void>(
Bind(&VideoCapturer::MuteToBlackThenPause, video_capturer, muted));
return true;
}
bool ChannelManager::StopVideoCapture(
VideoCapturer* capturer, const VideoFormat& video_format) {
return initialized_ && worker_thread_->Invoke<bool>(
Bind(&CaptureManager::StopVideoCapture,
capture_manager_.get(), capturer, video_format));
}
bool ChannelManager::RestartVideoCapture(
VideoCapturer* video_capturer,
const VideoFormat& previous_format,
const VideoFormat& desired_format,
CaptureManager::RestartOptions options) {
return initialized_ && worker_thread_->Invoke<bool>(
Bind(&CaptureManager::RestartVideoCapture, capture_manager_.get(),
video_capturer, previous_format, desired_format, options));
}
bool ChannelManager::AddVideoRenderer(
VideoCapturer* capturer, VideoRenderer* renderer) {
return initialized_ && worker_thread_->Invoke<bool>(
Bind(&CaptureManager::AddVideoRenderer,
capture_manager_.get(), capturer, renderer));
}
bool ChannelManager::RemoveVideoRenderer(
VideoCapturer* capturer, VideoRenderer* renderer) {
return initialized_ && worker_thread_->Invoke<bool>(
Bind(&CaptureManager::RemoveVideoRenderer,
capture_manager_.get(), capturer, renderer));
}
bool ChannelManager::IsScreencastRunning() const {
return initialized_ && worker_thread_->Invoke<bool>(
Bind(&ChannelManager::IsScreencastRunning_w, this));
}
bool ChannelManager::IsScreencastRunning_w() const {
VideoChannels::const_iterator it = video_channels_.begin();
for ( ; it != video_channels_.end(); ++it) {
if ((*it) && (*it)->IsScreencasting()) {
return true;
}
}
return false;
}
void ChannelManager::OnVideoCaptureStateChange(VideoCapturer* capturer,
CaptureState result) {
// TODO(whyuan): Check capturer and signal failure only for camera video, not
// screencast.
capturing_ = result == CS_RUNNING;
main_thread_->Post(this, MSG_VIDEOCAPTURESTATE,
new CaptureStateParams(capturer, result));
}
void ChannelManager::OnMessage(rtc::Message* message) {
switch (message->message_id) {
case MSG_VIDEOCAPTURESTATE: {
CaptureStateParams* data =
static_cast<CaptureStateParams*>(message->pdata);
SignalVideoCaptureStateChange(data->capturer, data->state);
delete data;
break;
}
}
}
static void GetDeviceNames(const std::vector<Device>& devs,
std::vector<std::string>* names) {
names->clear();
for (size_t i = 0; i < devs.size(); ++i) {
names->push_back(devs[i].name);
}
}
bool ChannelManager::GetAudioInputDevices(std::vector<std::string>* names) {
names->clear();
std::vector<Device> devs;
bool ret = device_manager_->GetAudioInputDevices(&devs);
if (ret)
GetDeviceNames(devs, names);
return ret;
}
bool ChannelManager::GetAudioOutputDevices(std::vector<std::string>* names) {
names->clear();
std::vector<Device> devs;
bool ret = device_manager_->GetAudioOutputDevices(&devs);
if (ret)
GetDeviceNames(devs, names);
return ret;
}
bool ChannelManager::GetVideoCaptureDevices(std::vector<std::string>* names) {
names->clear();
std::vector<Device> devs;
bool ret = device_manager_->GetVideoCaptureDevices(&devs);
if (ret)
GetDeviceNames(devs, names);
return ret;
}
void ChannelManager::SetVideoCaptureDeviceMaxFormat(
const std::string& usb_id,
const VideoFormat& max_format) {
device_manager_->SetVideoCaptureDeviceMaxFormat(usb_id, max_format);
}
bool ChannelManager::StartAecDump(rtc::PlatformFile file) {
return worker_thread_->Invoke<bool>(
Bind(&MediaEngineInterface::StartAecDump, media_engine_.get(), file));
}
} // namespace cricket
| dcpang/fatline-libjingle | session/media/channelmanager.cc | C++ | bsd-3-clause | 30,235 |
import React from 'react';
import Spinner from 'react-spinkit';
export default ({visible}) => {
const spinner = (
<div className="loading-spinner">
<h1>LADDAR</h1>
<Spinner name="wave" />
</div>
);
return visible ? spinner : null;
};
| dtekcth/dfotose | src/client/components/LoadingSpinner.js | JavaScript | bsd-3-clause | 264 |
<?php
/** XML Parser Functions.
See: {@link http://www.php.net/manual/en/ref.xml.php}
@package xml
*/
define("XML_ERROR_ASYNC_ENTITY", 13);
define("XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF", 16);
define("XML_ERROR_BAD_CHAR_REF", 14);
define("XML_ERROR_BINARY_ENTITY_REF", 15);
define("XML_ERROR_DUPLICATE_ATTRIBUTE", 8);
define("XML_ERROR_EXTERNAL_ENTITY_HANDLING", 21);
define("XML_ERROR_INCORRECT_ENCODING", 19);
define("XML_ERROR_INVALID_TOKEN", 4);
define("XML_ERROR_JUNK_AFTER_DOC_ELEMENT", 9);
define("XML_ERROR_MISPLACED_XML_PI", 17);
define("XML_ERROR_NONE", 0);
define("XML_ERROR_NO_ELEMENTS", 3);
define("XML_ERROR_NO_MEMORY", 1);
define("XML_ERROR_PARAM_ENTITY_REF", 10);
define("XML_ERROR_PARTIAL_CHAR", 6);
define("XML_ERROR_RECURSIVE_ENTITY_REF", 12);
define("XML_ERROR_SYNTAX", 2);
define("XML_ERROR_TAG_MISMATCH", 7);
define("XML_ERROR_UNCLOSED_CDATA_SECTION", 20);
define("XML_ERROR_UNCLOSED_TOKEN", 5);
define("XML_ERROR_UNDEFINED_ENTITY", 11);
define("XML_ERROR_UNKNOWN_ENCODING", 18);
define("XML_OPTION_CASE_FOLDING", 1);
define("XML_OPTION_SKIP_TAGSTART", 3);
define("XML_OPTION_SKIP_WHITE", 4);
define("XML_OPTION_TARGET_ENCODING", 2);
define("XML_SAX_IMPL", "?");
/*. resource .*/ function xml_parser_create( /*. args .*/){}
/*. resource .*/ function xml_parser_create_ns( /*. args .*/){}
/*. bool .*/ function xml_set_object(/*. resource .*/ $parser, /*. object .*/ &$obj){}
/*. bool .*/ function xml_set_element_handler(/*. resource .*/ $parser, /*. mixed .*/ $shdl, /*. mixed .*/ $ehdl){}
/*. bool .*/ function xml_set_character_data_handler(/*. resource .*/ $parser, /*. mixed .*/ $hdl){}
/*. bool .*/ function xml_set_processing_instruction_handler(/*. resource .*/ $parser, /*. mixed .*/ $hdl){}
/*. bool .*/ function xml_set_default_handler(/*. resource .*/ $parser, /*. mixed .*/ $hdl){}
/*. bool .*/ function xml_set_unparsed_entity_decl_handler(/*. resource .*/ $parser, /*. mixed .*/ $hdl){}
/*. bool .*/ function xml_set_notation_decl_handler(/*. resource .*/ $parser, /*. mixed .*/ $hdl){}
/*. bool .*/ function xml_set_external_entity_ref_handler(/*. resource .*/ $parser, /*. mixed .*/ $hdl){}
/*. bool .*/ function xml_set_start_namespace_decl_handler(/*. resource .*/ $parser, /*. mixed .*/ $hdl){}
/*. bool .*/ function xml_set_end_namespace_decl_handler(/*. resource .*/ $parser, /*. mixed .*/ $hdl){}
/*. int .*/ function xml_parse(/*. resource .*/ $parser, /*. string .*/ $data, $is_final = FALSE){}
/*. int .*/ function xml_parse_into_struct(/*. resource .*/ $parser, /*. string .*/ $data, /*. return array .*/ &$values, /*. return array .*/ &$index){}
/*. int .*/ function xml_get_error_code(/*. resource .*/ $parser){}
/*. string .*/ function xml_error_string(/*. int .*/ $code){}
/*. int .*/ function xml_get_current_line_number(/*. resource .*/ $parser){}
/*. int .*/ function xml_get_current_column_number(/*. resource .*/ $parser){}
/*. int .*/ function xml_get_current_byte_index(/*. resource .*/ $parser){}
/*. bool .*/ function xml_parser_free(/*. resource .*/ $parser){}
/*. bool .*/ function xml_parser_set_option(/*. resource .*/ $parser, /*. int .*/ $option, /*. mixed .*/ $value){}
/*. mixed .*/ function xml_parser_get_option(/*. resource .*/ $parser, /*. int .*/ $option){}
/*. string.*/ function utf8_encode(/*. string .*/ $data){}
/*. string.*/ function utf8_decode(/*. string .*/ $data){}
| zenus/thinkphpLint | modules/xml.php | PHP | bsd-3-clause | 3,358 |
<?php
namespace app\modules\mycompany\popularitems;
class PopularItems extends \yii\base\Module
{
public function init()
{
parent::init();
\Yii::configure($this, require(__DIR__ . '/config.php'));
}
} | lukos/yii2-tutorial | modules/mycompany/popularitems/PopularItems.php | PHP | bsd-3-clause | 230 |
package com.noxlogic.joindin;
/*
* This is the main activity class. All activities in our application will extend
* JIActivity instead of activity. This class supplies us with some additional
* tools and options which need to be set for all activity screens (for instance,
* the menu)
*/
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.widget.Toast;
public class JIActivity extends Activity {
static String _comment_history;
static public String getCommentHistory () {
return _comment_history;
}
public static void setCommentHistory(String comment) {
_comment_history = comment;
}
// Returns boolean if the user has entered valid credentials in the preferences
// screen to login into the joind.in API. Needed to send registered comments and
// to attend events.
static public boolean hasValidCredentials (Context context) {
String ret = validateCredentials (context);
return ret.startsWith("T|");
}
// This function will validate the credentials given in the preferences.
// Returns a string in the following format:
// T|<message> credentials are valid
// F|<message> credentials are not valid
static public String validateCredentials (Context context) {
String result;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// Check credentials in the joind.in API
JIRest rest = new JIRest (context);
int error = rest.postXML ("user", "<request><action type=\"validate\" output=\"json\"><uid>"+prefs.getString("username", "")+"</uid><pass>"+JIRest.md5(prefs.getString("password", ""))+"</pass></action></request>");
if (error == JIRest.OK) {
try {
JSONObject json = new JSONObject(rest.getResult());
result = json.optString("msg");
} catch (Exception e) {
// Incorrect JSON, just return plain result from http
result = rest.getResult();
}
} else {
// Incorrect result, return error
result = rest.getError();
}
// Result ok?
if (result.compareTo ("success") == 0) {
return "T|"+context.getString(R.string.JIActivityCorrectCredentials);
}
// Something went wrong
if (result.compareTo ("Invalid user") == 0) result = context.getString(R.string.JIActivityIncorrectCredentials);
return "F|"+result;
}
// Automatically called by all activities.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Needed to show the circular progress animation in the top right corner.
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
}
// Displays (or hides) the circular progress animation in the top left corner
public void displayProgressBar (final boolean state) {
runOnUiThread(new Runnable() {
public void run() {
setProgressBarIndeterminateVisibility(state);
}
});
}
// Automatically called. Creates option menu. All activities share the same menu.
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
// Handler for options menu
public boolean onOptionsItemSelected (MenuItem item) {
switch (item.getItemId()) {
case R.id.about_menu_item :
// Display about box
Dialog about = new AlertDialog.Builder(this)
.setTitle(R.string.generalAboutTitle)
.setPositiveButton(R.string.generalAboutButtonCaption, null)
.setMessage(R.string.generalAboutMessage)
.create();
about.show();
break;
case R.id.clear_menu_item :
// Removes all items from the database
DataHelper dh = DataHelper.getInstance ();
dh.deleteAll ();
Toast toast = Toast.makeText (getApplicationContext(), R.string.generalCacheCleared, Toast.LENGTH_LONG);
toast.show ();
break;
case R.id.settings_menu_item :
// Displays preferences
Intent settingsActivity = new Intent(getApplicationContext(), Preferences.class);
startActivity(settingsActivity);
break;
}
return true;
}
}
| derickr/Joind.in-android-app | source/src/com/noxlogic/joindin/JIActivity.java | Java | bsd-3-clause | 5,195 |
<?php
namespace Kino\Model;
class Comment
{
public $commentID;
public $imdbID;
public $commentHeading;
public $commentText;
public $rating;
public $created;
public $ip;
public function exchangeArray ($data)
{
$this->commentID = (! empty($data['commentID'])) ? $data['commentID'] : null;
$this->imdbID = (! empty($data['imdbID'])) ? $data['imdbID'] : null;
$this->commentHeading = (! empty($data['commentHeading'])) ? $data['commentHeading'] : null;
$this->commentText = (! empty($data['commentText'])) ? $data['commentText'] : null;
$this->rating = (! empty($data['rating'])) ? $data['rating'] : null;
$this->created = (! empty($data['created'])) ? $data['created'] : null;
$this->ip = (! empty($data['ip'])) ? $data['ip'] : null;
}
}
?> | denikin/kinodb | module/Kino/src/Kino/Model/Comment.php | PHP | bsd-3-clause | 842 |
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Weathers';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="weather-index">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Create Weather', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'city',
'time:datetime',
'json_data:ntext',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
| NbDasH/jgsoo | views/weather/index.php | PHP | bsd-3-clause | 715 |
<?php
/**
* Webino (http://webino.sk/)
*
* @link https://github.com/webino/WebinoDev/ for the canonical source repository
* @copyright Copyright (c) 2014-2017 Webino, s. r. o. (http://webino.sk/)
* @license BSD-3-Clause
*/
namespace WebinoDev\Test;
/**
* Concrete test trait
*/
class DomTestCase extends \PHPUnit_Framework_TestCase
{
use DomTrait;
}
| webino/WebinoDev | tests/resources/src/WebinoDev/Test/DomTestCase.php | PHP | bsd-3-clause | 377 |
#include "def_lang/impl/Poly_Type.h"
#include "def_lang/impl/Poly_Value.h"
#include "def_lang/IAttribute.h"
#include "def_lang/ILiteral_Attribute.h"
#include "def_lang/IStruct_Type.h"
#include "def_lang/IString_Value.h"
#include <deque>
namespace ts
{
Poly_Type::Poly_Type(std::string const& name)
: Symbol_EP(name)
, m_ui_name(name)
{
}
Poly_Type::Poly_Type(Poly_Type const& other, std::string const& name)
: Symbol_EP(other, name)
, Attribute_Container_EP(other)
, m_inner_qualified_type(other.m_inner_qualified_type)
, m_inner_type(other.m_inner_type)
, m_ui_name(name)
, m_native_type(other.m_ui_name)
{
}
Result<void> Poly_Type::init(std::vector<std::shared_ptr<const ITemplate_Argument>> const& arguments)
{
if (arguments.size() != 1)
{
return Error("Expected only one template argument, got " + std::to_string(arguments.size()));
}
std::shared_ptr<const Qualified_Type> qtype = std::dynamic_pointer_cast<const Qualified_Type>(arguments[0]);
if (!qtype)
{
return Error("Invalid template argument. Expected type");
}
m_inner_type = std::dynamic_pointer_cast<const IStruct_Type>(qtype->get_type());
if (!m_inner_type)
{
return Error("Invalid template argument. Expected struct type");
}
m_inner_qualified_type = qtype;
return success;
}
std::string const& Poly_Type::get_ui_name() const
{
return m_ui_name;
}
Symbol_Path Poly_Type::get_native_type() const
{
return m_native_type;
}
Result<void> Poly_Type::validate_attribute(IAttribute const& attribute)
{
if (attribute.get_name() == "ui_name")
{
if (ILiteral_Attribute const* att = dynamic_cast<ILiteral_Attribute const*>(&attribute))
{
IString_Value const* value = dynamic_cast<IString_Value const*>(&att->get_value());
if (!value)
{
return Error("Attribute '" + attribute.get_name() + "' has to be a string.");
}
m_ui_name = value->get_value();
return success;
}
else
{
return Error("Attribute '" + attribute.get_name() + "' has to be a string literal.");
}
}
else if (attribute.get_name() == "native_type")
{
if (ILiteral_Attribute const* att = dynamic_cast<ILiteral_Attribute const*>(&attribute))
{
IString_Value const* value = dynamic_cast<IString_Value const*>(&att->get_value());
if (!value)
{
return Error("Attribute '" + attribute.get_name() + "' has to be a string.");
}
m_native_type = value->get_value();
return success;
}
else
{
return Error("Attribute '" + attribute.get_name() + "' has to be a string literal.");
}
}
else
{
return Error("Attribute " + attribute.get_name() + " not supported");
}
}
std::shared_ptr<IType> Poly_Type::clone(std::string const& name) const
{
return std::make_shared<Poly_Type>(*this, name);
}
std::shared_ptr<IType> Poly_Type::alias(std::string const& name) const
{
std::shared_ptr<Poly_Type> alias = std::make_shared<Poly_Type>(*this, name);
alias->m_native_type = Symbol_Path(); //clear the native type as this is an alias
alias->m_aliased_type = this->shared_from_this();
return alias;
}
std::shared_ptr<const IType> Poly_Type::get_aliased_type() const
{
return m_aliased_type;
}
std::shared_ptr<const Qualified_Type> Poly_Type::get_inner_qualified_type() const
{
return m_inner_qualified_type;
}
std::vector<std::shared_ptr<const Qualified_Type>> Poly_Type::get_all_inner_qualified_types() const
{
IDeclaration_Scope const* top_scope = get_parent_scope();
if (!top_scope)
{
return {};
}
while (top_scope->get_parent_scope())
{
top_scope = top_scope->get_parent_scope();
}
std::vector<std::shared_ptr<const Qualified_Type>> results;
std::deque<const IDeclaration_Scope*> stack{ top_scope };
while (!stack.empty())
{
IDeclaration_Scope const* scope = stack.front();
stack.pop_front();
for (size_t i = 0; i < scope->get_symbol_count(); i++)
{
std::shared_ptr<ISymbol const> symbol = scope->get_symbol(i);
if (std::shared_ptr<IStruct_Type const> struct_type = std::dynamic_pointer_cast<IStruct_Type const>(symbol))
{
if (m_inner_type->is_base_of(*struct_type))
{
results.emplace_back(new Qualified_Type(struct_type, m_inner_qualified_type->is_const()));
}
}
if (std::shared_ptr<IDeclaration_Scope const> s = std::dynamic_pointer_cast<IDeclaration_Scope const>(symbol))
{
stack.push_back(s.get());
}
}
}
return results;
}
std::shared_ptr<IValue> Poly_Type::create_value() const
{
return create_specialized_value();
}
std::shared_ptr<Poly_Type::value_type> Poly_Type::create_specialized_value() const
{
return std::make_shared<Poly_Value>(shared_from_this());
}
}
| jeanleflambeur/silkopter | def_lang/src/ts/Poly_Type.cpp | C++ | bsd-3-clause | 5,151 |
module WpWrapper
module Modules
module Themes
def activate_random_theme(ignore_themes: [])
theme_links = get_theme_links(ignore_themes: ignore_themes)
random_url = (theme_links && theme_links.any?) ? theme_links.sample : nil
perform_activation(random_url) if random_url
end
def activate_theme(theme_identifier = 'twentytwelve')
success = false
theme_links = get_theme_links
if theme_links && theme_links.any?
activation_link = nil
regex = Regexp.new("stylesheet=#{theme_identifier}", Regexp::IGNORECASE)
theme_links.each do |link|
href = link["href"]
if regex.match(href)
activation_link = href
break
end
end
success = perform_activation(activation_link)
if success
puts "[WpWrapper::Modules::Themes] - #{Time.now}: Url: #{self.url}. Theme '#{theme_identifier}' has been activated!"
else
puts "[WpWrapper::Modules::Themes] - #{Time.now}: Url: #{self.url}. Couldn't find the theme #{theme_identifier}'s activation-link."
end
end
return success
end
def perform_activation(url)
success = false
if url && url.present?
puts "[WpWrapper::Modules::Themes] - #{Time.now}: Will activate theme with url #{url}."
self.mechanize_client.open_url(url)
success = true
end
return success
end
def get_theme_links(ignore_themes: [])
theme_links = []
if login
themes_page = self.mechanize_client.open_url(get_url(:themes))
links = themes_page ? themes_page.parser.css("div.themes div.theme div.theme-actions a.activate") : []
links.each do |link|
href = link["href"]
if ignore_themes && ignore_themes.any?
ignore_themes.each do |ignore_theme|
regex = ignore_theme.is_a?(Regexp) ? ignore_theme : Regexp.new("stylesheet=#{ignore_theme}", Regexp::IGNORECASE)
if !regex.match(href)
theme_links << href
break
end
end
else
theme_links << href
end
end if links && links.any?
end
puts "[WpWrapper::Modules::Themes] - #{Time.now}: Found a total of #{theme_links.size} theme activation links."
return theme_links
end
end
end
end
| Agiley/wp_wrapper | lib/wp_wrapper/modules/themes.rb | Ruby | bsd-3-clause | 2,887 |
/*
* [The "BSD license"]
* Copyright (c) 2012 Terence Parr
* Copyright (c) 2012 Sam Harwell
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.antlr.v4.test;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/*
cover these cases:
dead end
single alt
single alt + preds
conflict
conflict + preds
*/
public class TestFullContextParsing extends BaseTest {
@Test public void testAmbigYieldsCtxSensitiveDFA() {
String grammar =
"grammar T;\n"+
"s" +
"@after {dumpDFA();}\n" +
" : ID | ID {;} ;\n" +
"ID : 'a'..'z'+ ;\n"+
"WS : (' '|'\\t'|'\\n')+ -> skip ;\n";
String result = execParser("T.g4", grammar, "TParser", "TLexer", "s",
"abc", true);
String expecting =
"Decision 0:\n" +
"s0-ID->:s1^=>1\n"; // ctx sensitive
assertEquals(expecting, result);
assertEquals("line 1:0 reportAttemptingFullContext d=0 (s), input='abc'\n",
this.stderrDuringParse);
}
public String testCtxSensitiveDFA(String input) {
String grammar =
"grammar T;\n"+
"s @after {dumpDFA();}\n" +
" : '$' a | '@' b ;\n" +
"a : e ID ;\n" +
"b : e INT ID ;\n" +
"e : INT | ;\n" +
"ID : 'a'..'z'+ ;\n"+
"INT : '0'..'9'+ ;\n"+
"WS : (' '|'\\t'|'\\n')+ -> skip ;\n";
return execParser("T.g4", grammar, "TParser", "TLexer", "s", input, true);
}
@Test
public void testCtxSensitiveDFA1() {
String result = testCtxSensitiveDFA("$ 34 abc");
String expecting =
"Decision 1:\n" +
"s0-INT->s1\n" +
"s1-ID->:s2^=>1\n";
assertEquals(expecting, result);
assertEquals("line 1:5 reportAttemptingFullContext d=1 (e), input='34abc'\n" +
"line 1:2 reportContextSensitivity d=1 (e), input='34'\n",
this.stderrDuringParse);
}
@Test
public void testCtxSensitiveDFA2() {
String result = testCtxSensitiveDFA("@ 34 abc");
String expecting =
"Decision 1:\n" +
"s0-INT->s1\n" +
"s1-ID->:s2^=>1\n";
assertEquals(expecting, result);
assertEquals("line 1:5 reportAttemptingFullContext d=1 (e), input='34abc'\n" +
"line 1:5 reportContextSensitivity d=1 (e), input='34abc'\n",
this.stderrDuringParse);
}
@Test public void testCtxSensitiveDFATwoDiffInput() {
String grammar =
"grammar T;\n"+
"s @after {dumpDFA();}\n" +
" : ('$' a | '@' b)+ ;\n" +
"a : e ID ;\n" +
"b : e INT ID ;\n" +
"e : INT | ;\n" +
"ID : 'a'..'z'+ ;\n"+
"INT : '0'..'9'+ ;\n"+
"WS : (' '|'\\t'|'\\n')+ -> skip ;\n";
String result = execParser("T.g4", grammar, "TParser", "TLexer", "s",
"$ 34 abc @ 34 abc", true);
String expecting =
"Decision 2:\n" +
"s0-INT->s1\n" +
"s1-ID->:s2^=>1\n";
assertEquals(expecting, result);
assertEquals("line 1:5 reportAttemptingFullContext d=2 (e), input='34abc'\n" +
"line 1:2 reportContextSensitivity d=2 (e), input='34'\n" +
"line 1:14 reportAttemptingFullContext d=2 (e), input='34abc'\n" +
"line 1:14 reportContextSensitivity d=2 (e), input='34abc'\n",
this.stderrDuringParse);
}
@Test
public void testSLLSeesEOFInLLGrammar() {
String grammar =
"grammar T;\n"+
"s @after {dumpDFA();}\n" +
" : a ;\n" +
"a : e ID ;\n" +
"b : e INT ID ;\n" +
"e : INT | ;\n" +
"ID : 'a'..'z'+ ;\n"+
"INT : '0'..'9'+ ;\n"+
"WS : (' '|'\\t'|'\\n')+ -> skip ;\n";
String result = execParser("T.g4", grammar, "TParser", "TLexer", "s",
"34 abc", true);
String expecting =
"Decision 0:\n" +
"s0-INT->s1\n" +
"s1-ID->:s2^=>1\n"; // Must point at accept state
assertEquals(expecting, result);
assertEquals("line 1:3 reportAttemptingFullContext d=0 (e), input='34abc'\n" +
"line 1:0 reportContextSensitivity d=0 (e), input='34'\n",
this.stderrDuringParse);
}
@Test public void testFullContextIF_THEN_ELSEParse() {
String grammar =
"grammar T;\n"+
"s" +
"@init {_interp.setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);}\n" +
"@after {dumpDFA();}\n" +
" : '{' stat* '}'" +
" ;\n" +
"stat: 'if' ID 'then' stat ('else' ID)?\n" +
" | 'return'\n" +
" ;" +
"ID : 'a'..'z'+ ;\n"+
"WS : (' '|'\\t'|'\\n')+ -> skip ;\n";
String input = "{ if x then return }";
String result = execParser("T.g4", grammar, "TParser", "TLexer", "s",
input, true);
String expecting =
"Decision 1:\n" +
"s0-'}'->:s1=>2\n";
assertEquals(expecting, result);
assertEquals(null, this.stderrDuringParse);
input = "{ if x then return else foo }";
result = execParser("T.g4", grammar, "TParser", "TLexer", "s",
input, true);
expecting =
"Decision 1:\n" +
"s0-'else'->:s1^=>1\n";
assertEquals(expecting, result);
// Technically, this input sequence is not ambiguous because else
// uniquely predicts going into the optional subrule. else cannot
// be matched by exiting stat since that would only match '}' or
// the start of a stat. But, we are using the theory that
// SLL(1)=LL(1) and so we are avoiding full context parsing
// by declaring all else clause parsing to be ambiguous.
assertEquals("line 1:19 reportAttemptingFullContext d=1 (stat), input='else'\n" +
"line 1:19 reportContextSensitivity d=1 (stat), input='else'\n",
this.stderrDuringParse);
input =
"{ if x then if y then return else foo }";
result = execParser("T.g4", grammar, "TParser", "TLexer", "s",
input, true);
expecting =
"Decision 1:\n" +
"s0-'}'->:s2=>2\n" +
"s0-'else'->:s1^=>1\n";
assertEquals(expecting, result);
assertEquals("line 1:29 reportAttemptingFullContext d=1 (stat), input='else'\n" +
"line 1:38 reportAmbiguity d=1 (stat): ambigAlts={1, 2}, input='elsefoo}'\n",
this.stderrDuringParse);
// should not be ambiguous because the second 'else bar' clearly
// indicates that the first else should match to the innermost if.
// LL_EXACT_AMBIG_DETECTION makes us keep going to resolve
input =
"{ if x then if y then return else foo else bar }";
result = execParser("T.g4", grammar, "TParser", "TLexer", "s",
input, true);
expecting =
"Decision 1:\n" +
"s0-'else'->:s1^=>1\n";
assertEquals(expecting, result);
assertEquals("line 1:29 reportAttemptingFullContext d=1 (stat), input='else'\n" +
"line 1:38 reportContextSensitivity d=1 (stat), input='elsefooelse'\n" +
"line 1:38 reportAttemptingFullContext d=1 (stat), input='else'\n" +
"line 1:38 reportContextSensitivity d=1 (stat), input='else'\n",
this.stderrDuringParse);
input =
"{ if x then return else foo\n" +
"if x then if y then return else foo }";
result = execParser("T.g4", grammar, "TParser", "TLexer", "s",
input, true);
expecting =
"Decision 1:\n" +
"s0-'}'->:s2=>2\n" +
"s0-'else'->:s1^=>1\n";
assertEquals(expecting, result);
assertEquals("line 1:19 reportAttemptingFullContext d=1 (stat), input='else'\n" +
"line 1:19 reportContextSensitivity d=1 (stat), input='else'\n" +
"line 2:27 reportAttemptingFullContext d=1 (stat), input='else'\n" +
"line 2:36 reportAmbiguity d=1 (stat): ambigAlts={1, 2}, input='elsefoo}'\n",
this.stderrDuringParse);
input =
"{ if x then return else foo\n" +
"if x then if y then return else foo }";
result = execParser("T.g4", grammar, "TParser", "TLexer", "s",
input, true);
expecting =
"Decision 1:\n" +
"s0-'}'->:s2=>2\n" +
"s0-'else'->:s1^=>1\n";
assertEquals(expecting, result);
assertEquals("line 1:19 reportAttemptingFullContext d=1 (stat), input='else'\n" +
"line 1:19 reportContextSensitivity d=1 (stat), input='else'\n" +
"line 2:27 reportAttemptingFullContext d=1 (stat), input='else'\n" +
"line 2:36 reportAmbiguity d=1 (stat): ambigAlts={1, 2}, input='elsefoo}'\n",
this.stderrDuringParse);
}
/**
* Tests predictions for the following case involving closures.
* http://www.antlr.org/wiki/display/~admin/2011/12/29/Flaw+in+ANTLR+v3+LL(*)+analysis+algorithm
*/
@Test
public void testLoopsSimulateTailRecursion() throws Exception {
String grammar =
"grammar T;\n" +
"prog\n" +
"@init {_interp.setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);}\n" +
" : expr_or_assign*;\n" +
"expr_or_assign\n" +
" : expr '++' {System.out.println(\"fail.\");}\n" +
" | expr {System.out.println(\"pass: \"+$expr.text);}\n" +
" ;\n" +
"expr: expr_primary ('<-' ID)? ;\n" +
"expr_primary\n" +
" : '(' ID ')'\n" +
" | ID '(' ID ')'\n" +
" | ID\n" +
" ;\n" +
"ID : [a-z]+ ;\n" +
"";
String found = execParser("T.g4", grammar, "TParser", "TLexer", "prog", "a(i)<-x", true);
assertEquals("pass: a(i)<-x\n", found);
String expecting =
"line 1:3 reportAttemptingFullContext d=3 (expr_primary), input='a(i)'\n" +
"line 1:7 reportAmbiguity d=3 (expr_primary): ambigAlts={2, 3}, input='a(i)<-x'\n";
assertEquals(expecting, this.stderrDuringParse);
}
@Test
public void testAmbiguityNoLoop() throws Exception {
// simpler version of testLoopsSimulateTailRecursion, no loops
String grammar =
"grammar T;\n" +
"prog\n" +
"@init {_interp.setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);}\n" +
" : expr expr {System.out.println(\"alt 1\");}\n" +
" | expr\n" +
" ;\n" +
"expr: '@'\n" +
" | ID '@'\n" +
" | ID\n" +
" ;\n" +
"ID : [a-z]+ ;\n" +
"WS : [ \\r\\n\\t]+ -> skip ;\n";
String found = execParser("T.g4", grammar, "TParser", "TLexer", "prog", "a@", true);
assertEquals("alt 1\n", found);
String expecting =
"line 1:2 reportAttemptingFullContext d=0 (prog), input='a@'\n" +
"line 1:2 reportAmbiguity d=0 (prog): ambigAlts={1, 2}, input='a@'\n" +
"line 1:2 reportAttemptingFullContext d=1 (expr), input='a@'\n" +
"line 1:2 reportContextSensitivity d=1 (expr), input='a@'\n";
assertEquals(expecting, this.stderrDuringParse);
}
@Test
public void testExprAmbiguity() throws Exception {
// translated left-recursive expr rule to test ambig detection
String grammar =
"grammar T;\n" +
"s\n" +
"@init {_interp.setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);}\n" +
" : expr[0] {System.out.println($expr.ctx.toStringTree(this));} ;\n" +
"\n" +
"expr[int _p]\n" +
" : ID\n" +
" ( {5 >= $_p}? '*' expr[6]\n" +
" | {4 >= $_p}? '+' expr[5]\n" +
" )*\n" +
" ;\n" +
"\n" +
"ID : [a-zA-Z]+ ; // match identifiers\n" +
"WS : [ \\t\\r\\n]+ -> skip ; // toss out whitespace\n";
String found = execParser("T.g4", grammar, "TParser", "TLexer", "s", "a+b", true);
assertEquals("(expr a + (expr b))\n", found);
String expecting =
"line 1:1 reportAttemptingFullContext d=1 (expr), input='+'\n" +
"line 1:2 reportContextSensitivity d=1 (expr), input='+b'\n";
assertEquals(expecting, this.stderrDuringParse);
found = execParser("T.g4", grammar, "TParser", "TLexer", "s", "a+b*c", true);
assertEquals("(expr a + (expr b * (expr c)))\n", found);
expecting =
"line 1:1 reportAttemptingFullContext d=1 (expr), input='+'\n" +
"line 1:2 reportContextSensitivity d=1 (expr), input='+b'\n" +
"line 1:3 reportAttemptingFullContext d=1 (expr), input='*'\n" +
"line 1:5 reportAmbiguity d=1 (expr): ambigAlts={1, 2}, input='*c'\n";
assertEquals(expecting, this.stderrDuringParse);
}
}
| michaelpj/antlr4 | tool/test/org/antlr/v4/test/TestFullContextParsing.java | Java | bsd-3-clause | 12,779 |
import {init} from '../../public/mjs/team';
beforeEach(() => {
document.body.innerHTML = `
<button id="team-name-change-icon"></button>
<div class="popup-form" id="edit-team-name-form" style="display: none;"></div>
<div class="popup-form" id="first-pop-up" style="display: block;"></div>
`;
});
test('validate form shows', async () => {
init();
document.getElementById('team-name-change-icon').click();
expect(document.getElementById('edit-team-name-form').style.display).toEqual('block');
expect(document.getElementById('first-pop-up').style.display).toEqual('none');
});
| RCOS-Grading-Server/HWserver | site/tests/mjs/team.spec.js | JavaScript | bsd-3-clause | 611 |
/*
* default_nernst_planck_boundary.hh
*
* Created on: Jan 17, 2012
* Author: jpods
*/
#ifndef DUNE_AX1_ACME2CYL_ES_NERNST_PLANCK_BOUNDARY_HH
#define DUNE_AX1_ACME2CYL_ES_NERNST_PLANCK_BOUNDARY_HH
#include <dune/pdelab/localoperator/convectiondiffusionparameter.hh>
#include <dune/ax1/common/constants.hh>
template<typename GV, typename RF, typename GF_INITIAL_CON>
class ESNernstPlanckBoundary
{
public:
typedef Dune::PDELab::ConvectionDiffusionBoundaryConditions::Type BCType;
typedef Dune::PDELab::ConvectionDiffusionParameterTraits<GV,RF> Traits;
typedef GF_INITIAL_CON GFInitialCon;
ESNernstPlanckBoundary(const Acme2CylParameters& params_, const GF_INITIAL_CON& gfInitialCon_)
: params(params_),
gfInitialCon(gfInitialCon_),
yMemb(params.yMemb()),
topDirichlet(params_.isTopBoundaryDirichlet_Concentration()),
bottomDirichlet(params_.isBottomBoundaryDirichlet_Concentration()),
leftCytosolDirichlet(params_.isLeftCytosolBoundaryDirichlet_Concentration()),
rightCytosolDirichlet(params_.isRightCytosolBoundaryDirichlet_Concentration()),
leftExtracellularDirichlet(params_.isLeftExtracellularBoundaryDirichlet_Concentration()),
rightExtracellularDirichlet(params_.isRightExtracellularBoundaryDirichlet_Concentration())
{
if(params.nMembranes() == 1 && bottomDirichlet)
DUNE_THROW(Dune::Exception, "Lower boundary should be zero when using only one membrane!");
}
//! boundary condition type function
BCType
bctype (const typename Traits::IntersectionType& is, const typename Traits::IntersectionDomainType& x,
double time, int ionSpecies, bool isMembraneInterface) const
{
// Remember: BC types cannot be time-dependent, so the type set at the beginning will last
// through the entire simulation run!
// default: Dirichlet-bulk
BCType bctype = Dune::PDELab::ConvectionDiffusionBoundaryConditions::Dirichlet;
// Default: Neumann-0 when there is no membrane
if(not params.useMembrane())
{
bctype = Dune::PDELab::ConvectionDiffusionBoundaryConditions::Neumann;
} else {
// *** Handle MEMBRANE boundaries inside domain ***
// We currently only support Neumann bctypes on the membrane interface
if(isMembraneInterface)
{
bctype = Dune::PDELab::ConvectionDiffusionBoundaryConditions::Neumann;
// debug_jochen << "[membInterface] "<< "x = " << is.geometry().global(x)
// << " => " << ION_NAMES[ionSpecies] << " bctype = " << bctype << std::endl;
return bctype;
}
}
bool top = is.geometry().global(x)[1]+1e-6 > params.yMax();
bool bottom = is.geometry().global(x)[1]-1e-6 < params.yMin();
bool left = is.geometry().global(x)[0]-1e-6 < params.xMin();
bool right = is.geometry().global(x)[0]+1e-6 > params.xMax();
bool cytosolBoundary = false;
typename Traits::DomainFieldType yglobal = is.geometry().global(x)[1];
switch(params.nMembranes())
{
case 1:
{
// Side boundaries below membrane are cytosol borders
cytosolBoundary = (left || right)
&& yglobal-1e-6 < yMemb[0]; //- params.dMemb();
break;
}
case 2:
{
// Side boundaries between membranes are cytosol borders
cytosolBoundary = (left || right)
&& yglobal+1e-6 > yMemb[0] //+ params.dMemb()
&& yglobal-1e-6 < yMemb[1]; //+ params.dMemb() ;
break;
}
case 3:
{
// Side boundaries below membrane 1 and between membranes 2 and 3 are cytosol borders
cytosolBoundary = (left || right)
&& (yglobal-1e-6 < yMemb[0] ||
(yglobal+1e-6 > yMemb[1] && yglobal-1e-6 < yMemb[2]));
break;
}
default:
DUNE_THROW(Dune::NotImplemented, "Boundary types for more than 3 membranes not implemented!");
}
// *** Handle TOP boundary ***
if(top)
{
bctype = (topDirichlet ? Dune::PDELab::ConvectionDiffusionBoundaryConditions::Dirichlet
: Dune::PDELab::ConvectionDiffusionBoundaryConditions::Neumann);
return bctype;
}
// *** Handle BOTTOM boundary ***
if(bottom)
{
bctype = (bottomDirichlet ? Dune::PDELab::ConvectionDiffusionBoundaryConditions::Dirichlet
: Dune::PDELab::ConvectionDiffusionBoundaryConditions::Neumann);
return bctype;
}
// *** Handle LEFT boundary ***
if(left)
{
if(cytosolBoundary)
{
bctype = (leftCytosolDirichlet ? Dune::PDELab::ConvectionDiffusionBoundaryConditions::Dirichlet
: Dune::PDELab::ConvectionDiffusionBoundaryConditions::Neumann);
} else {
bctype = (leftExtracellularDirichlet ? Dune::PDELab::ConvectionDiffusionBoundaryConditions::Dirichlet
: Dune::PDELab::ConvectionDiffusionBoundaryConditions::Neumann);
}
return bctype;
}
// *** Handle RIGHT boundary ***
if(right)
{
if(cytosolBoundary)
{
bctype = (rightCytosolDirichlet ? Dune::PDELab::ConvectionDiffusionBoundaryConditions::Dirichlet
: Dune::PDELab::ConvectionDiffusionBoundaryConditions::Neumann);
} else {
bctype = (rightExtracellularDirichlet ? Dune::PDELab::ConvectionDiffusionBoundaryConditions::Dirichlet
: Dune::PDELab::ConvectionDiffusionBoundaryConditions::Neumann);
}
return bctype;
}
//debug_jochen << "x = " << is.geometry().global(x) << " => bctype = " << bctype << std::endl;
//return bctype;
DUNE_THROW(Dune::Exception, "Error checking this boundary's position!");
}
//! Dirichlet boundary condition value
typename Traits::RangeFieldType
g (const typename Traits::ElementType& e, const typename Traits::DomainType& x,
double time, int ionSpecies) const
{
typename Traits::DomainType xglobal = e.geometry().global(x);
//typename Traits::RangeFieldType norm = xglobal.two_norm2();
typename GF_INITIAL_CON::Traits::RangeType conc(0.0);
gfInitialCon.evaluate(e, x, conc);
//debug_jochen << xglobal << "gconc = " << conc[ionSpecies] << std::endl;
return conc[ionSpecies];
}
//! Neumann boundary condition
typename Traits::RangeFieldType
j (const typename Traits::IntersectionType& is, const typename Traits::IntersectionDomainType& x,
double time, int ionSpecies) const
{
return 0.0;
}
//! outflow boundary condition
typename Traits::RangeFieldType
o (const typename Traits::IntersectionType& is, const typename Traits::IntersectionDomainType& x,
double time, int ionSpecies) const
{
return 0.0;
}
private:
const Acme2CylParameters& params;
const GF_INITIAL_CON& gfInitialCon;
const std::vector<double> yMemb;
const bool topDirichlet;
const bool bottomDirichlet;
const bool leftCytosolDirichlet;
const bool rightCytosolDirichlet;
const bool leftExtracellularDirichlet;
const bool rightExtracellularDirichlet;
};
#endif /* DUNE_AX1_ACME2CYL_DEFAULT_NERNST_PLANCK_BOUNDARY_HH */
| pederpansen/dune-ax1 | dune/ax1/acme2_cyl/configurations/ES/ES_nernst_planck_boundary.hh | C++ | bsd-3-clause | 7,501 |
# Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
from django.conf.urls import patterns, url
urlpatterns = patterns('huxley.www.views',
# Match any URL and let the client take care of routing.
url(r'', 'index', name='index'),
)
| jmosky12/huxley | huxley/www/urls.py | Python | bsd-3-clause | 336 |
/*@ buildName :: (firstName: string) => string */
/*@ buildName :: (firstName: string, lastName: string) => string */
function buildName(firstName: string, lastName?: string) {
if (lastName)
return firstName + " " + lastName;
else
return firstName;
}
let result1 = buildName("Bob"); //works correctly now
let result3 = buildName("Bob", "Adams"); //ah, just right
| UCSD-PL/RefScript | tests/pos/misc/51-vararg.ts | TypeScript | bsd-3-clause | 415 |
package config
import (
"fmt"
"github.com/stretchr/testify/assert"
"os"
"testing"
"time"
)
type Config struct {
Some string `env:"somevar"`
Other bool `env:"othervar"`
Port int `env:"PORT"`
NotAnEnv string
DatabaseURL string `env:"DATABASE_URL" envDefault:"postgres://localhost:5432/db"`
Strings []string `env:"STRINGS"`
SepStrings []string `env:"SEPSTRINGS" envSeparator:":"`
Numbers []int `env:"NUMBERS"`
Numbers64 []int64 `env:"NUMBERS64"`
Bools []bool `env:"BOOLS"`
Duration time.Duration `env:"DURATION"`
Float32 float32 `env:"FLOAT32"`
Float64 float64 `env:"FLOAT64"`
Float32s []float32 `env:"FLOAT32S"`
Float64s []float64 `env:"FLOAT64S"`
}
func init() {
enableCache = false
}
func TestParsesEnv(t *testing.T) {
os.Setenv("somevar", "somevalue")
os.Setenv("othervar", "true")
os.Setenv("PORT", "8080")
os.Setenv("STRINGS", "string1,string2,string3")
os.Setenv("SEPSTRINGS", "string1:string2:string3")
os.Setenv("NUMBERS", "1,2,3,4")
os.Setenv("NUMBERS64", "1,2,2147483640,-2147483640")
os.Setenv("BOOLS", "t,TRUE,0,1")
os.Setenv("DURATION", "1s")
os.Setenv("FLOAT32", "3.40282346638528859811704183484516925440e+38")
os.Setenv("FLOAT64", "1.797693134862315708145274237317043567981e+308")
os.Setenv("FLOAT32S", "1.0,2.0,3.0")
os.Setenv("FLOAT64S", "1.0,2.0,3.0")
defer os.Setenv("somevar", "")
defer os.Setenv("othervar", "")
defer os.Setenv("PORT", "")
defer os.Setenv("STRINGS", "")
defer os.Setenv("SEPSTRINGS", "")
defer os.Setenv("NUMBERS", "")
defer os.Setenv("NUMBERS64", "")
defer os.Setenv("BOOLS", "")
defer os.Setenv("DURATION", "")
defer os.Setenv("FLOAT32", "")
defer os.Setenv("FLOAT64", "")
defer os.Setenv("FLOAT32S", "")
defer os.Setenv("FLOAT64S", "")
cfg := Config{}
assert.NoError(t, parse(&cfg))
assert.Equal(t, "somevalue", cfg.Some)
assert.Equal(t, true, cfg.Other)
assert.Equal(t, 8080, cfg.Port)
assert.Equal(t, []string{"string1", "string2", "string3"}, cfg.Strings)
assert.Equal(t, []string{"string1", "string2", "string3"}, cfg.SepStrings)
assert.Equal(t, []int{1, 2, 3, 4}, cfg.Numbers)
assert.Equal(t, []int64{1, 2, 2147483640, -2147483640}, cfg.Numbers64)
assert.Equal(t, []bool{true, true, false, true}, cfg.Bools)
d, _ := time.ParseDuration("1s")
assert.Equal(t, d, cfg.Duration)
f32 := float32(3.40282346638528859811704183484516925440e+38)
assert.Equal(t, f32, cfg.Float32)
f64 := float64(1.797693134862315708145274237317043567981e+308)
assert.Equal(t, f64, cfg.Float64)
assert.Equal(t, []float32{float32(1.0), float32(2.0), float32(3.0)}, cfg.Float32s)
assert.Equal(t, []float64{float64(1.0), float64(2.0), float64(3.0)}, cfg.Float64s)
}
func TestEmptyVars(t *testing.T) {
cfg := Config{}
assert.NoError(t, parse(&cfg))
assert.Equal(t, "", cfg.Some)
assert.Equal(t, false, cfg.Other)
assert.Equal(t, 0, cfg.Port)
assert.Equal(t, 0, len(cfg.Strings))
assert.Equal(t, 0, len(cfg.SepStrings))
assert.Equal(t, 0, len(cfg.Numbers))
assert.Equal(t, 0, len(cfg.Bools))
}
func TestPassAnInvalidPtr(t *testing.T) {
var thisShouldBreak int
assert.Error(t, parse(&thisShouldBreak))
}
func TestPassReference(t *testing.T) {
cfg := Config{}
assert.Error(t, parse(cfg))
}
func TestInvalidBool(t *testing.T) {
os.Setenv("othervar", "should-be-a-bool")
defer os.Setenv("othervar", "")
cfg := Config{}
assert.Error(t, parse(&cfg))
}
func TestInvalidInt(t *testing.T) {
os.Setenv("PORT", "should-be-an-int")
defer os.Setenv("PORT", "")
cfg := Config{}
assert.Error(t, parse(&cfg))
}
func TestInvalidBoolsSlice(t *testing.T) {
type config struct {
BadBools []bool `env:"BADBOOLS"`
}
os.Setenv("BADBOOLS", "t,f,TRUE,faaaalse")
cfg := &config{}
assert.Error(t, parse(cfg))
}
func TestInvalidDuration(t *testing.T) {
os.Setenv("DURATION", "should-be-a-valid-duration")
defer os.Setenv("DURATION", "")
cfg := Config{}
assert.Error(t, parse(&cfg))
}
func TestParsesDefaultConfig(t *testing.T) {
cfg := Config{}
assert.NoError(t, parse(&cfg))
assert.Equal(t, "postgres://localhost:5432/db", cfg.DatabaseURL)
}
func TestParseStructWithoutEnvTag(t *testing.T) {
cfg := Config{}
assert.NoError(t, parse(&cfg))
assert.Empty(t, cfg.NotAnEnv)
}
func TestParseStructWithInvalidFieldKind(t *testing.T) {
type config struct {
WontWorkByte byte `env:"BLAH"`
}
os.Setenv("BLAH", "a")
cfg := config{}
assert.Error(t, parse(&cfg))
}
func TestUnsupportedSliceType(t *testing.T) {
type config struct {
WontWork []map[int]int `env:"WONTWORK"`
}
os.Setenv("WONTWORK", "1,2,3")
defer os.Setenv("WONTWORK", "")
cfg := &config{}
assert.Error(t, parse(cfg))
}
func TestBadSeparator(t *testing.T) {
type config struct {
WontWork []int `env:"WONTWORK" envSeparator:":"`
}
cfg := &config{}
os.Setenv("WONTWORK", "1,2,3,4")
defer os.Setenv("WONTWORK", "")
assert.Error(t, parse(cfg))
}
func TestNoErrorRequiredSet(t *testing.T) {
type config struct {
IsRequired string `env:"IS_REQUIRED,required"`
}
cfg := &config{}
os.Setenv("IS_REQUIRED", "val")
defer os.Setenv("IS_REQUIRED", "")
assert.NoError(t, parse(cfg))
assert.Equal(t, "val", cfg.IsRequired)
}
func TestErrorRequiredNotSet(t *testing.T) {
type config struct {
IsRequired string `env:"IS_REQUIRED,required"`
}
cfg := &config{}
assert.Error(t, parse(cfg))
}
func TestEmptyOption(t *testing.T) {
type config struct {
Var string `env:"VAR,"`
}
cfg := &config{}
os.Setenv("VAR", "val")
defer os.Setenv("VAR", "")
assert.NoError(t, parse(cfg))
assert.Equal(t, "val", cfg.Var)
}
func TestErrorOptionNotRecognized(t *testing.T) {
type config struct {
Var string `env:"VAR,not_supported!"`
}
cfg := &config{}
assert.Error(t, parse(cfg))
}
func ExampleParse() {
type config struct {
Home string `env:"HOME"`
Port int `env:"PORT" envDefault:"3000"`
IsProduction bool `env:"PRODUCTION"`
}
os.Setenv("HOME", "/tmp/fakehome")
cfg := config{}
parse(&cfg)
fmt.Println(cfg)
// Output: {/tmp/fakehome 3000 false}
}
func ExampleParseRequiredField() {
type config struct {
Home string `env:"HOME"`
Port int `env:"PORT" envDefault:"3000"`
IsProduction bool `env:"PRODUCTION"`
SecretKey string `env:"SECRET_KEY,required"`
}
os.Setenv("HOME", "/tmp/fakehome")
cfg := config{}
err := parse(&cfg)
fmt.Println(err)
// Output: Required environment variable SECRET_KEY is not set
}
func ExampleParseMultipleOptions() {
type config struct {
Home string `env:"HOME"`
Port int `env:"PORT" envDefault:"3000"`
IsProduction bool `env:"PRODUCTION"`
SecretKey string `env:"SECRET_KEY,required,option1"`
}
os.Setenv("HOME", "/tmp/fakehome")
cfg := config{}
err := parse(&cfg)
fmt.Println(err)
// Output: Env tag option option1 not supported.
}
| geaviation/goboot | config/env_test.go | GO | bsd-3-clause | 6,886 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "core/paint/ReplacedPainter.h"
#include "core/layout/Layer.h"
#include "core/layout/LayoutReplaced.h"
#include "core/layout/PaintInfo.h"
#include "core/paint/BoxPainter.h"
#include "core/paint/GraphicsContextAnnotator.h"
#include "core/paint/ObjectPainter.h"
#include "core/paint/RenderDrawingRecorder.h"
#include "core/paint/RoundedInnerRectClipper.h"
namespace blink {
void ReplacedPainter::paint(const PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
ANNOTATE_GRAPHICS_CONTEXT(paintInfo, &m_layoutReplaced);
if (!m_layoutReplaced.shouldPaint(paintInfo, paintOffset))
return;
LayoutPoint adjustedPaintOffset = paintOffset + m_layoutReplaced.location();
LayoutRect paintRect(adjustedPaintOffset, m_layoutReplaced.size());
if (m_layoutReplaced.hasBoxDecorationBackground() && (paintInfo.phase == PaintPhaseForeground || paintInfo.phase == PaintPhaseSelection))
m_layoutReplaced.paintBoxDecorationBackground(paintInfo, adjustedPaintOffset);
if (paintInfo.phase == PaintPhaseMask) {
RenderDrawingRecorder renderDrawingRecorder(paintInfo.context, m_layoutReplaced, paintInfo.phase, paintRect);
m_layoutReplaced.paintMask(paintInfo, adjustedPaintOffset);
return;
}
if (paintInfo.phase == PaintPhaseClippingMask && (!m_layoutReplaced.hasLayer() || !m_layoutReplaced.layer()->hasCompositedClippingMask()))
return;
if ((paintInfo.phase == PaintPhaseOutline || paintInfo.phase == PaintPhaseSelfOutline) && m_layoutReplaced.style()->outlineWidth())
ObjectPainter(m_layoutReplaced).paintOutline(paintInfo, paintRect);
if (paintInfo.phase != PaintPhaseForeground && paintInfo.phase != PaintPhaseSelection && !m_layoutReplaced.canHaveChildren() && paintInfo.phase != PaintPhaseClippingMask)
return;
if (!paintInfo.shouldPaintWithinRoot(&m_layoutReplaced))
return;
bool drawSelectionTint = m_layoutReplaced.selectionState() != LayoutObject::SelectionNone && !m_layoutReplaced.document().printing();
if (paintInfo.phase == PaintPhaseSelection) {
if (m_layoutReplaced.selectionState() == LayoutObject::SelectionNone)
return;
drawSelectionTint = false;
}
// FIXME(crbug.com/444591): Refactor this to not create a drawing recorder for renderers with children.
OwnPtr<RenderDrawingRecorder> renderDrawingRecorder;
if (!m_layoutReplaced.isSVGRoot())
renderDrawingRecorder = adoptPtr(new RenderDrawingRecorder(paintInfo.context, m_layoutReplaced, paintInfo.phase, paintRect));
if (renderDrawingRecorder && renderDrawingRecorder->canUseCachedDrawing())
return;
{
OwnPtr<RoundedInnerRectClipper> clipper;
bool completelyClippedOut = false;
if (m_layoutReplaced.style()->hasBorderRadius()) {
LayoutRect borderRect = LayoutRect(adjustedPaintOffset, m_layoutReplaced.size());
if (borderRect.isEmpty()) {
completelyClippedOut = true;
} else {
// Push a clip if we have a border radius, since we want to round the foreground content that gets painted.
FloatRoundedRect roundedInnerRect = m_layoutReplaced.style()->getRoundedInnerBorderFor(paintRect,
m_layoutReplaced.paddingTop() + m_layoutReplaced.borderTop(), m_layoutReplaced.paddingBottom() + m_layoutReplaced.borderBottom(), m_layoutReplaced.paddingLeft() + m_layoutReplaced.borderLeft(), m_layoutReplaced.paddingRight() + m_layoutReplaced.borderRight(), true, true);
clipper = adoptPtr(new RoundedInnerRectClipper(m_layoutReplaced, paintInfo, paintRect, roundedInnerRect, ApplyToContext));
}
}
if (!completelyClippedOut) {
if (paintInfo.phase == PaintPhaseClippingMask) {
m_layoutReplaced.paintClippingMask(paintInfo, adjustedPaintOffset);
} else {
m_layoutReplaced.paintReplaced(paintInfo, adjustedPaintOffset);
}
}
}
// The selection tint never gets clipped by border-radius rounding, since we want it to run right up to the edges of
// surrounding content.
if (drawSelectionTint) {
LayoutRect selectionPaintingRect = m_layoutReplaced.localSelectionRect();
selectionPaintingRect.moveBy(adjustedPaintOffset);
paintInfo.context->fillRect(pixelSnappedIntRect(selectionPaintingRect), m_layoutReplaced.selectionBackgroundColor());
}
}
} // namespace blink
| CTSRD-SOAAP/chromium-42.0.2311.135 | third_party/WebKit/Source/core/paint/ReplacedPainter.cpp | C++ | bsd-3-clause | 4,687 |
<?php
namespace backend\controllers;
use Yii;
use backend\models\MirMaker;
use backend\models\MirMakerSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* MirMakerController implements the CRUD actions for MirMaker model.
*/
class MirMakerController extends CommonController
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
/**
* Lists all MirMaker models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new MirMakerSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
if(empty($sort)){
$_GET['sort'] = '-maker_id';
}
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single MirMaker model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new MirMaker model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new MirMaker();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->maker_id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing MirMaker model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->maker_id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing MirMaker model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the MirMaker model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return MirMaker the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = MirMaker::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
| hehekeke/mir_web | backend/controllers/MirMakerController.php | PHP | bsd-3-clause | 3,216 |
#include <avr/interrupt.h>
#include <interrupt/USART_RX.hpp>
template <>
callback_t USART_RXInterrupt::callback_ = nullptr;
| rkojedzinszky/thermo-sensor | lib/atmega328p/interrupt/USART_RX_cb.cpp | C++ | bsd-3-clause | 125 |
<?php
namespace Application\Entity\Repository;
use Doctrine\ORM\EntityRepository;
/**
* UserRepository
*
* Repository class to extend Doctrine ORM functions with your own
* using DQL language. More here http://mackstar.com/blog/2010/10/04/using-repositories-doctrine-2
*
*/
class ProjectRepository extends EntityRepository
{
public function youtCustomDQLFunction($number = 30)
{
}
}
| bit-it-krayina/free2 | module/Application/src/Application/Entity/Repository/ProjectRepository.php | PHP | bsd-3-clause | 407 |
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Devchamp.SentenceCompression")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Devchamp.SentenceCompression")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("bf735beb-24ad-45cf-8596-c408364592d0")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| poulfoged/SentenceCompression | Source/Devchamp.SentenceCompressor/Properties/AssemblyInfo.cs | C# | bsd-3-clause | 578 |
import font
import screenshot
import sys
if __name__ == '__main__':
f = font.Font()
s = screenshot.Screenshot(sys.argv[1], f)
print s.text
#print s.colours
#print s.get_coords_positions()
| barneygale/mcocr | mcocr/__init__.py | Python | bsd-3-clause | 209 |
"""
PlexAPI Utils
"""
from datetime import datetime
try:
from urllib import quote # Python2
except ImportError:
from urllib.parse import quote # Python3
NA = '__NA__' # Value not available
class PlexPartialObject(object):
""" Not all objects in the Plex listings return the complete list of
elements for the object. This object will allow you to assume each
object is complete, and if the specified value you request is None
it will fetch the full object automatically and update itself.
"""
def __init__(self, server, data, initpath):
self.server = server
self.initpath = initpath
self._loadData(data)
def __getattr__(self, attr):
if self.isPartialObject():
self.reload()
return self.__dict__[attr]
def __setattr__(self, attr, value):
if value != NA:
super(PlexPartialObject, self).__setattr__(attr, value)
def _loadData(self, data):
raise Exception('Abstract method not implemented.')
def isFullObject(self):
return self.initpath == self.key
def isPartialObject(self):
return self.initpath != self.key
def reload(self):
data = self.server.query(self.key)
self.initpath = self.key
self._loadData(data[0])
def cast(func, value):
if value not in [None, NA]:
if func == bool:
value = int(value)
value = func(value)
return value
def joinArgs(args):
if not args: return ''
arglist = []
for key in sorted(args, key=lambda x:x.lower()):
value = str(args[key])
arglist.append('%s=%s' % (key, quote(value)))
return '?%s' % '&'.join(arglist)
def toDatetime(value, format=None):
if value and value != NA:
if format: value = datetime.strptime(value, format)
else: value = datetime.fromtimestamp(int(value))
return value
| dodegy/python-plexapi | plexapi/utils.py | Python | bsd-3-clause | 1,909 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model backend\models\MemberOrderProductSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="member-order-product-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'id_order_product') ?>
<?= $form->field($model, 'id_order') ?>
<?= $form->field($model, 'id_product') ?>
<?= $form->field($model, 'quantity') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| wiratama/rama-yii2 | backend/views/member-order-product/_search.php | PHP | bsd-3-clause | 762 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>THConfig Help</TITLE>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=iso-iso-8859-1">
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<div align="center">
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
</div>
</BODY>
</HTML> | TR-Host/THConfig | interface/web/help/index.php | PHP | bsd-3-clause | 339 |
/**
* Created by anton on 25.08.16.
*/
$('#linkEditModalWindow').on('show.bs.modal', function(event){
HandleItem($(this), event, '/links/modal-add',
'/links/modal-edit', '#link_form', '.links-table', function(response){
$('tr#link_'+response.id+'>.link-url').html(response.url);
$('tr#link_'+response.id+'>.link-description').html(response.description);
});
});
$(document).on('click', '.btn-delete-link', function (event) {
DeleteItem($(event.currentTarget), '/links/delete', '#link_');
}); | kalny/portfolio | web/js/links.js | JavaScript | bsd-3-clause | 531 |
<?php
/**
* This file is part of the Zimbra API in PHP library.
*
* © Nguyen Van Nguyen <nguyennv1981@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Zimbra\Mail\Struct;
use Zimbra\Struct\Base;
/**
* CalendarAttach struct class
*
* @package Zimbra
* @subpackage Mail
* @category Struct
* @author Nguyen Van Nguyen - nguyennv1981@gmail.com
* @copyright Copyright © 2013 by Nguyen Van Nguyen.
*/
class CalendarAttach extends Base
{
/**
* Constructor method for CalendarAttach
* @param string $uri URI
* @param string $ct Content Type
* @param string $value Value. Base64 encoded binary alarrm attach data
* @return self
*/
public function __construct($uri = null, $ct = null, $value = null)
{
parent::__construct(trim($value));
if(null !== $uri)
{
$this->property('uri', trim($uri));
}
if(null !== $ct)
{
$this->property('ct', trim($ct));
}
}
/**
* Gets or sets uri
*
* @param string $uri
* @return string|self
*/
public function uri($uri = null)
{
if(null === $uri)
{
return $this->property('uri');
}
return $this->property('uri', trim($uri));
}
/**
* Gets or sets ct
*
* @param string $ct
* @return string|self
*/
public function ct($ct = null)
{
if(null === $ct)
{
return $this->property('ct');
}
return $this->property('ct', trim($ct));
}
/**
* Returns the array representation of this class
*
* @param string $name
* @return array
*/
public function toArray($name = 'attach')
{
return parent::toArray($name);
}
/**
* Method returning the xml representation of this class
*
* @param string $name
* @return SimpleXML
*/
public function toXml($name = 'attach')
{
return parent::toXml($name);
}
}
| malaleche/api-zimbra | src/Zimbra/Mail/Struct/CalendarAttach.php | PHP | bsd-3-clause | 2,135 |
#!/usr/bin/env python
import warnings
import pandas as pd
from pandas_ml.core.accessor import _AccessorMethods
class CrossValidationMethods(_AccessorMethods):
"""
Deprecated. Accessor to ``sklearn.cross_validation``.
"""
_module_name = 'sklearn.cross_validation'
def StratifiedShuffleSplit(self, *args, **kwargs):
"""
Instanciate ``sklearn.cross_validation.StratifiedShuffleSplit`` using automatic mapping.
- ``y``: ``ModelFrame.target``
"""
target = self._target
return self._module.StratifiedShuffleSplit(target.values, *args, **kwargs)
def iterate(self, cv, reset_index=False):
"""
Generate ``ModelFrame`` using iterators for cross validation
Parameters
----------
cv : cross validation iterator
reset_index : bool
logical value whether to reset index, default False
Returns
-------
generated : generator of ``ModelFrame``
"""
if not(isinstance(cv, self._module._PartitionIterator)):
msg = "{0} is not a subclass of PartitionIterator"
warnings.warn(msg.format(cv.__class__.__name__))
for train_index, test_index in cv:
train_df = self._df.iloc[train_index, :]
test_df = self._df.iloc[test_index, :]
if reset_index:
train_df = train_df.reset_index(drop=True)
test_df = test_df.reset_index(drop=True)
yield train_df, test_df
def train_test_split(self, reset_index=False, *args, **kwargs):
"""
Call ``sklearn.cross_validation.train_test_split`` using automatic mapping.
Parameters
----------
reset_index : bool
logical value whether to reset index, default False
kwargs : keywords passed to ``cross_validation.train_test_split``
Returns
-------
train, test : tuple of ``ModelFrame``
"""
func = self._module.train_test_split
def _init(klass, data, index, **kwargs):
if reset_index:
return klass(data, **kwargs)
else:
return klass(data, index=index, **kwargs)
data = self._data
idx = self._df.index
if self._df.has_target():
target = self._target
tr_d, te_d, tr_l, te_l, tr_i, te_i = func(data.values, target.values, idx.values,
*args, **kwargs)
# Create DataFrame here to retain data and target names
tr_d = _init(pd.DataFrame, tr_d, tr_i, columns=data.columns)
te_d = _init(pd.DataFrame, te_d, te_i, columns=data.columns)
tr_l = _init(pd.Series, tr_l, tr_i, name=target.name)
te_l = _init(pd.Series, te_l, te_i, name=target.name)
train_df = self._constructor(data=tr_d, target=tr_l)
test_df = self._constructor(data=te_d, target=te_l)
return train_df, test_df
else:
tr_d, te_d, tr_i, te_i = func(data.values, idx.values, *args, **kwargs)
# Create DataFrame here to retain data and target names
tr_d = _init(pd.DataFrame, tr_d, tr_i, columns=data.columns)
te_d = _init(pd.DataFrame, te_d, te_i, columns=data.columns)
train_df = self._constructor(data=tr_d)
train_df.target_name = self._df.target_name
test_df = self._constructor(data=te_d)
test_df.target_name = self._df.target_name
return train_df, test_df
def cross_val_score(self, estimator, *args, **kwargs):
"""
Call ``sklearn.cross_validation.cross_val_score`` using automatic mapping.
- ``X``: ``ModelFrame.data``
- ``y``: ``ModelFrame.target``
"""
func = self._module.cross_val_score
return func(estimator, X=self._data.values, y=self._target.values, *args, **kwargs)
def permutation_test_score(self, estimator, *args, **kwargs):
"""
Call ``sklearn.cross_validation.permutation_test_score`` using automatic mapping.
- ``X``: ``ModelFrame.data``
- ``y``: ``ModelFrame.target``
"""
func = self._module.permutation_test_score
score, pscores, pvalue = func(estimator, X=self._data.values, y=self._target.values,
*args, **kwargs)
return score, pscores, pvalue
def check_cv(self, cv, *args, **kwargs):
"""
Call ``sklearn.cross_validation.check_cv`` using automatic mapping.
- ``X``: ``ModelFrame.data``
- ``y``: ``ModelFrame.target``
"""
func = self._module.check_cv
return func(cv, X=self._data, y=self._target, *args, **kwargs)
| sinhrks/pandas-ml | pandas_ml/skaccessors/cross_validation.py | Python | bsd-3-clause | 4,933 |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PathReinforcement")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PathReinforcement")]
[assembly: AssemblyCopyright("Copyright © Autodesk, Inc. 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4052f210-ed18-4f51-8171-976c97f72e0b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| AMEE/revit | samples/Revit 2012 SDK/Samples/PathReinforcement/CS/Properties/AssemblyInfo.cs | C# | bsd-3-clause | 2,348 |
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel app\models\ContrySearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Countries';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="country-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Country', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'code',
'name',
'population',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
| ehernandez-xk/yii-test | views/country/index.php | PHP | bsd-3-clause | 845 |
package org.broadinstitute.hellbender.utils.read.markduplicates;
import htsjdk.samtools.util.SortingCollection;
import org.broadinstitute.hellbender.exceptions.GATKException;
import java.io.*;
/** Coded for ReadEnds that just outputs the primitive fields and reads them back. */
public class ReadEndsForMarkDuplicatesCodec implements SortingCollection.Codec<ReadEndsForMarkDuplicates> {
private DataInputStream in;
private DataOutputStream out;
/**
* For an explanation of why codecs must implement clone(),
* see the HTSJDK documentation for {@link htsjdk.samtools.util.SortingCollection.Codec}.
*/
@Override
public ReadEndsForMarkDuplicatesCodec clone() {
return new ReadEndsForMarkDuplicatesCodec();
}
public void setOutputStream(final OutputStream os) { this.out = new DataOutputStream(os); }
public void setInputStream(final InputStream is) { this.in = new DataInputStream(is); }
public DataInputStream getInputStream() {
return in;
}
public DataOutputStream getOutputStream() {
return out;
}
public void encode(final ReadEndsForMarkDuplicates read) {
try {
this.out.writeShort(read.score);
this.out.writeShort(read.libraryId);
this.out.writeByte(read.orientation);
this.out.writeInt(read.read1ReferenceIndex);
this.out.writeInt(read.read1Coordinate);
this.out.writeLong(read.read1IndexInFile);
this.out.writeInt(read.read2ReferenceIndex);
if (read.orientation > ReadEnds.R) {
this.out.writeInt(read.read2Coordinate);
this.out.writeLong(read.read2IndexInFile);
}
this.out.writeShort(read.readGroup);
this.out.writeShort(read.tile);
this.out.writeShort(read.x);
this.out.writeShort(read.y);
this.out.writeByte(read.orientationForOpticalDuplicates);
} catch (final IOException ioe) {
throw new GATKException("Exception writing ReadEnds to file.", ioe);
}
}
public ReadEndsForMarkDuplicates decode() {
final ReadEndsForMarkDuplicates read = new ReadEndsForMarkDuplicates();
try {
// If the first read results in an EOF we've exhausted the stream
try {
read.score = this.in.readShort();
} catch (final EOFException eof) {
return null;
}
read.libraryId = this.in.readShort();
read.orientation = this.in.readByte();
read.read1ReferenceIndex = this.in.readInt();
read.read1Coordinate = this.in.readInt();
read.read1IndexInFile = this.in.readLong();
read.read2ReferenceIndex = this.in.readInt();
if (read.orientation > ReadEnds.R) {
read.read2Coordinate = this.in.readInt();
read.read2IndexInFile = this.in.readLong();
}
read.readGroup = this.in.readShort();
read.tile = this.in.readShort();
read.x = this.in.readShort();
read.y = this.in.readShort();
read.orientationForOpticalDuplicates = this.in.readByte();
return read;
} catch (final IOException ioe) {
throw new GATKException("Exception writing ReadEnds to file.", ioe);
}
}
}
| tomwhite/hellbender | src/main/java/org/broadinstitute/hellbender/utils/read/markduplicates/ReadEndsForMarkDuplicatesCodec.java | Java | bsd-3-clause | 3,411 |
<?php
namespace common\models;
use Yii;
use dosamigos\google\maps\LatLng;
use dosamigos\google\maps\overlays\InfoWindow;
use dosamigos\google\maps\overlays\Marker;
use dosamigos\google\maps\Map;
use dosamigos\google\maps\overlays\Circle;
/**
* This is the model class for table "locations".
*
* @property string $id
* @property integer $is_fav
* @property string $user_id
* @property integer $def
* @property string $name
* @property string $country
* @property string $state
* @property string $district
* @property string $city
* @property string $zip
* @property string $mz
* @property string $street
* @property string $no
* @property integer $floor
* @property integer $apt
* @property string $lat
* @property string $lng
* @property string $location_name
*
* @property Bids[] $bids
* @property User $user
* @property Orders[] $orders
* @property Orders[] $orders0
* @property Presentations[] $presentations
* @property ProviderLocations[] $providerLocations
* @property UserDetails[] $userDetails
* @property UserLocations[] $userLocations
* @property UserObjects[] $userObjects
*/
class Locations extends \yii\db\ActiveRecord
{
public $control;
public $userControl;
/*const SCENARIO_DEFAULT = 'default';
const SCENARIO_REGISTER = 'register';
const SCENARIO_ORDER = 'order';
const SCENARIO_PRESENTATION = 'presentation'; */
/**
* @inheritdoc
*/
public static function tableName()
{
return 'locations';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['is_fav', 'user_id', 'def', 'zip', 'floor', 'apt'], 'integer'],
//[['user_id'], 'required'],
//[['lat', 'lng'], 'required', 'message'=>'Nepravilno uneta lokacija.'],
[['lat', 'lng'], 'number'],
[['name'], 'safe'],
[['country', 'state', 'district', 'city', 'mz', 'street'], 'string', 'max' => 64],
[['no'], 'string', 'max' => 4],
[['buzzer'], 'string', 'max' => 32],
[['location_name'], 'string', 'max' => 128],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
/*public function scenarios()
{
return [
self::SCENARIO_PRESENTATION => ['location_name', 'zip', 'floor', 'apt', 'no', 'name', 'lat', 'lng', 'city', 'country', 'state', 'district', 'mz', 'street'],
self::SCENARIO_REGISTER => ['location_name', 'zip', 'floor', 'apt', 'no', 'name', 'lat', 'lng', 'city', 'country', 'state', 'district', 'mz', 'street'],
self::SCENARIO_DEFAULT => ['location_name', 'zip', 'floor', 'apt', 'no', 'name', 'lat', 'lng', 'city', 'country', 'state', 'district', 'mz', 'street'],
];
}*/
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'is_fav' => 'Is Fav',
'user_id' => 'User ID',
'def' => 'Def',
'name' => 'Lokacija',
'country' => 'Country',
'state' => 'State',
'district' => 'District',
'city' => 'City',
'zip' => 'Zip',
'mz' => 'Mz',
'street' => 'Ulica',
'no' => 'Broj',
'floor' => 'Sprat',
'apt' => 'Stan',
'buzzer' => 'Interfon',
'lat' => 'Lat',
'lng' => 'Lng',
'location_name' => 'Ime Lokacije',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getBids()
{
return $this->hasMany(Bids::className(), ['loc_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getOrders()
{
return $this->hasMany(Orders::className(), ['loc_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getOrders0()
{
return $this->hasMany(Orders::className(), ['loc_id2' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getPresentations()
{
return $this->hasMany(Presentations::className(), ['loc_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUserDetails()
{
return $this->hasMany(UserDetails::className(), ['loc_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUserLocations()
{
return $this->hasMany(UserLocations::className(), ['loc_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUserObjects()
{
return $this->hasMany(UserObjects::className(), ['loc_id' => 'id']);
}
public function map($width = 400, $height = 420, $lw = null, $m = true)
{
$coord = new LatLng(['lat' => $this->lat, 'lng' => $this->lng]);
$map = new Map([
'center' => $coord,
'zoom' => $this->mapZoom($lw),
]);
$map->width = $width;
$map->height = $height;
if($m){
// Lets add a marker now
$marker = new Marker([
'position' => $coord,
'title' => 'Mesto gde vršimo uslugu',
]);
// Add marker to the map
$map->addOverlay($marker);
}
if($lw){
// Lets add a marker now
$circle = new Circle([
'center' => $coord,
'radius' => $lw*1000,
/*'strokeWeight' => '5px',
'strokeOpacity' => .0,*/
'strokeColor' => '#2196F3',
'strokeWeight' => 1,
'fillOpacity' => 0.08,
//'editable' => true,
]);
$map->addOverlay($circle);
}
return $map;
}
public function mapZoom($lw)
{
if($w = $lw){
if($w<1){return 14;}
else if($w>=1 && $w<3){return 13;}
else if($w>=3 && $w<6){return 12;}
else if($w>=6 && $w<11){return 11;}
else if($w>=11 && $w<22){return 10;}
else if($w>=22 && $w<45){return 9;}
else if($w>=45 && $w<90){return 8;}
else if($w>=90 && $w<180){return 7;}
else if($w>=180 && $w<300){return 6;}
else if($w>=300){return 5;}
} else {
return 14;
}
}
public function getCityLocation()
{
return ($this->city && $this->country) ? $this->city . ', ' .$this->country : null;
}
public function getStreetLocation()
{
return $this->street . ', ' . $this->city . ', ' . $this->country;
}
public function distanceTo(Locations $location_to)
{
return round(distance($this->lat, $this->lng, $location_to->lat, $location_to->lng), 2);
}
}
| bokko79/servicemapp | common/models/Locations.php | PHP | bsd-3-clause | 7,137 |
'''
Copyright (c) OS-Networks, http://os-networks.net
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the HWIOS Project nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.'''
import re
class Signal(object):
def __init__(self, name):
self.name = name
self.callees = []
def register_callee(self, callee_function, filters = None):
if filters != None:
_filter = []
for filter in filters:
_filter.append((re.compile(filter[0]), filter[1]))
filters = _filter
self.callees.append({'callee':callee_function,'filters':filters})
def execute(self, filters = None, **kwargs):
"""Matches available filters against callee filter options. Uses registered filter order """
for callee in self.callees:
if filters != None:
match = 0
for idx,compiled_filter in enumerate(callee['filters']):
rp = compiled_filter[0].match(filters[idx])
if rp != None and compiled_filter[1] == True:
match += 1
if rp == None and compiled_filter[1] == False:
match += 1
if match == len(filters):
callee['callee'](**kwargs)
else:
callee['callee'](**kwargs)
class SignalPool(object):
def __init__(self, signals = None):
self.signals = []
if signals != None:
self.signals = signals
def append(self, signal):
'''General signal adding'''
self.signals.append(signal)
def remove(self, signal):
for index, _signal in enumerate(self.signals):
if _signal == signal:
self.signal.remove(signal)
def send(self, signal_name, filters = None, **kwargs):
for _signal in self.signals:
if _signal.name == signal_name:
_signal.execute(filters = filters,**kwargs)
def subscribe(self, signal_name, function, filters = None):
'''signal registration, with option filter'''
for _signal in self.signals:
if _signal.name == signal_name:
_signal.register_callee(function, filters)
| Knygar/hwios | services/web_ui/models/signal.py | Python | bsd-3-clause | 3,723 |
<?php
class ClassProperties
{
public $publicProperty;
protected $protectedProperty;
private $privateProperty;
public $propertyWithDefault = 'non-empty';
public static $staticPropertyWithoutDefault;
public static $staticPropertyWithDefault = 'non-empty';
}
| console-helpers/code-insight | tests/CodeInsight/KnowledgeBase/DataCollector/fixtures/ClassDataCollector/ClassProperties.php | PHP | bsd-3-clause | 269 |
<?php
namespace backend\controllers;
use Yii;
use common\models\User;
use common\models\SignupForm;
use backend\models\UserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* UserController implements the CRUD actions for User model.
*/
class UserController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
/**
* Lists all User models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new UserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single User model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new User model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new User(['scenario' => 'create']);
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->createUser()) {
return $this->redirect(['view', 'id' => $model->id]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing User model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->setScenario('update');
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->createUser()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing User model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the User model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return User the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = User::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
| sanjaykrsingh/vyom | backend/controllers/UserController.php | PHP | bsd-3-clause | 3,362 |
<?php
/**
* TOP API: taobao.tmc.user.cancel request
*
* @author auto create
* @since 1.0, 2015.05.17
*/
class TmcUserCancelRequest
{
/**
* 用户昵称,支持子账号
**/
private $nick;
private $apiParas = array();
public function setNick($nick)
{
$this->nick = $nick;
$this->apiParas["nick"] = $nick;
}
public function getNick()
{
return $this->nick;
}
public function getApiMethodName()
{
return "taobao.tmc.user.cancel";
}
public function getApiParas()
{
return $this->apiParas;
}
public function check()
{
RequestCheckUtil::checkNotNull($this->nick,"nick");
}
public function putOtherTextParam($key, $value) {
$this->apiParas[$key] = $value;
$this->$key = $value;
}
}
| Treeway/sandbox | common/tb/sdk/top/request/TmcUserCancelRequest.php | PHP | bsd-3-clause | 737 |
/// <reference path="../scripts/typings/jquery/jquery.d.ts" />
declare interface webglUtils {
/**
* Creates a program from 2 script tags.
*
* @param {WebGLRenderingContext} gl The WebGLRenderingContext
* to use.
* @param {string[]} shaderScriptIds Array of ids of the script
* tags for the shaders. The first is assumed to be the
* vertex shader, the second the fragment shader.
* @param {string[]} [opt_attribs] An array of attribs names. Locations will be assigned by index if not passed in
* @param {number[]} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations.
* @param {module:webgl-utils.ErrorCallback} opt_errorCallback callback for errors. By default it just prints an error to the console
* on error. If you want something else pass an callback. It's passed an error message.
* @return {WebGLProgram} The created program.
* @memberOf module:webgl-utils
*/
createProgramFromScripts(gl: WebGLRenderingContext, shaderScriptIds: Array<string>,
opt_attribs?: any, opt_locations?: any, opt_errorCallback?: Function): WebGLProgram;
/**
* Resize a canvas to match the size its displayed.
* @param {HTMLCanvasElement} canvas The canvas to resize.
* @param {number} [multiplier] amount to multiply by.
* Pass in window.devicePixelRatio for native pixels.
* @return {boolean} true if the canvas was resized.
* @memberOf module:webgl-utils
*/
resizeCanvasToDisplaySize(canvas: HTMLCanvasElement, multiplier?: number): void;
}
declare const webglUtils: webglUtils;
declare interface webglLessonsHelper {
showNeedWebGL(canvas: HTMLCanvasElement): void;
setupLesson(canvas: HTMLCanvasElement, opt_options?: any): void;
setupSlider(selector: string, options?: any): void;
}
declare const webglLessonsHelper: webglLessonsHelper;
declare interface HTMLCanvasElement {
getContext(contextId: "webgl"): WebGLRenderingContext;
}
declare interface Matrix3 extends ArrayLike<number> {
0: number;
1: number;
2: number;
3: number;
4: number;
5: number;
6: number;
7: number;
8: number;
}
declare interface m3 {
multiply(a: Matrix3, b: Matrix3): Matrix3;
identity(): Matrix3;
projection(width: number, height: number): Matrix3;
project(m: Matrix3, width: number, height: number): Matrix3;
translation(tx: number, ty: number): Matrix3;
translate(m: Matrix3, tx: number, ty: number): Matrix3;
rotation(angleInRadians: number): Matrix3;
rotate(m: Matrix3, angleInRadians: number): Matrix3;
scaling(sx: number, sy: number): Matrix3;
scale(m: Matrix3, sx: number, sy: number): Matrix3;
dot(x1: number, y1: number, x2: number, y2: number): number;
distance(x1: number, y1: number, x2: number, y2: number): number;
normalize(x: number, y: number): Array<number>;
reflect(ix: number, iy: number, nx: number, ny: number): Array<number>;
radToDeg(r: number): number;
degToRad(r: number): number;
}
declare const m3: m3;
declare interface Vector3 extends ArrayLike<number> {
0: number;
1: number;
2: number;
}
declare interface Vector4 extends ArrayLike<number> {
0: number;
1: number;
2: number;
3: number;
}
declare interface Matrix4 extends ArrayLike<number> {
0: number;
1: number;
2: number;
3: number;
4: number;
5: number;
6: number;
7: number;
8: number;
9: number;
10: number;
11: number;
12: number;
13: number;
14: number;
15: number;
}
declare interface m4 {
multiply(a: Matrix4, b: Matrix4, dst?: Matrix4): Matrix4;
subtractVectors(a: Vector3, b: Vector3, dst?: Vector3): Vector3;
normalize(v: Vector3, dst?: Vector3): Vector3;
cross(a: Vector3, b: Vector3, dst?: Vector3): Vector3;
identity(dst?: Matrix4): Matrix4;
transpose(m: Matrix4, dst?: Matrix4): Matrix4;
lookAt(cameraPosition: Vector3, target: Vector3, up: Vector3, dst?: Matrix4): Matrix4;
perspective(fieldOfViewInRadians: number, aspect: number, near: number, far: number, dst?: Matrix4): Matrix4;
orthographic(left: number, right: number, bottom: number, top: number, near: number, far: number, dst?: Matrix4): Matrix4;
frustum(left: number, right: number, bottom: number, top: number, near: number, far: number, dst?: Matrix4): Matrix4;
translation(tx: number, ty: number, tz: number, dst?: Matrix4): Matrix4;
translate(m: Matrix4, tx: number, ty: number, tz: number, dst?: Matrix4): Matrix4;
xRotation(angleInRadians: number, dst?: Matrix4): Matrix4;
xRotate(m: Matrix4, angleInRadians: number, dst?: Matrix4): Matrix4;
yRotation(angleInRadians: number, dst?: Matrix4): Matrix4;
yRotate(m: Matrix4, angleInRadians: number, dst?: Matrix4): Matrix4;
zRotation(angleInRadians: number, dst?: Matrix4): Matrix4;
zRotate(m: Matrix4, angleInRadians: number, dst?: Matrix4): Matrix4;
axisRotation(axis: Vector3, angleInRadians: number, dst?: Matrix4): Matrix4;
axisRotate(m: Matrix4, axis: Vector3, angleInRadians: number, dst?: Matrix4): Matrix4;
scaling(sx: number, sy: number, sz: number, dst?: Matrix4): Matrix4;
scale(m: Matrix4, sx: number, sy: number, sz: number, dst?: Matrix4): Matrix4;
inverse(m: Matrix4, dst?: Matrix4): Matrix4;
transformVector(m: Matrix4, v: Vector4, dst?: Vector4): Vector4;
transformPoint(m: Matrix4, v: Vector3, dst?: Vector4): Vector4;
transformDirection(m: Matrix4, v: Vector3, dst?: Vector4): Vector4;
transformNormal(m: Matrix4, v: Vector3, dst?: Vector3): Vector3
copy(src: Matrix4, dst?: Matrix4);
}
declare const m4: m4; | ichenjin/webgl-fundamentals | study/index.d.ts | TypeScript | bsd-3-clause | 5,746 |
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Admin extends Controller_Template {
// Making use of the home template view
public $template = 'admin';
// This is the default entry point
public function action_index()
{
// Prepare the page and send the details to the template
$this->template->title = "Convo";
$this->template->icon = "comment";
$this->template->content = "";
// Process the forms
$this->process_forms();
// We need to get a list of all the comments
$comments = $comment = Model::factory("comment");
$getData = $comment->all("id", "DESC");
// Fire up the table helper
$table = Model::factory("table");
$output = "No results found";
// Set the table headings
$table->headings(
array(
"ID",
array(
"value" => "PID",
"title" => "Parent ID"
),
"Detail",
"Comment",
"Actions"
)
);
// Ensure that the data we get is not empty
if(!empty($getData))
{
// loop through the comments and create the table
foreach($getData as $comment)
{
// Inject the default forms
// Trash "delete" button form
$trash = Form::open("Admin", array("method" => "post"));
$trash .= Form::hidden("id", $comment['id']);
$trash .= Form::hidden("action", 'trash');
$trash .= Form::button(NULL, '<span class="glyphicon glyphicon-trash"></span>', array("class" => "btn btn-danger btn-sm", "type" => "submit", "title" => "Trash comment"));
$trash .= Form::close();
// Edit button form
$edit = Form::open("Admin", array("method" => "post"));
$edit .= Form::hidden("id", $comment['id']);
$edit .= Form::hidden("action", 'edit');
$edit .= Form::button(NULL, '<span class="glyphicon glyphicon-pencil"></span>', array("class" => "btn btn-default btn-sm", "type" => "submit", "title" => "Edit comment"));
$edit .= Form::close();
// Add the row
$table->addRow(
array(
$comment['id'],
$comment['parent'],
$comment['first_name']. "<br />" .$comment['email']. "<br />" .$comment['date'],
$comment['comment'],
$edit . $trash
)
);
}
// Render the table out
$output = $table->render();
}
# Add the output
$this->template->comments = $output;
}
// We need a simple way to process forms
public function process_forms()
{
// Set a default message array
$this->template->messages = array();
// Hook into the comment Model
$comments = $comment = Model::factory("comment");
// Process forms
if (!empty($_POST['action']) AND !empty($_POST['id']))
{
// Clean post details up
$clean = $comments->cleanse($_POST);
// Get the comment
$getComment = current($comments->id($clean['id']));
// Switch through the cases
switch ($_POST['action'])
{
// Trash request
case 'trash':
// Confirmation form
$this->template->content = Form::open("Admin", array("class" => "form form-vertical well", "method" => "post"));
$this->template->content .= "<h4>Confirm Comment Deletion</h4>";
// Ensure that we have a comment to get the information from
if (!empty($getComment))
{
// Add the content
$this->template->content .= "<p><b>AUTHOR</b> " . $getComment['first_name'] . "<br />";
$this->template->content .= "<b>DATE</b> " . $getComment['date'] . "<br />";
$this->template->content .= "<b>COMMENT</b> " . nl2br($getComment['comment']) . "</p>";
}
// We need some hidden content
$this->template->content .= Form::hidden("id", $clean['id']);
$this->template->content .= Form::hidden("action", 'trash-confirmed');
// And to group the confirm buttons
$this->template->content .= '<div class="form-group">';
$this->template->content .= Form::input("confirm", "Yes", array("class" => "btn btn-default btn-lg", "type" => "submit"));
$this->template->content .= " ";
$this->template->content .= Form::input("confirm", "No", array("class" => "btn btn-danger btn-lg", "type" => "submit"));
$this->template->content .= "</div>";
$this->template->content .= Form::close();
break;
// Trash request
case 'edit':
// Should the form be displayed?
$display = true;
// Set the default values
$values = array(
"first_name" => $getComment['first_name'],
"email" => $getComment['email'],
"comment" => $getComment['comment']
);
// Set blank errors
$errors = array(
"first_name" => array(
"class" => "",
"message" => "",
"min" => 2,
"max" => 30
),
"email" => array(
"class" => "",
"message" => "",
"min" => 0,
"max" => 0
),
"comment" => array(
"class" => "",
"message" => "",
"min" => 6,
"max" => 1000
)
);
// Check for a submit and process the values
if (!empty($_POST['confirm']) AND $_POST['confirm'] == "Save")
{
// Assign the new values from the post
foreach($values as $key => $value)
{
// Only use the indexes we are looking for
$values[$key] = $clean[$key];
}
// Start the validation engine up
$object = Validation::factory($clean);
$object
->rule('first_name', 'not_empty')
->rule('first_name', 'min_length', array(':value', '2'))
->rule('first_name', 'max_length', array(':value', '30'))
->rule('comment', 'not_empty')
->rule('comment', 'min_length', array(':value', '6'))
->rule('comment', 'max_length', array(':value', '1000'))
->rule('email', 'not_empty')
->rule('email', 'email_domain');
// Validate the post information
$valid = $object->check();
// Valid
if ($valid == TRUE)
{
// Build the info to insert
$updateValues = array(
"id" => $clean['id'],
"first_name" => $clean['first_name'],
"email" => $clean['email'],
"comment" => $clean['comment']
);
// Attempt to update the comment
$doUpdate = $comments->edit($updateValues);
// Success
if ($doUpdate)
{
$this->template->messages["info"][] = "Changes Saved";
}
// Failure
else
{
$this->template->messages["error"][] = "Could not update comment";
}
// Hide the form as complete
$display = false;
}
// Failure
else
{
// Check that there were errors indeed
if (!empty($object->errors()))
{
// Loop through them
foreach($object->errors() as $key => $error)
{
// Custom error messages
switch (current($error))
{
case 'not_empty':
$message = "Field cannot be empty";
break;
case 'min_length':
$message = "Field needs to be at least ". $errors[$key]["min"] ." in length";
break;
case 'max_length':
$message = "Field needs to be a maximum of ". $errors[$key]["max"] ." in length";
break;
case 'email_domain':
$message = "Email Address domain does not exist, address appears to be invalid";
break;
default:
$message = "Application issue, error unknown";
break;
}
// Update the errors
$errors[$key]['class'] = "has-error";
$errors[$key]['message'] = $message;
}
}
// Set the error to indicate there is issues
$this->template->messages["error"][] = "Some errors were encountered, details below";
}
}
// Only display when not posted / validated / saved
if ($display)
{
// Edit form, set default values. overriden with post values. including error messages and states
$this->template->content = Form::open("Admin", array("class" => "form form-vertical well", "method" => "post"));
$this->template->content .= "<h4>Update Comment</h4>";
$this->template->content .= Form::hidden("id", $clean['id']);
$this->template->content .= Form::hidden("action", 'edit');
$this->template->content .= '<div class="form-group '. $errors['first_name']['class'] .'">';
$this->template->content .= Form::label("Name", NULL, array("class" => "input-label"));
$this->template->content .= Form::input("first_name", $values['first_name'], array("class" => "form-control", "type" => "text", "placeholder" => "John Doe"));
$this->template->content .= "<span class='help-block'>". $errors['first_name']['message'] ."</span></div>";
$this->template->content .= '<div class="form-group '. $errors['email']['class'] .'">';
$this->template->content .= Form::label("Email Address", NULL, array("class" => "input-label"));
$this->template->content .= Form::input("email", $values['email'], array("class" => "form-control", "type" => "text", "placeholder" => "john.doe@mail.com"));
$this->template->content .= "<span class='help-block'>". $errors['email']['message'] ."</span></div>";
$this->template->content .= '<div class="form-group '. $errors['comment']['class'] .'">';
$this->template->content .= Form::label("Comment", NULL, array("class" => "input-label"));
$this->template->content .= Form::textarea("comment", $values['comment'], array("class" => "form-control", "type" => "text", "placeholder" => "Comment"));
$this->template->content .= "<span class='help-block'>". $errors['comment']['message'] ."</span></div>";
$this->template->content .= '<div class="form-group">';
$this->template->content .= Form::input("confirm", "Save", array("class" => "btn btn-danger btn-lg", "type" => "submit"));
$this->template->content .= "</div>";
$this->template->content .= Form::close();
}
break;
// Trash confirmation
case 'trash-confirmed':
if (isset($_POST['confirm']) AND $_POST['confirm'] == "Yes")
{
// Try and delete the trash
$trash = $comments->trash($clean['id']);
// Success
if ($trash == true)
{
$this->template->messages["info"][] = "Successfully deleted comment";
}
// Failure
else
{
$this->template->messages["error"][] = "Failed to delete comment, it's most likely already deleted";
}
}
break;
// Empty default
default:
break;
}
}
}
} | drpain/walkie-talkie | application/classes/Controller/Admin.php | PHP | bsd-3-clause | 14,886 |
require 'spec_helper'
class Alchemy::Config;
end
describe Alchemy::Admin::LanguagesController do
before(:each) do
activate_authlogic
Alchemy::UserSession.create FactoryGirl.create(:admin_user)
end
describe "new" do
context "when default_language.page_layout is set" do
it "should use it as page_layout-default for the new language" do
Alchemy::Config.should_receive(:get).with(:default_language) { {'page_layout' => "new_standard"} }
get :new
assigns(:language).page_layout.should eql("new_standard")
end
end
context "when default_language or page_layout aren't configured" do
it "should fallback to 'intro'" do
get :new
assigns(:language).page_layout.should eql("intro")
end
end
end
end | masche842/alchemy_cms | spec/controllers/admin/languages_controller_spec.rb | Ruby | bsd-3-clause | 790 |
#if 0 // Disabled until updated to use current API.
// Copyright 2019 Google LLC.
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#include "fiddle/examples.h"
// HASH=4468d573f42af6f5e234be10a5453bb2
REG_FIDDLE(Image_colorSpace, 256, 256, false, 3) {
void draw(SkCanvas* canvas) {
SkPixmap pixmap;
source.peekPixels(&pixmap);
canvas->scale(.25f, .25f);
int y = 0;
for (auto gamma : { SkColorSpace::kLinear_RenderTargetGamma,
SkColorSpace::kSRGB_RenderTargetGamma } ) {
int x = 0;
sk_sp<SkColorSpace> colorSpace = SkColorSpace::MakeRGB(gamma, SkColorSpace::kSRGB_Gamut);
for (int index = 0; index < 2; ++index) {
pixmap.setColorSpace(colorSpace);
sk_sp<SkImage> image = SkImage::MakeRasterCopy(pixmap);
canvas->drawImage(image, x, y);
colorSpace = image->colorSpace()->makeColorSpin();
x += 512;
}
y += 512;
}
}
} // END FIDDLE
#endif // Disabled until updated to use current API.
| rubenvb/skia | docs/examples/Image_colorSpace.cpp | C++ | bsd-3-clause | 1,084 |
import mock
from twisted.internet import defer
from twisted.trial import unittest
from OpenSSL import crypto
import oppy.connection.connectionbuildtask as connectionbuildtask
from oppy.connection.definitions import (
LINK_CERT_TYPE,
ID_CERT_TYPE,
OPENSSL_RSA_KEY_TYPE,
)
from oppy.cell.fixedlen import NetInfoCell
from oppy.cell.varlen import AuthChallengeCell, CertsCell, VersionsCell
from oppy.cell.util import CertsCellPayloadItem
from cert_der import test_cert_der
class ConnectionBuildTaskTest(unittest.TestCase):
@mock.patch('oppy.connection.connectionmanager.ConnectionManager', autospec=True)
def setUp(self, cm):
self.cm = cm
self.cbt = connectionbuildtask.ConnectionBuildTask(cm, mock.Mock())
@mock.patch('twisted.internet.defer.Deferred', autospec=True)
def test_connectionMade(self, mock_deferred):
mock_sendVersionsCell = mock.Mock()
mock_sendVersionsCell.return_value = mock_deferred
self.cbt._sendVersionsCell = mock_sendVersionsCell
self.cbt.connectionMade()
self.assertEqual(mock_sendVersionsCell.call_count, 1)
self.assertEqual(self.cbt._tasks.addCallback.call_count, 6)
self.assertTrue(mock.call(self.cbt._processVersionsCell) in
self.cbt._tasks.addCallback.call_args_list)
self.assertTrue(mock.call(self.cbt._processCertsCell) in
self.cbt._tasks.addCallback.call_args_list)
self.assertTrue(mock.call(self.cbt._processAuthChallengeCell) in
self.cbt._tasks.addCallback.call_args_list)
self.assertTrue(mock.call(self.cbt._processNetInfoCell) in
self.cbt._tasks.addCallback.call_args_list)
self.assertTrue(mock.call(self.cbt._sendNetInfoCell) in
self.cbt._tasks.addCallback.call_args_list)
self.assertTrue(mock.call(self.cbt._connectionSucceeded) in
self.cbt._tasks.addCallback.call_args_list)
self.cbt._tasks.addErrback.assert_called_once_with(
self.cbt._connectionFailed)
def test_connectionMade_send_versions_fail(self):
self.cbt._sendVersionsCell = mock.Mock()
self.cbt._sendVersionsCell.side_effect = Exception
self.cbt._connectionFailed = mock.Mock()
self.cbt._connectionSucceeded = mock.Mock()
self.cbt.connectionMade()
self.assertEqual(self.cbt._connectionFailed.call_count, 1)
self.assertEqual(self.cbt._connectionSucceeded.call_count, 0)
def test_connectionMade_callback_fail(self):
d = defer.Deferred()
self.cbt._sendVersionsCell = mock.Mock()
self.cbt._sendVersionsCell.return_value = d
self.cbt._processVersionsCell = mock.Mock()
self.cbt._processVersionsCell.return_value = 'test'
self.cbt._processCertsCell = mock.Mock()
self.cbt._processCertsCell.return_value = 'test'
self.cbt._processAuthChallengeCell = mock.Mock()
self.cbt._processAuthChallengeCell.side_effect = Exception
self.cbt._processNetInfoCell = mock.Mock()
self.cbt._sendNetInfoCell = mock.Mock()
self.cbt._connectionSucceeded = mock.Mock()
self.cbt._connectionFailed = mock.Mock()
self.cbt.connectionMade()
d.callback('test')
self.assertEqual(self.cbt._connectionFailed.call_count, 1)
self.assertEqual(self.cbt._connectionSucceeded.call_count, 0)
def test_connectionLost_not_failed_with_current_task(self):
self.cbt._current_task = mock.Mock()
self.cbt._current_task.errback = mock.Mock()
self.cbt._connectionFailed = mock.Mock()
self.cbt.connectionLost(mock.Mock())
self.assertTrue(self.cbt._failed)
self.assertEqual(self.cbt._connectionFailed.call_count, 0)
self.assertEqual(self.cbt._current_task.errback.call_count, 1)
def test_connectionLost_not_failed_no_current_task(self):
self.cbt._current_task = None
self.cbt._connectionFailed = mock.Mock()
self.cbt.connectionLost(mock.Mock())
self.assertTrue(self.cbt._failed)
self.assertEqual(self.cbt._connectionFailed.call_count, 1)
def test_connectionLost_failed(self):
self.cbt._failed = True
self.cbt._current_task = mock.Mock()
self.cbt._current_task.errback = mock.Mock()
self.cbt._connectionFailed = mock.Mock()
self.cbt.connectionLost(mock.Mock())
self.assertTrue(self.cbt._failed)
self.assertEqual(self.cbt._connectionFailed.call_count, 0)
self.assertEqual(self.cbt._current_task.errback.call_count, 0)
# TODO: test dataReceived(). blocked by fixing cell parsing code.
def test_recvCell(self):
self.cbt._read_queue = mock.Mock()
self.cbt._read_queue.get = mock.Mock()
ret = mock.Mock()
self.cbt._read_queue.get.return_value = ret
r = self.cbt._recvCell()
self.assertEqual(r, ret)
self.assertEqual(ret, self.cbt._current_task)
@mock.patch('oppy.connection.connectionbuildtask.VersionsCell',
autospec=True)
def test_sendVersionsCell(self, mock_versions):
mock_cell = mock.Mock()
mock_bytes = mock.Mock()
mock_cell.getBytes.return_value = mock_bytes
mock_versions.make.return_value = mock_cell
self.cbt.transport = mock.Mock()
self.cbt.transport.write = mock.Mock()
self.cbt._recvCell = mock.Mock()
ret = mock.Mock()
self.cbt._recvCell.return_value = ret
r = self.cbt._sendVersionsCell()
self.cbt.transport.write.assert_called_once_with(mock_bytes)
self.assertEqual(r, ret)
@mock.patch('oppy.connection.connectionbuildtask._connectionSupportsHandshake')
def test_processVersionsCell(self, csh):
csh.return_value = True
cell = VersionsCell.make([3])
self.cbt.transport = mock.Mock()
self.cbt.transport.getPeerCertificate = mock.Mock()
self.cbt.transport.getPeerCertificate.return_value = 'test'
self.cbt._recvCell = mock.Mock()
self.cbt._recvCell.return_value = 't'
self.assertEqual(self.cbt._processVersionsCell(cell), 't')
self.assertEqual(self.cbt._connection_cert, 'test')
self.assertEqual(self.cbt._link_protocol, 3)
self.assertEqual(self.cbt._recvCell.call_count, 1)
def test_processVersionsCell_wrong_cell_type(self):
cell = NetInfoCell.make(0, '127.0.0.1', ['127.0.0.1'])
self.assertRaises(TypeError,
self.cbt._processVersionsCell,
cell)
@mock.patch('oppy.connection.connectionbuildtask._connectionSupportsHandshake')
def test_processVersionsCell_unsupported_handshake(self, csh):
self.cbt.transport = mock.Mock()
self.cbt.transport.getPeerCertificate = mock.Mock()
self.cbt.transport.getPeerCertificate.return_value = 'test'
csh.return_value = False
cell = VersionsCell.make([3])
self.assertRaises(ValueError,
self.cbt._processVersionsCell,
cell)
@mock.patch('oppy.connection.connectionbuildtask._connectionSupportsHandshake')
def test_processVersionsCell_no_versions_in_common(self, csh):
self.cbt.transport = mock.Mock()
self.cbt.transport.getPeerCertificate = mock.Mock()
self.cbt.transport.getPeerCertificate.return_value = 'test'
csh.return_value = True
cell = VersionsCell(None, [2])
self.assertRaises(ValueError,
self.cbt._processVersionsCell,
cell)
@mock.patch('oppy.connection.connectionbuildtask._getCertsFromCell',
return_value=(mock.Mock(), mock.Mock()))
@mock.patch('oppy.connection.connectionbuildtask._certsHaveValidTime',
return_value=True)
@mock.patch('oppy.connection.connectionbuildtask._ASN1KeysEqual',
return_value=True)
@mock.patch('oppy.connection.connectionbuildtask._isRSA1024BitKey',
return_value=True)
@mock.patch('oppy.crypto.util.verifyCertSig', return_value=True)
def test_processCertsCell(self, gcfc, chvt, ake, irbk, crypto):
self.cbt._connection_cert = mock.Mock()
self.cbt._recvCell = mock.Mock()
self.cbt._recvCell.return_value = 'test'
cell = CertsCell(None)
self.assertEqual(self.cbt._processCertsCell(cell), 'test')
self.assertEqual(self.cbt._recvCell.call_count, 1)
def test_processCertsCell_wrong_cell_type(self):
cell = NetInfoCell.make(0, '127.0.0.1', ['127.0.0.1'])
self.assertRaises(TypeError,
self.cbt._processCertsCell,
cell)
@mock.patch('oppy.connection.connectionbuildtask._getCertsFromCell',
return_value=(mock.Mock(), mock.Mock()))
@mock.patch('oppy.connection.connectionbuildtask._certsHaveValidTime',
return_value=False)
def test_processCertsCell_invalid_cert_time(self, gcfc, chvt):
cell = CertsCell(None)
self.assertRaises(ValueError,
self.cbt._processCertsCell,
cell)
@mock.patch('oppy.connection.connectionbuildtask._getCertsFromCell',
return_value=(mock.Mock(), mock.Mock()))
@mock.patch('oppy.connection.connectionbuildtask._certsHaveValidTime',
return_value=True)
@mock.patch('oppy.connection.connectionbuildtask._ASN1KeysEqual',
return_value=False)
def test_processCertsCell_keys_neq(self, gcfc, chvt, ake):
self.cbt._connection_cert = mock.Mock()
cell = CertsCell(None)
self.assertRaises(ValueError,
self.cbt._processCertsCell,
cell)
@mock.patch('oppy.connection.connectionbuildtask._getCertsFromCell',
return_value=(mock.Mock(), mock.Mock()))
@mock.patch('oppy.connection.connectionbuildtask._certsHaveValidTime',
return_value=True)
@mock.patch('oppy.connection.connectionbuildtask._ASN1KeysEqual',
return_value=True)
@mock.patch('oppy.connection.connectionbuildtask._isRSA1024BitKey',
return_value=False)
def test_processCertsCell_not_RSA_1024(self, gcfc, chvt, ake, irbk):
self.cbt._connection_cert = mock.Mock()
cell = CertsCell(None)
self.assertRaises(ValueError,
self.cbt._processCertsCell,
cell)
@mock.patch('oppy.connection.connectionbuildtask._getCertsFromCell',
return_value=(mock.Mock(), mock.Mock()))
@mock.patch('oppy.connection.connectionbuildtask._certsHaveValidTime',
return_value=True)
@mock.patch('oppy.connection.connectionbuildtask._ASN1KeysEqual',
return_value=True)
@mock.patch('oppy.connection.connectionbuildtask._isRSA1024BitKey',
return_value=True)
@mock.patch('oppy.crypto.util.verifyCertSig', return_value=False)
def test_processCertsCell_cert_not_signed(self, gcfc, chvt, ake, irbk, c):
self.cbt._connection_cert = mock.Mock()
cell = CertsCell(None)
self.assertRaises(ValueError,
self.cbt._processCertsCell,
cell)
def test_processAuthChallengeCell(self):
cell = AuthChallengeCell(None)
self.cbt._recvCell = mock.Mock()
self.cbt._recvCell.return_value = 'test'
self.assertEqual(self.cbt._processAuthChallengeCell(cell), 'test')
self.assertEqual(self.cbt._recvCell.call_count, 1)
def test_processAuthChallengeCell_wrong_cell_type(self):
cell = CertsCell(None)
self.assertRaises(TypeError,
self.cbt._processAuthChallengeCell,
cell)
def test_processNetInfoCell(self):
cell = NetInfoCell.make(0, '127.0.0.1', ['127.0.0.2'])
self.assertEqual(self.cbt._processNetInfoCell(cell),
('127.0.0.1', '127.0.0.2'))
def test_processNetInfoCell_wrong_type(self):
self.assertRaises(TypeError,
self.cbt._processNetInfoCell,
CertsCell(None))
@mock.patch('oppy.connection.connectionbuildtask.NetInfoCell.getBytes',
return_value='test')
def test_sendNetInfoCell(self, cell):
self.cbt.transport = mock.Mock()
self.cbt.transport.write = mock.Mock()
self.cbt._sendNetInfoCell(('127.0.0.1', '127.0.0.2'))
self.cbt.transport.write.assert_called_once_with('test')
def test_connectionSucceeded(self):
self.cbt._connectionSucceeded(None)
self.cm.connectionTaskSucceeded.assert_called_once_with(self.cbt)
def test_connectionFailed_not_failed_yet(self):
self.cbt._failed = False
self.cbt.transport = mock.Mock()
self.cbt.transport.abortConnection = mock.Mock()
self.cbt._connectionFailed(None)
self.assertTrue(self.cbt._failed)
self.assertEqual(self.cbt.transport.abortConnection.call_count, 1)
self.assertEqual(self.cm.connectionTaskFailed.call_count, 1)
def test_connectionFailed_already_failed(self):
self.cbt._failed = True
self.cbt.transport = mock.Mock()
self.cbt.transport.abortConnection = mock.Mock()
self.cbt._connectionFailed(None)
self.assertTrue(self.cbt._failed)
self.assertEqual(self.cbt.transport.abortConnection.call_count, 0)
self.assertEqual(self.cm.connectionTaskFailed.call_count, 1)
@mock.patch('oppy.crypto.util.verifyCertSig', return_value=True)
def test_connectionSupportsHandshake_self_signed(self, _):
c = mock.Mock()
mock_issuer = mock.Mock()
mock_issuer.get_components.return_value = [('CN', None)]
mock_issuer.commonName = 'foo.net'
c.get_issuer.return_value = mock_issuer
mock_subject = mock.Mock()
mock_subject.get_components.return_value = [('CN', None)]
mock_subject.commonName = 'bar.net'
c.get_subject.return_value = mock_subject
b = mock.Mock()
c.get_pubkey.bits = mock.Mock(return_value=b)
b.bits.return_value = 1024
self.assertTrue(connectionbuildtask._connectionSupportsHandshake(c))
@mock.patch('oppy.crypto.util.verifyCertSig', return_value=False)
def test_connectionSupportsHandshake_issuer_CN(self, _):
c = mock.Mock()
mock_issuer = mock.Mock()
mock_issuer.get_components.return_value = [('XX', None)]
mock_issuer.commonName = 'foo.net'
c.get_issuer.return_value = mock_issuer
mock_subject = mock.Mock()
mock_subject.get_components.return_value = [('CN', None)]
mock_subject.commonName = 'bar.net'
c.get_subject.return_value = mock_subject
b = mock.Mock()
c.get_pubkey.bits = mock.Mock(return_value=b)
b.bits.return_value = 1024
self.assertTrue(connectionbuildtask._connectionSupportsHandshake(c))
@mock.patch('oppy.crypto.util.verifyCertSig', return_value=False)
def test_connectionSupportsHandshake_subject_CN(self, c):
c = mock.Mock()
mock_issuer = mock.Mock()
mock_issuer.get_components.return_value = [('CN', None)]
mock_issuer.commonName = 'foo.net'
c.get_issuer.return_value = mock_issuer
mock_subject = mock.Mock()
mock_subject.get_components.return_value = [('XX', None)]
mock_subject.commonName = 'bar.net'
c.get_subject.return_value = mock_subject
b = mock.Mock()
c.get_pubkey.bits = mock.Mock(return_value=b)
b.bits.return_value = 1024
self.assertTrue(connectionbuildtask._connectionSupportsHandshake(c))
@mock.patch('oppy.crypto.util.verifyCertSig', return_value=False)
def test_connectionSupportsHandshake_issuer_net(self, c):
c = mock.Mock()
mock_issuer = mock.Mock()
mock_issuer.get_components.return_value = [('CN', None)]
mock_issuer.commonName = 'foo.com'
c.get_issuer.return_value = mock_issuer
mock_subject = mock.Mock()
mock_subject.get_components.return_value = [('CN', None)]
mock_subject.commonName = 'bar.net'
c.get_subject.return_value = mock_subject
b = mock.Mock()
c.get_pubkey.bits = mock.Mock(return_value=b)
b.bits.return_value = 1024
self.assertTrue(connectionbuildtask._connectionSupportsHandshake(c))
@mock.patch('oppy.crypto.util.verifyCertSig', return_value=False)
def test_connectionSupportsHandshake_subject_net(self, c):
c = mock.Mock()
mock_issuer = mock.Mock()
mock_issuer.get_components.return_value = [('CN', None)]
mock_issuer.commonName = 'foo.net'
c.get_issuer.return_value = mock_issuer
mock_subject = mock.Mock()
mock_subject.get_components.return_value = [('CN', None)]
mock_subject.commonName = 'bar.com'
c.get_subject.return_value = mock_subject
b = mock.Mock()
c.get_pubkey.bits = mock.Mock(return_value=b)
b.bits.return_value = 1024
self.assertTrue(connectionbuildtask._connectionSupportsHandshake(c))
@mock.patch('oppy.crypto.util.verifyCertSig', return_value=False)
def test_connectionSupportsHandshake_longer_1024(self, c):
c = mock.Mock()
mock_issuer = mock.Mock()
mock_issuer.get_components.return_value = [('CN', None)]
mock_issuer.commonName = 'foo.net'
c.get_issuer.return_value = mock_issuer
mock_subject = mock.Mock()
mock_subject.get_components.return_value = [('CN', None)]
mock_subject.commonName = 'bar.net'
c.get_subject.return_value = mock_subject
b = mock.Mock()
c.get_pubkey.bits = mock.Mock(return_value=b)
b.bits.return_value = 2048
self.assertTrue(connectionbuildtask._connectionSupportsHandshake(c))
@mock.patch('oppy.crypto.util.verifyCertSig', return_value=False)
def test_connectionSupportsHandshake_all_fail(self, c):
c = mock.Mock()
mock_issuer = mock.Mock()
mock_issuer.get_components.return_value = [('CN', None)]
mock_issuer.commonName = 'foo.net'
c.get_issuer.return_value = mock_issuer
mock_subject = mock.Mock()
mock_subject.get_components.return_value = [('CN', None)]
mock_subject.commonName = 'bar.net'
c.get_subject.return_value = mock_subject
b = mock.Mock()
c.get_pubkey.bits = mock.Mock(return_value=b)
b.bits.return_value = 1024
self.assertTrue(connectionbuildtask._connectionSupportsHandshake(c))
def test_getCertsFromCell(self):
lc = test_cert_der
link_cert = CertsCellPayloadItem(LINK_CERT_TYPE, len(lc), lc)
ic = test_cert_der
id_cert = CertsCellPayloadItem(ID_CERT_TYPE, len(ic), ic)
cell = CertsCell.make(0, [link_cert, id_cert])
res1 = crypto.load_certificate(crypto.FILETYPE_ASN1, lc)
res2 = crypto.load_certificate(crypto.FILETYPE_ASN1, ic)
l, i = connectionbuildtask._getCertsFromCell(cell)
self.assertEqual(crypto.dump_certificate(crypto.FILETYPE_ASN1, l), lc)
self.assertEqual(crypto.dump_certificate(crypto.FILETYPE_ASN1, i), ic)
def test_getCertsFromCell_invalid_count(self):
lc = test_cert_der
link_cert = CertsCellPayloadItem(LINK_CERT_TYPE, len(lc), lc)
cell = CertsCell.make(0, [link_cert])
self.assertRaises(ValueError,
connectionbuildtask._getCertsFromCell,
cell)
def test_getCertsFromCell_malformed_cert(self):
lc = test_cert_der
link_cert = CertsCellPayloadItem(LINK_CERT_TYPE, len(lc), lc)
ic = test_cert_der[:len(test_cert_der)-1]
id_cert = CertsCellPayloadItem(ID_CERT_TYPE, len(ic), ic)
cell = CertsCell.make(0, [link_cert, id_cert])
self.assertRaises(ValueError,
connectionbuildtask._getCertsFromCell,
cell)
def test_getCertsFromCell_invalid_cert_type(self):
lc = test_cert_der
link_cert = CertsCellPayloadItem(LINK_CERT_TYPE, len(lc), lc)
ic = test_cert_der
id_cert = CertsCellPayloadItem(LINK_CERT_TYPE, len(ic), ic)
cell = CertsCell.make(0, [link_cert, id_cert])
self.assertRaises(ValueError,
connectionbuildtask._getCertsFromCell,
cell)
@mock.patch('oppy.crypto.util.validCertTime', return_value=True)
def test_certsHaveValidTime_fail(self, vct):
mock_cert = mock.Mock()
certs = [mock_cert]
self.assertTrue(connectionbuildtask._certsHaveValidTime(certs))
vct.assert_called_once_with(mock_cert)
@mock.patch('oppy.crypto.util.validCertTime', return_value=False)
def test_certsHaveValidTime_fail(self, vct):
mock_cert = mock.Mock()
certs = [mock_cert]
self.assertFalse(connectionbuildtask._certsHaveValidTime(certs))
vct.assert_called_once_with(mock_cert)
@mock.patch('oppy.crypto.util.constantStrEqual', return_value=True)
@mock.patch('OpenSSL.crypto.dump_privatekey', autospec=True)
def test_ASN1KeysEqual(self, dpk, cse):
mock_asn1_key = mock.Mock()
self.assertTrue(connectionbuildtask._ASN1KeysEqual(mock_asn1_key,
mock_asn1_key))
self.assertEqual(cse.call_count, 1)
@mock.patch('oppy.crypto.util.constantStrEqual', return_value=False)
@mock.patch('OpenSSL.crypto.dump_privatekey', autospec=True)
def test_ASN1KeysEqual_neq(self, dpk, cse):
mock_asn1_key = mock.Mock()
self.assertFalse(connectionbuildtask._ASN1KeysEqual(mock_asn1_key,
mock_asn1_key))
self.assertEqual(cse.call_count, 1)
def test_isRSA1024BitKey(self):
key = mock.Mock()
key.type.return_value = OPENSSL_RSA_KEY_TYPE
key.bits.return_value = 1024
self.assertTrue(connectionbuildtask._isRSA1024BitKey(key))
def test_isRSA1024BitKey_not_RSA(self):
key = mock.Mock()
key.type.return_value = OPENSSL_RSA_KEY_TYPE - 1
key.bits.return_value = 1024
self.assertFalse(connectionbuildtask._isRSA1024BitKey(key))
def test_isRSA1024BitKey_not_1024(self):
key = mock.Mock()
key.type.return_value = OPENSSL_RSA_KEY_TYPE
key.bits.return_value = 2048
self.assertFalse(connectionbuildtask._isRSA1024BitKey(key))
| nskinkel/oppy | oppy/tests/unit/connection/test_connectionbuildtask.py | Python | bsd-3-clause | 22,953 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.h"
#include <algorithm>
#include <functional>
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/i18n/rtl.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/utf_string_conversions.h"
#include "base/supports_user_data.h"
#include "base/threading/thread.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/download/download_danger_prompt.h"
#include "chrome/browser/download/download_history.h"
#include "chrome/browser/download/download_item_model.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/download/download_query.h"
#include "chrome/browser/download/download_service.h"
#include "chrome/browser/download/download_service_factory.h"
#include "chrome/browser/download/drag_download_item.h"
#include "chrome/browser/platform_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/fileicon_source.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_item.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/url_data_source.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "net/base/filename_util.h"
#include "ui/base/l10n/time_format.h"
#include "ui/gfx/image/image.h"
using base::UserMetricsAction;
using content::BrowserThread;
namespace {
enum DownloadsDOMEvent {
DOWNLOADS_DOM_EVENT_GET_DOWNLOADS = 0,
DOWNLOADS_DOM_EVENT_OPEN_FILE = 1,
DOWNLOADS_DOM_EVENT_DRAG = 2,
DOWNLOADS_DOM_EVENT_SAVE_DANGEROUS = 3,
DOWNLOADS_DOM_EVENT_DISCARD_DANGEROUS = 4,
DOWNLOADS_DOM_EVENT_SHOW = 5,
DOWNLOADS_DOM_EVENT_PAUSE = 6,
DOWNLOADS_DOM_EVENT_REMOVE = 7,
DOWNLOADS_DOM_EVENT_CANCEL = 8,
DOWNLOADS_DOM_EVENT_CLEAR_ALL = 9,
DOWNLOADS_DOM_EVENT_OPEN_FOLDER = 10,
DOWNLOADS_DOM_EVENT_RESUME = 11,
DOWNLOADS_DOM_EVENT_MAX
};
void CountDownloadsDOMEvents(DownloadsDOMEvent event) {
UMA_HISTOGRAM_ENUMERATION("Download.DOMEvent",
event,
DOWNLOADS_DOM_EVENT_MAX);
}
} // namespace
MdDownloadsDOMHandler::MdDownloadsDOMHandler(
content::DownloadManager* download_manager, content::WebUI* web_ui)
: list_tracker_(download_manager, web_ui),
weak_ptr_factory_(this) {
// Create our fileicon data source.
Profile* profile = Profile::FromBrowserContext(
download_manager->GetBrowserContext());
content::URLDataSource::Add(profile, new FileIconSource());
}
MdDownloadsDOMHandler::~MdDownloadsDOMHandler() {
FinalizeRemovals();
}
// MdDownloadsDOMHandler, public: ---------------------------------------------
void MdDownloadsDOMHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback("getDownloads",
base::Bind(&MdDownloadsDOMHandler::HandleGetDownloads,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback("openFile",
base::Bind(&MdDownloadsDOMHandler::HandleOpenFile,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback("drag",
base::Bind(&MdDownloadsDOMHandler::HandleDrag,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback("saveDangerous",
base::Bind(&MdDownloadsDOMHandler::HandleSaveDangerous,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback("discardDangerous",
base::Bind(&MdDownloadsDOMHandler::HandleDiscardDangerous,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback("show",
base::Bind(&MdDownloadsDOMHandler::HandleShow,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback("pause",
base::Bind(&MdDownloadsDOMHandler::HandlePause,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback("resume",
base::Bind(&MdDownloadsDOMHandler::HandleResume,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback("remove",
base::Bind(&MdDownloadsDOMHandler::HandleRemove,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback("undo",
base::Bind(&MdDownloadsDOMHandler::HandleUndo,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback("cancel",
base::Bind(&MdDownloadsDOMHandler::HandleCancel,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback("clearAll",
base::Bind(&MdDownloadsDOMHandler::HandleClearAll,
weak_ptr_factory_.GetWeakPtr()));
web_ui()->RegisterMessageCallback("openDownloadsFolder",
base::Bind(&MdDownloadsDOMHandler::HandleOpenDownloadsFolder,
weak_ptr_factory_.GetWeakPtr()));
}
void MdDownloadsDOMHandler::RenderViewReused(
content::RenderViewHost* render_view_host) {
list_tracker_.Stop();
}
void MdDownloadsDOMHandler::HandleGetDownloads(const base::ListValue* args) {
CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_GET_DOWNLOADS);
bool terms_changed = list_tracker_.SetSearchTerms(*args);
if (terms_changed)
list_tracker_.CallClearAll();
list_tracker_.Start();
}
void MdDownloadsDOMHandler::HandleOpenFile(const base::ListValue* args) {
CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_OPEN_FILE);
content::DownloadItem* file = GetDownloadByValue(args);
if (file)
file->OpenDownload();
}
void MdDownloadsDOMHandler::HandleDrag(const base::ListValue* args) {
CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_DRAG);
content::DownloadItem* file = GetDownloadByValue(args);
if (!file)
return;
content::WebContents* web_contents = GetWebUIWebContents();
// |web_contents| is only NULL in the test.
if (!web_contents)
return;
if (file->GetState() != content::DownloadItem::COMPLETE)
return;
gfx::Image* icon = g_browser_process->icon_manager()->LookupIconFromFilepath(
file->GetTargetFilePath(), IconLoader::NORMAL);
gfx::NativeView view = web_contents->GetNativeView();
{
// Enable nested tasks during DnD, while |DragDownload()| blocks.
base::MessageLoop::ScopedNestableTaskAllower allow(
base::MessageLoop::current());
DragDownloadItem(file, icon, view);
}
}
void MdDownloadsDOMHandler::HandleSaveDangerous(const base::ListValue* args) {
CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_SAVE_DANGEROUS);
content::DownloadItem* file = GetDownloadByValue(args);
if (file)
ShowDangerPrompt(file);
}
void MdDownloadsDOMHandler::HandleDiscardDangerous(
const base::ListValue* args) {
CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_DISCARD_DANGEROUS);
content::DownloadItem* file = GetDownloadByValue(args);
if (file)
file->Remove();
}
void MdDownloadsDOMHandler::HandleShow(const base::ListValue* args) {
CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_SHOW);
content::DownloadItem* file = GetDownloadByValue(args);
if (file)
file->ShowDownloadInShell();
}
void MdDownloadsDOMHandler::HandlePause(const base::ListValue* args) {
CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_PAUSE);
content::DownloadItem* file = GetDownloadByValue(args);
if (file)
file->Pause();
}
void MdDownloadsDOMHandler::HandleResume(const base::ListValue* args) {
CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_RESUME);
content::DownloadItem* file = GetDownloadByValue(args);
if (file)
file->Resume();
}
void MdDownloadsDOMHandler::HandleRemove(const base::ListValue* args) {
if (!IsDeletingHistoryAllowed())
return;
CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_REMOVE);
content::DownloadItem* file = GetDownloadByValue(args);
if (!file)
return;
DownloadVector downloads;
downloads.push_back(file);
RemoveDownloads(downloads);
}
void MdDownloadsDOMHandler::HandleUndo(const base::ListValue* args) {
// TODO(dbeam): handle more than removed downloads someday?
if (removals_.empty())
return;
const IdSet last_removed_ids = removals_.back();
removals_.pop_back();
for (auto id : last_removed_ids) {
content::DownloadItem* download = GetDownloadById(id);
if (!download)
continue;
DownloadItemModel model(download);
model.SetShouldShowInShelf(true);
model.SetIsBeingRevived(true);
download->UpdateObservers();
model.SetIsBeingRevived(false);
}
}
void MdDownloadsDOMHandler::HandleCancel(const base::ListValue* args) {
CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_CANCEL);
content::DownloadItem* file = GetDownloadByValue(args);
if (file)
file->Cancel(true);
}
void MdDownloadsDOMHandler::HandleClearAll(const base::ListValue* args) {
if (!IsDeletingHistoryAllowed()) {
// This should only be reached during tests.
return;
}
CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_CLEAR_ALL);
list_tracker_.CallClearAll();
list_tracker_.Stop();
DownloadVector downloads;
if (GetMainNotifierManager())
GetMainNotifierManager()->GetAllDownloads(&downloads);
if (GetOriginalNotifierManager())
GetOriginalNotifierManager()->GetAllDownloads(&downloads);
RemoveDownloads(downloads);
list_tracker_.Start();
}
void MdDownloadsDOMHandler::RemoveDownloads(const DownloadVector& to_remove) {
IdSet ids;
for (auto* download : to_remove) {
DownloadItemModel item_model(download);
if (!item_model.ShouldShowInShelf() ||
download->GetState() == content::DownloadItem::IN_PROGRESS) {
continue;
}
item_model.SetShouldShowInShelf(false);
ids.insert(download->GetId());
download->UpdateObservers();
}
if (!ids.empty())
removals_.push_back(ids);
}
void MdDownloadsDOMHandler::HandleOpenDownloadsFolder(
const base::ListValue* args) {
CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_OPEN_FOLDER);
content::DownloadManager* manager = GetMainNotifierManager();
if (manager) {
platform_util::OpenItem(
Profile::FromBrowserContext(manager->GetBrowserContext()),
DownloadPrefs::FromDownloadManager(manager)->DownloadPath(),
platform_util::OPEN_FOLDER, platform_util::OpenOperationCallback());
}
}
// MdDownloadsDOMHandler, private: --------------------------------------------
content::DownloadManager* MdDownloadsDOMHandler::GetMainNotifierManager()
const {
return list_tracker_.GetMainNotifierManager();
}
content::DownloadManager* MdDownloadsDOMHandler::GetOriginalNotifierManager()
const {
return list_tracker_.GetOriginalNotifierManager();
}
void MdDownloadsDOMHandler::FinalizeRemovals() {
while (!removals_.empty()) {
const IdSet remove = removals_.back();
removals_.pop_back();
for (const auto id : remove) {
content::DownloadItem* download = GetDownloadById(id);
if (download)
download->Remove();
}
}
}
void MdDownloadsDOMHandler::ShowDangerPrompt(
content::DownloadItem* dangerous_item) {
DownloadDangerPrompt* danger_prompt = DownloadDangerPrompt::Create(
dangerous_item,
GetWebUIWebContents(),
false,
base::Bind(&MdDownloadsDOMHandler::DangerPromptDone,
weak_ptr_factory_.GetWeakPtr(), dangerous_item->GetId()));
// danger_prompt will delete itself.
DCHECK(danger_prompt);
}
void MdDownloadsDOMHandler::DangerPromptDone(
int download_id, DownloadDangerPrompt::Action action) {
if (action != DownloadDangerPrompt::ACCEPT)
return;
content::DownloadItem* item = NULL;
if (GetMainNotifierManager())
item = GetMainNotifierManager()->GetDownload(download_id);
if (!item && GetOriginalNotifierManager())
item = GetOriginalNotifierManager()->GetDownload(download_id);
if (!item || item->IsDone())
return;
CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_SAVE_DANGEROUS);
item->ValidateDangerousDownload();
}
bool MdDownloadsDOMHandler::IsDeletingHistoryAllowed() {
content::DownloadManager* manager = GetMainNotifierManager();
return manager &&
Profile::FromBrowserContext(manager->GetBrowserContext())->
GetPrefs()->GetBoolean(prefs::kAllowDeletingBrowserHistory);
}
content::DownloadItem* MdDownloadsDOMHandler::GetDownloadByValue(
const base::ListValue* args) {
std::string download_id;
if (!args->GetString(0, &download_id)) {
NOTREACHED();
return nullptr;
}
uint64 id;
if (!base::StringToUint64(download_id, &id)) {
NOTREACHED();
return nullptr;
}
return GetDownloadById(static_cast<uint32>(id));
}
content::DownloadItem* MdDownloadsDOMHandler::GetDownloadById(uint32 id) {
content::DownloadItem* item = NULL;
if (GetMainNotifierManager())
item = GetMainNotifierManager()->GetDownload(id);
if (!item && GetOriginalNotifierManager())
item = GetOriginalNotifierManager()->GetDownload(id);
return item;
}
content::WebContents* MdDownloadsDOMHandler::GetWebUIWebContents() {
return web_ui()->GetWebContents();
}
| Workday/OpenFrame | chrome/browser/ui/webui/md_downloads/md_downloads_dom_handler.cc | C++ | bsd-3-clause | 13,408 |
<?php
$this->breadcrumbs=array(
'News'=>array('index'),
'Manage',
);
$this->menu=array(
array('label'=>'List News','url'=>array('index')),
array('label'=>'Create News','url'=>array('create')),
);
Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
$('.search-form').toggle();
return false;
});
$('.search-form form').submit(function(){
$.fn.yiiGridView.update('news-grid', {
data: $(this).serialize()
});
return false;
});
");
?>
<h1>Manage News</h1>
<p>
You may optionally enter a comparison operator (<b><</b>, <b><=</b>, <b>></b>, <b>>=</b>, <b><></b>
or <b>=</b>) at the beginning of each of your search values to specify how the comparison should be done.
</p>
<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button btn')); ?>
<div class="search-form" style="display:none">
<?php $this->renderPartial('_search',array(
'model'=>$model,
)); ?>
</div><!-- search-form -->
<?php $this->widget('bootstrap.widgets.TbGridView',array(
'id'=>'news-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'title',
'content',
'time_created',
'url_name',
array(
'class'=>'bootstrap.widgets.TbButtonColumn',
),
),
)); ?>
| Arsen007/viven-gallery-yii | application/views/news/admin.php | PHP | bsd-3-clause | 1,257 |
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel app\modules\risk\models\ClinicsSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Clinics';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="clinics-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Clinics', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'name',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
| inamjung/Yiiproject | modules/risk/views/clinics/index.php | PHP | bsd-3-clause | 827 |
package com.ra4king.opengl.superbible.osb5.chapter2.example3;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import java.nio.FloatBuffer;
import org.lwjgl.BufferUtils;
import com.ra4king.opengl.GLProgram;
import com.ra4king.opengl.util.ShaderProgram;
/**
* "Bounce" demo -- even more trivial than "Move".
*/
public class Example2_3 extends GLProgram {
private ShaderProgram program;
private int vbo;
private float blockSize = 0.1f;
private float[] block = new float[] {
-blockSize - 0.5f, -blockSize, 0.0f, 1.0f,
blockSize - 0.5f, -blockSize, 0.0f, 1.0f,
blockSize - 0.5f, blockSize, 0.0f, 1.0f,
-blockSize - 0.5f, blockSize, 0.0f, 1.0f,
};
private FloatBuffer verts = BufferUtils.createFloatBuffer(16);
private float stepSize = 0.005f;
private float dx = stepSize;
private float dy = stepSize;
public static void main(String[] args) {
new Example2_3().run(3, 0);
}
public Example2_3() {
super("Bounce", 500, 500, false);
}
@Override
public void init() {
glClearColor(0, 0, 1, 0); // Blue
program = new ShaderProgram(readFromFile("example2.3.vert"), readFromFile("example2.3.frag"));
verts.put(block).flip();
vbo = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, verts, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
@Override
public void update(long deltaTime) {
// Don't look here for OSB5's stupidly obfuscated calculations, this here is as simple as it gets
float left = block[0];
float right = block[4];
float bottom = block[1];
float top = block[9];
if(left < -1.0f || right > 1.0f)
dx = -dx;
if(bottom < -1.0f || top > 1.0f)
dy = -dy;
block[0] += dx;
block[1] += dy;
block[4] += dx;
block[5] += dy;
block[8] += dx;
block[9] += dy;
block[12] += dx;
block[13] += dy;
glBindBuffer(GL_ARRAY_BUFFER, vbo);
verts.rewind();
verts.put(block).flip();
glBufferSubData(GL_ARRAY_BUFFER, 0, verts);
}
@Override
public void render() {
glClear(GL_COLOR_BUFFER_BIT);
glEnableClientState(GL_VERTEX_ARRAY);
program.begin();
glUniform4f(program.getUniformLocation("color"), 1, 0, 0, 1); // red
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, false, 0, 0);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glUseProgram(0);
glDisableClientState(GL_VERTEX_ARRAY);
}
}
| ra4king/LWJGL-OpenGL-Tutorials | src/com/ra4king/opengl/superbible/osb5/chapter2/example3/Example2_3.java | Java | bsd-3-clause | 2,595 |
from django.contrib.localflavor.in_.forms import (INZipCodeField,
INStateField, INStateSelect, INPhoneNumberField)
from utils import LocalFlavorTestCase
class INLocalFlavorTests(LocalFlavorTestCase):
def test_INPhoneNumberField(self):
error_format = [u'Phone numbers must be in 02X-8X or 03X-7X or 04X-6X format.']
valid = {
'0423-2443667': '0423-2443667',
'0423 2443667': '0423 2443667',
'04236-244366': '04236-244366',
'040-24436678': '040-24436678',
}
invalid = {
'04-2443667': error_format,
'423-2443667': error_format,
'0423-9442667': error_format,
'0423-0443667': error_format,
'0423-244366': error_format,
'04232442667': error_format,
'0423DJANGO': error_format,
}
self.assertFieldOutput(INPhoneNumberField, valid, invalid)
def test_INPStateSelect(self):
f = INStateSelect()
out = u'''<select name="state">
<option value="KA">Karnataka</option>
<option value="AP" selected="selected">Andhra Pradesh</option>
<option value="KL">Kerala</option>
<option value="TN">Tamil Nadu</option>
<option value="MH">Maharashtra</option>
<option value="UP">Uttar Pradesh</option>
<option value="GA">Goa</option>
<option value="GJ">Gujarat</option>
<option value="RJ">Rajasthan</option>
<option value="HP">Himachal Pradesh</option>
<option value="JK">Jammu and Kashmir</option>
<option value="AR">Arunachal Pradesh</option>
<option value="AS">Assam</option>
<option value="BR">Bihar</option>
<option value="CG">Chattisgarh</option>
<option value="HR">Haryana</option>
<option value="JH">Jharkhand</option>
<option value="MP">Madhya Pradesh</option>
<option value="MN">Manipur</option>
<option value="ML">Meghalaya</option>
<option value="MZ">Mizoram</option>
<option value="NL">Nagaland</option>
<option value="OR">Orissa</option>
<option value="PB">Punjab</option>
<option value="SK">Sikkim</option>
<option value="TR">Tripura</option>
<option value="UA">Uttarakhand</option>
<option value="WB">West Bengal</option>
<option value="AN">Andaman and Nicobar</option>
<option value="CH">Chandigarh</option>
<option value="DN">Dadra and Nagar Haveli</option>
<option value="DD">Daman and Diu</option>
<option value="DL">Delhi</option>
<option value="LD">Lakshadweep</option>
<option value="PY">Pondicherry</option>
</select>'''
self.assertEqual(f.render('state', 'AP'), out)
def test_INZipCodeField(self):
error_format = [u'Enter a zip code in the format XXXXXX or XXX XXX.']
valid = {
'360311': '360311',
'360 311': '360311',
}
invalid = {
'36 0311': error_format,
'3603111': error_format,
'360 31': error_format,
'36031': error_format,
'O2B 2R3': error_format
}
self.assertFieldOutput(INZipCodeField, valid, invalid)
def test_INStateField(self):
error_format = [u'Enter an Indian state or territory.']
valid = {
'an': 'AN',
'AN': 'AN',
'andaman and nicobar': 'AN',
'andra pradesh': 'AP',
'andrapradesh': 'AP',
'andhrapradesh': 'AP',
'ap': 'AP',
'andhra pradesh': 'AP',
'ar': 'AR',
'arunachal pradesh': 'AR',
'assam': 'AS',
'as': 'AS',
'bihar': 'BR',
'br': 'BR',
'cg': 'CG',
'chattisgarh': 'CG',
'ch': 'CH',
'chandigarh': 'CH',
'daman and diu': 'DD',
'dd': 'DD',
'dl': 'DL',
'delhi': 'DL',
'dn': 'DN',
'dadra and nagar haveli': 'DN',
'ga': 'GA',
'goa': 'GA',
'gj': 'GJ',
'gujarat': 'GJ',
'himachal pradesh': 'HP',
'hp': 'HP',
'hr': 'HR',
'haryana': 'HR',
'jharkhand': 'JH',
'jh': 'JH',
'jammu and kashmir': 'JK',
'jk': 'JK',
'karnataka': 'KA',
'karnatka': 'KA',
'ka': 'KA',
'kerala': 'KL',
'kl': 'KL',
'ld': 'LD',
'lakshadweep': 'LD',
'maharastra': 'MH',
'mh': 'MH',
'maharashtra': 'MH',
'meghalaya': 'ML',
'ml': 'ML',
'mn': 'MN',
'manipur': 'MN',
'madhya pradesh': 'MP',
'mp': 'MP',
'mizoram': 'MZ',
'mizo': 'MZ',
'mz': 'MZ',
'nl': 'NL',
'nagaland': 'NL',
'orissa': 'OR',
'odisa': 'OR',
'orisa': 'OR',
'or': 'OR',
'pb': 'PB',
'punjab': 'PB',
'py': 'PY',
'pondicherry': 'PY',
'rajasthan': 'RJ',
'rajastan': 'RJ',
'rj': 'RJ',
'sikkim': 'SK',
'sk': 'SK',
'tamil nadu': 'TN',
'tn': 'TN',
'tamilnadu': 'TN',
'tamilnad': 'TN',
'tr': 'TR',
'tripura': 'TR',
'ua': 'UA',
'uttarakhand': 'UA',
'up': 'UP',
'uttar pradesh': 'UP',
'westbengal': 'WB',
'bengal': 'WB',
'wb': 'WB',
'west bengal': 'WB'
}
invalid = {
'florida': error_format,
'FL': error_format,
}
self.assertFieldOutput(INStateField, valid, invalid)
| disqus/django-old | tests/regressiontests/forms/localflavor/in_.py | Python | bsd-3-clause | 5,631 |
<?php
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\SchoolConditions;
/**
* SchoolConditionsSearch represents the model behind the search form about `backend\models\SchoolConditions`.
*/
class SchoolConditionsSearch extends SchoolConditions
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['school_condition_id'], 'integer'],
[['school_condition_title', 'school_condition_text'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = SchoolConditions::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'school_condition_id' => $this->school_condition_id,
]);
$query->andFilterWhere(['like', 'school_condition_title', $this->school_condition_title])
->andFilterWhere(['like', 'school_condition_text', $this->school_condition_text]);
return $dataProvider;
}
}
| robert-mill/cover | backend/models/SchoolConditionsSearch.php | PHP | bsd-3-clause | 1,744 |
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\models\CalendarEvent */
$this->title = Yii::t('app', 'Update {modelClass}: ', [
'modelClass' => 'Calendar Event',
]) . ' ' . $model->name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Calendar Events'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->name, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = Yii::t('app', 'Update');
?>
<div class="calendar-event-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| EQ-Port/site-2.0 | backend/views/calendar-event/update.php | PHP | bsd-3-clause | 649 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/toolbar/toolbar_view.h"
#include <algorithm>
#include "base/command_line.h"
#include "base/i18n/number_formatting.h"
#include "base/prefs/pref_service.h"
#include "base/strings/utf_string_conversions.h"
#include "base/trace_event/trace_event.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/command_updater.h"
#include "chrome/browser/extensions/extension_commands_global_registry.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_command_controller.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h"
#include "chrome/browser/ui/browser_instant_controller.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/global_error/global_error_service.h"
#include "chrome/browser/ui/global_error/global_error_service_factory.h"
#include "chrome/browser/ui/omnibox/omnibox_view.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/toolbar/wrench_menu_model.h"
#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/extensions/extension_popup.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/location_bar/page_action_image_view.h"
#include "chrome/browser/ui/views/location_bar/page_action_with_badge_view.h"
#include "chrome/browser/ui/views/location_bar/star_view.h"
#include "chrome/browser/ui/views/location_bar/translate_icon_view.h"
#include "chrome/browser/ui/views/outdated_upgrade_bubble_view.h"
#include "chrome/browser/ui/views/toolbar/back_button.h"
#include "chrome/browser/ui/views/toolbar/browser_actions_container.h"
#include "chrome/browser/ui/views/toolbar/home_button.h"
#include "chrome/browser/ui/views/toolbar/reload_button.h"
#include "chrome/browser/ui/views/toolbar/toolbar_button.h"
#include "chrome/browser/ui/views/toolbar/wrench_menu.h"
#include "chrome/browser/ui/views/toolbar/wrench_toolbar_button.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/grit/chromium_strings.h"
#include "chrome/grit/generated_resources.h"
#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "grit/theme_resources.h"
#include "ui/accessibility/ax_view_state.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/theme_provider.h"
#include "ui/base/window_open_disposition.h"
#include "ui/compositor/layer.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/image/canvas_image_source.h"
#include "ui/keyboard/keyboard_controller.h"
#include "ui/native_theme/native_theme_aura.h"
#include "ui/views/controls/menu/menu_listener.h"
#include "ui/views/focus/view_storage.h"
#include "ui/views/view_targeter.h"
#include "ui/views/widget/tooltip_manager.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/non_client_view.h"
#if defined(OS_WIN)
#include "chrome/browser/recovery/recovery_install_global_error_factory.h"
#include "chrome/browser/ui/views/conflicting_module_view_win.h"
#include "chrome/browser/ui/views/critical_notification_bubble_view.h"
#endif
#if !defined(OS_CHROMEOS)
#include "chrome/browser/signin/signin_global_error_factory.h"
#include "chrome/browser/sync/sync_global_error_factory.h"
#endif
#if defined(USE_ASH)
#include "ash/shell.h"
#endif
using base::UserMetricsAction;
using content::WebContents;
namespace {
// The edge graphics have some built-in spacing/shadowing, so we have to adjust
// our spacing to make it match.
const int kLeftEdgeSpacing = 3;
const int kRightEdgeSpacing = 2;
// Ash doesn't use a rounded content area and its top edge has an extra shadow.
const int kContentShadowHeightAsh = 2;
// Non-ash uses a rounded content area with no shadow in the assets.
const int kContentShadowHeight = 0;
#if !defined(OS_CHROMEOS)
bool HasAshShell() {
#if defined(USE_ASH)
return ash::Shell::HasInstance();
#else
return false;
#endif // USE_ASH
}
#endif // OS_CHROMEOS
} // namespace
// static
const char ToolbarView::kViewClassName[] = "ToolbarView";
////////////////////////////////////////////////////////////////////////////////
// ToolbarView, public:
ToolbarView::ToolbarView(Browser* browser)
: back_(NULL),
forward_(NULL),
reload_(NULL),
home_(NULL),
location_bar_(NULL),
browser_actions_(NULL),
app_menu_(NULL),
browser_(browser),
badge_controller_(browser->profile(), this) {
set_id(VIEW_ID_TOOLBAR);
SetEventTargeter(
scoped_ptr<views::ViewTargeter>(new views::ViewTargeter(this)));
chrome::AddCommandObserver(browser_, IDC_BACK, this);
chrome::AddCommandObserver(browser_, IDC_FORWARD, this);
chrome::AddCommandObserver(browser_, IDC_RELOAD, this);
chrome::AddCommandObserver(browser_, IDC_HOME, this);
chrome::AddCommandObserver(browser_, IDC_LOAD_NEW_TAB_PAGE, this);
display_mode_ = DISPLAYMODE_LOCATION;
if (browser->SupportsWindowFeature(Browser::FEATURE_TABSTRIP))
display_mode_ = DISPLAYMODE_NORMAL;
if (OutdatedUpgradeBubbleView::IsAvailable()) {
registrar_.Add(this, chrome::NOTIFICATION_OUTDATED_INSTALL,
content::NotificationService::AllSources());
registrar_.Add(this, chrome::NOTIFICATION_OUTDATED_INSTALL_NO_AU,
content::NotificationService::AllSources());
}
#if defined(OS_WIN)
registrar_.Add(this, chrome::NOTIFICATION_CRITICAL_UPGRADE_INSTALLED,
content::NotificationService::AllSources());
#endif
}
ToolbarView::~ToolbarView() {
// NOTE: Don't remove the command observers here. This object gets destroyed
// after the Browser (which owns the CommandUpdater), so the CommandUpdater is
// already gone.
}
void ToolbarView::Init() {
GetWidget()->AddObserver(this);
back_ = new BackButton(this, new BackForwardMenuModel(
browser_, BackForwardMenuModel::BACKWARD_MENU));
back_->set_triggerable_event_flags(
ui::EF_LEFT_MOUSE_BUTTON | ui::EF_MIDDLE_MOUSE_BUTTON);
back_->set_tag(IDC_BACK);
back_->SetTooltipText(l10n_util::GetStringUTF16(IDS_TOOLTIP_BACK));
back_->SetAccessibleName(l10n_util::GetStringUTF16(IDS_ACCNAME_BACK));
back_->set_id(VIEW_ID_BACK_BUTTON);
back_->Init();
forward_ = new ToolbarButton(this, new BackForwardMenuModel(
browser_, BackForwardMenuModel::FORWARD_MENU));
forward_->set_triggerable_event_flags(
ui::EF_LEFT_MOUSE_BUTTON | ui::EF_MIDDLE_MOUSE_BUTTON);
forward_->set_tag(IDC_FORWARD);
forward_->SetTooltipText(l10n_util::GetStringUTF16(IDS_TOOLTIP_FORWARD));
forward_->SetAccessibleName(l10n_util::GetStringUTF16(IDS_ACCNAME_FORWARD));
forward_->set_id(VIEW_ID_FORWARD_BUTTON);
forward_->Init();
location_bar_ = new LocationBarView(
browser_, browser_->profile(),
browser_->command_controller()->command_updater(), this,
display_mode_ == DISPLAYMODE_LOCATION);
reload_ = new ReloadButton(browser_->command_controller()->command_updater());
reload_->set_triggerable_event_flags(
ui::EF_LEFT_MOUSE_BUTTON | ui::EF_MIDDLE_MOUSE_BUTTON);
reload_->set_tag(IDC_RELOAD);
reload_->SetAccessibleName(l10n_util::GetStringUTF16(IDS_ACCNAME_RELOAD));
reload_->set_id(VIEW_ID_RELOAD_BUTTON);
reload_->Init();
home_ = new HomeButton(this, browser_);
home_->set_triggerable_event_flags(
ui::EF_LEFT_MOUSE_BUTTON | ui::EF_MIDDLE_MOUSE_BUTTON);
home_->set_tag(IDC_HOME);
home_->SetTooltipText(l10n_util::GetStringUTF16(IDS_TOOLTIP_HOME));
home_->SetAccessibleName(l10n_util::GetStringUTF16(IDS_ACCNAME_HOME));
home_->set_id(VIEW_ID_HOME_BUTTON);
home_->Init();
browser_actions_ = new BrowserActionsContainer(
browser_,
NULL); // No master container for this one (it is master).
app_menu_ = new WrenchToolbarButton(this);
app_menu_->EnableCanvasFlippingForRTLUI(true);
app_menu_->SetAccessibleName(l10n_util::GetStringUTF16(IDS_ACCNAME_APP));
app_menu_->SetTooltipText(l10n_util::GetStringUTF16(IDS_APPMENU_TOOLTIP));
app_menu_->set_id(VIEW_ID_APP_MENU);
// Always add children in order from left to right, for accessibility.
AddChildView(back_);
AddChildView(forward_);
AddChildView(reload_);
AddChildView(home_);
AddChildView(location_bar_);
AddChildView(browser_actions_);
AddChildView(app_menu_);
LoadImages();
// Start global error services now so we badge the menu correctly.
#if !defined(OS_CHROMEOS)
if (!HasAshShell()) {
SigninGlobalErrorFactory::GetForProfile(browser_->profile());
#if !defined(OS_ANDROID)
SyncGlobalErrorFactory::GetForProfile(browser_->profile());
#endif
}
#if defined(OS_WIN)
RecoveryInstallGlobalErrorFactory::GetForProfile(browser_->profile());
#endif
#endif // OS_CHROMEOS
// Add any necessary badges to the menu item based on the system state.
// Do this after |app_menu_| has been added as a bubble may be shown that
// needs the widget (widget found by way of app_menu_->GetWidget()).
badge_controller_.UpdateDelegate();
location_bar_->Init();
show_home_button_.Init(prefs::kShowHomeButton,
browser_->profile()->GetPrefs(),
base::Bind(&ToolbarView::OnShowHomeButtonChanged,
base::Unretained(this)));
browser_actions_->Init();
// Accessibility specific tooltip text.
if (content::BrowserAccessibilityState::GetInstance()->
IsAccessibleBrowser()) {
back_->SetTooltipText(
l10n_util::GetStringUTF16(IDS_ACCNAME_TOOLTIP_BACK));
forward_->SetTooltipText(
l10n_util::GetStringUTF16(IDS_ACCNAME_TOOLTIP_FORWARD));
}
}
void ToolbarView::OnWidgetActivationChanged(views::Widget* widget,
bool active) {
extensions::ExtensionCommandsGlobalRegistry* registry =
extensions::ExtensionCommandsGlobalRegistry::Get(browser_->profile());
if (active) {
registry->set_registry_for_active_window(
browser_actions_->extension_keybinding_registry());
} else if (registry->registry_for_active_window() ==
browser_actions_->extension_keybinding_registry()) {
registry->set_registry_for_active_window(nullptr);
}
}
void ToolbarView::Update(WebContents* tab) {
if (location_bar_)
location_bar_->Update(tab);
if (browser_actions_)
browser_actions_->RefreshToolbarActionViews();
if (reload_)
reload_->set_menu_enabled(chrome::IsDebuggerAttachedToCurrentTab(browser_));
}
void ToolbarView::ResetTabState(WebContents* tab) {
if (location_bar_)
location_bar_->ResetTabState(tab);
}
void ToolbarView::SetPaneFocusAndFocusAppMenu() {
SetPaneFocus(app_menu_);
}
bool ToolbarView::IsAppMenuFocused() {
return app_menu_->HasFocus();
}
void ToolbarView::AddMenuListener(views::MenuListener* listener) {
menu_listeners_.AddObserver(listener);
}
void ToolbarView::RemoveMenuListener(views::MenuListener* listener) {
menu_listeners_.RemoveObserver(listener);
}
views::View* ToolbarView::GetBookmarkBubbleAnchor() {
views::View* star_view = location_bar()->star_view();
return (star_view && star_view->visible()) ? star_view : app_menu_;
}
views::View* ToolbarView::GetTranslateBubbleAnchor() {
views::View* translate_icon_view = location_bar()->translate_icon_view();
return (translate_icon_view && translate_icon_view->visible()) ?
translate_icon_view : app_menu_;
}
void ToolbarView::ExecuteExtensionCommand(
const extensions::Extension* extension,
const extensions::Command& command) {
browser_actions_->ExecuteExtensionCommand(extension, command);
}
void ToolbarView::ShowAppMenu(bool for_drop) {
if (wrench_menu_.get() && wrench_menu_->IsShowing())
return;
#if defined(USE_AURA)
if (keyboard::KeyboardController::GetInstance() &&
keyboard::KeyboardController::GetInstance()->keyboard_visible()) {
keyboard::KeyboardController::GetInstance()->HideKeyboard(
keyboard::KeyboardController::HIDE_REASON_AUTOMATIC);
}
#endif
wrench_menu_.reset(
new WrenchMenu(browser_, for_drop ? WrenchMenu::FOR_DROP : 0));
wrench_menu_model_.reset(new WrenchMenuModel(this, browser_));
wrench_menu_->Init(wrench_menu_model_.get());
FOR_EACH_OBSERVER(views::MenuListener, menu_listeners_, OnMenuOpened());
wrench_menu_->RunMenu(app_menu_);
}
////////////////////////////////////////////////////////////////////////////////
// ToolbarView, AccessiblePaneView overrides:
bool ToolbarView::SetPaneFocus(views::View* initial_focus) {
if (!AccessiblePaneView::SetPaneFocus(initial_focus))
return false;
location_bar_->SetShowFocusRect(true);
return true;
}
void ToolbarView::GetAccessibleState(ui::AXViewState* state) {
state->role = ui::AX_ROLE_TOOLBAR;
state->name = l10n_util::GetStringUTF16(IDS_ACCNAME_TOOLBAR);
}
////////////////////////////////////////////////////////////////////////////////
// ToolbarView, Menu::Delegate overrides:
bool ToolbarView::GetAcceleratorInfo(int id, ui::Accelerator* accel) {
return GetWidget()->GetAccelerator(id, accel);
}
////////////////////////////////////////////////////////////////////////////////
// ToolbarView, views::MenuButtonListener implementation:
void ToolbarView::OnMenuButtonClicked(views::View* source,
const gfx::Point& point) {
TRACE_EVENT0("views", "ToolbarView::OnMenuButtonClicked");
DCHECK_EQ(VIEW_ID_APP_MENU, source->id());
ShowAppMenu(false); // Not for drop.
}
////////////////////////////////////////////////////////////////////////////////
// ToolbarView, LocationBarView::Delegate implementation:
WebContents* ToolbarView::GetWebContents() {
return browser_->tab_strip_model()->GetActiveWebContents();
}
ToolbarModel* ToolbarView::GetToolbarModel() {
return browser_->toolbar_model();
}
const ToolbarModel* ToolbarView::GetToolbarModel() const {
return browser_->toolbar_model();
}
InstantController* ToolbarView::GetInstant() {
return browser_->instant_controller() ?
browser_->instant_controller()->instant() : NULL;
}
ContentSettingBubbleModelDelegate*
ToolbarView::GetContentSettingBubbleModelDelegate() {
return browser_->content_setting_bubble_model_delegate();
}
void ToolbarView::ShowWebsiteSettings(content::WebContents* web_contents,
const GURL& url,
const content::SSLStatus& ssl) {
chrome::ShowWebsiteSettings(browser_, web_contents, url, ssl);
}
views::Widget* ToolbarView::CreateViewsBubble(
views::BubbleDelegateView* bubble_delegate) {
return views::BubbleDelegateView::CreateBubble(bubble_delegate);
}
PageActionImageView* ToolbarView::CreatePageActionImageView(
LocationBarView* owner, ExtensionAction* action) {
return new PageActionImageView(owner, action, browser_);
}
////////////////////////////////////////////////////////////////////////////////
// ToolbarView, CommandObserver implementation:
void ToolbarView::EnabledStateChangedForCommand(int id, bool enabled) {
views::Button* button = NULL;
switch (id) {
case IDC_BACK:
button = back_;
break;
case IDC_FORWARD:
button = forward_;
break;
case IDC_RELOAD:
button = reload_;
break;
case IDC_HOME:
button = home_;
break;
}
if (button)
button->SetEnabled(enabled);
}
////////////////////////////////////////////////////////////////////////////////
// ToolbarView, views::Button::ButtonListener implementation:
void ToolbarView::ButtonPressed(views::Button* sender,
const ui::Event& event) {
chrome::ExecuteCommandWithDisposition(
browser_, sender->tag(), ui::DispositionFromEventFlags(event.flags()));
}
////////////////////////////////////////////////////////////////////////////////
// ToolbarView, content::NotificationObserver implementation:
void ToolbarView::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_OUTDATED_INSTALL:
ShowOutdatedInstallNotification(true);
break;
case chrome::NOTIFICATION_OUTDATED_INSTALL_NO_AU:
ShowOutdatedInstallNotification(false);
break;
#if defined(OS_WIN)
case chrome::NOTIFICATION_CRITICAL_UPGRADE_INSTALLED:
ShowCriticalNotification();
break;
#endif
default:
NOTREACHED();
}
}
////////////////////////////////////////////////////////////////////////////////
// ToolbarView, ui::AcceleratorProvider implementation:
bool ToolbarView::GetAcceleratorForCommandId(int command_id,
ui::Accelerator* accelerator) {
return GetWidget()->GetAccelerator(command_id, accelerator);
}
////////////////////////////////////////////////////////////////////////////////
// ToolbarView, views::View overrides:
gfx::Size ToolbarView::GetPreferredSize() const {
gfx::Size size(location_bar_->GetPreferredSize());
if (is_display_mode_normal()) {
int content_width = kLeftEdgeSpacing + back_->GetPreferredSize().width() +
forward_->GetPreferredSize().width() +
reload_->GetPreferredSize().width() +
(show_home_button_.GetValue() ? home_->GetPreferredSize().width() : 0) +
kStandardSpacing + browser_actions_->GetPreferredSize().width() +
app_menu_->GetPreferredSize().width() + kRightEdgeSpacing;
size.Enlarge(content_width, 0);
}
return SizeForContentSize(size);
}
gfx::Size ToolbarView::GetMinimumSize() const {
gfx::Size size(location_bar_->GetMinimumSize());
if (is_display_mode_normal()) {
int content_width = kLeftEdgeSpacing + back_->GetMinimumSize().width() +
forward_->GetMinimumSize().width() + reload_->GetMinimumSize().width() +
(show_home_button_.GetValue() ? home_->GetMinimumSize().width() : 0) +
kStandardSpacing + browser_actions_->GetMinimumSize().width() +
app_menu_->GetMinimumSize().width() + kRightEdgeSpacing;
size.Enlarge(content_width, 0);
}
return SizeForContentSize(size);
}
void ToolbarView::Layout() {
// If we have not been initialized yet just do nothing.
if (back_ == NULL)
return;
if (!is_display_mode_normal()) {
location_bar_->SetBounds(0, PopupTopSpacing(), width(),
location_bar_->GetPreferredSize().height());
return;
}
// We assume all child elements except the location bar are the same height.
// Set child_y such that buttons appear vertically centered. We put any excess
// padding above the buttons.
int child_height =
std::min(back_->GetPreferredSize().height(), height());
int child_y = (height() - child_height + 1) / 2;
// If the window is maximized, we extend the back button to the left so that
// clicking on the left-most pixel will activate the back button.
// TODO(abarth): If the window becomes maximized but is not resized,
// then Layout() might not be called and the back button
// will be slightly the wrong size. We should force a
// Layout() in this case.
// http://crbug.com/5540
bool maximized = browser_->window() && browser_->window()->IsMaximized();
int back_width = back_->GetPreferredSize().width();
if (maximized) {
back_->SetBounds(0, child_y, back_width + kLeftEdgeSpacing, child_height);
back_->SetLeadingMargin(kLeftEdgeSpacing);
} else {
back_->SetBounds(kLeftEdgeSpacing, child_y, back_width, child_height);
back_->SetLeadingMargin(0);
}
int next_element_x = back_->bounds().right();
forward_->SetBounds(next_element_x, child_y,
forward_->GetPreferredSize().width(), child_height);
next_element_x = forward_->bounds().right();
reload_->SetBounds(next_element_x, child_y,
reload_->GetPreferredSize().width(), child_height);
next_element_x = reload_->bounds().right();
if (show_home_button_.GetValue() ||
(browser_->is_app() && extensions::util::IsNewBookmarkAppsEnabled())) {
home_->SetVisible(true);
home_->SetBounds(next_element_x, child_y,
home_->GetPreferredSize().width(), child_height);
} else {
home_->SetVisible(false);
home_->SetBounds(next_element_x, child_y, 0, child_height);
}
next_element_x = home_->bounds().right() + kStandardSpacing;
int browser_actions_width = browser_actions_->GetPreferredSize().width();
int app_menu_width = app_menu_->GetPreferredSize().width();
int available_width = std::max(0, width() - kRightEdgeSpacing -
app_menu_width - browser_actions_width - next_element_x);
int location_height = location_bar_->GetPreferredSize().height();
int location_y = (height() - location_height + 1) / 2;
location_bar_->SetBounds(next_element_x, location_y,
std::max(available_width, 0), location_height);
next_element_x = location_bar_->bounds().right();
browser_actions_->SetBounds(
next_element_x, child_y, browser_actions_width, child_height);
next_element_x = browser_actions_->bounds().right();
// The browser actions need to do a layout explicitly, because when an
// extension is loaded/unloaded/changed, BrowserActionContainer removes and
// re-adds everything, regardless of whether it has a page action. For a
// page action, browser action bounds do not change, as a result of which
// SetBounds does not do a layout at all.
// TODO(sidchat): Rework the above behavior so that explicit layout is not
// required.
browser_actions_->Layout();
// Extend the app menu to the screen's right edge in maximized mode just like
// we extend the back button to the left edge.
if (maximized)
app_menu_width += kRightEdgeSpacing;
app_menu_->SetBounds(next_element_x, child_y, app_menu_width, child_height);
}
void ToolbarView::OnPaint(gfx::Canvas* canvas) {
View::OnPaint(canvas);
if (is_display_mode_normal())
return;
// For glass, we need to draw a black line below the location bar to separate
// it from the content area. For non-glass, the NonClientView draws the
// toolbar background below the location bar for us.
// NOTE: Keep this in sync with BrowserView::GetInfoBarSeparatorColor()!
if (GetWidget()->ShouldWindowContentsBeTransparent())
canvas->FillRect(gfx::Rect(0, height() - 1, width(), 1), SK_ColorBLACK);
}
void ToolbarView::OnThemeChanged() {
LoadImages();
}
const char* ToolbarView::GetClassName() const {
return kViewClassName;
}
bool ToolbarView::AcceleratorPressed(const ui::Accelerator& accelerator) {
const views::View* focused_view = focus_manager()->GetFocusedView();
if (focused_view && (focused_view->id() == VIEW_ID_OMNIBOX))
return false; // Let the omnibox handle all accelerator events.
return AccessiblePaneView::AcceleratorPressed(accelerator);
}
bool ToolbarView::IsWrenchMenuShowing() const {
return wrench_menu_.get() && wrench_menu_->IsShowing();
}
bool ToolbarView::ShouldPaintBackground() const {
return display_mode_ == DISPLAYMODE_NORMAL;
}
////////////////////////////////////////////////////////////////////////////////
// ToolbarView, protected:
// Override this so that when the user presses F6 to rotate toolbar panes,
// the location bar gets focus, not the first control in the toolbar - and
// also so that it selects all content in the location bar.
bool ToolbarView::SetPaneFocusAndFocusDefault() {
if (!location_bar_->HasFocus()) {
SetPaneFocus(location_bar_);
location_bar_->FocusLocation(true);
return true;
}
if (!AccessiblePaneView::SetPaneFocusAndFocusDefault())
return false;
browser_->window()->RotatePaneFocus(true);
return true;
}
void ToolbarView::RemovePaneFocus() {
AccessiblePaneView::RemovePaneFocus();
location_bar_->SetShowFocusRect(false);
}
////////////////////////////////////////////////////////////////////////////////
// ToolbarView, private:
// views::ViewTargeterDelegate:
bool ToolbarView::DoesIntersectRect(const views::View* target,
const gfx::Rect& rect) const {
CHECK_EQ(target, this);
// Fall through to the tab strip above us if none of |rect| intersects
// with this view (intersection with the top shadow edge does not
// count as intersection with this view).
if (rect.bottom() < content_shadow_height())
return false;
// Otherwise let our superclass take care of it.
return ViewTargeterDelegate::DoesIntersectRect(this, rect);
}
void ToolbarView::UpdateBadgeSeverity(WrenchMenuBadgeController::BadgeType type,
WrenchIconPainter::Severity severity,
bool animate) {
// Showing the bubble requires |app_menu_| to be in a widget. See comment
// in ConflictingModuleView for details.
DCHECK(app_menu_->GetWidget());
base::string16 accname_app = l10n_util::GetStringUTF16(IDS_ACCNAME_APP);
if (type == WrenchMenuBadgeController::BADGE_TYPE_UPGRADE_NOTIFICATION) {
accname_app = l10n_util::GetStringFUTF16(
IDS_ACCNAME_APP_UPGRADE_RECOMMENDED, accname_app);
}
app_menu_->SetAccessibleName(accname_app);
app_menu_->SetSeverity(severity, animate);
// Keep track of whether we were showing the badge before, so we don't send
// multiple UMA events for example when multiple Chrome windows are open.
static bool incompatibility_badge_showing = false;
// Save the old value before resetting it.
bool was_showing = incompatibility_badge_showing;
incompatibility_badge_showing = false;
if (type == WrenchMenuBadgeController::BADGE_TYPE_INCOMPATIBILITY_WARNING) {
if (!was_showing) {
content::RecordAction(UserMetricsAction("ConflictBadge"));
#if defined(OS_WIN)
ConflictingModuleView::MaybeShow(browser_, app_menu_);
#endif
}
incompatibility_badge_showing = true;
return;
}
}
int ToolbarView::PopupTopSpacing() const {
const int kPopupTopSpacingNonGlass = 3;
return GetWidget()->ShouldWindowContentsBeTransparent() ?
0 : kPopupTopSpacingNonGlass;
}
gfx::Size ToolbarView::SizeForContentSize(gfx::Size size) const {
if (is_display_mode_normal()) {
gfx::ImageSkia* normal_background =
GetThemeProvider()->GetImageSkiaNamed(IDR_CONTENT_TOP_CENTER);
size.SetToMax(
gfx::Size(0, normal_background->height() - content_shadow_height()));
} else if (size.height() == 0) {
// Location mode with a 0 height location bar. If on ash, expand by one
// pixel to show a border in the title bar, otherwise leave the size as zero
// height.
const int kAshBorderSpacing = 1;
if (browser_->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH)
size.Enlarge(0, kAshBorderSpacing);
} else {
const int kPopupBottomSpacingGlass = 1;
const int kPopupBottomSpacingNonGlass = 2;
size.Enlarge(
0,
PopupTopSpacing() + (GetWidget()->ShouldWindowContentsBeTransparent() ?
kPopupBottomSpacingGlass : kPopupBottomSpacingNonGlass));
}
return size;
}
void ToolbarView::LoadImages() {
ui::ThemeProvider* tp = GetThemeProvider();
back_->SetImage(views::Button::STATE_NORMAL,
*(tp->GetImageSkiaNamed(IDR_BACK)));
back_->SetImage(views::Button::STATE_DISABLED,
*(tp->GetImageSkiaNamed(IDR_BACK_D)));
forward_->SetImage(views::Button::STATE_NORMAL,
*(tp->GetImageSkiaNamed(IDR_FORWARD)));
forward_->SetImage(views::Button::STATE_DISABLED,
*(tp->GetImageSkiaNamed(IDR_FORWARD_D)));
reload_->LoadImages();
home_->SetImage(views::Button::STATE_NORMAL,
*(tp->GetImageSkiaNamed(IDR_HOME)));
}
void ToolbarView::ShowCriticalNotification() {
#if defined(OS_WIN)
CriticalNotificationBubbleView* bubble_delegate =
new CriticalNotificationBubbleView(app_menu_);
views::BubbleDelegateView::CreateBubble(bubble_delegate)->Show();
#endif
}
void ToolbarView::ShowOutdatedInstallNotification(bool auto_update_enabled) {
if (OutdatedUpgradeBubbleView::IsAvailable()) {
OutdatedUpgradeBubbleView::ShowBubble(
app_menu_, browser_, auto_update_enabled);
}
}
void ToolbarView::OnShowHomeButtonChanged() {
Layout();
SchedulePaint();
}
int ToolbarView::content_shadow_height() const {
return browser_->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH ?
kContentShadowHeightAsh : kContentShadowHeight;
}
| ltilve/chromium | chrome/browser/ui/views/toolbar/toolbar_view.cc | C++ | bsd-3-clause | 29,000 |
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkBasicCombinationOpenCVImageFilter.h"
#include "cv.h"
namespace mitk {
bool BasicCombinationOpenCVImageFilter::FilterImage( cv::Mat& image )
{
// go through the list of all filters
for ( std::vector<AbstractOpenCVImageFilter::Pointer>::iterator it
= m_FilterList.begin(); it != m_FilterList.end(); it++ )
{
// apply current filter and return false if the filter returned false
if (! (*it)->FilterImage(image) ) { return false; }
}
return true;
}
void BasicCombinationOpenCVImageFilter::PushFilter( AbstractOpenCVImageFilter::Pointer filter )
{
m_FilterList.push_back(filter);
}
AbstractOpenCVImageFilter::Pointer BasicCombinationOpenCVImageFilter::PopFilter( )
{
AbstractOpenCVImageFilter::Pointer lastFilter = m_FilterList.at(m_FilterList.size()-1);
m_FilterList.pop_back();
return lastFilter;
}
bool BasicCombinationOpenCVImageFilter::RemoveFilter( AbstractOpenCVImageFilter::Pointer filter )
{
for ( std::vector<AbstractOpenCVImageFilter::Pointer>::iterator it
= m_FilterList.begin(); it != m_FilterList.end(); it++ )
{
if (*it == filter) {
m_FilterList.erase(it);
return true;
}
}
return false;
}
} // namespace mitk
| rfloca/MITK | Modules/OpenCVVideoSupport/Commands/mitkBasicCombinationOpenCVImageFilter.cpp | C++ | bsd-3-clause | 1,713 |
<?php
/* @var $this ProductAttributesController */
/* @var $model ProductAttributes */
/* @var $form CActiveForm */
?>
<div class="wide form">
<?php $form=$this->beginWidget('CActiveForm', array(
'action'=>Yii::app()->createUrl($this->route),
'method'=>'get',
)); ?>
<div class="row">
<?php echo $form->label($model,'id'); ?>
<?php echo $form->textField($model,'id'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'name'); ?>
<?php echo $form->textField($model,'name',array('size'=>60,'maxlength'=>255)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'label'); ?>
<?php echo $form->textField($model,'label',array('size'=>60,'maxlength'=>255)); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Search'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- search-form --> | Arsen007/viven-gallery-yii | application/modules/admin/views/productAttributes/_search.php | PHP | bsd-3-clause | 845 |
<?php
/**
* Apply the spam protection to the comments module if it is installed
*
* @package spamprotection
*/
class CommentSpamProtection extends Extension {
/**
* Disable the AJAX commenting and update the form
* with the {@link SpamProtectorField} which is enabled
*/
function alterCommentForm(&$form) {
SpamProtectorManager::update_form($form, null, array(
'Name' => 'author_name',
'CommenterURL' => 'author_url',
'Comment' => 'post_body',
'Email' => 'author_email'
));
}
} | comperio/comperio-site | spamprotection/code/extensions/CommentSpamProtection.php | PHP | bsd-3-clause | 513 |
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\models\AffiliatedTruck */
$this->title = 'เพิ่มข้อมูลรถ';
$this->params['breadcrumbs'][] = ['label' => 'รถบรรทุก', 'url' => ['affiliated/view', 'id' => $id]];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="box box-primary">
<div class="box-header with-border"><?php echo Html::encode($this->title) ?></div>
<div class="box-body">
<?php echo $this->render('_form', ['model' => $model, 'company_id' => $company_id, ]) ?>
</div>
</div>
| kimniyom/transport | views/affiliated-truck/create.php | PHP | bsd-3-clause | 587 |
<?php
use kartik\detail\DetailView;
use kartik\grid\GridView;
use yii\data\ActiveDataProvider;
/* @var $this yii\web\View */
/* @var $model app\modules\produksi\models\Proses2 */
?>
<div class="proses2-view">
<?= DetailView::widget([
'model' => $model,
'condensed'=>true,
'hover'=>true,
'mode'=>DetailView::MODE_VIEW,
'panel'=>[
'heading'=>'Proses2 # ' . $model->kode_proses,
'headingOptions'=>[
'template'=>'{title}'
]
],
'attributes' => [
[
'columns'=>[
[
'attribute'=>'id',
'valueColOptions'=>['style'=>'width:40%']
],
[
'attribute'=>'id_proses_1',
'valueColOptions'=>['style'=>'width:40%'],
'value'=> $model->getIdProses1()->one()->kode_proses_1,
]
]
],
[
'columns'=>[
[
'attribute'=>'kode_proses',
'valueColOptions'=>['style'=>'width:40%']
],
[
'attribute'=>'tanggal',
'valueColOptions'=>['style'=>'width:40%']
]
]
],
[
'columns'=>[
[
'attribute'=>'tanggal_selesai',
'valueColOptions'=>['style'=>'width:40%']
],
[
'attribute'=>'selesai',
'valueColOptions'=>['style'=>'width:40%'],
'format'=>'raw',
'value'=> $model->selesai == 1 ? "<span class='label label-success'>selesai</span>": "<span class='label label-warning'>belum</span>"
]
]
],
],
]) ?>
<?= GridView::widget([
'dataProvider' => $detile,
'showPageSummary'=>true,
'pjax'=>true,
'striped'=>false,
'hover'=>true,
'panel'=>[
'type'=>GridView::TYPE_PRIMARY,
'heading'=>'<center><b>Rincian Proses 2</b></center>',
],
'columns' => [
['class' => 'kartik\grid\SerialColumn'],
[
'class'=>'kartik\grid\ExpandRowColumn',
'detailRowCssClass'=>GridView::TYPE_DEFAULT,
'value'=>function($model, $key, $index, $column){
return GridView::ROW_COLLAPSED;
},
'detail'=>function($model, $key, $index){
$barang_keluar = $model->getIdKeluarBarang()->one();
$sql = $barang_keluar->getDetileBarangKeluars();
$dataProvider = new ActiveDataProvider([
'query' => $sql,
]);
return Yii::$app->controller->renderPartial('detile_barang_keluar', [
'dataProvider'=>$dataProvider
]);
}
],
[
'attribute'=>'id_keluar_barang',
'value'=>function($model){
$barang_keluar = $model->getIdKeluarBarang()->one();
return $barang_keluar->kode_keluar;
}
],
//'id_keluar_barang',
'kode_terima',
'tanggal',
[
'label'=> "Jumlah",
'hAlign'=>'center',
'value'=>function($model){
$barang_keluar = $model->getIdKeluarBarang()->one();
$sql = $barang_keluar->getDetileBarangKeluars()->sum('banyak');
return $sql;
}
],
'keterangan'
],
]); ?>
</div>
| saddamalmahali/gmimanajemen | backend/modules/produksi/views/proses-2/view.php | PHP | bsd-3-clause | 3,550 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/gdata/gdata_util.h"
#include <string>
#include <vector>
#include <utility>
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "base/string_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/libxml_utils.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/browser/chromeos/gdata/gdata_file_system.h"
#include "chrome/browser/chromeos/gdata/gdata_system_service.h"
#include "chrome/browser/chromeos/login/user.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_security_policy.h"
#include "net/base/escape.h"
namespace gdata {
namespace util {
namespace {
const char kGDataSpecialRootPath[] = "/special";
const char kGDataMountPointPath[] = "/special/drive";
const FilePath::CharType* kGDataMountPointPathComponents[] = {
"/", "special", "drive"
};
const FilePath::CharType* kGDataSearchPathComponents[] = {
"drive", ".search"
};
const int kReadOnlyFilePermissions = base::PLATFORM_FILE_OPEN |
base::PLATFORM_FILE_READ |
base::PLATFORM_FILE_EXCLUSIVE_READ |
base::PLATFORM_FILE_ASYNC;
GDataFileSystem* GetGDataFileSystem(Profile* profile) {
GDataSystemService* system_service =
GDataSystemServiceFactory::GetForProfile(profile);
return system_service ? system_service->file_system() : NULL;
}
void GetHostedDocumentURLBlockingThread(const FilePath& gdata_cache_path,
GURL* url) {
std::string json;
if (!file_util::ReadFileToString(gdata_cache_path, &json)) {
NOTREACHED() << "Unable to read file " << gdata_cache_path.value();
return;
}
DVLOG(1) << "Hosted doc content " << json;
scoped_ptr<base::Value> val(base::JSONReader::Read(json));
base::DictionaryValue* dict_val;
if (!val.get() || !val->GetAsDictionary(&dict_val)) {
NOTREACHED() << "Parse failure for " << json;
return;
}
std::string edit_url;
if (!dict_val->GetString("url", &edit_url)) {
NOTREACHED() << "url field doesn't exist in " << json;
return;
}
*url = GURL(edit_url);
DVLOG(1) << "edit url " << *url;
}
void OpenEditURLUIThread(Profile* profile, GURL* edit_url) {
Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
if (browser) {
browser->OpenURL(content::OpenURLParams(*edit_url, content::Referrer(),
CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false));
}
}
} // namespace
const FilePath& GetGDataMountPointPath() {
CR_DEFINE_STATIC_LOCAL(FilePath, gdata_mount_path,
(FilePath::FromUTF8Unsafe(kGDataMountPointPath)));
return gdata_mount_path;
}
const std::string& GetGDataMountPointPathAsString() {
CR_DEFINE_STATIC_LOCAL(std::string, gdata_mount_path_string,
(kGDataMountPointPath));
return gdata_mount_path_string;
}
const FilePath& GetSpecialRemoteRootPath() {
CR_DEFINE_STATIC_LOCAL(FilePath, gdata_mount_path,
(FilePath::FromUTF8Unsafe(kGDataSpecialRootPath)));
return gdata_mount_path;
}
GURL GetFileResourceUrl(const std::string& resource_id,
const std::string& file_name) {
std::string url(base::StringPrintf(
"%s:%s",
chrome::kDriveScheme,
net::EscapePath(resource_id).c_str()));
return GURL(url);
}
void ModifyGDataFileResourceUrl(Profile* profile,
const FilePath& gdata_cache_path,
GURL* url) {
GDataFileSystem* file_system = GetGDataFileSystem(profile);
if (!file_system)
return;
// Handle hosted documents. The edit url is in the temporary file, so we
// read it on a blocking thread.
if (file_system->GetCacheDirectoryPath(
GDataRootDirectory::CACHE_TYPE_TMP_DOCUMENTS).IsParent(
gdata_cache_path)) {
GURL* edit_url = new GURL();
content::BrowserThread::GetBlockingPool()->PostTaskAndReply(FROM_HERE,
base::Bind(&GetHostedDocumentURLBlockingThread,
gdata_cache_path, edit_url),
base::Bind(&OpenEditURLUIThread, profile, base::Owned(edit_url)));
*url = GURL();
return;
}
// Handle all other gdata files.
if (file_system->GetCacheDirectoryPath(
GDataRootDirectory::CACHE_TYPE_TMP).IsParent(gdata_cache_path)) {
const std::string resource_id =
gdata_cache_path.BaseName().RemoveExtension().AsUTF8Unsafe();
GDataEntry* entry = NULL;
file_system->FindEntryByResourceIdSync(
resource_id, base::Bind(&ReadOnlyFindEntryCallback, &entry));
std::string file_name;
if (entry && entry->AsGDataFile())
file_name = entry->AsGDataFile()->file_name();
*url = gdata::util::GetFileResourceUrl(resource_id, file_name);
DVLOG(1) << "ModifyGDataFileResourceUrl " << *url;
}
}
bool IsUnderGDataMountPoint(const FilePath& path) {
return GetGDataMountPointPath() == path ||
GetGDataMountPointPath().IsParent(path);
}
GDataSearchPathType GetSearchPathStatus(const FilePath& path) {
std::vector<std::string> components;
path.GetComponents(&components);
return GetSearchPathStatusForPathComponents(components);
}
GDataSearchPathType GetSearchPathStatusForPathComponents(
const std::vector<std::string>& path_components) {
if (path_components.size() < arraysize(kGDataSearchPathComponents))
return GDATA_SEARCH_PATH_INVALID;
for (size_t i = 0; i < arraysize(kGDataSearchPathComponents); i++) {
if (path_components[i] != kGDataSearchPathComponents[i])
return GDATA_SEARCH_PATH_INVALID;
}
switch (path_components.size()) {
case 2:
return GDATA_SEARCH_PATH_ROOT;
case 3:
return GDATA_SEARCH_PATH_QUERY;
case 4:
return GDATA_SEARCH_PATH_RESULT;
default:
return GDATA_SEARCH_PATH_RESULT_CHILD;
}
}
bool ParseSearchFileName(const std::string& search_file_name,
std::string* resource_id,
std::string* original_file_name) {
DCHECK(resource_id);
DCHECK(original_file_name);
*resource_id = "";
*original_file_name = "";
size_t dot_index = search_file_name.find('.');
if (dot_index == std::string::npos)
return false;
*resource_id = search_file_name.substr(0, dot_index);
if (search_file_name.length() - 1 > dot_index)
*original_file_name = search_file_name.substr(dot_index + 1);
return (!resource_id->empty() && !original_file_name->empty());
}
FilePath ExtractGDataPath(const FilePath& path) {
if (!IsUnderGDataMountPoint(path))
return FilePath();
std::vector<FilePath::StringType> components;
path.GetComponents(&components);
// -1 to include 'drive'.
FilePath extracted;
for (size_t i = arraysize(kGDataMountPointPathComponents) - 1;
i < components.size(); ++i) {
extracted = extracted.Append(components[i]);
}
return extracted;
}
void InsertGDataCachePathsPermissions(
Profile* profile,
const FilePath& gdata_path,
std::vector<std::pair<FilePath, int> >* cache_paths ) {
DCHECK(cache_paths);
GDataFileSystem* file_system = GetGDataFileSystem(profile);
if (!file_system)
return;
GDataFileProperties file_properties;
file_system->GetFileInfoByPath(gdata_path, &file_properties);
std::string resource_id = file_properties.resource_id;
std::string file_md5 = file_properties.file_md5;
// We check permissions for raw cache file paths only for read-only
// operations (when fileEntry.file() is called), so read only permissions
// should be sufficient for all cache paths. For the rest of supported
// operations the file access check is done for drive/ paths.
cache_paths->push_back(std::make_pair(
file_system->GetCacheFilePath(resource_id, file_md5,
GDataRootDirectory::CACHE_TYPE_PERSISTENT,
GDataFileSystem::CACHED_FILE_FROM_SERVER),
kReadOnlyFilePermissions));
// TODO(tbarzic): When we start supporting openFile operation, we may have to
// change permission for localy modified files to match handler's permissions.
cache_paths->push_back(std::make_pair(
file_system->GetCacheFilePath(resource_id, file_md5,
GDataRootDirectory::CACHE_TYPE_PERSISTENT,
GDataFileSystem::CACHED_FILE_LOCALLY_MODIFIED),
kReadOnlyFilePermissions));
cache_paths->push_back(std::make_pair(
file_system->GetCacheFilePath(resource_id, file_md5,
GDataRootDirectory::CACHE_TYPE_PERSISTENT,
GDataFileSystem::CACHED_FILE_MOUNTED),
kReadOnlyFilePermissions));
cache_paths->push_back(std::make_pair(
file_system->GetCacheFilePath(resource_id, file_md5,
GDataRootDirectory::CACHE_TYPE_TMP,
GDataFileSystem::CACHED_FILE_FROM_SERVER),
kReadOnlyFilePermissions));
}
bool IsGDataAvailable(Profile* profile) {
if (!chromeos::UserManager::Get()->IsUserLoggedIn() ||
chromeos::UserManager::Get()->IsLoggedInAsGuest() ||
chromeos::UserManager::Get()->IsLoggedInAsDemoUser())
return false;
// Do not allow GData for incognito windows / guest mode.
if (profile->IsOffTheRecord())
return false;
// Disable gdata if preference is set. This can happen with commandline flag
// --disable-gdata or enterprise policy, or probably with user settings too
// in the future.
if (profile->GetPrefs()->GetBoolean(prefs::kDisableGData))
return false;
return true;
}
std::string EscapeCacheFileName(const std::string& filename) {
// This is based on net/base/escape.cc: net::(anonymous namespace)::Escape
std::string escaped;
for (size_t i = 0; i < filename.size(); ++i) {
char c = filename[i];
if (c == '%' || c == '.' || c == '/') {
base::StringAppendF(&escaped, "%%%02X", c);
} else {
escaped.push_back(c);
}
}
return escaped;
}
std::string UnescapeCacheFileName(const std::string& filename) {
std::string unescaped;
for (size_t i = 0; i < filename.size(); ++i) {
char c = filename[i];
if (c == '%' && i + 2 < filename.length()) {
c = (HexDigitToInt(filename[i + 1]) << 4) +
HexDigitToInt(filename[i + 2]);
i += 2;
}
unescaped.push_back(c);
}
return unescaped;
}
void ParseCacheFilePath(const FilePath& path,
std::string* resource_id,
std::string* md5,
std::string* extra_extension) {
DCHECK(resource_id);
DCHECK(md5);
DCHECK(extra_extension);
// Extract up to two extensions from the right.
FilePath base_name = path.BaseName();
const int kNumExtensionsToExtract = 2;
std::vector<FilePath::StringType> extensions;
for (int i = 0; i < kNumExtensionsToExtract; ++i) {
FilePath::StringType extension = base_name.Extension();
if (!extension.empty()) {
// FilePath::Extension returns ".", so strip it.
extension = UnescapeCacheFileName(extension.substr(1));
base_name = base_name.RemoveExtension();
extensions.push_back(extension);
} else {
break;
}
}
// The base_name here is already stripped of extensions in the loop above.
*resource_id = UnescapeCacheFileName(base_name.value());
// Assign the extracted extensions to md5 and extra_extension.
int extension_count = extensions.size();
*md5 = (extension_count > 0) ? extensions[extension_count - 1] :
std::string();
*extra_extension = (extension_count > 1) ? extensions[extension_count - 2] :
std::string();
}
} // namespace util
} // namespace gdata
| robclark/chromium | chrome/browser/chromeos/gdata/gdata_util.cc | C++ | bsd-3-clause | 12,210 |
"""Tests for the object class AntiSpam.
Uses the pyweet AntiSpam with a 1 second timeout instead of the usual 5 minutes
that you would experience if you actually ran the program.
"""
import time
import pytest
from pyweet.spam import AntiSpam
@pytest.fixture(autouse=True)
def set_test_timeout(request):
request.addfinalizer(clear_store)
AntiSpam.timeout = 1
@pytest.fixture
def clear_store():
AntiSpam.tweet_store = {}
AntiSpam.timeout = 600
def test_duplicates_are_spam():
"""Identical messages without the timout should be marked as spam."""
message = "a generic message to test with"
assert not AntiSpam.is_spam(message)
assert AntiSpam.is_spam(message)
assert AntiSpam.is_spam(message)
assert AntiSpam.is_spam(message)
def test_timeouts():
""""After the timeout period, a message should get through."""
message = "another generic message to test with"
assert not AntiSpam.is_spam(message)
assert AntiSpam.is_spam(message)
assert AntiSpam.timeout == 1, "pytest isn't picking up the fixture"
time.sleep(2) # wait a bit
AntiSpam.clear()
assert not AntiSpam.is_spam(message)
assert AntiSpam.is_spam(message)
| a-tal/pyweet | test/test_anti_spam.py | Python | bsd-3-clause | 1,200 |
/**
* MOTECH PLATFORM OPENSOURCE LICENSE AGREEMENT
*
* Copyright (c) 2010-11 The Trustees of Columbia University in the City of
* New York and Grameen Foundation USA. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Grameen Foundation USA, Columbia University, or
* their respective contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY GRAMEEN FOUNDATION USA, COLUMBIA UNIVERSITY
* AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRAMEEN FOUNDATION
* USA, COLUMBIA UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.motechproject.mobile.omp.manager.intellivr;
import static org.junit.Assert.*;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.motechproject.mobile.core.model.Language;
import org.motechproject.mobile.core.model.LanguageImpl;
import org.motechproject.mobile.core.model.MStatus;
import org.motechproject.mobile.core.model.MessageRequest;
import org.motechproject.mobile.core.model.MessageRequestImpl;
import org.motechproject.mobile.core.model.MessageType;
import org.motechproject.mobile.core.model.NotificationType;
import org.motechproject.mobile.core.model.NotificationTypeImpl;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration( locations = {"classpath:META-INF/ivrcallstatsprovidertest-config.xml"})
public class IVRCallStatsProviderTest {
@Resource
IVRCallStatsProvider ivrCallStatsProvider;
@Resource
IntellIVRDAO ivrDao;
Language english;
NotificationType n1,n2,n3;
long n1Id = 1;
String n1IvrEntityName = "weekly_tree_name";
long n2Id = 2;
String n2IvrEntityName = "reminder_message1.wav";
long n3Id = 3;
String n3IvrEntityName = "reminder_message2.wav";
String primaryInfoRecordingName = "primary_informational_message.wav";
String secondaryInfoRecordingName = "secondary_informational_message.wav";
String recipientId1 = "1234561";
String phone1 = "5555551";
private long nextRequestId = 0;
@Before
public void setUp() throws Exception {
english = new LanguageImpl();
english.setCode("en");
english.setId(29000000001l);
english.setName("English");
n1 = new NotificationTypeImpl();
n1.setId(1L);
n1.setDescription("testing");
n1.setName("testing");
n2 = new NotificationTypeImpl();
n2.setId(2L);
n3 = new NotificationTypeImpl();
n3.setId(3L);
}
@Test
@Transactional
public void testGetCountIVRCallSessions() {
Date now = new Date();
Date oneDayAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -1);
Date tenDaysAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -10);
MessageRequest mr1 = getMessageRequestTemplate();
mr1.setNotificationType(n1);
MessageRequest mr2 = getMessageRequestTemplate();
mr2.setNotificationType(n2);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, oneDayAgo, now);
session1.getMessageRequests().add(mr1);
session1.getMessageRequests().add(mr2);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenDaysAgo, now);
session2.getMessageRequests().add(mr1);
session2.getMessageRequests().add(mr2);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
assertEquals(2, ivrCallStatsProvider.getCountIVRCallSessions());
}
@Test
@Transactional
public void testGetCountIVRCallSessionsInLastMinutes() {
Date now = new Date();
Date twoMinuteAgo = addToDate(now, GregorianCalendar.MINUTE, -2);
Date tenMinuteAgo = addToDate(now, GregorianCalendar.MINUTE, -10);
MessageRequest mr1 = getMessageRequestTemplate();
mr1.setNotificationType(n1);
MessageRequest mr2 = getMessageRequestTemplate();
mr2.setNotificationType(n2);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, twoMinuteAgo, now);
session1.getMessageRequests().add(mr1);
session1.getMessageRequests().add(mr2);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenMinuteAgo, now);
session2.getMessageRequests().add(mr1);
session2.getMessageRequests().add(mr2);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
assertEquals(0, ivrCallStatsProvider.getCountIVRSessionsInLastMinutes(1));
assertEquals(1, ivrCallStatsProvider.getCountIVRSessionsInLastMinutes(5));
assertEquals(2, ivrCallStatsProvider.getCountIVRSessionsInLastMinutes(11));
}
@Test
@Transactional
public void testGetCountIVRCallSessionsInLastHours() {
Date now = new Date();
Date twoHoursAgo = addToDate(now, GregorianCalendar.HOUR, -2);
Date tenHoursAgo = addToDate(now, GregorianCalendar.HOUR, -10);
MessageRequest mr1 = getMessageRequestTemplate();
mr1.setNotificationType(n1);
MessageRequest mr2 = getMessageRequestTemplate();
mr2.setNotificationType(n2);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, twoHoursAgo, now);
session1.getMessageRequests().add(mr1);
session1.getMessageRequests().add(mr2);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenHoursAgo, now);
session2.getMessageRequests().add(mr1);
session2.getMessageRequests().add(mr2);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
assertEquals(0, ivrCallStatsProvider.getCountIVRCallSessionsInLastHours(1));
assertEquals(1, ivrCallStatsProvider.getCountIVRCallSessionsInLastHours(5));
assertEquals(2, ivrCallStatsProvider.getCountIVRCallSessionsInLastHours(11));
}
@Test
@Transactional
public void testGetCountIVRCallSessionsInLastDays() {
Date now = new Date();
Date oneDayAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -1);
Date tenDaysAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -10);
MessageRequest mr1 = getMessageRequestTemplate();
mr1.setNotificationType(n1);
MessageRequest mr2 = getMessageRequestTemplate();
mr2.setNotificationType(n2);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, oneDayAgo, now);
session1.getMessageRequests().add(mr1);
session1.getMessageRequests().add(mr2);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenDaysAgo, now);
session2.getMessageRequests().add(mr1);
session2.getMessageRequests().add(mr2);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
assertEquals(0, ivrCallStatsProvider.getCountIVRCallSessionsInLastDays(1));
assertEquals(1, ivrCallStatsProvider.getCountIVRCallSessionsInLastDays(5));
assertEquals(1, ivrCallStatsProvider.getCountIVRCallSessionsInLastDays(10));
assertEquals(2, ivrCallStatsProvider.getCountIVRCallSessionsInLastDays(11));
}
@Test
@Transactional
public void testGetCountIVRCalls() {
Date now = new Date();
Date oneDayAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -1);
Date tenDaysAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -10);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, oneDayAgo, now);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenDaysAgo, now);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
IVRCall call1 = new IVRCall(now, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session1);
session1.getCalls().add(call1);
IVRCall call2 = new IVRCall(now, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session2);
session2.getCalls().add(call2);
assertEquals(2, ivrCallStatsProvider.getCountIVRCalls());
}
@Test
@Transactional
public void testGetCountIVRCallsInLastMinutes() {
Date now = new Date();
Date twoMinuteAgo = addToDate(now, GregorianCalendar.MINUTE, -2);
Date tenMinuteAgo = addToDate(now, GregorianCalendar.MINUTE, -10);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, twoMinuteAgo, now);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenMinuteAgo, now);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
IVRCall call1 = new IVRCall(twoMinuteAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session1);
session1.getCalls().add(call1);
IVRCall call2 = new IVRCall(tenMinuteAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session2);
session2.getCalls().add(call2);
assertEquals(0, ivrCallStatsProvider.getCountIVRCallsInLastMinutes(1));
assertEquals(1, ivrCallStatsProvider.getCountIVRCallsInLastMinutes(5));
assertEquals(2, ivrCallStatsProvider.getCountIVRCallsInLastMinutes(11));
}
@Test
@Transactional
public void testGetCountIVRCallsInLastHour() {
Date now = new Date();
Date twoHoursAgo = addToDate(now, GregorianCalendar.HOUR, -2);
Date tenHoursAgo = addToDate(now, GregorianCalendar.HOUR, -10);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, twoHoursAgo, now);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenHoursAgo, now);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
IVRCall call1 = new IVRCall(twoHoursAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session1);
session1.getCalls().add(call1);
IVRCall call2 = new IVRCall(tenHoursAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session2);
session2.getCalls().add(call2);
assertEquals(0, ivrCallStatsProvider.getCountIVRCallsInLastHours(1));
assertEquals(1, ivrCallStatsProvider.getCountIVRCallsInLastHours(5));
assertEquals(2, ivrCallStatsProvider.getCountIVRCallsInLastHours(11));
}
@Test
@Transactional
public void testGetCountIVRCallsInLastDays() {
Date now = new Date();
Date oneDayAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -1);
Date tenDaysAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -10);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, oneDayAgo, now);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenDaysAgo, now);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
IVRCall call1 = new IVRCall(oneDayAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session1);
session1.getCalls().add(call1);
IVRCall call2 = new IVRCall(tenDaysAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session2);
session2.getCalls().add(call2);
assertEquals(0, ivrCallStatsProvider.getCountIVRCallsInLastDays(1));
assertEquals(1, ivrCallStatsProvider.getCountIVRCallsInLastDays(5));
assertEquals(1, ivrCallStatsProvider.getCountIVRCallsInLastDays(10));
assertEquals(2, ivrCallStatsProvider.getCountIVRCallsInLastDays(11));
}
@Test
@Transactional
public void testGetCountIVRCallsWithStatus() {
Date now = new Date();
Date oneDayAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -1);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, oneDayAgo, now);
ivrDao.saveIVRCallSession(session1);
IVRCall call1 = new IVRCall(oneDayAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session1);
session1.getCalls().add(call1);
for ( IVRCallStatus cs : IVRCallStatus.values() ) {
if ( cs == IVRCallStatus.REQUESTED )
assertEquals(1, ivrCallStatsProvider.getCountIVRCallsWithStatus(cs));
else
assertEquals(0, ivrCallStatsProvider.getCountIVRCallsWithStatus(cs));
}
}
@Test
@Transactional
public void testGetCountIVRCallsInLastMinutesWithStatus() {
Date now = new Date();
Date twoMinuteAgo = addToDate(now, GregorianCalendar.MINUTE, -2);
Date tenMinuteAgo = addToDate(now, GregorianCalendar.MINUTE, -10);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, twoMinuteAgo, now);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenMinuteAgo, now);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
IVRCall call1 = new IVRCall(twoMinuteAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session1);
session1.getCalls().add(call1);
IVRCall call2 = new IVRCall(tenMinuteAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session2);
session2.getCalls().add(call2);
for ( IVRCallStatus cs : IVRCallStatus.values() ) {
assertEquals(0, ivrCallStatsProvider.getCountIVRCallsInLastMinutesWithStatus(1, cs));
if ( cs == IVRCallStatus.REQUESTED ) {
assertEquals(1, ivrCallStatsProvider.getCountIVRCallsInLastMinutesWithStatus(5, cs));
assertEquals(2, ivrCallStatsProvider.getCountIVRCallsInLastMinutesWithStatus(11,cs));
} else {
assertEquals(0, ivrCallStatsProvider.getCountIVRCallsInLastMinutesWithStatus(5, cs));
assertEquals(0, ivrCallStatsProvider.getCountIVRCallsInLastMinutesWithStatus(11,cs));
}
}
}
@Test
@Transactional
public void testGetCountIVRCallsInLastHoursWithStatus() {
Date now = new Date();
Date twoHoursAgo = addToDate(now, GregorianCalendar.HOUR, -2);
Date tenHoursAgo = addToDate(now, GregorianCalendar.HOUR, -10);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, twoHoursAgo, now);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenHoursAgo, now);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
IVRCall call1 = new IVRCall(twoHoursAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session1);
session1.getCalls().add(call1);
IVRCall call2 = new IVRCall(tenHoursAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session2);
session2.getCalls().add(call2);
for ( IVRCallStatus cs : IVRCallStatus.values() ) {
assertEquals(0, ivrCallStatsProvider.getCountIVRCallsInLastHoursWithStatus(1,cs));
if ( cs == IVRCallStatus.REQUESTED ) {
assertEquals(1, ivrCallStatsProvider.getCountIVRCallsInLastHoursWithStatus(5, cs));
assertEquals(2, ivrCallStatsProvider.getCountIVRCallsInLastHoursWithStatus(11, cs));
} else {
assertEquals(0, ivrCallStatsProvider.getCountIVRCallsInLastHoursWithStatus(5, cs));
assertEquals(0, ivrCallStatsProvider.getCountIVRCallsInLastHoursWithStatus(11, cs));
}
}
}
@Test
@Transactional
public void testGetCountIVRCallsInLastDaysWithStatus() {
Date now = new Date();
Date oneDayAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -1);
Date tenDaysAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -10);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, oneDayAgo, now);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenDaysAgo, now);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
IVRCall call1 = new IVRCall(oneDayAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session1);
session1.getCalls().add(call1);
IVRCall call2 = new IVRCall(tenDaysAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session2);
session2.getCalls().add(call2);
for ( IVRCallStatus cs : IVRCallStatus.values() ) {
assertEquals(0, ivrCallStatsProvider.getCountIVRCallsInLastDaysWithStatus(1, cs));
if ( cs == IVRCallStatus.REQUESTED ) {
assertEquals(1, ivrCallStatsProvider.getCountIVRCallsInLastDaysWithStatus(5, cs));
assertEquals(1, ivrCallStatsProvider.getCountIVRCallsInLastDaysWithStatus(10, cs));
assertEquals(2, ivrCallStatsProvider.getCountIVRCallsInLastDaysWithStatus(11, cs));
} else {
assertEquals(0, ivrCallStatsProvider.getCountIVRCallsInLastDaysWithStatus(5, cs));
assertEquals(0, ivrCallStatsProvider.getCountIVRCallsInLastDaysWithStatus(10, cs));
assertEquals(0, ivrCallStatsProvider.getCountIVRCallsInLastDaysWithStatus(11, cs));
}
}
}
@Test
@Transactional
public void testGetRecordingStats() {
Date now = new Date();
Date twoMinuteAgo = addToDate(now, GregorianCalendar.MINUTE, -2);
Date tenMinuteAgo = addToDate(now, GregorianCalendar.MINUTE, -10);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, twoMinuteAgo, now);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenMinuteAgo, now);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
IVRCall call1 = new IVRCall(twoMinuteAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session1);
session1.getCalls().add(call1);
IVRCall call2 = new IVRCall(tenMinuteAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session2);
session2.getCalls().add(call2);
IVRMenu m1 = new IVRMenu(n2IvrEntityName, twoMinuteAgo, 10, "", "");
IVRMenu m2 = new IVRMenu(n2IvrEntityName, twoMinuteAgo, 20, "", "");
IVRMenu m3 = new IVRMenu(primaryInfoRecordingName, twoMinuteAgo, 10, "", "");
IVRMenu m4 = new IVRMenu(primaryInfoRecordingName, twoMinuteAgo, 20, "", "");
call1.getMenus().add(m1);
call2.getMenus().add(m2);
call1.getMenus().add(m3);
call2.getMenus().add(m4);
List<IVRRecordingStat> stats = (List<IVRRecordingStat>)ivrCallStatsProvider.getIVRRecordingStats();
assertEquals(2, stats.size());
for ( IVRRecordingStat s : stats ) {
assertEquals(2, s.getTotalListens());
assertEquals(15, s.getAverageTimeListened(),1);
}
}
@Test
@Transactional
public void testGetIVRCallStatusStats() {
Date now = new Date();
Date twoMinuteAgo = addToDate(now, GregorianCalendar.MINUTE, -2);
Date tenMinuteAgo = addToDate(now, GregorianCalendar.MINUTE, -10);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, twoMinuteAgo, now);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenMinuteAgo, now);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
IVRCall call1 = new IVRCall(twoMinuteAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session1);
session1.getCalls().add(call1);
IVRCall call2 = new IVRCall(tenMinuteAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session2);
session2.getCalls().add(call2);
List<IVRCallStatusStat> stats = ivrCallStatsProvider.getIVRCallStatusStats();
assertEquals(IVRCallStatus.values().length, stats.size());
for ( IVRCallStatusStat s : stats ) {
if ( s.getStatus() == IVRCallStatus.REQUESTED )
assertEquals(2, s.getCount());
else
assertEquals(0, s.getCount());
}
}
@Test
@Transactional
public void testGetIVRCallStatusStatsInLastMinutes() {
Date now = new Date();
Date twoMinuteAgo = addToDate(now, GregorianCalendar.MINUTE, -2);
Date tenMinuteAgo = addToDate(now, GregorianCalendar.MINUTE, -10);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, twoMinuteAgo, now);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenMinuteAgo, now);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
IVRCall call1 = new IVRCall(twoMinuteAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session1);
session1.getCalls().add(call1);
IVRCall call2 = new IVRCall(tenMinuteAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session2);
session2.getCalls().add(call2);
List<IVRCallStatusStat> fiveMinuteStats = ivrCallStatsProvider.getIVRCallStatusStatsFromLastMinutes(5);
assertEquals(IVRCallStatus.values().length, fiveMinuteStats.size());
for ( IVRCallStatusStat s : fiveMinuteStats ) {
if ( s.getStatus() == IVRCallStatus.REQUESTED )
assertEquals(1, s.getCount());
else
assertEquals(0, s.getCount());
}
List<IVRCallStatusStat> ellevenMinuteStats = ivrCallStatsProvider.getIVRCallStatusStatsFromLastMinutes(11);
assertEquals(IVRCallStatus.values().length, ellevenMinuteStats.size());
for ( IVRCallStatusStat s : ellevenMinuteStats ) {
if ( s.getStatus() == IVRCallStatus.REQUESTED )
assertEquals(2, s.getCount());
else
assertEquals(0, s.getCount());
}
}
@Test
@Transactional
public void testGetIVRCallStatusStatsInLastHours() {
Date now = new Date();
Date twoHoursAgo = addToDate(now, GregorianCalendar.HOUR, -2);
Date tenHoursAgo = addToDate(now, GregorianCalendar.HOUR, -10);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, twoHoursAgo, now);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenHoursAgo, now);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
IVRCall call1 = new IVRCall(twoHoursAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session1);
session1.getCalls().add(call1);
IVRCall call2 = new IVRCall(tenHoursAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session2);
session2.getCalls().add(call2);
List<IVRCallStatusStat> fiveHourStats = ivrCallStatsProvider.getIVRCallStatusStatsFromLastHours(5);
assertEquals(IVRCallStatus.values().length, fiveHourStats.size());
for ( IVRCallStatusStat s : fiveHourStats ) {
if ( s.getStatus() == IVRCallStatus.REQUESTED )
assertEquals(1, s.getCount());
else
assertEquals(0, s.getCount());
}
List<IVRCallStatusStat> ellevenHourStats = ivrCallStatsProvider.getIVRCallStatusStatsFromLastHours(11);
assertEquals(IVRCallStatus.values().length, ellevenHourStats.size());
for ( IVRCallStatusStat s : ellevenHourStats ) {
if ( s.getStatus() == IVRCallStatus.REQUESTED )
assertEquals(2, s.getCount());
else
assertEquals(0, s.getCount());
}
}
@Test
@Transactional
public void testGetIVRCallStatusStatsInLastDays() {
Date now = new Date();
Date oneDayAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -1);
Date tenDaysAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -10);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, oneDayAgo, now);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenDaysAgo, now);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
IVRCall call1 = new IVRCall(oneDayAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session1);
session1.getCalls().add(call1);
IVRCall call2 = new IVRCall(tenDaysAgo, null, null, 0, UUID.randomUUID().toString(), IVRCallStatus.REQUESTED, "Call request accepted", session2);
session2.getCalls().add(call2);
List<IVRCallStatusStat> fiveDayStats = ivrCallStatsProvider.getIVRCallStatusStatsFromLastDays(5);
assertEquals(IVRCallStatus.values().length, fiveDayStats.size());
for ( IVRCallStatusStat s : fiveDayStats ) {
if ( s.getStatus() == IVRCallStatus.REQUESTED )
assertEquals(1, s.getCount());
else
assertEquals(0, s.getCount());
}
List<IVRCallStatusStat> ellevenDayStats = ivrCallStatsProvider.getIVRCallStatusStatsFromLastDays(11);
assertEquals(IVRCallStatus.values().length, ellevenDayStats.size());
for ( IVRCallStatusStat s : ellevenDayStats ) {
if ( s.getStatus() == IVRCallStatus.REQUESTED )
assertEquals(2, s.getCount());
else
assertEquals(0, s.getCount());
}
}
@Test
@Transactional
public void getIVRCallSessions() {
Date now = new Date();
Date oneDayAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -1);
Date tenDaysAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -10);
MessageRequest mr1 = getMessageRequestTemplate();
mr1.setNotificationType(n1);
MessageRequest mr2 = getMessageRequestTemplate();
mr2.setNotificationType(n2);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, oneDayAgo, now);
session1.getMessageRequests().add(mr1);
session1.getMessageRequests().add(mr2);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenDaysAgo, now);
session2.getMessageRequests().add(mr1);
session2.getMessageRequests().add(mr2);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
List<IVRCallSession> sessions = ivrCallStatsProvider.getIVRCallSessions();
assertEquals(2, sessions.size());
}
@Test
@Transactional
public void testGetIVRCallSessionsInLastMinutes() {
Date now = new Date();
Date twoMinuteAgo = addToDate(now, GregorianCalendar.MINUTE, -2);
Date tenMinuteAgo = addToDate(now, GregorianCalendar.MINUTE, -10);
MessageRequest mr1 = getMessageRequestTemplate();
mr1.setNotificationType(n1);
MessageRequest mr2 = getMessageRequestTemplate();
mr2.setNotificationType(n2);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, twoMinuteAgo, now);
session1.getMessageRequests().add(mr1);
session1.getMessageRequests().add(mr2);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenMinuteAgo, now);
session2.getMessageRequests().add(mr1);
session2.getMessageRequests().add(mr2);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
List<IVRCallSession> sessions = ivrCallStatsProvider.getIVRCallSessionsInLastMinutes(5);
assertEquals(1, sessions.size());
}
@Test
@Transactional
public void testGetIVRCallSessionsInLastHours() {
Date now = new Date();
Date twoHoursAgo = addToDate(now, GregorianCalendar.HOUR, -2);
Date tenHoursAgo = addToDate(now, GregorianCalendar.HOUR, -10);
MessageRequest mr1 = getMessageRequestTemplate();
mr1.setNotificationType(n1);
MessageRequest mr2 = getMessageRequestTemplate();
mr2.setNotificationType(n2);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, twoHoursAgo, now);
session1.getMessageRequests().add(mr1);
session1.getMessageRequests().add(mr2);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenHoursAgo, now);
session2.getMessageRequests().add(mr1);
session2.getMessageRequests().add(mr2);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
List<IVRCallSession> sessions = ivrCallStatsProvider.getIVRCallSessionsInLastHours(5);
assertEquals(1, sessions.size());
}
@Test
@Transactional
public void testGetIVRCallSessionsInLastDays() {
Date now = new Date();
Date oneDayAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -1);
Date tenDaysAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -10);
MessageRequest mr1 = getMessageRequestTemplate();
mr1.setNotificationType(n1);
MessageRequest mr2 = getMessageRequestTemplate();
mr2.setNotificationType(n2);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, oneDayAgo, now);
session1.getMessageRequests().add(mr1);
session1.getMessageRequests().add(mr2);
IVRCallSession session2 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenDaysAgo, now);
session2.getMessageRequests().add(mr1);
session2.getMessageRequests().add(mr2);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
List<IVRCallSession> sessions = ivrCallStatsProvider.getIVRCallSessionsInLastDays(5);
assertEquals(1, sessions.size());
}
@Test
@Transactional
public void testGetIVRCallSessionForUser() {
Date now = new Date();
Date oneDayAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -1);
Date tenDaysAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -10);
MessageRequest mr1 = getMessageRequestTemplate();
mr1.setNotificationType(n1);
MessageRequest mr2 = getMessageRequestTemplate();
mr2.setNotificationType(n2);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, oneDayAgo, now);
session1.getMessageRequests().add(mr1);
session1.getMessageRequests().add(mr2);
IVRCallSession session2 = new IVRCallSession("notRecip1", "notPhone1", english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenDaysAgo, now);
session2.getMessageRequests().add(mr1);
session2.getMessageRequests().add(mr2);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
List<IVRCallSession> sessions = ivrCallStatsProvider.getIVRCallSessionsForUser(recipientId1);
assertEquals(1, sessions.size());
}
@Test
@Transactional
public void testGetIVRCallSessionsForPhone() {
Date now = new Date();
Date oneDayAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -1);
Date tenDaysAgo = addToDate(now, GregorianCalendar.DAY_OF_MONTH, -10);
MessageRequest mr1 = getMessageRequestTemplate();
mr1.setNotificationType(n1);
MessageRequest mr2 = getMessageRequestTemplate();
mr2.setNotificationType(n2);
IVRCallSession session1 = new IVRCallSession(recipientId1, phone1, english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, oneDayAgo, now);
session1.getMessageRequests().add(mr1);
session1.getMessageRequests().add(mr2);
IVRCallSession session2 = new IVRCallSession("notRecip1", "notPhone1", english.getName(), IVRCallSession.OUTBOUND, 0, 0, IVRCallSession.OPEN, tenDaysAgo, now);
session2.getMessageRequests().add(mr1);
session2.getMessageRequests().add(mr2);
ivrDao.saveIVRCallSession(session1);
ivrDao.saveIVRCallSession(session2);
List<IVRCallSession> sessions = ivrCallStatsProvider.getIVRCallSessionsForPhone(phone1);
assertEquals(1, sessions.size());
}
private MessageRequest getMessageRequestTemplate() {
MessageRequest mr = new MessageRequestImpl();
mr.setDateCreated(new Date());
mr.setDateFrom(new Date());
mr.setDaysAttempted(1);
mr.setId(nextRequestId);
mr.setLanguage(english);
mr.setMessageType(MessageType.VOICE);
mr.setNotificationType(n1);
mr.setPhoneNumberType("PERSONAL");
mr.setRecipientId(recipientId1);
mr.setRecipientNumber(phone1);
mr.setRequestId(UUID.randomUUID().toString());
mr.setStatus(MStatus.PENDING);
mr.setTryNumber(1);
mr.setVersion(0);
return mr;
}
private Date addToDate(Date start, int field, int amount) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(start);
cal.add(field, amount);
return cal.getTime();
}
}
| motech/MOTECH-Mobile | motech-mobile-omp/src/test/java/org/motechproject/mobile/omp/manager/intellivr/IVRCallStatsProviderTest.java | Java | bsd-3-clause | 36,006 |
/******************************************************************************
* Copyright (c) 2009-2016, Barthelemy Dagenais and individual contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
package py4j.examples;
public interface InterfaceB {
public InterfaceA getA();
}
| jonahkichwacoders/py4j | py4j-java/src/test/java/py4j/examples/InterfaceB.java | Java | bsd-3-clause | 1,794 |
# This file is part of the Edison Project.
# Please refer to the LICENSE document that was supplied with this software for information on how it can be used.
# ensure that we include all the models required to administer this app
from cmdb.models import *
from django.contrib import admin
admin.site.register(Country)
admin.site.register(County)
admin.site.register(Address)
admin.site.register(Company)
admin.site.register(Contact)
admin.site.register(DataCentre)
admin.site.register(DataCentreRoom)
admin.site.register(DataCentreSuite)
admin.site.register(DataCentreRack)
admin.site.register(Repo)
admin.site.register(ConfigurationItemClass)
admin.site.register(NetworkInterface)
admin.site.register(PackageProvider)
admin.site.register(PackageFormat)
admin.site.register(OperatingSystemBreed)
admin.site.register(OperatingSystemName)
admin.site.register(OperatingSystemVersion)
admin.site.register(VirtualisationType)
admin.site.register(VirtualServerDefinition)
admin.site.register(ConfigurationItemProfile)
admin.site.register(ConfigurationItem)
| proffalken/edison | cmdb/admin.py | Python | bsd-3-clause | 1,052 |
<?php
class gnuplot
{
public static $RANGE_START = "START";
public static $RANGE_END = "END";
public static $TEXT_ROTATE_TRUE = "rotate";
public static $TEXT_ROTATE_FALSE = "norotate";
private $property = array();
public function __construct()
{
$this->init();
}
private function init()
{
$this->property['DataSeries'] = array();
$this->property['OutputImage'] = '//**php_gnuplot_image.png';
$this->property['ImageWidth'] = 1200;
$this->property['ImageHeight'] = 1200;
$this->property['tmargin'] = 4;
$this->property['bmargin'] = 9;
$this->property['lmargin'] = 9;
$this->property['rmargin'] = 4;
$this->property['YScaleInterval'] = 2;
$this->property['YScaleTextRotate'] = self::$TEXT_ROTATE_FALSE;
$this->property['YScaleLabel'] = 'Y-AXIS';
$this->property['YScaleFormat'] = "%3.2f";
$this->property['XScaleInterval'] = 1;
$this->property['XScaleTextRotate'] = self::$TEXT_ROTATE_TRUE;
$this->property['XScaleLabel'] = 'X-AXIS';
$this->property['XScaleFormat'] = "%3.2f";
$this->property['Title'] = 'TITLE';
$this->property['SubTitle'] = '';
$this->property['YRangeStart'] = 0;
$this->property['YRangeEnd'] = 100;
$this->property['XRangeStart'] = 0 ;
$this->property['XRangeEnd'] = 100;
$this->property['DotSize'] = 1;
$this->property['DotType'] = 59;
$this->property['AddSpline'] = false;
$this->property['AddBezier'] = false;
$this->property['additional_text'] = array();;
}
public function plot_single_series($series_name = null, $series_title = null)
{
if ($this->DataSeriesCount() == 0)
{
echo "##ERROR plot_single_series ... Can't plot data graph with NO DATA\n";
return null;
}
$array = null;
if (is_null($series_name))
$array = util::first_element($this->DataSeries());
else
{
$array = $this->DataSeries($series_name);
if (is_null($array))
{
echo "##ERROR Can't find data series with name $series_name\n";
return null;
}
}
if (is_null($series_title))
$series_title = util::first_key($this->DataSeries());
//** temp input filename
$temp_data_filename = "//**__php_gnu_plot.data";
//** convert input array to a temp tab delimited file of column1 = keys , column 2 = values
$temp_data_filename = file::Array2File($array, $temp_data_filename, "", "","\t");
if (is_null($temp_data_filename) )
{
echo "##ERROR could not write to data to $temp_data_filename\n";
return NULL;
}
$spline = "";
if ($this->AddSpline())
$spline = ", '{$temp_data_filename}' using 1:2 smooth csplines title 'spline' with lines";
$bezier = "";
if ($this->AddBezier())
$bezier = ", '{$temp_data_filename}' using 1:2 smooth bezier title 'bezier' with lines";
//** might be better at some stage to create folders in tmp to do this
$gnu_plot_command_filename = "//**php_gnuplot_script.gnu";
$series_title = str_replace('_', '-', $series_title);
//** build additional text
//** $additional_text ="";
//** if (count($this->property['additional_text']) > 0)
//** {
//**
//** foreach ($this->property['additional_text'] as $index => $single_text)
//** {
//** $single_text = trim($single_text);
//**
//** $plot_offset = ( ($this->MarginTop() - 1) - $index);
//** $label_num = $index + 1;
//** $additional_text .= "set label 11 \"{$single_text}\" at {$this->XRangeStart()}, {$this->YRangeEnd()}, 0 left norotate back textcolor lt 3 nopoint offset character 0, {$plot_offset}, 0";
//** }
//**
//** }
$gnu_script = <<<CMD
set termoption enhanced
set terminal png transparent nocrop enhanced size {$this->ImageWidth()},{$this->ImageHeight()}
set output '{$this->OutputImage()}'
set xtics nomirror {$this->XScaleInterval()} {$this->XScaleTextRotate()}
set ytics nomirror {$this->YScaleInterval()} offset character 0, 0, 0
set format y "{$this->XScaleFormat()}"
set format x "{$this->YScaleFormat()}"
set ylabel "{$this->YScaleLabel()}" offset 0
set xlabel "{$this->XScaleLabel()}" offset 0, -2
set title "{$this->FullTitle()}" left
set key right tmargin
set xrange [ {$this->XRangeAsString()} ] noreverse nowriteback
set yrange [ {$this->YRangeAsString()} ] noreverse nowriteback
set tmargin {$this->MarginTop()}
set bmargin {$this->MarginBottom()}
set lmargin {$this->MarginLeft()}
set rmargin {$this->MarginRight()}
set grid
set pointsize {$this->DotSize()}
plot '{$temp_data_filename}' using 1:2 with linespoints pointtype {$this->DotType()} title '{$series_title}' {$spline} {$bezier}
CMD;
//**logger::text($gnu_script);
file_put_contents($gnu_plot_command_filename, $gnu_script);
$gnuplot_result = exec("gnuplot $gnu_plot_command_filename");
if (!file_exists($this->OutputImage()))
{
logger::error("Failed to create output from GNUPLOT script \n--------------\n$gnu_script\n-------------------\n");
return null;
}
file::Delete($temp_data_filename);
file::Delete($gnu_plot_command_filename);
return $this->OutputImage(); //** this should be the path to the image they asked for
}
public function AddText($text)
{
$this->property['additional_text'][] = $text;
}
public function AddSeries($name,$data)
{
$this->DataSeries($name,$data);
}
public function DataSeries()
{
if (func_num_args() == 0 ) return $this->property['DataSeries'];
if (func_num_args() == 1 ) return $this->property['DataSeries'][func_get_arg(0)];
if (func_num_args() == 2 ) $this->property['DataSeries'][func_get_arg(0)] = func_get_arg(1);
}
public function DataSeriesCount()
{
return count($this->property['DataSeries']);
}
public function OutputImage()
{
if (func_num_args() == 0 ) return $this->property['OutputImage'];
if (func_num_args() == 1 ) $this->property['OutputImage'] = func_get_arg(0);
}
public function ImageWidth()
{
if (func_num_args() == 0 ) return $this->property['ImageWidth'];
if (func_num_args() == 1 ) $this->property['ImageWidth'] = func_get_arg(0);
}
public function ImageHeight()
{
if (func_num_args() == 0 ) return $this->property['ImageHeight'];
if (func_num_args() == 1 ) $this->property['ImageHeight'] = func_get_arg(0);
}
public function MarginTop()
{
if (func_num_args() == 0 ) return $this->property['tmargin'];
if (func_num_args() == 1 ) $this->property['tmargin'] = func_get_arg(0);
}
public function MarginBottom()
{
if (func_num_args() == 0 ) return $this->property['bmargin'];
if (func_num_args() == 1 ) $this->property['tmargin'] = func_get_arg(0);
}
public function MarginLeft()
{
if (func_num_args() == 0 ) return $this->property['lmargin'];
if (func_num_args() == 1 ) $this->property['tmargin'] = func_get_arg(0);
}
public function MarginRight()
{
if (func_num_args() == 0 ) return $this->property['rmargin'];
if (func_num_args() == 1 ) $this->property['tmargin'] = func_get_arg(0);
}
public function YScaleInterval()
{
if (func_num_args() == 0 ) return $this->property['YScaleInterval'];
if (func_num_args() == 1 ) $this->property['YScaleInterval'] = func_get_arg(0);
}
public function YScaleTextRotate()
{
if (func_num_args() == 0 ) return $this->property['YScaleTextRotate'];
if (func_num_args() == 1 ) $this->property['YScaleTextRotate'] = func_get_arg(0);
}
public function YScaleLabel()
{
if (func_num_args() == 0 ) return $this->property['YScaleLabel'];
if (func_num_args() == 1 ) $this->property['YScaleLabel'] = func_get_arg(0);
}
public function YScaleFormat()
{
if (func_num_args() == 0 ) return $this->property['YScaleFormat'];
if (func_num_args() == 1 ) $this->property['YScaleFormat'] = func_get_arg(0);
}
public function XScaleInterval()
{
if (func_num_args() == 0 ) return $this->property['XScaleInterval'];
if (func_num_args() == 1 ) $this->property['XScaleInterval'] = func_get_arg(0);
}
public function XScaleTextRotate()
{
if (func_num_args() == 0 ) return $this->property['XScaleTextRotate'];
if (func_num_args() == 1 ) $this->property['XScaleTextRotate'] = func_get_arg(0);
}
public function XScaleLabel()
{
if (func_num_args() == 0 ) return $this->property['XScaleLabel'];
if (func_num_args() == 1 ) $this->property['XScaleLabel'] = func_get_arg(0);
}
public function XScaleFormat()
{
if (func_num_args() == 0 ) return $this->property['XScaleFormat'];
if (func_num_args() == 1 ) $this->property['XScaleFormat'] = func_get_arg(0);
}
public function Title()
{
if (func_num_args() == 0 ) return $this->property['Title'];
if (func_num_args() == 1 ) $this->property['Title'] = func_get_arg(0);
}
public function SubTitle()
{
if (func_num_args() == 0 ) return $this->property['SubTitle'];
if (func_num_args() == 1 ) $this->property['SubTitle'] = func_get_arg(0);
}
private function FullTitle()
{
$result = "";
$result .= ($this->Title() == "") ? "" : $this->Title();
if (($this->Title() != "") && ($this->SubTitle() != ""))
$result .= "\\n"; //** add CR after title if it's not empty and we have a substtitle
$result .= ($this->SubTitle() == "") ? "" : $this->SubTitle();
$result = str_replace('_', '-', $result);
return $result ;
}
public function XRangeStart()
{
if (func_num_args() == 0 ) return $this->property['XRangeStart'];
if (func_num_args() == 1 ) $this->property['XRangeStart'] = func_get_arg(0);
}
public function XRangeEnd()
{
if (func_num_args() == 0 ) return $this->property['XRangeEnd'];
if (func_num_args() == 1 ) $this->property['XRangeEnd'] = func_get_arg(0);
}
private function XRangeAsString()
{
return $this->XRangeStart()." : ".$this->XRangeEnd();
}
public function YRangeStart()
{
if (func_num_args() == 0 ) return $this->property['YRangeStart'];
if (func_num_args() == 1 ) $this->property['YRangeStart'] = func_get_arg(0);
}
public function YRangeEnd()
{
if (func_num_args() == 0 ) return $this->property['YRangeEnd'];
if (func_num_args() == 1 ) $this->property['YRangeEnd'] = func_get_arg(0);
}
private function YRangeAsString()
{
return $this->YRangeStart()." : ".$this->YRangeEnd();
}
public function DotSize()
{
if (func_num_args() == 0 ) return $this->property['DotSize'];
if (func_num_args() == 1 ) $this->property['DotSize'] = func_get_arg(0);
}
public function DotType()
{
if (func_num_args() == 0 ) return $this->property['DotType'];
if (func_num_args() == 1 ) $this->property['DotType'] = func_get_arg(0);
}
public function AddSpline()
{
if (func_num_args() == 0 ) return $this->property['AddSpline'];
if (func_num_args() == 1 ) $this->property['AddSpline'] = func_get_arg(0);
}
public function AddBezier()
{
if (func_num_args() == 0 ) return $this->property['AddBezier'];
if (func_num_args() == 1 ) $this->property['AddBezier'] = func_get_arg(0);
}
public function Properties()
{
return $this->property;
}
public function toString()
{
$result = "";
foreach ($this->property as $key => $value) {
$result .= "$key => $value\n";
}
return $result;
}
}
?> | jcu-eresearch/TDH-Tools | Utilities/gnuplot.class.php | PHP | bsd-3-clause | 13,155 |
<?php
namespace backend\controllers;
use Yii;
use common\models\Locations;
use common\models\SearchLocations;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
class LocationsController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
public function actionIndex()
{
$searchModel = new SearchLocations;
$dataProvider = $searchModel->search(Yii::$app->request->getQueryParams());
return $this->render('index', [
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
]);
}
public function actionCreate()
{
$model = new Locations;
if ($model->load(Yii::$app->request->post())) {
if ($model->validate()) {
if($model->save()) {
\Yii::$app->getSession()->setFlash('admin_flash_message', 'Позиция добавлена');
return $this->redirect(['index']);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
public function actionCreateraion($location_id)
{
$model = new \common\models\LocationsRaion;
$model->location_id = $location_id;
if ($model->load(Yii::$app->request->post())) {
if ($model->validate()) {
if($model->save()) {
\Yii::$app->getSession()->setFlash('admin_flash_message', 'Позиция добавлена');
return $this->redirect(['update', 'id' => $model->location_id]);
}
} else {
return $this->render('createraion', [
'model' => $model,
]);
}
} else {
return $this->render('createraion', [
'model' => $model,
]);
}
}
public function actionCreatestreet($location_id)
{
$model = new \common\models\LocationsStreet;
$model->location_id = $location_id;
if ($model->load(Yii::$app->request->post())) {
if ($model->validate()) {
if($model->save()) {
\Yii::$app->getSession()->setFlash('admin_flash_message', 'Позиция добавлена');
return $this->redirect(['update', 'id' => $model->location_id]);
}
} else {
return $this->render('createstreet', [
'model' => $model,
]);
}
} else {
return $this->render('createstreet', [
'model' => $model,
]);
}
}
public function actionUpdateraion($id)
{
$model = $this->findModelRaion($id);
if ($model->load(Yii::$app->request->post())) {
if ($model->validate()) {
if($model->save()) {
\Yii::$app->getSession()->setFlash('admin_flash_message', 'Позиция изменена');
return $this->redirect(['update', 'id' => $model->location_id]);
}
} else {
return $this->render('updateraion', [
'model' => $model,
]);
}
} else {
return $this->render('updateraion', [
'model' => $model,
]);
}
}
public function actionUpdatestreet($id)
{
$model = $this->findModelStreet($id);
if ($model->load(Yii::$app->request->post())) {
if ($model->validate()) {
if($model->save()) {
\Yii::$app->getSession()->setFlash('admin_flash_message', 'Позиция изменена');
return $this->redirect(['update', 'id' => $model->location_id]);
}
} else {
return $this->render('updatestreet', [
'model' => $model,
]);
}
} else {
return $this->render('updatestreet', [
'model' => $model,
]);
}
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
$searchModelRaion = new \common\models\SearchLocationsRaion;
$dataProviderRaion = $searchModelRaion->search(Yii::$app->request->getQueryParams());
$searchModelStreet = new \common\models\SearchLocationsStreet;
$dataProviderStreet = $searchModelStreet->search(Yii::$app->request->getQueryParams());
if ($model->load(Yii::$app->request->post())) {
if ($model->validate()) {
if($model->save()) {
\Yii::$app->getSession()->setFlash('admin_flash_message', 'Позиция изменена');
return $this->redirect(['index']);
}
} else {
return $this->render('update', [
'model' => $model,
'dataProviderRaion' => $dataProviderRaion,
'searchModelRaion' => $searchModelRaion,
'dataProviderStreet' => $dataProviderStreet,
'searchModelStreet' => $searchModelStreet,
]);
}
} else {
return $this->render('update', [
'model' => $model,
'dataProviderRaion' => $dataProviderRaion,
'searchModelRaion' => $searchModelRaion,
'dataProviderStreet' => $dataProviderStreet,
'searchModelStreet' => $searchModelStreet,
]);
}
}
public function actionDelete($id)
{
$model = $this->findModel($id);
$model->delete();
\Yii::$app->getSession()->setFlash('admin_flash_message', 'Позиция удалена');
return $this->redirect(['index']);
}
public function actionDeleteraion($id)
{
$model = $this->findModelRaion($id);
$model->delete();
\Yii::$app->getSession()->setFlash('admin_flash_message', 'Позиция удалена');
return $this->redirect(['update', 'id' => $model->location_id]);
}
public function actionDeletestreet($id)
{
$model = $this->findModelStreet($id);
$model->delete();
\Yii::$app->getSession()->setFlash('admin_flash_message', 'Позиция удалена');
return $this->redirect(['update', 'id' => $model->location_id]);
}
protected function findModel($id)
{
if (($model = Locations::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
protected function findModelRaion($id)
{
if (($model = \common\models\LocationsRaion::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
protected function findModelStreet($id)
{
if (($model = \common\models\LocationsStreet::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
| alaevka/olam | backend/controllers/LocationsController.php | PHP | bsd-3-clause | 7,853 |
/*================================================================================
Copyright (c) 2012 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
public enum GuestOsDescriptorSupportLevel {
experimental ("experimental"),
legacy ("legacy"),
terminated ("terminated"),
supported ("supported"),
unsupported ("unsupported"),
deprecated ("deprecated"),
techPreview ("techPreview");
@SuppressWarnings("unused")
private final String val;
private GuestOsDescriptorSupportLevel(String val)
{
this.val = val;
}
} | xebialabs/vijava | src/com/vmware/vim25/GuestOsDescriptorSupportLevel.java | Java | bsd-3-clause | 2,126 |
//---------------------------------------------------------------------------//
/*
Copyright (c) 2012, Stuart R. Slattery
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
*: Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
*: Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
*: Neither the name of the University of Wisconsin - Madison nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//---------------------------------------------------------------------------//
/*!
* \file tstSTKMeshEntityLocalMap.cpp
* \author Stuart R. Slattery
* \brief STKMeshEntityLocalMap unit tests.
*/
//---------------------------------------------------------------------------//
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <vector>
#include <DTK_STKMeshEntity.hpp>
#include <DTK_STKMeshEntityLocalMap.hpp>
#include <Teuchos_Array.hpp>
#include <Teuchos_ArrayRCP.hpp>
#include <Teuchos_CommHelpers.hpp>
#include <Teuchos_DefaultComm.hpp>
#include <Teuchos_DefaultMpiComm.hpp>
#include <Teuchos_OpaqueWrapper.hpp>
#include <Teuchos_RCP.hpp>
#include <Teuchos_Tuple.hpp>
#include <Teuchos_TypeTraits.hpp>
#include <Teuchos_UnitTestHarness.hpp>
#include <stk_mesh/base/BulkData.hpp>
#include <stk_mesh/base/CoordinateSystems.hpp>
#include <stk_mesh/base/Field.hpp>
#include <stk_mesh/base/FieldBase.hpp>
#include <stk_mesh/base/MetaData.hpp>
#include <stk_topology/topology.hpp>
//---------------------------------------------------------------------------//
// MPI Setup
//---------------------------------------------------------------------------//
template <class Ordinal>
Teuchos::RCP<const Teuchos::Comm<Ordinal>> getDefaultComm()
{
#ifdef HAVE_MPI
return Teuchos::DefaultComm<Ordinal>::getComm();
#else
return Teuchos::rcp( new Teuchos::SerialComm<Ordinal>() );
#endif
}
//---------------------------------------------------------------------------//
// Hex-8 test.
TEUCHOS_UNIT_TEST( STKMeshEntity, hex_8_test )
{
// Extract the raw mpi communicator.
Teuchos::RCP<const Teuchos::Comm<int>> comm = getDefaultComm<int>();
Teuchos::RCP<const Teuchos::MpiComm<int>> mpi_comm =
Teuchos::rcp_dynamic_cast<const Teuchos::MpiComm<int>>( comm );
Teuchos::RCP<const Teuchos::OpaqueWrapper<MPI_Comm>> opaque_comm =
mpi_comm->getRawMpiComm();
MPI_Comm raw_comm = ( *opaque_comm )();
// Create meta data.
int space_dim = 3;
stk::mesh::MetaData meta_data( space_dim );
// Make two parts.
std::string p1_name = "part_1";
stk::mesh::Part &part_1 = meta_data.declare_part( p1_name );
stk::mesh::set_topology( part_1, stk::topology::HEX_8 );
// Make a coordinate field.
stk::mesh::Field<double, stk::mesh::Cartesian3d> &coord_field =
meta_data
.declare_field<stk::mesh::Field<double, stk::mesh::Cartesian3d>>(
stk::topology::NODE_RANK, "coordinates" );
meta_data.set_coordinate_field( &coord_field );
stk::mesh::put_field( coord_field, part_1 );
meta_data.commit();
// Create bulk data.
Teuchos::RCP<stk::mesh::BulkData> bulk_data =
Teuchos::rcp( new stk::mesh::BulkData( meta_data, raw_comm ) );
bulk_data->modification_begin();
// Make a hex-8.
int comm_rank = comm->getRank();
stk::mesh::EntityId hex_id = 23 + comm_rank;
stk::mesh::Entity hex_entity =
bulk_data->declare_entity( stk::topology::ELEM_RANK, hex_id, part_1 );
int num_nodes = 8;
Teuchos::Array<stk::mesh::EntityId> node_ids( num_nodes );
Teuchos::Array<stk::mesh::Entity> nodes( num_nodes );
for ( int i = 0; i < num_nodes; ++i )
{
node_ids[i] = num_nodes * comm_rank + i + 5;
nodes[i] = bulk_data->declare_entity( stk::topology::NODE_RANK,
node_ids[i], part_1 );
bulk_data->declare_relation( hex_entity, nodes[i], i );
}
bulk_data->modification_end();
// Create the node coordinates.
double *node_coords = 0;
node_coords = stk::mesh::field_data( coord_field, nodes[0] );
node_coords[0] = 0.0;
node_coords[1] = 0.0;
node_coords[2] = 0.0;
node_coords = stk::mesh::field_data( coord_field, nodes[1] );
node_coords[0] = 2.0;
node_coords[1] = 0.0;
node_coords[2] = 0.0;
node_coords = stk::mesh::field_data( coord_field, nodes[2] );
node_coords[0] = 2.0;
node_coords[1] = 2.0;
node_coords[2] = 0.0;
node_coords = stk::mesh::field_data( coord_field, nodes[3] );
node_coords[0] = 0.0;
node_coords[1] = 2.0;
node_coords[2] = 0.0;
node_coords = stk::mesh::field_data( coord_field, nodes[4] );
node_coords[0] = 0.0;
node_coords[1] = 0.0;
node_coords[2] = 2.0;
node_coords = stk::mesh::field_data( coord_field, nodes[5] );
node_coords[0] = 2.0;
node_coords[1] = 0.0;
node_coords[2] = 2.0;
node_coords = stk::mesh::field_data( coord_field, nodes[6] );
node_coords[0] = 2.0;
node_coords[1] = 2.0;
node_coords[2] = 2.0;
node_coords = stk::mesh::field_data( coord_field, nodes[7] );
node_coords[0] = 0.0;
node_coords[1] = 2.0;
node_coords[2] = 2.0;
// Create a local map from the bulk data.
Teuchos::RCP<DataTransferKit::EntityLocalMap> local_map =
Teuchos::rcp( new DataTransferKit::STKMeshEntityLocalMap( bulk_data ) );
// Create a DTK entity for the hex.
DataTransferKit::Entity dtk_entity =
DataTransferKit::STKMeshEntity( hex_entity, bulk_data.ptr() );
// Test the measure.
TEST_EQUALITY( local_map->measure( dtk_entity ), 8.0 );
// Test the centroid.
Teuchos::Array<double> centroid( space_dim, 0.0 );
local_map->centroid( dtk_entity, centroid() );
TEST_EQUALITY( centroid[0], 1.0 );
TEST_EQUALITY( centroid[1], 1.0 );
TEST_EQUALITY( centroid[2], 1.0 );
// Make a good point and a bad point.
Teuchos::Array<double> good_point( space_dim );
good_point[0] = 0.5;
good_point[1] = 1.5;
good_point[2] = 1.0;
Teuchos::Array<double> bad_point( space_dim );
bad_point[0] = 0.75;
bad_point[1] = -1.75;
bad_point[2] = 0.35;
// Test the reference frame safeguard.
TEST_ASSERT(
local_map->isSafeToMapToReferenceFrame( dtk_entity, good_point() ) );
TEST_ASSERT(
!local_map->isSafeToMapToReferenceFrame( dtk_entity, bad_point() ) );
// Test the mapping to reference frame.
Teuchos::Array<double> ref_good_point( space_dim );
bool good_map = local_map->mapToReferenceFrame( dtk_entity, good_point(),
ref_good_point() );
TEST_ASSERT( good_map );
TEST_EQUALITY( ref_good_point[0], -0.5 );
TEST_EQUALITY( ref_good_point[1], 0.5 );
TEST_EQUALITY( ref_good_point[2], 0.0 );
Teuchos::Array<double> ref_bad_point( space_dim );
bool bad_map = local_map->mapToReferenceFrame( dtk_entity, bad_point(),
ref_bad_point() );
TEST_ASSERT( bad_map );
// Test the point inclusion.
TEST_ASSERT(
local_map->checkPointInclusion( dtk_entity, ref_good_point() ) );
TEST_ASSERT(
!local_map->checkPointInclusion( dtk_entity, ref_bad_point() ) );
// Test the map to physical frame.
Teuchos::Array<double> phy_good_point( space_dim );
local_map->mapToPhysicalFrame( dtk_entity, ref_good_point(),
phy_good_point() );
TEST_EQUALITY( good_point[0], phy_good_point[0] );
TEST_EQUALITY( good_point[1], phy_good_point[1] );
TEST_EQUALITY( good_point[2], phy_good_point[2] );
Teuchos::Array<double> phy_bad_point( space_dim );
local_map->mapToPhysicalFrame( dtk_entity, ref_bad_point(),
phy_bad_point() );
TEST_EQUALITY( bad_point[0], phy_bad_point[0] );
TEST_EQUALITY( bad_point[1], phy_bad_point[1] );
TEST_EQUALITY( bad_point[2], phy_bad_point[2] );
// Test the coordinates of the points extracted through the centroid
// function.
DataTransferKit::Entity dtk_node;
Teuchos::Array<double> point_coords( space_dim );
for ( int n = 0; n < num_nodes; ++n )
{
dtk_node = DataTransferKit::STKMeshEntity( nodes[n], bulk_data.ptr() );
local_map->centroid( dtk_node, point_coords() );
node_coords = stk::mesh::field_data( coord_field, nodes[n] );
TEST_EQUALITY( node_coords[0], point_coords[0] );
TEST_EQUALITY( node_coords[1], point_coords[1] );
TEST_EQUALITY( node_coords[2], point_coords[2] );
}
}
//---------------------------------------------------------------------------//
// end tstSTKMeshEntityLocalMap.cpp
//---------------------------------------------------------------------------//
| amccaskey/DataTransferKit | packages/Adapters/STKMesh/test/tstSTKMeshEntityLocalMap.cpp | C++ | bsd-3-clause | 10,037 |
class Instance < ActiveRecord::Base
has_many :user_instances, :conditions => "active = 1"
has_many :squares
has_many :events
has_many :deeds
has_one :setting
end
| jwhitmire/llor-nu-legacy | app/models/instance.rb | Ruby | bsd-3-clause | 174 |
# vim:ts=4:sw=4:expandtab
"""A mongodb client library for Diesel"""
# needed to make diesel work with python 2.5
from __future__ import with_statement
import itertools
import struct
from collections import deque
from diesel import Client, call, sleep, send, receive, first, Loop, Application, ConnectionClosed
from bson import BSON, _make_c_string, decode_all
from bson.son import SON
_ZERO = "\x00\x00\x00\x00"
HEADER_SIZE = 16
class MongoOperationalError(Exception): pass
def _full_name(parent, child):
return "%s.%s" % (parent, child)
class TraversesCollections(object):
def __init__(self, name, client):
self.name = name
self.client = client
def __getattr__(self, name):
return self[name]
def __getitem__(self, name):
cls = self.client.collection_class or Collection
return cls(_full_name(self.name, name), self.client)
class Db(TraversesCollections):
pass
class Collection(TraversesCollections):
def find(self, spec=None, fields=None, skip=0, limit=0):
return MongoCursor(self.name, self.client, spec, fields, skip, limit)
def update(self, spec, doc, upsert=False, multi=False, safe=True):
return self.client.update(self.name, spec, doc, upsert, multi, safe)
def insert(self, doc_or_docs, safe=True):
return self.client.insert(self.name, doc_or_docs, safe)
def delete(self, spec, safe=True):
return self.client.delete(self.name, spec, safe)
class MongoClient(Client):
collection_class = None
def __init__(self, host='localhost', port=27017, **kw):
Client.__init__(self, host, port, **kw)
self._msg_id_counter = itertools.count(1)
@property
def _msg_id(self):
return self._msg_id_counter.next()
def _put_request_get_response(self, op, data):
self._put_request(op, data)
header = receive(HEADER_SIZE)
length, id, to, code = struct.unpack('<4i', header)
message = receive(length - HEADER_SIZE)
cutoff = struct.calcsize('<iqii')
flag, cid, start, numret = struct.unpack('<iqii', message[:cutoff])
body = decode_all(message[cutoff:])
return (cid, start, numret, body)
def _put_request(self, op, data):
req = struct.pack('<4i', HEADER_SIZE + len(data), self._msg_id, 0, op)
send("%s%s" % (req, data))
def _handle_response(self, cursor, resp):
cid, start, numret, result = resp
cursor.retrieved += numret
cursor.id = cid
if not cid or (cursor.retrieved == cursor.limit):
cursor.finished = True
return result
@call
def query(self, cursor):
op = Ops.OP_QUERY
c = cursor
msg = Ops.query(c.col, c.spec, c.fields, c.skip, c.limit)
resp = self._put_request_get_response(op, msg)
return self._handle_response(cursor, resp)
@call
def get_more(self, cursor):
limit = 0
if cursor.limit:
if cursor.limit > cursor.retrieved:
limit = cursor.limit - cursor.retrieved
else:
cursor.finished = True
if not cursor.finished:
op = Ops.OP_GET_MORE
msg = Ops.get_more(cursor.col, limit, cursor.id)
resp = self._put_request_get_response(op, msg)
return self._handle_response(cursor, resp)
else:
return []
def _put_gle_command(self):
msg = Ops.query('admin.$cmd', {'getlasterror' : 1}, 0, 0, -1)
res = self._put_request_get_response(Ops.OP_QUERY, msg)
_, _, _, r = res
doc = r[0]
if doc.get('err'):
raise MongoOperationalError(doc['err'])
return doc
@call
def update(self, col, spec, doc, upsert=False, multi=False, safe=True):
data = Ops.update(col, spec, doc, upsert, multi)
self._put_request(Ops.OP_UPDATE, data)
if safe:
return self._put_gle_command()
@call
def insert(self, col, doc_or_docs, safe=True):
data = Ops.insert(col, doc_or_docs)
self._put_request(Ops.OP_INSERT, data)
if safe:
return self._put_gle_command()
@call
def delete(self, col, spec, safe=True):
data = Ops.delete(col, spec)
self._put_request(Ops.OP_DELETE, data)
if safe:
return self._put_gle_command()
@call
def drop_database(self, name):
return self._command(name, {'dropDatabase':1})
@call
def list_databases(self):
result = self._command('admin', {'listDatabases':1})
return [(d['name'], d['sizeOnDisk']) for d in result['databases']]
@call
def _command(self, dbname, command):
msg = Ops.query('%s.$cmd' % dbname, command, None, 0, 1)
resp = self._put_request_get_response(Ops.OP_QUERY, msg)
cid, start, numret, result = resp
if result:
return result[0]
else:
return []
def __getattr__(self, name):
return Db(name, self)
class Ops(object):
ASCENDING = 1
DESCENDING = -1
OP_UPDATE = 2001
OP_INSERT = 2002
OP_GET_BY_OID = 2003
OP_QUERY = 2004
OP_GET_MORE = 2005
OP_DELETE = 2006
OP_KILL_CURSORS = 2007
@staticmethod
def query(col, spec, fields, skip, limit):
data = [
_ZERO,
_make_c_string(col),
struct.pack('<ii', skip, limit),
BSON.encode(spec or {}),
]
if fields:
if type(fields) == dict:
data.append(BSON.encode(fields))
else:
data.append(BSON.encode(dict.fromkeys(fields, 1)))
return "".join(data)
@staticmethod
def get_more(col, limit, id):
data = _ZERO
data += _make_c_string(col)
data += struct.pack('<iq', limit, id)
return data
@staticmethod
def update(col, spec, doc, upsert, multi):
colname = _make_c_string(col)
flags = 0
if upsert:
flags |= 1 << 0
if multi:
flags |= 1 << 1
fmt = '<i%dsi' % len(colname)
part = struct.pack(fmt, 0, colname, flags)
return "%s%s%s" % (part, BSON.encode(spec), BSON.encode(doc))
@staticmethod
def insert(col, doc_or_docs):
try:
doc_or_docs.fromkeys
doc_or_docs = [doc_or_docs]
except AttributeError:
pass
doc_data = "".join(BSON.encode(doc) for doc in doc_or_docs)
colname = _make_c_string(col)
return "%s%s%s" % (_ZERO, colname, doc_data)
@staticmethod
def delete(col, spec):
colname = _make_c_string(col)
return "%s%s%s%s" % (_ZERO, colname, _ZERO, BSON.encode(spec))
class MongoIter(object):
def __init__(self, cursor):
self.cursor = cursor
self.cache = deque()
def next(self):
try:
return self.cache.popleft()
except IndexError:
more = self.cursor.more()
if not more:
raise StopIteration()
else:
self.cache.extend(more)
return self.next()
class MongoCursor(object):
def __init__(self, col, client, spec, fields, skip, limit):
self.col = col
self.client = client
self.spec = spec
self.fields = fields
self.skip = skip
self.limit = limit
self.id = None
self.retrieved = 0
self.finished = False
self._query_additions = []
def more(self):
if not self.retrieved:
self._touch_query()
if not self.id and not self.finished:
return self.client.query(self)
elif not self.finished:
return self.client.get_more(self)
def all(self):
return list(self)
def __iter__(self):
return MongoIter(self)
def one(self):
all = self.all()
la = len(all)
if la == 1:
res = all[0]
elif la == 0:
res = None
else:
raise ValueError("Cursor returned more than 1 record")
return res
def count(self):
if self.retrieved:
raise ValueError("can't count an already started cursor")
db, col = self.col.split('.', 1)
l = [('count', col), ('query', self.spec)]
if self.skip:
l.append(('skip', self.skip))
if self.limit:
l.append(('limit', self.limit))
command = SON(l)
result = self.client._command(db, command)
return int(result.get('n', 0))
def sort(self, name, direction):
if self.retrieved:
raise ValueError("can't sort an already started cursor")
key = SON()
key[name] = direction
self._query_additions.append(('sort', key))
return self
def _touch_query(self):
if self._query_additions:
spec = SON({'$query': self.spec or {}})
for k, v in self._query_additions:
if k == 'sort':
ordering = spec.setdefault('$orderby', SON())
ordering.update(v)
self.spec = spec
def __enter__(self):
return self
def __exit__(self, *args, **params):
if self.id and not self.finished:
raise RuntimeError("need to cleanup cursor!")
class RawMongoClient(Client):
"A mongodb client that does the bare minimum to push bits over the wire."
@call
def send(self, data, respond=False):
"""Send raw mongodb data and optionally yield the server's response."""
send(data)
if not respond:
return ''
else:
header = receive(HEADER_SIZE)
length, id, to, opcode = struct.unpack('<4i', header)
body = receive(length - HEADER_SIZE)
return header + body
class MongoProxy(object):
ClientClass = RawMongoClient
def __init__(self, backend_host, backend_port):
self.backend_host = backend_host
self.backend_port = backend_port
def __call__(self, addr):
"""A persistent client<--proxy-->backend connection handler."""
try:
backend = None
while True:
header = receive(HEADER_SIZE)
info = struct.unpack('<4i', header)
length, id, to, opcode = info
body = receive(length - HEADER_SIZE)
resp, info, body = self.handle_request(info, body)
if resp is not None:
# our proxy will respond without talking to the backend
send(resp)
else:
# pass the (maybe modified) request on to the backend
length, id, to, opcode = info
is_query = opcode in [Ops.OP_QUERY, Ops.OP_GET_MORE]
payload = header + body
(backend, resp) = self.from_backend(payload, is_query, backend)
self.handle_response(resp)
except ConnectionClosed:
if backend:
backend.close()
def handle_request(self, info, body):
length, id, to, opcode = info
print "saw request with opcode", opcode
return None, info, body
def handle_response(self, response):
send(response)
def from_backend(self, data, respond, backend=None):
if not backend:
backend = self.ClientClass()
backend.connect(self.backend_host, self.backend_port)
resp = backend.send(data, respond)
return (backend, resp)
| dieseldev/diesel | diesel/protocols/mongodb.py | Python | bsd-3-clause | 11,619 |
<?php
/*
Copyright (c) 2009, Till Brehm, projektfarm Gmbh
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of THConfig nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
function sread() {
$input = fgets(STDIN);
return rtrim($input);
}
function swrite($text = '') {
echo $text;
}
function swriteln($text = '') {
echo $text."\n";
}
function simple_query($query, $answers, $default)
{
$finished = false;
do {
$answers_str = implode(',', $answers);
swrite($query.' ('.$answers_str.') ['.$default.']: ');
$input = sread();
//* Stop the installation
if($input == 'quit') {
swriteln("Installation terminated by user.\n");
die();
}
//* Select the default
if($input == '') {
$answer = $default;
$finished = true;
}
//* Set answer id valid
if(in_array($input, $answers)) {
$answer = $input;
$finished = true;
}
} while ($finished == false);
swriteln();
return $answer;
}
require_once('/usr/local/thconfig/server/lib/config.inc.php');
echo "\n\n".str_repeat('-',80)."\n";
echo "
_____ _ _ ____ __ _ ___ _ _ _
|_ _| | | |/ ___|___ _ __ / _(_) __ _ |_ _|_ __ ___| |_ __ _| | | ___ _ __
| | | |_| | | / _ \| '_ \| |_| |/ _` | | || '_ \/ __| __/ _` | | |/ _ \ '__|
| | | _ | |__| (_) | | | | _| | (_| | | || | | \__ \ || (_| | | | __/ |
|_| |_| |_|\____\___/|_| |_|_| |_|\__, | |___|_| |_|___/\__\__,_|_|_|\___|_|
|___/
";
echo "\n".str_repeat('-',80)."\n";
echo "\n\n>> Update \n\n";
echo "Please choose the update method. For production systems select 'stable'. \nThe update from svn is only for development systems and may break your current setup.\nNote: Update all slave server, before you update master server.\n\n";
$method = simple_query('Select update method', array('stable','svn'), 'stable');
if($method == 'stable') {
$new_version = @file_get_contents('http://www.thconfig.org/downloads/thconfig_version.txt') or die('Unable to retrieve version file.');
$new_version = trim($new_version);
if($new_version != ISPC_APP_VERSION) {
passthru('/usr/local/thconfig/server/scripts/update_from_tgz.sh');
exit;
} else {
echo "There are no updates available for THConfig ".ISPC_APP_VERSION."\n";
}
} else {
passthru('/usr/local/thconfig/server/scripts/update_from_svn.sh');
exit;
}
?> | TR-Host/THConfig | server/scripts/thconfig_update.php | PHP | bsd-3-clause | 3,834 |
<?php
/*
services_iscsitarget_pg_edit.php
Part of NAS4Free (http://www.nas4free.org).
Copyright (c) 2012-2017 The NAS4Free Project <info@nas4free.org>.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the NAS4Free Project.
*/
require 'auth.inc';
require 'guiconfig.inc';
if (isset($_GET['uuid']))
$uuid = $_GET['uuid'];
if (isset($_POST['uuid']))
$uuid = $_POST['uuid'];
$pgtitle = [gtext('Services'),gtext('iSCSI Target'),gtext('Portal Group'), isset($uuid) ? gtext('Edit') : gtext('Add')];
$a_iscsitarget_pg = &array_make_branch($config,'iscsitarget','portalgroup');
if(empty($a_iscsitarget_pg)):
else:
array_sort_key($a_iscsitarget_pg,'tag');
endif;
if (isset($uuid) && (FALSE !== ($cnid = array_search_ex($uuid, $a_iscsitarget_pg, "uuid")))) {
$pconfig['uuid'] = $a_iscsitarget_pg[$cnid]['uuid'];
$pconfig['tag'] = $a_iscsitarget_pg[$cnid]['tag'];
$pconfig['portals'] = "";
$pconfig['comment'] = $a_iscsitarget_pg[$cnid]['comment'];
foreach ($a_iscsitarget_pg[$cnid]['portal'] as $portal) {
$pconfig['portals'] .= $portal."\n";
}
} else {
// Find next unused tag.
$tag = 1;
$a_tags = [];
foreach($a_iscsitarget_pg as $pg)
$a_tags[] = $pg['tag'];
while (true === in_array($tag, $a_tags))
$tag += 1;
$pconfig['uuid'] = uuid();
$pconfig['tag'] = $tag;
$pconfig['portals'] = "";
$pconfig['comment'] = "";
// default portals at first portal group
if (count($config['iscsitarget']['portalgroup']) == 0) {
$use_v4wildcard = 0;
$v4_portals = "";
$use_v6wildcard = 0;
$v6_portals = "";
foreach ($config['interfaces'] as $ifs) {
if (isset($ifs['enable'])) {
if (strcmp("dhcp", $ifs['ipaddr']) != 0) {
$addr = $ifs['ipaddr'];
$v4_portals .= $addr.":3260\n";
} else {
$use_v4wildcard = 1;
}
}
if (isset($ifs['ipv6_enable'])) {
if (strcmp("auto", $ifs['ipv6addr']) != 0) {
$addr = normalize_ipv6addr($ifs['ipv6addr']);
$v6_portals .= "[".$addr."]:3260\n";
} else {
$use_v6wildcard = 1;
}
}
}
if ($use_v4wildcard) {
$v4_portals = "0.0.0.0:3260\n";
}
if ($use_v6wildcard) {
$v6_portals = "[::]:3260\n";
}
$pconfig['portals'] .= $v4_portals;
$pconfig['portals'] .= $v6_portals;
}
}
if ($_POST) {
unset($input_errors);
unset($errormsg);
$pconfig = $_POST;
if (isset($_POST['Cancel']) && $_POST['Cancel']) {
header("Location: services_iscsitarget_pg.php");
exit;
}
// Input validation.
$reqdfields = ['tag'];
$reqdfieldsn = [gtext('Tag Number')];
$reqdfieldst = ['numericint'];
do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors);
do_input_validation_type($_POST, $reqdfields, $reqdfieldsn, $reqdfieldst, $input_errors);
if ($pconfig['tag'] < 1 || $pconfig['tag'] > 65535) {
$input_errors[] = gtext("The tag range is invalid.");
}
// Check for duplicates.
$index = array_search_ex($_POST['tag'], $config['iscsitarget']['portalgroup'], "tag");
if (FALSE !== $index) {
if (!((FALSE !== $cnid) && ($config['iscsitarget']['portalgroup'][$cnid]['uuid'] === $config['iscsitarget']['portalgroup'][$index]['uuid']))) {
$input_errors[] = gtext("This tag already exists.");
}
}
$portals = [];
foreach (explode("\n", $_POST['portals']) as $portal) {
$portal = trim($portal, " \t\r\n");
if (!empty($portal)) {
if (preg_match("/^\[([0-9a-fA-F:]+)\](:([0-9]+))?$/", $portal, $tmp)) {
// IPv6
$addr = normalize_ipv6addr($tmp[1]);
$port = isset($tmp[3]) ? $tmp[3] : 3260;
if (!is_ipv6addr($addr) || $port < 1 || $port > 65535) {
$input_errors[] = sprintf(gtext("The portal '%s' is invalid."), $portal);
}
$portals[] = sprintf("[%s]:%d", $addr, $port);
} else if (preg_match("/^([0-9\.]+)(:([0-9]+))?$/", $portal, $tmp)) {
// IPv4
$addr = $tmp[1];
$port = isset($tmp[3]) ? $tmp[3] : 3260;
if (!is_ipv4addr($addr) || $port < 1 || $port > 65535) {
$input_errors[] = sprintf(gtext("The portal '%s' is invalid."), $portal);
}
$portals[] = sprintf("%s:%d", $addr, $port);
} else {
$input_errors[] = sprintf(gtext("The portal '%s' is invalid."), $portal);
}
}
}
if (count($portals) == 0) {
$input_errors[] = sprintf(gtext("The attribute '%s' is required."), gtext("Portals"));
}
if (empty($input_errors)) {
$iscsitarget_pg = [];
$iscsitarget_pg['uuid'] = $_POST['uuid'];
$iscsitarget_pg['tag'] = $_POST['tag'];
$iscsitarget_pg['comment'] = $_POST['comment'];
$iscsitarget_pg['portal'] = $portals;
if (isset($uuid) && (FALSE !== $cnid)) {
$a_iscsitarget_pg[$cnid] = $iscsitarget_pg;
$mode = UPDATENOTIFY_MODE_MODIFIED;
} else {
$a_iscsitarget_pg[] = $iscsitarget_pg;
$mode = UPDATENOTIFY_MODE_NEW;
}
updatenotify_set("iscsitarget_pg", $mode, $iscsitarget_pg['uuid']);
write_config();
header("Location: services_iscsitarget_pg.php");
exit;
}
}
function expand_ipv6addr($v6addr) {
if (strlen($v6addr) == 0)
return null;
$v6str = $v6addr;
// IPv4 mapped address
$pos = strpos($v6str, ".");
if ($pos !== false) {
$pos = strrpos($v6str, ":");
if ($pos === false) {
return null;
}
$v6lstr = substr($v6str, 0, $pos);
$v6rstr = substr($v6str, $pos + 1);
$v4a = sscanf($v6rstr, "%d.%d.%d.%d");
$v6rstr = sprintf("%02x%02x:%02x%02x",
$v4a[0], $v4a[1], $v4a[2], $v4a[3]);
$v6str = $v6lstr.":".$v6rstr;
}
// replace zero for "::"
$pos = strpos($v6str, "::");
if ($pos !== false) {
$v6lstr = substr($v6str, 0, $pos);
$v6rstr = substr($v6str, $pos + 2);
if (strlen($v6lstr) == 0) {
$v6lstr = "0";
}
if (strlen($v6rstr) == 0) {
$v6rstr = "0";
}
$v6lcnt = strlen(preg_replace("/[^:]/", "", $v6lstr));
$v6rcnt = strlen(preg_replace("/[^:]/", "", $v6rstr));
$v6str = $v6lstr;
$v6ncnt = 8 - ($v6lcnt + 1 + $v6rcnt + 1);
while ($v6ncnt > 0) {
$v6str .= ":0";
$v6ncnt--;
}
$v6str .= ":".$v6rstr;
}
// zero padding
$v6a = explode(":", $v6str);
foreach ($v6a as &$tmp) {
$tmp = str_pad($tmp, 4, "0", STR_PAD_LEFT);
}
unset($tmp);
$v6str = implode(":", $v6a);
return $v6str;
}
function normalize_ipv6addr($v6addr) {
if (strlen($v6addr) == 0)
return null;
$v6str = expand_ipv6addr($v6addr);
// suppress prefix zero
$v6a = explode(":", $v6str);
foreach ($v6a as &$tmp) {
$tmp = preg_replace("/^[0]+/", "", $tmp);
if (strlen($tmp) == 0) {
$tmp = "0";
}
}
$v6str = implode(":", $v6a);
// replace first zero as "::"
$replace_flag = 1;
$found_zero = 0;
$v6a = explode(":", $v6str);
foreach ($v6a as &$tmp) {
if (strcmp($tmp, "0") == 0) {
if ($replace_flag) {
$tmp = "z";
$found_zero++;
}
} else {
if ($found_zero) {
$replace_flag = 0;
}
}
}
unset($tmp);
$v6str = implode(":", $v6a);
if ($found_zero > 1) {
$v6str = preg_replace("/(:?z:?)+/", "::", $v6str);
} else {
$v6str = preg_replace("/(z)+/", "0", $v6str);
}
return $v6str;
}
?>
<?php include 'fbegin.inc';?>
<form action="services_iscsitarget_pg_edit.php" method="post" name="iform" id="iform" onsubmit="spinner()">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td class="tabnavtbl">
<ul id="tabnav">
<li class="tabinact"><a href="services_iscsitarget.php"><span><?=gtext("Settings");?></span></a></li>
<li class="tabinact"><a href="services_iscsitarget_target.php"><span><?=gtext("Targets");?></span></a></li>
<li class="tabact"><a href="services_iscsitarget_pg.php" title="<?=gtext('Reload page');?>"><span><?=gtext("Portals");?></span></a></li>
<li class="tabinact"><a href="services_iscsitarget_ig.php"><span><?=gtext("Initiators");?></span></a></li>
<li class="tabinact"><a href="services_iscsitarget_ag.php"><span><?=gtext("Auths");?></span></a></li>
<li class="tabinact"><a href="services_iscsitarget_media.php"><span><?=gtext("Media");?></span></a></li>
</ul>
</td>
</tr>
<tr>
<td class="tabcont">
<?php if (!empty($input_errors)) print_input_errors($input_errors);?>
<table width="100%" border="0" cellpadding="6" cellspacing="0">
<?php html_titleline(gtext("Portal Group Settings"));?>
<?php html_inputbox("tag", gtext("Tag number"), $pconfig['tag'], gtext("Numeric identifier of the group."), true, 10, (isset($uuid) && (FALSE !== $cnid)));?>
<?php html_textarea("portals", gtext("Portals"), $pconfig['portals'], gtext("The portal takes the form of 'address:port'. for example '192.168.1.1:3260' for IPv4, '[2001:db8:1:1::1]:3260' for IPv6. the port 3260 is standard iSCSI port number. For any IPs (wildcard address), use '0.0.0.0:3260' and/or '[::]:3260'. Do not mix wildcard and other IPs at same address family."), true, 65, 7, false, false);?>
<?php html_inputbox("comment", gtext("Comment"), $pconfig['comment'], gtext("You may enter a description here for your reference."), false, 40);?>
</table>
<div id="submit">
<input name="Submit" type="submit" class="formbtn" value="<?=(isset($uuid) && (FALSE !== $cnid)) ? gtext("Save") : gtext("Add")?>" />
<input name="Cancel" type="submit" class="formbtn" value="<?=gtext("Cancel");?>" />
<input name="uuid" type="hidden" value="<?=$pconfig['uuid'];?>" />
</div>
</td>
</tr>
</table>
<?php include 'formend.inc';?>
</form>
<?php include 'fend.inc';?>
| nas4free/nas4free | www/services_iscsitarget_pg_edit.php | PHP | bsd-3-clause | 10,591 |
#region Copyright
//+ Copyright © David Betz 2007-2017
#endregion
using System.Collections;
namespace Nalarium
{
public class Int32StringMap : Map<int, string>
{
//- @Ctor -//
/// <summary>
/// Initializes a new instance of the <see cref="Int32StringMap" /> class.
/// </summary>
public Int32StringMap()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Int32StringMap" /> class.
/// </summary>
/// <param name="parameterArray">The parameter array.</param>
public Int32StringMap(params Int32StringMapEntry[] parameterArray)
{
AddMapEntrySeries(parameterArray);
}
/// <summary>
/// Initializes a new instance of the <see cref="Int32StringMap" /> class.
/// </summary>
/// <param name="parameterArray">The parameter array.</param>
public Int32StringMap(params string[] parameterArray)
{
AddPairSeries(parameterArray);
}
/// <summary>
/// Initializes a new instance of the <see cref="Int32StringMap" /> class.
/// </summary>
/// <param name="initMap">The init map.</param>
public Int32StringMap(Int32StringMap initMap)
: base(initMap)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Int32StringMap" /> class.
/// </summary>
/// <param name="dictionary">The dictionary.</param>
public Int32StringMap(IDictionary dictionary)
{
if (dictionary != null)
{
foreach (string key in dictionary.Keys)
{
var k = key;
var v = dictionary[key] as string;
//+
if (k != null && v != null)
{
int keyInt32;
if (int.TryParse(k, out keyInt32))
{
Add(keyInt32, v);
}
}
}
}
}
//+
//- Indexer -//
public new string this[int key]
{
get { return base[key]; }
set { base[key] = value; }
}
//+
//- @AddCommaSeries -//
/// <summary>
/// Adds the comma series.
/// </summary>
/// <param name="seriesMapping">The series mapping.</param>
public void AddCommaSeries(string seriesMapping)
{
if (!string.IsNullOrEmpty(seriesMapping))
{
var parts = seriesMapping.Split(',');
if (parts.Length > 0)
{
AddPairSeries(parts);
}
}
}
//- @AddMapEntrySeries -//
/// <summary>
/// Adds the map entry series.
/// </summary>
/// <param name="mapEntryArray">The map entry array.</param>
public void AddMapEntrySeries(Int32StringMapEntry[] mapEntryArray)
{
if (mapEntryArray != null)
{
foreach (var mapEntry in mapEntryArray)
{
AddMapEntry(mapEntry);
}
}
}
//- @AddPairSeries -//
/// <summary>
/// Adds the pair series.
/// </summary>
/// <param name="parameterArray">The parameter array.</param>
public void AddPairSeries(params string[] parameterArray)
{
if (parameterArray != null)
{
foreach (var mapping in parameterArray)
{
AddPair(mapping);
}
}
}
//- @AddPair -//
/// <summary>
/// Adds the pair.
/// </summary>
/// <param name="singleMapping">The single mapping.</param>
public void AddPair(string singleMapping)
{
var name = string.Empty;
var value = string.Empty;
var parts = singleMapping.Split('=');
if (parts.Length == 2)
{
name = parts[0];
value = parts[1];
}
else if (parts.Length == 1)
{
name = parts[0];
value = parts[0];
}
//+
if (!string.IsNullOrEmpty(name))
{
if (!string.IsNullOrEmpty(value))
{
value = value.Trim();
}
int keyInt32;
if (int.TryParse(name.Trim(), out keyInt32))
{
Add(keyInt32, value);
}
}
}
}
} | davidbetz/nalarium | Nalarium/Int32StringMap.cs | C# | bsd-3-clause | 4,849 |
namespace Thinktecture.IdentityServer.Web.ViewModels
{
using System.ComponentModel.DataAnnotations;
public class SetupAccountModel : SignInModel
{
public SetupAccountModel ()
{
}
public SetupAccountModel (SignInModel signInModel)
{
UserName = signInModel.UserName;
Password = signInModel.Password;
ReturnUrl = signInModel.ReturnUrl;
EnableSSO = signInModel.EnableSSO;
}
[Required]
[DataType(DataType.Password)]
[Display(Name = "NewPassword", ResourceType = typeof(Resources.SetupAccountModel))]
public string NewPassword { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "ConfirmPassword", ResourceType = typeof(Resources.SetupAccountModel))]
public string ConfirmPassword { get; set; }
[Required]
public string SecurityAnswer { get; set; }
[Required]
public string SecurityQuestion { get; set; }
}
} | OBHITA/PROCenter | IdentityServer/src/OnPremise/WebSite/ViewModels/SetupAccountModel.cs | C# | bsd-3-clause | 1,059 |
/*
* Copyright (c) 2012, František Haas, Martin Lacina, Jaroslav Kotrč, Jiří Daniel
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package cz.cuni.mff.spl.deploy;
import static org.junit.Assert.fail;
import java.io.File;
import java.util.List;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import cz.cuni.mff.spl.annotation.Info;
import cz.cuni.mff.spl.annotation.Machine;
import cz.cuni.mff.spl.deploy.build.Builder;
import cz.cuni.mff.spl.deploy.build.Sampler;
import cz.cuni.mff.spl.deploy.execution.run.IExecution;
import cz.cuni.mff.spl.deploy.execution.run.LocalExecution;
import cz.cuni.mff.spl.deploy.store.LocalStore;
/**
*
* @author Frantisek Haas
*
*/
public class ConcurrentServerRunTest {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
private final File xml = new File("src/test/projects/test-basic/spl.xml");
@Before
public void init() {
LogManager.getRootLogger().setLevel(Level.FATAL);
}
@Test
public void test()
throws Exception {
LocalStore store = new LocalStore(folder.newFolder("store"));
Builder builder = new Builder(store, new Machine("test", "test"), xml, null, Utils.createTestConfig());
builder.call();
List<Sampler> samplers = builder.getSamplers();
Info info = builder.getInfo();
if (samplers.isEmpty()) {
fail("No sampling code built.");
}
File executionDirectory = store.createTemporaryDirectory("execution");
try (
IExecution e1 = new LocalExecution(info, samplers, executionDirectory, Utils.createTestConfig());
IExecution e2 = new LocalExecution(info, samplers, executionDirectory, Utils.createTestConfig());
IExecution e3 = new LocalExecution(info, samplers, executionDirectory, Utils.createTestConfig());
IExecution e4 = new LocalExecution(info, samplers, executionDirectory, Utils.createTestConfig());
IExecution e5 = new LocalExecution(info, samplers, executionDirectory, Utils.createTestConfig())) {
e1.start();
e2.start();
e3.start();
e4.start();
e5.start();
e1.waitForFinished();
e2.waitForFinished();
e3.waitForFinished();
e4.waitForFinished();
e5.waitForFinished();
if (!e1.isSuccessful() || !e2.isSuccessful() || !e3.isSuccessful() || !e4.isSuccessful() || !e5.isSuccessful()) {
fail("Execution server 1 failed to finish successfully.");
}
}
}
}
| lottie-c/spl_tests_new | src/test/junit/cz/cuni/mff/spl/deploy/ConcurrentServerRunTest.java | Java | bsd-3-clause | 4,240 |
/*L
* Copyright SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/caimage/LICENSE.txt for details.
*/
/**
*
* $Id: NewDropdownUtil.java,v 1.61 2009-05-28 18:49:31 pandyas Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.60 2009/03/13 15:02:04 pandyas
* modified for #19758 Remove the filter from the PI drop-down list on admin (Edit Models) search criteria screen
*
* Revision 1.59 2008/08/27 13:56:42 pandyas
* Updated comments for method
*
* Revision 1.58 2008/08/14 17:09:40 pandyas
* remove debug lines
*
* Revision 1.57 2008/08/12 19:40:31 pandyas
* Fixed #15053 Search for models with transgenic or targeted modification on advanced search page confusing
*
* Revision 1.56 2008/05/21 19:07:43 pandyas
* Modified advanced search to prevent SQL injection
* Converted text entry to dropdown lists for easier validation
* Re: Apps Scan run 05/15/2008
*
* Revision 1.55 2007/10/18 18:28:04 pandyas
* Modified to prevent cross--site scripting attacks
*
* Revision 1.54 2007/10/17 18:36:55 pandyas
* Trying to set constanst for PI list to use in validation of searchForm
*
* Revision 1.53 2007/08/27 15:41:03 pandyas
* hide debug code printout
*
* Revision 1.52 2007/08/07 20:02:45 pandyas
* removed blank in editor and screener admin list until validation is worked out
*
* Revision 1.51 2007/07/31 12:01:20 pandyas
* VCDE silver level and caMOD 2.3 changes
*
* Revision 1.50 2007/05/21 17:37:04 pandyas
* Modified simple and adv search species drop down to pull from DB (approved model species only)
*
* Revision 1.49 2007/03/28 18:03:09 pandyas
* Modified for the following Test Track items:
* #462 - Customized search for carcinogens for Jackson Lab data
* #494 - Advanced search for Carcinogens for Jackson Lab data
*
* Revision 1.48 2006/11/09 17:15:56 pandyas
* Commented out debug
*
* Revision 1.47 2006/10/17 16:10:31 pandyas
* modified during development of caMOD 2.2 - various
*
* Revision 1.46 2006/05/24 18:54:37 georgeda
* Added staining method
*
* Revision 1.45 2006/05/24 16:53:09 pandyas
* Converted StainingMethod to lookup - modified code to pull dropdown list from DB
* All changes from earlier version were merged into this version manually
*
* Revision 1.44 2006/05/23 18:16:38 georgeda
* Removed hardcode of other into species dropdown
*
* Revision 1.43 2006/05/19 16:41:54 pandyas
* Defect #249 - add other to species on the Xenograft screen
*
* Revision 1.42 2006/05/15 15:45:40 georgeda
* Cleaned up contact info management
*
* Revision 1.41 2006/05/10 14:16:14 schroedn
* New Features - Changes from code review
*
* Revision 1.40 2006/04/17 19:08:38 pandyas
* caMod 2.1 OM changes
*
* Revision 1.39 2005/11/29 20:47:21 georgeda
* Removed debug
*
* Revision 1.38 2005/11/16 21:36:40 georgeda
* Defect #47, Clean up EF querying
*
* Revision 1.37 2005/11/16 19:26:30 pandyas
* added javadocs
*
*
*/
package gov.nih.nci.caIMAGE.util;
import gov.nih.nci.caIMAGE.Constants;
//import gov.nih.nci.camod.domain.*;
//import gov.nih.nci.camod.service.*;
//import gov.nih.nci.camod.service.impl.CurationManagerImpl;
//import gov.nih.nci.camod.service.impl.QueryManagerSingleton;
//import gov.nih.nci.common.persistence.Search;
//import gov.nih.nci.camod.service.SpeciesManager;
import gov.nih.nci.caimage.db.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class NewDropdownUtil
{
private static final Log log = LogFactory.getLog(NewDropdownUtil.class);
private static Map ourFileBasedLists = new HashMap();
public static void setup(HttpServletRequest inRequest) throws Exception {
System.out.println("In NewDropdownUtil.setup");
NewDropdownUtil.populateDropdown(inRequest, Constants.Dropdowns.GENDERQUERYDROP,
Constants.Dropdowns.ADD_BLANK_OPTION);
NewDropdownUtil.populateDropdown(inRequest, Constants.Dropdowns.SPECIESQUERYDROP,
Constants.Dropdowns.ADD_BLANK_OPTION);
NewDropdownUtil.populateDropdown(inRequest, Constants.Dropdowns.INSTITUTIONQUERYDROP,
Constants.Dropdowns.ADD_BLANK_OPTION);
NewDropdownUtil.populateDropdown(inRequest, Constants.Dropdowns.PRINCIPALINVESTIGATORDROP,
Constants.Dropdowns.ADD_BLANK_OPTION);
NewDropdownUtil.populateDropdown(inRequest, Constants.Dropdowns.STAININGDROP,
Constants.Dropdowns.ADD_BLANK_OPTION);
NewDropdownUtil.populateDropdown(inRequest, Constants.Dropdowns.STRAINDROP,
Constants.Dropdowns.ADD_BLANK_OPTION);
}
public static void populateDropdown(HttpServletRequest inRequest,
String inDropdownKey,
String inFilter) throws Exception
{
log.debug("Entering NewDropdownUtil.populateDropdown");
log.debug("Generating a dropdown for the following key: " + inDropdownKey);
List theList = null;
if (inDropdownKey.indexOf(".txt") != -1)
{
theList = getTextFileDropdown(inRequest, inDropdownKey);
}
else if (inDropdownKey.indexOf(".db") != -1)
{
theList = getDatabaseDropdown(inRequest, inDropdownKey, inFilter);
}
// Add a blank as the first line
if (Constants.Dropdowns.ADD_BLANK.equals(inFilter))
{
addBlank(theList);
}
// Add a blank as the first line
else if (Constants.Dropdowns.ADD_BLANK_OPTION.equals(inFilter))
{
addBlankOption(theList);
}
// Add a blank as the first line
else if (Constants.Dropdowns.ADD_OTHER.equals(inFilter))
{
addOther(theList);
}
// Add a blank as the first line
else if (Constants.Dropdowns.ADD_OTHER_OPTION.equals(inFilter))
{
addOtherOption(theList);
}
else if (Constants.Dropdowns.ADD_BLANK_AND_OTHER.equals(inFilter))
{
addOther(theList);
addBlank(theList);
}
else if (Constants.Dropdowns.ADD_BLANK_AND_OTHER_OPTION.equals(inFilter))
{
addOtherOption(theList);
addBlankOption(theList);
}
if (theList == null)
{
throw new IllegalArgumentException("Unknown dropdown list key: " + inDropdownKey);
}
inRequest.getSession().setAttribute(inDropdownKey, theList);
log.trace("Exiting NewDropdownUtil.populateDropdown");
}
private static List getDatabaseDropdown(HttpServletRequest inRequest,
String inDropdownKey,
String inFilter) throws Exception
{
log.debug("Entering NewDropdownUtil.getDatabaseDropdown");
List theReturnList = null;
//modified for species from DB
if (inDropdownKey.equals(Constants.Dropdowns.SPECIESQUERYDROP))
{
theReturnList = getQueryOnlySpeciesList(inRequest, inFilter);
log.debug("NewDropdownUtil.getDatabaseDropdown.SpeciesDrop:" + theReturnList.size());
}
else if (inDropdownKey.equals(Constants.Dropdowns.GENDERQUERYDROP))
{
theReturnList = getQueryGenderList(inRequest, inFilter);
log.debug("NewDropdownUtil.getDatabaseDropdown.GenderDrop:" + theReturnList.size());
}
else if (inDropdownKey.equals(Constants.Dropdowns.INSTITUTIONQUERYDROP))
{
theReturnList = getQueryInstitutionList(inRequest, inFilter);
log.debug("NewDropdownUtil.getDatabaseDropdown.InstitutionDrop:" + theReturnList.size());
}
else if (inDropdownKey.equals(Constants.Dropdowns.PRINCIPALINVESTIGATORDROP))
{
theReturnList = getQueryPIList(inRequest, inFilter);
log.debug("NewDropdownUtil.getDatabaseDropdown.PRINCIPALINVESTIGATORDROP:" + theReturnList.size());
}
else if (inDropdownKey.equals(Constants.Dropdowns.STAININGDROP))
{
theReturnList = getQueryStainingList(inRequest, inFilter);
log.debug("NewDropdownUtil.getDatabaseDropdown.STAININGDROP:" + theReturnList.size());
}
else if (inDropdownKey.equals(Constants.Dropdowns.STRAINDROP))
{
theReturnList = getQueryStrainList(inRequest, inFilter);
log.debug("NewDropdownUtil.getDatabaseDropdown.STRAINDROP:" + theReturnList.size());
}
else
{
log.error("No matching dropdown for key: " + inDropdownKey);
theReturnList = new ArrayList<Object>();
}
log.debug("Exiting NewDropdownUtil.getDatabaseDropdown");
return theReturnList;
}
// Get the context so we can get to our managers
private static WebApplicationContext getContext(HttpServletRequest inRequest)
{
return WebApplicationContextUtils.getRequiredWebApplicationContext(inRequest.getSession().getServletContext());
}
// Get a text file dropdown
private static synchronized List getTextFileDropdown(HttpServletRequest inRequest,
String inDropdownKey) throws Exception
{
log.trace("Entering NewDropdownUtil.getTextFileDropdown");
List theReturnList = new ArrayList<Object>();
if (ourFileBasedLists.containsKey(inDropdownKey))
{
log.debug("Dropdown already cached");
List theCachedList = (List) ourFileBasedLists.get(inDropdownKey);
theReturnList.addAll(theCachedList);
}
else
{
String theFilename = inRequest.getSession().getServletContext().getRealPath("/config/dropdowns") + "/" + inDropdownKey;
List theList = readListFromFile(theFilename);
// Built a list. Add to static hash
if (theList.size() != 0)
{
log.debug("Caching new dropdown: " + theList);
ourFileBasedLists.put(inDropdownKey, theList);
theReturnList.addAll(theList);
}
}
log.trace("Exiting NewDropdownUtil.getTextFileDropdown");
return theReturnList;
}
// Read from a file
static private List readListFromFile(String inFilename) throws Exception
{
List theReturnList = new ArrayList<Object>();
log.debug("Filename to read dropdown from: " + inFilename);
BufferedReader in = new BufferedReader(new FileReader(inFilename));
boolean isDropdownOption = false;
String str;
while ((str = in.readLine()) != null)
{
log.debug("readListFromFile method: Reading value from file: " + str);
// It's a DropdownOption file
if (str.indexOf("DROPDOWN_OPTION") > 0)
{
isDropdownOption = true;
}
else if (isDropdownOption == true)
{
StringTokenizer theTokenizer = new StringTokenizer(str);
String theLabel = theTokenizer.nextToken(",");
String theValue = theTokenizer.nextToken(",");
DropdownOption theDropdownOption = new DropdownOption(theLabel, theValue);
theReturnList.add(theDropdownOption);
}
else
{
theReturnList.add(str);
}
}
in.close();
return theReturnList;
}
/**
* Returns a list of all Gender
* Used for submission and search screens
*
* @return genders
* @throws Exception
*/
private static List getQueryGenderList(HttpServletRequest inRequest,
String inAddBlank) throws Exception
{
log.debug("Entering NewDropdownUtil.getQueryGenderList");
// Get values for dropdown lists for Gender
Gender gen = new Gender();
Vector gender = gen.retrieveAllWhere("gender_name IS NOT NULL ORDER BY gender_name");
List<DropdownOption> theReturnList = new ArrayList<DropdownOption>();
for (int j = 0; j < gender.size(); j++) {
Gender Gen = (Gender) gender.elementAt(j);
if (Gen.getGender_id() != null) {
DropdownOption theOption = new DropdownOption(Gen.getGender_name(), Gen.getGender_id().toString());
theReturnList.add(theOption);
}
}
log.debug("Exiting getQueryGenderList.size " + theReturnList.size());
return theReturnList;
}
/**
* Returns a list of all Species
* Used for submission and search screens
*
* @return speciesNames
* @throws Exception
*/
private static List getQueryOnlySpeciesList(HttpServletRequest inRequest,
String inAddBlank) throws Exception
{
log.debug("Entering NewDropdownUtil.getQueryOnlySpeciesList");
Species sp = new Species();
Vector species = sp.retrieveAllWhere("species_name IS NOT NULL ORDER BY species_name");
// Get values for dropdown lists for Species
List<DropdownOption> theReturnList = new ArrayList<DropdownOption>();
for (int j = 0; j < species.size(); j++) {
Species speciesTab = (Species) species.elementAt(j);
if (speciesTab.getSpecies_id() != null) {
DropdownOption theOption = new DropdownOption(speciesTab.getSpecies_name(), speciesTab.getSpecies_id().toString());
theReturnList.add(theOption);
}
}
log.debug("Exiting getQueryOnlySpeciesList.size " + theReturnList.size());
return theReturnList;
}
/**
* Returns a list of all Institution
* Used for submission and search screens
*
* @return Institution
* @throws Exception
*/
private static List getQueryInstitutionList(HttpServletRequest inRequest,
String inAddBlank) throws Exception
{
log.debug("Entering NewDropdownUtil.getQueryInstitutionList");
Annotations annot = new Annotations();
Login login = new Login();
// Get values for dropdown lists for Institution
List<DropdownOption> theReturnList = new ArrayList<DropdownOption>();
Vector logins = login.retrieveAllWhere("loginuid is not null order by pi_name");
Hashtable v1 = new Hashtable();
for (int j = 0; j < logins.size(); j++) {
Login LogIn = (Login) logins.elementAt(j);
if (LogIn.getLoginuid() != null) {
if (LogIn.getInstitute() != null) {
Vector v = annot.retrieveByANNOTATIONS__DONATOR_ID(LogIn.getLoginuid());
if (v.size() != 0) {
DropdownOption theOption = new DropdownOption(LogIn.getInstitute(), LogIn.getInstitute());
theReturnList.add(theOption);
}//if
}//if
}//if
}//for
log.debug("Exiting getQueryInstitutionList.size " + theReturnList.size());
return theReturnList;
}
/**
* Returns a list of all Institution
* Used for submission and search screens
*
* @return Institution
* @throws Exception
*/
private static List getQueryPIList(HttpServletRequest inRequest,
String inAddBlank) throws Exception
{
log.debug("Entering NewDropdownUtil.getQueryPIList");
Annotations annot = new Annotations();
Login login = new Login();
// Get values for dropdown lists for Institution
List<DropdownOption> theReturnList = new ArrayList<DropdownOption>();
Vector logins = login.retrieveAllWhere("loginuid is not null order by pi_name");
Hashtable v1 = new Hashtable();
for (int j = 0; j < logins.size(); j++) {
Login LogIn = (Login) logins.elementAt(j);
if (LogIn.getLoginuid() != null) {
if (LogIn.getInstitute() != null) {
Vector v = annot.retrieveByANNOTATIONS__DONATOR_ID(LogIn.getLoginuid());
if (v.size() != 0) {
DropdownOption theOption = new DropdownOption(LogIn.getPi_name(), LogIn.getLoginuid().toString());
theReturnList.add(theOption);
}//if
}//if
}//if
}//for
log.debug("Exiting getQueryPIList.size " + theReturnList.size());
return theReturnList;
}
/**
* Returns a list of all Staining
* Used for submission and search screens
*
* @return Staining
* @throws Exception
*/
private static List getQueryStainingList(HttpServletRequest inRequest,
String inAddBlank) throws Exception
{
log.debug("Entering NewDropdownUtil.getQueryStainingList");
// Get values for dropdown lists for Staining
List<DropdownOption> theReturnList = new ArrayList<DropdownOption>();
Stain st = new Stain();
Vector stain = st.retrieveAllWhere("stain_name IS NOT NULL ORDER BY stain_description");
for (int j = 0; j < stain.size(); j++) {
Stain St = (Stain) stain.elementAt(j);
if (St.getStain_id() != null) {
DropdownOption theOption = new DropdownOption(St.getStain_description(), St.getStain_id().toString());
theReturnList.add(theOption);
}
}
log.debug("Exiting getQueryStainingList.size " + theReturnList.size());
return theReturnList;
}
/**
* Returns a list of all Strain
* Used for submission and search screens
*
* @return Strain
* @throws Exception
*/
private static List getQueryStrainList(HttpServletRequest inRequest,
String inAddBlank) throws Exception
{
log.debug("Entering NewDropdownUtil.getQueryStrainList");
// Get values for dropdown lists for Strain
List<DropdownOption> theReturnList = new ArrayList<DropdownOption>();
Strain str = new Strain();
Vector strain = str.retrieveAllWhere("strain_name IS NOT NULL ORDER BY strain_name");
for (int j = 0; j < strain.size(); j++) {
Strain Str = (Strain) strain.elementAt(j);
if (Str.getStrain_id() != null) {
DropdownOption theOption = new DropdownOption(Str.getStrain_name(), Str.getStrain_id().toString());
theReturnList.add(theOption);
}
}
log.debug("Exiting getQueryStrainList.size " + theReturnList.size());
return theReturnList;
}
/**
* Add Other to the list in the first spot if it's not already there.
* Removes it and put's it in the first spot if it is.
*/
private static void addOther(List inList)
{
if (!inList.contains(Constants.Dropdowns.OTHER_OPTION))
{
inList.add(0, Constants.Dropdowns.OTHER_OPTION);
}
else
{
inList.remove(Constants.Dropdowns.OTHER_OPTION);
inList.add(0, Constants.Dropdowns.OTHER_OPTION);
}
}
/**
* Add Not Specified to the list in the first spot if it's not already there.
* Removes it and put's it in the second spot if it is.
*/
private static void addNotSpecified(List inList)
{
if (!inList.contains(Constants.Dropdowns.NOT_SPECIFIED_OPTION))
{
inList.add(0, Constants.Dropdowns.NOT_SPECIFIED_OPTION);
}
else
{
inList.remove(Constants.Dropdowns.NOT_SPECIFIED_OPTION);
inList.add(0, Constants.Dropdowns.NOT_SPECIFIED_OPTION);
}
}
/**
* Add Other to the list in the first spot if it's not already there.
* Removes it and put's it in the first spot if it is.
*/
private static void addOtherOption(List inList)
{
DropdownOption theDropdownOption = new DropdownOption(Constants.Dropdowns.OTHER_OPTION, Constants.Dropdowns.OTHER_OPTION);
if (!inList.contains(theDropdownOption))
{
inList.add(0, theDropdownOption);
}
else
{
inList.remove(theDropdownOption);
inList.add(0, theDropdownOption);
}
}
/**
* Add "" to the list in the first spot if it's not already there. Removes
* it and put's it in the first spot if it is.
*/
private static void addBlank(List inList)
{
if (!inList.contains(""))
{
inList.add(0, "");
}
else
{
inList.remove("");
inList.add(0, "");
}
}
/**
* Add "" to the list in the first spot if it's not already there. Removes
* it and put's it in the first spot if it is.
*/
private static void addBlankOption(List inList)
{
DropdownOption theDropdownOption = new DropdownOption("", "");
if (!inList.contains(theDropdownOption))
{
inList.add(0, theDropdownOption);
}
else
{
inList.remove(theDropdownOption);
inList.add(0, theDropdownOption);
}
}
}
| NCIP/caimage | src/gov/nih/nci/caIMAGE/util/NewDropdownUtil.java | Java | bsd-3-clause | 21,978 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/prerender/prerender_tab_helper.h"
#include "base/metrics/histogram.h"
#include "base/string_number_conversions.h"
#include "base/time.h"
#include "chrome/browser/prerender/prerender_histograms.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/prerender/prerender_manager_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/tab_contents/core_tab_helper.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "skia/ext/platform_canvas.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/rect.h"
using content::WebContents;
namespace prerender {
namespace {
enum PAGEVIEW_EVENTS {
PAGEVIEW_EVENT_NEW_URL = 0,
PAGEVIEW_EVENT_TOP_SITE_NEW_URL = 1,
PAGEVIEW_EVENT_LOAD_START = 2,
PAGEVIEW_EVENT_TOP_SITE_LOAD_START = 3,
PAGEVIEW_EVENT_MAX = 4
};
void RecordPageviewEvent(PAGEVIEW_EVENTS event) {
UMA_HISTOGRAM_ENUMERATION("Prerender.PageviewEvents",
event, PAGEVIEW_EVENT_MAX);
}
} // namespace
// Helper class to compute pixel-based stats on the paint progress
// between when a prerendered page is swapped in and when the onload event
// fires.
class PrerenderTabHelper::PixelStats {
public:
explicit PixelStats(PrerenderTabHelper* tab_helper) :
weak_factory_(this),
tab_helper_(tab_helper) {
}
// Reasons why we need to fetch bitmaps: either a prerender was swapped in,
// or a prerendered page has finished loading.
enum BitmapType {
BITMAP_SWAP_IN,
BITMAP_ON_LOAD
};
void GetBitmap(BitmapType bitmap_type, WebContents* web_contents) {
if (bitmap_type == BITMAP_SWAP_IN) {
bitmap_.reset();
bitmap_web_contents_ = web_contents;
}
if (bitmap_type == BITMAP_ON_LOAD && bitmap_web_contents_ != web_contents)
return;
if (!web_contents || !web_contents->GetView() ||
!web_contents->GetRenderViewHost()) {
return;
}
skia::PlatformCanvas* temp_canvas = new skia::PlatformCanvas;
web_contents->GetRenderViewHost()->CopyFromBackingStore(
gfx::Rect(), gfx::Size(), temp_canvas,
base::Bind(&PrerenderTabHelper::PixelStats::HandleBitmapResult,
weak_factory_.GetWeakPtr(),
bitmap_type,
web_contents,
base::Owned(temp_canvas)));
}
private:
void HandleBitmapResult(BitmapType bitmap_type,
WebContents* web_contents,
skia::PlatformCanvas* temp_canvas,
bool succeeded) {
scoped_ptr<SkBitmap> bitmap;
if (succeeded) {
const SkBitmap& canvas_bitmap =
skia::GetTopDevice(*temp_canvas)->accessBitmap(false);
bitmap.reset(new SkBitmap());
canvas_bitmap.copyTo(bitmap.get(), SkBitmap::kARGB_8888_Config);
}
if (bitmap_web_contents_ != web_contents)
return;
if (bitmap_type == BITMAP_SWAP_IN)
bitmap_.swap(bitmap);
if (bitmap_type == BITMAP_ON_LOAD) {
PrerenderManager* prerender_manager =
tab_helper_->MaybeGetPrerenderManager();
if (prerender_manager) {
prerender_manager->histograms()->RecordFractionPixelsFinalAtSwapin(
CompareBitmaps(bitmap_.get(), bitmap.get()));
}
bitmap_.reset();
bitmap_web_contents_ = NULL;
}
}
// Helper comparing two bitmaps of identical size.
// Returns a value < 0.0 if there is an error, and otherwise, a double in
// [0, 1] indicating the fraction of pixels that are the same.
double CompareBitmaps(SkBitmap* bitmap1, SkBitmap* bitmap2) {
if (!bitmap1 || !bitmap2) {
return -2.0;
}
if (bitmap1->width() != bitmap2->width() ||
bitmap1->height() != bitmap2->height()) {
return -1.0;
}
int pixels = bitmap1->width() * bitmap1->height();
int same_pixels = 0;
for (int y = 0; y < bitmap1->height(); ++y) {
for (int x = 0; x < bitmap1->width(); ++x) {
if (bitmap1->getColor(x, y) == bitmap2->getColor(x, y))
same_pixels++;
}
}
return static_cast<double>(same_pixels) / static_cast<double>(pixels);
}
// Bitmap of what the last swapped in prerendered tab looked like at swapin,
// and the WebContents that it was swapped into.
scoped_ptr<SkBitmap> bitmap_;
WebContents* bitmap_web_contents_;
base::WeakPtrFactory<PixelStats> weak_factory_;
PrerenderTabHelper* tab_helper_;
};
PrerenderTabHelper::PrerenderTabHelper(TabContentsWrapper* tab)
: content::WebContentsObserver(tab->web_contents()),
pixel_stats_(new PixelStats(this)),
tab_(tab) {
}
PrerenderTabHelper::~PrerenderTabHelper() {
}
void PrerenderTabHelper::ProvisionalChangeToMainFrameUrl(
const GURL& url,
const GURL& opener_url) {
url_ = url;
RecordPageviewEvent(PAGEVIEW_EVENT_NEW_URL);
if (IsTopSite(url))
RecordPageviewEvent(PAGEVIEW_EVENT_TOP_SITE_NEW_URL);
PrerenderManager* prerender_manager = MaybeGetPrerenderManager();
if (!prerender_manager)
return;
if (prerender_manager->IsWebContentsPrerendering(web_contents()))
return;
prerender_manager->MarkWebContentsAsNotPrerendered(web_contents());
}
void PrerenderTabHelper::DidCommitProvisionalLoadForFrame(
int64 frame_id,
bool is_main_frame,
const GURL& validated_url,
content::PageTransition transition_type) {
if (!is_main_frame)
return;
PrerenderManager* prerender_manager = MaybeGetPrerenderManager();
if (!prerender_manager)
return;
if (prerender_manager->IsWebContentsPrerendering(web_contents()))
return;
prerender_manager->RecordNavigation(validated_url);
}
void PrerenderTabHelper::DidStopLoading() {
// Compute the PPLT metric and report it in a histogram, if needed.
// We include pages that are still prerendering and have just finished
// loading -- PrerenderManager will sort this out and handle it correctly
// (putting those times into a separate histogram).
if (!pplt_load_start_.is_null()) {
double fraction_elapsed_at_swapin = -1.0;
base::TimeTicks now = base::TimeTicks::Now();
if (!actual_load_start_.is_null()) {
double plt = (now - actual_load_start_).InMillisecondsF();
if (plt > 0.0) {
fraction_elapsed_at_swapin = 1.0 -
(now - pplt_load_start_).InMillisecondsF() / plt;
} else {
fraction_elapsed_at_swapin = 1.0;
}
DCHECK_GE(fraction_elapsed_at_swapin, 0.0);
DCHECK_LE(fraction_elapsed_at_swapin, 1.0);
}
PrerenderManager::RecordPerceivedPageLoadTime(
now - pplt_load_start_, fraction_elapsed_at_swapin, web_contents(),
url_);
if (IsPrerendered())
pixel_stats_->GetBitmap(PixelStats::BITMAP_ON_LOAD, web_contents());
}
// Reset the PPLT metric.
pplt_load_start_ = base::TimeTicks();
actual_load_start_ = base::TimeTicks();
}
void PrerenderTabHelper::DidStartProvisionalLoadForFrame(
int64 frame_id,
bool is_main_frame,
const GURL& validated_url,
bool is_error_page,
content::RenderViewHost* render_view_host) {
if (is_main_frame) {
RecordPageviewEvent(PAGEVIEW_EVENT_LOAD_START);
if (IsTopSite(validated_url))
RecordPageviewEvent(PAGEVIEW_EVENT_TOP_SITE_LOAD_START);
// Record the beginning of a new PPLT navigation.
pplt_load_start_ = base::TimeTicks::Now();
actual_load_start_ = base::TimeTicks();
}
}
PrerenderManager* PrerenderTabHelper::MaybeGetPrerenderManager() const {
return PrerenderManagerFactory::GetForProfile(
Profile::FromBrowserContext(web_contents()->GetBrowserContext()));
}
bool PrerenderTabHelper::IsPrerendering() {
PrerenderManager* prerender_manager = MaybeGetPrerenderManager();
if (!prerender_manager)
return false;
return prerender_manager->IsWebContentsPrerendering(web_contents());
}
bool PrerenderTabHelper::IsPrerendered() {
PrerenderManager* prerender_manager = MaybeGetPrerenderManager();
if (!prerender_manager)
return false;
return prerender_manager->IsWebContentsPrerendered(web_contents());
}
void PrerenderTabHelper::PrerenderSwappedIn() {
// Ensure we are not prerendering any more.
DCHECK(!IsPrerendering());
if (pplt_load_start_.is_null()) {
// If we have already finished loading, report a 0 PPLT.
PrerenderManager::RecordPerceivedPageLoadTime(base::TimeDelta(), 1.0,
web_contents(), url_);
PrerenderManager* prerender_manager = MaybeGetPrerenderManager();
if (prerender_manager)
prerender_manager->histograms()->RecordFractionPixelsFinalAtSwapin(1.0);
} else {
// If we have not finished loading yet, record the actual load start, and
// rebase the start time to now.
actual_load_start_ = pplt_load_start_;
pplt_load_start_ = base::TimeTicks::Now();
pixel_stats_->GetBitmap(PixelStats::BITMAP_SWAP_IN, web_contents());
}
}
bool PrerenderTabHelper::IsTopSite(const GURL& url) {
PrerenderManager* pm = MaybeGetPrerenderManager();
return (pm && pm->IsTopSite(url));
}
} // namespace prerender
| robclark/chromium | chrome/browser/prerender/prerender_tab_helper.cc | C++ | bsd-3-clause | 9,431 |
from __future__ import division
import math
from django.db.models import Q
from django.http import Http404
from django.shortcuts import get_object_or_404, render
from django.views.generic.detail import DetailView
from pontoon.base.models import Locale, Project, ProjectLocale, TranslatedResource
from pontoon.base.utils import require_AJAX
from pontoon.contributors.views import ContributorsMixin
def localization(request, code, slug):
"""Locale-project overview."""
locale = get_object_or_404(Locale, code=code)
project = get_object_or_404(Project.objects.available(), slug=slug)
project_locale = get_object_or_404(ProjectLocale, locale=locale, project=project)
resource_count = len(locale.parts_stats(project)) - 1
return render(request, 'localizations/localization.html', {
'locale': locale,
'project': project,
'project_locale': project_locale,
'resource_count': resource_count,
})
@require_AJAX
def ajax_resources(request, code, slug):
"""Resources tab."""
locale = get_object_or_404(Locale, code=code)
project = get_object_or_404(
Project.objects.available().prefetch_related('subpage_set'),
slug=slug
)
# Amend the parts dict with latest activity info.
translatedresources_qs = (
TranslatedResource.objects
.filter(resource__project=project, locale=locale)
.prefetch_related('resource', 'latest_translation__user')
)
if not len(translatedresources_qs):
raise Http404
pages = {}
for page in project.subpage_set.all():
latest_page_translatedresource = None
page_translatedresources_qs = (
TranslatedResource.objects
.filter(resource__in=page.resources.all(), locale=locale)
.prefetch_related('resource', 'latest_translation__user')
)
for page_translatedresource in page_translatedresources_qs:
latest = (
latest_page_translatedresource.latest_translation
if latest_page_translatedresource
else None
)
if (
latest is None or
(
page_translatedresource.latest_translation.latest_activity['date'] >
latest.latest_activity['date']
)
):
latest_page_translatedresource = page_translatedresource
pages[page.name] = latest_page_translatedresource
translatedresources = {s.resource.path: s for s in translatedresources_qs}
translatedresources = dict(translatedresources.items() + pages.items())
parts = locale.parts_stats(project)
for part in parts:
translatedresource = translatedresources.get(part['title'], None)
if translatedresource and translatedresource.latest_translation:
part['latest_activity'] = translatedresource.latest_translation.latest_activity
else:
part['latest_activity'] = None
part['chart'] = {
'translated_strings': part['translated_strings'],
'fuzzy_strings': part['fuzzy_strings'],
'total_strings': part['resource__total_strings'],
'approved_strings': part['approved_strings'],
'approved_share': round(
part['approved_strings'] / part['resource__total_strings'] * 100
),
'translated_share': round(
part['translated_strings'] / part['resource__total_strings'] * 100
),
'fuzzy_share': round(part['fuzzy_strings'] / part['resource__total_strings'] * 100),
'approved_percent': int(
math.floor(part['approved_strings'] / part['resource__total_strings'] * 100)
),
}
return render(request, 'localizations/includes/resources.html', {
'locale': locale,
'project': project,
'resources': parts,
})
class LocalizationContributorsView(ContributorsMixin, DetailView):
"""
Renders view of contributors for the localization.
"""
template_name = 'localizations/includes/contributors.html'
def get_object(self):
return get_object_or_404(
ProjectLocale,
locale__code=self.kwargs['code'],
project__slug=self.kwargs['slug']
)
def get_context_object_name(self, obj):
return 'projectlocale'
def contributors_filter(self, **kwargs):
return Q(
entity__resource__project=self.object.project,
locale=self.object.locale
)
| mastizada/pontoon | pontoon/localizations/views.py | Python | bsd-3-clause | 4,580 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-24 16:13
from __future__ import unicode_literals
from django.db import migrations, models
def add_questions(apps, schema_editor):
current_database = schema_editor.connection.alias
QuestionSubmodels = [
apps.get_model('wizard_builder.SingleLineText'),
apps.get_model('wizard_builder.TextArea'),
apps.get_model('wizard_builder.RadioButton'),
apps.get_model('wizard_builder.Checkbox'),
]
for Model in QuestionSubmodels:
for question in Model.objects.using(current_database):
question_type = question._meta.model_name.lower()
question.type = question_type
question.save()
class Migration(migrations.Migration):
dependencies = [
('wizard_builder', '0028_formquestion_type'),
]
operations = [
migrations.RunPython(
add_questions,
migrations.RunPython.noop,
),
]
| SexualHealthInnovations/django-wizard-builder | wizard_builder/migrations/0029_populate_type.py | Python | bsd-3-clause | 983 |
package main
import (
"flag"
"log"
"os"
"time"
"bottle/debug"
"bottle/shutil"
)
// TODO: Better panic error output (maybe defer shutil.RescueExit()?)
func init() {
// TODO: Add as a "main" command-line flag? (possibly secret...)
debug.ShouldTimeFunctions = false
}
func main() {
defer debug.TimedFunction(time.Now(), "main()")
// Configure logger
log.SetFlags(0)
// Configure cli flags
flag.Usage = printHelp
flag.Parse()
// Parse the command
var command string
args := flag.Args()
if len(args) > 0 {
command = args[0]
args = args[1:]
} else {
flag.Usage()
shutil.Exit(0)
}
// Handle the chosen command
switch command {
case "build":
var flags BuildFlags
build := flag.NewFlagSet("build", flag.ExitOnError)
build.Usage = printHelpBuild
build.StringVar(&flags.outfile, "o", "", "")
build.StringVar(&flags.outdir, "out-dir", "", "")
build.StringVar(&flags.ldflags, "ldflags", "", "")
build.Parse(args)
if len(build.Args()) > 0 {
shutil.Stderr("error: unexpected argument '" + build.Arg(0) + "'\n")
shutil.Exit(1)
}
workdir := shutil.Pwd() // NOTE: changed by syncProject
project := syncProject(workdir)
buildProject(project, workdir, flags)
shutil.Exit(0)
case "exec":
exec := flag.NewFlagSet("exec", flag.ExitOnError)
exec.Usage = printHelpExec
exec.Parse(args)
args := exec.Args()
if len(args) == 0 {
shutil.Stderr("error: missing tool to execute\n")
shutil.Exit(1)
}
workdir := shutil.Pwd() // NOTE: changed by syncProject
project := syncProject(workdir)
execTool(project, args[0], args[1:])
shutil.Exit(0)
case "publish":
var flags PublishFlags
publish := flag.NewFlagSet("publish", flag.ExitOnError)
publish.Usage = printHelpPublish
publish.StringVar(&flags.release, "release", "", "")
publish.Parse(args)
if len(publish.Args()) > 0 {
shutil.Stderr("error: unexpected argument '" + publish.Arg(0) + "'\n")
shutil.Exit(1)
}
workdir := shutil.Pwd() // NOTE: changed by syncProject
project := syncProject(workdir)
publishProject(project, flags)
shutil.Exit(0)
case "which":
var printRoot bool
which := flag.NewFlagSet("which", flag.ExitOnError)
which.Usage = printHelpWhich
which.BoolVar(&printRoot, "root", false, "")
which.Parse(args)
args := which.Args()
if len(args) != 1 {
shutil.Stderr("error: 'which' expects a single path\n")
shutil.Exit(1)
}
// Check the target path
targetPath := args[0]
if !shutil.Exists(targetPath) {
shutil.Stderr("error: the file '" + targetPath + "' does not exist\n")
shutil.Exit(1)
} else if !shutil.IsDirectory(targetPath) && !shutil.IsRegularFile(targetPath) {
shutil.Stderr("error: the file '" + targetPath + "' is not a regular file or directory\n")
shutil.Exit(1)
}
if shutil.IsRegularFile(targetPath) {
targetPath = shutil.Dirname(targetPath)
}
// Find the config file
shutil.Cd(targetPath)
cfg, err := discoverPackage(".", "./Bottle.toml", true)
if err != nil {
shutil.Stderr("error: could not find Bottle.toml or GOPATH\n")
shutil.Stderr(err.Error() + "\n")
shutil.Exit(1)
}
// Output the project information
message := "[" + cfg.Package.Name + "] "
if printRoot {
message += cfg.Package.Root
} else {
message += cfg.Project
}
shutil.Echo(message)
shutil.Exit(0)
case "help":
if len(args) == 0 {
printHelp()
shutil.Exit(0)
}
switch args[0] {
case "build":
printHelpBuild()
case "exec":
printHelpExec()
case "publish":
printHelpPublish()
case "which":
printHelpWhich()
default:
shutil.Stderr("error: unknown help topic '" + command + "'\n")
shutil.Exit(1)
}
shutil.Exit(0)
default:
shutil.Stderr("error: unknown command '" + command + "'\n")
shutil.Stderr(commandDescriptions + "\n")
shutil.Exit(1)
}
shutil.Stderr("error: reached end of main before 'Exit' (this is a bug!)")
shutil.Exit(2) // catch-all
}
func syncProject(pwd string) *Config {
defer debug.TimedFunction(time.Now(), "syncProject("+pwd+")")
// Read the config file
cfg, err := discoverPackage(".", "./Bottle.toml", true)
if err != nil {
shutil.Stderr("error: could not find Bottle.toml or GOPATH\n")
shutil.Stderr(err.Error() + "\n")
shutil.Exit(1)
}
shutil.Cd(cfg.Project)
os.Setenv("GOPATH", cfg.Workspace)
// Discover, fetch, and install dependencies
deps := NewDependencyTracker(cfg)
err = deps.ResolveAll()
if err != nil {
log.Fatal(err)
}
err = deps.InstallAll()
if err != nil {
log.Fatal(err)
}
// Copy this project into the workspace
pathResolver(cfg.Package.Root, cfg.Package.Name, cfg.Workspace)
return cfg
}
| gobottle/bottle | src/main.go | GO | bsd-3-clause | 4,648 |
// Demonstration of a single-threaded client
#include <cstdio>
#include <boost/lexical_cast.hpp>
#include "randexample/randexample.pb.h"
#include "client.hpp"
int main(int argc, char **argv) {
if (argc != 3) {
printf ("usage: %s <nMessage> <nSample>\n", "cmdclient");
return 1;
}
int nMessage = boost::lexical_cast<int>(argv[1]);
int nSample = boost::lexical_cast<int>(argv[2]);
urpc::Client client;
client.connect("tcp://127.0.0.1:5555");
randexample::Request request;
randexample::Reply reply;
request.set_nmessage (nMessage);
request.set_nsample (nSample);
client.sendRequest("Rand", 1, request);
printf("[Rand] (nMesage=%d,nSample=%d)\n", nMessage, nSample);
bool thereIsMore;
do {
thereIsMore = client.getReply (reply);
printf ("Reply block:\n");
for (int i = 0; i < reply.r_size(); i++) {
printf("%f\n", reply.r(i));
}
reply.Clear();
} while (thereIsMore);
return 0;
}
| npalko/uRPC | examples/cpp/cmdclient.cpp | C++ | bsd-3-clause | 959 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from django.core.urlresolvers import reverse
from django.test.client import RequestFactory
from tests.apidocs.util import APIDocsTestCase
class OrganizationStatsDocs(APIDocsTestCase):
def setUp(self):
self.create_event("a", message="oh no")
self.create_event("b", message="oh no")
self.url = reverse(
"sentry-api-0-organization-stats", kwargs={"organization_slug": self.organization.slug},
)
self.login_as(user=self.user)
def test_get(self):
response = self.client.get(self.url)
request = RequestFactory().get(self.url)
self.validate_schema(request, response)
| beeftornado/sentry | tests/apidocs/endpoints/organizations/test-org-stats.py | Python | bsd-3-clause | 716 |
# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Fabian Pedregosa <fabian.pedregosa@inria.fr>
# Olivier Grisel <olivier.grisel@ensta.org>
# Gael Varoquaux <gael.varoquaux@inria.fr>
#
# License: BSD Style.
import sys
import warnings
import itertools
import operator
from abc import ABCMeta, abstractmethod
import numpy as np
from scipy import sparse
from .base import LinearModel
from ..base import RegressorMixin
from .base import sparse_center_data, center_data
from ..utils import array2d, atleast2d_or_csc
from ..cross_validation import check_cv
from ..externals.joblib import Parallel, delayed
from ..utils.extmath import safe_sparse_dot
from . import cd_fast
###############################################################################
# ElasticNet model
class ElasticNet(LinearModel, RegressorMixin):
"""Linear Model trained with L1 and L2 prior as regularizer
Minimizes the objective function::
1 / (2 * n_samples) * ||y - Xw||^2_2 +
+ alpha * l1_ratio * ||w||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
If you are interested in controlling the L1 and L2 penalty
separately, keep in mind that this is equivalent to::
a * L1 + b * L2
where::
alpha = a + b and l1_ratio = a / (a + b)
The parameter l1_ratio corresponds to alpha in the glmnet R package while
alpha corresponds to the lambda parameter in glmnet. Specifically, l1_ratio
= 1 is the lasso penalty. Currently, l1_ratio <= 0.01 is not reliable,
unless you supply your own sequence of alpha.
Parameters
----------
alpha : float
Constant that multiplies the penalty terms. Defaults to 1.0
See the notes for the exact mathematical meaning of this
parameter
alpha = 0 is equivalent to an ordinary least square, solved
by the LinearRegression object in the scikit. For numerical
reasons, using alpha = 0 is with the Lasso object is not advised
and you should prefer the LinearRegression object.
l1_ratio : float
The ElasticNet mixing parameter, with 0 <= l1_ratio <= 1. For
l1_ratio = 0 the penalty is an L2 penalty. For l1_ratio = 1 it is an L1
penalty. For 0 < l1_ratio < 1, the penalty is a combination of L1 and
L2.
fit_intercept: bool
Whether the intercept should be estimated or not. If False, the
data is assumed to be already centered.
normalize : boolean, optional
If True, the regressors X are normalized
precompute : True | False | 'auto' | array-like
Whether to use a precomputed Gram matrix to speed up
calculations. If set to 'auto' let us decide. The Gram
matrix can also be passed as argument. For sparse input
this option is always True to preserve sparsity.
max_iter: int, optional
The maximum number of iterations
copy_X : boolean, optional, default False
If True, X will be copied; else, it may be overwritten.
tol: float, optional
The tolerance for the optimization: if the updates are
smaller than 'tol', the optimization code checks the
dual gap for optimality and continues until it is smaller
than tol.
warm_start : bool, optional
When set to True, reuse the solution of the previous call to fit as
initialization, otherwise, just erase the previous solution.
positive: bool, optional
When set to True, forces the coefficients to be positive.
Attributes
----------
`coef_` : array, shape = (n_features,)
parameter vector (w in the cost function formula)
`sparse_coef_` : scipy.sparse matrix, shape = (n_features, 1)
`sparse_coef_` is a readonly property derived from `coef_`
`intercept_` : float | array, shape = (n_targets,)
independent term in decision function.
`dual_gap_` : float
the current fit is guaranteed to be epsilon-suboptimal with
epsilon := `dual_gap_`
`eps_` : float
`eps_` is used to check if the fit converged to the requested
`tol`
Notes
-----
To avoid unnecessary memory duplication the X argument of the fit method
should be directly passed as a fortran contiguous numpy array.
"""
def __init__(self, alpha=1.0, l1_ratio=0.5, fit_intercept=True,
normalize=False, precompute='auto', max_iter=1000,
copy_X=True, tol=1e-4, warm_start=False, positive=False,
rho=None):
self.alpha = alpha
self.l1_ratio = l1_ratio
if rho is not None:
self.l1_ratio = rho
warnings.warn("rho was renamed to l1_ratio and will be removed "
"in 0.15", DeprecationWarning)
self.coef_ = None
self.fit_intercept = fit_intercept
self.normalize = normalize
self.precompute = precompute
self.max_iter = max_iter
self.copy_X = copy_X
self.tol = tol
self.warm_start = warm_start
self.positive = positive
self.intercept_ = 0.0
def fit(self, X, y, Xy=None, coef_init=None):
"""Fit model with coordinate descent
Parameters
-----------
X: ndarray or scipy.sparse matrix, (n_samples, n_features)
Data
y: ndarray, shape = (n_samples,) or (n_samples, n_targets)
Target
Xy : array-like, optional
Xy = np.dot(X.T, y) that can be precomputed. It is useful
only when the Gram matrix is precomputed.
coef_init: ndarray of shape n_features or (n_targets, n_features)
The initial coeffients to warm-start the optimization
Notes
-----
Coordinate descent is an algorithm that considers each column of
data at a time hence it will automatically convert the X input
as a fortran contiguous numpy array if necessary.
To avoid memory re-allocation it is advised to allocate the
initial data in memory directly using that format.
"""
if self.alpha == 0:
warnings.warn("With alpha=0, this aglorithm does not converge"
"well. You are advised to use the LinearRegression "
"estimator", stacklevel=2)
X = atleast2d_or_csc(X, dtype=np.float64, order='F',
copy=self.copy_X and self.fit_intercept)
# From now on X can be touched inplace
y = np.asarray(y, dtype=np.float64)
# now all computation with X can be done inplace
fit = self._sparse_fit if sparse.isspmatrix(X) else self._dense_fit
fit(X, y, Xy, coef_init)
return self
def _dense_fit(self, X, y, Xy=None, coef_init=None):
# copy was done in fit if necessary
X, y, X_mean, y_mean, X_std = center_data(
X, y, self.fit_intercept, self.normalize, copy=False)
if y.ndim == 1:
y = y[:, np.newaxis]
if Xy is not None and Xy.ndim == 1:
Xy = Xy[:, np.newaxis]
n_samples, n_features = X.shape
n_targets = y.shape[1]
precompute = self.precompute
if hasattr(precompute, '__array__') \
and not np.allclose(X_mean, np.zeros(n_features)) \
and not np.allclose(X_std, np.ones(n_features)):
# recompute Gram
precompute = 'auto'
Xy = None
coef_ = self._init_coef(coef_init, n_features, n_targets)
dual_gap_ = np.empty(n_targets)
eps_ = np.empty(n_targets)
l1_reg = self.alpha * self.l1_ratio * n_samples
l2_reg = self.alpha * (1.0 - self.l1_ratio) * n_samples
# precompute if n_samples > n_features
if hasattr(precompute, '__array__'):
Gram = precompute
elif precompute or (precompute == 'auto' and n_samples > n_features):
Gram = np.dot(X.T, X)
else:
Gram = None
for k in xrange(n_targets):
if Gram is None:
coef_[k, :], dual_gap_[k], eps_[k] = \
cd_fast.enet_coordinate_descent(
coef_[k, :], l1_reg, l2_reg, X, y[:, k], self.max_iter,
self.tol, self.positive)
else:
Gram = Gram.copy()
if Xy is None:
this_Xy = np.dot(X.T, y[:, k])
else:
this_Xy = Xy[:, k]
coef_[k, :], dual_gap_[k], eps_[k] = \
cd_fast.enet_coordinate_descent_gram(
coef_[k, :], l1_reg, l2_reg, Gram, this_Xy, y[:, k],
self.max_iter, self.tol, self.positive)
if dual_gap_[k] > eps_[k]:
warnings.warn('Objective did not converge for ' +
'target %d, you might want' % k +
' to increase the number of iterations')
self.coef_, self.dual_gap_, self.eps_ = (np.squeeze(a) for a in
(coef_, dual_gap_, eps_))
self._set_intercept(X_mean, y_mean, X_std)
# return self for chaining fit and predict calls
return self
def _sparse_fit(self, X, y, Xy=None, coef_init=None):
if X.shape[0] != y.shape[0]:
raise ValueError("X and y have incompatible shapes.\n" +
"Note: Sparse matrices cannot be indexed w/" +
"boolean masks (use `indices=True` in CV).")
# NOTE: we are explicitly not centering the data the naive way to
# avoid breaking the sparsity of X
X_data, y, X_mean, y_mean, X_std = sparse_center_data(
X, y, self.fit_intercept, self.normalize)
if y.ndim == 1:
y = y[:, np.newaxis]
n_samples, n_features = X.shape[0], X.shape[1]
n_targets = y.shape[1]
coef_ = self._init_coef(coef_init, n_features, n_targets)
dual_gap_ = np.empty(n_targets)
eps_ = np.empty(n_targets)
l1_reg = self.alpha * self.l1_ratio * n_samples
l2_reg = self.alpha * (1.0 - self.l1_ratio) * n_samples
for k in xrange(n_targets):
coef_[k, :], dual_gap_[k], eps_[k] = \
cd_fast.sparse_enet_coordinate_descent(
coef_[k, :], l1_reg, l2_reg, X_data, X.indices,
X.indptr, y[:, k], X_mean / X_std,
self.max_iter, self.tol, self.positive)
if dual_gap_[k] > eps_[k]:
warnings.warn('Objective did not converge for ' +
'target %d, you might want' % k +
' to increase the number of iterations')
self.coef_, self.dual_gap_, self.eps_ = (np.squeeze(a) for a in
(coef_, dual_gap_, eps_))
self._set_intercept(X_mean, y_mean, X_std)
# return self for chaining fit and predict calls
return self
def _init_coef(self, coef_init, n_features, n_targets):
if coef_init is None:
if not self.warm_start or self.coef_ is None:
coef_ = np.zeros((n_targets, n_features), dtype=np.float64)
else:
coef_ = self.coef_
else:
coef_ = coef_init
if coef_.ndim == 1:
coef_ = coef_[np.newaxis, :]
if coef_.shape != (n_targets, n_features):
raise ValueError("X and coef_init have incompatible "
"shapes (%s != %s)."
% (coef_.shape, (n_targets, n_features)))
return coef_
@property
def sparse_coef_(self):
""" sparse representation of the fitted coef """
return sparse.csr_matrix(self.coef_)
def decision_function(self, X):
"""Decision function of the linear model
Parameters
----------
X : numpy array or scipy.sparse matrix of shape (n_samples, n_features)
Returns
-------
T : array, shape = (n_samples,)
The predicted decision function
"""
if sparse.isspmatrix(X):
return np.ravel(safe_sparse_dot(self.coef_, X.T, dense_output=True)
+ self.intercept_)
else:
return super(ElasticNet, self).decision_function(X)
###############################################################################
# Lasso model
class Lasso(ElasticNet):
"""Linear Model trained with L1 prior as regularizer (aka the Lasso)
The optimization objective for Lasso is::
(1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1
Technically the Lasso model is optimizing the same objective function as
the Elastic Net with l1_ratio=1.0 (no L2 penalty).
Parameters
----------
alpha : float, optional
Constant that multiplies the L1 term. Defaults to 1.0
alpha = 0 is equivalent to an ordinary least square, solved
by the LinearRegression object in the scikit. For numerical
reasons, using alpha = 0 is with the Lasso object is not advised
and you should prefer the LinearRegression object.
fit_intercept : boolean
whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(e.g. data is expected to be already centered).
normalize : boolean, optional
If True, the regressors X are normalized
copy_X : boolean, optional, default True
If True, X will be copied; else, it may be overwritten.
precompute : True | False | 'auto' | array-like
Whether to use a precomputed Gram matrix to speed up
calculations. If set to 'auto' let us decide. The Gram
matrix can also be passed as argument. For sparse input
this option is always True to preserve sparsity.
max_iter: int, optional
The maximum number of iterations
tol : float, optional
The tolerance for the optimization: if the updates are
smaller than 'tol', the optimization code checks the
dual gap for optimality and continues until it is smaller
than tol.
warm_start : bool, optional
When set to True, reuse the solution of the previous call to fit as
initialization, otherwise, just erase the previous solution.
positive : bool, optional
When set to True, forces the coefficients to be positive.
Attributes
----------
`coef_` : array, shape = (n_features,)
parameter vector (w in the cost function formula)
`sparse_coef_` : scipy.sparse matrix, shape = (n_features, 1)
`sparse_coef_` is a readonly property derived from `coef_`
`intercept_` : float
independent term in decision function.
`dual_gap_` : float
the current fit is guaranteed to be epsilon-suboptimal with
epsilon := `dual_gap_`
`eps_` : float
`eps_` is used to check if the fit converged to the requested
`tol`
Examples
--------
>>> from sklearn import linear_model
>>> clf = linear_model.Lasso(alpha=0.1)
>>> clf.fit([[0,0], [1, 1], [2, 2]], [0, 1, 2])
Lasso(alpha=0.1, copy_X=True, fit_intercept=True, max_iter=1000,
normalize=False, positive=False, precompute='auto', tol=0.0001,
warm_start=False)
>>> print(clf.coef_)
[ 0.85 0. ]
>>> print(clf.intercept_)
0.15
See also
--------
lars_path
lasso_path
LassoLars
LassoCV
LassoLarsCV
sklearn.decomposition.sparse_encode
Notes
-----
The algorithm used to fit the model is coordinate descent.
To avoid unnecessary memory duplication the X argument of the fit method
should be directly passed as a fortran contiguous numpy array.
"""
def __init__(self, alpha=1.0, fit_intercept=True, normalize=False,
precompute='auto', copy_X=True, max_iter=1000,
tol=1e-4, warm_start=False, positive=False):
super(Lasso, self).__init__(
alpha=alpha, l1_ratio=1.0, fit_intercept=fit_intercept,
normalize=normalize, precompute=precompute, copy_X=copy_X,
max_iter=max_iter, tol=tol, warm_start=warm_start,
positive=positive)
###############################################################################
# Classes to store linear models along a regularization path
def lasso_path(X, y, eps=1e-3, n_alphas=100, alphas=None,
precompute='auto', Xy=None, fit_intercept=True,
normalize=False, copy_X=True, verbose=False,
**params):
"""Compute Lasso path with coordinate descent
The optimization objective for Lasso is::
(1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1
Parameters
----------
X : ndarray, shape = (n_samples, n_features)
Training data. Pass directly as fortran contiguous data to avoid
unnecessary memory duplication
y : ndarray, shape = (n_samples,)
Target values
eps : float, optional
Length of the path. eps=1e-3 means that
alpha_min / alpha_max = 1e-3
n_alphas : int, optional
Number of alphas along the regularization path
alphas : ndarray, optional
List of alphas where to compute the models.
If None alphas are set automatically
precompute : True | False | 'auto' | array-like
Whether to use a precomputed Gram matrix to speed up
calculations. If set to 'auto' let us decide. The Gram
matrix can also be passed as argument.
Xy : array-like, optional
Xy = np.dot(X.T, y) that can be precomputed. It is useful
only when the Gram matrix is precomputed.
fit_intercept : bool
Fit or not an intercept
normalize : boolean, optional
If True, the regressors X are normalized
copy_X : boolean, optional, default True
If True, X will be copied; else, it may be overwritten.
verbose : bool or integer
Amount of verbosity
params : kwargs
keyword arguments passed to the Lasso objects
Returns
-------
models : a list of models along the regularization path
Notes
-----
See examples/linear_model/plot_lasso_coordinate_descent_path.py
for an example.
To avoid unnecessary memory duplication the X argument of the fit method
should be directly passed as a fortran contiguous numpy array.
See also
--------
lars_path
Lasso
LassoLars
LassoCV
LassoLarsCV
sklearn.decomposition.sparse_encode
"""
return enet_path(X, y, l1_ratio=1., eps=eps, n_alphas=n_alphas,
alphas=alphas, precompute=precompute, Xy=Xy,
fit_intercept=fit_intercept, normalize=normalize,
copy_X=copy_X, verbose=verbose, **params)
def enet_path(X, y, l1_ratio=0.5, eps=1e-3, n_alphas=100, alphas=None,
precompute='auto', Xy=None, fit_intercept=True,
normalize=False, copy_X=True, verbose=False, rho=None,
**params):
"""Compute Elastic-Net path with coordinate descent
The Elastic Net optimization function is::
1 / (2 * n_samples) * ||y - Xw||^2_2 +
+ alpha * l1_ratio * ||w||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
Parameters
----------
X : ndarray, shape = (n_samples, n_features)
Training data. Pass directly as fortran contiguous data to avoid
unnecessary memory duplication
y : ndarray, shape = (n_samples,)
Target values
l1_ratio : float, optional
float between 0 and 1 passed to ElasticNet (scaling between
l1 and l2 penalties). l1_ratio=1 corresponds to the Lasso
eps : float
Length of the path. eps=1e-3 means that
alpha_min / alpha_max = 1e-3
n_alphas : int, optional
Number of alphas along the regularization path
alphas : ndarray, optional
List of alphas where to compute the models.
If None alphas are set automatically
precompute : True | False | 'auto' | array-like
Whether to use a precomputed Gram matrix to speed up
calculations. If set to 'auto' let us decide. The Gram
matrix can also be passed as argument.
Xy : array-like, optional
Xy = np.dot(X.T, y) that can be precomputed. It is useful
only when the Gram matrix is precomputed.
fit_intercept : bool
Fit or not an intercept
normalize : boolean, optional
If True, the regressors X are normalized
copy_X : boolean, optional, default True
If True, X will be copied; else, it may be overwritten.
verbose : bool or integer
Amount of verbosity
params : kwargs
keyword arguments passed to the Lasso objects
Returns
-------
models : a list of models along the regularization path
Notes
-----
See examples/plot_lasso_coordinate_descent_path.py for an example.
See also
--------
ElasticNet
ElasticNetCV
"""
if rho is not None:
l1_ratio = rho
warnings.warn("rho was renamed to l1_ratio and will be removed "
"in 0.15", DeprecationWarning)
X = atleast2d_or_csc(X, dtype=np.float64, order='F',
copy=copy_X and fit_intercept)
# From now on X can be touched inplace
if not sparse.isspmatrix(X):
X, y, X_mean, y_mean, X_std = center_data(X, y, fit_intercept,
normalize, copy=False)
# XXX : in the sparse case the data will be centered
# at each fit...
n_samples, n_features = X.shape
if (hasattr(precompute, '__array__')
and not np.allclose(X_mean, np.zeros(n_features))
and not np.allclose(X_std, np.ones(n_features))):
# recompute Gram
precompute = 'auto'
Xy = None
if precompute or ((precompute == 'auto') and (n_samples > n_features)):
if sparse.isspmatrix(X):
warnings.warn("precompute is ignored for sparse data")
precompute = False
else:
precompute = np.dot(X.T, X)
if Xy is None:
Xy = safe_sparse_dot(X.T, y, dense_output=True)
n_samples = X.shape[0]
if alphas is None:
alpha_max = np.abs(Xy).max() / (n_samples * l1_ratio)
alphas = np.logspace(np.log10(alpha_max * eps), np.log10(alpha_max),
num=n_alphas)[::-1]
else:
alphas = np.sort(alphas)[::-1] # make sure alphas are properly ordered
coef_ = None # init coef_
models = []
n_alphas = len(alphas)
for i, alpha in enumerate(alphas):
model = ElasticNet(
alpha=alpha, l1_ratio=l1_ratio,
fit_intercept=fit_intercept if sparse.isspmatrix(X) else False,
precompute=precompute)
model.set_params(**params)
model.fit(X, y, coef_init=coef_, Xy=Xy)
if fit_intercept and not sparse.isspmatrix(X):
model.fit_intercept = True
model._set_intercept(X_mean, y_mean, X_std)
if verbose:
if verbose > 2:
print model
elif verbose > 1:
print 'Path: %03i out of %03i' % (i, n_alphas)
else:
sys.stderr.write('.')
coef_ = model.coef_.copy()
models.append(model)
return models
def _path_residuals(X, y, train, test, path, path_params, l1_ratio=1):
this_mses = list()
if 'l1_ratio' in path_params:
path_params['l1_ratio'] = l1_ratio
models_train = path(X[train], y[train], **path_params)
this_mses = np.empty(len(models_train))
for i_model, model in enumerate(models_train):
y_ = model.predict(X[test])
this_mses[i_model] = ((y_ - y[test]) ** 2).mean()
return this_mses, l1_ratio
class LinearModelCV(LinearModel):
"""Base class for iterative model fitting along a regularization path"""
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, eps=1e-3, n_alphas=100, alphas=None, fit_intercept=True,
normalize=False, precompute='auto', max_iter=1000, tol=1e-4,
copy_X=True, cv=None, verbose=False):
self.eps = eps
self.n_alphas = n_alphas
self.alphas = alphas
self.fit_intercept = fit_intercept
self.normalize = normalize
self.precompute = precompute
self.max_iter = max_iter
self.tol = tol
self.copy_X = copy_X
self.cv = cv
self.verbose = verbose
def fit(self, X, y):
"""Fit linear model with coordinate descent
Fit is on grid of alphas and best alpha estimated by cross-validation.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data. Pass directly as fortran contiguous data to avoid
unnecessary memory duplication
y : narray, shape (n_samples,) or (n_samples, n_targets)
Target values
"""
X = atleast2d_or_csc(X, dtype=np.float64, order='F',
copy=self.copy_X and self.fit_intercept)
# From now on X can be touched inplace
y = np.asarray(y, dtype=np.float64)
if X.shape[0] != y.shape[0]:
raise ValueError("X and y have inconsistent dimensions (%d != %d)"
% (X.shape[0], y.shape[0]))
# All LinearModelCV parameters except 'cv' are acceptable
path_params = self.get_params()
if 'l1_ratio' in path_params:
l1_ratios = np.atleast_1d(path_params['l1_ratio'])
# For the first path, we need to set l1_ratio
path_params['l1_ratio'] = l1_ratios[0]
else:
l1_ratios = [1, ]
path_params.pop('cv', None)
path_params.pop('n_jobs', None)
# Start to compute path on full data
# XXX: is this really useful: we are fitting models that we won't
# use later
models = self.path(X, y, **path_params)
# Update the alphas list
alphas = [model.alpha for model in models]
n_alphas = len(alphas)
path_params.update({'alphas': alphas, 'n_alphas': n_alphas})
# init cross-validation generator
cv = check_cv(self.cv, X)
# Compute path for all folds and compute MSE to get the best alpha
folds = list(cv)
best_mse = np.inf
all_mse_paths = list()
# We do a double for loop folded in one, in order to be able to
# iterate in parallel on l1_ratio and folds
for l1_ratio, mse_alphas in itertools.groupby(
Parallel(n_jobs=self.n_jobs, verbose=self.verbose)(
delayed(_path_residuals)(
X, y, train, test, self.path, path_params,
l1_ratio=l1_ratio)
for l1_ratio in l1_ratios for train, test in folds
), operator.itemgetter(1)):
mse_alphas = [m[0] for m in mse_alphas]
mse_alphas = np.array(mse_alphas)
mse = np.mean(mse_alphas, axis=0)
i_best_alpha = np.argmin(mse)
this_best_mse = mse[i_best_alpha]
all_mse_paths.append(mse_alphas.T)
if this_best_mse < best_mse:
model = models[i_best_alpha]
best_l1_ratio = l1_ratio
if hasattr(model, 'l1_ratio'):
if model.l1_ratio != best_l1_ratio:
# Need to refit the model
model.l1_ratio = best_l1_ratio
model.fit(X, y)
self.l1_ratio_ = model.l1_ratio
self.coef_ = model.coef_
self.intercept_ = model.intercept_
self.alpha_ = model.alpha
self.alphas_ = np.asarray(alphas)
self.coef_path_ = np.asarray([model.coef_ for model in models])
self.mse_path_ = np.squeeze(all_mse_paths)
return self
@property
def rho_(self):
warnings.warn("rho was renamed to l1_ratio and will be removed "
"in 0.15", DeprecationWarning)
return self.l1_ratio_
@property
def alpha(self):
warnings.warn("Use alpha_. Using alpha is deprecated "
"since version 0.12, and backward compatibility "
"won't be maintained from version 0.14 onward. ",
DeprecationWarning, stacklevel=1)
return self.alpha_
class LassoCV(LinearModelCV, RegressorMixin):
"""Lasso linear model with iterative fitting along a regularization path
The best model is selected by cross-validation.
The optimization objective for Lasso is::
(1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1
Parameters
----------
eps : float, optional
Length of the path. eps=1e-3 means that
alpha_min / alpha_max = 1e-3.
n_alphas : int, optional
Number of alphas along the regularization path
alphas : numpy array, optional
List of alphas where to compute the models.
If None alphas are set automatically
precompute : True | False | 'auto' | array-like
Whether to use a precomputed Gram matrix to speed up
calculations. If set to 'auto' let us decide. The Gram
matrix can also be passed as argument.
max_iter: int, optional
The maximum number of iterations
tol: float, optional
The tolerance for the optimization: if the updates are
smaller than 'tol', the optimization code checks the
dual gap for optimality and continues until it is smaller
than tol.
cv : integer or crossvalidation generator, optional
If an integer is passed, it is the number of fold (default 3).
Specific crossvalidation objects can be passed, see
sklearn.cross_validation module for the list of possible objects
verbose : bool or integer
amount of verbosity
Attributes
----------
`alpha_`: float
The amount of penalization choosen by cross validation
`coef_` : array, shape = (n_features,)
parameter vector (w in the cost function formula)
`intercept_` : float
independent term in decision function.
`mse_path_`: array, shape = (n_alphas, n_folds)
mean square error for the test set on each fold, varying alpha
`alphas_`: numpy array
The grid of alphas used for fitting
Notes
-----
See examples/linear_model/lasso_path_with_crossvalidation.py
for an example.
To avoid unnecessary memory duplication the X argument of the fit method
should be directly passed as a fortran contiguous numpy array.
See also
--------
lars_path
lasso_path
LassoLars
Lasso
LassoLarsCV
"""
path = staticmethod(lasso_path)
n_jobs = 1
def __init__(self, eps=1e-3, n_alphas=100, alphas=None, fit_intercept=True,
normalize=False, precompute='auto', max_iter=1000, tol=1e-4,
copy_X=True, cv=None, verbose=False):
super(LassoCV, self).__init__(
eps=eps, n_alphas=n_alphas, alphas=alphas,
fit_intercept=fit_intercept, normalize=normalize,
precompute=precompute, max_iter=max_iter, tol=tol, copy_X=copy_X,
cv=cv, verbose=verbose)
class ElasticNetCV(LinearModelCV, RegressorMixin):
"""Elastic Net model with iterative fitting along a regularization path
The best model is selected by cross-validation.
Parameters
----------
l1_ratio : float, optional
float between 0 and 1 passed to ElasticNet (scaling between
l1 and l2 penalties). For l1_ratio = 0
the penalty is an L2 penalty. For l1_ratio = 1 it is an L1 penalty.
For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2
This parameter can be a list, in which case the different
values are tested by cross-validation and the one giving the best
prediction score is used. Note that a good choice of list of
values for l1_ratio is often to put more values close to 1
(i.e. Lasso) and less close to 0 (i.e. Ridge), as in [.1, .5, .7,
.9, .95, .99, 1]
eps : float, optional
Length of the path. eps=1e-3 means that
alpha_min / alpha_max = 1e-3.
n_alphas : int, optional
Number of alphas along the regularization path
alphas : numpy array, optional
List of alphas where to compute the models.
If None alphas are set automatically
precompute : True | False | 'auto' | array-like
Whether to use a precomputed Gram matrix to speed up
calculations. If set to 'auto' let us decide. The Gram
matrix can also be passed as argument.
max_iter : int, optional
The maximum number of iterations
tol : float, optional
The tolerance for the optimization: if the updates are
smaller than 'tol', the optimization code checks the
dual gap for optimality and continues until it is smaller
than tol.
cv : integer or crossvalidation generator, optional
If an integer is passed, it is the number of fold (default 3).
Specific crossvalidation objects can be passed, see
sklearn.cross_validation module for the list of possible objects
verbose : bool or integer
amount of verbosity
n_jobs : integer, optional
Number of CPUs to use during the cross validation. If '-1', use
all the CPUs. Note that this is used only if multiple values for
l1_ratio are given.
Attributes
----------
`alpha_` : float
The amount of penalization choosen by cross validation
`l1_ratio_` : float
The compromise between l1 and l2 penalization choosen by
cross validation
`coef_` : array, shape = (n_features,)
Parameter vector (w in the cost function formula),
`intercept_` : float
Independent term in the decision function.
`mse_path_` : array, shape = (n_l1_ratio, n_alpha, n_folds)
Mean square error for the test set on each fold, varying l1_ratio and
alpha.
Notes
-----
See examples/linear_model/lasso_path_with_crossvalidation.py
for an example.
To avoid unnecessary memory duplication the X argument of the fit method
should be directly passed as a fortran contiguous numpy array.
The parameter l1_ratio corresponds to alpha in the glmnet R package
while alpha corresponds to the lambda parameter in glmnet.
More specifically, the optimization objective is::
1 / (2 * n_samples) * ||y - Xw||^2_2 +
+ alpha * l1_ratio * ||w||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
If you are interested in controlling the L1 and L2 penalty
separately, keep in mind that this is equivalent to::
a * L1 + b * L2
for::
alpha = a + b and l1_ratio = a / (a + b).
See also
--------
enet_path
ElasticNet
"""
path = staticmethod(enet_path)
def __init__(self, l1_ratio=0.5, eps=1e-3, n_alphas=100, alphas=None,
fit_intercept=True, normalize=False, precompute='auto',
max_iter=1000, tol=1e-4, cv=None, copy_X=True,
verbose=0, n_jobs=1, rho=None):
self.l1_ratio = l1_ratio
if rho is not None:
self.l1_ratio = rho
warnings.warn("rho was renamed to l1_ratio and will be removed "
"in 0.15", DeprecationWarning)
self.eps = eps
self.n_alphas = n_alphas
self.alphas = alphas
self.fit_intercept = fit_intercept
self.normalize = normalize
self.precompute = precompute
self.max_iter = max_iter
self.tol = tol
self.cv = cv
self.copy_X = copy_X
self.verbose = verbose
self.n_jobs = n_jobs
###############################################################################
# Multi Task ElasticNet and Lasso models (with joint feature selection)
class MultiTaskElasticNet(Lasso):
"""Multi-task ElasticNet model trained with L1/L2 mixed-norm as regularizer
The optimization objective for Lasso is::
(1 / (2 * n_samples)) * ||Y - XW||^Fro_2
+ alpha * l1_ratio * ||W||_21
+ 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
Where::
||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2}
i.e. the sum of norm of earch row.
Parameters
----------
alpha : float, optional
Constant that multiplies the L1/L2 term. Defaults to 1.0
l1_ratio : float
The ElasticNet mixing parameter, with 0 < l1_ratio <= 1.
For l1_ratio = 0 the penalty is an L1/L2 penalty. For l1_ratio = 1 it
is an L1 penalty.
For 0 < l1_ratio < 1, the penalty is a combination of L1/L2 and L2.
fit_intercept : boolean
whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(e.g. data is expected to be already centered).
normalize : boolean, optional
If True, the regressors X are normalized
copy_X : boolean, optional, default True
If True, X will be copied; else, it may be overwritten.
max_iter : int, optional
The maximum number of iterations
tol : float, optional
The tolerance for the optimization: if the updates are
smaller than 'tol', the optimization code checks the
dual gap for optimality and continues until it is smaller
than tol.
warm_start : bool, optional
When set to True, reuse the solution of the previous call to fit as
initialization, otherwise, just erase the previous solution.
Attributes
----------
`intercept_` : array, shape = (n_tasks,)
Independent term in decision function.
`coef_` : array, shape = (n_tasks, n_features)
Parameter vector (W in the cost function formula). If a 1D y is \
passed in at fit (non multi-task usage), `coef_` is then a 1D array
Examples
--------
>>> from sklearn import linear_model
>>> clf = linear_model.MultiTaskElasticNet(alpha=0.1)
>>> clf.fit([[0,0], [1, 1], [2, 2]], [[0, 0], [1, 1], [2, 2]])
... #doctest: +NORMALIZE_WHITESPACE
MultiTaskElasticNet(alpha=0.1, copy_X=True, fit_intercept=True,
l1_ratio=0.5, max_iter=1000, normalize=False, rho=None, tol=0.0001,
warm_start=False)
>>> print clf.coef_
[[ 0.45663524 0.45612256]
[ 0.45663524 0.45612256]]
>>> print clf.intercept_
[ 0.0872422 0.0872422]
See also
--------
ElasticNet, MultiTaskLasso
Notes
-----
The algorithm used to fit the model is coordinate descent.
To avoid unnecessary memory duplication the X argument of the fit method
should be directly passed as a fortran contiguous numpy array.
"""
def __init__(self, alpha=1.0, l1_ratio=0.5, fit_intercept=True,
normalize=False, copy_X=True, max_iter=1000, tol=1e-4,
warm_start=False, rho=None):
self.l1_ratio = l1_ratio
if rho is not None:
self.l1_ratio = rho
warnings.warn("rho was renamed to l1_ratio and will be removed "
"in 0.15", DeprecationWarning)
self.alpha = alpha
self.coef_ = None
self.fit_intercept = fit_intercept
self.normalize = normalize
self.max_iter = max_iter
self.copy_X = copy_X
self.tol = tol
self.warm_start = warm_start
def fit(self, X, y, Xy=None, coef_init=None):
"""Fit MultiTaskLasso model with coordinate descent
Parameters
-----------
X: ndarray, shape = (n_samples, n_features)
Data
y: ndarray, shape = (n_samples, n_tasks)
Target
coef_init: ndarray of shape n_features
The initial coeffients to warm-start the optimization
Notes
-----
Coordinate descent is an algorithm that considers each column of
data at a time hence it will automatically convert the X input
as a fortran contiguous numpy array if necessary.
To avoid memory re-allocation it is advised to allocate the
initial data in memory directly using that format.
"""
# X and y must be of type float64
X = array2d(X, dtype=np.float64, order='F',
copy=self.copy_X and self.fit_intercept)
y = np.asarray(y, dtype=np.float64)
squeeze_me = False
if y.ndim == 1:
squeeze_me = True
y = y[:, np.newaxis]
n_samples, n_features = X.shape
_, n_tasks = y.shape
X, y, X_mean, y_mean, X_std = center_data(
X, y, self.fit_intercept, self.normalize, copy=False)
if coef_init is None:
if not self.warm_start or self.coef_ is None:
self.coef_ = np.zeros((n_tasks, n_features), dtype=np.float64,
order='F')
else:
self.coef_ = coef_init
l1_reg = self.alpha * self.l1_ratio * n_samples
l2_reg = self.alpha * (1.0 - self.l1_ratio) * n_samples
self.coef_ = np.asfortranarray(self.coef_) # coef contiguous in memory
self.coef_, self.dual_gap_, self.eps_ = \
cd_fast.enet_coordinate_descent_multi_task(
self.coef_, l1_reg, l2_reg, X, y, self.max_iter, self.tol)
self._set_intercept(X_mean, y_mean, X_std)
# Make sure that the coef_ have the same shape as the given 'y',
# to predict with the same shape
if squeeze_me:
self.coef_ = self.coef_.squeeze()
if self.dual_gap_ > self.eps_:
warnings.warn('Objective did not converge, you might want'
' to increase the number of iterations')
# return self for chaining fit and predict calls
return self
class MultiTaskLasso(MultiTaskElasticNet):
"""Multi-task Lasso model trained with L1/L2 mixed-norm as regularizer
The optimization objective for Lasso is::
(1 / (2 * n_samples)) * ||Y - XW||^2_Fro + alpha * ||W||_21
Where::
||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2}
i.e. the sum of norm of earch row.
Parameters
----------
alpha : float, optional
Constant that multiplies the L1/L2 term. Defaults to 1.0
fit_intercept : boolean
whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(e.g. data is expected to be already centered).
normalize : boolean, optional
If True, the regressors X are normalized
copy_X : boolean, optional, default True
If True, X will be copied; else, it may be overwritten.
max_iter : int, optional
The maximum number of iterations
tol : float, optional
The tolerance for the optimization: if the updates are
smaller than 'tol', the optimization code checks the
dual gap for optimality and continues until it is smaller
than tol.
warm_start : bool, optional
When set to True, reuse the solution of the previous call to fit as
initialization, otherwise, just erase the previous solution.
Attributes
----------
`coef_` : array, shape = (n_tasks, n_features)
parameter vector (W in the cost function formula)
`intercept_` : array, shape = (n_tasks,)
independent term in decision function.
Examples
--------
>>> from sklearn import linear_model
>>> clf = linear_model.MultiTaskLasso(alpha=0.1)
>>> clf.fit([[0,0], [1, 1], [2, 2]], [[0, 0], [1, 1], [2, 2]])
MultiTaskLasso(alpha=0.1, copy_X=True, fit_intercept=True, max_iter=1000,
normalize=False, tol=0.0001, warm_start=False)
>>> print clf.coef_
[[ 0.89393398 0. ]
[ 0.89393398 0. ]]
>>> print clf.intercept_
[ 0.10606602 0.10606602]
See also
--------
Lasso, MultiTaskElasticNet
Notes
-----
The algorithm used to fit the model is coordinate descent.
To avoid unnecessary memory duplication the X argument of the fit method
should be directly passed as a fortran contiguous numpy array.
"""
def __init__(self, alpha=1.0, fit_intercept=True, normalize=False,
copy_X=True, max_iter=1000, tol=1e-4, warm_start=False):
self.alpha = alpha
self.coef_ = None
self.fit_intercept = fit_intercept
self.normalize = normalize
self.max_iter = max_iter
self.copy_X = copy_X
self.tol = tol
self.warm_start = warm_start
self.l1_ratio = 1.0
| mrshu/scikit-learn | sklearn/linear_model/coordinate_descent.py | Python | bsd-3-clause | 44,980 |
import pandas as pd
import numpy as np
import pyaf.ForecastEngine as autof
import pyaf.Bench.TS_datasets as tsds
#get_ipython().magic('matplotlib inline')
lValues = [ k for k in range(2,24, 4)];
# lValues = lValues + [ k for k in range(24, 128, 8)];
for cyc in lValues:
print("TEST_CYCLES_START", cyc)
b1 = tsds.generate_random_TS(N = 3200 , FREQ = 'D', seed = 0, trendtype = "constant", cycle_length = cyc, transform = "None", sigma = 0.1, exog_count = 0, ar_order=0);
df = b1.mPastData
# df.tail(10)
# df[:-10].tail()
# df[:-10:-1]
# df.describe()
lEngine = autof.cForecastEngine()
lEngine.mOptions.mCycleLengths = [ k for k in range(2,128) ];
lEngine
H = cyc * 2;
lEngine.train(df , b1.mTimeVar , b1.mSignalVar, H);
lEngine.getModelInfo();
lEngine.mSignalDecomposition.mBestModel.mTimeInfo.mResolution
dfapp_in = df.copy();
dfapp_in.tail()
# H = 12
dfapp_out = lEngine.forecast(dfapp_in, H);
dfapp_out.tail(2 * H)
print("Forecast Columns " , dfapp_out.columns);
Forecast_DF = dfapp_out[[b1.mTimeVar , b1.mSignalVar, b1.mSignalVar + '_Forecast']]
print(Forecast_DF.info())
print("Forecasts\n" , Forecast_DF.tail(H).values);
print("\n\n<ModelInfo>")
print(lEngine.to_json());
print("</ModelInfo>\n\n")
print("\n\n<Forecast>")
print(Forecast_DF.tail(H).to_json(date_format='iso'))
print("</Forecast>\n\n")
print("TEST_CYCLES_END", cyc)
| antoinecarme/pyaf | tests/perf/test_cycles_full_long.py | Python | bsd-3-clause | 1,473 |
#coding:utf-8
from PyQt4 import QtGui
#from PyQt4 import QtCore
from libblah.consts import ABOUT_MSG, ABOUT_TITLE
from ui.ui_verification_dialog import Ui_VerificationDialog
def popup_confirm(parent, msg = None):
reply = QtGui.QMessageBox.question(parent, u"提示",
msg,
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
return True
else:
return False
def popup_warning(parent, msg = None):
QtGui.QMessageBox.warning(parent, u"警告", msg, QtGui.QMessageBox.Close)
def popup_error(parent, msg = None):
QtGui.QMessageBox.critical(parent, u"错误", msg, QtGui.QMessageBox.Close)
def popup_about(parent):
QtGui.QMessageBox.about(parent, ABOUT_TITLE, ABOUT_MSG)
class GetInputDialog(QtGui.QDialog, Ui_VerificationDialog):
def __init__(self, body = "Input: "):
QtGui.QDialog.__init__(self)
self.setupUi(self)
self.label.setText(body)
class GetVerificationDialog(GetInputDialog):
def __init__(self, body, path):
GetInputDialog.__init__(self, body)
pix = QtGui.QPixmap(path)
lab = QtGui.QLabel("verification", self)
lab.setPixmap(pix)
self.verticalLayout.addWidget(lab)
@staticmethod
def get_input(body = "Recognise and Input 4 characters: ", path = None):
dlg = GetVerificationDialog(body, path)
dlg.show()
result = dlg.exec_()
if result == QtGui.QDialog.Accepted:
btn_val = True
else:
btn_val = False
return (btn_val, str(dlg.lineEdit.text()))
| williamyangcn/iBlah_py | libiblah/popup_dlgs.py | Python | bsd-3-clause | 1,614 |
<?php
/* @var $this yii\web\View */
use yii\helpers\Html;
use yii\widgets\LinkPager;
use yii\helpers\Url;
?>
<section id="advertisement">
<div class="container">
<img src="/images/shop/1.jpg" alt="" />
</div>
</section>
<section>
<div class="container">
<div class="row">
<div class="col-sm-3">
<div class="left-sidebar">
<h2>Category</h2>
<ul class="catalog category-products"> <!-- Виджет категорий -->
<?= \app\components\MenuWidget::widget(['tpl' => 'menu'])?>
</ul> <!-- Виджет категорий -->
<div class="brands_products"><!--brands_products-->
<h2>Brands</h2>
<div class="brands-name">
<ul class="nav nav-pills nav-stacked">
<li><a href=""> <span class="pull-right">(50)</span>Acne</a></li>
<li><a href=""> <span class="pull-right">(56)</span>Grüne Erde</a></li>
<li><a href=""> <span class="pull-right">(27)</span>Albiro</a></li>
<li><a href=""> <span class="pull-right">(32)</span>Ronhill</a></li>
<li><a href=""> <span class="pull-right">(5)</span>Oddmolly</a></li>
<li><a href=""> <span class="pull-right">(9)</span>Boudestijn</a></li>
<li><a href=""> <span class="pull-right">(4)</span>Rösch creative culture</a></li>
</ul>
</div>
</div><!--/brands_products-->
<div class="price-range"><!--price-range-->
<h2>Price Range</h2>
<div class="well">
<input type="text" class="span2" value="" data-slider-min="0" data-slider-max="600" data-slider-step="5" data-slider-value="[250,450]" id="sl2" ><br />
<b>$ 0</b> <b class="pull-right">$ 600</b>
</div>
</div><!--/price-range-->
<div class="shipping text-center"><!--shipping-->
<img src="/images/home/shipping.jpg" alt="" />
</div><!--/shipping-->
</div>
</div>
<div class="col-sm-9 padding-right">
<div class="features_items"><!--features_items-->
<h2 class="title text-center"><?= $category->name ?></h2>
<?php if(!empty($products)): ?>
<?php $i = 0; foreach($products as $product): ?>
<?php $mainImg = $product->getImage();?>
<div class="col-sm-4">
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfo text-center">
<?= Html::img($mainImg->getUrl('268x249'), ['alt' => $product->name])?>
<h2>$<?= $product->price?></h2>
<p><a href="<?= Url::to(['product/view', 'id' => $product->id]) ?>"><?= $product->name?></a></p>
<a href="#" data-id="<?= $product->id ?>" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>
</div>
<!--<div class="product-overlay">
<div class="overlay-content">
<h2>$<?= $product->price?></h2>
<p><?= $product->name?></p>
<a href="#" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>
</div>
</div>-->
<?php if($product->new): ?>
<?= Html::img("@web/images/home/new.png", ['alt' => 'Новинка', 'class' => 'new'])?>
<?php endif?>
<?php if($product->sale): ?>
<?= Html::img("@web/images/home/sale.png", ['alt' => 'Распродажа', 'class' => 'new'])?>
<?php endif?>
</div>
<div class="choose">
<ul class="nav nav-pills nav-justified">
<li><a href=""><i class="fa fa-plus-square"></i>Add to wishlist</a></li>
<li><a href=""><i class="fa fa-plus-square"></i>Add to compare</a></li>
</ul>
</div>
</div>
</div>
<?php $i++?>
<?php if($i % 3 == 0): // % - делится без остатка ?>
<div class="clearfix"></div>
<?php endif;?>
<?php endforeach;?>
<div class="clearfix"></div>
<?php //Пагинация
echo LinkPager::widget([
'pagination' => $pages,
]);
?>
<?php else :?>
<h2>Здесь товаров пока нет...</h2>
<?php endif;?>
<!--<ul class="pagination">
<li class="active"><a href="">1</a></li>
<li><a href="">2</a></li>
<li><a href="">3</a></li>
<li><a href="">»</a></li>
</ul>-->
</div><!--features_items-->
</div>
</div>
</div>
</section> | RuslanKozin/yii2-int.mag | views/category/view.php | PHP | bsd-3-clause | 4,734 |
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\models\Users */
$this->title = '添加学员';
$this->params['breadcrumbs'][] = ['label' => '学员管理', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="users-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| hanxiao84322/coach_system | views/admin/users/create.php | PHP | bsd-3-clause | 414 |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-----------------------------------------------------------------------------
'''
'''
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
import logging # isort:skip
log = logging.getLogger(__name__)
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
import json
from os.path import abspath, basename, dirname, exists, join, normpath
from typing import Dict, List, NamedTuple, Optional
from warnings import warn
# Bokeh imports
from ..core.templates import CSS_RESOURCES, JS_RESOURCES
from ..document.document import Document
from ..model import Model
from ..resources import BaseResources, Resources
from ..settings import settings
from ..util.compiler import bundle_models
#-----------------------------------------------------------------------------
# Globals and constants
#-----------------------------------------------------------------------------
__all__ = (
'Bundle',
'bundle_for_objs_and_resources',
)
#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
class ScriptRef(object):
def __init__(self, url, type="text/javascript"):
self.url = url
self.type = type
class Script(object):
def __init__(self, content, type="text/javascript"):
self.content = content
self.type = type
class StyleRef(object):
def __init__(self, url):
self.url = url
class Style(object):
def __init__(self, content):
self.content = content
class Bundle(object):
@classmethod
def of(cls, js_files, js_raw, css_files, css_raw, hashes):
return cls(js_files=js_files, js_raw=js_raw, css_files=css_files, css_raw=css_raw, hashes=hashes)
def __init__(self, **kwargs):
self.js_files = kwargs.get("js_files", [])
self.js_raw = kwargs.get("js_raw", [])
self.css_files = kwargs.get("css_files", [])
self.css_raw = kwargs.get("css_raw", [])
self.hashes = kwargs.get("hashes", {})
def __iter__(self):
yield self._render_js()
yield self._render_css()
def _render_js(self):
return JS_RESOURCES.render(js_files=self.js_files, js_raw=self.js_raw, hashes=self.hashes)
def _render_css(self):
return CSS_RESOURCES.render(css_files=self.css_files, css_raw=self.css_raw)
def scripts(self, tag=True):
if tag:
return JS_RESOURCES.render(js_raw=self.js_raw, js_files=[])
else:
return "\n".join(self.js_raw)
@property
def js_urls(self):
return self.js_files
@property
def css_urls(self):
return self.css_files
def add(self, artifact):
if isinstance(artifact, ScriptRef):
self.js_files.append(artifact.url)
elif isinstance(artifact, Script):
self.js_raw.append(artifact.content)
elif isinstance(artifact, StyleRef):
self.css_files.append(artifact.url)
elif isinstance(artifact, Style):
self.css_raw.append(artifact.content)
def bundle_for_objs_and_resources(objs, resources):
''' Generate rendered CSS and JS resources suitable for the given
collection of Bokeh objects
Args:
objs (seq[Model or Document]) :
resources (BaseResources or tuple[BaseResources])
Returns:
Bundle
'''
# Any env vars will overide a local default passed in
resources = settings.resources(default=resources)
if isinstance(resources, str):
resources = Resources(mode=resources)
if resources is None or isinstance(resources, BaseResources):
js_resources = css_resources = resources
elif isinstance(resources, tuple) and len(resources) == 2 and all(r is None or isinstance(r, BaseResources) for r in resources):
js_resources, css_resources = resources
if js_resources and not css_resources:
warn('No Bokeh CSS Resources provided to template. If required you will need to provide them manually.')
if css_resources and not js_resources:
warn('No Bokeh JS Resources provided to template. If required you will need to provide them manually.')
else:
raise ValueError("expected Resources or a pair of optional Resources, got %r" % resources)
from copy import deepcopy
# XXX: force all components on server and in notebook, because we don't know in advance what will be used
use_widgets = _use_widgets(objs) if objs else True
use_tables = _use_tables(objs) if objs else True
use_gl = _use_gl(objs) if objs else True
js_files = []
js_raw = []
css_files = []
css_raw = []
if js_resources:
js_resources = deepcopy(js_resources)
if not use_widgets and "bokeh-widgets" in js_resources.js_components:
js_resources.js_components.remove("bokeh-widgets")
if not use_tables and "bokeh-tables" in js_resources.js_components:
js_resources.js_components.remove("bokeh-tables")
if not use_gl and "bokeh-gl" in js_resources.js_components:
js_resources.js_components.remove("bokeh-gl")
js_files.extend(js_resources.js_files)
js_raw.extend(js_resources.js_raw)
if css_resources:
css_resources = deepcopy(css_resources)
css_files.extend(css_resources.css_files)
css_raw.extend(css_resources.css_raw)
if js_resources:
extensions = _bundle_extensions(objs, js_resources)
mode = js_resources.mode if resources is not None else "inline"
if mode == "inline":
js_raw.extend([ Resources._inline(bundle.artifact_path) for bundle in extensions ])
elif mode == "server":
js_files.extend([ bundle.server_url for bundle in extensions ])
elif mode == "cdn":
js_files.extend([ bundle.cdn_url for bundle in extensions if bundle.cdn_url is not None ])
else:
js_files.extend([ bundle.artifact_path for bundle in extensions ])
models = [ obj.__class__ for obj in _all_objs(objs) ] if objs else None
ext = bundle_models(models)
if ext is not None:
js_raw.append(ext)
return Bundle.of(js_files, js_raw, css_files, css_raw, js_resources.hashes if js_resources else {})
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
def _query_extensions(objs, query):
names = set()
for obj in _all_objs(objs):
if hasattr(obj, "__implementation__"):
continue
name = obj.__view_module__.split(".")[0]
if name == "bokeh":
continue
if name in names:
continue
names.add(name)
for model in Model.model_class_reverse_map.values():
if model.__module__.startswith(name):
if query(model):
return True
return False
_default_cdn_host = "https://unpkg.com"
class ExtensionEmbed(NamedTuple):
artifact_path: str
server_url: str
cdn_url: Optional[str] = None
extension_dirs: Dict[str, str] = {} # name -> path
def _bundle_extensions(objs, resources: Resources) -> List[ExtensionEmbed]:
names = set()
bundles = []
extensions = [".min.js", ".js"] if resources.minified else [".js"]
for obj in _all_objs(objs) if objs is not None else Model.model_class_reverse_map.values():
if hasattr(obj, "__implementation__"):
continue
name = obj.__view_module__.split(".")[0]
if name == "bokeh":
continue
if name in names:
continue
names.add(name)
module = __import__(name)
this_file = abspath(module.__file__)
base_dir = dirname(this_file)
dist_dir = join(base_dir, "dist")
ext_path = join(base_dir, "bokeh.ext.json")
if not exists(ext_path):
continue
server_prefix = f"{resources.root_url}static/extensions"
package_path = join(base_dir, "package.json")
pkg: Optional[str] = None
if exists(package_path):
with open(package_path) as io:
try:
pkg = json.load(io)
except json.decoder.JSONDecodeError:
pass
artifact_path: str
server_url: str
cdn_url: Optional[str] = None
if pkg is not None:
pkg_name = pkg["name"]
pkg_version = pkg.get("version", "latest")
pkg_main = pkg.get("module", pkg.get("main", None))
if pkg_main is not None:
cdn_url = f"{_default_cdn_host}/{pkg_name}@^{pkg_version}/{pkg_main}"
else:
pkg_main = join(dist_dir, f"{name}.js")
artifact_path = join(base_dir, normpath(pkg_main))
artifacts_dir = dirname(artifact_path)
artifact_name = basename(artifact_path)
server_path = f"{name}/{artifact_name}"
else:
for ext in extensions:
artifact_path = join(dist_dir, f"{name}{ext}")
artifacts_dir = dist_dir
server_path = f"{name}/{name}{ext}"
if exists(artifact_path):
break
else:
raise ValueError(f"can't resolve artifact path for '{name}' extension")
extension_dirs[name] = artifacts_dir
server_url = f"{server_prefix}/{server_path}"
embed = ExtensionEmbed(artifact_path, server_url, cdn_url)
bundles.append(embed)
return bundles
def _all_objs(objs):
all_objs = set()
for obj in objs:
if isinstance(obj, Document):
for root in obj.roots:
all_objs |= root.references()
else:
all_objs |= obj.references()
return all_objs
def _any(objs, query):
''' Whether any of a collection of objects satisfies a given query predicate
Args:
objs (seq[Model or Document]) :
query (callable)
Returns:
True, if ``query(obj)`` is True for some object in ``objs``, else False
'''
for obj in objs:
if isinstance(obj, Document):
if _any(obj.roots, query):
return True
else:
if any(query(ref) for ref in obj.references()):
return True
return False
def _use_gl(objs):
''' Whether a collection of Bokeh objects contains a plot requesting WebGL
Args:
objs (seq[Model or Document]) :
Returns:
bool
'''
from ..models.plots import Plot
return _any(objs, lambda obj: isinstance(obj, Plot) and obj.output_backend == "webgl")
def _use_tables(objs):
''' Whether a collection of Bokeh objects contains a TableWidget
Args:
objs (seq[Model or Document]) :
Returns:
bool
'''
from ..models.widgets import TableWidget
return _any(objs, lambda obj: isinstance(obj, TableWidget)) or _ext_use_tables(objs)
def _use_widgets(objs):
''' Whether a collection of Bokeh objects contains a any Widget
Args:
objs (seq[Model or Document]) :
Returns:
bool
'''
from ..models.widgets import Widget
return _any(objs, lambda obj: isinstance(obj, Widget)) or _ext_use_widgets(objs)
def _ext_use_tables(objs):
from ..models.widgets import TableWidget
return _query_extensions(objs, lambda cls: issubclass(cls, TableWidget))
def _ext_use_widgets(objs):
from ..models.widgets import Widget
return _query_extensions(objs, lambda cls: issubclass(cls, Widget))
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| ericmjl/bokeh | bokeh/embed/bundle.py | Python | bsd-3-clause | 12,481 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.coderedrobotics.tiberius.libs.dash;
import java.util.Vector;
/**
*
* @author laptop
*/
public interface SRAListener {
public void alertToSRAUpdates();
}
| CodeRed2771/Tiberius2014 | src/com/coderedrobotics/tiberius/libs/dash/SRAListener.java | Java | bsd-3-clause | 274 |
"use strict";
var JumpGateTravelCapability = require("./JumpGateTravelCapability");
/**
* This namespace contains helper regarding the jump gate travel capability.
*
* @namespace jumpGate
* @memberof everoute.travel.capabilities
*/
/**
* The type identification for the jumps: "jumpGate".
*
* @type {String}
* @const
* @memberof everoute.travel.capabilities.jumpGate
*/
var JUMP_TYPE = JumpGateTravelCapability.JUMP_TYPE;
module.exports = {
JUMP_TYPE: JUMP_TYPE,
JumpGateTravelCapability: JumpGateTravelCapability
};
| dertseha/eve-route.js | src/travel/capabilities/jumpGate/index.js | JavaScript | bsd-3-clause | 537 |
<?php
namespace app\modules\admin\controllers;
use Yii;
use app\models\Article;
use app\models\ArticleSearch;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* ArticleController implements the CRUD actions for Article model.
*/
class ArticleController extends BaseController
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
/**
* Lists all Article models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new ArticleSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Article model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Article model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Article();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Article model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Article model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Article model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Article the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Article::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
| w1nsun/content-analyzer | modules/admin/controllers/ArticleController.php | PHP | bsd-3-clause | 3,088 |
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include <cassert>
#include "IECore/Primitive.h"
#include "IECore/VectorTypedData.h"
#include "IECore/TypeTraits.h"
#include "IECore/DespatchTypedData.h"
#include "IECore/MurmurHash.h"
using namespace IECore;
using namespace boost;
using namespace std;
using namespace Imath;
/////////////////////////////////////////////////////////////////////////////////////
// Primitive
/////////////////////////////////////////////////////////////////////////////////////
static IndexedIO::EntryID g_variablesEntry("variables");
static IndexedIO::EntryID g_interpolationEntry("interpolation");
static IndexedIO::EntryID g_dataEntry("data");
const unsigned int Primitive::m_ioVersion = 1;
IE_CORE_DEFINEABSTRACTOBJECTTYPEDESCRIPTION( Primitive );
Primitive::Primitive()
{
}
Primitive::~Primitive()
{
}
Imath::Box3f Primitive::bound() const
{
Box3f result;
PrimitiveVariableMap::const_iterator it = variables.find( "P" );
if( it!=variables.end() )
{
ConstV3fVectorDataPtr p = runTimeCast<const V3fVectorData>( it->second.data );
if( p )
{
const vector<V3f> &pp = p->readable();
for( size_t i=0; i<pp.size(); i++ )
{
result.extendBy( pp[i] );
}
}
}
return result;
}
void Primitive::copyFrom( const Object *other, IECore::Object::CopyContext *context )
{
VisibleRenderable::copyFrom( other, context );
const Primitive *tOther = static_cast<const Primitive *>( other );
variables.clear();
for( PrimitiveVariableMap::const_iterator it=tOther->variables.begin(); it!=tOther->variables.end(); it++ )
{
variables.insert( PrimitiveVariableMap::value_type( it->first, PrimitiveVariable( it->second.interpolation, context->copy<Data>( it->second.data.get() ) ) ) );
}
}
void Primitive::save( IECore::Object::SaveContext *context ) const
{
VisibleRenderable::save( context );
IndexedIOPtr container = context->container( staticTypeName(), m_ioVersion );
IndexedIOPtr ioVariables = container->subdirectory( g_variablesEntry, IndexedIO::CreateIfMissing );
for( PrimitiveVariableMap::const_iterator it=variables.begin(); it!=variables.end(); it++ )
{
IndexedIOPtr ioPrimVar = ioVariables->subdirectory( it->first, IndexedIO::CreateIfMissing );
const int i = it->second.interpolation;
ioPrimVar->write( g_interpolationEntry, i );
context->save( it->second.data.get(), ioPrimVar.get(), g_dataEntry );
}
}
void Primitive::load( IECore::Object::LoadContextPtr context )
{
unsigned int v = m_ioVersion;
ConstIndexedIOPtr container = context->container( staticTypeName(), v );
// we changed the inheritance hierarchy at io version 1
if( v==0 )
{
Renderable::load( context );
}
else
{
VisibleRenderable::load( context );
}
ConstIndexedIOPtr ioVariables = container->subdirectory( g_variablesEntry );
variables.clear();
IndexedIO::EntryIDList names;
ioVariables->entryIds( names, IndexedIO::Directory );
IndexedIO::EntryIDList::const_iterator it;
for( it=names.begin(); it!=names.end(); it++ )
{
ConstIndexedIOPtr ioPrimVar = ioVariables->subdirectory( *it );
int i;
ioPrimVar->read( g_interpolationEntry, i );
variables.insert(
PrimitiveVariableMap::value_type( *it, PrimitiveVariable( (PrimitiveVariable::Interpolation)i, context->load<Data>( ioPrimVar.get(), g_dataEntry ) ) )
);
}
}
PrimitiveVariableMap Primitive::loadPrimitiveVariables( const IndexedIO *ioInterface, const IndexedIO::EntryID &name, const IndexedIO::EntryIDList &primVarNames )
{
IECore::Object::LoadContextPtr context = new Object::LoadContext( ioInterface->subdirectory( name )->subdirectory( g_dataEntry ) );
unsigned int v = m_ioVersion;
ConstIndexedIOPtr container = context->container( Primitive::staticTypeName(), v );
if ( !container )
{
throw Exception( "Could not find Primitive entry in the file!" );
}
ConstIndexedIOPtr ioVariables = container->subdirectory( g_variablesEntry );
PrimitiveVariableMap variables;
IndexedIO::EntryIDList::const_iterator it;
for( it=primVarNames.begin(); it!=primVarNames.end(); it++ )
{
ConstIndexedIOPtr ioPrimVar = ioVariables->subdirectory( *it, IndexedIO::NullIfMissing );
if ( !ioPrimVar )
{
continue;
}
int i;
ioPrimVar->read( g_interpolationEntry, i );
variables.insert(
PrimitiveVariableMap::value_type( *it, PrimitiveVariable( (PrimitiveVariable::Interpolation)i, context->load<Data>( ioPrimVar.get(), g_dataEntry ) ) )
);
}
return variables;
}
bool Primitive::isEqualTo( const Object *other ) const
{
if( !VisibleRenderable::isEqualTo( other ) )
{
return false;
}
const Primitive *tOther = static_cast<const Primitive *>( other );
if( tOther->variables!=variables )
{
return false;
}
return true;
}
void Primitive::memoryUsage( Object::MemoryAccumulator &a ) const
{
VisibleRenderable::memoryUsage( a );
for( PrimitiveVariableMap::const_iterator it=variables.begin(); it!=variables.end(); it++ )
{
a.accumulate( it->second.data.get() );
}
}
void Primitive::hash( MurmurHash &h ) const
{
VisibleRenderable::hash( h );
for( PrimitiveVariableMap::const_iterator it=variables.begin(); it!=variables.end(); it++ )
{
h.append( it->first );
h.append( it->second.interpolation );
it->second.data->hash( h );
}
topologyHash( h );
}
struct ValidateArraySize
{
typedef bool ReturnType;
ValidateArraySize( size_t sz ) : m_variableSize( sz )
{
}
template<typename T>
bool operator() ( const T *data )
{
assert( data );
const typename T::ValueType &v = data->readable();
return v.size() == m_variableSize;
}
private:
size_t m_variableSize;
};
struct ReturnFalseErrorHandler
{
typedef bool ReturnType;
template<typename T, typename F>
bool operator() ( const T *data, const F &f )
{
return false;
}
};
bool Primitive::isPrimitiveVariableValid( const PrimitiveVariable &pv ) const
{
if (! pv.data || pv.interpolation==PrimitiveVariable::Invalid)
{
return false;
}
if( pv.interpolation==PrimitiveVariable::Constant )
{
// any data is reasonable for constant interpolation
return true;
}
// all other interpolations require an array of data of the correct length. it could be argued tha
// SimpleTypedData should be accepted in the rare case that variableSize==1, but we're rejecting that
// argument on the grounds that it makes for a whole bunch of special cases with no gain - the general
// cases all require arrays so that's what we require.
/// \todo This is not correct in the case of CurvesPrimitives, where uniform interpolation should be
/// treated the same as constant.
size_t sz = variableSize( pv.interpolation );
ValidateArraySize func( sz );
return despatchTypedData<ValidateArraySize, TypeTraits::IsVectorTypedData, ReturnFalseErrorHandler>( pv.data.get(), func );
}
bool Primitive::arePrimitiveVariablesValid() const
{
for( PrimitiveVariableMap::const_iterator it=variables.begin(); it!=variables.end(); it++ )
{
if ( !isPrimitiveVariableValid( it->second ) )
{
return false;
}
}
return true;
}
PrimitiveVariable::Interpolation Primitive::inferInterpolation( size_t numElements ) const
{
if( variableSize( PrimitiveVariable::Constant )==numElements )
{
return PrimitiveVariable::Constant;
}
else if( variableSize( PrimitiveVariable::Uniform )==numElements )
{
return PrimitiveVariable::Uniform;
}
else if( variableSize( PrimitiveVariable::Vertex )==numElements )
{
return PrimitiveVariable::Vertex;
}
else if( variableSize( PrimitiveVariable::Varying )==numElements )
{
return PrimitiveVariable::Varying;
}
else if( variableSize( PrimitiveVariable::FaceVarying )==numElements )
{
return PrimitiveVariable::FaceVarying;
}
return PrimitiveVariable::Invalid;
}
PrimitiveVariable::Interpolation Primitive::inferInterpolation( const Data *data ) const
{
size_t s = IECore::despatchTypedData<IECore::TypedDataSize>( const_cast<Data *>( data ) );
return inferInterpolation( s );
}
| hradec/cortex | src/IECore/Primitive.cpp | C++ | bsd-3-clause | 9,664 |
package org.broadinstitute.hellbender.tools.exome.alleliccount;
import org.broadinstitute.hellbender.tools.exome.alleliccount.AllelicCountTableColumn.AllelicCountTableVerbosity;
import org.broadinstitute.hellbender.utils.tsv.DataLine;
import org.broadinstitute.hellbender.utils.tsv.TableWriter;
import java.io.File;
import java.io.IOException;
/**
* Writes {@link AllelicCountWithPhasePosteriors} instances to a tab-separated table file.
*
* @author Samuel Lee <slee@broadinstitute.org>
*/
public class AllelicCountWithPhasePosteriorsWriter extends TableWriter<AllelicCountWithPhasePosteriors> {
private final AllelicCountTableVerbosity verbosity;
public AllelicCountWithPhasePosteriorsWriter(final File file, final AllelicCountTableVerbosity verbosity) throws IOException {
super(file, PhasePosteriorsTableColumn.appendPhasePosteriorColumns(AllelicCountTableColumn.getColumns(verbosity)));
this.verbosity = verbosity;
}
@Override
protected void composeLine(final AllelicCountWithPhasePosteriors record, final DataLine dataLine) {
AllelicCountWriter.composeLine(record, dataLine, verbosity);
composeLinePhasePosteriors(record, dataLine);
}
/**
* Compose the record for the phase posteriors.
*
* @param record the {@link AllelicCount} record
* @param dataLine the {@link DataLine} to the composed
*/
private static void composeLinePhasePosteriors(final AllelicCountWithPhasePosteriors record, final DataLine dataLine) {
dataLine.append(AllelicCountWriter.formatProb(record.getRefMinorProb()))
.append(AllelicCountWriter.formatProb(record.getAltMinorProb()))
.append(AllelicCountWriter.formatProb(record.getOutlierProb()));
}
}
| broadinstitute/gatk-protected | src/main/java/org/broadinstitute/hellbender/tools/exome/alleliccount/AllelicCountWithPhasePosteriorsWriter.java | Java | bsd-3-clause | 1,776 |
/* Copyright (c) 2015, Daniel C. Dillon
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <dqtx/QIconTheme.hpp>
#include <QFile>
#include <QTextStream>
namespace dqtx
{
QIconTheme::QIconTheme()
{
m_uuid = QUuid::createUuid();
m_dir = QDir::temp();
m_dir.mkdir(m_uuid.toString());
m_dir.cd(m_uuid.toString());
QFile file(m_dir.absolutePath() + QString("/index.theme"));
file.open(QIODevice::WriteOnly);
QTextStream outfile(&file);
outfile << "[Icon Theme]\n"
<< "Name=QIconTheme\n"
<< "Comment=Temporary icon theme\n"
<< "Hidden=true\n";
file.close();
}
QIconTheme::~QIconTheme()
{
QStringList files = m_dir.entryList();
QStringList::iterator i = files.begin();
QStringList::iterator iend = files.end();
for (; i != iend; ++i)
{
m_dir.remove(*i);
}
m_dir.cdUp();
m_dir.rmdir(m_uuid.toString());
}
void QIconTheme::addIcon(const QIcon &_icon, const QString &_name)
{
m_lock.lock();
_icon.pixmap(48).toImage().save(m_dir.absolutePath() + QString("/") +
_name + QString(".png"));
m_iconByName[_name] = _icon;
m_lock.unlock();
}
bool QIconTheme::hasIcon(const QString &_name) const
{
bool retval = false;
m_lock.lock();
QMap< QString, QIcon >::const_iterator i = m_iconByName.find(_name);
if (i != m_iconByName.end())
{
retval = true;
}
m_lock.unlock();
return retval;
}
QDir QIconTheme::dir() const { return m_dir; }
} // namespace dqtx
| dcdillon/dqtx | dqtx/src/QIconTheme.cpp | C++ | bsd-3-clause | 3,056 |
<?php
/**
* Common formatter class for console output.
*
* PHP version 5
*
* @category PHP
* @package PHP_Reflect
* @author Laurent Laville <pear@laurent-laville.org>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version GIT: $Id$
* @link http://php5.laurent-laville.org/reflect/
*/
namespace Bartlett\Reflect\Console\Formatter;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Formatter\OutputFormatter as BaseOutputFormatter;
/**
* Common formatter helpers for console output.
*
* @category PHP
* @package PHP_Reflect
* @author Laurent Laville <pear@laurent-laville.org>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version Release: @package_version@
* @link http://php5.laurent-laville.org/reflect/
* @since Class available since Release 3.0.0-alpha1
*/
class OutputFormatter extends BaseOutputFormatter
{
/**
* Helper that convert analyser results to a console table
*
* @param OutputInterface $output Console Output concrete instance
* @param array $headers All table headers
* @param array $rows All table rows
* @param string $style The default style name to render tables
*
* @return void
*/
protected function tableHelper(OutputInterface $output, $headers, $rows, $style = 'compact')
{
$table = new Table($output);
$table->setStyle($style)
->setHeaders($headers)
->setRows($rows)
->render()
;
}
/**
* Helper that convert an array key-value pairs to a console report.
*
* See Structure and Loc analysers for implementation examples
*
* @param OutputInterface $output Console Output concrete instance
* @param array $lines Any analyser formatted metrics
*
* @return void
*/
protected function printFormattedLines(OutputInterface $output, array $lines)
{
foreach ($lines as $ident => $contents) {
list ($format, $args) = $contents;
$output->writeln(vsprintf($format, $args));
}
}
}
| remicollet/php-reflect | src/Bartlett/Reflect/Console/Formatter/OutputFormatter.php | PHP | bsd-3-clause | 2,246 |
<?php
namespace common\models\base;
use Yii;
/**
* This is the model class for table "blood_group".
*
* @property integer $ID
* @property string $Name
* @property string $created_on
* @property string $modified_on
*/
class baseBloodGroup extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'blood_group';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['Name', 'created_on', 'modified_on'], 'required'],
[['created_on', 'modified_on'], 'safe'],
[['Name'], 'string', 'max' => 200],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'ID' => 'ID',
'Name' => 'Name',
'created_on' => 'Created On',
'modified_on' => 'Modified On',
];
}
}
| shibam2015/KandePohe | common/models/base/baseBloodGroup.php | PHP | bsd-3-clause | 923 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/cert_net/cert_net_fetcher_impl.h"
#include <string>
#include <utility>
#include "base/compiler_specific.h"
#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "net/cert/ct_policy_enforcer.h"
#include "net/cert/mock_cert_verifier.h"
#include "net/cert/multi_log_ct_verifier.h"
#include "net/dns/mock_host_resolver.h"
#include "net/http/http_server_properties_impl.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/gtest_util.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
using net::test::IsOk;
// TODO(eroman): Test that cookies aren't sent.
using base::ASCIIToUTF16;
namespace net {
namespace {
const base::FilePath::CharType kDocRoot[] =
FILE_PATH_LITERAL("net/data/cert_net_fetcher_impl_unittest");
// A non-mock URLRequestContext which can access http:// urls.
class RequestContext : public URLRequestContext {
public:
RequestContext() : storage_(this) {
ProxyConfig no_proxy;
storage_.set_host_resolver(
std::unique_ptr<HostResolver>(new MockHostResolver));
storage_.set_cert_verifier(base::WrapUnique(new MockCertVerifier));
storage_.set_transport_security_state(
base::WrapUnique(new TransportSecurityState));
storage_.set_cert_transparency_verifier(
base::WrapUnique(new MultiLogCTVerifier));
storage_.set_ct_policy_enforcer(base::WrapUnique(new CTPolicyEnforcer));
storage_.set_proxy_service(ProxyService::CreateFixed(no_proxy));
storage_.set_ssl_config_service(new SSLConfigServiceDefaults);
storage_.set_http_server_properties(
std::unique_ptr<HttpServerProperties>(new HttpServerPropertiesImpl()));
HttpNetworkSession::Params params;
params.host_resolver = host_resolver();
params.cert_verifier = cert_verifier();
params.transport_security_state = transport_security_state();
params.cert_transparency_verifier = cert_transparency_verifier();
params.ct_policy_enforcer = ct_policy_enforcer();
params.proxy_service = proxy_service();
params.ssl_config_service = ssl_config_service();
params.http_server_properties = http_server_properties();
storage_.set_http_network_session(
base::WrapUnique(new HttpNetworkSession(params)));
storage_.set_http_transaction_factory(base::WrapUnique(new HttpCache(
storage_.http_network_session(), HttpCache::DefaultBackend::InMemory(0),
false /* set_up_quic_server_info */)));
storage_.set_job_factory(base::WrapUnique(new URLRequestJobFactoryImpl()));
}
~RequestContext() override { AssertNoURLRequests(); }
private:
URLRequestContextStorage storage_;
};
class FetchResult {
public:
FetchResult(Error net_error, const std::vector<uint8_t>& response_body)
: net_error_(net_error), response_body_(response_body) {}
void VerifySuccess(const std::string& expected_body) {
EXPECT_THAT(net_error_, IsOk());
EXPECT_EQ(expected_body,
std::string(response_body_.begin(), response_body_.end()));
}
void VerifyFailure(Error expected_error) {
EXPECT_EQ(expected_error, net_error_);
EXPECT_EQ(0u, response_body_.size());
}
private:
const Error net_error_;
const std::vector<uint8_t> response_body_;
};
// Helper to synchronously wait for the fetch completion. This is similar to
// net's TestCompletionCallback, but built around FetchCallback.
class TestFetchCallback {
public:
TestFetchCallback()
: callback_(base::Bind(&TestFetchCallback::OnCallback,
base::Unretained(this))) {}
const CertNetFetcher::FetchCallback& callback() const { return callback_; }
std::unique_ptr<FetchResult> WaitForResult() {
DCHECK(quit_closure_.is_null());
while (!HasResult()) {
base::RunLoop run_loop;
quit_closure_ = run_loop.QuitClosure();
run_loop.Run();
quit_closure_.Reset();
}
return std::move(result_);
}
bool HasResult() const { return result_.get(); }
// Sets an extra action (in addition to recording the result) that is run when
// the FetchCallback is invoked.
void set_extra_closure(const base::Closure& closure) {
extra_closure_ = closure;
}
private:
void OnCallback(Error net_error, const std::vector<uint8_t>& response_body) {
DCHECK(!HasResult());
result_.reset(new FetchResult(net_error, response_body));
if (!extra_closure_.is_null())
extra_closure_.Run();
if (!quit_closure_.is_null())
quit_closure_.Run();
}
CertNetFetcher::FetchCallback callback_;
std::unique_ptr<FetchResult> result_;
base::Closure quit_closure_;
base::Closure extra_closure_;
};
} // namespace
class CertNetFetcherImplTest : public PlatformTest {
public:
CertNetFetcherImplTest() {
test_server_.AddDefaultHandlers(base::FilePath(kDocRoot));
context_.set_network_delegate(&network_delegate_);
}
protected:
EmbeddedTestServer test_server_;
TestNetworkDelegate network_delegate_;
RequestContext context_;
};
// Helper to start an AIA fetch using default parameters.
WARN_UNUSED_RESULT std::unique_ptr<CertNetFetcher::Request> StartRequest(
CertNetFetcher* fetcher,
const GURL& url,
const TestFetchCallback& callback) {
return fetcher->FetchCaIssuers(url, CertNetFetcher::DEFAULT,
CertNetFetcher::DEFAULT, callback.callback());
}
// Fetch a few unique URLs using GET in parallel. Each URL has a different body
// and Content-Type.
TEST_F(CertNetFetcherImplTest, ParallelFetchNoDuplicates) {
ASSERT_TRUE(test_server_.Start());
CertNetFetcherImpl fetcher(&context_);
TestFetchCallback callback1;
TestFetchCallback callback2;
TestFetchCallback callback3;
// Request a URL with Content-Type "application/pkix-cert"
GURL url1 = test_server_.GetURL("/cert.crt");
std::unique_ptr<CertNetFetcher::Request> request1 =
StartRequest(&fetcher, url1, callback1);
// Request a URL with Content-Type "application/pkix-crl"
GURL url2 = test_server_.GetURL("/root.crl");
std::unique_ptr<CertNetFetcher::Request> request2 =
StartRequest(&fetcher, url2, callback2);
// Request a URL with Content-Type "application/pkcs7-mime"
GURL url3 = test_server_.GetURL("/certs.p7c");
std::unique_ptr<CertNetFetcher::Request> request3 =
StartRequest(&fetcher, url3, callback3);
// Wait for all of the requests to complete.
std::unique_ptr<FetchResult> result1 = callback1.WaitForResult();
std::unique_ptr<FetchResult> result2 = callback2.WaitForResult();
std::unique_ptr<FetchResult> result3 = callback3.WaitForResult();
// Verify the fetch results.
result1->VerifySuccess("-cert.crt-\n");
result2->VerifySuccess("-root.crl-\n");
result3->VerifySuccess("-certs.p7c-\n");
EXPECT_EQ(3, network_delegate_.created_requests());
}
// Fetch a caIssuers URL which has an unexpected extension and Content-Type.
// The extension is .txt and the Content-Type is text/plain. Despite being
// unusual this succeeds as the extension and Content-Type are not required to
// be meaningful.
TEST_F(CertNetFetcherImplTest, ContentTypeDoesntMatter) {
ASSERT_TRUE(test_server_.Start());
CertNetFetcherImpl fetcher(&context_);
TestFetchCallback callback;
GURL url = test_server_.GetURL("/foo.txt");
std::unique_ptr<CertNetFetcher::Request> request =
StartRequest(&fetcher, url, callback);
std::unique_ptr<FetchResult> result = callback.WaitForResult();
result->VerifySuccess("-foo.txt-\n");
}
// Fetch a URLs whose HTTP response code is not 200. These are considered
// failures.
TEST_F(CertNetFetcherImplTest, HttpStatusCode) {
ASSERT_TRUE(test_server_.Start());
CertNetFetcherImpl fetcher(&context_);
// Response was HTTP status 404.
{
TestFetchCallback callback;
GURL url = test_server_.GetURL("/404.html");
std::unique_ptr<CertNetFetcher::Request> request =
StartRequest(&fetcher, url, callback);
std::unique_ptr<FetchResult> result = callback.WaitForResult();
result->VerifyFailure(ERR_FAILED);
}
// Response was HTTP status 500.
{
TestFetchCallback callback;
GURL url = test_server_.GetURL("/500.html");
std::unique_ptr<CertNetFetcher::Request> request =
StartRequest(&fetcher, url, callback);
std::unique_ptr<FetchResult> result = callback.WaitForResult();
result->VerifyFailure(ERR_FAILED);
}
}
// Fetching a URL with a Content-Disposition header should have no effect.
TEST_F(CertNetFetcherImplTest, ContentDisposition) {
ASSERT_TRUE(test_server_.Start());
CertNetFetcherImpl fetcher(&context_);
TestFetchCallback callback;
GURL url = test_server_.GetURL("/downloadable.js");
std::unique_ptr<CertNetFetcher::Request> request =
StartRequest(&fetcher, url, callback);
std::unique_ptr<FetchResult> result = callback.WaitForResult();
result->VerifySuccess("-downloadable.js-\n");
}
// Verifies that a cachable request will be served from the HTTP cache the
// second time it is requested.
TEST_F(CertNetFetcherImplTest, Cache) {
ASSERT_TRUE(test_server_.Start());
CertNetFetcherImpl fetcher(&context_);
// Fetch a URL whose HTTP headers make it cacheable for 1 hour.
GURL url(test_server_.GetURL("/cacheable_1hr.crt"));
{
TestFetchCallback callback;
std::unique_ptr<CertNetFetcher::Request> request =
StartRequest(&fetcher, url, callback);
std::unique_ptr<FetchResult> result = callback.WaitForResult();
result->VerifySuccess("-cacheable_1hr.crt-\n");
}
EXPECT_EQ(1, network_delegate_.created_requests());
// Kill the HTTP server.
ASSERT_TRUE(test_server_.ShutdownAndWaitUntilComplete());
// Fetch again -- will fail unless served from cache.
{
TestFetchCallback callback;
std::unique_ptr<CertNetFetcher::Request> request =
StartRequest(&fetcher, url, callback);
std::unique_ptr<FetchResult> result = callback.WaitForResult();
result->VerifySuccess("-cacheable_1hr.crt-\n");
}
EXPECT_EQ(2, network_delegate_.created_requests());
}
// Verify that the maximum response body constraints are enforced by fetching a
// resource that is larger than the limit.
TEST_F(CertNetFetcherImplTest, TooLarge) {
ASSERT_TRUE(test_server_.Start());
CertNetFetcherImpl fetcher(&context_);
// This file has a response body 12 bytes long. So setting the maximum to 11
// bytes will cause it to fail.
GURL url(test_server_.GetURL("/certs.p7c"));
TestFetchCallback callback;
std::unique_ptr<CertNetFetcher::Request> request = fetcher.FetchCaIssuers(
url, CertNetFetcher::DEFAULT, 11, callback.callback());
std::unique_ptr<FetchResult> result = callback.WaitForResult();
result->VerifyFailure(ERR_FILE_TOO_BIG);
}
// Set the timeout to 10 milliseconds, and try fetching a URL that takes 5
// seconds to complete. It should fail due to a timeout.
TEST_F(CertNetFetcherImplTest, Hang) {
ASSERT_TRUE(test_server_.Start());
CertNetFetcherImpl fetcher(&context_);
GURL url(test_server_.GetURL("/slow/certs.p7c?5"));
TestFetchCallback callback;
std::unique_ptr<CertNetFetcher::Request> request = fetcher.FetchCaIssuers(
url, 10, CertNetFetcher::DEFAULT, callback.callback());
std::unique_ptr<FetchResult> result = callback.WaitForResult();
result->VerifyFailure(ERR_TIMED_OUT);
}
// Verify that if a response is gzip-encoded it gets inflated before being
// returned to the caller.
TEST_F(CertNetFetcherImplTest, Gzip) {
ASSERT_TRUE(test_server_.Start());
CertNetFetcherImpl fetcher(&context_);
GURL url(test_server_.GetURL("/gzipped_crl"));
TestFetchCallback callback;
std::unique_ptr<CertNetFetcher::Request> request =
StartRequest(&fetcher, url, callback);
std::unique_ptr<FetchResult> result = callback.WaitForResult();
result->VerifySuccess("-gzipped_crl-\n");
}
// Try fetching an unsupported URL scheme (https).
TEST_F(CertNetFetcherImplTest, HttpsNotAllowed) {
ASSERT_TRUE(test_server_.Start());
CertNetFetcherImpl fetcher(&context_);
GURL url("https://foopy/foo.crt");
TestFetchCallback callback;
std::unique_ptr<CertNetFetcher::Request> request =
StartRequest(&fetcher, url, callback);
// Should NOT complete synchronously despite being a test that could be done
// immediately.
EXPECT_FALSE(callback.HasResult());
std::unique_ptr<FetchResult> result = callback.WaitForResult();
result->VerifyFailure(ERR_DISALLOWED_URL_SCHEME);
// No request was created because the URL scheme was unsupported.
EXPECT_EQ(0, network_delegate_.created_requests());
}
// Try fetching a URL which redirects to https.
TEST_F(CertNetFetcherImplTest, RedirectToHttpsNotAllowed) {
ASSERT_TRUE(test_server_.Start());
CertNetFetcherImpl fetcher(&context_);
GURL url(test_server_.GetURL("/redirect_https"));
TestFetchCallback callback;
std::unique_ptr<CertNetFetcher::Request> request =
StartRequest(&fetcher, url, callback);
std::unique_ptr<FetchResult> result = callback.WaitForResult();
result->VerifyFailure(ERR_DISALLOWED_URL_SCHEME);
EXPECT_EQ(1, network_delegate_.created_requests());
}
// Try fetching an unsupported URL scheme (https) and then immediately
// cancelling. This is a bit special because this codepath needs to post a task.
TEST_F(CertNetFetcherImplTest, CancelHttpsNotAllowed) {
ASSERT_TRUE(test_server_.Start());
CertNetFetcherImpl fetcher(&context_);
GURL url("https://foopy/foo.crt");
TestFetchCallback callback;
std::unique_ptr<CertNetFetcher::Request> request =
StartRequest(&fetcher, url, callback);
// Cancel the request.
request.reset();
// Spin the message loop to increase chance of catching a bug.
base::RunLoop().RunUntilIdle();
// Should NOT complete synchronously despite being a test that could be done
// immediately.
EXPECT_FALSE(callback.HasResult());
EXPECT_EQ(0, network_delegate_.created_requests());
}
// Start a few requests, and cancel one of them before running the message loop
// again.
TEST_F(CertNetFetcherImplTest, CancelBeforeRunningMessageLoop) {
ASSERT_TRUE(test_server_.Start());
CertNetFetcherImpl fetcher(&context_);
TestFetchCallback callback1;
TestFetchCallback callback2;
TestFetchCallback callback3;
GURL url1 = test_server_.GetURL("/cert.crt");
std::unique_ptr<CertNetFetcher::Request> request1 =
StartRequest(&fetcher, url1, callback1);
GURL url2 = test_server_.GetURL("/root.crl");
std::unique_ptr<CertNetFetcher::Request> request2 =
StartRequest(&fetcher, url2, callback2);
GURL url3 = test_server_.GetURL("/certs.p7c");
std::unique_ptr<CertNetFetcher::Request> request3 =
StartRequest(&fetcher, url3, callback3);
EXPECT_EQ(3, network_delegate_.created_requests());
EXPECT_FALSE(callback1.HasResult());
EXPECT_FALSE(callback2.HasResult());
EXPECT_FALSE(callback3.HasResult());
// Cancel the second request.
request2.reset();
// Wait for the non-cancelled requests to complete.
std::unique_ptr<FetchResult> result1 = callback1.WaitForResult();
std::unique_ptr<FetchResult> result3 = callback3.WaitForResult();
// Verify the fetch results.
result1->VerifySuccess("-cert.crt-\n");
result3->VerifySuccess("-certs.p7c-\n");
EXPECT_FALSE(callback2.HasResult());
}
// Start several requests, and cancel one of them after the first has completed.
// NOTE: The python test server is single threaded and can only service one
// request at a time. After a socket is opened by the server it waits for it to
// be completed, and any subsequent request will hang until the first socket is
// closed.
// Cancelling the first request can therefore be problematic, since if
// cancellation is done after the socket is opened but before reading/writing,
// then the socket is re-cycled and things will be stalled until the cleanup
// timer (10 seconds) closes it.
// To work around this, the last request is cancelled, and hope that the
// requests are given opened sockets in a FIFO order.
// TODO(eroman): Make this more robust.
TEST_F(CertNetFetcherImplTest, CancelAfterRunningMessageLoop) {
ASSERT_TRUE(test_server_.Start());
CertNetFetcherImpl fetcher(&context_);
TestFetchCallback callback1;
TestFetchCallback callback2;
TestFetchCallback callback3;
GURL url1 = test_server_.GetURL("/cert.crt");
std::unique_ptr<CertNetFetcher::Request> request1 =
StartRequest(&fetcher, url1, callback1);
GURL url2 = test_server_.GetURL("/certs.p7c");
std::unique_ptr<CertNetFetcher::Request> request2 =
StartRequest(&fetcher, url2, callback2);
GURL url3("ftp://www.not.supported.com/foo");
std::unique_ptr<CertNetFetcher::Request> request3 =
StartRequest(&fetcher, url3, callback3);
EXPECT_FALSE(callback1.HasResult());
EXPECT_FALSE(callback2.HasResult());
EXPECT_FALSE(callback3.HasResult());
// Wait for the ftp request to complete (it should complete right away since
// it doesn't even try to connect to the server).
std::unique_ptr<FetchResult> result3 = callback3.WaitForResult();
result3->VerifyFailure(ERR_DISALLOWED_URL_SCHEME);
// Cancel the second outstanding request.
request2.reset();
// Wait for the first request to complete.
std::unique_ptr<FetchResult> result2 = callback1.WaitForResult();
// Verify the fetch results.
result2->VerifySuccess("-cert.crt-\n");
}
// Delete a CertNetFetcherImpl with outstanding requests on it.
TEST_F(CertNetFetcherImplTest, DeleteCancels) {
ASSERT_TRUE(test_server_.Start());
std::unique_ptr<CertNetFetcherImpl> fetcher(
new CertNetFetcherImpl(&context_));
GURL url(test_server_.GetURL("/slow/certs.p7c?20"));
TestFetchCallback callback;
std::unique_ptr<CertNetFetcher::Request> request =
StartRequest(fetcher.get(), url, callback);
// Destroy the fetcher before the outstanding request.
fetcher.reset();
}
// Fetch the same URLs in parallel and verify that only 1 request is made per
// URL.
TEST_F(CertNetFetcherImplTest, ParallelFetchDuplicates) {
ASSERT_TRUE(test_server_.Start());
CertNetFetcherImpl fetcher(&context_);
GURL url1 = test_server_.GetURL("/cert.crt");
GURL url2 = test_server_.GetURL("/root.crl");
// Issue 3 requests for url1, and 3 requests for url2
TestFetchCallback callback1;
std::unique_ptr<CertNetFetcher::Request> request1 =
StartRequest(&fetcher, url1, callback1);
TestFetchCallback callback2;
std::unique_ptr<CertNetFetcher::Request> request2 =
StartRequest(&fetcher, url2, callback2);
TestFetchCallback callback3;
std::unique_ptr<CertNetFetcher::Request> request3 =
StartRequest(&fetcher, url1, callback3);
TestFetchCallback callback4;
std::unique_ptr<CertNetFetcher::Request> request4 =
StartRequest(&fetcher, url2, callback4);
TestFetchCallback callback5;
std::unique_ptr<CertNetFetcher::Request> request5 =
StartRequest(&fetcher, url2, callback5);
TestFetchCallback callback6;
std::unique_ptr<CertNetFetcher::Request> request6 =
StartRequest(&fetcher, url1, callback6);
// Cancel all but one of the requests for url1.
request1.reset();
request3.reset();
// Wait for the remaining requests to finish.
std::unique_ptr<FetchResult> result2 = callback2.WaitForResult();
std::unique_ptr<FetchResult> result4 = callback4.WaitForResult();
std::unique_ptr<FetchResult> result5 = callback5.WaitForResult();
std::unique_ptr<FetchResult> result6 = callback6.WaitForResult();
// Verify that none of the cancelled requests for url1 completed (since they
// were cancelled).
EXPECT_FALSE(callback1.HasResult());
EXPECT_FALSE(callback3.HasResult());
// Verify the fetch results.
result2->VerifySuccess("-root.crl-\n");
result4->VerifySuccess("-root.crl-\n");
result5->VerifySuccess("-root.crl-\n");
result6->VerifySuccess("-cert.crt-\n");
// Verify that only 2 URLRequests were started even though 6 requests were
// issued.
EXPECT_EQ(2, network_delegate_.created_requests());
}
// Cancel a request and then start another one for the same URL.
TEST_F(CertNetFetcherImplTest, CancelThenStart) {
ASSERT_TRUE(test_server_.Start());
CertNetFetcherImpl fetcher(&context_);
TestFetchCallback callback1;
TestFetchCallback callback2;
TestFetchCallback callback3;
GURL url = test_server_.GetURL("/cert.crt");
std::unique_ptr<CertNetFetcher::Request> request1 =
StartRequest(&fetcher, url, callback1);
request1.reset();
std::unique_ptr<CertNetFetcher::Request> request2 =
StartRequest(&fetcher, url, callback2);
std::unique_ptr<CertNetFetcher::Request> request3 =
StartRequest(&fetcher, url, callback3);
request3.reset();
// All but |request2| were canceled.
std::unique_ptr<FetchResult> result = callback2.WaitForResult();
result->VerifySuccess("-cert.crt-\n");
EXPECT_FALSE(callback1.HasResult());
EXPECT_FALSE(callback3.HasResult());
// One URLRequest that was cancelled, then another right afterwards.
EXPECT_EQ(2, network_delegate_.created_requests());
}
// Start duplicate requests and then cancel all of them.
TEST_F(CertNetFetcherImplTest, CancelAll) {
ASSERT_TRUE(test_server_.Start());
CertNetFetcherImpl fetcher(&context_);
TestFetchCallback callback[3];
std::unique_ptr<CertNetFetcher::Request> request[3];
GURL url = test_server_.GetURL("/cert.crt");
for (size_t i = 0; i < arraysize(callback); ++i) {
request[i] = StartRequest(&fetcher, url, callback[i]);
}
// Cancel all the requests.
for (size_t i = 0; i < arraysize(request); ++i)
request[i].reset();
EXPECT_EQ(1, network_delegate_.created_requests());
for (size_t i = 0; i < arraysize(request); ++i)
EXPECT_FALSE(callback[i].HasResult());
}
void DeleteCertNetFetcher(CertNetFetcher* fetcher) {
delete fetcher;
}
// Delete the CertNetFetcherImpl within a request callback.
TEST_F(CertNetFetcherImplTest, DeleteWithinCallback) {
ASSERT_TRUE(test_server_.Start());
// Deleted by callback2.
CertNetFetcher* fetcher = new CertNetFetcherImpl(&context_);
GURL url = test_server_.GetURL("/cert.crt");
TestFetchCallback callback[4];
std::unique_ptr<CertNetFetcher::Request> reqs[4];
callback[1].set_extra_closure(base::Bind(DeleteCertNetFetcher, fetcher));
for (size_t i = 0; i < arraysize(callback); ++i)
reqs[i] = StartRequest(fetcher, url, callback[i]);
EXPECT_EQ(1, network_delegate_.created_requests());
callback[1].WaitForResult();
// Assume requests for the same URL are executed in FIFO order.
EXPECT_TRUE(callback[0].HasResult());
EXPECT_FALSE(callback[2].HasResult());
EXPECT_FALSE(callback[3].HasResult());
}
void FetchRequest(CertNetFetcher* fetcher,
const GURL& url,
TestFetchCallback* callback,
std::unique_ptr<CertNetFetcher::Request>* request) {
*request = StartRequest(fetcher, url, *callback);
}
// Make a request during callback for the same URL.
TEST_F(CertNetFetcherImplTest, FetchWithinCallback) {
ASSERT_TRUE(test_server_.Start());
CertNetFetcherImpl fetcher(&context_);
GURL url = test_server_.GetURL("/cert.crt");
TestFetchCallback callback[5];
std::unique_ptr<CertNetFetcher::Request> req[5];
callback[1].set_extra_closure(
base::Bind(FetchRequest, &fetcher, url, &callback[4], &req[4]));
for (size_t i = 0; i < arraysize(callback) - 1; ++i)
req[i] = StartRequest(&fetcher, url, callback[i]);
EXPECT_EQ(1, network_delegate_.created_requests());
for (size_t i = 0; i < arraysize(callback); ++i) {
std::unique_ptr<FetchResult> result = callback[i].WaitForResult();
result->VerifySuccess("-cert.crt-\n");
}
// The fetch started within a callback should have started a new request
// rather than attaching to the current job.
EXPECT_EQ(2, network_delegate_.created_requests());
}
void CancelRequest(std::unique_ptr<CertNetFetcher::Request>* request) {
request->reset();
}
// Cancel a request while executing a callback for the same job.
TEST_F(CertNetFetcherImplTest, CancelWithinCallback) {
ASSERT_TRUE(test_server_.Start());
CertNetFetcherImpl fetcher(&context_);
GURL url = test_server_.GetURL("/cert.crt");
TestFetchCallback callback[4];
std::unique_ptr<CertNetFetcher::Request> request[4];
for (size_t i = 0; i < arraysize(callback); ++i)
request[i] = StartRequest(&fetcher, url, callback[i]);
// Cancel request[2] when the callback for request[1] runs.
callback[1].set_extra_closure(base::Bind(CancelRequest, &request[2]));
EXPECT_EQ(1, network_delegate_.created_requests());
for (size_t i = 0; i < arraysize(request); ++i) {
if (i == 2)
continue;
std::unique_ptr<FetchResult> result = callback[i].WaitForResult();
result->VerifySuccess("-cert.crt-\n");
}
// request[2] was cancelled.
EXPECT_FALSE(callback[2].HasResult());
}
// Cancel the final request while executing a callback for the same job. Ensure
// that the job is not deleted twice.
TEST_F(CertNetFetcherImplTest, CancelLastRequestWithinCallback) {
ASSERT_TRUE(test_server_.Start());
CertNetFetcherImpl fetcher(&context_);
GURL url = test_server_.GetURL("/cert.crt");
TestFetchCallback callback1;
std::unique_ptr<CertNetFetcher::Request> request1 =
StartRequest(&fetcher, url, callback1);
TestFetchCallback callback2;
std::unique_ptr<CertNetFetcher::Request> request2 =
StartRequest(&fetcher, url, callback1);
// Cancel request2 when the callback for request1 runs.
callback1.set_extra_closure(base::Bind(CancelRequest, &request2));
EXPECT_EQ(1, network_delegate_.created_requests());
std::unique_ptr<FetchResult> result = callback1.WaitForResult();
result->VerifySuccess("-cert.crt-\n");
// request2 was cancelled.
EXPECT_FALSE(callback2.HasResult());
}
} // namespace net
| danakj/chromium | net/cert_net/cert_net_fetcher_impl_unittest.cc | C++ | bsd-3-clause | 26,024 |
<?php
/**
* @copyright Frederic G. Østby
* @license http://www.makoframework.com/license
*/
namespace mako\cache\stores;
use Memcached as PHPMemcached;
use mako\cache\stores\IncrementDecrementInterface;
use mako\cache\stores\Store;
/**
* Memcached store.
*
* @author Frederic G. Østby
*/
class Memcached extends Store implements IncrementDecrementInterface
{
/**
* Memcached instance.
*
* @var \Memcached
*/
protected $memcached;
/**
* Constructor.
*
* @param array $servers Memcache servers
* @param int $timeout Timeout in seconds
* @param bool $compressData Compress data?
*/
public function __construct(array $servers, int $timeout = 1, bool $compressData = false)
{
$this->memcached = new PHPMemcached();
$this->memcached->setOption(PHPMemcached::OPT_BINARY_PROTOCOL, true);
if($timeout !== 1)
{
$this->memcached->setOption(PHPMemcached::OPT_CONNECT_TIMEOUT, ($timeout * 1000)); // Multiply by 1000 to convert to ms
}
if($compressData === false)
{
$this->memcached->setOption(PHPMemcached::OPT_COMPRESSION, false);
}
// Add servers to the connection pool
foreach($servers as $server)
{
$this->memcached->addServer($server['server'], $server['port'], $server['weight']);
}
}
/**
* {@inheritdoc}
*/
public function put(string $key, $data, int $ttl = 0): bool
{
if($ttl !== 0)
{
$ttl += time();
}
$key = $this->getPrefixedKey($key);
if($this->memcached->replace($key, $data, $ttl) === false)
{
return $this->memcached->set($key, $data, $ttl);
}
return true;
}
/**
* {@inheritdoc}
*/
public function putIfNotExists(string $key, $data, int $ttl = 0): bool
{
if($ttl !== 0)
{
$ttl += time();
}
return $this->memcached->add($this->getPrefixedKey($key), $data, $ttl);
}
/**
* {@inheritdoc}
*/
public function increment(string $key, int $step = 1)
{
return $this->memcached->increment($this->getPrefixedKey($key), $step, $step);
}
/**
* {@inheritdoc}
*/
public function decrement(string $key, int $step = 1)
{
return $this->memcached->decrement($this->getPrefixedKey($key), $step, $step);
}
/**
* {@inheritdoc}
*/
public function has(string $key): bool
{
return ($this->memcached->get($this->getPrefixedKey($key)) !== false);
}
/**
* {@inheritdoc}
*/
public function get(string $key)
{
return $this->memcached->get($this->getPrefixedKey($key));
}
/**
* {@inheritdoc}
*/
public function remove(string $key): bool
{
return $this->memcached->delete($this->getPrefixedKey($key), 0);
}
/**
* {@inheritdoc}
*/
public function clear(): bool
{
return $this->memcached->flush();
}
}
| letr0n/framework | src/mako/cache/stores/Memcached.php | PHP | bsd-3-clause | 2,685 |
/*
-- MAGMA (version 1.5.0-beta3) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
November 2011
@precisions normal z -> c d s
@author Hartwig Anzt
*/
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
// includes, project
#include "flops.h"
#include "magma.h"
#include "../include/magmasparse.h"
#include "magma_lapack.h"
#include "testings.h"
/* ////////////////////////////////////////////////////////////////////////////
-- running magma_zlobpcg
*/
int main( int argc, char** argv)
{
TESTING_INIT();
magma_z_solver_par solver_par;
solver_par.epsilon = 1e-5;
solver_par.maxiter = 1000;
solver_par.verbose = 0;
solver_par.num_eigenvalues = 32;
solver_par.solver = Magma_LOBPCG;
magma_z_preconditioner precond_par;
precond_par.solver = Magma_JACOBI;
int precond = 0;
int format = 0;
int scale = 0;
magma_scale_t scaling = Magma_NOSCALE;
magma_z_sparse_matrix A, B, dA;
B.blocksize = 8;
B.alignment = 8;
B.storage_type = Magma_CSR;
int i;
for( i = 1; i < argc; ++i ) {
if ( strcmp("--format", argv[i]) == 0 ) {
format = atoi( argv[++i] );
switch( format ) {
case 0: B.storage_type = Magma_CSR; break;
case 1: B.storage_type = Magma_ELL; break;
case 2: B.storage_type = Magma_ELLRT; break;
case 3: B.storage_type = Magma_SELLP; break;
}
}else if ( strcmp("--mscale", argv[i]) == 0 ) {
scale = atoi( argv[++i] );
switch( scale ) {
case 0: scaling = Magma_NOSCALE; break;
case 1: scaling = Magma_UNITDIAG; break;
case 2: scaling = Magma_UNITROW; break;
}
}else if ( strcmp("--precond", argv[i]) == 0 ) {
format = atoi( argv[++i] );
switch( precond ) {
case 0: precond_par.solver = Magma_JACOBI; break;
}
}else if ( strcmp("--blocksize", argv[i]) == 0 ) {
B.blocksize = atoi( argv[++i] );
}else if ( strcmp("--alignment", argv[i]) == 0 ) {
B.alignment = atoi( argv[++i] );
}else if ( strcmp("--verbose", argv[i]) == 0 ) {
solver_par.verbose = atoi( argv[++i] );
} else if ( strcmp("--maxiter", argv[i]) == 0 ) {
solver_par.maxiter = atoi( argv[++i] );
} else if ( strcmp("--tol", argv[i]) == 0 ) {
sscanf( argv[++i], "%lf", &solver_par.epsilon );
} else if ( strcmp("--eigenvalues", argv[i]) == 0 ) {
solver_par.num_eigenvalues = atoi( argv[++i] );
} else
break;
}
printf( "\n# usage: ./run_zlobpcg"
" [ --format %d (0=CSR, 1=ELL, 2=ELLRT, 4=SELLP)"
" [ --blocksize %d --alignment %d ]"
" --mscale %d (0=no, 1=unitdiag, 2=unitrownrm)"
" --verbose %d (0=summary, k=details every k iterations)"
" --maxiter %d --tol %.2e"
" --preconditioner %d (0=Jacobi) "
" --eigenvalues %d ]"
" matrices \n\n", format, (int) B.blocksize, (int) B.alignment,
(int) scale,
(int) solver_par.verbose,
(int) solver_par.maxiter, solver_par.epsilon, precond,
(int) solver_par.num_eigenvalues);
while( i < argc ){
magma_z_csr_mtx( &A, argv[i] );
printf( "\n# matrix info: %d-by-%d with %d nonzeros\n\n",
(int) A.num_rows,(int) A.num_cols,(int) A.nnz );
// scale initial guess
magma_zmscale( &A, scaling );
solver_par.ev_length = A.num_cols;
magma_z_sparse_matrix A2;
A2.storage_type = Magma_SELLC;
A2.blocksize = 8;
A2.alignment = 4;
magma_z_mconvert( A, &A2, Magma_CSR, A2.storage_type );
// copy matrix to GPU
magma_z_mtransfer( A2, &dA, Magma_CPU, Magma_DEV);
magma_zsolverinfo_init( &solver_par, &precond_par ); // inside the loop!
// as the matrix size has influence on the EV-length
real_Double_t gpu_time;
// Find the blockSize smallest eigenvalues and corresponding eigen-vectors
gpu_time = magma_wtime();
magma_zlobpcg( dA, &solver_par );
gpu_time = magma_wtime() - gpu_time;
printf("Time (sec) = %7.2f\n", gpu_time);
printf("solver runtime (sec) = %7.2f\n", solver_par.runtime );
magma_zsolverinfo_free( &solver_par, &precond_par );
magma_z_mfree( &dA );
magma_z_mfree( &A2 );
magma_z_mfree( &A );
i++;
}
TESTING_FINALIZE();
return 0;
}
| EmergentOrder/magma | sparse-iter/testing/run_zlobpcg.cpp | C++ | bsd-3-clause | 4,817 |
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package watchable
import (
"sync"
"v.io/x/ref/services/syncbase/common"
"v.io/x/ref/services/syncbase/store"
)
// stream streams keys and values for versioned records.
type stream struct {
iit store.Stream
sntx store.SnapshotOrTransaction
mu sync.Mutex
err error
hasValue bool
key []byte
value []byte
}
var _ store.Stream = (*stream)(nil)
// newStreamVersioned creates a new stream. It assumes all records in range
// [start, limit) are managed, i.e. versioned.
func newStreamVersioned(sntx store.SnapshotOrTransaction, start, limit []byte) *stream {
return &stream{
iit: sntx.Scan(makeVersionKey(start), makeVersionKey(limit)),
sntx: sntx,
}
}
// Advance implements the store.Stream interface.
func (s *stream) Advance() bool {
s.mu.Lock()
defer s.mu.Unlock()
s.hasValue = false
if s.err != nil {
return false
}
if advanced := s.iit.Advance(); !advanced {
return false
}
versionKey, version := s.iit.Key(nil), s.iit.Value(nil)
s.key = []byte(common.StripFirstKeyPartOrDie(string(versionKey))) // drop "$version" prefix
s.value, s.err = s.sntx.Get(makeAtVersionKey(s.key, version), nil)
if s.err != nil {
return false
}
s.hasValue = true
return true
}
// Key implements the store.Stream interface.
func (s *stream) Key(keybuf []byte) []byte {
s.mu.Lock()
defer s.mu.Unlock()
if !s.hasValue {
panic("nothing staged")
}
return store.CopyBytes(keybuf, s.key)
}
// Value implements the store.Stream interface.
func (s *stream) Value(valbuf []byte) []byte {
s.mu.Lock()
defer s.mu.Unlock()
if !s.hasValue {
panic("nothing staged")
}
return store.CopyBytes(valbuf, s.value)
}
// Err implements the store.Stream interface.
func (s *stream) Err() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.err != nil {
return convertError(s.err)
}
return s.iit.Err()
}
// Cancel implements the store.Stream interface.
func (s *stream) Cancel() {
s.mu.Lock()
defer s.mu.Unlock()
if s.err != nil {
return
}
s.iit.Cancel()
}
| vanadium/go.ref | services/syncbase/store/watchable/stream.go | GO | bsd-3-clause | 2,169 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace OnlinePC
{
public partial class CallBack : System.Web.UI.Page
{
/// <summary>
/// 接收易宝支付回调示例
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder log = new StringBuilder();
string data = Request["data"];
string type = Request["type"];
Labtype.Value = type;
LabData.Value = data;
}
}
} | hiihellox10/ICanPay | ICanPay/Doc/易宝(YeePay)/C#/OnlinePC/OnlinePC/CallBack.aspx.cs | C# | bsd-3-clause | 744 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/accessibility/ax_event_generator.h"
#include "testing/gmock/include/gmock/gmock-matchers.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node.h"
#include "ui/accessibility/ax_serializable_tree.h"
#include "ui/accessibility/ax_tree_serializer.h"
namespace ui {
// Required by gmock to print TargetedEvent in a human-readable way.
void PrintTo(const AXEventGenerator::TargetedEvent& event, std::ostream* os) {
*os << event.event_params.event << " on " << event.node->id();
}
namespace {
using testing::Matches;
using testing::PrintToString;
using testing::UnorderedElementsAre;
// TODO(gilmanmh): Improve printing of test failure messages when the expected
// values are themselves matchers (e.g. Not(3)).
MATCHER_P2(HasEventAtNode,
expected_event_type,
expected_node_id,
std::string(negation ? "does not have" : "has") + " " +
PrintToString(expected_event_type) + " on " +
PrintToString(expected_node_id)) {
const auto& event = arg;
return Matches(expected_event_type)(event.event_params.event) &&
Matches(expected_node_id)(event.node->id());
}
} // namespace
TEST(AXEventGeneratorTest, LoadCompleteSameTree) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].relative_bounds.bounds = gfx::RectF(0, 0, 800, 600);
initial_state.has_tree_data = true;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate load_complete_update = initial_state;
load_complete_update.tree_data.loaded = true;
ASSERT_TRUE(tree.Unserialize(load_complete_update));
EXPECT_THAT(event_generator, UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::LOAD_COMPLETE, 1)));
}
TEST(AXEventGeneratorTest, LoadCompleteNewTree) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.has_tree_data = true;
initial_state.tree_data.loaded = true;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate load_complete_update;
load_complete_update.root_id = 2;
load_complete_update.nodes.resize(1);
load_complete_update.nodes[0].id = 2;
load_complete_update.nodes[0].relative_bounds.bounds =
gfx::RectF(0, 0, 800, 600);
load_complete_update.has_tree_data = true;
load_complete_update.tree_data.loaded = true;
ASSERT_TRUE(tree.Unserialize(load_complete_update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::LOAD_COMPLETE, 2),
HasEventAtNode(AXEventGenerator::Event::SUBTREE_CREATED, 2)));
// Load complete should not be emitted for sizeless roots.
load_complete_update.root_id = 3;
load_complete_update.nodes.resize(1);
load_complete_update.nodes[0].id = 3;
load_complete_update.nodes[0].relative_bounds.bounds = gfx::RectF(0, 0, 0, 0);
load_complete_update.has_tree_data = true;
load_complete_update.tree_data.loaded = true;
ASSERT_TRUE(tree.Unserialize(load_complete_update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::SUBTREE_CREATED, 3)));
// TODO(accessibility): http://crbug.com/888758
// Load complete should not be emitted for chrome-search URLs.
load_complete_update.root_id = 4;
load_complete_update.nodes.resize(1);
load_complete_update.nodes[0].id = 4;
load_complete_update.nodes[0].relative_bounds.bounds =
gfx::RectF(0, 0, 800, 600);
load_complete_update.nodes[0].AddStringAttribute(
ax::mojom::StringAttribute::kUrl, "chrome-search://foo");
load_complete_update.has_tree_data = true;
load_complete_update.tree_data.loaded = true;
ASSERT_TRUE(tree.Unserialize(load_complete_update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::LOAD_COMPLETE, 4),
HasEventAtNode(AXEventGenerator::Event::SUBTREE_CREATED, 4)));
}
TEST(AXEventGeneratorTest, LoadStart) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].relative_bounds.bounds = gfx::RectF(0, 0, 800, 600);
initial_state.has_tree_data = true;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate load_start_update;
load_start_update.root_id = 2;
load_start_update.nodes.resize(1);
load_start_update.nodes[0].id = 2;
load_start_update.nodes[0].relative_bounds.bounds =
gfx::RectF(0, 0, 800, 600);
load_start_update.has_tree_data = true;
load_start_update.tree_data.loaded = false;
ASSERT_TRUE(tree.Unserialize(load_start_update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::LOAD_START, 2),
HasEventAtNode(AXEventGenerator::Event::SUBTREE_CREATED, 2)));
}
TEST(AXEventGeneratorTest, DocumentSelectionChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.has_tree_data = true;
initial_state.tree_data.sel_focus_object_id = 1;
initial_state.tree_data.sel_focus_offset = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.tree_data.sel_focus_offset = 2;
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::DOCUMENT_SELECTION_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, DocumentTitleChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.has_tree_data = true;
initial_state.tree_data.title = "Before";
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.tree_data.title = "After";
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::DOCUMENT_TITLE_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, ExpandedAndRowCount) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(4);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(4);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kTable;
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kRow;
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kPopUpButton;
initial_state.nodes[3].AddState(ax::mojom::State::kExpanded);
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[2].AddState(ax::mojom::State::kExpanded);
update.nodes[3].state = 0;
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::COLLAPSED, 4),
HasEventAtNode(AXEventGenerator::Event::EXPANDED, 3),
HasEventAtNode(AXEventGenerator::Event::ROW_COUNT_CHANGED, 2),
HasEventAtNode(AXEventGenerator::Event::STATE_CHANGED, 3),
HasEventAtNode(AXEventGenerator::Event::STATE_CHANGED, 4)));
}
TEST(AXEventGeneratorTest, SelectedAndSelectedChildren) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(4);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(4);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kMenu;
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kMenuItem;
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kListBoxOption;
initial_state.nodes[3].AddBoolAttribute(ax::mojom::BoolAttribute::kSelected,
true);
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[2].AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, true);
update.nodes.pop_back();
update.nodes.emplace_back();
update.nodes[3].id = 4;
update.nodes[3].role = ax::mojom::Role::kListBoxOption;
update.nodes[3].AddBoolAttribute(ax::mojom::BoolAttribute::kSelected, false);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::SELECTED_CHILDREN_CHANGED, 2),
HasEventAtNode(AXEventGenerator::Event::SELECTED_CHANGED, 3),
HasEventAtNode(AXEventGenerator::Event::SELECTED_CHANGED, 4)));
}
TEST(AXEventGeneratorTest, StringValueChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kTextField;
initial_state.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kValue,
"Before");
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].string_attributes.clear();
update.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kValue,
"After");
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator, UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::VALUE_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, FloatValueChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kSlider;
initial_state.nodes[0].AddFloatAttribute(
ax::mojom::FloatAttribute::kValueForRange, 1.0);
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].float_attributes.clear();
update.nodes[0].AddFloatAttribute(ax::mojom::FloatAttribute::kValueForRange,
2.0);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator, UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::VALUE_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, InvalidStatusChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kTextField;
initial_state.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kValue,
"Text");
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].SetInvalidState(ax::mojom::InvalidState::kTrue);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::INVALID_STATUS_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, AddLiveRegionAttribute) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kLiveStatus,
"polite");
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::LIVE_STATUS_CHANGED, 1),
HasEventAtNode(AXEventGenerator::Event::LIVE_REGION_CREATED, 1)));
event_generator.ClearEvents();
update.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kLiveStatus,
"assertive");
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::LIVE_STATUS_CHANGED, 1)));
event_generator.ClearEvents();
update.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kLiveStatus,
"off");
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::LIVE_STATUS_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, CheckedStateChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kCheckBox;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].SetCheckedState(ax::mojom::CheckedState::kTrue);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::CHECKED_STATE_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, ActiveDescendantChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kListBox;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(3);
initial_state.nodes[0].AddIntAttribute(
ax::mojom::IntAttribute::kActivedescendantId, 2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kListBoxOption;
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kListBoxOption;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].int_attributes.clear();
update.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kActivedescendantId,
3);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::ACTIVE_DESCENDANT_CHANGED, 1),
HasEventAtNode(AXEventGenerator::Event::RELATED_NODE_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, CreateAlertAndLiveRegion) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes.resize(4);
update.nodes[0].child_ids.push_back(2);
update.nodes[0].child_ids.push_back(3);
update.nodes[0].child_ids.push_back(4);
update.nodes[1].id = 2;
update.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kLiveStatus,
"polite");
// Blink should automatically add aria-live="assertive" to elements with role
// kAlert, but we should fire an alert event regardless.
update.nodes[2].id = 3;
update.nodes[2].role = ax::mojom::Role::kAlert;
// Elements with role kAlertDialog will *not* usually have a live region
// status, but again, we should always fire an alert event.
update.nodes[3].id = 4;
update.nodes[3].role = ax::mojom::Role::kAlertDialog;
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::ALERT, 3),
HasEventAtNode(AXEventGenerator::Event::ALERT, 4),
HasEventAtNode(AXEventGenerator::Event::CHILDREN_CHANGED, 1),
HasEventAtNode(AXEventGenerator::Event::LIVE_REGION_CREATED, 2),
HasEventAtNode(AXEventGenerator::Event::SUBTREE_CREATED, 2),
HasEventAtNode(AXEventGenerator::Event::SUBTREE_CREATED, 3),
HasEventAtNode(AXEventGenerator::Event::SUBTREE_CREATED, 4)));
}
TEST(AXEventGeneratorTest, LiveRegionChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].AddStringAttribute(
ax::mojom::StringAttribute::kLiveStatus, "polite");
initial_state.nodes[0].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(3);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kStaticText;
initial_state.nodes[1].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
initial_state.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kName,
"Before 1");
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kStaticText;
initial_state.nodes[2].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
initial_state.nodes[2].AddStringAttribute(ax::mojom::StringAttribute::kName,
"Before 2");
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].string_attributes.clear();
update.nodes[1].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
update.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kName,
"After 1");
update.nodes[2].string_attributes.clear();
update.nodes[2].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
update.nodes[2].AddStringAttribute(ax::mojom::StringAttribute::kName,
"After 2");
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::LIVE_REGION_CHANGED, 1),
HasEventAtNode(AXEventGenerator::Event::LIVE_REGION_NODE_CHANGED, 2),
HasEventAtNode(AXEventGenerator::Event::LIVE_REGION_NODE_CHANGED, 3),
HasEventAtNode(AXEventGenerator::Event::NAME_CHANGED, 2),
HasEventAtNode(AXEventGenerator::Event::NAME_CHANGED, 3)));
}
TEST(AXEventGeneratorTest, LiveRegionOnlyTextChanges) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].AddStringAttribute(
ax::mojom::StringAttribute::kLiveStatus, "polite");
initial_state.nodes[0].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(3);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kStaticText;
initial_state.nodes[1].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
initial_state.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kName,
"Before 1");
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kStaticText;
initial_state.nodes[2].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
initial_state.nodes[2].AddStringAttribute(ax::mojom::StringAttribute::kName,
"Before 2");
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kDescription,
"Description 1");
update.nodes[2].SetCheckedState(ax::mojom::CheckedState::kTrue);
// Note that we do NOT expect a LIVE_REGION_CHANGED event here, because
// the name did not change.
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::CHECKED_STATE_CHANGED, 3),
HasEventAtNode(AXEventGenerator::Event::DESCRIPTION_CHANGED, 2)));
}
TEST(AXEventGeneratorTest, BusyLiveRegionChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].AddStringAttribute(
ax::mojom::StringAttribute::kLiveStatus, "polite");
initial_state.nodes[0].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
initial_state.nodes[0].AddBoolAttribute(ax::mojom::BoolAttribute::kBusy,
true);
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(3);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kStaticText;
initial_state.nodes[1].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
initial_state.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kName,
"Before 1");
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kStaticText;
initial_state.nodes[2].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
initial_state.nodes[2].AddStringAttribute(ax::mojom::StringAttribute::kName,
"Before 2");
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].string_attributes.clear();
update.nodes[1].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
update.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kName,
"After 1");
update.nodes[2].string_attributes.clear();
update.nodes[2].AddStringAttribute(
ax::mojom::StringAttribute::kContainerLiveStatus, "polite");
update.nodes[2].AddStringAttribute(ax::mojom::StringAttribute::kName,
"After 2");
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::NAME_CHANGED, 2),
HasEventAtNode(AXEventGenerator::Event::NAME_CHANGED, 3)));
}
TEST(AXEventGeneratorTest, AddChild) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(2);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes.resize(3);
update.nodes[0].child_ids.push_back(3);
update.nodes[2].id = 3;
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::CHILDREN_CHANGED, 1),
HasEventAtNode(AXEventGenerator::Event::SUBTREE_CREATED, 3)));
}
TEST(AXEventGeneratorTest, RemoveChild) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(3);
initial_state.nodes[1].id = 2;
initial_state.nodes[2].id = 3;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes.resize(2);
update.nodes[0].child_ids.clear();
update.nodes[0].child_ids.push_back(2);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::CHILDREN_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, ReorderChildren) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(3);
initial_state.nodes[1].id = 2;
initial_state.nodes[2].id = 3;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].child_ids.clear();
update.nodes[0].child_ids.push_back(3);
update.nodes[0].child_ids.push_back(2);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::CHILDREN_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, ScrollHorizontalPositionChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kScrollX, 10);
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::SCROLL_HORIZONTAL_POSITION_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, ScrollVerticalPositionChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kScrollY, 10);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::SCROLL_VERTICAL_POSITION_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, OtherAttributeChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(6);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(3);
initial_state.nodes[0].child_ids.push_back(4);
initial_state.nodes[0].child_ids.push_back(5);
initial_state.nodes[0].child_ids.push_back(6);
initial_state.nodes[1].id = 2;
initial_state.nodes[2].id = 3;
initial_state.nodes[3].id = 4;
initial_state.nodes[4].id = 5;
initial_state.nodes[5].id = 6;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kLanguage,
"de");
update.nodes[2].AddIntAttribute(ax::mojom::IntAttribute::kAriaCellColumnIndex,
7);
update.nodes[3].AddFloatAttribute(ax::mojom::FloatAttribute::kFontSize,
12.0f);
update.nodes[4].AddBoolAttribute(ax::mojom::BoolAttribute::kModal, true);
std::vector<int> ids = {2};
update.nodes[5].AddIntListAttribute(ax::mojom::IntListAttribute::kControlsIds,
ids);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::CONTROLS_CHANGED, 6),
HasEventAtNode(AXEventGenerator::Event::LANGUAGE_CHANGED, 2),
HasEventAtNode(AXEventGenerator::Event::OTHER_ATTRIBUTE_CHANGED, 3),
HasEventAtNode(AXEventGenerator::Event::OTHER_ATTRIBUTE_CHANGED, 4),
HasEventAtNode(AXEventGenerator::Event::OTHER_ATTRIBUTE_CHANGED, 5),
HasEventAtNode(AXEventGenerator::Event::RELATED_NODE_CHANGED, 6)));
}
TEST(AXEventGeneratorTest, NameChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(2);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].AddStringAttribute(ax::mojom::StringAttribute::kName,
"Hello");
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator, UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::NAME_CHANGED, 2)));
}
TEST(AXEventGeneratorTest, DescriptionChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kDescription,
"Hello");
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::DESCRIPTION_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, RoleChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].role = ax::mojom::Role::kCheckBox;
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator, UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::ROLE_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, MenuItemSelected) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kMenu;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[0].child_ids.push_back(3);
initial_state.nodes[0].AddIntAttribute(
ax::mojom::IntAttribute::kActivedescendantId, 2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kMenuListOption;
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kMenuListOption;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].int_attributes.clear();
update.nodes[0].AddIntAttribute(ax::mojom::IntAttribute::kActivedescendantId,
3);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::ACTIVE_DESCENDANT_CHANGED, 1),
HasEventAtNode(AXEventGenerator::Event::MENU_ITEM_SELECTED, 3),
HasEventAtNode(AXEventGenerator::Event::RELATED_NODE_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, NodeBecomesIgnored) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(5);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kArticle;
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
initial_state.nodes[2].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[2].child_ids.push_back(4);
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kGroup;
initial_state.nodes[3].child_ids.push_back(5);
initial_state.nodes[4].id = 5;
initial_state.nodes[4].role = ax::mojom::Role::kStaticText;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[3].AddState(ax::mojom::State::kIgnored);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::CHILDREN_CHANGED, 2),
HasEventAtNode(AXEventGenerator::Event::IGNORED_CHANGED, 4)));
}
TEST(AXEventGeneratorTest, NodeBecomesIgnored2) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(5);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kArticle;
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
initial_state.nodes[2].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[2].child_ids.push_back(4);
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kGroup;
initial_state.nodes[3].child_ids.push_back(5);
initial_state.nodes[4].id = 5;
initial_state.nodes[4].role = ax::mojom::Role::kStaticText;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
// Marking as ignored should fire CHILDREN_CHANGED on 2
update.nodes[3].AddState(ax::mojom::State::kIgnored);
// Remove node id 5 so it also fires CHILDREN_CHANGED on 4.
update.nodes.pop_back();
update.nodes[3].child_ids.clear();
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::CHILDREN_CHANGED, 2),
HasEventAtNode(AXEventGenerator::Event::IGNORED_CHANGED, 4)));
}
TEST(AXEventGeneratorTest, NodeBecomesUnignored) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(5);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kArticle;
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
initial_state.nodes[2].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[2].child_ids.push_back(4);
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kGroup;
initial_state.nodes[3].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[3].child_ids.push_back(5);
initial_state.nodes[4].id = 5;
initial_state.nodes[4].role = ax::mojom::Role::kStaticText;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[3].state = 0;
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::CHILDREN_CHANGED, 2),
HasEventAtNode(AXEventGenerator::Event::SUBTREE_CREATED, 4),
HasEventAtNode(AXEventGenerator::Event::IGNORED_CHANGED, 4)));
}
TEST(AXEventGeneratorTest, NodeBecomesUnignored2) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(5);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kArticle;
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
initial_state.nodes[2].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[2].child_ids.push_back(4);
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kGroup;
initial_state.nodes[3].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[3].child_ids.push_back(5);
initial_state.nodes[4].id = 5;
initial_state.nodes[4].role = ax::mojom::Role::kStaticText;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
// Marking as no longer ignored should fire CHILDREN_CHANGED on 2
update.nodes[3].state = 0;
// Remove node id 5 so it also fires CHILDREN_CHANGED on 4.
update.nodes.pop_back();
update.nodes[3].child_ids.clear();
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::CHILDREN_CHANGED, 2),
HasEventAtNode(AXEventGenerator::Event::SUBTREE_CREATED, 4),
HasEventAtNode(AXEventGenerator::Event::IGNORED_CHANGED, 4)));
}
TEST(AXEventGeneratorTest, SubtreeBecomesUnignored) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kArticle;
initial_state.nodes[1].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
initial_state.nodes[2].AddState(ax::mojom::State::kIgnored);
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].RemoveState(ax::mojom::State::kIgnored);
update.nodes[2].RemoveState(ax::mojom::State::kIgnored);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::CHILDREN_CHANGED, 1),
HasEventAtNode(AXEventGenerator::Event::SUBTREE_CREATED, 2),
HasEventAtNode(AXEventGenerator::Event::IGNORED_CHANGED, 2),
HasEventAtNode(AXEventGenerator::Event::IGNORED_CHANGED, 3)));
}
TEST(AXEventGeneratorTest, TwoNodesSwapIgnored) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kArticle;
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
initial_state.nodes[2].AddState(ax::mojom::State::kIgnored);
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].AddState(ax::mojom::State::kIgnored);
update.nodes[2].RemoveState(ax::mojom::State::kIgnored);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::CHILDREN_CHANGED, 1),
HasEventAtNode(AXEventGenerator::Event::IGNORED_CHANGED, 2),
HasEventAtNode(AXEventGenerator::Event::IGNORED_CHANGED, 3),
HasEventAtNode(AXEventGenerator::Event::SUBTREE_CREATED, 3)));
}
TEST(AXEventGeneratorTest, TwoNodesSwapIgnored2) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kArticle;
initial_state.nodes[1].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].RemoveState(ax::mojom::State::kIgnored);
update.nodes[2].AddState(ax::mojom::State::kIgnored);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::CHILDREN_CHANGED, 1),
HasEventAtNode(AXEventGenerator::Event::IGNORED_CHANGED, 2),
HasEventAtNode(AXEventGenerator::Event::IGNORED_CHANGED, 3),
HasEventAtNode(AXEventGenerator::Event::SUBTREE_CREATED, 2)));
}
TEST(AXEventGeneratorTest, ActiveDescendantChangeOnDescendant) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(5);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kGenericContainer;
initial_state.nodes[1].child_ids.push_back(3);
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGroup;
initial_state.nodes[2].AddIntAttribute(
ax::mojom::IntAttribute::kActivedescendantId, 4);
initial_state.nodes[2].child_ids.push_back(4);
initial_state.nodes[2].child_ids.push_back(5);
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kGroup;
initial_state.nodes[4].id = 5;
initial_state.nodes[4].role = ax::mojom::Role::kGroup;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
initial_state.nodes[2].RemoveIntAttribute(
ax::mojom::IntAttribute::kActivedescendantId);
initial_state.nodes[2].AddIntAttribute(
ax::mojom::IntAttribute::kActivedescendantId, 5);
AXTreeUpdate update = initial_state;
update.node_id_to_clear = 2;
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::ACTIVE_DESCENDANT_CHANGED, 3),
HasEventAtNode(AXEventGenerator::Event::RELATED_NODE_CHANGED, 3)));
}
TEST(AXEventGeneratorTest, ImageAnnotationChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddStringAttribute(
ax::mojom::StringAttribute::kImageAnnotation, "Hello");
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::IMAGE_ANNOTATION_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, ImageAnnotationStatusChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].SetImageAnnotationStatus(
ax::mojom::ImageAnnotationStatus::kAnnotationSucceeded);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::IMAGE_ANNOTATION_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, StringPropertyChanges) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
struct {
ax::mojom::StringAttribute id;
std::string old_value;
std::string new_value;
} attributes[] = {
{ax::mojom::StringAttribute::kAccessKey, "a", "b"},
{ax::mojom::StringAttribute::kClassName, "a", "b"},
{ax::mojom::StringAttribute::kKeyShortcuts, "a", "b"},
{ax::mojom::StringAttribute::kLanguage, "a", "b"},
{ax::mojom::StringAttribute::kPlaceholder, "a", "b"},
};
for (auto&& attrib : attributes) {
initial_state.nodes.push_back({});
initial_state.nodes.back().id = initial_state.nodes.size();
initial_state.nodes.back().AddStringAttribute(attrib.id, attrib.old_value);
initial_state.nodes[0].child_ids.push_back(initial_state.nodes.size());
}
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
int index = 1;
for (auto&& attrib : attributes) {
initial_state.nodes[index++].AddStringAttribute(attrib.id,
attrib.new_value);
}
AXTreeUpdate update = initial_state;
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::ACCESS_KEY_CHANGED, 2),
HasEventAtNode(AXEventGenerator::Event::CLASS_NAME_CHANGED, 3),
HasEventAtNode(AXEventGenerator::Event::KEY_SHORTCUTS_CHANGED, 4),
HasEventAtNode(AXEventGenerator::Event::LANGUAGE_CHANGED, 5),
HasEventAtNode(AXEventGenerator::Event::PLACEHOLDER_CHANGED, 6)));
}
TEST(AXEventGeneratorTest, IntPropertyChanges) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
struct {
ax::mojom::IntAttribute id;
int old_value;
int new_value;
} attributes[] = {
{ax::mojom::IntAttribute::kHierarchicalLevel, 1, 2},
{ax::mojom::IntAttribute::kPosInSet, 1, 2},
{ax::mojom::IntAttribute::kSetSize, 1, 2},
};
for (auto&& attrib : attributes) {
initial_state.nodes.push_back({});
initial_state.nodes.back().id = initial_state.nodes.size();
initial_state.nodes.back().AddIntAttribute(attrib.id, attrib.old_value);
initial_state.nodes[0].child_ids.push_back(initial_state.nodes.size());
}
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
int index = 1;
for (auto&& attrib : attributes)
initial_state.nodes[index++].AddIntAttribute(attrib.id, attrib.new_value);
AXTreeUpdate update = initial_state;
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::HIERARCHICAL_LEVEL_CHANGED,
2),
HasEventAtNode(AXEventGenerator::Event::POSITION_IN_SET_CHANGED, 3),
HasEventAtNode(AXEventGenerator::Event::SET_SIZE_CHANGED, 4)));
}
TEST(AXEventGeneratorTest, IntListPropertyChanges) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
struct {
ax::mojom::IntListAttribute id;
std::vector<int> old_value;
std::vector<int> new_value;
} attributes[] = {
{ax::mojom::IntListAttribute::kDescribedbyIds, {1}, {2}},
{ax::mojom::IntListAttribute::kFlowtoIds, {1}, {2}},
{ax::mojom::IntListAttribute::kLabelledbyIds, {1}, {2}},
};
for (auto&& attrib : attributes) {
initial_state.nodes.push_back({});
initial_state.nodes.back().id = initial_state.nodes.size();
initial_state.nodes.back().AddIntListAttribute(attrib.id, attrib.old_value);
initial_state.nodes[0].child_ids.push_back(initial_state.nodes.size());
}
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
int index = 1;
for (auto&& attrib : attributes) {
initial_state.nodes[index++].AddIntListAttribute(attrib.id,
attrib.new_value);
}
AXTreeUpdate update = initial_state;
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::DESCRIBED_BY_CHANGED, 2),
HasEventAtNode(AXEventGenerator::Event::FLOW_FROM_CHANGED, 1),
HasEventAtNode(AXEventGenerator::Event::FLOW_FROM_CHANGED, 2),
HasEventAtNode(AXEventGenerator::Event::FLOW_TO_CHANGED, 3),
HasEventAtNode(AXEventGenerator::Event::LABELED_BY_CHANGED, 4),
HasEventAtNode(AXEventGenerator::Event::RELATED_NODE_CHANGED, 2),
HasEventAtNode(AXEventGenerator::Event::RELATED_NODE_CHANGED, 3),
HasEventAtNode(AXEventGenerator::Event::RELATED_NODE_CHANGED, 4)));
}
TEST(AXEventGeneratorTest, AriaBusyChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
initial_state.nodes[0].AddBoolAttribute(ax::mojom::BoolAttribute::kBusy,
true);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddBoolAttribute(ax::mojom::BoolAttribute::kBusy, false);
ASSERT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::BUSY_CHANGED, 1),
HasEventAtNode(AXEventGenerator::Event::LAYOUT_INVALIDATED, 1)));
}
TEST(AXEventGeneratorTest, MultiselectableStateChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kGrid;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddState(ax::mojom::State::kMultiselectable);
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::MULTISELECTABLE_STATE_CHANGED,
1),
HasEventAtNode(AXEventGenerator::Event::STATE_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, RequiredStateChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kTextField;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddState(ax::mojom::State::kRequired);
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::REQUIRED_STATE_CHANGED, 1),
HasEventAtNode(AXEventGenerator::Event::STATE_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, FlowToChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(6);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].role = ax::mojom::Role::kGenericContainer;
initial_state.nodes[0].child_ids.assign({2, 3, 4, 5, 6});
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kGenericContainer;
initial_state.nodes[1].AddIntListAttribute(
ax::mojom::IntListAttribute::kFlowtoIds, {3, 4});
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kGenericContainer;
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kGenericContainer;
initial_state.nodes[4].id = 5;
initial_state.nodes[4].role = ax::mojom::Role::kGenericContainer;
initial_state.nodes[5].id = 6;
initial_state.nodes[5].role = ax::mojom::Role::kGenericContainer;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[1].AddIntListAttribute(ax::mojom::IntListAttribute::kFlowtoIds,
{4, 5, 6});
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::FLOW_FROM_CHANGED, 3),
HasEventAtNode(AXEventGenerator::Event::FLOW_FROM_CHANGED, 5),
HasEventAtNode(AXEventGenerator::Event::FLOW_FROM_CHANGED, 6),
HasEventAtNode(AXEventGenerator::Event::FLOW_TO_CHANGED, 2),
HasEventAtNode(AXEventGenerator::Event::RELATED_NODE_CHANGED, 2)));
}
TEST(AXEventGeneratorTest, ControlsChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(2);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids.push_back(2);
initial_state.nodes[1].id = 2;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
std::vector<int> ids = {2};
update.nodes[0].AddIntListAttribute(ax::mojom::IntListAttribute::kControlsIds,
ids);
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::CONTROLS_CHANGED, 1),
HasEventAtNode(AXEventGenerator::Event::RELATED_NODE_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, AtomicChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddBoolAttribute(ax::mojom::BoolAttribute::kLiveAtomic, true);
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::ATOMIC_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, DropeffectChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddDropeffect(ax::mojom::Dropeffect::kCopy);
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::DROPEFFECT_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, GrabbedChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddBoolAttribute(ax::mojom::BoolAttribute::kGrabbed, true);
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::GRABBED_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, HasPopupChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].SetHasPopup(ax::mojom::HasPopup::kTrue);
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::HASPOPUP_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, LiveRelevantChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddStringAttribute(ax::mojom::StringAttribute::kLiveRelevant,
"all");
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_THAT(event_generator,
UnorderedElementsAre(HasEventAtNode(
AXEventGenerator::Event::LIVE_RELEVANT_CHANGED, 1)));
}
TEST(AXEventGeneratorTest, MultilineStateChanged) {
AXTreeUpdate initial_state;
initial_state.root_id = 1;
initial_state.nodes.resize(1);
initial_state.nodes[0].id = 1;
AXTree tree(initial_state);
AXEventGenerator event_generator(&tree);
AXTreeUpdate update = initial_state;
update.nodes[0].AddState(ax::mojom::State::kMultiline);
EXPECT_TRUE(tree.Unserialize(update));
EXPECT_THAT(
event_generator,
UnorderedElementsAre(
HasEventAtNode(AXEventGenerator::Event::MULTILINE_STATE_CHANGED, 1),
HasEventAtNode(AXEventGenerator::Event::STATE_CHANGED, 1)));
}
} // namespace ui
| endlessm/chromium-browser | ui/accessibility/ax_event_generator_unittest.cc | C++ | bsd-3-clause | 56,678 |
'use strict';
const bundleTypes = {
UMD_DEV: 'UMD_DEV',
UMD_PROD: 'UMD_PROD',
NODE_DEV: 'NODE_DEV',
NODE_PROD: 'NODE_PROD',
FB_DEV: 'FB_DEV',
FB_PROD: 'FB_PROD',
RN_DEV: 'RN_DEV',
RN_PROD: 'RN_PROD',
};
const UMD_DEV = bundleTypes.UMD_DEV;
const UMD_PROD = bundleTypes.UMD_PROD;
const NODE_DEV = bundleTypes.NODE_DEV;
const NODE_PROD = bundleTypes.NODE_PROD;
const FB_DEV = bundleTypes.FB_DEV;
const FB_PROD = bundleTypes.FB_PROD;
const RN_DEV = bundleTypes.RN_DEV;
const RN_PROD = bundleTypes.RN_PROD;
const babelOptsReact = {
exclude: 'node_modules/**',
presets: [],
plugins: [],
};
const babelOptsReactART = Object.assign({}, babelOptsReact, {
// Include JSX
presets: babelOptsReact.presets.concat([
require.resolve('babel-preset-react'),
]),
});
const bundles = [
/******* Isomorphic *******/
{
babelOpts: babelOptsReact,
bundleTypes: [UMD_DEV, UMD_PROD, NODE_DEV, NODE_PROD, FB_DEV, FB_PROD],
config: {
destDir: 'build/',
moduleName: 'React',
sourceMap: false,
},
entry: 'src/isomorphic/React.js',
externals: [
'create-react-class/factory',
'prop-types',
'prop-types/checkPropTypes',
],
fbEntry: 'src/fb/ReactFBEntry.js',
hasteName: 'React',
isRenderer: false,
label: 'core',
manglePropertiesOnProd: false,
name: 'react',
paths: [
'src/isomorphic/**/*.js',
'src/addons/**/*.js',
'src/ReactVersion.js',
'src/shared/**/*.js',
],
},
/******* React DOM *******/
{
babelOpts: babelOptsReact,
bundleTypes: [UMD_DEV, UMD_PROD, NODE_DEV, NODE_PROD, FB_DEV, FB_PROD],
config: {
destDir: 'build/',
globals: {
react: 'React',
},
moduleName: 'ReactDOM',
sourceMap: false,
},
entry: 'src/renderers/dom/fiber/ReactDOMFiber.js',
externals: ['prop-types', 'prop-types/checkPropTypes'],
fbEntry: 'src/fb/ReactDOMFiberFBEntry.js',
hasteName: 'ReactDOMFiber',
isRenderer: true,
label: 'dom-fiber',
manglePropertiesOnProd: false,
name: 'react-dom',
paths: [
'src/renderers/dom/**/*.js',
'src/renderers/shared/**/*.js',
'src/ReactVersion.js',
'src/shared/**/*.js',
],
},
{
babelOpts: babelOptsReact,
bundleTypes: [FB_DEV, NODE_DEV],
config: {
destDir: 'build/',
globals: {
react: 'React',
},
moduleName: 'ReactTestUtils',
sourceMap: false,
},
entry: 'src/renderers/dom/test/ReactTestUtils',
externals: [
'prop-types',
'prop-types/checkPropTypes',
'react',
'react-dom',
'react-test-renderer', // TODO (bvaughn) Remove this dependency before 16.0.0
],
fbEntry: 'src/renderers/dom/test/ReactTestUtils',
hasteName: 'ReactTestUtils',
isRenderer: true,
label: 'test-utils',
manglePropertiesOnProd: false,
name: 'react-dom/test-utils',
paths: [
'src/renderers/dom/test/**/*.js',
'src/renderers/shared/**/*.js',
'src/renderers/testing/**/*.js', // TODO (bvaughn) Remove this dependency before 16.0.0
'src/ReactVersion.js',
'src/shared/**/*.js',
],
},
/******* React DOM Server *******/
{
babelOpts: babelOptsReact,
bundleTypes: [FB_DEV, FB_PROD],
config: {
destDir: 'build/',
globals: {
react: 'React',
},
moduleName: 'ReactDOMServer',
sourceMap: false,
},
entry: 'src/renderers/dom/ReactDOMServer.js',
externals: ['prop-types', 'prop-types/checkPropTypes'],
fbEntry: 'src/renderers/dom/ReactDOMServer.js',
hasteName: 'ReactDOMServerStack',
isRenderer: true,
label: 'dom-server-stack',
manglePropertiesOnProd: false,
name: 'react-dom-stack/server',
paths: [
'src/renderers/dom/**/*.js',
'src/renderers/shared/**/*.js',
'src/ReactVersion.js',
'src/shared/**/*.js',
],
},
{
babelOpts: babelOptsReact,
bundleTypes: [UMD_DEV, UMD_PROD, NODE_DEV, NODE_PROD, FB_DEV, FB_PROD],
config: {
destDir: 'build/',
globals: {
react: 'React',
},
moduleName: 'ReactDOMServer',
sourceMap: false,
},
entry: 'src/renderers/dom/ReactDOMServerStream.js',
externals: ['prop-types', 'prop-types/checkPropTypes'],
fbEntry: 'src/renderers/dom/ReactDOMServerStream.js',
hasteName: 'ReactDOMServerStream',
isRenderer: true,
label: 'dom-server-stream',
manglePropertiesOnProd: false,
name: 'react-dom/server',
paths: [
'src/renderers/dom/**/*.js',
'src/renderers/shared/**/*.js',
'src/ReactVersion.js',
'src/shared/**/*.js',
],
},
/******* React ART *******/
{
babelOpts: babelOptsReactART,
// TODO: we merge react-art repo into this repo so the NODE_DEV and NODE_PROD
// builds sync up to the building of the package directories
bundleTypes: [UMD_DEV, UMD_PROD, NODE_DEV, NODE_PROD, FB_DEV, FB_PROD],
config: {
destDir: 'build/',
globals: {
react: 'React',
},
moduleName: 'ReactART',
sourceMap: false,
},
entry: 'src/renderers/art/ReactARTFiber.js',
externals: [
'art/modes/current',
'art/modes/fast-noSideEffects',
'art/core/transform',
'prop-types/checkPropTypes',
'react-dom',
],
fbEntry: 'src/renderers/art/ReactARTFiber.js',
hasteName: 'ReactARTFiber',
isRenderer: true,
label: 'art-fiber',
manglePropertiesOnProd: false,
name: 'react-art',
paths: [
'src/renderers/art/**/*.js',
'src/renderers/shared/**/*.js',
'src/ReactVersion.js',
'src/shared/**/*.js',
],
},
/******* React Native *******/
{
babelOpts: babelOptsReact,
bundleTypes: [RN_DEV, RN_PROD],
config: {
destDir: 'build/',
moduleName: 'ReactNativeStack',
sourceMap: false,
},
entry: 'src/renderers/native/ReactNativeStack.js',
externals: [
'ExceptionsManager',
'InitializeCore',
'ReactNativeFeatureFlags',
'RCTEventEmitter',
'TextInputState',
'UIManager',
'View',
'deepDiffer',
'deepFreezeAndThrowOnMutationInDev',
'flattenStyle',
'prop-types/checkPropTypes',
],
hasteName: 'ReactNativeStack',
isRenderer: true,
label: 'native-stack',
manglePropertiesOnProd: false,
name: 'react-native-renderer',
paths: [
'src/renderers/native/**/*.js',
'src/renderers/shared/**/*.js',
'src/ReactVersion.js',
'src/shared/**/*.js',
],
useFiber: false,
modulesToStub: [
"'createReactNativeComponentClassFiber'",
"'ReactNativeFiberRenderer'",
"'findNumericNodeHandleFiber'",
"'ReactNativeFiber'",
],
},
{
babelOpts: babelOptsReact,
bundleTypes: [RN_DEV, RN_PROD],
config: {
destDir: 'build/',
moduleName: 'ReactNativeFiber',
sourceMap: false,
},
entry: 'src/renderers/native/ReactNativeFiber.js',
externals: [
'ExceptionsManager',
'InitializeCore',
'ReactNativeFeatureFlags',
'RCTEventEmitter',
'TextInputState',
'UIManager',
'View',
'deepDiffer',
'deepFreezeAndThrowOnMutationInDev',
'flattenStyle',
'prop-types/checkPropTypes',
],
hasteName: 'ReactNativeFiber',
isRenderer: true,
label: 'native-fiber',
manglePropertiesOnProd: false,
name: 'react-native-renderer',
paths: [
'src/renderers/native/**/*.js',
'src/renderers/shared/**/*.js',
'src/ReactVersion.js',
'src/shared/**/*.js',
],
useFiber: true,
modulesToStub: [
"'createReactNativeComponentClassStack'",
"'findNumericNodeHandleStack'",
"'ReactNativeStack'",
],
},
/******* React Test Renderer *******/
{
babelOpts: babelOptsReact,
bundleTypes: [FB_DEV, NODE_DEV],
config: {
destDir: 'build/',
moduleName: 'ReactTestRenderer',
sourceMap: false,
},
entry: 'src/renderers/testing/ReactTestRendererFiber',
externals: ['prop-types/checkPropTypes'],
fbEntry: 'src/renderers/testing/ReactTestRendererFiber',
hasteName: 'ReactTestRendererFiber',
isRenderer: true,
label: 'test-fiber',
manglePropertiesOnProd: false,
name: 'react-test-renderer',
paths: [
'src/renderers/native/**/*.js',
'src/renderers/shared/**/*.js',
'src/renderers/testing/**/*.js',
'src/ReactVersion.js',
'src/shared/**/*.js',
],
},
{
babelOpts: babelOptsReact,
bundleTypes: [FB_DEV, NODE_DEV],
config: {
destDir: 'build/',
moduleName: 'ReactTestRenderer',
sourceMap: false,
},
entry: 'src/renderers/testing/stack/ReactTestRendererStack',
externals: ['prop-types/checkPropTypes'],
fbEntry: 'src/renderers/testing/stack/ReactTestRendererStack',
hasteName: 'ReactTestRendererStack',
isRenderer: true,
label: 'test-stack',
manglePropertiesOnProd: false,
name: 'react-test-renderer/stack',
paths: [
'src/renderers/native/**/*.js',
'src/renderers/shared/**/*.js',
'src/renderers/testing/**/*.js',
'src/ReactVersion.js',
'src/shared/**/*.js',
],
},
{
babelOpts: babelOptsReact,
bundleTypes: [FB_DEV, NODE_DEV],
config: {
destDir: 'build/',
moduleName: 'ReactShallowRenderer',
sourceMap: false,
},
entry: 'src/renderers/testing/ReactShallowRenderer',
externals: [
'react-dom',
'prop-types/checkPropTypes',
'react-test-renderer',
],
fbEntry: 'src/renderers/testing/ReactShallowRenderer',
hasteName: 'ReactShallowRenderer',
isRenderer: true,
label: 'shallow-renderer',
manglePropertiesOnProd: false,
name: 'react-test-renderer/shallow',
paths: ['src/renderers/shared/**/*.js', 'src/renderers/testing/**/*.js'],
},
/******* React Noop Renderer (used only for fixtures/fiber-debugger) *******/
{
babelOpts: babelOptsReact,
bundleTypes: [NODE_DEV],
config: {
destDir: 'build/',
globals: {
react: 'React',
},
moduleName: 'ReactNoop',
sourceMap: false,
},
entry: 'src/renderers/noop/ReactNoop.js',
externals: ['prop-types/checkPropTypes'],
isRenderer: true,
label: 'noop-fiber',
manglePropertiesOnProd: false,
name: 'react-noop-renderer',
paths: [
'src/renderers/noop/**/*.js',
'src/renderers/shared/**/*.js',
'src/ReactVersion.js',
'src/shared/**/*.js',
],
},
];
module.exports = {
bundleTypes,
bundles,
};
| edvinerikson/react | scripts/rollup/bundles.js | JavaScript | bsd-3-clause | 10,623 |
#include "Ht.h"
#include "PersTest00.h"
void CPersTest00::PersTest00() {
if (PR1_htValid) {
switch (PR1_htInst) {
case TEST00_ENTRY: {
HtContinue(TEST00_WR);
break;
}
case TEST00_WR: {
S_test00_0_src_u0_data.write_addr(1);
S_test00_0_src_u0_data.write_mem().test00_0_src_v2_data = ((uint16_t)0x001bcfbd25fc3420LL);
HtContinue(TEST00_ST0);
break;
}
case TEST00_ST0: {
if (WriteMemBusy()) {
HtRetry();
break;
}
S_test00_0_src_u0_data.read_addr(1);
WriteMem_uint16_t(PR1_memAddr + 0, S_test00_0_src_u0_data.read_mem().test00_0_src_v2_data);
WriteMemPause(TEST00_LD0);
break;
}
case TEST00_LD0: {
if (ReadMemBusy()) {
HtRetry();
break;
}
ReadMem_test00_0_src_v3_data(PR1_memAddr + 0, 1, 1);
ReadMemPause(TEST00_CHK);
break;
}
case TEST00_CHK: {
S_test00_0_src_u0_data.read_addr(1);
if ((uint16_t)SR_test00_0_src_u0_data.read_mem().test00_0_src_v3_data != ((uint16_t)0x001bcfbd25fc3420LL)) {
HtAssert(0, 0);
}
HtContinue(TEST00_RTN);
break;
}
case TEST00_RTN: {
if (SendReturnBusy_test00()) {
HtRetry();
break;
}
SendReturn_test00();
break;
}
default:
assert(0);
}
}
}
| TonyBrewer/OpenHT | tests/memPSGRand_bug36/src_pers/PersTest00_src.cpp | C++ | bsd-3-clause | 1,206 |
require 'test_helper'
class DevelopmentValidationTest < ActiveSupport::TestCase
test 'requires housing units and commercial square feet' do
d.tothu = d.commsf = nil
refute d.valid?
d.tothu = d.commsf = 0
assert d.valid?, d.errors.full_messages
end
test 'requires extra housing information' do
# If it's in construction or completed, and there's more than
# one housing unit, require extra housing information.
housing_fields = Development::HOUSING_FIELDS
[:in_construction, :completed].each do |status|
d.status = status
d.tothu = 1
d.commsf = 0
housing_fields.each { |attrib| d.send("#{attrib}=", nil) }
refute d.valid?
housing_fields.each { |attrib| d.send("#{attrib}=", 0) }
d.singfamhu = 1 # for sum validation
assert d.valid?, d.errors.full_messages
end
[:in_construction, :completed].each do |status|
d.status = status
d.tothu = d.commsf = 0
housing_fields.each { |attrib| d.send("#{attrib}=", nil) }
assert d.valid?, d.errors.full_messages
end
end
test 'requires extra nonres information if in_construction or completed' do
nonres_fields = Development::COMMERCIAL_FIELDS
[:in_construction, :completed].each do |status|
d.status = status
d.tothu = 0
d.commsf = 1
nonres_fields.each { |attrib| d.send("#{attrib}=", nil) }
refute d.valid?
nonres_fields.each { |attrib| d.send("#{attrib}=", 0) }
d.fa_ret = 1 # For sum validation
assert d.valid?, d.errors.full_messages
end
[:in_construction, :completed].each do |status|
d.status = status
d.tothu = d.commsf = 0
nonres_fields.each { |attrib| d.send("#{attrib}=", nil) }
assert d.valid?, d.errors.full_messages
end
end
test 'housing units must add up' do
d.status = :in_construction
d.tothu = 100
d.commsf = d.gqpop = 0
d.singfamhu = d.twnhsmmult = d.lgmultifam = 0
refute d.valid?
d.singfamhu = 100
assert d.valid?, d.errors.full_messages
d.singfamhu = d.twnhsmmult = 25
d.lgmultifam = 50
assert d.valid?, d.errors.full_messages
end
test 'commercial square feet must add up' do
d.status = :in_construction
d.tothu = 0
d.commsf = 1000
d.fa_ret = 0
d.fa_ofcmd = 0
d.fa_indmf = 0
d.fa_whs = 0
d.fa_rnd = 0
d.fa_edinst = 0
d.fa_other = 0
d.fa_hotel = 0
refute d.valid?
d.fa_ret = 1000
assert d.valid?, d.errors.full_messages
d.fa_ret = d.fa_ofcmd = d.fa_hotel = d.fa_other = 250
assert d.valid?, d.errors.full_messages
end
end
| MAPC/developmentdatabase | test/models/development_validation_test.rb | Ruby | bsd-3-clause | 2,638 |