repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
openkava/PublicStable | Native/ThirdParty/Private/include/boost/boost/asio/detail/win_iocp_socket_accept_op.hpp | 5246 | //
// detail/win_iocp_socket_accept_op.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_DETAIL_WIN_IOCP_SOCKET_ACCEPT_OP_HPP
#define BOOST_ASIO_DETAIL_WIN_IOCP_SOCKET_ACCEPT_OP_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#if defined(BOOST_ASIO_HAS_IOCP)
#include <boost/utility/addressof.hpp>
#include <boost/asio/detail/bind_handler.hpp>
#include <boost/asio/detail/buffer_sequence_adapter.hpp>
#include <boost/asio/detail/fenced_block.hpp>
#include <boost/asio/detail/handler_alloc_helpers.hpp>
#include <boost/asio/detail/handler_invoke_helpers.hpp>
#include <boost/asio/detail/operation.hpp>
#include <boost/asio/detail/socket_ops.hpp>
#include <boost/asio/detail/win_iocp_socket_service_base.hpp>
#include <boost/asio/error.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace detail {
template <typename Socket, typename Protocol, typename Handler>
class win_iocp_socket_accept_op : public operation
{
public:
BOOST_ASIO_DEFINE_HANDLER_PTR(win_iocp_socket_accept_op);
win_iocp_socket_accept_op(win_iocp_socket_service_base& socket_service,
socket_type socket, Socket& peer, const Protocol& protocol,
typename Protocol::endpoint* peer_endpoint,
bool enable_connection_aborted, Handler& handler)
: operation(&win_iocp_socket_accept_op::do_complete),
socket_service_(socket_service),
socket_(socket),
peer_(peer),
protocol_(protocol),
peer_endpoint_(peer_endpoint),
enable_connection_aborted_(enable_connection_aborted),
handler_(BOOST_ASIO_MOVE_CAST(Handler)(handler))
{
}
socket_holder& new_socket()
{
return new_socket_;
}
void* output_buffer()
{
return output_buffer_;
}
DWORD address_length()
{
return sizeof(sockaddr_storage_type) + 16;
}
static void do_complete(io_service_impl* owner, operation* base,
boost::system::error_code ec, std::size_t /*bytes_transferred*/)
{
// Take ownership of the operation object.
win_iocp_socket_accept_op* o(static_cast<win_iocp_socket_accept_op*>(base));
ptr p = { boost::addressof(o->handler_), o, o };
if (owner)
{
typename Protocol::endpoint peer_endpoint;
std::size_t addr_len = peer_endpoint.capacity();
socket_ops::complete_iocp_accept(o->socket_,
o->output_buffer(), o->address_length(),
peer_endpoint.data(), &addr_len,
o->new_socket_.get(), ec);
// Restart the accept operation if we got the connection_aborted error
// and the enable_connection_aborted socket option is not set.
if (ec == boost::asio::error::connection_aborted
&& !o->enable_connection_aborted_)
{
o->reset();
o->socket_service_.restart_accept_op(o->socket_,
o->new_socket_, o->protocol_.family(),
o->protocol_.type(), o->protocol_.protocol(),
o->output_buffer(), o->address_length(), o);
p.v = p.p = 0;
return;
}
// If the socket was successfully accepted, transfer ownership of the
// socket to the peer object.
if (!ec)
{
o->peer_.assign(o->protocol_,
typename Socket::native_handle_type(
o->new_socket_.get(), peer_endpoint), ec);
if (!ec)
o->new_socket_.release();
}
// Pass endpoint back to caller.
if (o->peer_endpoint_)
*o->peer_endpoint_ = peer_endpoint;
}
BOOST_ASIO_HANDLER_COMPLETION((o));
// Make a copy of the handler so that the memory can be deallocated before
// the upcall is made. Even if we're not about to make an upcall, a
// sub-object of the handler may be the true owner of the memory associated
// with the handler. Consequently, a local copy of the handler is required
// to ensure that any owning sub-object remains valid until after we have
// deallocated the memory here.
detail::binder1<Handler, boost::system::error_code>
handler(o->handler_, ec);
p.h = boost::addressof(handler.handler_);
p.reset();
// Make the upcall if required.
if (owner)
{
boost::asio::detail::fenced_block b;
BOOST_ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_));
boost_asio_handler_invoke_helpers::invoke(handler, handler.handler_);
BOOST_ASIO_HANDLER_INVOCATION_END;
}
}
private:
win_iocp_socket_service_base& socket_service_;
socket_type socket_;
socket_holder new_socket_;
Socket& peer_;
Protocol protocol_;
typename Protocol::endpoint* peer_endpoint_;
unsigned char output_buffer_[(sizeof(sockaddr_storage_type) + 16) * 2];
bool enable_connection_aborted_;
Handler handler_;
};
} // namespace detail
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#endif // defined(BOOST_ASIO_HAS_IOCP)
#endif // BOOST_ASIO_DETAIL_WIN_IOCP_SOCKET_ACCEPT_OP_HPP
| agpl-3.0 |
Grasia/bolotweet | plugins/Bookmark/js/bookmark.js | 983 | var Bookmark = {
// Special XHR that sends in some code to be run
// when the full bookmark form gets loaded
BookmarkXHR: function(form)
{
SN.U.FormXHR(form, Bookmark.InitBookmarkForm);
return false;
},
// Special initialization function just for the
// second step in the bookmarking workflow
InitBookmarkForm: function() {
SN.Init.CheckBoxes();
$('fieldset fieldset label').inFieldLabels({ fadeOpacity:0 });
SN.Init.NoticeFormSetup($('#form_new_bookmark'));
}
}
$(document).ready(function() {
// Stop normal live event stuff
$('form.ajax').die();
$('form.ajax input[type=submit]').die();
// Make the bookmark submit super special
$('#form_initial_bookmark').bind('submit', function(e) {
Bookmark.BookmarkXHR($(this));
e.stopPropagation();
return false;
});
// Restore live event stuff to other forms & submit buttons
SN.Init.AjaxForms();
});
| agpl-3.0 |
summoners-riftodon/mastodon | app/services/post_status_service.rb | 3626 | # frozen_string_literal: true
class PostStatusService < BaseService
# Post a text status update, fetch and notify remote users mentioned
# @param [Account] account Account from which to post
# @param [String] text Message
# @param [Status] in_reply_to Optional status to reply to
# @param [Hash] options
# @option [Boolean] :sensitive
# @option [String] :visibility
# @option [String] :spoiler_text
# @option [Enumerable] :media_ids Optional array of media IDs to attach
# @option [Doorkeeper::Application] :application
# @option [String] :idempotency Optional idempotency key
# @return [Status]
def call(account, text, in_reply_to = nil, **options)
if options[:idempotency].present?
existing_id = redis.get("idempotency:status:#{account.id}:#{options[:idempotency]}")
return Status.find(existing_id) if existing_id
end
media = validate_media!(options[:media_ids])
status = nil
text = options.delete(:spoiler_text) if text.blank? && options[:spoiler_text].present?
ApplicationRecord.transaction do
status = account.statuses.create!(text: text,
media_attachments: media || [],
thread: in_reply_to,
sensitive: (options[:sensitive].nil? ? account.user&.setting_default_sensitive : options[:sensitive]) || options[:spoiler_text].present?,
spoiler_text: options[:spoiler_text] || '',
visibility: options[:visibility] || account.user&.setting_default_privacy,
language: language_from_option(options[:language]) || account.user&.setting_default_language&.presence || LanguageDetector.instance.detect(text, account),
application: options[:application])
end
process_hashtags_service.call(status)
process_mentions_service.call(status)
LinkCrawlWorker.perform_async(status.id) unless status.spoiler_text?
DistributionWorker.perform_async(status.id)
Pubsubhubbub::DistributionWorker.perform_async(status.stream_entry.id)
ActivityPub::DistributionWorker.perform_async(status.id)
ActivityPub::ReplyDistributionWorker.perform_async(status.id) if status.reply? && status.thread.account.local?
if options[:idempotency].present?
redis.setex("idempotency:status:#{account.id}:#{options[:idempotency]}", 3_600, status.id)
end
bump_potential_friendship(account, status)
status
end
private
def validate_media!(media_ids)
return if media_ids.blank? || !media_ids.is_a?(Enumerable)
raise Mastodon::ValidationError, I18n.t('media_attachments.validations.too_many') if media_ids.size > 4
media = MediaAttachment.where(status_id: nil).where(id: media_ids.take(4).map(&:to_i))
raise Mastodon::ValidationError, I18n.t('media_attachments.validations.images_and_video') if media.size > 1 && media.find(&:video?)
media
end
def language_from_option(str)
ISO_639.find(str)&.alpha2
end
def process_mentions_service
ProcessMentionsService.new
end
def process_hashtags_service
ProcessHashtagsService.new
end
def redis
Redis.current
end
def bump_potential_friendship(account, status)
return if !status.reply? || account.id == status.in_reply_to_account_id
ActivityTracker.increment('activity:interactions')
return if account.following?(status.in_reply_to_account_id)
PotentialFriendshipTracker.record(account.id, status.in_reply_to_account_id, :reply)
end
end
| agpl-3.0 |
shidao-fm/canvas-lms | app/models/notification_finder.rb | 1137 | #
# Copyright (C) 2011 - 2014 Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
class NotificationFinder
attr_reader :notifications
def initialize(notifications = Notification.all)
refresh_cache(notifications)
end
def find_by_name(name)
notifications[name]
end
alias :by_name :find_by_name
def reset_cache
@notifications = []
true
end
def refresh_cache(notifications = Notification.all)
@notifications = notifications.index_by(&:name)
@notifications.values.each(&:freeze)
true
end
end
| agpl-3.0 |
abcdelf/apm_planner | src/ui/QGCMAVLinkInspector.cc | 27683 | #include <QList>
#include "QGCMAVLink.h"
#include "QGCMAVLinkInspector.h"
#include "UASManager.h"
#include "LinkManager.h"
#include "ui_QGCMAVLinkInspector.h"
const float QGCMAVLinkInspector::updateHzLowpass = 0.2f;
const unsigned int QGCMAVLinkInspector::updateInterval = 1000U;
QGCMAVLinkInspector::QGCMAVLinkInspector(MAVLinkProtocol* protocol, QWidget *parent) :
QWidget(parent),
_protocol(protocol),
selectedSystemID(0),
selectedComponentID(0),
ui(new Ui::QGCMAVLinkInspector)
{
ui->setupUi(this);
// Make sure "All" is an option for both the system and components
ui->systemComboBox->addItem(tr("All"), 0);
ui->componentComboBox->addItem(tr("All"), 0);
// Store metadata for all MAVLink messages.
mavlink_message_info_t msg_infos[256] = MAVLINK_MESSAGE_INFO;
memcpy(messageInfo, msg_infos, sizeof(mavlink_message_info_t)*256);
// Set up the column headers for the message listing
QStringList header;
header << tr("Name");
header << tr("Value");
header << tr("Type");
ui->treeWidget->setHeaderLabels(header);
ui->treeWidget->sortByColumn(0,Qt::AscendingOrder);
// Set up the column headers for the rate listing
QStringList rateHeader;
rateHeader << tr("Name");
rateHeader << tr("#ID");
rateHeader << tr("Rate");
ui->rateTreeWidget->setHeaderLabels(rateHeader);
connect(ui->rateTreeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)),
this, SLOT(rateTreeItemChanged(QTreeWidgetItem*,int)));
ui->rateTreeWidget->hide();
// Connect the UI
connect(ui->systemComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(selectDropDownMenuSystem(int)));
connect(ui->componentComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(selectDropDownMenuComponent(int)));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clearView()));
// Connect external connections
connect(UASManager::instance(), SIGNAL(UASCreated(UASInterface*)), this, SLOT(addSystem(UASInterface*)));
connect(LinkManager::instance(), SIGNAL(messageReceived(LinkInterface*,mavlink_message_t)), this, SLOT(receiveMessage(LinkInterface*,mavlink_message_t)));
for(int count=0; count < UASManager::instance()->getUASList().count();count++){
addSystem(UASManager::instance()->getUASList()[count]);
}
// Attach the UI's refresh rate to a timer.
connect(&updateTimer, SIGNAL(timeout()), this, SLOT(refreshView()));
updateTimer.start(updateInterval);
}
void QGCMAVLinkInspector::addSystem(UASInterface* uas)
{
ui->systemComboBox->addItem(uas->getUASName(), uas->getUASID());
// Add a tree for a new UAS
addUAStoTree(uas->getUASID());
}
void QGCMAVLinkInspector::selectDropDownMenuSystem(int dropdownid)
{
selectedSystemID = ui->systemComboBox->itemData(dropdownid).toInt();
rebuildComponentList();
if (selectedSystemID != 0 && selectedComponentID != 0) {
ui->rateTreeWidget->show();
} else {
ui->rateTreeWidget->hide();
}
}
void QGCMAVLinkInspector::selectDropDownMenuComponent(int dropdownid)
{
selectedComponentID = ui->componentComboBox->itemData(dropdownid).toInt();
if (selectedSystemID != 0 && selectedComponentID != 0) {
ui->rateTreeWidget->show();
} else {
ui->rateTreeWidget->hide();
}
}
void QGCMAVLinkInspector::rebuildComponentList()
{
ui->componentComboBox->clear();
components.clear();
ui->componentComboBox->addItem(tr("All"), 0);
// Fill
UASInterface* uas = UASManager::instance()->getUASForId(selectedSystemID);
if (uas)
{
QMap<int, QString> components = uas->getComponents();
foreach (int id, components.keys())
{
QString name = components.value(id);
ui->componentComboBox->addItem(name, id);
}
}
}
void QGCMAVLinkInspector::addComponent(int uas, int component, const QString& name)
{
Q_UNUSED(component);
Q_UNUSED(name);
if (uas != selectedSystemID) return;
rebuildComponentList();
}
/**
* Reset the view. This entails clearing all data structures and resetting data from already-
* received messages.
*/
void QGCMAVLinkInspector::clearView()
{
QMap<int, mavlink_message_t* >::iterator ite;
for(ite=uasMessageStorage.begin(); ite!=uasMessageStorage.end();++ite)
{
delete ite.value();
ite.value() = NULL;
}
uasMessageStorage.clear();
QMap<int, QMap<int, QTreeWidgetItem*>* >::iterator iteMsg;
for (iteMsg=uasMsgTreeItems.begin(); iteMsg!=uasMsgTreeItems.end();++iteMsg)
{
QMap<int, QTreeWidgetItem*>* msgTreeItems = iteMsg.value();
QList<int> groupKeys = msgTreeItems->uniqueKeys();
QList<int>::iterator listKeys;
for (listKeys=groupKeys.begin();listKeys!=groupKeys.end();++listKeys)
{
delete msgTreeItems->take(*listKeys);
}
}
uasMsgTreeItems.clear();
QMap<int, QTreeWidgetItem* >::iterator iteTree;
for(iteTree=uasTreeWidgetItems.begin(); iteTree!=uasTreeWidgetItems.end();++iteTree)
{
delete iteTree.value();
iteTree.value() = NULL;
}
uasTreeWidgetItems.clear();
QMap<int, QMap<int, float>* >::iterator iteHz;
for (iteHz=uasMessageHz.begin(); iteHz!=uasMessageHz.end();++iteHz)
{
iteHz.value()->clear();
delete iteHz.value();
iteHz.value() = NULL;
}
uasMessageHz.clear();
QMap<int, QMap<int, unsigned int>* >::iterator iteCount;
for(iteCount=uasMessageCount.begin(); iteCount!=uasMessageCount.end();++iteCount)
{
iteCount.value()->clear();
delete iteCount.value();
iteCount.value() = NULL;
}
uasMessageCount.clear();
QMap<int, QMap<int, quint64>* >::iterator iteLast;
for(iteLast=uasLastMessageUpdate.begin(); iteLast!=uasLastMessageUpdate.end();++iteLast)
{
iteLast.value()->clear();
delete iteLast.value();
iteLast.value() = NULL;
}
uasLastMessageUpdate.clear();
onboardMessageInterval.clear();
ui->treeWidget->clear();
ui->rateTreeWidget->clear();
}
void QGCMAVLinkInspector::refreshView()
{
QMap<int, mavlink_message_t* >::const_iterator ite;
for(ite=uasMessageStorage.constBegin(); ite!=uasMessageStorage.constEnd();++ite)
{
mavlink_message_t* msg = ite.value();
// Ignore NULL values
if (msg->msgid == 0xFF) continue;
// Update the message frenquency
// Get the previous frequency for low-pass filtering
float msgHz = 0.0f;
QMap<int, QMap<int, float>* >::const_iterator iteHz = uasMessageHz.find(msg->sysid);
QMap<int, float>* uasMsgHz = iteHz.value();
while((iteHz != uasMessageHz.end()) && (iteHz.key() == msg->sysid))
{
if(iteHz.value()->contains(msg->msgid))
{
uasMsgHz = iteHz.value();
msgHz = iteHz.value()->value(msg->msgid);
break;
}
++iteHz;
}
// Get the number of message received
float msgCount = 0;
QMap<int, QMap<int, unsigned int> * >::const_iterator iter = uasMessageCount.find(msg->sysid);
QMap<int, unsigned int>* uasMsgCount = iter.value();
while((iter != uasMessageCount.end()) && (iter.key()==msg->sysid))
{
if(iter.value()->contains(msg->msgid))
{
msgCount = (float) iter.value()->value(msg->msgid);
uasMsgCount = iter.value();
break;
}
++iter;
}
// Compute the new low-pass filtered frequency and update the message count
msgHz = (1.0f-updateHzLowpass)* msgHz + updateHzLowpass*msgCount/((float)updateInterval/1000.0f);
uasMsgHz->insert(msg->msgid,msgHz);
uasMsgCount->insert(msg->msgid,(unsigned int) 0);
// Update the tree view
QString messageName("%1 (%2 Hz, #%3)");
messageName = messageName.arg(messageInfo[msg->msgid].name).arg(msgHz, 3, 'f', 1).arg(msg->msgid);
addUAStoTree(msg->sysid);
// Look for the tree for the UAS sysid
QMap<int, QTreeWidgetItem*>* msgTreeItems = uasMsgTreeItems.value(msg->sysid);
if (!msgTreeItems)
{
// The UAS tree has not been created yet, no update
return;
}
// Add the message with msgid to the tree if not done yet
if(!msgTreeItems->contains(msg->msgid))
{
QStringList fields;
fields << messageName;
QTreeWidgetItem* widget = new QTreeWidgetItem();
for (unsigned int i = 0; i < messageInfo[msg->msgid].num_fields; ++i)
{
QTreeWidgetItem* field = new QTreeWidgetItem();
widget->addChild(field);
}
msgTreeItems->insert(msg->msgid,widget);
QList<int> groupKeys = msgTreeItems->uniqueKeys();
int insertIndex = groupKeys.indexOf(msg->msgid);
uasTreeWidgetItems.value(msg->sysid)->insertChild(insertIndex,widget);
}
// Update the message
QTreeWidgetItem* message = msgTreeItems->value(msg->msgid);
if(message)
{
message->setFirstColumnSpanned(true);
message->setData(0, Qt::DisplayRole, QVariant(messageName));
for (unsigned int i = 0; i < messageInfo[msg->msgid].num_fields; ++i)
{
updateField(msg->sysid,msg->msgid, i, message->child(i));
}
}
}
if (selectedSystemID == 0 || selectedComponentID == 0)
{
return;
}
for (int i = 0; i < 256; ++i)//mavlink_message_t msg, receivedMessages)
{
QString msgname(messageInfo[i].name);
if (msgname.length() < 3) {
continue;
}
if (!msgname.contains("EMPTY")) {
continue;
}
// Update the tree view
QString messageName("%1");
messageName = messageName.arg(msgname);
if (!rateTreeWidgetItems.contains(i))
{
QStringList fields;
fields << messageName;
fields << QString("%1").arg(i);
fields << "OFF / --- Hz";
QTreeWidgetItem* widget = new QTreeWidgetItem(fields);
widget->setFlags(widget->flags() | Qt::ItemIsEditable);
rateTreeWidgetItems.insert(i, widget);
ui->rateTreeWidget->addTopLevelItem(widget);
}
// Set Hz
//QTreeWidgetItem* message = rateTreeWidgetItems.value(i);
//message->setData(0, Qt::DisplayRole, QVariant(messageName));
}
}
void QGCMAVLinkInspector::addUAStoTree(int sysId)
{
if(!uasTreeWidgetItems.contains(sysId))
{
// Add the UAS to the main tree after it has been created
UASInterface* uas = UASManager::instance()->getUASForId(sysId);
if (uas)
{
QStringList idstring;
if (uas->getUASName() == "")
{
idstring << tr("UAS ") + QString::number(uas->getUASID());
}
else
{
idstring << uas->getUASName();
}
QTreeWidgetItem* uasWidget = new QTreeWidgetItem(idstring);
uasWidget->setFirstColumnSpanned(true);
uasTreeWidgetItems.insert(sysId,uasWidget);
ui->treeWidget->addTopLevelItem(uasWidget);
uasMsgTreeItems.insert(sysId,new QMap<int, QTreeWidgetItem*>());
}
}
}
void QGCMAVLinkInspector::receiveMessage(LinkInterface* link,mavlink_message_t message)
{
Q_UNUSED(link);
quint64 receiveTime;
if (selectedSystemID != 0 && selectedSystemID != message.sysid) return;
if (selectedComponentID != 0 && selectedComponentID != message.compid) return;
// Create dynamically an array to store the messages for each UAS
if (!uasMessageStorage.contains(message.sysid))
{
mavlink_message_t* msg = new mavlink_message_t;
*msg = message;
uasMessageStorage.insertMulti(message.sysid,msg);
}
bool msgFound = false;
QMap<int, mavlink_message_t* >::const_iterator iteMsg = uasMessageStorage.find(message.sysid);
mavlink_message_t* uasMessage = iteMsg.value();
while((iteMsg != uasMessageStorage.end()) && (iteMsg.key() == message.sysid))
{
if (iteMsg.value()->msgid == message.msgid)
{
msgFound = true;
uasMessage = iteMsg.value();
break;
}
++iteMsg;
}
if (!msgFound)
{
mavlink_message_t* msgIdMessage = new mavlink_message_t;
*msgIdMessage = message;
uasMessageStorage.insertMulti(message.sysid,msgIdMessage);
}
else
{
*uasMessage = message;
}
// Looking if this message has already been received once
msgFound = false;
QMap<int, QMap<int, quint64>* >::const_iterator ite = uasLastMessageUpdate.find(message.sysid);
QMap<int, quint64>* lastMsgUpdate = ite.value();
while((ite != uasLastMessageUpdate.end()) && (ite.key() == message.sysid))
{
if(ite.value()->contains(message.msgid))
{
msgFound = true;
// Point to the found message
lastMsgUpdate = ite.value();
break;
}
++ite;
}
receiveTime = QGC::groundTimeMilliseconds();
// If the message doesn't exist, create a map for the frequency, message count and time of reception
if(!msgFound)
{
// Create a map for the message frequency
QMap<int, float>* messageHz = new QMap<int,float>;
messageHz->insert(message.msgid,0.0f);
uasMessageHz.insertMulti(message.sysid,messageHz);
// Create a map for the message count
QMap<int, unsigned int>* messagesCount = new QMap<int, unsigned int>;
messagesCount->insert(message.msgid,0);
uasMessageCount.insertMulti(message.sysid,messagesCount);
// Create a map for the time of reception of the message
QMap<int, quint64>* lastMessage = new QMap<int, quint64>;
lastMessage->insert(message.msgid,receiveTime);
uasLastMessageUpdate.insertMulti(message.sysid,lastMessage);
// Point to the created message
lastMsgUpdate = lastMessage;
}
else
{
// The message has been found/created
if ((lastMsgUpdate->contains(message.msgid))&&(uasMessageCount.contains(message.sysid)))
{
// Looking for and updating the message count
unsigned int count = 0;
QMap<int, QMap<int, unsigned int>* >::const_iterator iter = uasMessageCount.find(message.sysid);
QMap<int, unsigned int> * uasMsgCount = iter.value();
while((iter != uasMessageCount.end()) && (iter.key() == message.sysid))
{
if(iter.value()->contains(message.msgid))
{
uasMsgCount = iter.value();
count = uasMsgCount->value(message.msgid,0);
uasMsgCount->insert(message.msgid,count+1);
break;
}
++iter;
}
}
lastMsgUpdate->insert(message.msgid,receiveTime);
}
if (selectedSystemID == 0 || selectedComponentID == 0)
{
return;
}
switch (message.msgid)
{
case MAVLINK_MSG_ID_DATA_STREAM:
{
mavlink_data_stream_t stream;
mavlink_msg_data_stream_decode(&message, &stream);
onboardMessageInterval.insert(stream.stream_id, stream.message_rate);
}
break;
}
}
void QGCMAVLinkInspector::changeStreamInterval(int msgid, int interval)
{
//REQUEST_DATA_STREAM
if (selectedSystemID == 0 || selectedComponentID == 0) {
return;
}
// mavlink_request_data_stream_t stream;
// stream.target_system = selectedSystemID;
// stream.target_component = selectedComponentID;
// stream.req_stream_id = msgid;
// stream.req_message_rate = interval;
// stream.start_stop = (interval > 0);
// mavlink_message_t msg;
// mavlink_msg_request_data_stream_encode(_protocol->getSystemId(), _protocol->getComponentId(), &msg, &stream);
// _protocol->sendMessage(msg);
}
void QGCMAVLinkInspector::rateTreeItemChanged(QTreeWidgetItem* paramItem, int column)
{
if (paramItem && column > 0) {
int key = paramItem->data(1, Qt::DisplayRole).toInt();
QVariant value = paramItem->data(2, Qt::DisplayRole);
float interval = 1000 / value.toFloat();
qDebug() << "Stream " << key << "interval" << interval;
changeStreamInterval(key, interval);
}
}
QGCMAVLinkInspector::~QGCMAVLinkInspector()
{
clearView();
delete ui;
}
void QGCMAVLinkInspector::updateField(int sysid, int msgid, int fieldid, QTreeWidgetItem* item)
{
// Add field tree widget item
item->setData(0, Qt::DisplayRole, QVariant(messageInfo[msgid].fields[fieldid].name));
bool msgFound = false;
QMap<int, mavlink_message_t* >::const_iterator iteMsg = uasMessageStorage.find(sysid);
mavlink_message_t* uasMessage = iteMsg.value();
while((iteMsg != uasMessageStorage.end()) && (iteMsg.key() == sysid))
{
if (iteMsg.value()->msgid == msgid)
{
msgFound = true;
uasMessage = iteMsg.value();
break;
}
++iteMsg;
}
if (!msgFound)
{
return;
}
uint8_t* m = ((uint8_t*)uasMessage)+8;
switch (messageInfo[msgid].fields[fieldid].type)
{
case MAVLINK_TYPE_CHAR:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
char* str = (char*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
// Enforce null termination
str[messageInfo[msgid].fields[fieldid].array_length-1] = '\0';
QString string(str);
item->setData(2, Qt::DisplayRole, "char");
item->setData(1, Qt::DisplayRole, string);
}
else
{
// Single char
char b = *((char*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
item->setData(2, Qt::DisplayRole, QString("char[%1]").arg(messageInfo[msgid].fields[fieldid].array_length));
item->setData(1, Qt::DisplayRole, b);
}
break;
case MAVLINK_TYPE_UINT8_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
uint8_t* nums = m+messageInfo[msgid].fields[fieldid].wire_offset;
// Enforce null termination
QString tmp("%1, ");
QString string;
for (unsigned int j = 0; j < messageInfo[msgid].fields[fieldid].array_length; ++j)
{
string += tmp.arg(nums[j]);
}
item->setData(2, Qt::DisplayRole, QString("uint8_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length));
item->setData(1, Qt::DisplayRole, string);
}
else
{
// Single value
uint8_t u = *(m+messageInfo[msgid].fields[fieldid].wire_offset);
item->setData(2, Qt::DisplayRole, "uint8_t");
item->setData(1, Qt::DisplayRole, u);
}
break;
case MAVLINK_TYPE_INT8_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
int8_t* nums = (int8_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
// Enforce null termination
QString tmp("%1, ");
QString string;
for (unsigned int j = 0; j < messageInfo[msgid].fields[fieldid].array_length; ++j)
{
string += tmp.arg(nums[j]);
}
item->setData(2, Qt::DisplayRole, QString("int8_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length));
item->setData(1, Qt::DisplayRole, string);
}
else
{
// Single value
int8_t n = *((int8_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
item->setData(2, Qt::DisplayRole, "int8_t");
item->setData(1, Qt::DisplayRole, n);
}
break;
case MAVLINK_TYPE_UINT16_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
uint16_t* nums = (uint16_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
// Enforce null termination
QString tmp("%1, ");
QString string;
for (unsigned int j = 0; j < messageInfo[msgid].fields[fieldid].array_length; ++j)
{
string += tmp.arg(nums[j]);
}
item->setData(2, Qt::DisplayRole, QString("uint16_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length));
item->setData(1, Qt::DisplayRole, string);
}
else
{
// Single value
uint16_t n = *((uint16_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
item->setData(2, Qt::DisplayRole, "uint16_t");
item->setData(1, Qt::DisplayRole, n);
}
break;
case MAVLINK_TYPE_INT16_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
int16_t* nums = (int16_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
// Enforce null termination
QString tmp("%1, ");
QString string;
for (unsigned int j = 0; j < messageInfo[msgid].fields[fieldid].array_length; ++j)
{
string += tmp.arg(nums[j]);
}
item->setData(2, Qt::DisplayRole, QString("int16_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length));
item->setData(1, Qt::DisplayRole, string);
}
else
{
// Single value
int16_t n = *((int16_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
item->setData(2, Qt::DisplayRole, "int16_t");
item->setData(1, Qt::DisplayRole, n);
}
break;
case MAVLINK_TYPE_UINT32_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
uint32_t* nums = (uint32_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
// Enforce null termination
QString tmp("%1, ");
QString string;
for (unsigned int j = 0; j < messageInfo[msgid].fields[fieldid].array_length; ++j)
{
string += tmp.arg(nums[j]);
}
item->setData(2, Qt::DisplayRole, QString("uint32_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length));
item->setData(1, Qt::DisplayRole, string);
}
else
{
// Single value
float n = *((uint32_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
item->setData(2, Qt::DisplayRole, "uint32_t");
item->setData(1, Qt::DisplayRole, n);
}
break;
case MAVLINK_TYPE_INT32_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
int32_t* nums = (int32_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
// Enforce null termination
QString tmp("%1, ");
QString string;
for (unsigned int j = 0; j < messageInfo[msgid].fields[fieldid].array_length; ++j)
{
string += tmp.arg(nums[j]);
}
item->setData(2, Qt::DisplayRole, QString("int32_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length));
item->setData(1, Qt::DisplayRole, string);
}
else
{
// Single value
int32_t n = *((int32_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
item->setData(2, Qt::DisplayRole, "int32_t");
item->setData(1, Qt::DisplayRole, n);
}
break;
case MAVLINK_TYPE_FLOAT:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
float* nums = (float*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
// Enforce null termination
QString tmp("%1, ");
QString string;
for (unsigned int j = 0; j < messageInfo[msgid].fields[fieldid].array_length; ++j)
{
string += tmp.arg(nums[j]);
}
item->setData(2, Qt::DisplayRole, QString("float[%1]").arg(messageInfo[msgid].fields[fieldid].array_length));
item->setData(1, Qt::DisplayRole, string);
}
else
{
// Single value
float f = *((float*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
item->setData(2, Qt::DisplayRole, "float");
item->setData(1, Qt::DisplayRole, f);
}
break;
case MAVLINK_TYPE_DOUBLE:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
double* nums = (double*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
// Enforce null termination
QString tmp("%1, ");
QString string;
for (unsigned int j = 0; j < messageInfo[msgid].fields[fieldid].array_length; ++j)
{
string += tmp.arg(nums[j]);
}
item->setData(2, Qt::DisplayRole, QString("double[%1]").arg(messageInfo[msgid].fields[fieldid].array_length));
item->setData(1, Qt::DisplayRole, string);
}
else
{
// Single value
double f = *((double*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
item->setData(2, Qt::DisplayRole, "double");
item->setData(1, Qt::DisplayRole, f);
}
break;
case MAVLINK_TYPE_UINT64_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
uint64_t* nums = (uint64_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
// Enforce null termination
QString tmp("%1, ");
QString string;
for (unsigned int j = 0; j < messageInfo[msgid].fields[fieldid].array_length; ++j)
{
string += tmp.arg(nums[j]);
}
item->setData(2, Qt::DisplayRole, QString("uint64_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length));
item->setData(1, Qt::DisplayRole, string);
}
else
{
// Single value
uint64_t n = *((uint64_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
item->setData(2, Qt::DisplayRole, "uint64_t");
item->setData(1, Qt::DisplayRole, (quint64) n);
}
break;
case MAVLINK_TYPE_INT64_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
int64_t* nums = (int64_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
// Enforce null termination
QString tmp("%1, ");
QString string;
for (unsigned int j = 0; j < messageInfo[msgid].fields[fieldid].array_length; ++j)
{
string += tmp.arg(nums[j]);
}
item->setData(2, Qt::DisplayRole, QString("int64_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length));
item->setData(1, Qt::DisplayRole, string);
}
else
{
// Single value
int64_t n = *((int64_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
item->setData(2, Qt::DisplayRole, "int64_t");
item->setData(1, Qt::DisplayRole, (qint64) n);
}
break;
}
}
| agpl-3.0 |
bengusty/cbioportal | portal/src/main/webapp/js/lib/jsmol/j2s/J/thread/AnimationThread.js | 2984 | Clazz.declarePackage ("J.thread");
Clazz.load (["J.thread.JmolThread"], "J.thread.AnimationThread", ["JU.Logger"], function () {
c$ = Clazz.decorateAsClass (function () {
this.am = null;
this.framePointer1 = 0;
this.framePointer2 = 0;
this.intThread = 0;
this.isFirst = false;
Clazz.instantialize (this, arguments);
}, J.thread, "AnimationThread", J.thread.JmolThread);
Clazz.makeConstructor (c$,
function () {
Clazz.superConstructor (this, J.thread.AnimationThread, []);
});
Clazz.overrideMethod (c$, "setManager",
function (manager, vwr, params) {
var options = params;
this.framePointer1 = options[0];
this.framePointer2 = options[1];
this.intThread = options[2];
this.am = manager;
this.setViewer (vwr, "AnimationThread");
vwr.startHoverWatcher (false);
return 0;
}, "~O,JV.Viewer,~O");
Clazz.defineMethod (c$, "interrupt",
function () {
if (this.stopped) return;
this.stopped = true;
if (JU.Logger.debugging) JU.Logger.debug ("animation thread interrupted!");
try {
this.am.setAnimationOn (false);
} catch (e) {
if (Clazz.exceptionOf (e, Exception)) {
} else {
throw e;
}
}
Clazz.superCall (this, J.thread.AnimationThread, "interrupt", []);
});
Clazz.overrideMethod (c$, "run1",
function (mode) {
while (true) {
switch (mode) {
case -1:
if (JU.Logger.debugging) JU.Logger.debug ("animation thread " + this.intThread + " running");
this.vwr.requestRepaintAndWait ("animationThread");
this.vwr.startHoverWatcher (false);
this.haveReference = true;
this.isFirst = true;
mode = 0;
break;
case 0:
if (!this.am.animationOn || this.checkInterrupted (this.am.animationThread)) {
mode = -2;
break;
}if (this.am.currentFrameIs (this.framePointer1)) {
this.targetTime += this.am.firstFrameDelayMs;
this.sleepTime = (this.targetTime - (System.currentTimeMillis () - this.startTime));
if (!this.runSleep (this.sleepTime, 1)) return;
}mode = 1;
break;
case 1:
if (this.am.currentFrameIs (this.framePointer2)) {
this.targetTime += this.am.lastFrameDelayMs;
this.sleepTime = (this.targetTime - (System.currentTimeMillis () - this.startTime));
if (!this.runSleep (this.sleepTime, 2)) return;
}mode = 2;
break;
case 2:
if (!this.isFirst && this.am.currentIsLast () && !this.am.setAnimationNext ()) {
mode = -2;
break;
}this.isFirst = false;
this.targetTime += Clazz.floatToInt ((1000 / this.am.animationFps) + this.vwr.getFrameDelayMs (this.am.cmi));
mode = 3;
break;
case 3:
while (this.am.animationOn && !this.checkInterrupted (this.am.animationThread) && !this.vwr.getRefreshing ()) {
if (!this.runSleep (10, 3)) return;
}
if (!this.vwr.tm.spinOn) this.vwr.refresh (1, "animationThread");
this.sleepTime = (this.targetTime - (System.currentTimeMillis () - this.startTime));
if (!this.runSleep (this.sleepTime, 0)) return;
mode = 0;
break;
case -2:
if (JU.Logger.debugging) JU.Logger.debug ("animation thread " + this.intThread + " exiting");
this.am.stopThread (false);
return;
}
}
}, "~N");
});
| agpl-3.0 |
0-14N/soot-inflow | test/soot/jimple/infoflow/test/LengthTestCode.java | 1733 | /*******************************************************************************
* Copyright (c) 2012 Secure Software Engineering Group at EC SPRIDE.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors: Christian Fritz, Steven Arzt, Siegfried Rasthofer, Eric
* Bodden, and others.
******************************************************************************/
package soot.jimple.infoflow.test;
import soot.jimple.infoflow.test.android.ConnectionManager;
import soot.jimple.infoflow.test.android.TelephonyManager;
public class LengthTestCode{
public void easy1(){
String taint = TelephonyManager.getDeviceId();
Firstclass f = new Firstclass();
f.data.secretValue = taint;
ConnectionManager cm = new ConnectionManager();
cm.publish(f.data.publicValue);
}
public void method1(){
String taint = TelephonyManager.getDeviceId();
Firstclass f = new Firstclass();
f.data.secretValue = taint;
f.data.publicValue = "PUBLIC";
ConnectionManager cm = new ConnectionManager();
cm.publish(f.data.publicValue);
}
public void method2(){
String taint = TelephonyManager.getDeviceId();
Firstclass f = new Firstclass();
f.data.secretValue = taint;
f.data.publicValue = "PUBLIC";
ConnectionManager cm = new ConnectionManager();
cm.publish(f.data.secretValue);
}
class Firstclass{
SecondClass data;
public Firstclass(){
data = new SecondClass();
}
}
class SecondClass{
public String secretValue;
public String publicValue;
}
}
| lgpl-2.1 |
chowjee/VirtualApp | VirtualApp/lib/src/main/java/mirror/com/android/internal/telephony/ITelephonyRegistry.java | 609 | package mirror.com.android.internal.telephony;
import android.os.IBinder;
import android.os.IInterface;
import mirror.MethodParams;
import mirror.RefClass;
import mirror.RefStaticMethod;
public class ITelephonyRegistry {
public static Class<?> TYPE = RefClass.load(ITelephonyRegistry.class, "com.android.internal.telephony.ITelephonyRegistry");
public static class Stub {
public static Class<?> TYPE = RefClass.load(ITelephonyRegistry.Stub.class, "com.android.internal.telephony.ITelephonyRegistry$Stub");
@MethodParams({IBinder.class})
public static RefStaticMethod<IInterface> asInterface;
}
}
| lgpl-3.0 |
mjs/utils | parallel/try_test.go | 8503 | // Copyright 2013 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package parallel_test
import (
"errors"
"fmt"
"io"
"sort"
"sync"
"time"
"github.com/juju/testing"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
"github.com/juju/utils/parallel"
)
const (
shortWait = 50 * time.Millisecond
longWait = 10 * time.Second
)
type result string
func (r result) Close() error {
return nil
}
type trySuite struct {
testing.IsolationSuite
}
var _ = gc.Suite(&trySuite{})
func tryFunc(delay time.Duration, val io.Closer, err error) func(<-chan struct{}) (io.Closer, error) {
return func(<-chan struct{}) (io.Closer, error) {
time.Sleep(delay)
return val, err
}
}
func (*trySuite) TestOneSuccess(c *gc.C) {
try := parallel.NewTry(0, nil)
try.Start(tryFunc(0, result("hello"), nil))
val, err := try.Result()
c.Assert(err, gc.IsNil)
c.Assert(val, gc.Equals, result("hello"))
}
func (*trySuite) TestOneFailure(c *gc.C) {
try := parallel.NewTry(0, nil)
expectErr := errors.New("foo")
err := try.Start(tryFunc(0, nil, expectErr))
c.Assert(err, gc.IsNil)
select {
case <-try.Dead():
c.Fatalf("try died before it should")
case <-time.After(shortWait):
}
try.Close()
select {
case <-try.Dead():
case <-time.After(longWait):
c.Fatalf("timed out waiting for Try to complete")
}
val, err := try.Result()
c.Assert(val, gc.IsNil)
c.Assert(err, gc.Equals, expectErr)
}
func (*trySuite) TestStartReturnsErrorAfterClose(c *gc.C) {
try := parallel.NewTry(0, nil)
expectErr := errors.New("foo")
err := try.Start(tryFunc(0, nil, expectErr))
c.Assert(err, gc.IsNil)
try.Close()
err = try.Start(tryFunc(0, result("goodbye"), nil))
c.Assert(err, gc.Equals, parallel.ErrClosed)
// Wait for the first try to deliver its result
time.Sleep(shortWait)
try.Kill()
err = try.Wait()
c.Assert(err, gc.Equals, expectErr)
}
func (*trySuite) TestOutOfOrderResults(c *gc.C) {
try := parallel.NewTry(0, nil)
try.Start(tryFunc(50*time.Millisecond, result("first"), nil))
try.Start(tryFunc(10*time.Millisecond, result("second"), nil))
r, err := try.Result()
c.Assert(err, gc.IsNil)
c.Assert(r, gc.Equals, result("second"))
}
func (*trySuite) TestMaxParallel(c *gc.C) {
try := parallel.NewTry(3, nil)
var (
mu sync.Mutex
count int
max int
)
for i := 0; i < 10; i++ {
try.Start(func(<-chan struct{}) (io.Closer, error) {
mu.Lock()
if count++; count > max {
max = count
}
c.Check(count, gc.Not(jc.GreaterThan), 3)
mu.Unlock()
time.Sleep(20 * time.Millisecond)
mu.Lock()
count--
mu.Unlock()
return result("hello"), nil
})
}
r, err := try.Result()
c.Assert(err, gc.IsNil)
c.Assert(r, gc.Equals, result("hello"))
mu.Lock()
defer mu.Unlock()
c.Assert(max, gc.Equals, 3)
}
func (*trySuite) TestStartBlocksForMaxParallel(c *gc.C) {
try := parallel.NewTry(3, nil)
started := make(chan struct{})
begin := make(chan struct{})
go func() {
for i := 0; i < 6; i++ {
err := try.Start(func(<-chan struct{}) (io.Closer, error) {
<-begin
return nil, fmt.Errorf("an error")
})
started <- struct{}{}
if i < 5 {
c.Check(err, gc.IsNil)
} else {
c.Check(err, gc.Equals, parallel.ErrClosed)
}
}
close(started)
}()
// Check we can start the first three.
timeout := time.After(longWait)
for i := 0; i < 3; i++ {
select {
case <-started:
case <-timeout:
c.Fatalf("timed out")
}
}
// Check we block when going above maxParallel.
timeout = time.After(shortWait)
select {
case <-started:
c.Fatalf("Start did not block")
case <-timeout:
}
// Unblock two attempts.
begin <- struct{}{}
begin <- struct{}{}
// Check we can start another two.
timeout = time.After(longWait)
for i := 0; i < 2; i++ {
select {
case <-started:
case <-timeout:
c.Fatalf("timed out")
}
}
// Check we block again when going above maxParallel.
timeout = time.After(shortWait)
select {
case <-started:
c.Fatalf("Start did not block")
case <-timeout:
}
// Close the Try - the last request should be discarded,
// unblocking last remaining Start request.
try.Close()
timeout = time.After(longWait)
select {
case <-started:
case <-timeout:
c.Fatalf("Start did not unblock after Close")
}
// Ensure all checks are completed
select {
case _, ok := <-started:
c.Assert(ok, gc.Equals, false)
case <-timeout:
c.Fatalf("Start goroutine did not finish")
}
}
func (*trySuite) TestAllConcurrent(c *gc.C) {
try := parallel.NewTry(0, nil)
started := make(chan chan struct{})
for i := 0; i < 10; i++ {
try.Start(func(<-chan struct{}) (io.Closer, error) {
reply := make(chan struct{})
started <- reply
<-reply
return result("hello"), nil
})
}
timeout := time.After(longWait)
for i := 0; i < 10; i++ {
select {
case reply := <-started:
reply <- struct{}{}
case <-timeout:
c.Fatalf("timed out")
}
}
}
type gradedError int
func (e gradedError) Error() string {
return fmt.Sprintf("error with importance %d", e)
}
func gradedErrorCombine(err0, err1 error) error {
if err0 == nil || err0.(gradedError) < err1.(gradedError) {
return err1
}
return err0
}
type multiError struct {
errs []int
}
func (e *multiError) Error() string {
return fmt.Sprintf("%v", e.errs)
}
func (*trySuite) TestErrorCombine(c *gc.C) {
// Use maxParallel=1 to guarantee that all errors are processed sequentially.
try := parallel.NewTry(1, func(err0, err1 error) error {
if err0 == nil {
err0 = &multiError{}
}
err0.(*multiError).errs = append(err0.(*multiError).errs, int(err1.(gradedError)))
return err0
})
errors := []gradedError{3, 2, 4, 0, 5, 5, 3}
for _, err := range errors {
err := err
try.Start(func(<-chan struct{}) (io.Closer, error) {
return nil, err
})
}
try.Close()
val, err := try.Result()
c.Assert(val, gc.IsNil)
grades := err.(*multiError).errs
sort.Ints(grades)
c.Assert(grades, gc.DeepEquals, []int{0, 2, 3, 3, 4, 5, 5})
}
func (*trySuite) TestTriesAreStopped(c *gc.C) {
try := parallel.NewTry(0, nil)
stopped := make(chan struct{})
try.Start(func(stop <-chan struct{}) (io.Closer, error) {
<-stop
stopped <- struct{}{}
return nil, parallel.ErrStopped
})
try.Start(tryFunc(0, result("hello"), nil))
val, err := try.Result()
c.Assert(err, gc.IsNil)
c.Assert(val, gc.Equals, result("hello"))
select {
case <-stopped:
case <-time.After(longWait):
c.Fatalf("timed out waiting for stop")
}
}
func (*trySuite) TestCloseTwice(c *gc.C) {
try := parallel.NewTry(0, nil)
try.Close()
try.Close()
val, err := try.Result()
c.Assert(val, gc.IsNil)
c.Assert(err, gc.IsNil)
}
type closeResult struct {
closed chan struct{}
}
func (r *closeResult) Close() error {
close(r.closed)
return nil
}
func (*trySuite) TestExtraResultsAreClosed(c *gc.C) {
try := parallel.NewTry(0, nil)
begin := make([]chan struct{}, 4)
results := make([]*closeResult, len(begin))
for i := range begin {
begin[i] = make(chan struct{})
results[i] = &closeResult{make(chan struct{})}
i := i
try.Start(func(<-chan struct{}) (io.Closer, error) {
<-begin[i]
return results[i], nil
})
}
begin[0] <- struct{}{}
val, err := try.Result()
c.Assert(err, gc.IsNil)
c.Assert(val, gc.Equals, results[0])
timeout := time.After(shortWait)
for i, r := range results[1:] {
begin[i+1] <- struct{}{}
select {
case <-r.closed:
case <-timeout:
c.Fatalf("timed out waiting for close")
}
}
select {
case <-results[0].closed:
c.Fatalf("result was inappropriately closed")
case <-time.After(shortWait):
}
}
func (*trySuite) TestEverything(c *gc.C) {
try := parallel.NewTry(5, gradedErrorCombine)
tries := []struct {
startAt time.Duration
wait time.Duration
val result
err error
}{{
wait: 30 * time.Millisecond,
err: gradedError(3),
}, {
startAt: 10 * time.Millisecond,
wait: 20 * time.Millisecond,
val: result("result 1"),
}, {
startAt: 20 * time.Millisecond,
wait: 10 * time.Millisecond,
val: result("result 2"),
}, {
startAt: 20 * time.Millisecond,
wait: 5 * time.Second,
val: "delayed result",
}, {
startAt: 5 * time.Millisecond,
err: gradedError(4),
}}
for _, t := range tries {
t := t
go func() {
time.Sleep(t.startAt)
try.Start(tryFunc(t.wait, t.val, t.err))
}()
}
val, err := try.Result()
if val != result("result 1") && val != result("result 2") {
c.Errorf(`expected "result 1" or "result 2" got %#v`, val)
}
c.Assert(err, gc.IsNil)
}
| lgpl-3.0 |
ezpublishlegacy/LiveVotingBundle | Resources/public/js/handlebars-intl/dist/locale-data/rw.js | 1031 | HandlebarsIntl.__addLocaleData({"locale":"rw","pluralRuleFunction":function (n,ord){if(ord)return"other";return"other"},"fields":{"year":{"displayName":"Year","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}},"month":{"displayName":"Month","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"day":{"displayName":"Day","relative":{"0":"today","1":"tomorrow","-1":"yesterday"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"hour":{"displayName":"Hour","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"minute":{"displayName":"Minute","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"second":{"displayName":"Second","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}}}});
HandlebarsIntl.__addLocaleData({"locale":"rw-RW","parentLocale":"rw"});
| lgpl-3.0 |
djs55/vpnkit | go/pkg/vpnkit/transport/vsock.go | 18 | package transport
| apache-2.0 |
vobruba-martin/closure-compiler | contrib/externs/maps/google_maps_api_v3_22.js | 141134 | /*
* Copyright 2010 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Externs for the Google Maps v3.22 API.
* @see http://code.google.com/apis/maps/documentation/javascript/reference.html
* @externs
*/
/**
* @const
* @suppress {const,duplicate,strictMissingProperties}
*/
var google = {};
/** @const */
google.maps = {};
/**
* @enum {number}
*/
google.maps.Animation = {
BOUNCE: 1,
DROP: 2
};
/**
* @interface
*/
google.maps.Attribution = function() {};
/**
* @type {string}
*/
google.maps.Attribution.prototype.iosDeepLinkId;
/**
* @type {string}
*/
google.maps.Attribution.prototype.source;
/**
* @type {string}
*/
google.maps.Attribution.prototype.webUrl;
/**
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.BicyclingLayer = function() {};
/**
* @nosideeffects
* @return {google.maps.Map}
*/
google.maps.BicyclingLayer.prototype.getMap = function() {};
/**
* @param {google.maps.Map} map
* @return {undefined}
*/
google.maps.BicyclingLayer.prototype.setMap = function(map) {};
/**
* @param {(google.maps.CircleOptions|Object.<string>)=} opt_opts
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.Circle = function(opt_opts) {};
/**
* @nosideeffects
* @return {google.maps.LatLngBounds}
*/
google.maps.Circle.prototype.getBounds = function() {};
/**
* @nosideeffects
* @return {google.maps.LatLng}
*/
google.maps.Circle.prototype.getCenter = function() {};
/**
* @nosideeffects
* @return {boolean}
*/
google.maps.Circle.prototype.getDraggable = function() {};
/**
* @nosideeffects
* @return {boolean}
*/
google.maps.Circle.prototype.getEditable = function() {};
/**
* @nosideeffects
* @return {google.maps.Map}
*/
google.maps.Circle.prototype.getMap = function() {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.Circle.prototype.getRadius = function() {};
/**
* @nosideeffects
* @return {boolean}
*/
google.maps.Circle.prototype.getVisible = function() {};
/**
* @param {google.maps.LatLng|google.maps.LatLngLiteral} center
* @return {undefined}
*/
google.maps.Circle.prototype.setCenter = function(center) {};
/**
* @param {boolean} draggable
* @return {undefined}
*/
google.maps.Circle.prototype.setDraggable = function(draggable) {};
/**
* @param {boolean} editable
* @return {undefined}
*/
google.maps.Circle.prototype.setEditable = function(editable) {};
/**
* @param {google.maps.Map} map
* @return {undefined}
*/
google.maps.Circle.prototype.setMap = function(map) {};
/**
* @param {google.maps.CircleOptions|Object.<string>} options
* @return {undefined}
*/
google.maps.Circle.prototype.setOptions = function(options) {};
/**
* @param {number} radius
* @return {undefined}
*/
google.maps.Circle.prototype.setRadius = function(radius) {};
/**
* @param {boolean} visible
* @return {undefined}
*/
google.maps.Circle.prototype.setVisible = function(visible) {};
/**
* @interface
*/
google.maps.CircleOptions = function() {};
/**
* @type {google.maps.LatLng}
*/
google.maps.CircleOptions.prototype.center;
/**
* @type {boolean}
*/
google.maps.CircleOptions.prototype.clickable;
/**
* @type {boolean}
*/
google.maps.CircleOptions.prototype.draggable;
/**
* @type {boolean}
*/
google.maps.CircleOptions.prototype.editable;
/**
* @type {string}
*/
google.maps.CircleOptions.prototype.fillColor;
/**
* @type {number}
*/
google.maps.CircleOptions.prototype.fillOpacity;
/**
* @type {google.maps.Map}
*/
google.maps.CircleOptions.prototype.map;
/**
* @type {number}
*/
google.maps.CircleOptions.prototype.radius;
/**
* @type {string}
*/
google.maps.CircleOptions.prototype.strokeColor;
/**
* @type {number}
*/
google.maps.CircleOptions.prototype.strokeOpacity;
/**
* @type {google.maps.StrokePosition}
*/
google.maps.CircleOptions.prototype.strokePosition;
/**
* @type {number}
*/
google.maps.CircleOptions.prototype.strokeWeight;
/**
* @type {boolean}
*/
google.maps.CircleOptions.prototype.visible;
/**
* @type {number}
*/
google.maps.CircleOptions.prototype.zIndex;
/**
* @enum {number}
*/
google.maps.ControlPosition = {
BOTTOM_CENTER: 1,
BOTTOM_LEFT: 2,
BOTTOM_RIGHT: 3,
LEFT_BOTTOM: 4,
LEFT_CENTER: 5,
LEFT_TOP: 6,
RIGHT_BOTTOM: 7,
RIGHT_CENTER: 8,
RIGHT_TOP: 9,
TOP_CENTER: 10,
TOP_LEFT: 11,
TOP_RIGHT: 12
};
/**
* @param {(google.maps.Data.DataOptions|Object.<string>)=} opt_options
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.Data = function(opt_options) {};
/**
* @param {google.maps.Data.Feature|google.maps.Data.FeatureOptions|Object.<string>} feature
* @return {google.maps.Data.Feature}
*/
google.maps.Data.prototype.add = function(feature) {};
/**
* @param {Object} geoJson
* @param {(google.maps.Data.GeoJsonOptions|Object.<string>)=} opt_options
* @return {Array<google.maps.Data.Feature>}
*/
google.maps.Data.prototype.addGeoJson = function(geoJson, opt_options) {};
/**
* @param {google.maps.Data.Feature} feature
* @return {boolean}
*/
google.maps.Data.prototype.contains = function(feature) {};
/**
* @param {function(google.maps.Data.Feature)} callback
* @return {undefined}
*/
google.maps.Data.prototype.forEach = function(callback) {};
/**
* @nosideeffects
* @return {google.maps.ControlPosition}
*/
google.maps.Data.prototype.getControlPosition = function() {};
/**
* @nosideeffects
* @return {Array<string>}
*/
google.maps.Data.prototype.getControls = function() {};
/**
* @nosideeffects
* @return {?string}
*/
google.maps.Data.prototype.getDrawingMode = function() {};
/**
* @param {number|string} id
* @return {google.maps.Data.Feature|undefined}
*/
google.maps.Data.prototype.getFeatureById = function(id) {};
/**
* @nosideeffects
* @return {google.maps.Map}
*/
google.maps.Data.prototype.getMap = function() {};
/**
* @nosideeffects
* @return {google.maps.Data.StylingFunction|google.maps.Data.StyleOptions|Object.<string>}
*/
google.maps.Data.prototype.getStyle = function() {};
/**
* @param {string} url
* @param {(google.maps.Data.GeoJsonOptions|Object.<string>)=} opt_options
* @param {function(Array<google.maps.Data.Feature>)=} opt_callback
* @return {undefined}
*/
google.maps.Data.prototype.loadGeoJson = function(url, opt_options, opt_callback) {};
/**
* @param {google.maps.Data.Feature} feature
* @param {google.maps.Data.StyleOptions|Object.<string>} style
* @return {undefined}
*/
google.maps.Data.prototype.overrideStyle = function(feature, style) {};
/**
* @param {google.maps.Data.Feature} feature
* @return {undefined}
*/
google.maps.Data.prototype.remove = function(feature) {};
/**
* @param {google.maps.Data.Feature=} opt_feature
* @return {undefined}
*/
google.maps.Data.prototype.revertStyle = function(opt_feature) {};
/**
* @param {google.maps.ControlPosition} controlPosition
* @return {undefined}
*/
google.maps.Data.prototype.setControlPosition = function(controlPosition) {};
/**
* @param {Array<string>} controls
* @return {undefined}
*/
google.maps.Data.prototype.setControls = function(controls) {};
/**
* @param {?string} drawingMode
* @return {undefined}
*/
google.maps.Data.prototype.setDrawingMode = function(drawingMode) {};
/**
* @param {google.maps.Map} map
* @return {undefined}
*/
google.maps.Data.prototype.setMap = function(map) {};
/**
* @param {google.maps.Data.StylingFunction|google.maps.Data.StyleOptions|Object.<string>} style
* @return {undefined}
*/
google.maps.Data.prototype.setStyle = function(style) {};
/**
* @param {function(Object)} callback
* @return {undefined}
*/
google.maps.Data.prototype.toGeoJson = function(callback) {};
/**
* @interface
*/
google.maps.Data.AddFeatureEvent = function() {};
/**
* @type {google.maps.Data.Feature}
*/
google.maps.Data.AddFeatureEvent.prototype.feature;
/**
* @interface
*/
google.maps.Data.DataOptions = function() {};
/**
* @type {google.maps.ControlPosition}
*/
google.maps.Data.DataOptions.prototype.controlPosition;
/**
* @type {Array<string>}
*/
google.maps.Data.DataOptions.prototype.controls;
/**
* @type {string}
*/
google.maps.Data.DataOptions.prototype.drawingMode;
/**
* @type {function(google.maps.Data.Geometry): google.maps.Data.Feature}
*/
google.maps.Data.DataOptions.prototype.featureFactory;
/**
* @type {google.maps.Map}
*/
google.maps.Data.DataOptions.prototype.map;
/**
* @type {google.maps.Data.StylingFunction|google.maps.Data.StyleOptions|Object.<string>}
*/
google.maps.Data.DataOptions.prototype.style;
/**
* @param {(google.maps.Data.FeatureOptions|Object.<string>)=} opt_options
* @constructor
*/
google.maps.Data.Feature = function(opt_options) {};
/**
* @param {function(*, string)} callback
* @return {undefined}
*/
google.maps.Data.Feature.prototype.forEachProperty = function(callback) {};
/**
* @nosideeffects
* @return {google.maps.Data.Geometry}
*/
google.maps.Data.Feature.prototype.getGeometry = function() {};
/**
* @nosideeffects
* @return {number|string|undefined}
*/
google.maps.Data.Feature.prototype.getId = function() {};
/**
* @param {string} name
* @return {*}
*/
google.maps.Data.Feature.prototype.getProperty = function(name) {};
/**
* @param {string} name
* @return {undefined}
*/
google.maps.Data.Feature.prototype.removeProperty = function(name) {};
/**
* @param {google.maps.Data.Geometry|google.maps.LatLng|google.maps.LatLngLiteral} newGeometry
* @return {undefined}
*/
google.maps.Data.Feature.prototype.setGeometry = function(newGeometry) {};
/**
* @param {string} name
* @param {*} newValue
* @return {undefined}
*/
google.maps.Data.Feature.prototype.setProperty = function(name, newValue) {};
/**
* @param {function(Object)} callback
* @return {undefined}
*/
google.maps.Data.Feature.prototype.toGeoJson = function(callback) {};
/**
* @interface
*/
google.maps.Data.FeatureOptions = function() {};
/**
* @type {google.maps.Data.Geometry|google.maps.LatLng|google.maps.LatLngLiteral}
*/
google.maps.Data.FeatureOptions.prototype.geometry;
/**
* @type {number|string}
*/
google.maps.Data.FeatureOptions.prototype.id;
/**
* @type {Object}
*/
google.maps.Data.FeatureOptions.prototype.properties;
/**
* @interface
*/
google.maps.Data.GeoJsonOptions = function() {};
/**
* @type {string}
*/
google.maps.Data.GeoJsonOptions.prototype.idPropertyName;
/**
* @constructor
*/
google.maps.Data.Geometry = function() {};
/**
* @nosideeffects
* @return {string}
*/
google.maps.Data.Geometry.prototype.getType = function() {};
/**
* @param {Array<google.maps.Data.Geometry|google.maps.LatLng|google.maps.LatLngLiteral>} elements
* @extends {google.maps.Data.Geometry}
* @constructor
*/
google.maps.Data.GeometryCollection = function(elements) {};
/**
* @nosideeffects
* @return {Array<google.maps.Data.Geometry>}
*/
google.maps.Data.GeometryCollection.prototype.getArray = function() {};
/**
* @param {number} n
* @return {google.maps.Data.Geometry}
*/
google.maps.Data.GeometryCollection.prototype.getAt = function(n) {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.Data.GeometryCollection.prototype.getLength = function() {};
/**
* @nosideeffects
* @return {string}
* @override
*/
google.maps.Data.GeometryCollection.prototype.getType = function() {};
/**
* @param {Array<google.maps.LatLng|google.maps.LatLngLiteral>} elements
* @extends {google.maps.Data.Geometry}
* @constructor
*/
google.maps.Data.LineString = function(elements) {};
/**
* @nosideeffects
* @return {Array<google.maps.LatLng>}
*/
google.maps.Data.LineString.prototype.getArray = function() {};
/**
* @param {number} n
* @return {google.maps.LatLng}
*/
google.maps.Data.LineString.prototype.getAt = function(n) {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.Data.LineString.prototype.getLength = function() {};
/**
* @nosideeffects
* @return {string}
* @override
*/
google.maps.Data.LineString.prototype.getType = function() {};
/**
* @param {Array<google.maps.LatLng|google.maps.LatLngLiteral>} elements
* @extends {google.maps.Data.Geometry}
* @constructor
*/
google.maps.Data.LinearRing = function(elements) {};
/**
* @nosideeffects
* @return {Array<google.maps.LatLng>}
*/
google.maps.Data.LinearRing.prototype.getArray = function() {};
/**
* @param {number} n
* @return {google.maps.LatLng}
*/
google.maps.Data.LinearRing.prototype.getAt = function(n) {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.Data.LinearRing.prototype.getLength = function() {};
/**
* @nosideeffects
* @return {string}
* @override
*/
google.maps.Data.LinearRing.prototype.getType = function() {};
/**
* @extends {google.maps.MouseEvent}
* @constructor
*/
google.maps.Data.MouseEvent = function() {};
/**
* @type {google.maps.Data.Feature}
*/
google.maps.Data.MouseEvent.prototype.feature;
/**
* @param {Array<google.maps.Data.LineString|Array<google.maps.LatLng|google.maps.LatLngLiteral>>} elements
* @extends {google.maps.Data.Geometry}
* @constructor
*/
google.maps.Data.MultiLineString = function(elements) {};
/**
* @nosideeffects
* @return {Array<google.maps.Data.LineString>}
*/
google.maps.Data.MultiLineString.prototype.getArray = function() {};
/**
* @param {number} n
* @return {google.maps.Data.LineString}
*/
google.maps.Data.MultiLineString.prototype.getAt = function(n) {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.Data.MultiLineString.prototype.getLength = function() {};
/**
* @nosideeffects
* @return {string}
* @override
*/
google.maps.Data.MultiLineString.prototype.getType = function() {};
/**
* @param {Array<google.maps.LatLng|google.maps.LatLngLiteral>} elements
* @extends {google.maps.Data.Geometry}
* @constructor
*/
google.maps.Data.MultiPoint = function(elements) {};
/**
* @nosideeffects
* @return {Array<google.maps.LatLng>}
*/
google.maps.Data.MultiPoint.prototype.getArray = function() {};
/**
* @param {number} n
* @return {google.maps.LatLng}
*/
google.maps.Data.MultiPoint.prototype.getAt = function(n) {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.Data.MultiPoint.prototype.getLength = function() {};
/**
* @nosideeffects
* @return {string}
* @override
*/
google.maps.Data.MultiPoint.prototype.getType = function() {};
/**
* @param {Array<google.maps.Data.Polygon|Array<google.maps.Data.LinearRing|Array<google.maps.LatLng|google.maps.LatLngLiteral>>>} elements
* @extends {google.maps.Data.Geometry}
* @constructor
*/
google.maps.Data.MultiPolygon = function(elements) {};
/**
* @nosideeffects
* @return {Array<google.maps.Data.Polygon>}
*/
google.maps.Data.MultiPolygon.prototype.getArray = function() {};
/**
* @param {number} n
* @return {google.maps.Data.Polygon}
*/
google.maps.Data.MultiPolygon.prototype.getAt = function(n) {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.Data.MultiPolygon.prototype.getLength = function() {};
/**
* @nosideeffects
* @return {string}
* @override
*/
google.maps.Data.MultiPolygon.prototype.getType = function() {};
/**
* @param {google.maps.LatLng|google.maps.LatLngLiteral} latLng
* @extends {google.maps.Data.Geometry}
* @constructor
*/
google.maps.Data.Point = function(latLng) {};
/**
* @nosideeffects
* @return {google.maps.LatLng}
*/
google.maps.Data.Point.prototype.get = function() {};
/**
* @nosideeffects
* @return {string}
* @override
*/
google.maps.Data.Point.prototype.getType = function() {};
/**
* @param {Array<google.maps.Data.LinearRing|Array<google.maps.LatLng|google.maps.LatLngLiteral>>} elements
* @extends {google.maps.Data.Geometry}
* @constructor
*/
google.maps.Data.Polygon = function(elements) {};
/**
* @nosideeffects
* @return {Array<google.maps.Data.LinearRing>}
*/
google.maps.Data.Polygon.prototype.getArray = function() {};
/**
* @param {number} n
* @return {google.maps.Data.LinearRing}
*/
google.maps.Data.Polygon.prototype.getAt = function(n) {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.Data.Polygon.prototype.getLength = function() {};
/**
* @nosideeffects
* @return {string}
* @override
*/
google.maps.Data.Polygon.prototype.getType = function() {};
/**
* @interface
*/
google.maps.Data.RemoveFeatureEvent = function() {};
/**
* @type {google.maps.Data.Feature}
*/
google.maps.Data.RemoveFeatureEvent.prototype.feature;
/**
* @interface
*/
google.maps.Data.RemovePropertyEvent = function() {};
/**
* @type {google.maps.Data.Feature}
*/
google.maps.Data.RemovePropertyEvent.prototype.feature;
/**
* @type {string}
*/
google.maps.Data.RemovePropertyEvent.prototype.name;
/**
* @type {*}
*/
google.maps.Data.RemovePropertyEvent.prototype.oldValue;
/**
* @interface
*/
google.maps.Data.SetGeometryEvent = function() {};
/**
* @type {google.maps.Data.Feature}
*/
google.maps.Data.SetGeometryEvent.prototype.feature;
/**
* @type {google.maps.Data.Geometry}
*/
google.maps.Data.SetGeometryEvent.prototype.newGeometry;
/**
* @type {google.maps.Data.Geometry}
*/
google.maps.Data.SetGeometryEvent.prototype.oldGeometry;
/**
* @interface
*/
google.maps.Data.SetPropertyEvent = function() {};
/**
* @type {google.maps.Data.Feature}
*/
google.maps.Data.SetPropertyEvent.prototype.feature;
/**
* @type {string}
*/
google.maps.Data.SetPropertyEvent.prototype.name;
/**
* @type {*}
*/
google.maps.Data.SetPropertyEvent.prototype.newValue;
/**
* @type {*}
*/
google.maps.Data.SetPropertyEvent.prototype.oldValue;
/**
* @interface
*/
google.maps.Data.StyleOptions = function() {};
/**
* @type {boolean}
*/
google.maps.Data.StyleOptions.prototype.clickable;
/**
* @type {string}
*/
google.maps.Data.StyleOptions.prototype.cursor;
/**
* @type {boolean}
*/
google.maps.Data.StyleOptions.prototype.draggable;
/**
* @type {boolean}
*/
google.maps.Data.StyleOptions.prototype.editable;
/**
* @type {string}
*/
google.maps.Data.StyleOptions.prototype.fillColor;
/**
* @type {number}
*/
google.maps.Data.StyleOptions.prototype.fillOpacity;
/**
* @type {string|google.maps.Icon|google.maps.Symbol}
*/
google.maps.Data.StyleOptions.prototype.icon;
/**
* @type {google.maps.MarkerShape}
*/
google.maps.Data.StyleOptions.prototype.shape;
/**
* @type {string}
*/
google.maps.Data.StyleOptions.prototype.strokeColor;
/**
* @type {number}
*/
google.maps.Data.StyleOptions.prototype.strokeOpacity;
/**
* @type {number}
*/
google.maps.Data.StyleOptions.prototype.strokeWeight;
/**
* @type {string}
*/
google.maps.Data.StyleOptions.prototype.title;
/**
* @type {boolean}
*/
google.maps.Data.StyleOptions.prototype.visible;
/**
* @type {number}
*/
google.maps.Data.StyleOptions.prototype.zIndex;
/**
* @typedef {function(google.maps.Data.Feature):google.maps.Data.StyleOptions|Object.<string>}
*/
google.maps.Data.StylingFunction;
/**
* @interface
*/
google.maps.DirectionsGeocodedWaypoint = function() {};
/**
* @type {boolean}
*/
google.maps.DirectionsGeocodedWaypoint.prototype.partial_match;
/**
* @type {string}
*/
google.maps.DirectionsGeocodedWaypoint.prototype.place_id;
/**
* @type {Array<string>}
*/
google.maps.DirectionsGeocodedWaypoint.prototype.types;
/**
* @interface
*/
google.maps.DirectionsLeg = function() {};
/**
* @type {google.maps.Time}
*/
google.maps.DirectionsLeg.prototype.arrival_time;
/**
* @type {google.maps.Time}
*/
google.maps.DirectionsLeg.prototype.departure_time;
/**
* @type {google.maps.Distance}
*/
google.maps.DirectionsLeg.prototype.distance;
/**
* @type {google.maps.Duration}
*/
google.maps.DirectionsLeg.prototype.duration;
/**
* @type {google.maps.Duration}
*/
google.maps.DirectionsLeg.prototype.duration_in_traffic;
/**
* @type {string}
*/
google.maps.DirectionsLeg.prototype.end_address;
/**
* @type {google.maps.LatLng}
*/
google.maps.DirectionsLeg.prototype.end_location;
/**
* @type {string}
*/
google.maps.DirectionsLeg.prototype.start_address;
/**
* @type {google.maps.LatLng}
*/
google.maps.DirectionsLeg.prototype.start_location;
/**
* @type {Array<google.maps.DirectionsStep>}
*/
google.maps.DirectionsLeg.prototype.steps;
/**
* @type {Array<google.maps.LatLng>}
*/
google.maps.DirectionsLeg.prototype.via_waypoints;
/**
* @param {(google.maps.DirectionsRendererOptions|Object.<string>)=} opt_opts
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.DirectionsRenderer = function(opt_opts) {};
/**
* @nosideeffects
* @return {google.maps.DirectionsResult}
*/
google.maps.DirectionsRenderer.prototype.getDirections = function() {};
/**
* @nosideeffects
* @return {google.maps.Map}
*/
google.maps.DirectionsRenderer.prototype.getMap = function() {};
/**
* @nosideeffects
* @return {Node}
*/
google.maps.DirectionsRenderer.prototype.getPanel = function() {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.DirectionsRenderer.prototype.getRouteIndex = function() {};
/**
* @param {google.maps.DirectionsResult} directions
* @return {undefined}
*/
google.maps.DirectionsRenderer.prototype.setDirections = function(directions) {};
/**
* @param {google.maps.Map} map
* @return {undefined}
*/
google.maps.DirectionsRenderer.prototype.setMap = function(map) {};
/**
* @param {google.maps.DirectionsRendererOptions|Object.<string>} options
* @return {undefined}
*/
google.maps.DirectionsRenderer.prototype.setOptions = function(options) {};
/**
* @param {Node} panel
* @return {undefined}
*/
google.maps.DirectionsRenderer.prototype.setPanel = function(panel) {};
/**
* @param {number} routeIndex
* @return {undefined}
*/
google.maps.DirectionsRenderer.prototype.setRouteIndex = function(routeIndex) {};
/**
* @interface
*/
google.maps.DirectionsRendererOptions = function() {};
/**
* @type {google.maps.DirectionsResult}
*/
google.maps.DirectionsRendererOptions.prototype.directions;
/**
* @type {boolean}
*/
google.maps.DirectionsRendererOptions.prototype.draggable;
/**
* @type {boolean}
*/
google.maps.DirectionsRendererOptions.prototype.hideRouteList;
/**
* @type {google.maps.InfoWindow}
*/
google.maps.DirectionsRendererOptions.prototype.infoWindow;
/**
* @type {google.maps.Map}
*/
google.maps.DirectionsRendererOptions.prototype.map;
/**
* @type {google.maps.MarkerOptions|Object.<string>}
*/
google.maps.DirectionsRendererOptions.prototype.markerOptions;
/**
* @type {Node}
*/
google.maps.DirectionsRendererOptions.prototype.panel;
/**
* @type {google.maps.PolylineOptions|Object.<string>}
*/
google.maps.DirectionsRendererOptions.prototype.polylineOptions;
/**
* @type {boolean}
*/
google.maps.DirectionsRendererOptions.prototype.preserveViewport;
/**
* @type {number}
*/
google.maps.DirectionsRendererOptions.prototype.routeIndex;
/**
* @type {boolean}
*/
google.maps.DirectionsRendererOptions.prototype.suppressBicyclingLayer;
/**
* @type {boolean}
*/
google.maps.DirectionsRendererOptions.prototype.suppressInfoWindows;
/**
* @type {boolean}
*/
google.maps.DirectionsRendererOptions.prototype.suppressMarkers;
/**
* @type {boolean}
*/
google.maps.DirectionsRendererOptions.prototype.suppressPolylines;
/**
* @interface
*/
google.maps.DirectionsRequest = function() {};
/**
* @type {boolean}
*/
google.maps.DirectionsRequest.prototype.avoidFerries;
/**
* @type {boolean}
*/
google.maps.DirectionsRequest.prototype.avoidHighways;
/**
* @type {boolean}
*/
google.maps.DirectionsRequest.prototype.avoidTolls;
/**
* @type {google.maps.Place}
*/
google.maps.DirectionsRequest.prototype.destination;
/**
* @type {google.maps.DrivingOptions|Object.<string>}
*/
google.maps.DirectionsRequest.prototype.drivingOptions;
/**
* @type {boolean}
*/
google.maps.DirectionsRequest.prototype.optimizeWaypoints;
/**
* @type {google.maps.Place}
*/
google.maps.DirectionsRequest.prototype.origin;
/**
* @type {boolean}
*/
google.maps.DirectionsRequest.prototype.provideRouteAlternatives;
/**
* @type {string}
*/
google.maps.DirectionsRequest.prototype.region;
/**
* @type {google.maps.TransitOptions|Object.<string>}
*/
google.maps.DirectionsRequest.prototype.transitOptions;
/**
* @type {google.maps.TravelMode}
*/
google.maps.DirectionsRequest.prototype.travelMode;
/**
* @type {google.maps.UnitSystem}
*/
google.maps.DirectionsRequest.prototype.unitSystem;
/**
* @type {Array<google.maps.DirectionsWaypoint>}
*/
google.maps.DirectionsRequest.prototype.waypoints;
/**
* @interface
*/
google.maps.DirectionsResult = function() {};
/**
* @type {Array<google.maps.DirectionsGeocodedWaypoint>}
*/
google.maps.DirectionsResult.prototype.geocoded_waypoints;
/**
* @type {Array<google.maps.DirectionsRoute>}
*/
google.maps.DirectionsResult.prototype.routes;
/**
* @interface
*/
google.maps.DirectionsRoute = function() {};
/**
* @type {google.maps.LatLngBounds}
*/
google.maps.DirectionsRoute.prototype.bounds;
/**
* @type {string}
*/
google.maps.DirectionsRoute.prototype.copyrights;
/**
* @type {google.maps.TransitFare}
*/
google.maps.DirectionsRoute.prototype.fare;
/**
* @type {Array<google.maps.DirectionsLeg>}
*/
google.maps.DirectionsRoute.prototype.legs;
/**
* @type {Array<google.maps.LatLng>}
*/
google.maps.DirectionsRoute.prototype.overview_path;
/**
* @type {string}
*/
google.maps.DirectionsRoute.prototype.overview_polyline;
/**
* @type {Array<string>}
*/
google.maps.DirectionsRoute.prototype.warnings;
/**
* @type {Array<number>}
*/
google.maps.DirectionsRoute.prototype.waypoint_order;
/**
* @constructor
*/
google.maps.DirectionsService = function() {};
/**
* @param {google.maps.DirectionsRequest|Object.<string>} request
* @param {function(google.maps.DirectionsResult, google.maps.DirectionsStatus)} callback
* @return {undefined}
*/
google.maps.DirectionsService.prototype.route = function(request, callback) {};
/**
* @enum {string}
*/
google.maps.DirectionsStatus = {
INVALID_REQUEST: '1',
MAX_WAYPOINTS_EXCEEDED: '2',
NOT_FOUND: '3',
OK: '4',
OVER_QUERY_LIMIT: '5',
REQUEST_DENIED: '6',
UNKNOWN_ERROR: '7',
ZERO_RESULTS: ''
};
/**
* @interface
*/
google.maps.DirectionsStep = function() {};
/**
* @type {google.maps.Distance}
*/
google.maps.DirectionsStep.prototype.distance;
/**
* @type {google.maps.Duration}
*/
google.maps.DirectionsStep.prototype.duration;
/**
* @type {google.maps.LatLng}
*/
google.maps.DirectionsStep.prototype.end_location;
/**
* @type {string}
*/
google.maps.DirectionsStep.prototype.instructions;
/**
* @type {Array<google.maps.LatLng>}
*/
google.maps.DirectionsStep.prototype.path;
/**
* @type {google.maps.LatLng}
*/
google.maps.DirectionsStep.prototype.start_location;
/**
* @type {Array<google.maps.DirectionsStep>}
*/
google.maps.DirectionsStep.prototype.steps;
/**
* @type {google.maps.TransitDetails}
*/
google.maps.DirectionsStep.prototype.transit;
/**
* @type {google.maps.TravelMode}
*/
google.maps.DirectionsStep.prototype.travel_mode;
/**
* @interface
*/
google.maps.DirectionsWaypoint = function() {};
/**
* @type {google.maps.Place}
*/
google.maps.DirectionsWaypoint.prototype.location;
/**
* @type {boolean}
*/
google.maps.DirectionsWaypoint.prototype.stopover;
/**
* @interface
*/
google.maps.Distance = function() {};
/**
* @type {string}
*/
google.maps.Distance.prototype.text;
/**
* @type {number}
*/
google.maps.Distance.prototype.value;
/**
* @enum {string}
*/
google.maps.DistanceMatrixElementStatus = {
NOT_FOUND: '1',
OK: '2',
ZERO_RESULTS: '3'
};
/**
* @interface
*/
google.maps.DistanceMatrixRequest = function() {};
/**
* @type {boolean}
*/
google.maps.DistanceMatrixRequest.prototype.avoidFerries;
/**
* @type {boolean}
*/
google.maps.DistanceMatrixRequest.prototype.avoidHighways;
/**
* @type {boolean}
*/
google.maps.DistanceMatrixRequest.prototype.avoidTolls;
/**
* @type {Array<google.maps.Place>}
*/
google.maps.DistanceMatrixRequest.prototype.destinations;
/**
* @type {google.maps.DrivingOptions|Object.<string>}
*/
google.maps.DistanceMatrixRequest.prototype.drivingOptions;
/**
* @type {Array<google.maps.Place>}
*/
google.maps.DistanceMatrixRequest.prototype.origins;
/**
* @type {string}
*/
google.maps.DistanceMatrixRequest.prototype.region;
/**
* @type {google.maps.TransitOptions|Object.<string>}
*/
google.maps.DistanceMatrixRequest.prototype.transitOptions;
/**
* @type {google.maps.TravelMode}
*/
google.maps.DistanceMatrixRequest.prototype.travelMode;
/**
* @type {google.maps.UnitSystem}
*/
google.maps.DistanceMatrixRequest.prototype.unitSystem;
/**
* @interface
*/
google.maps.DistanceMatrixResponse = function() {};
/**
* @type {Array<string>}
*/
google.maps.DistanceMatrixResponse.prototype.destinationAddresses;
/**
* @type {Array<string>}
*/
google.maps.DistanceMatrixResponse.prototype.originAddresses;
/**
* @type {Array<google.maps.DistanceMatrixResponseRow>}
*/
google.maps.DistanceMatrixResponse.prototype.rows;
/**
* @interface
*/
google.maps.DistanceMatrixResponseElement = function() {};
/**
* @type {google.maps.Distance}
*/
google.maps.DistanceMatrixResponseElement.prototype.distance;
/**
* @type {google.maps.Duration}
*/
google.maps.DistanceMatrixResponseElement.prototype.duration;
/**
* @type {google.maps.Duration}
*/
google.maps.DistanceMatrixResponseElement.prototype.duration_in_traffic;
/**
* @type {google.maps.TransitFare}
*/
google.maps.DistanceMatrixResponseElement.prototype.fare;
/**
* @type {google.maps.DistanceMatrixElementStatus}
*/
google.maps.DistanceMatrixResponseElement.prototype.status;
/**
* @interface
*/
google.maps.DistanceMatrixResponseRow = function() {};
/**
* @type {Array<google.maps.DistanceMatrixResponseElement>}
*/
google.maps.DistanceMatrixResponseRow.prototype.elements;
/**
* @constructor
*/
google.maps.DistanceMatrixService = function() {};
/**
* @param {google.maps.DistanceMatrixRequest|Object.<string>} request
* @param {function(google.maps.DistanceMatrixResponse, google.maps.DistanceMatrixStatus)} callback
* @return {undefined}
*/
google.maps.DistanceMatrixService.prototype.getDistanceMatrix = function(request, callback) {};
/**
* @enum {string}
*/
google.maps.DistanceMatrixStatus = {
INVALID_REQUEST: '1',
MAX_DIMENSIONS_EXCEEDED: '2',
MAX_ELEMENTS_EXCEEDED: '3',
OK: '4',
OVER_QUERY_LIMIT: '5',
REQUEST_DENIED: '6',
UNKNOWN_ERROR: ''
};
/**
* @interface
*/
google.maps.DrivingOptions = function() {};
/**
* @type {Date}
*/
google.maps.DrivingOptions.prototype.departureTime;
/**
* @type {google.maps.TrafficModel}
*/
google.maps.DrivingOptions.prototype.trafficModel;
/**
* @interface
*/
google.maps.Duration = function() {};
/**
* @type {string}
*/
google.maps.Duration.prototype.text;
/**
* @type {number}
*/
google.maps.Duration.prototype.value;
/**
* @interface
*/
google.maps.ElevationResult = function() {};
/**
* @type {number}
*/
google.maps.ElevationResult.prototype.elevation;
/**
* @type {google.maps.LatLng}
*/
google.maps.ElevationResult.prototype.location;
/**
* @type {number}
*/
google.maps.ElevationResult.prototype.resolution;
/**
* @constructor
*/
google.maps.ElevationService = function() {};
/**
* @param {google.maps.PathElevationRequest|Object.<string>} request
* @param {function(Array<google.maps.ElevationResult>, google.maps.ElevationStatus)} callback
* @return {undefined}
*/
google.maps.ElevationService.prototype.getElevationAlongPath = function(request, callback) {};
/**
* @param {google.maps.LocationElevationRequest|Object.<string>} request
* @param {function(Array<google.maps.ElevationResult>, google.maps.ElevationStatus)} callback
* @return {undefined}
*/
google.maps.ElevationService.prototype.getElevationForLocations = function(request, callback) {};
/**
* @enum {string}
*/
google.maps.ElevationStatus = {
INVALID_REQUEST: '1',
OK: '2',
OVER_QUERY_LIMIT: '3',
REQUEST_DENIED: '4',
UNKNOWN_ERROR: ''
};
/**
* @interface
*/
google.maps.FusionTablesCell = function() {};
/**
* @type {string}
*/
google.maps.FusionTablesCell.prototype.columnName;
/**
* @type {string}
*/
google.maps.FusionTablesCell.prototype.value;
/**
* @constructor
*/
google.maps.FusionTablesHeatmap = function() {};
/**
* @type {boolean}
*/
google.maps.FusionTablesHeatmap.prototype.enabled;
/**
* @param {google.maps.FusionTablesLayerOptions|Object.<string>} options
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.FusionTablesLayer = function(options) {};
/**
* @nosideeffects
* @return {google.maps.Map}
*/
google.maps.FusionTablesLayer.prototype.getMap = function() {};
/**
* @param {google.maps.Map} map
* @return {undefined}
*/
google.maps.FusionTablesLayer.prototype.setMap = function(map) {};
/**
* @param {google.maps.FusionTablesLayerOptions|Object.<string>} options
* @return {undefined}
*/
google.maps.FusionTablesLayer.prototype.setOptions = function(options) {};
/**
* @interface
*/
google.maps.FusionTablesLayerOptions = function() {};
/**
* @type {boolean}
*/
google.maps.FusionTablesLayerOptions.prototype.clickable;
/**
* @type {google.maps.FusionTablesHeatmap}
*/
google.maps.FusionTablesLayerOptions.prototype.heatmap;
/**
* @type {google.maps.Map}
*/
google.maps.FusionTablesLayerOptions.prototype.map;
/**
* @type {google.maps.FusionTablesQuery}
*/
google.maps.FusionTablesLayerOptions.prototype.query;
/**
* @type {Array<google.maps.FusionTablesStyle>}
*/
google.maps.FusionTablesLayerOptions.prototype.styles;
/**
* @type {boolean}
*/
google.maps.FusionTablesLayerOptions.prototype.suppressInfoWindows;
/**
* @constructor
*/
google.maps.FusionTablesMarkerOptions = function() {};
/**
* @type {string}
*/
google.maps.FusionTablesMarkerOptions.prototype.iconName;
/**
* @interface
*/
google.maps.FusionTablesMouseEvent = function() {};
/**
* @type {string}
*/
google.maps.FusionTablesMouseEvent.prototype.infoWindowHtml;
/**
* @type {google.maps.LatLng}
*/
google.maps.FusionTablesMouseEvent.prototype.latLng;
/**
* @type {google.maps.Size}
*/
google.maps.FusionTablesMouseEvent.prototype.pixelOffset;
/**
* @type {Object<google.maps.FusionTablesCell>}
*/
google.maps.FusionTablesMouseEvent.prototype.row;
/**
* @constructor
*/
google.maps.FusionTablesPolygonOptions = function() {};
/**
* @type {string}
*/
google.maps.FusionTablesPolygonOptions.prototype.fillColor;
/**
* @type {number}
*/
google.maps.FusionTablesPolygonOptions.prototype.fillOpacity;
/**
* @type {string}
*/
google.maps.FusionTablesPolygonOptions.prototype.strokeColor;
/**
* @type {number}
*/
google.maps.FusionTablesPolygonOptions.prototype.strokeOpacity;
/**
* @type {number}
*/
google.maps.FusionTablesPolygonOptions.prototype.strokeWeight;
/**
* @constructor
*/
google.maps.FusionTablesPolylineOptions = function() {};
/**
* @type {string}
*/
google.maps.FusionTablesPolylineOptions.prototype.strokeColor;
/**
* @type {number}
*/
google.maps.FusionTablesPolylineOptions.prototype.strokeOpacity;
/**
* @type {number}
*/
google.maps.FusionTablesPolylineOptions.prototype.strokeWeight;
/**
* @constructor
*/
google.maps.FusionTablesQuery = function() {};
/**
* @type {string}
*/
google.maps.FusionTablesQuery.prototype.from;
/**
* @type {number}
*/
google.maps.FusionTablesQuery.prototype.limit;
/**
* @type {number}
*/
google.maps.FusionTablesQuery.prototype.offset;
/**
* @type {string}
*/
google.maps.FusionTablesQuery.prototype.orderBy;
/**
* @type {string}
*/
google.maps.FusionTablesQuery.prototype.select;
/**
* @type {string}
*/
google.maps.FusionTablesQuery.prototype.where;
/**
* @constructor
*/
google.maps.FusionTablesStyle = function() {};
/**
* @type {google.maps.FusionTablesMarkerOptions|Object.<string>}
*/
google.maps.FusionTablesStyle.prototype.markerOptions;
/**
* @type {google.maps.FusionTablesPolygonOptions|Object.<string>}
*/
google.maps.FusionTablesStyle.prototype.polygonOptions;
/**
* @type {google.maps.FusionTablesPolylineOptions|Object.<string>}
*/
google.maps.FusionTablesStyle.prototype.polylineOptions;
/**
* @type {string}
*/
google.maps.FusionTablesStyle.prototype.where;
/**
* @constructor
*/
google.maps.Geocoder = function() {};
/**
* @param {google.maps.GeocoderRequest|Object.<string>} request
* @param {function(Array<google.maps.GeocoderResult>, google.maps.GeocoderStatus)} callback
* @return {undefined}
*/
google.maps.Geocoder.prototype.geocode = function(request, callback) {};
/**
* @constructor
*/
google.maps.GeocoderAddressComponent = function() {};
/**
* @type {string}
*/
google.maps.GeocoderAddressComponent.prototype.long_name;
/**
* @type {string}
*/
google.maps.GeocoderAddressComponent.prototype.short_name;
/**
* @type {Array<string>}
*/
google.maps.GeocoderAddressComponent.prototype.types;
/**
* @interface
*/
google.maps.GeocoderComponentRestrictions = function() {};
/**
* @type {string}
*/
google.maps.GeocoderComponentRestrictions.prototype.administrativeArea;
/**
* @type {string}
*/
google.maps.GeocoderComponentRestrictions.prototype.country;
/**
* @type {string}
*/
google.maps.GeocoderComponentRestrictions.prototype.locality;
/**
* @type {string}
*/
google.maps.GeocoderComponentRestrictions.prototype.postalCode;
/**
* @type {string}
*/
google.maps.GeocoderComponentRestrictions.prototype.route;
/**
* @constructor
*/
google.maps.GeocoderGeometry = function() {};
/**
* @type {google.maps.LatLngBounds}
*/
google.maps.GeocoderGeometry.prototype.bounds;
/**
* @type {google.maps.LatLng}
*/
google.maps.GeocoderGeometry.prototype.location;
/**
* @type {google.maps.GeocoderLocationType}
*/
google.maps.GeocoderGeometry.prototype.location_type;
/**
* @type {google.maps.LatLngBounds}
*/
google.maps.GeocoderGeometry.prototype.viewport;
/**
* @enum {string}
*/
google.maps.GeocoderLocationType = {
APPROXIMATE: '1',
GEOMETRIC_CENTER: '2',
RANGE_INTERPOLATED: '3',
ROOFTOP: '4'
};
/**
* @interface
*/
google.maps.GeocoderRequest = function() {};
/**
* @type {string}
*/
google.maps.GeocoderRequest.prototype.address;
/**
* @type {google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral}
*/
google.maps.GeocoderRequest.prototype.bounds;
/**
* @type {google.maps.GeocoderComponentRestrictions}
*/
google.maps.GeocoderRequest.prototype.componentRestrictions;
/**
* @type {google.maps.LatLng|google.maps.LatLngLiteral}
*/
google.maps.GeocoderRequest.prototype.location;
/**
* @type {string}
*/
google.maps.GeocoderRequest.prototype.placeId;
/**
* @type {string}
*/
google.maps.GeocoderRequest.prototype.region;
/**
* @constructor
*/
google.maps.GeocoderResult = function() {};
/**
* @type {Array<google.maps.GeocoderAddressComponent>}
*/
google.maps.GeocoderResult.prototype.address_components;
/**
* @type {string}
*/
google.maps.GeocoderResult.prototype.formatted_address;
/**
* @type {google.maps.GeocoderGeometry}
*/
google.maps.GeocoderResult.prototype.geometry;
/**
* @type {boolean}
*/
google.maps.GeocoderResult.prototype.partial_match;
/**
* @type {string}
*/
google.maps.GeocoderResult.prototype.place_id;
/**
* @type {Array<string>}
*/
google.maps.GeocoderResult.prototype.postcode_localities;
/**
* @type {Array<string>}
*/
google.maps.GeocoderResult.prototype.types;
/**
* @enum {string}
*/
google.maps.GeocoderStatus = {
ERROR: '1',
INVALID_REQUEST: '2',
OK: '3',
OVER_QUERY_LIMIT: '4',
REQUEST_DENIED: '5',
UNKNOWN_ERROR: '6',
ZERO_RESULTS: ''
};
/**
* @param {string} url
* @param {google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral} bounds
* @param {(google.maps.GroundOverlayOptions|Object.<string>)=} opt_opts
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.GroundOverlay = function(url, bounds, opt_opts) {};
/**
* @nosideeffects
* @return {google.maps.LatLngBounds}
*/
google.maps.GroundOverlay.prototype.getBounds = function() {};
/**
* @nosideeffects
* @return {google.maps.Map}
*/
google.maps.GroundOverlay.prototype.getMap = function() {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.GroundOverlay.prototype.getOpacity = function() {};
/**
* @nosideeffects
* @return {string}
*/
google.maps.GroundOverlay.prototype.getUrl = function() {};
/**
* @param {google.maps.Map} map
* @return {undefined}
*/
google.maps.GroundOverlay.prototype.setMap = function(map) {};
/**
* @param {number} opacity
* @return {undefined}
*/
google.maps.GroundOverlay.prototype.setOpacity = function(opacity) {};
/**
* @interface
*/
google.maps.GroundOverlayOptions = function() {};
/**
* @type {boolean}
*/
google.maps.GroundOverlayOptions.prototype.clickable;
/**
* @type {google.maps.Map}
*/
google.maps.GroundOverlayOptions.prototype.map;
/**
* @type {number}
*/
google.maps.GroundOverlayOptions.prototype.opacity;
/**
* @interface
*/
google.maps.Icon = function() {};
/**
* @type {google.maps.Point}
*/
google.maps.Icon.prototype.anchor;
/**
* @type {google.maps.Point}
*/
google.maps.Icon.prototype.labelOrigin;
/**
* @type {google.maps.Point}
*/
google.maps.Icon.prototype.origin;
/**
* @type {google.maps.Size}
*/
google.maps.Icon.prototype.scaledSize;
/**
* @type {google.maps.Size}
*/
google.maps.Icon.prototype.size;
/**
* @type {string}
*/
google.maps.Icon.prototype.url;
/**
* @interface
*/
google.maps.IconSequence = function() {};
/**
* @type {boolean}
*/
google.maps.IconSequence.prototype.fixedRotation;
/**
* @type {google.maps.Symbol}
*/
google.maps.IconSequence.prototype.icon;
/**
* @type {string}
*/
google.maps.IconSequence.prototype.offset;
/**
* @type {string}
*/
google.maps.IconSequence.prototype.repeat;
/**
* @param {google.maps.ImageMapTypeOptions|Object.<string>} opts
* @implements {google.maps.MapType}
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.ImageMapType = function(opts) {};
/**
* @type {string}
*/
google.maps.ImageMapType.prototype.alt;
/**
* @type {number}
*/
google.maps.ImageMapType.prototype.maxZoom;
/**
* @type {number}
*/
google.maps.ImageMapType.prototype.minZoom;
/**
* @type {string}
*/
google.maps.ImageMapType.prototype.name;
/**
* @type {google.maps.Projection}
*/
google.maps.ImageMapType.prototype.projection;
/**
* @type {number}
*/
google.maps.ImageMapType.prototype.radius;
/**
* @type {google.maps.Size}
*/
google.maps.ImageMapType.prototype.tileSize;
/**
* @nosideeffects
* @return {number}
*/
google.maps.ImageMapType.prototype.getOpacity = function() {};
/**
* @param {google.maps.Point} tileCoord
* @param {number} zoom
* @param {Document} ownerDocument
* @return {Node}
*/
google.maps.ImageMapType.prototype.getTile = function(tileCoord, zoom, ownerDocument) {};
/**
* @param {Node} tileDiv
* @return {undefined}
*/
google.maps.ImageMapType.prototype.releaseTile = function(tileDiv) {};
/**
* @param {number} opacity
* @return {undefined}
*/
google.maps.ImageMapType.prototype.setOpacity = function(opacity) {};
/**
* @interface
*/
google.maps.ImageMapTypeOptions = function() {};
/**
* @type {string}
*/
google.maps.ImageMapTypeOptions.prototype.alt;
/**
* @type {function(google.maps.Point, number): string}
*/
google.maps.ImageMapTypeOptions.prototype.getTileUrl;
/**
* @type {number}
*/
google.maps.ImageMapTypeOptions.prototype.maxZoom;
/**
* @type {number}
*/
google.maps.ImageMapTypeOptions.prototype.minZoom;
/**
* @type {string}
*/
google.maps.ImageMapTypeOptions.prototype.name;
/**
* @type {number}
*/
google.maps.ImageMapTypeOptions.prototype.opacity;
/**
* @type {google.maps.Size}
*/
google.maps.ImageMapTypeOptions.prototype.tileSize;
/**
* @param {(google.maps.InfoWindowOptions|Object.<string>)=} opt_opts
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.InfoWindow = function(opt_opts) {};
/**
* @return {undefined}
*/
google.maps.InfoWindow.prototype.close = function() {};
/**
* @nosideeffects
* @return {string|Node}
*/
google.maps.InfoWindow.prototype.getContent = function() {};
/**
* @nosideeffects
* @return {google.maps.LatLng}
*/
google.maps.InfoWindow.prototype.getPosition = function() {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.InfoWindow.prototype.getZIndex = function() {};
/**
* @param {(google.maps.Map|google.maps.StreetViewPanorama)=} opt_map
* @param {google.maps.MVCObject=} opt_anchor
* @return {undefined}
*/
google.maps.InfoWindow.prototype.open = function(opt_map, opt_anchor) {};
/**
* @param {string|Node} content
* @return {undefined}
*/
google.maps.InfoWindow.prototype.setContent = function(content) {};
/**
* @param {google.maps.InfoWindowOptions|Object.<string>} options
* @return {undefined}
*/
google.maps.InfoWindow.prototype.setOptions = function(options) {};
/**
* @param {google.maps.LatLng|google.maps.LatLngLiteral} position
* @return {undefined}
*/
google.maps.InfoWindow.prototype.setPosition = function(position) {};
/**
* @param {number} zIndex
* @return {undefined}
*/
google.maps.InfoWindow.prototype.setZIndex = function(zIndex) {};
/**
* @interface
*/
google.maps.InfoWindowOptions = function() {};
/**
* @type {string|Node}
*/
google.maps.InfoWindowOptions.prototype.content;
/**
* @type {boolean}
*/
google.maps.InfoWindowOptions.prototype.disableAutoPan;
/**
* @type {number}
*/
google.maps.InfoWindowOptions.prototype.maxWidth;
/**
* @type {google.maps.Size}
*/
google.maps.InfoWindowOptions.prototype.pixelOffset;
/**
* @type {google.maps.LatLng|google.maps.LatLngLiteral}
*/
google.maps.InfoWindowOptions.prototype.position;
/**
* @type {number}
*/
google.maps.InfoWindowOptions.prototype.zIndex;
/**
* @constructor
*/
google.maps.KmlAuthor = function() {};
/**
* @type {string}
*/
google.maps.KmlAuthor.prototype.email;
/**
* @type {string}
*/
google.maps.KmlAuthor.prototype.name;
/**
* @type {string}
*/
google.maps.KmlAuthor.prototype.uri;
/**
* @constructor
*/
google.maps.KmlFeatureData = function() {};
/**
* @type {google.maps.KmlAuthor}
*/
google.maps.KmlFeatureData.prototype.author;
/**
* @type {string}
*/
google.maps.KmlFeatureData.prototype.description;
/**
* @type {string}
*/
google.maps.KmlFeatureData.prototype.id;
/**
* @type {string}
*/
google.maps.KmlFeatureData.prototype.infoWindowHtml;
/**
* @type {string}
*/
google.maps.KmlFeatureData.prototype.name;
/**
* @type {string}
*/
google.maps.KmlFeatureData.prototype.snippet;
/**
* @param {(google.maps.KmlLayerOptions|Object.<string>)=} opt_opts
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.KmlLayer = function(opt_opts) {};
/**
* @nosideeffects
* @return {google.maps.LatLngBounds}
*/
google.maps.KmlLayer.prototype.getDefaultViewport = function() {};
/**
* @nosideeffects
* @return {google.maps.Map}
*/
google.maps.KmlLayer.prototype.getMap = function() {};
/**
* @nosideeffects
* @return {google.maps.KmlLayerMetadata}
*/
google.maps.KmlLayer.prototype.getMetadata = function() {};
/**
* @nosideeffects
* @return {google.maps.KmlLayerStatus}
*/
google.maps.KmlLayer.prototype.getStatus = function() {};
/**
* @nosideeffects
* @return {string}
*/
google.maps.KmlLayer.prototype.getUrl = function() {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.KmlLayer.prototype.getZIndex = function() {};
/**
* @param {google.maps.Map} map
* @return {undefined}
*/
google.maps.KmlLayer.prototype.setMap = function(map) {};
/**
* @param {string} url
* @return {undefined}
*/
google.maps.KmlLayer.prototype.setUrl = function(url) {};
/**
* @param {number} zIndex
* @return {undefined}
*/
google.maps.KmlLayer.prototype.setZIndex = function(zIndex) {};
/**
* @constructor
*/
google.maps.KmlLayerMetadata = function() {};
/**
* @type {google.maps.KmlAuthor}
*/
google.maps.KmlLayerMetadata.prototype.author;
/**
* @type {string}
*/
google.maps.KmlLayerMetadata.prototype.description;
/**
* @type {boolean}
*/
google.maps.KmlLayerMetadata.prototype.hasScreenOverlays;
/**
* @type {string}
*/
google.maps.KmlLayerMetadata.prototype.name;
/**
* @type {string}
*/
google.maps.KmlLayerMetadata.prototype.snippet;
/**
* @interface
*/
google.maps.KmlLayerOptions = function() {};
/**
* @type {boolean}
*/
google.maps.KmlLayerOptions.prototype.clickable;
/**
* @type {google.maps.Map}
*/
google.maps.KmlLayerOptions.prototype.map;
/**
* @type {boolean}
*/
google.maps.KmlLayerOptions.prototype.preserveViewport;
/**
* @type {boolean}
*/
google.maps.KmlLayerOptions.prototype.screenOverlays;
/**
* @type {boolean}
*/
google.maps.KmlLayerOptions.prototype.suppressInfoWindows;
/**
* @type {string}
*/
google.maps.KmlLayerOptions.prototype.url;
/**
* @type {number}
*/
google.maps.KmlLayerOptions.prototype.zIndex;
/**
* @enum {string}
*/
google.maps.KmlLayerStatus = {
DOCUMENT_NOT_FOUND: '1',
DOCUMENT_TOO_LARGE: '2',
FETCH_ERROR: '3',
INVALID_DOCUMENT: '4',
INVALID_REQUEST: '5',
LIMITS_EXCEEDED: '6',
OK: '7',
TIMED_OUT: '8',
UNKNOWN: ''
};
/**
* @constructor
*/
google.maps.KmlMouseEvent = function() {};
/**
* @type {google.maps.KmlFeatureData}
*/
google.maps.KmlMouseEvent.prototype.featureData;
/**
* @type {google.maps.LatLng}
*/
google.maps.KmlMouseEvent.prototype.latLng;
/**
* @type {google.maps.Size}
*/
google.maps.KmlMouseEvent.prototype.pixelOffset;
/**
* @param {number} lat
* @param {number} lng
* @param {boolean=} opt_noWrap
* @constructor
*/
google.maps.LatLng = function(lat, lng, opt_noWrap) {};
/**
* @param {google.maps.LatLng} other
* @return {boolean}
*/
google.maps.LatLng.prototype.equals = function(other) {};
/**
* @return {number}
*/
google.maps.LatLng.prototype.lat = function() {};
/**
* @return {number}
*/
google.maps.LatLng.prototype.lng = function() {};
/**
* @return {string}
*/
google.maps.LatLng.prototype.toString = function() {};
/**
* @param {number=} opt_precision
* @return {string}
*/
google.maps.LatLng.prototype.toUrlValue = function(opt_precision) {};
/**
* @param {(google.maps.LatLng|google.maps.LatLngLiteral)=} opt_sw
* @param {(google.maps.LatLng|google.maps.LatLngLiteral)=} opt_ne
* @constructor
*/
google.maps.LatLngBounds = function(opt_sw, opt_ne) {};
/**
* @param {google.maps.LatLng} latLng
* @return {boolean}
*/
google.maps.LatLngBounds.prototype.contains = function(latLng) {};
/**
* @param {google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral} other
* @return {boolean}
*/
google.maps.LatLngBounds.prototype.equals = function(other) {};
/**
* @param {google.maps.LatLng} point
* @return {google.maps.LatLngBounds}
*/
google.maps.LatLngBounds.prototype.extend = function(point) {};
/**
* @nosideeffects
* @return {google.maps.LatLng}
*/
google.maps.LatLngBounds.prototype.getCenter = function() {};
/**
* @nosideeffects
* @return {google.maps.LatLng}
*/
google.maps.LatLngBounds.prototype.getNorthEast = function() {};
/**
* @nosideeffects
* @return {google.maps.LatLng}
*/
google.maps.LatLngBounds.prototype.getSouthWest = function() {};
/**
* @param {google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral} other
* @return {boolean}
*/
google.maps.LatLngBounds.prototype.intersects = function(other) {};
/**
* @return {boolean}
*/
google.maps.LatLngBounds.prototype.isEmpty = function() {};
/**
* @return {google.maps.LatLng}
*/
google.maps.LatLngBounds.prototype.toSpan = function() {};
/**
* @return {string}
*/
google.maps.LatLngBounds.prototype.toString = function() {};
/**
* @param {number=} opt_precision
* @return {string}
*/
google.maps.LatLngBounds.prototype.toUrlValue = function(opt_precision) {};
/**
* @param {google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral} other
* @return {google.maps.LatLngBounds}
*/
google.maps.LatLngBounds.prototype.union = function(other) {};
/**
* @interface
*/
google.maps.LatLngBoundsLiteral = function() {};
/**
* @type {number}
*/
google.maps.LatLngBoundsLiteral.prototype.east;
/**
* @type {number}
*/
google.maps.LatLngBoundsLiteral.prototype.north;
/**
* @type {number}
*/
google.maps.LatLngBoundsLiteral.prototype.south;
/**
* @type {number}
*/
google.maps.LatLngBoundsLiteral.prototype.west;
/**
* @interface
*/
google.maps.LatLngLiteral = function() {};
/**
* @type {number}
*/
google.maps.LatLngLiteral.prototype.lat;
/**
* @type {number}
*/
google.maps.LatLngLiteral.prototype.lng;
/**
* @interface
*/
google.maps.LocationElevationRequest = function() {};
/**
* @type {Array<google.maps.LatLng>}
*/
google.maps.LocationElevationRequest.prototype.locations;
/**
* @param {Array=} opt_array
* @extends {google.maps.MVCObject}
* @template T
* @constructor
*/
google.maps.MVCArray = function(opt_array) {};
/**
* @return {undefined}
*/
google.maps.MVCArray.prototype.clear = function() {};
/**
* @param {function(?, number)} callback
* @return {undefined}
*/
google.maps.MVCArray.prototype.forEach = function(callback) {};
/**
* @nosideeffects
* @return {Array}
*/
google.maps.MVCArray.prototype.getArray = function() {};
/**
* @param {number} i
* @return {T}
*/
google.maps.MVCArray.prototype.getAt = function(i) {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.MVCArray.prototype.getLength = function() {};
/**
* @param {number} i
* @param {T} elem
* @return {undefined}
*/
google.maps.MVCArray.prototype.insertAt = function(i, elem) {};
/**
* @return {T}
*/
google.maps.MVCArray.prototype.pop = function() {};
/**
* @param {T} elem
* @return {number}
*/
google.maps.MVCArray.prototype.push = function(elem) {};
/**
* @param {number} i
* @return {T}
*/
google.maps.MVCArray.prototype.removeAt = function(i) {};
/**
* @param {number} i
* @param {T} elem
* @return {undefined}
*/
google.maps.MVCArray.prototype.setAt = function(i, elem) {};
/**
* @constructor
*/
google.maps.MVCObject = function() {};
/**
* @param {string} eventName
* @param {!Function} handler
* @return {google.maps.MapsEventListener}
*/
google.maps.MVCObject.prototype.addListener = function(eventName, handler) {};
/**
* @param {string} key
* @param {google.maps.MVCObject} target
* @param {?string=} opt_targetKey
* @param {boolean=} opt_noNotify
* @return {undefined}
*/
google.maps.MVCObject.prototype.bindTo = function(key, target, opt_targetKey, opt_noNotify) {};
/**
* @param {string} key
* @return {undefined}
*/
google.maps.MVCObject.prototype.changed = function(key) {};
/**
* @param {string} key
* @return {?}
*/
google.maps.MVCObject.prototype.get = function(key) {};
/**
* @param {string} key
* @return {undefined}
*/
google.maps.MVCObject.prototype.notify = function(key) {};
/**
* @param {string} key
* @param {?} value
* @return {undefined}
*/
google.maps.MVCObject.prototype.set = function(key, value) {};
/**
* @param {Object|undefined} values
* @return {undefined}
*/
google.maps.MVCObject.prototype.setValues = function(values) {};
/**
* @param {string} key
* @return {undefined}
*/
google.maps.MVCObject.prototype.unbind = function(key) {};
/**
* @return {undefined}
*/
google.maps.MVCObject.prototype.unbindAll = function() {};
/**
* @param {Node} mapDiv
* @param {(google.maps.MapOptions|Object.<string>)=} opt_opts
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.Map = function(mapDiv, opt_opts) {};
/**
* @type {Array<google.maps.MVCArray<Node>>}
*/
google.maps.Map.prototype.controls;
/**
* @type {google.maps.Data}
*/
google.maps.Map.prototype.data;
/**
* @type {google.maps.MapTypeRegistry}
*/
google.maps.Map.prototype.mapTypes;
/**
* @type {google.maps.MVCArray<google.maps.MapType>}
*/
google.maps.Map.prototype.overlayMapTypes;
/**
* @param {google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral} bounds
* @return {undefined}
*/
google.maps.Map.prototype.fitBounds = function(bounds) {};
/**
* @nosideeffects
* @return {google.maps.LatLngBounds}
*/
google.maps.Map.prototype.getBounds = function() {};
/**
* @nosideeffects
* @return {google.maps.LatLng}
*/
google.maps.Map.prototype.getCenter = function() {};
/**
* @nosideeffects
* @return {Node}
*/
google.maps.Map.prototype.getDiv = function() {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.Map.prototype.getHeading = function() {};
/**
* @nosideeffects
* @return {google.maps.MapTypeId|string}
*/
google.maps.Map.prototype.getMapTypeId = function() {};
/**
* @nosideeffects
* @return {google.maps.Projection}
*/
google.maps.Map.prototype.getProjection = function() {};
/**
* @nosideeffects
* @return {google.maps.StreetViewPanorama}
*/
google.maps.Map.prototype.getStreetView = function() {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.Map.prototype.getTilt = function() {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.Map.prototype.getZoom = function() {};
/**
* @param {number} x
* @param {number} y
* @return {undefined}
*/
google.maps.Map.prototype.panBy = function(x, y) {};
/**
* @param {google.maps.LatLng|google.maps.LatLngLiteral} latLng
* @return {undefined}
*/
google.maps.Map.prototype.panTo = function(latLng) {};
/**
* @param {google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral} latLngBounds
* @return {undefined}
*/
google.maps.Map.prototype.panToBounds = function(latLngBounds) {};
/**
* @param {google.maps.LatLng|google.maps.LatLngLiteral} latlng
* @return {undefined}
*/
google.maps.Map.prototype.setCenter = function(latlng) {};
/**
* @param {number} heading
* @return {undefined}
*/
google.maps.Map.prototype.setHeading = function(heading) {};
/**
* @param {google.maps.MapTypeId|string} mapTypeId
* @return {undefined}
*/
google.maps.Map.prototype.setMapTypeId = function(mapTypeId) {};
/**
* @param {google.maps.MapOptions|Object.<string>} options
* @return {undefined}
*/
google.maps.Map.prototype.setOptions = function(options) {};
/**
* @param {google.maps.StreetViewPanorama} panorama
* @return {undefined}
*/
google.maps.Map.prototype.setStreetView = function(panorama) {};
/**
* @param {number} tilt
* @return {undefined}
*/
google.maps.Map.prototype.setTilt = function(tilt) {};
/**
* @param {number} zoom
* @return {undefined}
*/
google.maps.Map.prototype.setZoom = function(zoom) {};
/**
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.MapCanvasProjection = function() {};
/**
* @param {google.maps.Point} pixel
* @param {boolean=} opt_nowrap
* @return {google.maps.LatLng}
*/
google.maps.MapCanvasProjection.prototype.fromContainerPixelToLatLng = function(pixel, opt_nowrap) {};
/**
* @param {google.maps.Point} pixel
* @param {boolean=} opt_nowrap
* @return {google.maps.LatLng}
*/
google.maps.MapCanvasProjection.prototype.fromDivPixelToLatLng = function(pixel, opt_nowrap) {};
/**
* @param {google.maps.LatLng} latLng
* @return {google.maps.Point}
*/
google.maps.MapCanvasProjection.prototype.fromLatLngToContainerPixel = function(latLng) {};
/**
* @param {google.maps.LatLng} latLng
* @return {google.maps.Point}
*/
google.maps.MapCanvasProjection.prototype.fromLatLngToDivPixel = function(latLng) {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.MapCanvasProjection.prototype.getWorldWidth = function() {};
/**
* @interface
*/
google.maps.MapOptions = function() {};
/**
* @type {string}
*/
google.maps.MapOptions.prototype.backgroundColor;
/**
* @type {google.maps.LatLng}
*/
google.maps.MapOptions.prototype.center;
/**
* @type {boolean}
*/
google.maps.MapOptions.prototype.disableDefaultUI;
/**
* @type {boolean}
*/
google.maps.MapOptions.prototype.disableDoubleClickZoom;
/**
* @type {boolean}
*/
google.maps.MapOptions.prototype.draggable;
/**
* @type {string}
*/
google.maps.MapOptions.prototype.draggableCursor;
/**
* @type {string}
*/
google.maps.MapOptions.prototype.draggingCursor;
/**
* @type {number}
*/
google.maps.MapOptions.prototype.heading;
/**
* @type {boolean}
*/
google.maps.MapOptions.prototype.keyboardShortcuts;
/**
* @type {boolean}
*/
google.maps.MapOptions.prototype.mapMaker;
/**
* @type {boolean}
*/
google.maps.MapOptions.prototype.mapTypeControl;
/**
* @type {google.maps.MapTypeControlOptions|Object.<string>}
*/
google.maps.MapOptions.prototype.mapTypeControlOptions;
/**
* @type {google.maps.MapTypeId}
*/
google.maps.MapOptions.prototype.mapTypeId;
/**
* @type {number}
*/
google.maps.MapOptions.prototype.maxZoom;
/**
* @type {number}
*/
google.maps.MapOptions.prototype.minZoom;
/**
* @type {boolean}
*/
google.maps.MapOptions.prototype.noClear;
/**
* @type {boolean}
*/
google.maps.MapOptions.prototype.overviewMapControl;
/**
* @type {google.maps.OverviewMapControlOptions|Object.<string>}
*/
google.maps.MapOptions.prototype.overviewMapControlOptions;
/**
* @type {boolean}
*/
google.maps.MapOptions.prototype.panControl;
/**
* @type {google.maps.PanControlOptions|Object.<string>}
*/
google.maps.MapOptions.prototype.panControlOptions;
/**
* @type {boolean}
*/
google.maps.MapOptions.prototype.rotateControl;
/**
* @type {google.maps.RotateControlOptions|Object.<string>}
*/
google.maps.MapOptions.prototype.rotateControlOptions;
/**
* @type {boolean}
*/
google.maps.MapOptions.prototype.scaleControl;
/**
* @type {google.maps.ScaleControlOptions|Object.<string>}
*/
google.maps.MapOptions.prototype.scaleControlOptions;
/**
* @type {boolean}
*/
google.maps.MapOptions.prototype.scrollwheel;
/**
* @type {google.maps.StreetViewPanorama}
*/
google.maps.MapOptions.prototype.streetView;
/**
* @type {boolean}
*/
google.maps.MapOptions.prototype.streetViewControl;
/**
* @type {google.maps.StreetViewControlOptions|Object.<string>}
*/
google.maps.MapOptions.prototype.streetViewControlOptions;
/**
* @type {Array<google.maps.MapTypeStyle>}
*/
google.maps.MapOptions.prototype.styles;
/**
* @type {number}
*/
google.maps.MapOptions.prototype.tilt;
/**
* @type {number}
*/
google.maps.MapOptions.prototype.zoom;
/**
* @type {boolean}
*/
google.maps.MapOptions.prototype.zoomControl;
/**
* @type {google.maps.ZoomControlOptions|Object.<string>}
*/
google.maps.MapOptions.prototype.zoomControlOptions;
/**
* @constructor
*/
google.maps.MapPanes = function() {};
/**
* @type {Node}
*/
google.maps.MapPanes.prototype.floatPane;
/**
* @type {Node}
*/
google.maps.MapPanes.prototype.mapPane;
/**
* @type {Node}
*/
google.maps.MapPanes.prototype.markerLayer;
/**
* @type {Node}
*/
google.maps.MapPanes.prototype.overlayLayer;
/**
* @type {Node}
*/
google.maps.MapPanes.prototype.overlayMouseTarget;
/**
* @interface
*/
google.maps.MapType = function() {};
/**
* @type {string}
*/
google.maps.MapType.prototype.alt;
/**
* @type {number}
*/
google.maps.MapType.prototype.maxZoom;
/**
* @type {number}
*/
google.maps.MapType.prototype.minZoom;
/**
* @type {string}
*/
google.maps.MapType.prototype.name;
/**
* @type {google.maps.Projection}
*/
google.maps.MapType.prototype.projection;
/**
* @type {number}
*/
google.maps.MapType.prototype.radius;
/**
* @type {google.maps.Size}
*/
google.maps.MapType.prototype.tileSize;
/**
* @param {google.maps.Point} tileCoord
* @param {number} zoom
* @param {Document} ownerDocument
* @return {Node}
*/
google.maps.MapType.prototype.getTile = function(tileCoord, zoom, ownerDocument) {};
/**
* @param {Node} tile
* @return {undefined}
*/
google.maps.MapType.prototype.releaseTile = function(tile) {};
/**
* @interface
*/
google.maps.MapTypeControlOptions = function() {};
/**
* @type {Array<google.maps.MapTypeId|string>}
*/
google.maps.MapTypeControlOptions.prototype.mapTypeIds;
/**
* @type {google.maps.ControlPosition}
*/
google.maps.MapTypeControlOptions.prototype.position;
/**
* @type {google.maps.MapTypeControlStyle}
*/
google.maps.MapTypeControlOptions.prototype.style;
/**
* @enum {number}
*/
google.maps.MapTypeControlStyle = {
DEFAULT: 1,
DROPDOWN_MENU: 2,
HORIZONTAL_BAR: 3
};
/**
* @enum {string}
*/
google.maps.MapTypeId = {
HYBRID: '1',
ROADMAP: '2',
SATELLITE: '3',
TERRAIN: '4'
};
/**
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.MapTypeRegistry = function() {};
/**
* @param {string} id
* @param {google.maps.MapType|undefined} mapType
* @return {undefined}
* @override
*/
google.maps.MapTypeRegistry.prototype.set = function(id, mapType) {};
/**
* @interface
*/
google.maps.MapTypeStyle = function() {};
/**
* @type {string}
*/
google.maps.MapTypeStyle.prototype.elementType;
/**
* @type {string}
*/
google.maps.MapTypeStyle.prototype.featureType;
/**
* @type {Array<google.maps.MapTypeStyler>}
*/
google.maps.MapTypeStyle.prototype.stylers;
/**
* @interface
*/
google.maps.MapTypeStyler = function() {};
/**
* @type {string}
*/
google.maps.MapTypeStyler.prototype.color;
/**
* @type {number}
*/
google.maps.MapTypeStyler.prototype.gamma;
/**
* @type {string}
*/
google.maps.MapTypeStyler.prototype.hue;
/**
* @type {boolean}
*/
google.maps.MapTypeStyler.prototype.invert_lightness;
/**
* @type {number}
*/
google.maps.MapTypeStyler.prototype.lightness;
/**
* @type {number}
*/
google.maps.MapTypeStyler.prototype.saturation;
/**
* @type {string}
*/
google.maps.MapTypeStyler.prototype.visibility;
/**
* @type {number}
*/
google.maps.MapTypeStyler.prototype.weight;
/**
* @constructor
*/
google.maps.MapsEventListener = function() {};
/**
* @param {(google.maps.MarkerOptions|Object.<string>)=} opt_opts
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.Marker = function(opt_opts) {};
/**
* @nosideeffects
* @return {?google.maps.Animation}
*/
google.maps.Marker.prototype.getAnimation = function() {};
/**
* @nosideeffects
* @return {google.maps.Attribution}
*/
google.maps.Marker.prototype.getAttribution = function() {};
/**
* @nosideeffects
* @return {boolean}
*/
google.maps.Marker.prototype.getClickable = function() {};
/**
* @nosideeffects
* @return {string}
*/
google.maps.Marker.prototype.getCursor = function() {};
/**
* @nosideeffects
* @return {boolean}
*/
google.maps.Marker.prototype.getDraggable = function() {};
/**
* @nosideeffects
* @return {string|google.maps.Icon|google.maps.Symbol}
*/
google.maps.Marker.prototype.getIcon = function() {};
/**
* @nosideeffects
* @return {google.maps.MarkerLabel}
*/
google.maps.Marker.prototype.getLabel = function() {};
/**
* @nosideeffects
* @return {google.maps.Map|google.maps.StreetViewPanorama}
*/
google.maps.Marker.prototype.getMap = function() {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.Marker.prototype.getOpacity = function() {};
/**
* @nosideeffects
* @return {google.maps.MarkerPlace}
*/
google.maps.Marker.prototype.getPlace = function() {};
/**
* @nosideeffects
* @return {google.maps.LatLng}
*/
google.maps.Marker.prototype.getPosition = function() {};
/**
* @nosideeffects
* @return {google.maps.MarkerShape}
*/
google.maps.Marker.prototype.getShape = function() {};
/**
* @nosideeffects
* @return {string}
*/
google.maps.Marker.prototype.getTitle = function() {};
/**
* @nosideeffects
* @return {boolean}
*/
google.maps.Marker.prototype.getVisible = function() {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.Marker.prototype.getZIndex = function() {};
/**
* @param {?google.maps.Animation} animation
* @return {undefined}
*/
google.maps.Marker.prototype.setAnimation = function(animation) {};
/**
* @param {google.maps.Attribution} attribution
* @return {undefined}
*/
google.maps.Marker.prototype.setAttribution = function(attribution) {};
/**
* @param {boolean} flag
* @return {undefined}
*/
google.maps.Marker.prototype.setClickable = function(flag) {};
/**
* @param {string} cursor
* @return {undefined}
*/
google.maps.Marker.prototype.setCursor = function(cursor) {};
/**
* @param {?boolean} flag
* @return {undefined}
*/
google.maps.Marker.prototype.setDraggable = function(flag) {};
/**
* @param {string|google.maps.Icon|google.maps.Symbol} icon
* @return {undefined}
*/
google.maps.Marker.prototype.setIcon = function(icon) {};
/**
* @param {string|google.maps.MarkerLabel} label
* @return {undefined}
*/
google.maps.Marker.prototype.setLabel = function(label) {};
/**
* @param {google.maps.Map|google.maps.StreetViewPanorama} map
* @return {undefined}
*/
google.maps.Marker.prototype.setMap = function(map) {};
/**
* @param {number} opacity
* @return {undefined}
*/
google.maps.Marker.prototype.setOpacity = function(opacity) {};
/**
* @param {google.maps.MarkerOptions|Object.<string>} options
* @return {undefined}
*/
google.maps.Marker.prototype.setOptions = function(options) {};
/**
* @param {google.maps.MarkerPlace} place
* @return {undefined}
*/
google.maps.Marker.prototype.setPlace = function(place) {};
/**
* @param {google.maps.LatLng|google.maps.LatLngLiteral} latlng
* @return {undefined}
*/
google.maps.Marker.prototype.setPosition = function(latlng) {};
/**
* @param {google.maps.MarkerShape} shape
* @return {undefined}
*/
google.maps.Marker.prototype.setShape = function(shape) {};
/**
* @param {string} title
* @return {undefined}
*/
google.maps.Marker.prototype.setTitle = function(title) {};
/**
* @param {boolean} visible
* @return {undefined}
*/
google.maps.Marker.prototype.setVisible = function(visible) {};
/**
* @param {number} zIndex
* @return {undefined}
*/
google.maps.Marker.prototype.setZIndex = function(zIndex) {};
/**
* @constant
* @type {number|string}
*/
google.maps.Marker.MAX_ZINDEX;
/**
* @interface
*/
google.maps.MarkerLabel = function() {};
/**
* @type {string}
*/
google.maps.MarkerLabel.prototype.color;
/**
* @type {string}
*/
google.maps.MarkerLabel.prototype.fontFamily;
/**
* @type {string}
*/
google.maps.MarkerLabel.prototype.fontSize;
/**
* @type {string}
*/
google.maps.MarkerLabel.prototype.fontWeight;
/**
* @type {string}
*/
google.maps.MarkerLabel.prototype.text;
/**
* @interface
*/
google.maps.MarkerOptions = function() {};
/**
* @type {google.maps.Point}
*/
google.maps.MarkerOptions.prototype.anchorPoint;
/**
* @type {google.maps.Animation}
*/
google.maps.MarkerOptions.prototype.animation;
/**
* @type {google.maps.Attribution}
*/
google.maps.MarkerOptions.prototype.attribution;
/**
* @type {boolean}
*/
google.maps.MarkerOptions.prototype.clickable;
/**
* @type {boolean}
*/
google.maps.MarkerOptions.prototype.crossOnDrag;
/**
* @type {string}
*/
google.maps.MarkerOptions.prototype.cursor;
/**
* @type {boolean}
*/
google.maps.MarkerOptions.prototype.draggable;
/**
* @type {string|google.maps.Icon|google.maps.Symbol}
*/
google.maps.MarkerOptions.prototype.icon;
/**
* @type {string|google.maps.MarkerLabel}
*/
google.maps.MarkerOptions.prototype.label;
/**
* @type {google.maps.Map|google.maps.StreetViewPanorama}
*/
google.maps.MarkerOptions.prototype.map;
/**
* @type {number}
*/
google.maps.MarkerOptions.prototype.opacity;
/**
* @type {boolean}
*/
google.maps.MarkerOptions.prototype.optimized;
/**
* @type {google.maps.MarkerPlace}
*/
google.maps.MarkerOptions.prototype.place;
/**
* @type {google.maps.LatLng}
*/
google.maps.MarkerOptions.prototype.position;
/**
* @type {google.maps.MarkerShape}
*/
google.maps.MarkerOptions.prototype.shape;
/**
* @type {string}
*/
google.maps.MarkerOptions.prototype.title;
/**
* @type {boolean}
*/
google.maps.MarkerOptions.prototype.visible;
/**
* @type {number}
*/
google.maps.MarkerOptions.prototype.zIndex;
/**
* @interface
*/
google.maps.MarkerPlace = function() {};
/**
* @type {google.maps.LatLng|google.maps.LatLngLiteral}
*/
google.maps.MarkerPlace.prototype.location;
/**
* @type {string}
*/
google.maps.MarkerPlace.prototype.placeId;
/**
* @type {string}
*/
google.maps.MarkerPlace.prototype.query;
/**
* @interface
*/
google.maps.MarkerShape = function() {};
/**
* @type {Array<number>}
*/
google.maps.MarkerShape.prototype.coords;
/**
* @type {string}
*/
google.maps.MarkerShape.prototype.type;
/**
* @interface
*/
google.maps.MaxZoomResult = function() {};
/**
* @type {google.maps.MaxZoomStatus}
*/
google.maps.MaxZoomResult.prototype.status;
/**
* @type {number}
*/
google.maps.MaxZoomResult.prototype.zoom;
/**
* @constructor
*/
google.maps.MaxZoomService = function() {};
/**
* @param {google.maps.LatLng|google.maps.LatLngLiteral} latlng
* @param {function(google.maps.MaxZoomResult)} callback
* @return {undefined}
*/
google.maps.MaxZoomService.prototype.getMaxZoomAtLatLng = function(latlng, callback) {};
/**
* @enum {string}
*/
google.maps.MaxZoomStatus = {
ERROR: '1',
OK: '2'
};
/**
* @constructor
*/
google.maps.MouseEvent = function() {};
/**
* @type {google.maps.LatLng}
*/
google.maps.MouseEvent.prototype.latLng;
/**
* @return {undefined}
*/
google.maps.MouseEvent.prototype.stop = function() {};
/**
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.OverlayView = function() {};
/**
* @return {undefined}
*/
google.maps.OverlayView.prototype.draw = function() {};
/**
* @nosideeffects
* @return {google.maps.Map|google.maps.StreetViewPanorama}
*/
google.maps.OverlayView.prototype.getMap = function() {};
/**
* @nosideeffects
* @return {google.maps.MapPanes}
*/
google.maps.OverlayView.prototype.getPanes = function() {};
/**
* @nosideeffects
* @return {google.maps.MapCanvasProjection}
*/
google.maps.OverlayView.prototype.getProjection = function() {};
/**
* @return {undefined}
*/
google.maps.OverlayView.prototype.onAdd = function() {};
/**
* @return {undefined}
*/
google.maps.OverlayView.prototype.onRemove = function() {};
/**
* @param {google.maps.Map|google.maps.StreetViewPanorama} map
* @return {undefined}
*/
google.maps.OverlayView.prototype.setMap = function(map) {};
/**
* @interface
*/
google.maps.OverviewMapControlOptions = function() {};
/**
* @type {boolean}
*/
google.maps.OverviewMapControlOptions.prototype.opened;
/**
* @interface
*/
google.maps.PanControlOptions = function() {};
/**
* @type {google.maps.ControlPosition}
*/
google.maps.PanControlOptions.prototype.position;
/**
* @interface
*/
google.maps.PathElevationRequest = function() {};
/**
* @type {Array<google.maps.LatLng>}
*/
google.maps.PathElevationRequest.prototype.path;
/**
* @type {number}
*/
google.maps.PathElevationRequest.prototype.samples;
/**
* @interface
*/
google.maps.Place = function() {};
/**
* @type {google.maps.LatLng|google.maps.LatLngLiteral}
*/
google.maps.Place.prototype.location;
/**
* @type {string}
*/
google.maps.Place.prototype.placeId;
/**
* @type {string}
*/
google.maps.Place.prototype.query;
/**
* @param {number} x
* @param {number} y
* @constructor
*/
google.maps.Point = function(x, y) {};
/**
* @type {number}
*/
google.maps.Point.prototype.x;
/**
* @type {number}
*/
google.maps.Point.prototype.y;
/**
* @param {google.maps.Point} other
* @return {boolean}
*/
google.maps.Point.prototype.equals = function(other) {};
/**
* @return {string}
*/
google.maps.Point.prototype.toString = function() {};
/**
* @extends {google.maps.MouseEvent}
* @constructor
*/
google.maps.PolyMouseEvent = function() {};
/**
* @type {number}
*/
google.maps.PolyMouseEvent.prototype.edge;
/**
* @type {number}
*/
google.maps.PolyMouseEvent.prototype.path;
/**
* @type {number}
*/
google.maps.PolyMouseEvent.prototype.vertex;
/**
* @param {(google.maps.PolygonOptions|Object.<string>)=} opt_opts
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.Polygon = function(opt_opts) {};
/**
* @nosideeffects
* @return {boolean}
*/
google.maps.Polygon.prototype.getDraggable = function() {};
/**
* @nosideeffects
* @return {boolean}
*/
google.maps.Polygon.prototype.getEditable = function() {};
/**
* @nosideeffects
* @return {google.maps.Map}
*/
google.maps.Polygon.prototype.getMap = function() {};
/**
* @nosideeffects
* @return {google.maps.MVCArray<google.maps.LatLng>}
*/
google.maps.Polygon.prototype.getPath = function() {};
/**
* @nosideeffects
* @return {google.maps.MVCArray<google.maps.MVCArray<google.maps.LatLng>>}
*/
google.maps.Polygon.prototype.getPaths = function() {};
/**
* @nosideeffects
* @return {boolean}
*/
google.maps.Polygon.prototype.getVisible = function() {};
/**
* @param {boolean} draggable
* @return {undefined}
*/
google.maps.Polygon.prototype.setDraggable = function(draggable) {};
/**
* @param {boolean} editable
* @return {undefined}
*/
google.maps.Polygon.prototype.setEditable = function(editable) {};
/**
* @param {google.maps.Map} map
* @return {undefined}
*/
google.maps.Polygon.prototype.setMap = function(map) {};
/**
* @param {google.maps.PolygonOptions|Object.<string>} options
* @return {undefined}
*/
google.maps.Polygon.prototype.setOptions = function(options) {};
/**
* @param {google.maps.MVCArray<google.maps.LatLng>|Array<google.maps.LatLng|google.maps.LatLngLiteral>} path
* @return {undefined}
*/
google.maps.Polygon.prototype.setPath = function(path) {};
/**
* @param {google.maps.MVCArray<google.maps.MVCArray<google.maps.LatLng>>|google.maps.MVCArray<google.maps.LatLng>|Array<Array<google.maps.LatLng|google.maps.LatLngLiteral>>|Array<google.maps.LatLng|google.maps.LatLngLiteral>} paths
* @return {undefined}
*/
google.maps.Polygon.prototype.setPaths = function(paths) {};
/**
* @param {boolean} visible
* @return {undefined}
*/
google.maps.Polygon.prototype.setVisible = function(visible) {};
/**
* @interface
*/
google.maps.PolygonOptions = function() {};
/**
* @type {boolean}
*/
google.maps.PolygonOptions.prototype.clickable;
/**
* @type {boolean}
*/
google.maps.PolygonOptions.prototype.draggable;
/**
* @type {boolean}
*/
google.maps.PolygonOptions.prototype.editable;
/**
* @type {string}
*/
google.maps.PolygonOptions.prototype.fillColor;
/**
* @type {number}
*/
google.maps.PolygonOptions.prototype.fillOpacity;
/**
* @type {boolean}
*/
google.maps.PolygonOptions.prototype.geodesic;
/**
* @type {google.maps.Map}
*/
google.maps.PolygonOptions.prototype.map;
/**
* @type {google.maps.MVCArray<google.maps.MVCArray<google.maps.LatLng>>|google.maps.MVCArray<google.maps.LatLng>|Array<Array<google.maps.LatLng|google.maps.LatLngLiteral>>|Array<google.maps.LatLng|google.maps.LatLngLiteral>}
*/
google.maps.PolygonOptions.prototype.paths;
/**
* @type {string}
*/
google.maps.PolygonOptions.prototype.strokeColor;
/**
* @type {number}
*/
google.maps.PolygonOptions.prototype.strokeOpacity;
/**
* @type {google.maps.StrokePosition}
*/
google.maps.PolygonOptions.prototype.strokePosition;
/**
* @type {number}
*/
google.maps.PolygonOptions.prototype.strokeWeight;
/**
* @type {boolean}
*/
google.maps.PolygonOptions.prototype.visible;
/**
* @type {number}
*/
google.maps.PolygonOptions.prototype.zIndex;
/**
* @param {(google.maps.PolylineOptions|Object.<string>)=} opt_opts
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.Polyline = function(opt_opts) {};
/**
* @nosideeffects
* @return {boolean}
*/
google.maps.Polyline.prototype.getDraggable = function() {};
/**
* @nosideeffects
* @return {boolean}
*/
google.maps.Polyline.prototype.getEditable = function() {};
/**
* @nosideeffects
* @return {google.maps.Map}
*/
google.maps.Polyline.prototype.getMap = function() {};
/**
* @nosideeffects
* @return {google.maps.MVCArray<google.maps.LatLng>}
*/
google.maps.Polyline.prototype.getPath = function() {};
/**
* @nosideeffects
* @return {boolean}
*/
google.maps.Polyline.prototype.getVisible = function() {};
/**
* @param {boolean} draggable
* @return {undefined}
*/
google.maps.Polyline.prototype.setDraggable = function(draggable) {};
/**
* @param {boolean} editable
* @return {undefined}
*/
google.maps.Polyline.prototype.setEditable = function(editable) {};
/**
* @param {google.maps.Map} map
* @return {undefined}
*/
google.maps.Polyline.prototype.setMap = function(map) {};
/**
* @param {google.maps.PolylineOptions|Object.<string>} options
* @return {undefined}
*/
google.maps.Polyline.prototype.setOptions = function(options) {};
/**
* @param {google.maps.MVCArray<google.maps.LatLng>|Array<google.maps.LatLng|google.maps.LatLngLiteral>} path
* @return {undefined}
*/
google.maps.Polyline.prototype.setPath = function(path) {};
/**
* @param {boolean} visible
* @return {undefined}
*/
google.maps.Polyline.prototype.setVisible = function(visible) {};
/**
* @interface
*/
google.maps.PolylineOptions = function() {};
/**
* @type {boolean}
*/
google.maps.PolylineOptions.prototype.clickable;
/**
* @type {boolean}
*/
google.maps.PolylineOptions.prototype.draggable;
/**
* @type {boolean}
*/
google.maps.PolylineOptions.prototype.editable;
/**
* @type {boolean}
*/
google.maps.PolylineOptions.prototype.geodesic;
/**
* @type {Array<google.maps.IconSequence>}
*/
google.maps.PolylineOptions.prototype.icons;
/**
* @type {google.maps.Map}
*/
google.maps.PolylineOptions.prototype.map;
/**
* @type {google.maps.MVCArray<google.maps.LatLng>|Array<google.maps.LatLng|google.maps.LatLngLiteral>}
*/
google.maps.PolylineOptions.prototype.path;
/**
* @type {string}
*/
google.maps.PolylineOptions.prototype.strokeColor;
/**
* @type {number}
*/
google.maps.PolylineOptions.prototype.strokeOpacity;
/**
* @type {number}
*/
google.maps.PolylineOptions.prototype.strokeWeight;
/**
* @type {boolean}
*/
google.maps.PolylineOptions.prototype.visible;
/**
* @type {number}
*/
google.maps.PolylineOptions.prototype.zIndex;
/**
* @interface
*/
google.maps.Projection = function() {};
/**
* @param {google.maps.LatLng} latLng
* @param {google.maps.Point=} opt_point
* @return {google.maps.Point}
*/
google.maps.Projection.prototype.fromLatLngToPoint = function(latLng, opt_point) {};
/**
* @param {google.maps.Point} pixel
* @param {boolean=} opt_nowrap
* @return {google.maps.LatLng}
*/
google.maps.Projection.prototype.fromPointToLatLng = function(pixel, opt_nowrap) {};
/**
* @param {(google.maps.RectangleOptions|Object.<string>)=} opt_opts
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.Rectangle = function(opt_opts) {};
/**
* @nosideeffects
* @return {google.maps.LatLngBounds}
*/
google.maps.Rectangle.prototype.getBounds = function() {};
/**
* @nosideeffects
* @return {boolean}
*/
google.maps.Rectangle.prototype.getDraggable = function() {};
/**
* @nosideeffects
* @return {boolean}
*/
google.maps.Rectangle.prototype.getEditable = function() {};
/**
* @nosideeffects
* @return {google.maps.Map}
*/
google.maps.Rectangle.prototype.getMap = function() {};
/**
* @nosideeffects
* @return {boolean}
*/
google.maps.Rectangle.prototype.getVisible = function() {};
/**
* @param {google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral} bounds
* @return {undefined}
*/
google.maps.Rectangle.prototype.setBounds = function(bounds) {};
/**
* @param {boolean} draggable
* @return {undefined}
*/
google.maps.Rectangle.prototype.setDraggable = function(draggable) {};
/**
* @param {boolean} editable
* @return {undefined}
*/
google.maps.Rectangle.prototype.setEditable = function(editable) {};
/**
* @param {google.maps.Map} map
* @return {undefined}
*/
google.maps.Rectangle.prototype.setMap = function(map) {};
/**
* @param {google.maps.RectangleOptions|Object.<string>} options
* @return {undefined}
*/
google.maps.Rectangle.prototype.setOptions = function(options) {};
/**
* @param {boolean} visible
* @return {undefined}
*/
google.maps.Rectangle.prototype.setVisible = function(visible) {};
/**
* @interface
*/
google.maps.RectangleOptions = function() {};
/**
* @type {google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral}
*/
google.maps.RectangleOptions.prototype.bounds;
/**
* @type {boolean}
*/
google.maps.RectangleOptions.prototype.clickable;
/**
* @type {boolean}
*/
google.maps.RectangleOptions.prototype.draggable;
/**
* @type {boolean}
*/
google.maps.RectangleOptions.prototype.editable;
/**
* @type {string}
*/
google.maps.RectangleOptions.prototype.fillColor;
/**
* @type {number}
*/
google.maps.RectangleOptions.prototype.fillOpacity;
/**
* @type {google.maps.Map}
*/
google.maps.RectangleOptions.prototype.map;
/**
* @type {string}
*/
google.maps.RectangleOptions.prototype.strokeColor;
/**
* @type {number}
*/
google.maps.RectangleOptions.prototype.strokeOpacity;
/**
* @type {google.maps.StrokePosition}
*/
google.maps.RectangleOptions.prototype.strokePosition;
/**
* @type {number}
*/
google.maps.RectangleOptions.prototype.strokeWeight;
/**
* @type {boolean}
*/
google.maps.RectangleOptions.prototype.visible;
/**
* @type {number}
*/
google.maps.RectangleOptions.prototype.zIndex;
/**
* @interface
*/
google.maps.RotateControlOptions = function() {};
/**
* @type {google.maps.ControlPosition}
*/
google.maps.RotateControlOptions.prototype.position;
/**
* @param {Node} container
* @param {(google.maps.SaveWidgetOptions|Object.<string>)=} opt_opts
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.SaveWidget = function(container, opt_opts) {};
/**
* @nosideeffects
* @return {google.maps.Attribution}
*/
google.maps.SaveWidget.prototype.getAttribution = function() {};
/**
* @nosideeffects
* @return {google.maps.MarkerPlace}
*/
google.maps.SaveWidget.prototype.getPlace = function() {};
/**
* @param {google.maps.Attribution} attribution
* @return {undefined}
*/
google.maps.SaveWidget.prototype.setAttribution = function(attribution) {};
/**
* @param {google.maps.SaveWidgetOptions|Object.<string>} opts
* @return {undefined}
*/
google.maps.SaveWidget.prototype.setOptions = function(opts) {};
/**
* @param {google.maps.MarkerPlace} place
* @return {undefined}
*/
google.maps.SaveWidget.prototype.setPlace = function(place) {};
/**
* @interface
*/
google.maps.SaveWidgetOptions = function() {};
/**
* @type {google.maps.Attribution}
*/
google.maps.SaveWidgetOptions.prototype.attribution;
/**
* @type {google.maps.MarkerPlace}
*/
google.maps.SaveWidgetOptions.prototype.place;
/**
* @interface
*/
google.maps.ScaleControlOptions = function() {};
/**
* @type {google.maps.ScaleControlStyle}
*/
google.maps.ScaleControlOptions.prototype.style;
/**
* @enum {number}
*/
google.maps.ScaleControlStyle = {
DEFAULT: 1
};
/**
* @param {number} width
* @param {number} height
* @param {string=} opt_widthUnit
* @param {string=} opt_heightUnit
* @constructor
*/
google.maps.Size = function(width, height, opt_widthUnit, opt_heightUnit) {};
/**
* @type {number}
*/
google.maps.Size.prototype.height;
/**
* @type {number}
*/
google.maps.Size.prototype.width;
/**
* @param {google.maps.Size} other
* @return {boolean}
*/
google.maps.Size.prototype.equals = function(other) {};
/**
* @return {string}
*/
google.maps.Size.prototype.toString = function() {};
/**
* @interface
*/
google.maps.StreetViewAddressControlOptions = function() {};
/**
* @type {google.maps.ControlPosition}
*/
google.maps.StreetViewAddressControlOptions.prototype.position;
/**
* @interface
*/
google.maps.StreetViewControlOptions = function() {};
/**
* @type {google.maps.ControlPosition}
*/
google.maps.StreetViewControlOptions.prototype.position;
/**
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.StreetViewCoverageLayer = function() {};
/**
* @nosideeffects
* @return {google.maps.Map}
*/
google.maps.StreetViewCoverageLayer.prototype.getMap = function() {};
/**
* @param {google.maps.Map} map
* @return {undefined}
*/
google.maps.StreetViewCoverageLayer.prototype.setMap = function(map) {};
/**
* @interface
*/
google.maps.StreetViewLink = function() {};
/**
* @type {string}
*/
google.maps.StreetViewLink.prototype.description;
/**
* @type {number}
*/
google.maps.StreetViewLink.prototype.heading;
/**
* @type {string}
*/
google.maps.StreetViewLink.prototype.pano;
/**
* @interface
*/
google.maps.StreetViewLocation = function() {};
/**
* @type {string}
*/
google.maps.StreetViewLocation.prototype.description;
/**
* @type {google.maps.LatLng}
*/
google.maps.StreetViewLocation.prototype.latLng;
/**
* @type {string}
*/
google.maps.StreetViewLocation.prototype.pano;
/**
* @type {string}
*/
google.maps.StreetViewLocation.prototype.shortDescription;
/**
* @interface
*/
google.maps.StreetViewLocationRequest = function() {};
/**
* @type {google.maps.LatLng|google.maps.LatLngLiteral}
*/
google.maps.StreetViewLocationRequest.prototype.location;
/**
* @type {google.maps.StreetViewPreference}
*/
google.maps.StreetViewLocationRequest.prototype.preference;
/**
* @type {number}
*/
google.maps.StreetViewLocationRequest.prototype.radius;
/**
* @type {google.maps.StreetViewSource}
*/
google.maps.StreetViewLocationRequest.prototype.source;
/**
* @interface
*/
google.maps.StreetViewPanoRequest = function() {};
/**
* @type {string}
*/
google.maps.StreetViewPanoRequest.prototype.pano;
/**
* @param {Node} container
* @param {(google.maps.StreetViewPanoramaOptions|Object.<string>)=} opt_opts
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.StreetViewPanorama = function(container, opt_opts) {};
/**
* @type {Array<google.maps.MVCArray<Node>>}
*/
google.maps.StreetViewPanorama.prototype.controls;
/**
* @nosideeffects
* @return {Array<google.maps.StreetViewLink>}
*/
google.maps.StreetViewPanorama.prototype.getLinks = function() {};
/**
* @nosideeffects
* @return {google.maps.StreetViewLocation}
*/
google.maps.StreetViewPanorama.prototype.getLocation = function() {};
/**
* @nosideeffects
* @return {string}
*/
google.maps.StreetViewPanorama.prototype.getPano = function() {};
/**
* @nosideeffects
* @return {google.maps.StreetViewPov}
*/
google.maps.StreetViewPanorama.prototype.getPhotographerPov = function() {};
/**
* @nosideeffects
* @return {google.maps.LatLng}
*/
google.maps.StreetViewPanorama.prototype.getPosition = function() {};
/**
* @nosideeffects
* @return {google.maps.StreetViewPov}
*/
google.maps.StreetViewPanorama.prototype.getPov = function() {};
/**
* @nosideeffects
* @return {google.maps.StreetViewStatus}
*/
google.maps.StreetViewPanorama.prototype.getStatus = function() {};
/**
* @nosideeffects
* @return {boolean}
*/
google.maps.StreetViewPanorama.prototype.getVisible = function() {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.StreetViewPanorama.prototype.getZoom = function() {};
/**
* @param {function(string):google.maps.StreetViewPanoramaData} provider
* @return {undefined}
*/
google.maps.StreetViewPanorama.prototype.registerPanoProvider = function(provider) {};
/**
* @param {Array<google.maps.StreetViewLink>} links
* @return {undefined}
*/
google.maps.StreetViewPanorama.prototype.setLinks = function(links) {};
/**
* @param {google.maps.StreetViewPanoramaOptions|Object.<string>} options
* @return {undefined}
*/
google.maps.StreetViewPanorama.prototype.setOptions = function(options) {};
/**
* @param {string} pano
* @return {undefined}
*/
google.maps.StreetViewPanorama.prototype.setPano = function(pano) {};
/**
* @param {google.maps.LatLng|google.maps.LatLngLiteral} latLng
* @return {undefined}
*/
google.maps.StreetViewPanorama.prototype.setPosition = function(latLng) {};
/**
* @param {google.maps.StreetViewPov} pov
* @return {undefined}
*/
google.maps.StreetViewPanorama.prototype.setPov = function(pov) {};
/**
* @param {boolean} flag
* @return {undefined}
*/
google.maps.StreetViewPanorama.prototype.setVisible = function(flag) {};
/**
* @param {number} zoom
* @return {undefined}
*/
google.maps.StreetViewPanorama.prototype.setZoom = function(zoom) {};
/**
* @interface
*/
google.maps.StreetViewPanoramaData = function() {};
/**
* @type {string}
*/
google.maps.StreetViewPanoramaData.prototype.copyright;
/**
* @type {string}
*/
google.maps.StreetViewPanoramaData.prototype.imageDate;
/**
* @type {Array<google.maps.StreetViewLink>}
*/
google.maps.StreetViewPanoramaData.prototype.links;
/**
* @type {google.maps.StreetViewLocation}
*/
google.maps.StreetViewPanoramaData.prototype.location;
/**
* @type {google.maps.StreetViewTileData}
*/
google.maps.StreetViewPanoramaData.prototype.tiles;
/**
* @interface
*/
google.maps.StreetViewPanoramaOptions = function() {};
/**
* @type {boolean}
*/
google.maps.StreetViewPanoramaOptions.prototype.addressControl;
/**
* @type {google.maps.StreetViewAddressControlOptions|Object.<string>}
*/
google.maps.StreetViewPanoramaOptions.prototype.addressControlOptions;
/**
* @type {boolean}
*/
google.maps.StreetViewPanoramaOptions.prototype.clickToGo;
/**
* @type {boolean}
*/
google.maps.StreetViewPanoramaOptions.prototype.disableDefaultUI;
/**
* @type {boolean}
*/
google.maps.StreetViewPanoramaOptions.prototype.disableDoubleClickZoom;
/**
* @type {boolean}
*/
google.maps.StreetViewPanoramaOptions.prototype.enableCloseButton;
/**
* @type {boolean}
*/
google.maps.StreetViewPanoramaOptions.prototype.imageDateControl;
/**
* @type {boolean}
*/
google.maps.StreetViewPanoramaOptions.prototype.linksControl;
/**
* @type {boolean}
*/
google.maps.StreetViewPanoramaOptions.prototype.panControl;
/**
* @type {google.maps.PanControlOptions|Object.<string>}
*/
google.maps.StreetViewPanoramaOptions.prototype.panControlOptions;
/**
* @type {string}
*/
google.maps.StreetViewPanoramaOptions.prototype.pano;
/**
* @type {function(string): google.maps.StreetViewPanoramaData}
*/
google.maps.StreetViewPanoramaOptions.prototype.panoProvider;
/**
* @type {google.maps.LatLng|google.maps.LatLngLiteral}
*/
google.maps.StreetViewPanoramaOptions.prototype.position;
/**
* @type {google.maps.StreetViewPov}
*/
google.maps.StreetViewPanoramaOptions.prototype.pov;
/**
* @type {boolean}
*/
google.maps.StreetViewPanoramaOptions.prototype.scrollwheel;
/**
* @type {boolean}
*/
google.maps.StreetViewPanoramaOptions.prototype.visible;
/**
* @type {boolean}
*/
google.maps.StreetViewPanoramaOptions.prototype.zoomControl;
/**
* @type {google.maps.ZoomControlOptions|Object.<string>}
*/
google.maps.StreetViewPanoramaOptions.prototype.zoomControlOptions;
/**
* @constructor
*/
google.maps.StreetViewPov = function() {};
/**
* @type {number}
*/
google.maps.StreetViewPov.prototype.heading;
/**
* @type {number}
*/
google.maps.StreetViewPov.prototype.pitch;
/**
* @enum {string}
*/
google.maps.StreetViewPreference = {
BEST: '1',
NEAREST: '2'
};
/**
* @constructor
*/
google.maps.StreetViewService = function() {};
/**
* @param {google.maps.StreetViewLocationRequest|google.maps.StreetViewPanoRequest|Object.<string>} request
* @param {function(google.maps.StreetViewPanoramaData, google.maps.StreetViewStatus)} callback
* @return {undefined}
*/
google.maps.StreetViewService.prototype.getPanorama = function(request, callback) {};
/**
* @enum {string}
*/
google.maps.StreetViewSource = {
DEFAULT: '1',
OUTDOOR: '2'
};
/**
* @enum {string}
*/
google.maps.StreetViewStatus = {
OK: '1',
UNKNOWN_ERROR: '2',
ZERO_RESULTS: '3'
};
/**
* @interface
*/
google.maps.StreetViewTileData = function() {};
/**
* @type {number}
*/
google.maps.StreetViewTileData.prototype.centerHeading;
/**
* @type {google.maps.Size}
*/
google.maps.StreetViewTileData.prototype.tileSize;
/**
* @type {google.maps.Size}
*/
google.maps.StreetViewTileData.prototype.worldSize;
/**
* @param {string} pano
* @param {number} tileZoom
* @param {number} tileX
* @param {number} tileY
* @return {string}
*/
google.maps.StreetViewTileData.prototype.getTileUrl = function(pano, tileZoom, tileX, tileY) {};
/**
* @enum {number}
*/
google.maps.StrokePosition = {
CENTER: 1,
INSIDE: 2,
OUTSIDE: 3
};
/**
* @param {Array<google.maps.MapTypeStyle>} styles
* @param {(google.maps.StyledMapTypeOptions|Object.<string>)=} opt_options
* @implements {google.maps.MapType}
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.StyledMapType = function(styles, opt_options) {};
/**
* @type {string}
*/
google.maps.StyledMapType.prototype.alt;
/**
* @type {number}
*/
google.maps.StyledMapType.prototype.maxZoom;
/**
* @type {number}
*/
google.maps.StyledMapType.prototype.minZoom;
/**
* @type {string}
*/
google.maps.StyledMapType.prototype.name;
/**
* @type {google.maps.Projection}
*/
google.maps.StyledMapType.prototype.projection;
/**
* @type {number}
*/
google.maps.StyledMapType.prototype.radius;
/**
* @type {google.maps.Size}
*/
google.maps.StyledMapType.prototype.tileSize;
/**
* @param {google.maps.Point} tileCoord
* @param {number} zoom
* @param {Document} ownerDocument
* @return {Node}
*/
google.maps.StyledMapType.prototype.getTile = function(tileCoord, zoom, ownerDocument) {};
/**
* @param {Node} tile
* @return {undefined}
*/
google.maps.StyledMapType.prototype.releaseTile = function(tile) {};
/**
* @interface
*/
google.maps.StyledMapTypeOptions = function() {};
/**
* @type {string}
*/
google.maps.StyledMapTypeOptions.prototype.alt;
/**
* @type {number}
*/
google.maps.StyledMapTypeOptions.prototype.maxZoom;
/**
* @type {number}
*/
google.maps.StyledMapTypeOptions.prototype.minZoom;
/**
* @type {string}
*/
google.maps.StyledMapTypeOptions.prototype.name;
/**
* @interface
*/
google.maps.Symbol = function() {};
/**
* @type {google.maps.Point}
*/
google.maps.Symbol.prototype.anchor;
/**
* @type {string}
*/
google.maps.Symbol.prototype.fillColor;
/**
* @type {number}
*/
google.maps.Symbol.prototype.fillOpacity;
/**
* @type {google.maps.Point}
*/
google.maps.Symbol.prototype.labelOrigin;
/**
* @type {google.maps.SymbolPath|string}
*/
google.maps.Symbol.prototype.path;
/**
* @type {number}
*/
google.maps.Symbol.prototype.rotation;
/**
* @type {number}
*/
google.maps.Symbol.prototype.scale;
/**
* @type {string}
*/
google.maps.Symbol.prototype.strokeColor;
/**
* @type {number}
*/
google.maps.Symbol.prototype.strokeOpacity;
/**
* @type {number}
*/
google.maps.Symbol.prototype.strokeWeight;
/**
* @enum {number}
*/
google.maps.SymbolPath = {
BACKWARD_CLOSED_ARROW: 1,
BACKWARD_OPEN_ARROW: 2,
CIRCLE: 3,
FORWARD_CLOSED_ARROW: 4,
FORWARD_OPEN_ARROW: 5
};
/**
* @interface
*/
google.maps.Time = function() {};
/**
* @type {string}
*/
google.maps.Time.prototype.text;
/**
* @type {string}
*/
google.maps.Time.prototype.time_zone;
/**
* @type {Date}
*/
google.maps.Time.prototype.value;
/**
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.TrafficLayer = function() {};
/**
* @nosideeffects
* @return {google.maps.Map}
*/
google.maps.TrafficLayer.prototype.getMap = function() {};
/**
* @param {google.maps.Map} map
* @return {undefined}
*/
google.maps.TrafficLayer.prototype.setMap = function(map) {};
/**
* @enum {string}
*/
google.maps.TrafficModel = {
BEST_GUESS: '1',
OPTIMISTIC: '2',
PESSIMISTIC: '3'
};
/**
* @interface
*/
google.maps.TransitAgency = function() {};
/**
* @type {string}
*/
google.maps.TransitAgency.prototype.name;
/**
* @type {string}
*/
google.maps.TransitAgency.prototype.phone;
/**
* @type {string}
*/
google.maps.TransitAgency.prototype.url;
/**
* @interface
*/
google.maps.TransitDetails = function() {};
/**
* @type {google.maps.TransitStop}
*/
google.maps.TransitDetails.prototype.arrival_stop;
/**
* @type {google.maps.Time}
*/
google.maps.TransitDetails.prototype.arrival_time;
/**
* @type {google.maps.TransitStop}
*/
google.maps.TransitDetails.prototype.departure_stop;
/**
* @type {google.maps.Time}
*/
google.maps.TransitDetails.prototype.departure_time;
/**
* @type {string}
*/
google.maps.TransitDetails.prototype.headsign;
/**
* @type {number}
*/
google.maps.TransitDetails.prototype.headway;
/**
* @type {google.maps.TransitLine}
*/
google.maps.TransitDetails.prototype.line;
/**
* @type {number}
*/
google.maps.TransitDetails.prototype.num_stops;
/**
* @interface
*/
google.maps.TransitFare = function() {};
/**
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.TransitLayer = function() {};
/**
* @nosideeffects
* @return {google.maps.Map}
*/
google.maps.TransitLayer.prototype.getMap = function() {};
/**
* @param {google.maps.Map} map
* @return {undefined}
*/
google.maps.TransitLayer.prototype.setMap = function(map) {};
/**
* @interface
*/
google.maps.TransitLine = function() {};
/**
* @type {Array<google.maps.TransitAgency>}
*/
google.maps.TransitLine.prototype.agencies;
/**
* @type {string}
*/
google.maps.TransitLine.prototype.color;
/**
* @type {string}
*/
google.maps.TransitLine.prototype.icon;
/**
* @type {string}
*/
google.maps.TransitLine.prototype.name;
/**
* @type {string}
*/
google.maps.TransitLine.prototype.short_name;
/**
* @type {string}
*/
google.maps.TransitLine.prototype.text_color;
/**
* @type {string}
*/
google.maps.TransitLine.prototype.url;
/**
* @type {google.maps.TransitVehicle}
*/
google.maps.TransitLine.prototype.vehicle;
/**
* @enum {string}
*/
google.maps.TransitMode = {
BUS: '1',
RAIL: '2',
SUBWAY: '3',
TRAIN: '4',
TRAM: ''
};
/**
* @interface
*/
google.maps.TransitOptions = function() {};
/**
* @type {Date}
*/
google.maps.TransitOptions.prototype.arrivalTime;
/**
* @type {Date}
*/
google.maps.TransitOptions.prototype.departureTime;
/**
* @type {Array<google.maps.TransitMode>}
*/
google.maps.TransitOptions.prototype.modes;
/**
* @type {google.maps.TransitRoutePreference}
*/
google.maps.TransitOptions.prototype.routingPreference;
/**
* @enum {string}
*/
google.maps.TransitRoutePreference = {
FEWER_TRANSFERS: '1',
LESS_WALKING: '2'
};
/**
* @interface
*/
google.maps.TransitStop = function() {};
/**
* @type {google.maps.LatLng}
*/
google.maps.TransitStop.prototype.location;
/**
* @type {string}
*/
google.maps.TransitStop.prototype.name;
/**
* @interface
*/
google.maps.TransitVehicle = function() {};
/**
* @type {string}
*/
google.maps.TransitVehicle.prototype.icon;
/**
* @type {string}
*/
google.maps.TransitVehicle.prototype.local_icon;
/**
* @type {string}
*/
google.maps.TransitVehicle.prototype.name;
/**
* @type {string}
*/
google.maps.TransitVehicle.prototype.type;
/**
* @enum {string}
*/
google.maps.TravelMode = {
BICYCLING: '1',
DRIVING: '2',
TRANSIT: '3',
WALKING: '4'
};
/**
* @enum {number}
*/
google.maps.UnitSystem = {
IMPERIAL: 1,
METRIC: 2
};
/**
* @interface
*/
google.maps.ZoomControlOptions = function() {};
/**
* @type {google.maps.ControlPosition}
*/
google.maps.ZoomControlOptions.prototype.position;
/**
* @type {google.maps.ZoomControlStyle}
*/
google.maps.ZoomControlOptions.prototype.style;
/**
* @enum {number}
*/
google.maps.ZoomControlStyle = {
DEFAULT: 1,
LARGE: 2,
SMALL: 3
};
/** @const */
google.maps.adsense = {};
/**
* @enum {string}
*/
google.maps.adsense.AdFormat = {
BANNER: '1',
BUTTON: '2',
HALF_BANNER: '3',
LARGE_HORIZONTAL_LINK_UNIT: '4',
LARGE_RECTANGLE: '5',
LARGE_VERTICAL_LINK_UNIT: '6',
LEADERBOARD: '7',
MEDIUM_RECTANGLE: '8',
MEDIUM_VERTICAL_LINK_UNIT: '9',
SKYSCRAPER: '10',
SMALL_HORIZONTAL_LINK_UNIT: '11',
SMALL_RECTANGLE: '12',
SMALL_SQUARE: '13',
SMALL_VERTICAL_LINK_UNIT: '14',
SQUARE: '15',
VERTICAL_BANNER: '16',
WIDE_SKYSCRAPER: '17',
X_LARGE_VERTICAL_LINK_UNIT: ''
};
/**
* @param {Node} container
* @param {google.maps.adsense.AdUnitOptions|Object.<string>} opts
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.adsense.AdUnit = function(container, opts) {};
/**
* @nosideeffects
* @return {string}
*/
google.maps.adsense.AdUnit.prototype.getBackgroundColor = function() {};
/**
* @nosideeffects
* @return {string}
*/
google.maps.adsense.AdUnit.prototype.getBorderColor = function() {};
/**
* @nosideeffects
* @return {string}
*/
google.maps.adsense.AdUnit.prototype.getChannelNumber = function() {};
/**
* @nosideeffects
* @return {Node}
*/
google.maps.adsense.AdUnit.prototype.getContainer = function() {};
/**
* @nosideeffects
* @return {google.maps.adsense.AdFormat}
*/
google.maps.adsense.AdUnit.prototype.getFormat = function() {};
/**
* @nosideeffects
* @return {google.maps.Map}
*/
google.maps.adsense.AdUnit.prototype.getMap = function() {};
/**
* @nosideeffects
* @return {google.maps.ControlPosition}
*/
google.maps.adsense.AdUnit.prototype.getPosition = function() {};
/**
* @nosideeffects
* @return {string}
*/
google.maps.adsense.AdUnit.prototype.getPublisherId = function() {};
/**
* @nosideeffects
* @return {string}
*/
google.maps.adsense.AdUnit.prototype.getTextColor = function() {};
/**
* @nosideeffects
* @return {string}
*/
google.maps.adsense.AdUnit.prototype.getTitleColor = function() {};
/**
* @nosideeffects
* @return {string}
*/
google.maps.adsense.AdUnit.prototype.getUrlColor = function() {};
/**
* @param {string} backgroundColor
* @return {undefined}
*/
google.maps.adsense.AdUnit.prototype.setBackgroundColor = function(backgroundColor) {};
/**
* @param {string} borderColor
* @return {undefined}
*/
google.maps.adsense.AdUnit.prototype.setBorderColor = function(borderColor) {};
/**
* @param {string} channelNumber
* @return {undefined}
*/
google.maps.adsense.AdUnit.prototype.setChannelNumber = function(channelNumber) {};
/**
* @param {google.maps.adsense.AdFormat} format
* @return {undefined}
*/
google.maps.adsense.AdUnit.prototype.setFormat = function(format) {};
/**
* @param {google.maps.Map} map
* @return {undefined}
*/
google.maps.adsense.AdUnit.prototype.setMap = function(map) {};
/**
* @param {google.maps.ControlPosition} position
* @return {undefined}
*/
google.maps.adsense.AdUnit.prototype.setPosition = function(position) {};
/**
* @param {string} textColor
* @return {undefined}
*/
google.maps.adsense.AdUnit.prototype.setTextColor = function(textColor) {};
/**
* @param {string} titleColor
* @return {undefined}
*/
google.maps.adsense.AdUnit.prototype.setTitleColor = function(titleColor) {};
/**
* @param {string} urlColor
* @return {undefined}
*/
google.maps.adsense.AdUnit.prototype.setUrlColor = function(urlColor) {};
/**
* @interface
*/
google.maps.adsense.AdUnitOptions = function() {};
/**
* @type {string}
*/
google.maps.adsense.AdUnitOptions.prototype.backgroundColor;
/**
* @type {string}
*/
google.maps.adsense.AdUnitOptions.prototype.borderColor;
/**
* @type {string}
*/
google.maps.adsense.AdUnitOptions.prototype.channelNumber;
/**
* @type {google.maps.adsense.AdFormat}
*/
google.maps.adsense.AdUnitOptions.prototype.format;
/**
* @type {google.maps.Map}
*/
google.maps.adsense.AdUnitOptions.prototype.map;
/**
* @type {google.maps.ControlPosition}
*/
google.maps.adsense.AdUnitOptions.prototype.position;
/**
* @type {string}
*/
google.maps.adsense.AdUnitOptions.prototype.publisherId;
/**
* @type {string}
*/
google.maps.adsense.AdUnitOptions.prototype.textColor;
/**
* @type {string}
*/
google.maps.adsense.AdUnitOptions.prototype.titleColor;
/**
* @type {string}
*/
google.maps.adsense.AdUnitOptions.prototype.urlColor;
/** @const */
google.maps.drawing = {};
/**
* @interface
*/
google.maps.drawing.DrawingControlOptions = function() {};
/**
* @type {Array<google.maps.drawing.OverlayType>}
*/
google.maps.drawing.DrawingControlOptions.prototype.drawingModes;
/**
* @type {google.maps.ControlPosition}
*/
google.maps.drawing.DrawingControlOptions.prototype.position;
/**
* @param {(google.maps.drawing.DrawingManagerOptions|Object.<string>)=} opt_options
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.drawing.DrawingManager = function(opt_options) {};
/**
* @nosideeffects
* @return {?google.maps.drawing.OverlayType}
*/
google.maps.drawing.DrawingManager.prototype.getDrawingMode = function() {};
/**
* @nosideeffects
* @return {google.maps.Map}
*/
google.maps.drawing.DrawingManager.prototype.getMap = function() {};
/**
* @param {?google.maps.drawing.OverlayType} drawingMode
* @return {undefined}
*/
google.maps.drawing.DrawingManager.prototype.setDrawingMode = function(drawingMode) {};
/**
* @param {google.maps.Map} map
* @return {undefined}
*/
google.maps.drawing.DrawingManager.prototype.setMap = function(map) {};
/**
* @param {google.maps.drawing.DrawingManagerOptions|Object.<string>} options
* @return {undefined}
*/
google.maps.drawing.DrawingManager.prototype.setOptions = function(options) {};
/**
* @interface
*/
google.maps.drawing.DrawingManagerOptions = function() {};
/**
* @type {google.maps.CircleOptions|Object.<string>}
*/
google.maps.drawing.DrawingManagerOptions.prototype.circleOptions;
/**
* @type {boolean}
*/
google.maps.drawing.DrawingManagerOptions.prototype.drawingControl;
/**
* @type {google.maps.drawing.DrawingControlOptions|Object.<string>}
*/
google.maps.drawing.DrawingManagerOptions.prototype.drawingControlOptions;
/**
* @type {google.maps.drawing.OverlayType}
*/
google.maps.drawing.DrawingManagerOptions.prototype.drawingMode;
/**
* @type {google.maps.Map}
*/
google.maps.drawing.DrawingManagerOptions.prototype.map;
/**
* @type {google.maps.MarkerOptions|Object.<string>}
*/
google.maps.drawing.DrawingManagerOptions.prototype.markerOptions;
/**
* @type {google.maps.PolygonOptions|Object.<string>}
*/
google.maps.drawing.DrawingManagerOptions.prototype.polygonOptions;
/**
* @type {google.maps.PolylineOptions|Object.<string>}
*/
google.maps.drawing.DrawingManagerOptions.prototype.polylineOptions;
/**
* @type {google.maps.RectangleOptions|Object.<string>}
*/
google.maps.drawing.DrawingManagerOptions.prototype.rectangleOptions;
/**
* @constructor
*/
google.maps.drawing.OverlayCompleteEvent = function() {};
/**
* @type {google.maps.Marker|google.maps.Polygon|google.maps.Polyline|google.maps.Rectangle|google.maps.Circle}
*/
google.maps.drawing.OverlayCompleteEvent.prototype.overlay;
/**
* @type {google.maps.drawing.OverlayType}
*/
google.maps.drawing.OverlayCompleteEvent.prototype.type;
/**
* @enum {string}
*/
google.maps.drawing.OverlayType = {
CIRCLE: '1',
MARKER: '2',
POLYGON: '3',
POLYLINE: '4',
RECTANGLE: ''
};
/** @const */
google.maps.event = {};
/**
* @param {Object} instance
* @param {string} eventName
* @param {?function(?)} handler
* @param {boolean=} opt_capture
* @return {google.maps.MapsEventListener}
*/
google.maps.event.addDomListener = function(instance, eventName, handler, opt_capture) {};
/**
* @param {Object} instance
* @param {string} eventName
* @param {function(?)} handler
* @param {boolean=} opt_capture
* @return {google.maps.MapsEventListener}
*/
google.maps.event.addDomListenerOnce = function(instance, eventName, handler, opt_capture) {};
/**
* @param {Object} instance
* @param {string} eventName
* @param {?Function} handler
* @return {google.maps.MapsEventListener}
*/
google.maps.event.addListener = function(instance, eventName, handler) {};
/**
* @param {Object} instance
* @param {string} eventName
* @param {?Function} handler
* @return {google.maps.MapsEventListener}
*/
google.maps.event.addListenerOnce = function(instance, eventName, handler) {};
/**
* @param {Object} instance
* @return {undefined}
*/
google.maps.event.clearInstanceListeners = function(instance) {};
/**
* @param {Object} instance
* @param {string} eventName
* @return {undefined}
*/
google.maps.event.clearListeners = function(instance, eventName) {};
/**
* @param {google.maps.MapsEventListener} listener
* @return {undefined}
*/
google.maps.event.removeListener = function(listener) {};
/**
* @param {Object} instance
* @param {string} eventName
* @param {...*} var_args
* @return {undefined}
*/
google.maps.event.trigger = function(instance, eventName, var_args) {};
/** @const */
google.maps.geometry = {};
/** @const */
google.maps.geometry.encoding = {};
/**
* @param {string} encodedPath
* @return {Array<google.maps.LatLng>}
*/
google.maps.geometry.encoding.decodePath = function(encodedPath) {};
/**
* @param {Array<google.maps.LatLng>|google.maps.MVCArray<google.maps.LatLng>} path
* @return {string}
*/
google.maps.geometry.encoding.encodePath = function(path) {};
/** @const */
google.maps.geometry.poly = {};
/**
* @param {google.maps.LatLng} point
* @param {google.maps.Polygon} polygon
* @return {boolean}
*/
google.maps.geometry.poly.containsLocation = function(point, polygon) {};
/**
* @param {google.maps.LatLng} point
* @param {google.maps.Polygon|google.maps.Polyline} poly
* @param {number=} opt_tolerance
* @return {boolean}
*/
google.maps.geometry.poly.isLocationOnEdge = function(point, poly, opt_tolerance) {};
/** @const */
google.maps.geometry.spherical = {};
/**
* @param {Array<google.maps.LatLng>|google.maps.MVCArray<google.maps.LatLng>} path
* @param {number=} opt_radius
* @return {number}
*/
google.maps.geometry.spherical.computeArea = function(path, opt_radius) {};
/**
* @param {google.maps.LatLng} from
* @param {google.maps.LatLng} to
* @param {number=} opt_radius
* @return {number}
*/
google.maps.geometry.spherical.computeDistanceBetween = function(from, to, opt_radius) {};
/**
* @param {google.maps.LatLng} from
* @param {google.maps.LatLng} to
* @return {number}
*/
google.maps.geometry.spherical.computeHeading = function(from, to) {};
/**
* @param {Array<google.maps.LatLng>|google.maps.MVCArray<google.maps.LatLng>} path
* @param {number=} opt_radius
* @return {number}
*/
google.maps.geometry.spherical.computeLength = function(path, opt_radius) {};
/**
* @param {google.maps.LatLng} from
* @param {number} distance
* @param {number} heading
* @param {number=} opt_radius
* @return {google.maps.LatLng}
*/
google.maps.geometry.spherical.computeOffset = function(from, distance, heading, opt_radius) {};
/**
* @param {google.maps.LatLng} to
* @param {number} distance
* @param {number} heading
* @param {number=} opt_radius
* @return {google.maps.LatLng}
*/
google.maps.geometry.spherical.computeOffsetOrigin = function(to, distance, heading, opt_radius) {};
/**
* @param {Array<google.maps.LatLng>|google.maps.MVCArray<google.maps.LatLng>} loop
* @param {number=} opt_radius
* @return {number}
*/
google.maps.geometry.spherical.computeSignedArea = function(loop, opt_radius) {};
/**
* @param {google.maps.LatLng} from
* @param {google.maps.LatLng} to
* @param {number} fraction
* @return {google.maps.LatLng}
*/
google.maps.geometry.spherical.interpolate = function(from, to, fraction) {};
/** @const */
google.maps.places = {};
/**
* @param {HTMLInputElement} inputField
* @param {(google.maps.places.AutocompleteOptions|Object.<string>)=} opt_opts
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.places.Autocomplete = function(inputField, opt_opts) {};
/**
* @nosideeffects
* @return {google.maps.LatLngBounds}
*/
google.maps.places.Autocomplete.prototype.getBounds = function() {};
/**
* @nosideeffects
* @return {google.maps.places.PlaceResult}
*/
google.maps.places.Autocomplete.prototype.getPlace = function() {};
/**
* @param {google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral} bounds
* @return {undefined}
*/
google.maps.places.Autocomplete.prototype.setBounds = function(bounds) {};
/**
* @param {google.maps.places.ComponentRestrictions} restrictions
* @return {undefined}
*/
google.maps.places.Autocomplete.prototype.setComponentRestrictions = function(restrictions) {};
/**
* @param {Array<string>} types
* @return {undefined}
*/
google.maps.places.Autocomplete.prototype.setTypes = function(types) {};
/**
* @interface
*/
google.maps.places.AutocompleteOptions = function() {};
/**
* @type {google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral}
*/
google.maps.places.AutocompleteOptions.prototype.bounds;
/**
* @type {google.maps.places.ComponentRestrictions}
*/
google.maps.places.AutocompleteOptions.prototype.componentRestrictions;
/**
* @type {Array<string>}
*/
google.maps.places.AutocompleteOptions.prototype.types;
/**
* @interface
*/
google.maps.places.AutocompletePrediction = function() {};
/**
* @type {string}
*/
google.maps.places.AutocompletePrediction.prototype.description;
/**
* @type {Array<google.maps.places.PredictionSubstring>}
*/
google.maps.places.AutocompletePrediction.prototype.matched_substrings;
/**
* @type {string}
*/
google.maps.places.AutocompletePrediction.prototype.place_id;
/**
* @type {Array<google.maps.places.PredictionTerm>}
*/
google.maps.places.AutocompletePrediction.prototype.terms;
/**
* @type {Array<string>}
*/
google.maps.places.AutocompletePrediction.prototype.types;
/**
* @constructor
*/
google.maps.places.AutocompleteService = function() {};
/**
* @param {google.maps.places.AutocompletionRequest|Object.<string>} request
* @param {function(Array<google.maps.places.AutocompletePrediction>, google.maps.places.PlacesServiceStatus)} callback
* @return {undefined}
*/
google.maps.places.AutocompleteService.prototype.getPlacePredictions = function(request, callback) {};
/**
* @param {google.maps.places.QueryAutocompletionRequest|Object.<string>} request
* @param {function(Array<google.maps.places.QueryAutocompletePrediction>, google.maps.places.PlacesServiceStatus)} callback
* @return {undefined}
*/
google.maps.places.AutocompleteService.prototype.getQueryPredictions = function(request, callback) {};
/**
* @interface
*/
google.maps.places.AutocompletionRequest = function() {};
/**
* @type {google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral}
*/
google.maps.places.AutocompletionRequest.prototype.bounds;
/**
* @type {google.maps.places.ComponentRestrictions}
*/
google.maps.places.AutocompletionRequest.prototype.componentRestrictions;
/**
* @type {string}
*/
google.maps.places.AutocompletionRequest.prototype.input;
/**
* @type {google.maps.LatLng}
*/
google.maps.places.AutocompletionRequest.prototype.location;
/**
* @type {number}
*/
google.maps.places.AutocompletionRequest.prototype.offset;
/**
* @type {number}
*/
google.maps.places.AutocompletionRequest.prototype.radius;
/**
* @type {Array<string>}
*/
google.maps.places.AutocompletionRequest.prototype.types;
/**
* @interface
*/
google.maps.places.ComponentRestrictions = function() {};
/**
* @type {string}
*/
google.maps.places.ComponentRestrictions.prototype.country;
/**
* @constructor
*/
google.maps.places.PhotoOptions = function() {};
/**
* @type {number}
*/
google.maps.places.PhotoOptions.prototype.maxHeight;
/**
* @type {number}
*/
google.maps.places.PhotoOptions.prototype.maxWidth;
/**
* @constructor
*/
google.maps.places.PlaceAspectRating = function() {};
/**
* @type {number}
*/
google.maps.places.PlaceAspectRating.prototype.rating;
/**
* @type {string}
*/
google.maps.places.PlaceAspectRating.prototype.type;
/**
* @interface
*/
google.maps.places.PlaceDetailsRequest = function() {};
/**
* @type {string}
*/
google.maps.places.PlaceDetailsRequest.prototype.placeId;
/**
* @interface
*/
google.maps.places.PlaceGeometry = function() {};
/**
* @type {google.maps.LatLng}
*/
google.maps.places.PlaceGeometry.prototype.location;
/**
* @type {google.maps.LatLngBounds}
*/
google.maps.places.PlaceGeometry.prototype.viewport;
/**
* @interface
*/
google.maps.places.PlacePhoto = function() {};
/**
* @type {number}
*/
google.maps.places.PlacePhoto.prototype.height;
/**
* @type {Array<string>}
*/
google.maps.places.PlacePhoto.prototype.html_attributions;
/**
* @type {number}
*/
google.maps.places.PlacePhoto.prototype.width;
/**
* @param {google.maps.places.PhotoOptions|Object.<string>} opts
* @return {string}
*/
google.maps.places.PlacePhoto.prototype.getUrl = function(opts) {};
/**
* @interface
*/
google.maps.places.PlaceResult = function() {};
/**
* @type {Array<google.maps.GeocoderAddressComponent>}
*/
google.maps.places.PlaceResult.prototype.address_components;
/**
* @type {Array<google.maps.places.PlaceAspectRating>}
*/
google.maps.places.PlaceResult.prototype.aspects;
/**
* @type {string}
*/
google.maps.places.PlaceResult.prototype.formatted_address;
/**
* @type {string}
*/
google.maps.places.PlaceResult.prototype.formatted_phone_number;
/**
* @type {google.maps.places.PlaceGeometry}
*/
google.maps.places.PlaceResult.prototype.geometry;
/**
* @type {Array<string>}
*/
google.maps.places.PlaceResult.prototype.html_attributions;
/**
* @type {string}
*/
google.maps.places.PlaceResult.prototype.icon;
/**
* @type {string}
*/
google.maps.places.PlaceResult.prototype.international_phone_number;
/**
* @type {string}
*/
google.maps.places.PlaceResult.prototype.name;
/**
* @type {boolean}
*/
google.maps.places.PlaceResult.prototype.permanently_closed;
/**
* @type {Array<google.maps.places.PlacePhoto>}
*/
google.maps.places.PlaceResult.prototype.photos;
/**
* @type {string}
*/
google.maps.places.PlaceResult.prototype.place_id;
/**
* @type {number}
*/
google.maps.places.PlaceResult.prototype.price_level;
/**
* @type {number}
*/
google.maps.places.PlaceResult.prototype.rating;
/**
* @type {Array<google.maps.places.PlaceReview>}
*/
google.maps.places.PlaceResult.prototype.reviews;
/**
* @type {Array<string>}
*/
google.maps.places.PlaceResult.prototype.types;
/**
* @type {string}
*/
google.maps.places.PlaceResult.prototype.url;
/**
* @type {number}
*/
google.maps.places.PlaceResult.prototype.utc_offset;
/**
* @type {string}
*/
google.maps.places.PlaceResult.prototype.vicinity;
/**
* @type {string}
*/
google.maps.places.PlaceResult.prototype.website;
/**
* @constructor
*/
google.maps.places.PlaceReview = function() {};
/**
* @type {Array<google.maps.places.PlaceAspectRating>}
*/
google.maps.places.PlaceReview.prototype.aspects;
/**
* @type {string}
*/
google.maps.places.PlaceReview.prototype.author_name;
/**
* @type {string}
*/
google.maps.places.PlaceReview.prototype.author_url;
/**
* @type {string}
*/
google.maps.places.PlaceReview.prototype.language;
/**
* @type {string}
*/
google.maps.places.PlaceReview.prototype.text;
/**
* @constructor
*/
google.maps.places.PlaceSearchPagination = function() {};
/**
* @type {boolean}
*/
google.maps.places.PlaceSearchPagination.prototype.hasNextPage;
/**
* @return {undefined}
*/
google.maps.places.PlaceSearchPagination.prototype.nextPage = function() {};
/**
* @interface
*/
google.maps.places.PlaceSearchRequest = function() {};
/**
* @type {google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral}
*/
google.maps.places.PlaceSearchRequest.prototype.bounds;
/**
* @type {string}
*/
google.maps.places.PlaceSearchRequest.prototype.keyword;
/**
* @type {google.maps.LatLng|google.maps.LatLngLiteral}
*/
google.maps.places.PlaceSearchRequest.prototype.location;
/**
* @type {number}
*/
google.maps.places.PlaceSearchRequest.prototype.maxPriceLevel;
/**
* @type {number}
*/
google.maps.places.PlaceSearchRequest.prototype.minPriceLevel;
/**
* @type {string}
*/
google.maps.places.PlaceSearchRequest.prototype.name;
/**
* @type {boolean}
*/
google.maps.places.PlaceSearchRequest.prototype.openNow;
/**
* @type {number}
*/
google.maps.places.PlaceSearchRequest.prototype.radius;
/**
* @type {google.maps.places.RankBy}
*/
google.maps.places.PlaceSearchRequest.prototype.rankBy;
/**
* @type {Array<string>}
*/
google.maps.places.PlaceSearchRequest.prototype.types;
/**
* @param {HTMLDivElement|google.maps.Map} attrContainer
* @constructor
*/
google.maps.places.PlacesService = function(attrContainer) {};
/**
* @param {google.maps.places.PlaceDetailsRequest|Object.<string>} request
* @param {function(google.maps.places.PlaceResult, google.maps.places.PlacesServiceStatus)} callback
* @return {undefined}
*/
google.maps.places.PlacesService.prototype.getDetails = function(request, callback) {};
/**
* @param {google.maps.places.PlaceSearchRequest|Object.<string>} request
* @param {function(Array<google.maps.places.PlaceResult>, google.maps.places.PlacesServiceStatus,
google.maps.places.PlaceSearchPagination)} callback
* @return {undefined}
*/
google.maps.places.PlacesService.prototype.nearbySearch = function(request, callback) {};
/**
* @param {google.maps.places.RadarSearchRequest|Object.<string>} request
* @param {function(Array<google.maps.places.PlaceResult>, google.maps.places.PlacesServiceStatus)} callback
* @return {undefined}
*/
google.maps.places.PlacesService.prototype.radarSearch = function(request, callback) {};
/**
* @param {google.maps.places.TextSearchRequest|Object.<string>} request
* @param {function(Array<google.maps.places.PlaceResult>, google.maps.places.PlacesServiceStatus,
google.maps.places.PlaceSearchPagination)} callback
* @return {undefined}
*/
google.maps.places.PlacesService.prototype.textSearch = function(request, callback) {};
/**
* @enum {string}
*/
google.maps.places.PlacesServiceStatus = {
INVALID_REQUEST: '1',
OK: '2',
OVER_QUERY_LIMIT: '3',
REQUEST_DENIED: '4',
UNKNOWN_ERROR: '5',
ZERO_RESULTS: ''
};
/**
* @interface
*/
google.maps.places.PredictionSubstring = function() {};
/**
* @type {number}
*/
google.maps.places.PredictionSubstring.prototype.length;
/**
* @type {number}
*/
google.maps.places.PredictionSubstring.prototype.offset;
/**
* @interface
*/
google.maps.places.PredictionTerm = function() {};
/**
* @type {number}
*/
google.maps.places.PredictionTerm.prototype.offset;
/**
* @type {string}
*/
google.maps.places.PredictionTerm.prototype.value;
/**
* @interface
*/
google.maps.places.QueryAutocompletePrediction = function() {};
/**
* @type {string}
*/
google.maps.places.QueryAutocompletePrediction.prototype.description;
/**
* @type {Array<google.maps.places.PredictionSubstring>}
*/
google.maps.places.QueryAutocompletePrediction.prototype.matched_substrings;
/**
* @type {string}
*/
google.maps.places.QueryAutocompletePrediction.prototype.place_id;
/**
* @type {Array<google.maps.places.PredictionTerm>}
*/
google.maps.places.QueryAutocompletePrediction.prototype.terms;
/**
* @interface
*/
google.maps.places.QueryAutocompletionRequest = function() {};
/**
* @type {google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral}
*/
google.maps.places.QueryAutocompletionRequest.prototype.bounds;
/**
* @type {string}
*/
google.maps.places.QueryAutocompletionRequest.prototype.input;
/**
* @type {google.maps.LatLng}
*/
google.maps.places.QueryAutocompletionRequest.prototype.location;
/**
* @type {number}
*/
google.maps.places.QueryAutocompletionRequest.prototype.offset;
/**
* @type {number}
*/
google.maps.places.QueryAutocompletionRequest.prototype.radius;
/**
* @interface
*/
google.maps.places.RadarSearchRequest = function() {};
/**
* @type {google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral}
*/
google.maps.places.RadarSearchRequest.prototype.bounds;
/**
* @type {string}
*/
google.maps.places.RadarSearchRequest.prototype.keyword;
/**
* @type {google.maps.LatLng|google.maps.LatLngLiteral}
*/
google.maps.places.RadarSearchRequest.prototype.location;
/**
* @type {string}
*/
google.maps.places.RadarSearchRequest.prototype.name;
/**
* @type {number}
*/
google.maps.places.RadarSearchRequest.prototype.radius;
/**
* @type {Array<string>}
*/
google.maps.places.RadarSearchRequest.prototype.types;
/**
* @enum {number}
*/
google.maps.places.RankBy = {
DISTANCE: 1,
PROMINENCE: 2
};
/**
* @param {HTMLInputElement} inputField
* @param {(google.maps.places.SearchBoxOptions|Object.<string>)=} opt_opts
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.places.SearchBox = function(inputField, opt_opts) {};
/**
* @nosideeffects
* @return {google.maps.LatLngBounds}
*/
google.maps.places.SearchBox.prototype.getBounds = function() {};
/**
* @nosideeffects
* @return {Array<google.maps.places.PlaceResult>}
*/
google.maps.places.SearchBox.prototype.getPlaces = function() {};
/**
* @param {google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral} bounds
* @return {undefined}
*/
google.maps.places.SearchBox.prototype.setBounds = function(bounds) {};
/**
* @interface
*/
google.maps.places.SearchBoxOptions = function() {};
/**
* @type {google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral}
*/
google.maps.places.SearchBoxOptions.prototype.bounds;
/**
* @interface
*/
google.maps.places.TextSearchRequest = function() {};
/**
* @type {google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral}
*/
google.maps.places.TextSearchRequest.prototype.bounds;
/**
* @type {google.maps.LatLng|google.maps.LatLngLiteral}
*/
google.maps.places.TextSearchRequest.prototype.location;
/**
* @type {string}
*/
google.maps.places.TextSearchRequest.prototype.query;
/**
* @type {number}
*/
google.maps.places.TextSearchRequest.prototype.radius;
/**
* @type {Array<string>}
*/
google.maps.places.TextSearchRequest.prototype.types;
/** @const */
google.maps.visualization = {};
/**
* @param {google.maps.visualization.DynamicMapsEngineLayerOptions|Object.<string>} options
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.visualization.DynamicMapsEngineLayer = function(options) {};
/**
* @param {string} featureId
* @return {google.maps.visualization.FeatureStyle}
*/
google.maps.visualization.DynamicMapsEngineLayer.prototype.getFeatureStyle = function(featureId) {};
/**
* @nosideeffects
* @return {string}
*/
google.maps.visualization.DynamicMapsEngineLayer.prototype.getLayerId = function() {};
/**
* @nosideeffects
* @return {string}
*/
google.maps.visualization.DynamicMapsEngineLayer.prototype.getLayerKey = function() {};
/**
* @nosideeffects
* @return {google.maps.Map}
*/
google.maps.visualization.DynamicMapsEngineLayer.prototype.getMap = function() {};
/**
* @nosideeffects
* @return {string}
*/
google.maps.visualization.DynamicMapsEngineLayer.prototype.getMapId = function() {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.visualization.DynamicMapsEngineLayer.prototype.getOpacity = function() {};
/**
* @nosideeffects
* @return {google.maps.visualization.MapsEngineStatus}
*/
google.maps.visualization.DynamicMapsEngineLayer.prototype.getStatus = function() {};
/**
* @param {string} layerId
* @return {undefined}
*/
google.maps.visualization.DynamicMapsEngineLayer.prototype.setLayerId = function(layerId) {};
/**
* @param {string} layerKey
* @return {undefined}
*/
google.maps.visualization.DynamicMapsEngineLayer.prototype.setLayerKey = function(layerKey) {};
/**
* @param {google.maps.Map} map
* @return {undefined}
*/
google.maps.visualization.DynamicMapsEngineLayer.prototype.setMap = function(map) {};
/**
* @param {string} mapId
* @return {undefined}
*/
google.maps.visualization.DynamicMapsEngineLayer.prototype.setMapId = function(mapId) {};
/**
* @param {number} opacity
* @return {undefined}
*/
google.maps.visualization.DynamicMapsEngineLayer.prototype.setOpacity = function(opacity) {};
/**
* @param {google.maps.visualization.DynamicMapsEngineLayerOptions|Object.<string>} options
* @return {undefined}
*/
google.maps.visualization.DynamicMapsEngineLayer.prototype.setOptions = function(options) {};
/**
* @interface
*/
google.maps.visualization.DynamicMapsEngineLayerOptions = function() {};
/**
* @type {string}
*/
google.maps.visualization.DynamicMapsEngineLayerOptions.prototype.accessToken;
/**
* @type {boolean}
*/
google.maps.visualization.DynamicMapsEngineLayerOptions.prototype.clickable;
/**
* @type {string}
*/
google.maps.visualization.DynamicMapsEngineLayerOptions.prototype.layerId;
/**
* @type {string}
*/
google.maps.visualization.DynamicMapsEngineLayerOptions.prototype.layerKey;
/**
* @type {google.maps.Map}
*/
google.maps.visualization.DynamicMapsEngineLayerOptions.prototype.map;
/**
* @type {string}
*/
google.maps.visualization.DynamicMapsEngineLayerOptions.prototype.mapId;
/**
* @type {number}
*/
google.maps.visualization.DynamicMapsEngineLayerOptions.prototype.opacity;
/**
* @type {boolean}
*/
google.maps.visualization.DynamicMapsEngineLayerOptions.prototype.suppressInfoWindows;
/**
* @interface
*/
google.maps.visualization.DynamicMapsEngineMouseEvent = function() {};
/**
* @type {string}
*/
google.maps.visualization.DynamicMapsEngineMouseEvent.prototype.featureId;
/**
* @type {google.maps.LatLng}
*/
google.maps.visualization.DynamicMapsEngineMouseEvent.prototype.latLng;
/**
* @param {function(google.maps.visualization.MapsEngineMouseEvent)} callback
* @return {undefined}
*/
google.maps.visualization.DynamicMapsEngineMouseEvent.prototype.getDetails = function(callback) {};
/**
* @interface
*/
google.maps.visualization.FeatureStyle = function() {};
/**
* @type {string}
*/
google.maps.visualization.FeatureStyle.prototype.fillColor;
/**
* @type {string}
*/
google.maps.visualization.FeatureStyle.prototype.fillOpacity;
/**
* @type {string}
*/
google.maps.visualization.FeatureStyle.prototype.iconAnchor;
/**
* @type {string}
*/
google.maps.visualization.FeatureStyle.prototype.iconClip;
/**
* @type {string}
*/
google.maps.visualization.FeatureStyle.prototype.iconImage;
/**
* @type {string}
*/
google.maps.visualization.FeatureStyle.prototype.iconOpacity;
/**
* @type {string}
*/
google.maps.visualization.FeatureStyle.prototype.iconSize;
/**
* @type {string}
*/
google.maps.visualization.FeatureStyle.prototype.strokeColor;
/**
* @type {string}
*/
google.maps.visualization.FeatureStyle.prototype.strokeOpacity;
/**
* @type {string}
*/
google.maps.visualization.FeatureStyle.prototype.strokeWidth;
/**
* @type {string}
*/
google.maps.visualization.FeatureStyle.prototype.zIndex;
/**
* @param {string} property
* @return {undefined}
*/
google.maps.visualization.FeatureStyle.prototype.reset = function(property) {};
/**
* @return {undefined}
*/
google.maps.visualization.FeatureStyle.prototype.resetAll = function() {};
/**
* @param {(google.maps.visualization.HeatmapLayerOptions|Object.<string>)=} opt_opts
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.visualization.HeatmapLayer = function(opt_opts) {};
/**
* @nosideeffects
* @return {google.maps.MVCArray<google.maps.LatLng|google.maps.visualization.WeightedLocation>}
*/
google.maps.visualization.HeatmapLayer.prototype.getData = function() {};
/**
* @nosideeffects
* @return {google.maps.Map}
*/
google.maps.visualization.HeatmapLayer.prototype.getMap = function() {};
/**
* @param {google.maps.MVCArray<google.maps.LatLng|google.maps.visualization.WeightedLocation>|
Array<google.maps.LatLng|google.maps.visualization.WeightedLocation>} data
* @return {undefined}
*/
google.maps.visualization.HeatmapLayer.prototype.setData = function(data) {};
/**
* @param {google.maps.Map} map
* @return {undefined}
*/
google.maps.visualization.HeatmapLayer.prototype.setMap = function(map) {};
/**
* @param {google.maps.visualization.HeatmapLayerOptions|Object.<string>} options
* @return {undefined}
*/
google.maps.visualization.HeatmapLayer.prototype.setOptions = function(options) {};
/**
* @interface
*/
google.maps.visualization.HeatmapLayerOptions = function() {};
/**
* @type {google.maps.MVCArray<google.maps.LatLng>}
*/
google.maps.visualization.HeatmapLayerOptions.prototype.data;
/**
* @type {boolean}
*/
google.maps.visualization.HeatmapLayerOptions.prototype.dissipating;
/**
* @type {Array<string>}
*/
google.maps.visualization.HeatmapLayerOptions.prototype.gradient;
/**
* @type {google.maps.Map}
*/
google.maps.visualization.HeatmapLayerOptions.prototype.map;
/**
* @type {number}
*/
google.maps.visualization.HeatmapLayerOptions.prototype.maxIntensity;
/**
* @type {number}
*/
google.maps.visualization.HeatmapLayerOptions.prototype.opacity;
/**
* @type {number}
*/
google.maps.visualization.HeatmapLayerOptions.prototype.radius;
/**
* @param {google.maps.visualization.MapsEngineLayerOptions|Object.<string>} options
* @extends {google.maps.MVCObject}
* @constructor
*/
google.maps.visualization.MapsEngineLayer = function(options) {};
/**
* @nosideeffects
* @return {string}
*/
google.maps.visualization.MapsEngineLayer.prototype.getLayerId = function() {};
/**
* @nosideeffects
* @return {string}
*/
google.maps.visualization.MapsEngineLayer.prototype.getLayerKey = function() {};
/**
* @nosideeffects
* @return {google.maps.Map}
*/
google.maps.visualization.MapsEngineLayer.prototype.getMap = function() {};
/**
* @nosideeffects
* @return {string}
*/
google.maps.visualization.MapsEngineLayer.prototype.getMapId = function() {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.visualization.MapsEngineLayer.prototype.getOpacity = function() {};
/**
* @nosideeffects
* @return {google.maps.visualization.MapsEngineLayerProperties}
*/
google.maps.visualization.MapsEngineLayer.prototype.getProperties = function() {};
/**
* @nosideeffects
* @return {google.maps.visualization.MapsEngineStatus}
*/
google.maps.visualization.MapsEngineLayer.prototype.getStatus = function() {};
/**
* @nosideeffects
* @return {number}
*/
google.maps.visualization.MapsEngineLayer.prototype.getZIndex = function() {};
/**
* @param {string} layerId
* @return {undefined}
*/
google.maps.visualization.MapsEngineLayer.prototype.setLayerId = function(layerId) {};
/**
* @param {string} layerKey
* @return {undefined}
*/
google.maps.visualization.MapsEngineLayer.prototype.setLayerKey = function(layerKey) {};
/**
* @param {google.maps.Map} map
* @return {undefined}
*/
google.maps.visualization.MapsEngineLayer.prototype.setMap = function(map) {};
/**
* @param {string} mapId
* @return {undefined}
*/
google.maps.visualization.MapsEngineLayer.prototype.setMapId = function(mapId) {};
/**
* @param {number} opacity
* @return {undefined}
*/
google.maps.visualization.MapsEngineLayer.prototype.setOpacity = function(opacity) {};
/**
* @param {google.maps.visualization.MapsEngineLayerOptions|Object.<string>} options
* @return {undefined}
*/
google.maps.visualization.MapsEngineLayer.prototype.setOptions = function(options) {};
/**
* @param {number} zIndex
* @return {undefined}
*/
google.maps.visualization.MapsEngineLayer.prototype.setZIndex = function(zIndex) {};
/**
* @interface
*/
google.maps.visualization.MapsEngineLayerOptions = function() {};
/**
* @type {string}
*/
google.maps.visualization.MapsEngineLayerOptions.prototype.accessToken;
/**
* @type {boolean}
*/
google.maps.visualization.MapsEngineLayerOptions.prototype.clickable;
/**
* @type {boolean}
*/
google.maps.visualization.MapsEngineLayerOptions.prototype.fitBounds;
/**
* @type {string}
*/
google.maps.visualization.MapsEngineLayerOptions.prototype.layerId;
/**
* @type {string}
*/
google.maps.visualization.MapsEngineLayerOptions.prototype.layerKey;
/**
* @type {google.maps.Map}
*/
google.maps.visualization.MapsEngineLayerOptions.prototype.map;
/**
* @type {string}
*/
google.maps.visualization.MapsEngineLayerOptions.prototype.mapId;
/**
* @type {number}
*/
google.maps.visualization.MapsEngineLayerOptions.prototype.opacity;
/**
* @type {boolean}
*/
google.maps.visualization.MapsEngineLayerOptions.prototype.suppressInfoWindows;
/**
* @type {number}
*/
google.maps.visualization.MapsEngineLayerOptions.prototype.zIndex;
/**
* @interface
*/
google.maps.visualization.MapsEngineLayerProperties = function() {};
/**
* @type {string}
*/
google.maps.visualization.MapsEngineLayerProperties.prototype.name;
/**
* @interface
*/
google.maps.visualization.MapsEngineMouseEvent = function() {};
/**
* @type {string}
*/
google.maps.visualization.MapsEngineMouseEvent.prototype.featureId;
/**
* @type {string}
*/
google.maps.visualization.MapsEngineMouseEvent.prototype.infoWindowHtml;
/**
* @type {google.maps.LatLng}
*/
google.maps.visualization.MapsEngineMouseEvent.prototype.latLng;
/**
* @type {google.maps.Size}
*/
google.maps.visualization.MapsEngineMouseEvent.prototype.pixelOffset;
/**
* @enum {string}
*/
google.maps.visualization.MapsEngineStatus = {
INVALID_LAYER: '1',
OK: '2',
UNKNOWN_ERROR: '3'
};
/**
* @interface
*/
google.maps.visualization.WeightedLocation = function() {};
/**
* @type {google.maps.LatLng}
*/
google.maps.visualization.WeightedLocation.prototype.location;
/**
* @type {number}
*/
google.maps.visualization.WeightedLocation.prototype.weight;
| apache-2.0 |
neumerance/cloudloon2 | horizon/forms/__init__.py | 1400 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
# FIXME(gabriel): Legacy imports for API compatibility.
from django.forms import * # noqa
from django.forms import widgets
# Convenience imports for public API components.
from horizon.forms.base import DateForm # noqa
from horizon.forms.base import SelfHandlingForm # noqa
from horizon.forms.base import SelfHandlingMixin # noqa
from horizon.forms.fields import DynamicChoiceField # noqa
from horizon.forms.fields import DynamicTypedChoiceField # noqa
from horizon.forms.views import ModalFormMixin # noqa
from horizon.forms.views import ModalFormView # noqa
assert widgets
assert SelfHandlingMixin
assert SelfHandlingForm
assert DateForm
assert ModalFormView
assert ModalFormMixin
assert DynamicTypedChoiceField
assert DynamicChoiceField
| apache-2.0 |
sferich888/origin | vendor/github.com/go-ozzo/ozzo-validation/multipleof_test.go | 1069 | // Copyright 2016 Qiang Xue, Google LLC. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package validation
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestMultipleof(t *testing.T) {
r := MultipleOf(int(10))
assert.Equal(t, "must be multiple of 10", r.Validate(int(11)).Error())
assert.Equal(t, nil, r.Validate(int(20)))
assert.Equal(t, "cannot convert float32 to int64", r.Validate(float32(20)).Error())
r2 := MultipleOf("some string ....")
assert.Equal(t, "type not supported: string", r2.Validate(10).Error())
r3 := MultipleOf(uint(10))
assert.Equal(t, "must be multiple of 10", r3.Validate(uint(11)).Error())
assert.Equal(t, nil, r3.Validate(uint(20)))
assert.Equal(t, "cannot convert float32 to uint64", r3.Validate(float32(20)).Error())
}
func Test_Multipleof_Error(t *testing.T) {
r := MultipleOf(10)
assert.Equal(t, "must be multiple of 10", r.message)
r.Error("some error string ...")
assert.Equal(t, "some error string ...", r.message)
}
| apache-2.0 |
olafdm/tp-off-oasp4j | oasp4j-samples/oasp4j-sample-core/src/main/java/io/oasp/gastronomy/restaurant/offermanagement/dataaccess/api/dao/ProductDao.java | 1527 | package io.oasp.gastronomy.restaurant.offermanagement.dataaccess.api.dao;
import io.oasp.gastronomy.restaurant.general.dataaccess.api.dao.ApplicationRevisionedDao;
import io.oasp.gastronomy.restaurant.offermanagement.dataaccess.api.ProductEntity;
import io.oasp.gastronomy.restaurant.offermanagement.logic.api.to.ProductFilter;
import io.oasp.gastronomy.restaurant.offermanagement.logic.api.to.ProductSearchCriteriaTo;
import io.oasp.gastronomy.restaurant.offermanagement.logic.api.to.ProductSortBy;
import io.oasp.module.jpa.common.api.to.PaginatedListTo;
import io.oasp.module.jpa.dataaccess.api.MasterDataDao;
import java.util.List;
/**
* {@link ApplicationRevisionedDao Data Access Object} for {@link ProductEntity} entity.
*
* @author loverbec
*/
public interface ProductDao extends ApplicationRevisionedDao<ProductEntity>, MasterDataDao<ProductEntity> {
/**
* @param productFilter is the {@link ProductFilter}.
* @param sortBy is the {@link ProductSortBy} criteria.
* @return the {@link List} of filtered and sorted {@link ProductEntity products}.
*/
@Deprecated
List<ProductEntity> findProductsFiltered(ProductFilter productFilter, ProductSortBy sortBy);
/**
* Finds the {@link ProductEntity} objects matching the given {@link ProductSearchCriteriaTo}.
*
* @param criteria is the {@link ProductSearchCriteriaTo}.
* @return the {@link List} with the matching {@link ProductEntity} objects.
*/
PaginatedListTo<ProductEntity> findProducts(ProductSearchCriteriaTo criteria);
}
| apache-2.0 |
simon3z/kubernetes | pkg/kubelet/types.go | 3235 | /*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubelet
import (
"fmt"
"strings"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
"github.com/golang/glog"
)
const ConfigSourceAnnotationKey = "kubernetes.io/config.source"
// PodOperation defines what changes will be made on a pod configuration.
type PodOperation int
const (
// This is the current pod configuration
SET PodOperation = iota
// Pods with the given ids are new to this source
ADD
// Pods with the given ids have been removed from this source
REMOVE
// Pods with the given ids have been updated in this source
UPDATE
// These constants identify the sources of pods
// Updates from a file
FileSource = "file"
// Updates from etcd
EtcdSource = "etcd"
// Updates from querying a web page
HTTPSource = "http"
// Updates received to the kubelet server
ServerSource = "server"
// Updates from Kubernetes API Server
ApiserverSource = "api"
// Updates from all sources
AllSource = "*"
)
// PodUpdate defines an operation sent on the channel. You can add or remove single services by
// sending an array of size one and Op == ADD|REMOVE (with REMOVE, only the ID is required).
// For setting the state of the system to a given state for this source configuration, set
// Pods as desired and Op to SET, which will reset the system state to that specified in this
// operation for this source channel. To remove all pods, set Pods to empty object and Op to SET.
//
// Additionally, Pods should never be nil - it should always point to an empty slice. While
// functionally similar, this helps our unit tests properly check that the correct PodUpdates
// are generated.
type PodUpdate struct {
Pods []api.BoundPod
Op PodOperation
Source string
}
// GetPodFullName returns a name that uniquely identifies a pod across all config sources.
func GetPodFullName(pod *api.BoundPod) string {
return fmt.Sprintf("%s.%s.%s", pod.Name, pod.Namespace, pod.Annotations[ConfigSourceAnnotationKey])
}
// ParsePodFullName unpacks a pod full name and returns the pod name, namespace, and annotations.
// If the pod full name is invalid, empty strings are returend.
func ParsePodFullName(podFullName string) (podName, podNamespace string, podAnnotations map[string]string) {
parts := strings.Split(podFullName, ".")
expectedNumFields := 3
actualNumFields := len(parts)
if actualNumFields != expectedNumFields {
glog.Errorf("found a podFullName (%q) with too few fields: expected %d, actual %d.", podFullName, expectedNumFields, actualNumFields)
return
}
podName = parts[0]
podNamespace = parts[1]
podAnnotations = make(map[string]string)
podAnnotations[ConfigSourceAnnotationKey] = parts[2]
return
}
| apache-2.0 |
astaxie/tidb | parser/lexer.go | 15437 | // Copyright 2016 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package parser
import (
"bytes"
"fmt"
"strings"
"unicode"
"unicode/utf8"
"github.com/pingcap/tidb/mysql"
)
var _ = yyLexer(&Scanner{})
// Pos represents the position of a token.
type Pos struct {
Line int
Col int
Offset int
}
// Scanner implements the yyLexer interface.
type Scanner struct {
r reader
buf bytes.Buffer
errs []error
stmtStartPos int
// For scanning such kind of comment: /*! MySQL-specific code */ or /*+ optimizer hint */
specialComment specialCommentScanner
sqlMode mysql.SQLMode
}
type specialCommentScanner interface {
scan() (tok int, pos Pos, lit string)
}
type mysqlSpecificCodeScanner struct {
*Scanner
Pos
}
func (s *mysqlSpecificCodeScanner) scan() (tok int, pos Pos, lit string) {
tok, pos, lit = s.Scanner.scan()
pos.Line += s.Pos.Line
pos.Col += s.Pos.Col
pos.Offset += s.Pos.Offset
return
}
type optimizerHintScanner struct {
*Scanner
Pos
end bool
}
func (s *optimizerHintScanner) scan() (tok int, pos Pos, lit string) {
tok, pos, lit = s.Scanner.scan()
pos.Line += s.Pos.Line
pos.Col += s.Pos.Col
pos.Offset += s.Pos.Offset
if tok == 0 {
if !s.end {
tok = hintEnd
s.end = true
}
}
return
}
// Errors returns the errors during a scan.
func (s *Scanner) Errors() []error {
return s.errs
}
// reset resets the sql string to be scanned.
func (s *Scanner) reset(sql string) {
s.r = reader{s: sql}
s.buf.Reset()
s.errs = s.errs[:0]
s.stmtStartPos = 0
}
func (s *Scanner) stmtText() string {
endPos := s.r.pos().Offset
if s.r.s[endPos-1] == '\n' {
endPos = endPos - 1 // trim new line
}
if s.r.s[s.stmtStartPos] == '\n' {
s.stmtStartPos++
}
text := s.r.s[s.stmtStartPos:endPos]
s.stmtStartPos = endPos
return text
}
// Errorf tells scanner something is wrong.
// Scanner satisfies yyLexer interface which need this function.
func (s *Scanner) Errorf(format string, a ...interface{}) {
str := fmt.Sprintf(format, a...)
val := s.r.s[s.r.pos().Offset:]
if len(val) > 2048 {
val = val[:2048]
}
err := fmt.Errorf("line %d column %d near \"%s\"%s (total length %d)", s.r.p.Line, s.r.p.Col, val, str, len(s.r.s))
s.errs = append(s.errs, err)
}
// Lex returns a token and store the token value in v.
// Scanner satisfies yyLexer interface.
// 0 and invalid are special token id this function would return:
// return 0 tells parser that scanner meets EOF,
// return invalid tells parser that scanner meets illegal character.
func (s *Scanner) Lex(v *yySymType) int {
tok, pos, lit := s.scan()
v.offset = pos.Offset
v.ident = lit
if tok == identifier {
tok = handleIdent(v)
}
if tok == identifier {
if tok1 := isTokenIdentifier(lit, &s.buf); tok1 != 0 {
tok = tok1
}
}
if (s.sqlMode&mysql.ModeANSIQuotes) > 0 &&
tok == stringLit &&
s.r.s[v.offset] == '"' {
tok = identifier
}
switch tok {
case intLit:
return toInt(s, v, lit)
case floatLit:
return toFloat(s, v, lit)
case decLit:
return toDecimal(s, v, lit)
case hexLit:
return toHex(s, v, lit)
case bitLit:
return toBit(s, v, lit)
case userVar, sysVar, cast, curDate, extract:
v.item = lit
return tok
case null:
v.item = nil
case quotedIdentifier:
tok = identifier
}
if tok == unicode.ReplacementChar && s.r.eof() {
return 0
}
return tok
}
// SetSQLMode sets the SQL mode for scanner.
func (s *Scanner) SetSQLMode(mode mysql.SQLMode) {
s.sqlMode = mode
}
// NewScanner returns a new scanner object.
func NewScanner(s string) *Scanner {
return &Scanner{r: reader{s: s}}
}
func (s *Scanner) skipWhitespace() rune {
return s.r.incAsLongAs(unicode.IsSpace)
}
func (s *Scanner) scan() (tok int, pos Pos, lit string) {
if s.specialComment != nil {
// Enter specialComment scan mode.
// for scanning such kind of comment: /*! MySQL-specific code */
specialComment := s.specialComment
tok, pos, lit = specialComment.scan()
if tok != 0 {
// return the specialComment scan result as the result
return
}
// leave specialComment scan mode after all stream consumed.
s.specialComment = nil
}
ch0 := s.r.peek()
if unicode.IsSpace(ch0) {
ch0 = s.skipWhitespace()
}
pos = s.r.pos()
if s.r.eof() {
// when scanner meets EOF, the returned token should be 0,
// because 0 is a special token id to remind the parser that stream is end.
return 0, pos, ""
}
if !s.r.eof() && isIdentExtend(ch0) {
return scanIdentifier(s)
}
// search a trie to get a token.
node := &ruleTable
for ch0 >= 0 && ch0 <= 255 {
if node.childs[ch0] == nil || s.r.eof() {
break
}
node = node.childs[ch0]
if node.fn != nil {
return node.fn(s)
}
s.r.inc()
ch0 = s.r.peek()
}
tok, lit = node.token, s.r.data(&pos)
return
}
func startWithXx(s *Scanner) (tok int, pos Pos, lit string) {
pos = s.r.pos()
s.r.inc()
if s.r.peek() == '\'' {
s.r.inc()
s.scanHex()
if s.r.peek() == '\'' {
s.r.inc()
tok, lit = hexLit, s.r.data(&pos)
} else {
tok = unicode.ReplacementChar
}
return
}
s.r.incAsLongAs(isIdentChar)
tok, lit = identifier, s.r.data(&pos)
return
}
func startWithNn(s *Scanner) (tok int, pos Pos, lit string) {
tok, pos, lit = scanIdentifier(s)
// The National Character Set, N'some text' or n'some test'.
// See https://dev.mysql.com/doc/refman/5.7/en/string-literals.html
// and https://dev.mysql.com/doc/refman/5.7/en/charset-national.html
if lit == "N" || lit == "n" {
if s.r.peek() == '\'' {
tok = underscoreCS
lit = "utf8"
}
}
return
}
func startWithBb(s *Scanner) (tok int, pos Pos, lit string) {
pos = s.r.pos()
s.r.inc()
if s.r.peek() == '\'' {
s.r.inc()
s.scanBit()
if s.r.peek() == '\'' {
s.r.inc()
tok, lit = bitLit, s.r.data(&pos)
} else {
tok = unicode.ReplacementChar
}
return
}
s.r.incAsLongAs(isIdentChar)
tok, lit = identifier, s.r.data(&pos)
return
}
func startWithSharp(s *Scanner) (tok int, pos Pos, lit string) {
s.r.incAsLongAs(func(ch rune) bool {
return ch != '\n'
})
return s.scan()
}
func startWithDash(s *Scanner) (tok int, pos Pos, lit string) {
pos = s.r.pos()
if !strings.HasPrefix(s.r.s[pos.Offset:], "-- ") {
tok = int('-')
s.r.inc()
return
}
s.r.incN(3)
s.r.incAsLongAs(func(ch rune) bool {
return ch != '\n'
})
return s.scan()
}
func startWithSlash(s *Scanner) (tok int, pos Pos, lit string) {
pos = s.r.pos()
s.r.inc()
ch0 := s.r.peek()
if ch0 == '*' {
s.r.inc()
for {
ch0 = s.r.readByte()
if ch0 == unicode.ReplacementChar && s.r.eof() {
tok = unicode.ReplacementChar
return
}
if ch0 == '*' && s.r.readByte() == '/' {
break
}
}
comment := s.r.data(&pos)
// See https://dev.mysql.com/doc/refman/5.7/en/optimizer-hints.html
if strings.HasPrefix(comment, "/*+") {
begin := sqlOffsetInComment(comment)
end := len(comment) - 2
sql := comment[begin:end]
s.specialComment = &optimizerHintScanner{
Scanner: NewScanner(sql),
Pos: Pos{
pos.Line,
pos.Col,
pos.Offset + begin,
},
}
tok = hintBegin
return
}
// See http://dev.mysql.com/doc/refman/5.7/en/comments.html
// Convert "/*!VersionNumber MySQL-specific-code */" to "MySQL-specific-code".
if strings.HasPrefix(comment, "/*!") {
sql := specCodePattern.ReplaceAllStringFunc(comment, trimComment)
s.specialComment = &mysqlSpecificCodeScanner{
Scanner: NewScanner(sql),
Pos: Pos{
pos.Line,
pos.Col,
pos.Offset + sqlOffsetInComment(comment),
},
}
}
return s.scan()
}
tok = int('/')
return
}
func sqlOffsetInComment(comment string) int {
// find the first SQL token offset in pattern like "/*!40101 mysql specific code */"
offset := 0
for i := 0; i < len(comment); i++ {
if unicode.IsSpace(rune(comment[i])) {
offset = i
break
}
}
for offset < len(comment) {
offset++
if !unicode.IsSpace(rune(comment[offset])) {
break
}
}
return offset
}
func startWithAt(s *Scanner) (tok int, pos Pos, lit string) {
pos = s.r.pos()
s.r.inc()
ch1 := s.r.peek()
if isIdentFirstChar(ch1) {
s.r.incAsLongAs(isIdentChar)
tok, lit = userVar, s.r.data(&pos)
} else if ch1 == '@' {
s.r.inc()
stream := s.r.s[pos.Offset+2:]
for _, v := range []string{"global.", "session.", "local."} {
if len(v) > len(stream) {
continue
}
if strings.EqualFold(stream[:len(v)], v) {
s.r.incN(len(v))
break
}
}
s.r.incAsLongAs(isIdentChar)
tok, lit = sysVar, s.r.data(&pos)
} else {
tok = at
}
return
}
func scanIdentifier(s *Scanner) (int, Pos, string) {
pos := s.r.pos()
s.r.inc()
s.r.incAsLongAs(isIdentChar)
return identifier, pos, s.r.data(&pos)
}
var (
quotedIdentifier = -identifier
)
func scanQuotedIdent(s *Scanner) (tok int, pos Pos, lit string) {
pos = s.r.pos()
s.r.inc()
s.buf.Reset()
for {
ch := s.r.readByte()
if ch == unicode.ReplacementChar && s.r.eof() {
tok = unicode.ReplacementChar
return
}
if ch == '`' {
if s.r.peek() != '`' {
// don't return identifier in case that it's interpreted as keyword token later.
tok, lit = quotedIdentifier, s.buf.String()
return
}
s.r.inc()
}
s.buf.WriteRune(ch)
}
}
func startString(s *Scanner) (tok int, pos Pos, lit string) {
tok, pos, lit = s.scanString()
// Quoted strings placed next to each other are concatenated to a single string.
// See http://dev.mysql.com/doc/refman/5.7/en/string-literals.html
ch := s.skipWhitespace()
if s.sqlMode&mysql.ModeANSIQuotes > 0 &&
ch == '"' || s.r.s[pos.Offset] == '"' {
return
}
for ch == '\'' || ch == '"' {
_, _, lit1 := s.scanString()
lit = lit + lit1
ch = s.skipWhitespace()
}
return
}
// lazyBuf is used to avoid allocation if possible.
// it has a useBuf field indicates whether bytes.Buffer is necessary. if
// useBuf is false, we can avoid calling bytes.Buffer.String(), which
// make a copy of data and cause allocation.
type lazyBuf struct {
useBuf bool
r *reader
b *bytes.Buffer
p *Pos
}
func (mb *lazyBuf) setUseBuf(str string) {
if !mb.useBuf {
mb.useBuf = true
mb.b.Reset()
mb.b.WriteString(str)
}
}
func (mb *lazyBuf) writeRune(r rune, w int) {
if mb.useBuf {
if w > 1 {
mb.b.WriteRune(r)
} else {
mb.b.WriteByte(byte(r))
}
}
}
func (mb *lazyBuf) data() string {
var lit string
if mb.useBuf {
lit = mb.b.String()
} else {
lit = mb.r.data(mb.p)
lit = lit[1 : len(lit)-1]
}
return lit
}
func (s *Scanner) scanString() (tok int, pos Pos, lit string) {
tok, pos = stringLit, s.r.pos()
mb := lazyBuf{false, &s.r, &s.buf, &pos}
ending := s.r.readByte()
ch0 := s.r.peek()
for !s.r.eof() {
if ch0 == ending {
s.r.inc()
if s.r.peek() != ending {
lit = mb.data()
return
}
str := mb.r.data(&pos)
mb.setUseBuf(str[1 : len(str)-1])
} else if ch0 == '\\' {
mb.setUseBuf(mb.r.data(&pos)[1:])
ch0 = handleEscape(s)
}
mb.writeRune(ch0, s.r.w)
s.r.inc()
ch0 = s.r.peek()
}
tok = unicode.ReplacementChar
return
}
// handleEscape handles the case in scanString when previous char is '\'.
func handleEscape(s *Scanner) rune {
s.r.inc()
ch0 := s.r.peek()
/*
\" \' \\ \n \0 \b \Z \r \t ==> escape to one char
\% \_ ==> preserve both char
other ==> remove \
*/
switch ch0 {
case 'n':
ch0 = '\n'
case '0':
ch0 = 0
case 'b':
ch0 = 8
case 'Z':
ch0 = 26
case 'r':
ch0 = '\r'
case 't':
ch0 = '\t'
case '%', '_':
s.buf.WriteByte('\\')
}
return ch0
}
func startWithNumber(s *Scanner) (tok int, pos Pos, lit string) {
pos = s.r.pos()
tok = intLit
ch0 := s.r.readByte()
if ch0 == '0' {
tok = intLit
ch1 := s.r.peek()
switch {
case ch1 >= '0' && ch1 <= '7':
s.r.inc()
s.scanOct()
case ch1 == 'x' || ch1 == 'X':
s.r.inc()
s.scanHex()
tok = hexLit
case ch1 == 'b':
s.r.inc()
s.scanBit()
tok = bitLit
case ch1 == '.':
return s.scanFloat(&pos)
case ch1 == 'B':
tok = unicode.ReplacementChar
return
}
}
s.scanDigits()
ch0 = s.r.peek()
if ch0 == '.' || ch0 == 'e' || ch0 == 'E' {
return s.scanFloat(&pos)
}
// Identifiers may begin with a digit but unless quoted may not consist solely of digits.
if !s.r.eof() && isIdentChar(ch0) {
s.r.incAsLongAs(isIdentChar)
return identifier, pos, s.r.data(&pos)
}
lit = s.r.data(&pos)
return
}
func startWithDot(s *Scanner) (tok int, pos Pos, lit string) {
pos = s.r.pos()
s.r.inc()
save := s.r.pos()
if isDigit(s.r.peek()) {
tok, _, lit = s.scanFloat(&pos)
if s.r.eof() || unicode.IsSpace(s.r.peek()) {
return
}
// Fail to parse a float, reset to dot.
s.r.p = save
}
tok, lit = int('.'), "."
return
}
func (s *Scanner) scanOct() {
s.r.incAsLongAs(func(ch rune) bool {
return ch >= '0' && ch <= '7'
})
}
func (s *Scanner) scanHex() {
s.r.incAsLongAs(func(ch rune) bool {
return ch >= '0' && ch <= '9' ||
ch >= 'a' && ch <= 'f' ||
ch >= 'A' && ch <= 'F'
})
}
func (s *Scanner) scanBit() {
s.r.incAsLongAs(func(ch rune) bool {
return ch == '0' || ch == '1'
})
}
func (s *Scanner) scanFloat(beg *Pos) (tok int, pos Pos, lit string) {
s.r.p = *beg
// float = D1 . D2 e D3
s.scanDigits()
ch0 := s.r.peek()
if ch0 == '.' {
s.r.inc()
s.scanDigits()
ch0 = s.r.peek()
}
if ch0 == 'e' || ch0 == 'E' {
s.r.inc()
ch0 = s.r.peek()
if ch0 == '-' || ch0 == '+' {
s.r.inc()
}
s.scanDigits()
tok = floatLit
} else {
tok = decLit
}
pos, lit = *beg, s.r.data(beg)
return
}
func (s *Scanner) scanDigits() string {
pos := s.r.pos()
s.r.incAsLongAs(isDigit)
return s.r.data(&pos)
}
type reader struct {
s string
p Pos
w int
}
var eof = Pos{-1, -1, -1}
func (r *reader) eof() bool {
return r.p.Offset >= len(r.s)
}
// peek() peeks a rune from underlying reader.
// if reader meets EOF, it will return unicode.ReplacementChar. to distinguish from
// the real unicode.ReplacementChar, the caller should call r.eof() again to check.
func (r *reader) peek() rune {
if r.eof() {
return unicode.ReplacementChar
}
v, w := rune(r.s[r.p.Offset]), 1
switch {
case v == 0:
r.w = w
return v // illegal UTF-8 encoding
case v >= 0x80:
v, w = utf8.DecodeRuneInString(r.s[r.p.Offset:])
if v == utf8.RuneError && w == 1 {
v = rune(r.s[r.p.Offset]) // illegal UTF-8 encoding
}
}
r.w = w
return v
}
// inc increase the position offset of the reader.
// peek must be called before calling inc!
func (r *reader) inc() {
if r.s[r.p.Offset] == '\n' {
r.p.Line++
r.p.Col = 0
}
r.p.Offset += r.w
r.p.Col++
}
func (r *reader) incN(n int) {
for i := 0; i < n; i++ {
r.inc()
}
}
func (r *reader) readByte() (ch rune) {
ch = r.peek()
if ch == unicode.ReplacementChar && r.eof() {
return
}
r.inc()
return
}
func (r *reader) pos() Pos {
return r.p
}
func (r *reader) data(from *Pos) string {
return r.s[from.Offset:r.p.Offset]
}
func (r *reader) incAsLongAs(fn func(rune) bool) rune {
for {
ch := r.peek()
if !fn(ch) {
return ch
}
if ch == unicode.ReplacementChar && r.eof() {
return 0
}
r.inc()
}
}
| apache-2.0 |
mblomdahl/cron | test/fixtures/cookbooks/cron_test/recipes/default.rb | 1593 | #
# Cookbook Name:: cron_test
# Recipe:: test
#
# Copyright:: (c) 2008-2014, Chef Software, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
include_recipe 'cron'
cron_d 'bizarrely-scheduled-usage-report' do
minute '*/5'
hour '1,23'
day '2-5'
command '/srv/app/scripts/generate_report'
user 'appuser'
action :create
end
cron_d 'test-month-usage-report' do
minute '0'
hour '6'
month '1'
command '/srv/app/scripts/generate_report'
user 'appuser'
action :create
end
cron_d 'test-weekday-usage-report' do
minute '45'
hour '13'
weekday '7'
command '/srv/app/scripts/generate_report'
user 'appuser'
action :create
end
cron_d 'fixnum-job' do
minute 0
hour 1
day 2
command '/bin/true'
user 'appuser'
action :create
end
cron_d 'predefined_value_check' do
predefined_value '@midnight'
command '/bin/true'
user 'appuser'
action :create
end
cron_d 'nil_value_check' do
predefined_value nil
command '/bin/true'
user 'appuser'
action :create
end
cron_d 'no_value_check' do
command '/bin/true'
user 'appuser'
action :create
end
| apache-2.0 |
lixueclaire/website | pkg/cmd/admin/policy/modify_roles.go | 12094 | package policy
import (
"errors"
"fmt"
"io"
"github.com/spf13/cobra"
kapi "k8s.io/kubernetes/pkg/api"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
authorizationapi "github.com/openshift/origin/pkg/authorization/api"
"github.com/openshift/origin/pkg/cmd/util/clientcmd"
uservalidation "github.com/openshift/origin/pkg/user/api/validation"
)
const (
AddRoleToGroupRecommendedName = "add-role-to-group"
AddRoleToUserRecommendedName = "add-role-to-user"
RemoveRoleFromGroupRecommendedName = "remove-role-from-group"
RemoveRoleFromUserRecommendedName = "remove-role-from-user"
AddClusterRoleToGroupRecommendedName = "add-cluster-role-to-group"
AddClusterRoleToUserRecommendedName = "add-cluster-role-to-user"
RemoveClusterRoleFromGroupRecommendedName = "remove-cluster-role-from-group"
RemoveClusterRoleFromUserRecommendedName = "remove-cluster-role-from-user"
)
type RoleModificationOptions struct {
RoleNamespace string
RoleName string
RoleBindingAccessor RoleBindingAccessor
Users []string
Groups []string
Subjects []kapi.ObjectReference
}
// NewCmdAddRoleToGroup implements the OpenShift cli add-role-to-group command
func NewCmdAddRoleToGroup(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
options := &RoleModificationOptions{}
cmd := &cobra.Command{
Use: name + " ROLE GROUP [GROUP ...]",
Short: "Add groups to a role in the current project",
Long: `Add groups to a role in the current project`,
Run: func(cmd *cobra.Command, args []string) {
if err := options.Complete(f, args, &options.Groups, "group", true); err != nil {
kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
}
if err := options.AddRole(); err != nil {
kcmdutil.CheckErr(err)
}
},
}
cmd.Flags().StringVar(&options.RoleNamespace, "role-namespace", "", "namespace where the role is located: empty means a role defined in cluster policy")
return cmd
}
// NewCmdAddRoleToUser implements the OpenShift cli add-role-to-user command
func NewCmdAddRoleToUser(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
options := &RoleModificationOptions{}
saNames := []string{}
cmd := &cobra.Command{
Use: name + " ROLE USER [USER ...]",
Short: "Add users to a role in the current project",
Long: `Add users to a role in the current project`,
Run: func(cmd *cobra.Command, args []string) {
if err := options.CompleteUserWithSA(f, args, saNames); err != nil {
kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
}
if err := options.AddRole(); err != nil {
kcmdutil.CheckErr(err)
}
},
}
cmd.Flags().StringVar(&options.RoleNamespace, "role-namespace", "", "namespace where the role is located: empty means a role defined in cluster policy")
cmd.Flags().StringSliceVarP(&saNames, "serviceaccount", "z", saNames, "service account in the current namespace to use as a user")
return cmd
}
// NewCmdRemoveRoleFromGroup implements the OpenShift cli remove-role-from-group command
func NewCmdRemoveRoleFromGroup(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
options := &RoleModificationOptions{}
cmd := &cobra.Command{
Use: name + " ROLE GROUP [GROUP ...]",
Short: "Remove group from role in the current project",
Long: `Remove group from role in the current project`,
Run: func(cmd *cobra.Command, args []string) {
if err := options.Complete(f, args, &options.Groups, "group", true); err != nil {
kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
}
if err := options.RemoveRole(); err != nil {
kcmdutil.CheckErr(err)
}
},
}
cmd.Flags().StringVar(&options.RoleNamespace, "role-namespace", "", "namespace where the role is located: empty means a role defined in cluster policy")
return cmd
}
// NewCmdRemoveRoleFromUser implements the OpenShift cli remove-role-from-user command
func NewCmdRemoveRoleFromUser(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
options := &RoleModificationOptions{}
saNames := []string{}
cmd := &cobra.Command{
Use: name + " ROLE USER [USER ...]",
Short: "Remove user from role in the current project",
Long: `Remove user from role in the current project`,
Run: func(cmd *cobra.Command, args []string) {
if err := options.CompleteUserWithSA(f, args, saNames); err != nil {
kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
}
if err := options.RemoveRole(); err != nil {
kcmdutil.CheckErr(err)
}
},
}
cmd.Flags().StringVar(&options.RoleNamespace, "role-namespace", "", "namespace where the role is located: empty means a role defined in cluster policy")
cmd.Flags().StringSliceVarP(&saNames, "serviceaccount", "z", saNames, "service account in the current namespace to use as a user")
return cmd
}
// NewCmdAddClusterRoleToGroup implements the OpenShift cli add-cluster-role-to-group command
func NewCmdAddClusterRoleToGroup(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
options := &RoleModificationOptions{}
cmd := &cobra.Command{
Use: name + " <role> <group> [group]...",
Short: "Add groups to a role for all projects in the cluster",
Long: `Add groups to a role for all projects in the cluster`,
Run: func(cmd *cobra.Command, args []string) {
if err := options.Complete(f, args, &options.Groups, "group", false); err != nil {
kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
}
if err := options.AddRole(); err != nil {
kcmdutil.CheckErr(err)
}
},
}
return cmd
}
// NewCmdAddClusterRoleToUser implements the OpenShift cli add-cluster-role-to-user command
func NewCmdAddClusterRoleToUser(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
options := &RoleModificationOptions{}
cmd := &cobra.Command{
Use: name + " <role> <user> [user]...",
Short: "Add users to a role for all projects in the cluster",
Long: `Add users to a role for all projects in the cluster`,
Run: func(cmd *cobra.Command, args []string) {
if err := options.Complete(f, args, &options.Users, "user", false); err != nil {
kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
}
if err := options.AddRole(); err != nil {
kcmdutil.CheckErr(err)
}
},
}
return cmd
}
// NewCmdRemoveClusterRoleFromGroup implements the OpenShift cli remove-cluster-role-from-group command
func NewCmdRemoveClusterRoleFromGroup(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
options := &RoleModificationOptions{}
cmd := &cobra.Command{
Use: name + " <role> <group> [group]...",
Short: "Remove group from role for all projects in the cluster",
Long: `Remove group from role for all projects in the cluster`,
Run: func(cmd *cobra.Command, args []string) {
if err := options.Complete(f, args, &options.Groups, "group", false); err != nil {
kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
}
if err := options.RemoveRole(); err != nil {
kcmdutil.CheckErr(err)
}
},
}
return cmd
}
// NewCmdRemoveClusterRoleFromUser implements the OpenShift cli remove-cluster-role-from-user command
func NewCmdRemoveClusterRoleFromUser(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
options := &RoleModificationOptions{}
cmd := &cobra.Command{
Use: name + " <role> <user> [user]...",
Short: "Remove user from role for all projects in the cluster",
Long: `Remove user from role for all projects in the cluster`,
Run: func(cmd *cobra.Command, args []string) {
if err := options.Complete(f, args, &options.Users, "user", false); err != nil {
kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
}
if err := options.RemoveRole(); err != nil {
kcmdutil.CheckErr(err)
}
},
}
return cmd
}
func (o *RoleModificationOptions) CompleteUserWithSA(f *clientcmd.Factory, args []string, saNames []string) error {
if (len(args) < 2) && (len(saNames) == 0) {
return errors.New("you must specify at least two arguments: <role> <user> [user]...")
}
o.RoleName = args[0]
if len(args) > 1 {
o.Users = append(o.Users, args[1:]...)
}
osClient, _, err := f.Clients()
if err != nil {
return err
}
roleBindingNamespace, _, err := f.DefaultNamespace()
if err != nil {
return err
}
o.RoleBindingAccessor = NewLocalRoleBindingAccessor(roleBindingNamespace, osClient)
for _, sa := range saNames {
o.Subjects = append(o.Subjects, kapi.ObjectReference{Namespace: roleBindingNamespace, Name: sa, Kind: "ServiceAccount"})
}
return nil
}
func (o *RoleModificationOptions) Complete(f *clientcmd.Factory, args []string, target *[]string, targetName string, isNamespaced bool) error {
if len(args) < 2 {
return fmt.Errorf("you must specify at least two arguments: <role> <%s> [%s]...", targetName, targetName)
}
o.RoleName = args[0]
*target = append(*target, args[1:]...)
osClient, _, err := f.Clients()
if err != nil {
return err
}
if isNamespaced {
roleBindingNamespace, _, err := f.DefaultNamespace()
if err != nil {
return err
}
o.RoleBindingAccessor = NewLocalRoleBindingAccessor(roleBindingNamespace, osClient)
} else {
o.RoleBindingAccessor = NewClusterRoleBindingAccessor(osClient)
}
return nil
}
func (o *RoleModificationOptions) AddRole() error {
roleBindings, err := o.RoleBindingAccessor.GetExistingRoleBindingsForRole(o.RoleNamespace, o.RoleName)
if err != nil {
return err
}
roleBindingNames, err := o.RoleBindingAccessor.GetExistingRoleBindingNames()
if err != nil {
return err
}
var roleBinding *authorizationapi.RoleBinding
isUpdate := true
if len(roleBindings) == 0 {
roleBinding = &authorizationapi.RoleBinding{}
isUpdate = false
} else {
// only need to add the user or group to a single roleBinding on the role. Just choose the first one
roleBinding = roleBindings[0]
}
roleBinding.RoleRef.Namespace = o.RoleNamespace
roleBinding.RoleRef.Name = o.RoleName
newSubjects := authorizationapi.BuildSubjects(o.Users, o.Groups, uservalidation.ValidateUserName, uservalidation.ValidateGroupName)
newSubjects = append(newSubjects, o.Subjects...)
subjectCheck:
for _, newSubject := range newSubjects {
for _, existingSubject := range roleBinding.Subjects {
if existingSubject.Kind == newSubject.Kind &&
existingSubject.Name == newSubject.Name &&
existingSubject.Namespace == newSubject.Namespace {
continue subjectCheck
}
}
roleBinding.Subjects = append(roleBinding.Subjects, newSubject)
}
if isUpdate {
err = o.RoleBindingAccessor.UpdateRoleBinding(roleBinding)
} else {
roleBinding.Name = getUniqueName(o.RoleName, roleBindingNames)
err = o.RoleBindingAccessor.CreateRoleBinding(roleBinding)
}
if err != nil {
return err
}
return nil
}
func (o *RoleModificationOptions) RemoveRole() error {
roleBindings, err := o.RoleBindingAccessor.GetExistingRoleBindingsForRole(o.RoleNamespace, o.RoleName)
if err != nil {
return err
}
if len(roleBindings) == 0 {
return fmt.Errorf("unable to locate RoleBinding for %v/%v", o.RoleNamespace, o.RoleName)
}
subjectsToRemove := authorizationapi.BuildSubjects(o.Users, o.Groups, uservalidation.ValidateUserName, uservalidation.ValidateGroupName)
subjectsToRemove = append(subjectsToRemove, o.Subjects...)
for _, roleBinding := range roleBindings {
roleBinding.Subjects = removeSubjects(roleBinding.Subjects, subjectsToRemove)
err = o.RoleBindingAccessor.UpdateRoleBinding(roleBinding)
if err != nil {
return err
}
}
return nil
}
func removeSubjects(haystack, needles []kapi.ObjectReference) []kapi.ObjectReference {
newSubjects := []kapi.ObjectReference{}
existingLoop:
for _, existingSubject := range haystack {
for _, toRemove := range needles {
if existingSubject.Kind == toRemove.Kind &&
existingSubject.Name == toRemove.Name &&
existingSubject.Namespace == toRemove.Namespace {
continue existingLoop
}
}
newSubjects = append(newSubjects, existingSubject)
}
return newSubjects
}
| apache-2.0 |
abaditsegay/arangodb | 3rdParty/V8-4.3.61/src/weak-collection.js | 4842 | // Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
"use strict";
// This file relies on the fact that the following declaration has been made
// in runtime.js:
// var $Array = global.Array;
var $WeakMap = global.WeakMap;
var $WeakSet = global.WeakSet;
// -------------------------------------------------------------------
// Harmony WeakMap
function WeakMapConstructor(iterable) {
if (!%_IsConstructCall()) {
throw MakeTypeError('constructor_not_function', ['WeakMap']);
}
%WeakCollectionInitialize(this);
if (!IS_NULL_OR_UNDEFINED(iterable)) {
var adder = this.set;
if (!IS_SPEC_FUNCTION(adder)) {
throw MakeTypeError('property_not_function', ['set', this]);
}
for (var nextItem of iterable) {
if (!IS_SPEC_OBJECT(nextItem)) {
throw MakeTypeError('iterator_value_not_an_object', [nextItem]);
}
%_CallFunction(this, nextItem[0], nextItem[1], adder);
}
}
}
function WeakMapGet(key) {
if (!IS_WEAKMAP(this)) {
throw MakeTypeError('incompatible_method_receiver',
['WeakMap.prototype.get', this]);
}
if (!IS_SPEC_OBJECT(key)) return UNDEFINED;
return %WeakCollectionGet(this, key);
}
function WeakMapSet(key, value) {
if (!IS_WEAKMAP(this)) {
throw MakeTypeError('incompatible_method_receiver',
['WeakMap.prototype.set', this]);
}
if (!IS_SPEC_OBJECT(key)) {
throw %MakeTypeError('invalid_weakmap_key', [this, key]);
}
return %WeakCollectionSet(this, key, value);
}
function WeakMapHas(key) {
if (!IS_WEAKMAP(this)) {
throw MakeTypeError('incompatible_method_receiver',
['WeakMap.prototype.has', this]);
}
if (!IS_SPEC_OBJECT(key)) return false;
return %WeakCollectionHas(this, key);
}
function WeakMapDelete(key) {
if (!IS_WEAKMAP(this)) {
throw MakeTypeError('incompatible_method_receiver',
['WeakMap.prototype.delete', this]);
}
if (!IS_SPEC_OBJECT(key)) return false;
return %WeakCollectionDelete(this, key);
}
// -------------------------------------------------------------------
function SetUpWeakMap() {
%CheckIsBootstrapping();
%SetCode($WeakMap, WeakMapConstructor);
%FunctionSetPrototype($WeakMap, new $Object());
%AddNamedProperty($WeakMap.prototype, "constructor", $WeakMap, DONT_ENUM);
%AddNamedProperty(
$WeakMap.prototype, symbolToStringTag, "WeakMap", DONT_ENUM | READ_ONLY);
// Set up the non-enumerable functions on the WeakMap prototype object.
InstallFunctions($WeakMap.prototype, DONT_ENUM, $Array(
"get", WeakMapGet,
"set", WeakMapSet,
"has", WeakMapHas,
"delete", WeakMapDelete
));
}
SetUpWeakMap();
// -------------------------------------------------------------------
// Harmony WeakSet
function WeakSetConstructor(iterable) {
if (!%_IsConstructCall()) {
throw MakeTypeError('constructor_not_function', ['WeakSet']);
}
%WeakCollectionInitialize(this);
if (!IS_NULL_OR_UNDEFINED(iterable)) {
var adder = this.add;
if (!IS_SPEC_FUNCTION(adder)) {
throw MakeTypeError('property_not_function', ['add', this]);
}
for (var value of iterable) {
%_CallFunction(this, value, adder);
}
}
}
function WeakSetAdd(value) {
if (!IS_WEAKSET(this)) {
throw MakeTypeError('incompatible_method_receiver',
['WeakSet.prototype.add', this]);
}
if (!IS_SPEC_OBJECT(value)) {
throw %MakeTypeError('invalid_weakset_value', [this, value]);
}
return %WeakCollectionSet(this, value, true);
}
function WeakSetHas(value) {
if (!IS_WEAKSET(this)) {
throw MakeTypeError('incompatible_method_receiver',
['WeakSet.prototype.has', this]);
}
if (!IS_SPEC_OBJECT(value)) return false;
return %WeakCollectionHas(this, value);
}
function WeakSetDelete(value) {
if (!IS_WEAKSET(this)) {
throw MakeTypeError('incompatible_method_receiver',
['WeakSet.prototype.delete', this]);
}
if (!IS_SPEC_OBJECT(value)) return false;
return %WeakCollectionDelete(this, value);
}
// -------------------------------------------------------------------
function SetUpWeakSet() {
%CheckIsBootstrapping();
%SetCode($WeakSet, WeakSetConstructor);
%FunctionSetPrototype($WeakSet, new $Object());
%AddNamedProperty($WeakSet.prototype, "constructor", $WeakSet, DONT_ENUM);
%AddNamedProperty(
$WeakSet.prototype, symbolToStringTag, "WeakSet", DONT_ENUM | READ_ONLY);
// Set up the non-enumerable functions on the WeakSet prototype object.
InstallFunctions($WeakSet.prototype, DONT_ENUM, $Array(
"add", WeakSetAdd,
"has", WeakSetHas,
"delete", WeakSetDelete
));
}
SetUpWeakSet();
| apache-2.0 |
peterfraedrich/platoon | node_modules/exec-sync/node_modules/ffi/test/objc.js | 1588 |
var expect = require('expect.js')
, ref = require('ref')
, ffi = require('../')
, voidPtr = ref.refType(ref.types.void)
// these are "opaque" pointer types, so we only care about the memory addess,
// and not the contents (which are internal to Apple). Therefore we can typedef
// these opaque types to `void *` and it's essentially the same thing.
var id = voidPtr
, SEL = voidPtr
, Class = voidPtr
if (ffi.HAS_OBJC) {
describe('@try / @catch', function () {
afterEach(gc)
var objcLib = new ffi.Library('libobjc', {
'objc_msgSend': [ id, [ id, SEL ] ]
, 'objc_getClass': [ Class, [ 'string' ] ]
, 'sel_registerName': [ SEL, [ 'string' ] ]
})
// create an NSAutoreleasePool instance
var NSAutoreleasePool = objcLib.objc_getClass('NSAutoreleasePool')
, sel_new = objcLib.sel_registerName('new')
, pool = objcLib.objc_msgSend(NSAutoreleasePool, sel_new)
it('should proxy @try/@catch to JavaScript via try/catch/throw', function () {
var sel_retain = objcLib.sel_registerName('retain')
expect(function () {
objcLib.objc_msgSend(pool, sel_retain)
}).to.throwException()
})
it('should throw a Buffer instance when an exception happens', function () {
var sel_retain = objcLib.sel_registerName('retain')
try {
objcLib.objc_msgSend(pool, sel_retain)
expect(false).to.be(true)
} catch (e) {
expect(Buffer.isBuffer(e)).to.be(true)
expect(e.isNull()).to.be(false)
expect(e.address()).to.be.greaterThan(0)
}
})
})
}
| apache-2.0 |
ninqing/tddl | tddl-parser/src/main/java/com/alibaba/cobar/parser/ast/expression/primary/function/string/Concat.java | 1240 | /*
* Copyright 1999-2012 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* (created at 2011-1-23)
*/
package com.alibaba.cobar.parser.ast.expression.primary.function.string;
import java.util.List;
import com.alibaba.cobar.parser.ast.expression.Expression;
import com.alibaba.cobar.parser.ast.expression.primary.function.FunctionExpression;
/**
* @author <a href="mailto:shuo.qius@alibaba-inc.com">QIU Shuo</a>
*/
public class Concat extends FunctionExpression {
public Concat(List<Expression> arguments){
super("CONCAT", arguments);
}
@Override
public FunctionExpression constructFunction(List<Expression> arguments) {
return new Concat(arguments);
}
}
| apache-2.0 |
kidaa/incubator-ignite | modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/counter/HadoopPerformanceCounter.java | 8206 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.hadoop.counter;
import org.apache.ignite.internal.processors.hadoop.*;
import org.apache.ignite.internal.util.typedef.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.jetbrains.annotations.*;
import java.io.*;
import java.util.*;
import static org.apache.ignite.internal.processors.hadoop.HadoopUtils.*;
/**
* Counter for the job statistics accumulation.
*/
public class HadoopPerformanceCounter extends HadoopCounterAdapter {
/** */
private static final long serialVersionUID = 0L;
/** The group name for this counter. */
private static final String GROUP_NAME = "SYSTEM";
/** The counter name for this counter. */
private static final String COUNTER_NAME = "PERFORMANCE";
/** Events collections. */
private Collection<T2<String,Long>> evts = new ArrayList<>();
/** Node id to insert into the event info. */
private UUID nodeId;
/** */
private int reducerNum;
/** */
private volatile Long firstShuffleMsg;
/** */
private volatile Long lastShuffleMsg;
/**
* Default constructor required by {@link Externalizable}.
*/
public HadoopPerformanceCounter() {
// No-op.
}
/**
* Constructor.
*
* @param grp Group name.
* @param name Counter name.
*/
public HadoopPerformanceCounter(String grp, String name) {
super(grp, name);
}
/**
* Constructor to create instance to use this as helper.
*
* @param nodeId Id of the work node.
*/
public HadoopPerformanceCounter(UUID nodeId) {
this.nodeId = nodeId;
}
/** {@inheritDoc} */
@Override protected void writeValue(ObjectOutput out) throws IOException {
U.writeCollection(out, evts);
}
/** {@inheritDoc} */
@Override protected void readValue(ObjectInput in) throws IOException {
try {
evts = U.readCollection(in);
}
catch (ClassNotFoundException e) {
throw new IOException(e);
}
}
/** {@inheritDoc} */
@Override public void merge(HadoopCounter cntr) {
evts.addAll(((HadoopPerformanceCounter)cntr).evts);
}
/**
* Gets the events collection.
*
* @return Collection of event.
*/
public Collection<T2<String, Long>> evts() {
return evts;
}
/**
* Generate name that consists of some event information.
*
* @param info Task info.
* @param evtType The type of the event.
* @return String contains necessary event information.
*/
private String eventName(HadoopTaskInfo info, String evtType) {
return eventName(info.type().toString(), info.taskNumber(), evtType);
}
/**
* Generate name that consists of some event information.
*
* @param taskType Task type.
* @param taskNum Number of the task.
* @param evtType The type of the event.
* @return String contains necessary event information.
*/
private String eventName(String taskType, int taskNum, String evtType) {
assert nodeId != null;
return taskType + " " + taskNum + " " + evtType + " " + nodeId;
}
/**
* Adds event of the task submission (task instance creation).
*
* @param info Task info.
* @param ts Timestamp of the event.
*/
public void onTaskSubmit(HadoopTaskInfo info, long ts) {
evts.add(new T2<>(eventName(info, "submit"), ts));
}
/**
* Adds event of the task preparation.
*
* @param info Task info.
* @param ts Timestamp of the event.
*/
public void onTaskPrepare(HadoopTaskInfo info, long ts) {
evts.add(new T2<>(eventName(info, "prepare"), ts));
}
/**
* Adds event of the task finish.
*
* @param info Task info.
* @param ts Timestamp of the event.
*/
public void onTaskFinish(HadoopTaskInfo info, long ts) {
if (info.type() == HadoopTaskType.REDUCE && lastShuffleMsg != null) {
evts.add(new T2<>(eventName("SHUFFLE", reducerNum, "start"), firstShuffleMsg));
evts.add(new T2<>(eventName("SHUFFLE", reducerNum, "finish"), lastShuffleMsg));
lastShuffleMsg = null;
}
evts.add(new T2<>(eventName(info, "finish"), ts));
}
/**
* Adds event of the task run.
*
* @param info Task info.
* @param ts Timestamp of the event.
*/
public void onTaskStart(HadoopTaskInfo info, long ts) {
evts.add(new T2<>(eventName(info, "start"), ts));
}
/**
* Adds event of the job preparation.
*
* @param ts Timestamp of the event.
*/
public void onJobPrepare(long ts) {
assert nodeId != null;
evts.add(new T2<>("JOB prepare " + nodeId, ts));
}
/**
* Adds event of the job start.
*
* @param ts Timestamp of the event.
*/
public void onJobStart(long ts) {
assert nodeId != null;
evts.add(new T2<>("JOB start " + nodeId, ts));
}
/**
* Adds client submission events from job info.
*
* @param info Job info.
*/
public void clientSubmissionEvents(HadoopJobInfo info) {
assert nodeId != null;
addEventFromProperty("JOB requestId", info, REQ_NEW_JOBID_TS_PROPERTY);
addEventFromProperty("JOB responseId", info, RESPONSE_NEW_JOBID_TS_PROPERTY);
addEventFromProperty("JOB submit", info, JOB_SUBMISSION_START_TS_PROPERTY);
}
/**
* Adds event with timestamp from some property in job info.
*
* @param evt Event type and phase.
* @param info Job info.
* @param propName Property name to get timestamp.
*/
private void addEventFromProperty(String evt, HadoopJobInfo info, String propName) {
String val = info.property(propName);
if (!F.isEmpty(val)) {
try {
evts.add(new T2<>(evt + " " + nodeId, Long.parseLong(val)));
}
catch (NumberFormatException e) {
throw new IllegalStateException("Invalid value '" + val + "' of property '" + propName + "'", e);
}
}
}
/**
* Registers shuffle message event.
*
* @param reducerNum Number of reducer that receives the data.
* @param ts Timestamp of the event.
*/
public void onShuffleMessage(int reducerNum, long ts) {
this.reducerNum = reducerNum;
if (firstShuffleMsg == null)
firstShuffleMsg = ts;
lastShuffleMsg = ts;
}
/**
* Gets system predefined performance counter from the HadoopCounters object.
*
* @param cntrs HadoopCounters object.
* @param nodeId Node id for methods that adds events. It may be null if you don't use ones.
* @return Predefined performance counter.
*/
public static HadoopPerformanceCounter getCounter(HadoopCounters cntrs, @Nullable UUID nodeId) {
HadoopPerformanceCounter cntr = cntrs.counter(GROUP_NAME, COUNTER_NAME, HadoopPerformanceCounter.class);
if (nodeId != null)
cntr.nodeId(nodeId);
return cntrs.counter(GROUP_NAME, COUNTER_NAME, HadoopPerformanceCounter.class);
}
/**
* Sets the nodeId field.
*
* @param nodeId Node id.
*/
private void nodeId(UUID nodeId) {
this.nodeId = nodeId;
}
}
| apache-2.0 |
anindoasaha/php_nginx | php-5.5.16/ext/ctype/tests/001.phpt | 788 | --TEST--
ctype on integers
--SKIPIF--
<?php require_once('skipif.inc'); ?>
--FILE--
<?php
setlocale(LC_ALL,"C");
function ctype_test_001($function) {
$n=0;
for($a=0;$a<256;$a++) {
if($function($a)) $n++;
}
echo "$function $n\n";
}
ctype_test_001("ctype_lower");
ctype_test_001("ctype_upper");
ctype_test_001("ctype_alpha");
ctype_test_001("ctype_digit");
ctype_test_001("ctype_alnum");
ctype_test_001("ctype_cntrl");
ctype_test_001("ctype_graph");
ctype_test_001("ctype_print");
ctype_test_001("ctype_punct");
ctype_test_001("ctype_space");
ctype_test_001("ctype_xdigit");
?>
--EXPECT--
ctype_lower 26
ctype_upper 26
ctype_alpha 52
ctype_digit 10
ctype_alnum 62
ctype_cntrl 33
ctype_graph 94
ctype_print 95
ctype_punct 32
ctype_space 6
ctype_xdigit 22
| apache-2.0 |
RedAlliances/RedminePM2 | db/migrate/20131004113137_support_for_multiple_commit_keywords.rb | 832 | class SupportForMultipleCommitKeywords < ActiveRecord::Migration
def up
# Replaces commit_fix_keywords, commit_fix_status_id, commit_fix_done_ratio settings
# with commit_update_keywords setting
keywords = Setting.where(:name => 'commit_fix_keywords').limit(1).pluck(:value).first
status_id = Setting.where(:name => 'commit_fix_status_id').limit(1).pluck(:value).first
done_ratio = Setting.where(:name => 'commit_fix_done_ratio').limit(1).pluck(:value).first
if keywords.present?
Setting.commit_update_keywords = [{'keywords' => keywords, 'status_id' => status_id, 'done_ratio' => done_ratio}]
end
Setting.where(:name => %w(commit_fix_keywords commit_fix_status_id commit_fix_done_ratio)).delete_all
end
def down
Setting.where(:name => 'commit_update_keywords').delete_all
end
end
| apache-2.0 |
DCSaunders/tensorflow | tensorflow/contrib/distributions/python/kernel_tests/inverse_gamma_test.py | 13564 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy import stats
import tensorflow as tf
class InverseGammaTest(tf.test.TestCase):
def testInverseGammaShape(self):
with self.test_session():
alpha = tf.constant([3.0] * 5)
beta = tf.constant(11.0)
inv_gamma = tf.contrib.distributions.InverseGamma(alpha=alpha, beta=beta)
self.assertEqual(inv_gamma.batch_shape().eval(), (5,))
self.assertEqual(inv_gamma.get_batch_shape(), tf.TensorShape([5]))
self.assertAllEqual(inv_gamma.event_shape().eval(), [])
self.assertEqual(inv_gamma.get_event_shape(), tf.TensorShape([]))
def testInverseGammaLogPDF(self):
with self.test_session():
batch_size = 6
alpha = tf.constant([2.0] * batch_size)
beta = tf.constant([3.0] * batch_size)
alpha_v = 2.0
beta_v = 3.0
x = np.array([2.5, 2.5, 4.0, 0.1, 1.0, 2.0], dtype=np.float32)
inv_gamma = tf.contrib.distributions.InverseGamma(alpha=alpha, beta=beta)
expected_log_pdf = stats.invgamma.logpdf(x, alpha_v, scale=beta_v)
log_pdf = inv_gamma.log_pdf(x)
self.assertEqual(log_pdf.get_shape(), (6,))
self.assertAllClose(log_pdf.eval(), expected_log_pdf)
pdf = inv_gamma.pdf(x)
self.assertEqual(pdf.get_shape(), (6,))
self.assertAllClose(pdf.eval(), np.exp(expected_log_pdf))
def testInverseGammaLogPDFMultidimensional(self):
with self.test_session():
batch_size = 6
alpha = tf.constant([[2.0, 4.0]] * batch_size)
beta = tf.constant([[3.0, 4.0]] * batch_size)
alpha_v = np.array([2.0, 4.0])
beta_v = np.array([3.0, 4.0])
x = np.array([[2.5, 2.5, 4.0, 0.1, 1.0, 2.0]], dtype=np.float32).T
inv_gamma = tf.contrib.distributions.InverseGamma(alpha=alpha, beta=beta)
expected_log_pdf = stats.invgamma.logpdf(x, alpha_v, scale=beta_v)
log_pdf = inv_gamma.log_pdf(x)
log_pdf_values = log_pdf.eval()
self.assertEqual(log_pdf.get_shape(), (6, 2))
self.assertAllClose(log_pdf_values, expected_log_pdf)
pdf = inv_gamma.pdf(x)
pdf_values = pdf.eval()
self.assertEqual(pdf.get_shape(), (6, 2))
self.assertAllClose(pdf_values, np.exp(expected_log_pdf))
def testInverseGammaLogPDFMultidimensionalBroadcasting(self):
with self.test_session():
batch_size = 6
alpha = tf.constant([[2.0, 4.0]] * batch_size)
beta = tf.constant(3.0)
alpha_v = np.array([2.0, 4.0])
beta_v = 3.0
x = np.array([[2.5, 2.5, 4.0, 0.1, 1.0, 2.0]], dtype=np.float32).T
inv_gamma = tf.contrib.distributions.InverseGamma(alpha=alpha, beta=beta)
expected_log_pdf = stats.invgamma.logpdf(x, alpha_v, scale=beta_v)
log_pdf = inv_gamma.log_pdf(x)
log_pdf_values = log_pdf.eval()
self.assertEqual(log_pdf.get_shape(), (6, 2))
self.assertAllClose(log_pdf_values, expected_log_pdf)
pdf = inv_gamma.pdf(x)
pdf_values = pdf.eval()
self.assertEqual(pdf.get_shape(), (6, 2))
self.assertAllClose(pdf_values, np.exp(expected_log_pdf))
def testInverseGammaCDF(self):
with self.test_session():
batch_size = 6
alpha_v = 2.0
beta_v = 3.0
alpha = tf.constant([alpha_v] * batch_size)
beta = tf.constant([beta_v] * batch_size)
x = np.array([2.5, 2.5, 4.0, 0.1, 1.0, 2.0], dtype=np.float32)
inv_gamma = tf.contrib.distributions.InverseGamma(alpha=alpha, beta=beta)
expected_cdf = stats.invgamma.cdf(x, alpha_v, scale=beta_v)
cdf = inv_gamma.cdf(x)
self.assertEqual(cdf.get_shape(), (batch_size,))
self.assertAllClose(cdf.eval(), expected_cdf)
def testInverseGammaMode(self):
with self.test_session():
alpha_v = np.array([5.5, 3.0, 2.5])
beta_v = np.array([1.0, 4.0, 5.0])
inv_gamma = tf.contrib.distributions.InverseGamma(alpha=alpha_v,
beta=beta_v)
expected_modes = beta_v / (alpha_v + 1)
self.assertEqual(inv_gamma.mode().get_shape(), (3,))
self.assertAllClose(inv_gamma.mode().eval(), expected_modes)
def testInverseGammaMeanAllDefined(self):
with self.test_session():
alpha_v = np.array([5.5, 3.0, 2.5])
beta_v = np.array([1.0, 4.0, 5.0])
inv_gamma = tf.contrib.distributions.InverseGamma(
alpha=alpha_v, beta=beta_v)
expected_means = stats.invgamma.mean(alpha_v, scale=beta_v)
self.assertEqual(inv_gamma.mean().get_shape(), (3,))
self.assertAllClose(inv_gamma.mean().eval(), expected_means)
def testInverseGammaMeanAllowNanStats(self):
with self.test_session():
# Mean will not be defined for the first entry.
alpha_v = np.array([1.0, 3.0, 2.5])
beta_v = np.array([1.0, 4.0, 5.0])
inv_gamma = tf.contrib.distributions.InverseGamma(
alpha=alpha_v, beta=beta_v, allow_nan_stats=False)
with self.assertRaisesOpError("x < y"):
inv_gamma.mean().eval()
def testInverseGammaMeanNanStats(self):
with self.test_session():
# Mode will not be defined for the first two entries.
alpha_v = np.array([0.5, 1.0, 3.0, 2.5])
beta_v = np.array([1.0, 2.0, 4.0, 5.0])
inv_gamma = tf.contrib.distributions.InverseGamma(alpha=alpha_v,
beta=beta_v,
allow_nan_stats=True)
expected_means = beta_v / (alpha_v - 1)
expected_means[0] = np.nan
expected_means[1] = np.nan
self.assertEqual(inv_gamma.mean().get_shape(), (4,))
self.assertAllClose(inv_gamma.mean().eval(), expected_means)
def testInverseGammaVarianceAllDefined(self):
with self.test_session():
alpha_v = np.array([7.0, 3.0, 2.5])
beta_v = np.array([1.0, 4.0, 5.0])
inv_gamma = tf.contrib.distributions.InverseGamma(alpha=alpha_v,
beta=beta_v)
expected_variances = stats.invgamma.var(alpha_v, scale=beta_v)
self.assertEqual(inv_gamma.variance().get_shape(), (3,))
self.assertAllClose(inv_gamma.variance().eval(), expected_variances)
def testInverseGammaVarianceAllowNanStats(self):
with self.test_session():
alpha_v = np.array([1.5, 3.0, 2.5])
beta_v = np.array([1.0, 4.0, 5.0])
inv_gamma = tf.contrib.distributions.InverseGamma(alpha=alpha_v,
beta=beta_v,
allow_nan_stats=False)
with self.assertRaisesOpError("x < y"):
inv_gamma.variance().eval()
def testInverseGammaVarianceNanStats(self):
with self.test_session():
alpha_v = np.array([1.5, 3.0, 2.5])
beta_v = np.array([1.0, 4.0, 5.0])
inv_gamma = tf.contrib.distributions.InverseGamma(alpha=alpha_v,
beta=beta_v,
allow_nan_stats=True)
expected_variances = stats.invgamma.var(alpha_v, scale=beta_v)
expected_variances[0] = np.nan
self.assertEqual(inv_gamma.variance().get_shape(), (3,))
self.assertAllClose(inv_gamma.variance().eval(), expected_variances)
def testInverseGammaEntropy(self):
with self.test_session():
alpha_v = np.array([1.0, 3.0, 2.5])
beta_v = np.array([1.0, 4.0, 5.0])
expected_entropy = stats.invgamma.entropy(alpha_v, scale=beta_v)
inv_gamma = tf.contrib.distributions.InverseGamma(alpha=alpha_v,
beta=beta_v)
self.assertEqual(inv_gamma.entropy().get_shape(), (3,))
self.assertAllClose(inv_gamma.entropy().eval(), expected_entropy)
def testInverseGammaSample(self):
with tf.Session():
alpha_v = 4.0
beta_v = 3.0
alpha = tf.constant(alpha_v)
beta = tf.constant(beta_v)
n = 100000
inv_gamma = tf.contrib.distributions.InverseGamma(alpha=alpha, beta=beta)
samples = inv_gamma.sample(n, seed=137)
sample_values = samples.eval()
self.assertEqual(samples.get_shape(), (n,))
self.assertEqual(sample_values.shape, (n,))
self.assertAllClose(sample_values.mean(),
stats.invgamma.mean(alpha_v, scale=beta_v),
atol=.0025)
self.assertAllClose(sample_values.var(),
stats.invgamma.var(alpha_v, scale=beta_v),
atol=.15)
self.assertTrue(self._kstest(alpha_v, beta_v, sample_values))
def testInverseGammaSampleMultiDimensional(self):
with tf.Session():
alpha_v = np.array([np.arange(3, 103, dtype=np.float32)]) # 1 x 100
beta_v = np.array([np.arange(1, 11, dtype=np.float32)]).T # 10 x 1
inv_gamma = tf.contrib.distributions.InverseGamma(alpha=alpha_v,
beta=beta_v)
n = 10000
samples = inv_gamma.sample(n, seed=137)
sample_values = samples.eval()
self.assertEqual(samples.get_shape(), (n, 10, 100))
self.assertEqual(sample_values.shape, (n, 10, 100))
zeros = np.zeros_like(alpha_v + beta_v) # 10 x 100
alpha_bc = alpha_v + zeros
beta_bc = beta_v + zeros
self.assertAllClose(
sample_values.mean(axis=0),
stats.invgamma.mean(alpha_bc, scale=beta_bc),
atol=.25)
self.assertAllClose(
sample_values.var(axis=0),
stats.invgamma.var(alpha_bc, scale=beta_bc),
atol=4.5)
fails = 0
trials = 0
for ai, a in enumerate(np.reshape(alpha_v, [-1])):
for bi, b in enumerate(np.reshape(beta_v, [-1])):
s = sample_values[:, bi, ai]
trials += 1
fails += 0 if self._kstest(a, b, s) else 1
self.assertLess(fails, trials * 0.03)
def _kstest(self, alpha, beta, samples):
# Uses the Kolmogorov-Smirnov test for goodness of fit.
ks, _ = stats.kstest(samples, stats.invgamma(alpha, scale=beta).cdf)
# Return True when the test passes.
return ks < 0.02
def testInverseGammaPdfOfSampleMultiDims(self):
with tf.Session() as sess:
inv_gamma = tf.contrib.distributions.InverseGamma(alpha=[7., 11.],
beta=[[5.], [6.]])
num = 50000
samples = inv_gamma.sample(num, seed=137)
pdfs = inv_gamma.pdf(samples)
sample_vals, pdf_vals = sess.run([samples, pdfs])
self.assertEqual(samples.get_shape(), (num, 2, 2))
self.assertEqual(pdfs.get_shape(), (num, 2, 2))
self.assertAllClose(
stats.invgamma.mean([[7., 11.], [7., 11.]],
scale=np.array([[5., 5.], [6., 6.]])),
sample_vals.mean(axis=0),
atol=.1)
self.assertAllClose(
stats.invgamma.var([[7., 11.], [7., 11.]],
scale=np.array([[5., 5.], [6., 6.]])),
sample_vals.var(axis=0),
atol=.1)
self._assertIntegral(sample_vals[:, 0, 0], pdf_vals[:, 0, 0], err=0.02)
self._assertIntegral(sample_vals[:, 0, 1], pdf_vals[:, 0, 1], err=0.02)
self._assertIntegral(sample_vals[:, 1, 0], pdf_vals[:, 1, 0], err=0.02)
self._assertIntegral(sample_vals[:, 1, 1], pdf_vals[:, 1, 1], err=0.02)
def _assertIntegral(self, sample_vals, pdf_vals, err=1e-3):
s_p = zip(sample_vals, pdf_vals)
prev = (0, 0)
total = 0
for k in sorted(s_p, key=lambda x: x[0]):
pair_pdf = (k[1] + prev[1]) / 2
total += (k[0] - prev[0]) * pair_pdf
prev = k
self.assertNear(1., total, err=err)
def testInverseGammaNonPositiveInitializationParamsRaises(self):
with self.test_session():
alpha_v = tf.constant(0.0, name="alpha")
beta_v = tf.constant(1.0, name="beta")
inv_gamma = tf.contrib.distributions.InverseGamma(
alpha=alpha_v, beta=beta_v, validate_args=True)
with self.assertRaisesOpError("alpha"):
inv_gamma.mean().eval()
alpha_v = tf.constant(1.0, name="alpha")
beta_v = tf.constant(0.0, name="beta")
inv_gamma = tf.contrib.distributions.InverseGamma(
alpha=alpha_v, beta=beta_v, validate_args=True)
with self.assertRaisesOpError("beta"):
inv_gamma.mean().eval()
def testInverseGammaWithSoftplusAlphaBeta(self):
with self.test_session():
alpha = tf.constant([-0.1, -2.9], name="alpha")
beta = tf.constant([1.0, -4.8], name="beta")
inv_gamma = tf.contrib.distributions.InverseGammaWithSoftplusAlphaBeta(
alpha=alpha, beta=beta, validate_args=True)
self.assertAllClose(tf.nn.softplus(alpha).eval(), inv_gamma.alpha.eval())
self.assertAllClose(tf.nn.softplus(beta).eval(), inv_gamma.beta.eval())
if __name__ == "__main__":
tf.test.main()
| apache-2.0 |
bikash/oryx-1 | framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/param/ContinuousRange.java | 1745 | /*
* Copyright (c) 2014, Cloudera, Inc. All Rights Reserved.
*
* Cloudera, Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for
* the specific language governing permissions and limitations under the
* License.
*/
package com.cloudera.oryx.ml.param;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.google.common.base.Preconditions;
final class ContinuousRange implements HyperParamValues<Double>, Serializable {
private final double min;
private final double max;
ContinuousRange(double min, double max) {
Preconditions.checkArgument(min <= max);
this.min = min;
this.max = max;
}
@Override
public List<Double> getTrialValues(int num) {
Preconditions.checkArgument(num > 0);
if (max == min) {
return Collections.singletonList(min);
}
if (num == 1) {
return Collections.singletonList((max + min) / 2.0);
}
if (num == 2) {
return Arrays.asList(min, max);
}
List<Double> values = new ArrayList<>(num);
double diff = (max - min) / (num - 1.0);
values.add(min);
for (int i = 1; i < num - 1; i++) {
values.add(values.get(i - 1) + diff);
}
values.add(max);
return values;
}
@Override
public String toString() {
return "ContinuousRange[..." + getTrialValues(3) + "...]";
}
}
| apache-2.0 |
mglukhikh/intellij-community | platform/lang-impl/src/com/intellij/ui/debugger/extensions/FocusDebugger.java | 6886 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui.debugger.extensions;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ui.Splitter;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.SimpleColoredText;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.ui.components.JBList;
import com.intellij.ui.debugger.UiDebuggerExtension;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.DefaultCaret;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
public class FocusDebugger implements UiDebuggerExtension, PropertyChangeListener, ListSelectionListener {
private static final Logger LOG = Logger.getInstance("#com.intellij.ui.debugger.extensions.FocusDebugger");
private JComponent myComponent;
private JList myLog;
private DefaultListModel myLogModel;
private JEditorPane myAllocation;
@Override
public JComponent getComponent() {
if (myComponent == null) {
myComponent = init();
}
return myComponent;
}
private JComponent init() {
final JPanel result = new JPanel(new BorderLayout());
myLogModel = new DefaultListModel();
myLog = new JBList(myLogModel);
myLog.setCellRenderer(new FocusElementRenderer());
myAllocation = new JEditorPane();
final DefaultCaret caret = new DefaultCaret();
myAllocation.setCaret(caret);
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
myAllocation.setEditable(false);
final Splitter splitter = new Splitter(true);
splitter.setFirstComponent(ScrollPaneFactory.createScrollPane(myLog));
splitter.setSecondComponent(ScrollPaneFactory.createScrollPane(myAllocation));
myLog.addListSelectionListener(this);
KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener(this);
result.add(splitter, BorderLayout.CENTER);
final DefaultActionGroup group = new DefaultActionGroup();
group.add(new ClearAction());
result.add(ActionManager.getInstance().createActionToolbar("FocusDbg", group, true).getComponent(), BorderLayout.NORTH);
return result;
}
class ClearAction extends AnAction {
ClearAction() {
super("Clear", "", AllIcons.Actions.Cross);
}
@Override
public void actionPerformed(AnActionEvent e) {
myLogModel.clear();
}
}
@Override
public void valueChanged(ListSelectionEvent e) {
if (myLog.getSelectedIndex() == -1) {
myAllocation.setText(null);
} else {
FocusElement element = (FocusElement)myLog.getSelectedValue();
final StringWriter s = new StringWriter();
final PrintWriter writer = new PrintWriter(s);
element.getAllocation().printStackTrace(writer);
myAllocation.setText(s.toString());
}
}
private boolean isInsideDebuggerDialog(Component c) {
final Window debuggerWindow = SwingUtilities.getWindowAncestor(myComponent);
if (!(debuggerWindow instanceof Dialog)) return false;
return c == debuggerWindow || SwingUtilities.getWindowAncestor(c) == debuggerWindow;
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
final Object newValue = evt.getNewValue();
final Object oldValue = evt.getOldValue();
boolean affectsDebugger = false;
if (newValue instanceof Component && isInsideDebuggerDialog((Component)newValue)) {
affectsDebugger |= true;
}
if (oldValue instanceof Component && isInsideDebuggerDialog((Component)oldValue)) {
affectsDebugger |= true;
}
final SimpleColoredText text = new SimpleColoredText();
text.append(evt.getPropertyName(), maybeGrayOut(new SimpleTextAttributes(SimpleTextAttributes.STYLE_UNDERLINE, null), affectsDebugger));
text.append(" newValue=", maybeGrayOut(SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES, affectsDebugger));
text.append(evt.getNewValue() + "", maybeGrayOut(SimpleTextAttributes.REGULAR_ATTRIBUTES, affectsDebugger));
text.append(" oldValue=" + evt.getOldValue(), maybeGrayOut(SimpleTextAttributes.REGULAR_ATTRIBUTES, affectsDebugger));
myLogModel.addElement(new FocusElement(text, new Throwable()));
SwingUtilities.invokeLater(() -> {
if (myLog != null && myLog.isShowing()) {
final int h = myLog.getFixedCellHeight();
myLog.scrollRectToVisible(new Rectangle(0, myLog.getPreferredSize().height - h, myLog.getWidth(), h));
if (myLog.getModel().getSize() > 0) {
myLog.setSelectedIndex(myLog.getModel().getSize() - 1);
}
}
});
}
private SimpleTextAttributes maybeGrayOut(SimpleTextAttributes attr, boolean greyOut) {
return greyOut ? attr.derive(attr.getStyle(), Color.gray, attr.getBgColor(), attr.getWaveColor()) : attr;
}
static class FocusElementRenderer extends ColoredListCellRenderer {
@Override
protected void customizeCellRenderer(@NotNull JList list, Object value, int index, boolean selected, boolean hasFocus) {
clear();
final FocusElement element = (FocusElement)value;
final SimpleColoredText text = element.getText();
final ArrayList<String> strings = text.getTexts();
final ArrayList<SimpleTextAttributes> attributes = element.getText().getAttributes();
for (int i = 0; i < strings.size(); i++) {
append(strings.get(i), attributes.get(i));
}
}
}
static class FocusElement {
private final SimpleColoredText myText;
private final Throwable myAllocation;
FocusElement(SimpleColoredText text, Throwable allocation) {
myText = text;
myAllocation = allocation;
}
public SimpleColoredText getText() {
return myText;
}
public Throwable getAllocation() {
return myAllocation;
}
}
@Override
public String getName() {
return "Focus";
}
@Override
public void disposeUiResources() {
myComponent = null;
KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener(this);
}
}
| apache-2.0 |
linkedin/gobblin | gobblin-utility/src/test/java/org/apache/gobblin/util/DatePartitionTypeTest.java | 1151 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.gobblin.util;
import org.testng.Assert;
import org.testng.annotations.Test;
public class DatePartitionTypeTest {
@Test
public void testGetMillis() {
Assert.assertEquals(DatePartitionType.MINUTE.getUnitMilliseconds(), 60000L);
Assert.assertEquals(DatePartitionType.HOUR.getUnitMilliseconds(), 60 * 60 * 1000L);
}
}
| apache-2.0 |
ankurcha/secor | src/main/java/com/pinterest/secor/parser/TimestampedMessageParser.java | 6836 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pinterest.secor.parser;
import com.pinterest.secor.common.SecorConfig;
import com.pinterest.secor.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public abstract class TimestampedMessageParser extends MessageParser implements Partitioner {
private static final Logger LOG = LoggerFactory.getLogger(TimestampedMessageParser.class);
private static final long HOUR_IN_MILLIS = 3600L * 1000L;
private static final long DAY_IN_MILLIS = 3600L * 24 * 1000L;
private static final SimpleDateFormat mDtFormatter = new SimpleDateFormat("yyyy-MM-dd");
private static final SimpleDateFormat mHrFormatter = new SimpleDateFormat("HH");
private static final SimpleDateFormat mDtHrFormatter = new SimpleDateFormat("yyyy-MM-dd-HH");
static {
mDtFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
mHrFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
mDtHrFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
}
private final boolean mUsingHourly;
public TimestampedMessageParser(SecorConfig config) {
super(config);
mUsingHourly = usingHourly(config);
LOG.info("UsingHourly: {}", mUsingHourly);
}
public abstract long extractTimestampMillis(final Message message) throws Exception;
static boolean usingHourly(SecorConfig config) {
return config.getBoolean("partitioner.granularity.hour", false);
}
protected static long toMillis(final long timestamp) {
final long nanosecondDivider = (long) Math.pow(10, 9 + 9);
final long millisecondDivider = (long) Math.pow(10, 9 + 3);
long timestampMillis;
if (timestamp / nanosecondDivider > 0L) {
timestampMillis = timestamp / (long) Math.pow(10, 6);
} else if (timestamp / millisecondDivider > 0L) {
timestampMillis = timestamp;
} else { // assume seconds
timestampMillis = timestamp * 1000L;
}
return timestampMillis;
}
protected String[] generatePartitions(long timestampMillis, boolean usingHourly)
throws Exception {
Date date = new Date(timestampMillis);
String dt = "dt=" + mDtFormatter.format(date);
String hr = "hr=" + mHrFormatter.format(date);
if (usingHourly) {
return new String[]{dt, hr};
} else {
return new String[]{dt};
}
}
protected long parsePartitions(String[] partitions) throws Exception {
String dtValue = partitions[0].split("=")[1];
String hrValue = partitions.length > 1 ? partitions[1].split("=")[1] : "00";
String value = dtValue + "-" + hrValue;
Date date = mDtHrFormatter.parse(value);
return date.getTime();
}
@Override
public String[] extractPartitions(Message message) throws Exception {
// Date constructor takes milliseconds since epoch.
long timestampMillis = extractTimestampMillis(message);
return generatePartitions(timestampMillis, mUsingHourly);
}
private long getFinalizedTimestampMillis(Message lastMessage,
Message committedMessage) throws Exception {
long lastTimestamp = extractTimestampMillis(lastMessage);
long committedTimestamp = extractTimestampMillis(committedMessage);
long now = System.currentTimeMillis();
if (lastTimestamp == committedTimestamp && (now - lastTimestamp) > 3600 * 1000) {
LOG.info("No new message coming, use the current time: " + now);
return now;
}
return committedTimestamp;
}
@Override
public String[] getFinalizedUptoPartitions(List<Message> lastMessages,
List<Message> committedMessages) throws Exception {
if (lastMessages == null || committedMessages == null) {
LOG.error("Either: {} and {} is null", lastMessages,
committedMessages);
return null;
}
assert lastMessages.size() == committedMessages.size();
long minMillis = Long.MAX_VALUE;
for (int i = 0; i < lastMessages.size(); i++) {
long millis = getFinalizedTimestampMillis(lastMessages.get(i),
committedMessages.get(i));
if (millis < minMillis) {
minMillis = millis;
}
}
if (minMillis == Long.MAX_VALUE) {
LOG.error("No valid timestamps among messages: {} and {}", lastMessages,
committedMessages);
return null;
}
// add the safety lag for late-arrival messages
minMillis -= 3600L * 1000L;
LOG.info("adjusted millis {}", minMillis);
return generatePartitions(minMillis, mUsingHourly);
}
@Override
public String[] getPreviousPartitions(String[] partitions) throws Exception {
long millis = parsePartitions(partitions);
boolean usingHourly = mUsingHourly;
if (mUsingHourly && millis % DAY_IN_MILLIS == 0) {
// On the day boundary, if the currrent partition is [dt=07-07, hr=00], the previous
// one is dt=07-06; If the current one is [dt=07-06], the previous one is
// [dt=07-06, hr-23]
// So we would return in the order of:
// dt=07-07, hr=01
// dt=07-07, hr=00
// dt=07-06
// dt=07-06, hr=23
if (partitions.length == 2 ) {
usingHourly = false;
millis -= DAY_IN_MILLIS;
} else {
usingHourly = true;
millis += DAY_IN_MILLIS;
millis -= HOUR_IN_MILLIS;
}
} else {
long delta = mUsingHourly ? HOUR_IN_MILLIS : DAY_IN_MILLIS;
millis -= delta;
}
return generatePartitions(millis, usingHourly);
}
}
| apache-2.0 |
rajanm/elasticsearch | server/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsIT.java | 53747 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.termvectors;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.Fields;
import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.admin.cluster.shards.ClusterSearchShardsResponse;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.lucene.uid.Versions;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.engine.VersionConflictEngineException;
import org.elasticsearch.index.mapper.FieldMapper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
public class GetTermVectorsIT extends AbstractTermVectorsTestCase {
public void testNoSuchDoc() throws Exception {
XContentBuilder mapping = jsonBuilder().startObject().startObject("type1")
.startObject("properties")
.startObject("field")
.field("type", "text")
.field("term_vector", "with_positions_offsets_payloads")
.endObject()
.endObject()
.endObject().endObject();
assertAcked(prepareCreate("test").addAlias(new Alias("alias")).addMapping("type1", mapping));
client().prepareIndex("test", "type1", "666").setSource("field", "foo bar").execute().actionGet();
refresh();
for (int i = 0; i < 20; i++) {
ActionFuture<TermVectorsResponse> termVector = client().termVectors(new TermVectorsRequest(indexOrAlias(), "type1", "" + i));
TermVectorsResponse actionGet = termVector.actionGet();
assertThat(actionGet, notNullValue());
assertThat(actionGet.getIndex(), equalTo("test"));
assertThat(actionGet.isExists(), equalTo(false));
// check response is nevertheless serializable to json
actionGet.toXContent(jsonBuilder(), ToXContent.EMPTY_PARAMS);
}
}
public void testExistingFieldWithNoTermVectorsNoNPE() throws Exception {
XContentBuilder mapping = jsonBuilder().startObject().startObject("type1")
.startObject("properties")
.startObject("existingfield")
.field("type", "text")
.field("term_vector", "with_positions_offsets_payloads")
.endObject()
.endObject()
.endObject().endObject();
assertAcked(prepareCreate("test").addAlias(new Alias("alias")).addMapping("type1", mapping));
// when indexing a field that simply has a question mark, the term vectors will be null
client().prepareIndex("test", "type1", "0").setSource("existingfield", "?").execute().actionGet();
refresh();
ActionFuture<TermVectorsResponse> termVector = client().termVectors(new TermVectorsRequest(indexOrAlias(), "type1", "0")
.selectedFields(new String[]{"existingfield"}));
// lets see if the null term vectors are caught...
TermVectorsResponse actionGet = termVector.actionGet();
assertThat(actionGet, notNullValue());
assertThat(actionGet.isExists(), equalTo(true));
assertThat(actionGet.getIndex(), equalTo("test"));
assertThat(actionGet.getFields().terms("existingfield"), nullValue());
}
public void testExistingFieldButNotInDocNPE() throws Exception {
XContentBuilder mapping = jsonBuilder().startObject().startObject("type1")
.startObject("properties")
.startObject("existingfield")
.field("type", "text")
.field("term_vector", "with_positions_offsets_payloads")
.endObject()
.endObject()
.endObject().endObject();
assertAcked(prepareCreate("test").addAlias(new Alias("alias")).addMapping("type1", mapping));
// when indexing a field that simply has a question mark, the term vectors will be null
client().prepareIndex("test", "type1", "0").setSource("anotherexistingfield", 1).execute().actionGet();
refresh();
ActionFuture<TermVectorsResponse> termVectors = client().termVectors(new TermVectorsRequest(indexOrAlias(), "type1", "0")
.selectedFields(randomBoolean() ? new String[]{"existingfield"} : null)
.termStatistics(true)
.fieldStatistics(true));
// lets see if the null term vectors are caught...
TermVectorsResponse actionGet = termVectors.actionGet();
assertThat(actionGet, notNullValue());
assertThat(actionGet.isExists(), equalTo(true));
assertThat(actionGet.getIndex(), equalTo("test"));
assertThat(actionGet.getFields().terms("existingfield"), nullValue());
}
public void testNotIndexedField() throws Exception {
// must be of type string and indexed.
assertAcked(prepareCreate("test")
.addAlias(new Alias("alias"))
.addMapping("type1",
"field0", "type=integer,", // no tvs
"field1", "type=text,index=false", // no tvs
"field2", "type=text,index=false,store=true", // no tvs
"field3", "type=text,index=false,term_vector=yes", // no tvs
"field4", "type=keyword", // yes tvs
"field5", "type=text,index=true")); // yes tvs
List<IndexRequestBuilder> indexBuilders = new ArrayList<>();
for (int i = 0; i < 6; i++) {
indexBuilders.add(client().prepareIndex()
.setIndex("test")
.setType("type1")
.setId(String.valueOf(i))
.setSource("field" + i, i));
}
indexRandom(true, indexBuilders);
for (int i = 0; i < 4; i++) {
TermVectorsResponse resp = client().prepareTermVectors(indexOrAlias(), "type1", String.valueOf(i))
.setSelectedFields("field" + i)
.get();
assertThat(resp, notNullValue());
assertThat(resp.isExists(), equalTo(true));
assertThat(resp.getIndex(), equalTo("test"));
assertThat("field" + i + " :", resp.getFields().terms("field" + i), nullValue());
}
for (int i = 4; i < 6; i++) {
TermVectorsResponse resp = client().prepareTermVectors(indexOrAlias(), "type1", String.valueOf(i))
.setSelectedFields("field" + i).get();
assertThat(resp.getIndex(), equalTo("test"));
assertThat("field" + i + " :", resp.getFields().terms("field" + i), notNullValue());
}
}
public void testSimpleTermVectors() throws IOException {
XContentBuilder mapping = jsonBuilder().startObject().startObject("type1")
.startObject("properties")
.startObject("field")
.field("type", "text")
.field("term_vector", "with_positions_offsets_payloads")
.field("analyzer", "tv_test")
.endObject()
.endObject()
.endObject().endObject();
assertAcked(prepareCreate("test").addMapping("type1", mapping)
.addAlias(new Alias("alias"))
.setSettings(Settings.builder()
.put(indexSettings())
.put("index.analysis.analyzer.tv_test.tokenizer", "whitespace")
.putList("index.analysis.analyzer.tv_test.filter", "lowercase")));
for (int i = 0; i < 10; i++) {
client().prepareIndex("test", "type1", Integer.toString(i))
.setSource(jsonBuilder().startObject().field("field", "the quick brown fox jumps over the lazy dog")
// 0the3 4quick9 10brown15 16fox19 20jumps25 26over30
// 31the34 35lazy39 40dog43
.endObject()).execute().actionGet();
refresh();
}
for (int i = 0; i < 10; i++) {
TermVectorsRequestBuilder resp = client().prepareTermVectors(indexOrAlias(), "type1", Integer.toString(i)).setPayloads(true)
.setOffsets(true).setPositions(true).setSelectedFields();
TermVectorsResponse response = resp.execute().actionGet();
assertThat(response.getIndex(), equalTo("test"));
assertThat("doc id: " + i + " doesn't exists but should", response.isExists(), equalTo(true));
Fields fields = response.getFields();
assertThat(fields.size(), equalTo(1));
checkBrownFoxTermVector(fields, "field", true);
}
}
public void testRandomSingleTermVectors() throws IOException {
FieldType ft = new FieldType();
int config = randomInt(4);
boolean storePositions = false;
boolean storeOffsets = false;
boolean storeTermVectors = false;
switch (config) {
case 0: {
// do nothing
break;
}
case 1: {
storeTermVectors = true;
break;
}
case 2: {
storeTermVectors = true;
storePositions = true;
break;
}
case 3: {
storeTermVectors = true;
storeOffsets = true;
break;
}
case 4: {
storeTermVectors = true;
storePositions = true;
storeOffsets = true;
break;
}
default:
throw new IllegalArgumentException("Unsupported option: " + config);
}
ft.setStoreTermVectors(storeTermVectors);
ft.setStoreTermVectorOffsets(storeOffsets);
ft.setStoreTermVectorPositions(storePositions);
String optionString = FieldMapper.termVectorOptionsToString(ft);
XContentBuilder mapping = jsonBuilder().startObject().startObject("type1")
.startObject("properties")
.startObject("field")
.field("type", "text")
.field("term_vector", optionString)
.field("analyzer", "tv_test")
.endObject()
.endObject()
.endObject().endObject();
assertAcked(prepareCreate("test").addMapping("type1", mapping)
.setSettings(Settings.builder()
.put("index.analysis.analyzer.tv_test.tokenizer", "whitespace")
.putList("index.analysis.analyzer.tv_test.filter", "lowercase")));
for (int i = 0; i < 10; i++) {
client().prepareIndex("test", "type1", Integer.toString(i))
.setSource(jsonBuilder().startObject().field("field", "the quick brown fox jumps over the lazy dog")
// 0the3 4quick9 10brown15 16fox19 20jumps25 26over30
// 31the34 35lazy39 40dog43
.endObject()).execute().actionGet();
refresh();
}
String[] values = {"brown", "dog", "fox", "jumps", "lazy", "over", "quick", "the"};
int[] freq = {1, 1, 1, 1, 1, 1, 1, 2};
int[][] pos = {{2}, {8}, {3}, {4}, {7}, {5}, {1}, {0, 6}};
int[][] startOffset = {{10}, {40}, {16}, {20}, {35}, {26}, {4}, {0, 31}};
int[][] endOffset = {{15}, {43}, {19}, {25}, {39}, {30}, {9}, {3, 34}};
boolean isOffsetRequested = randomBoolean();
boolean isPositionsRequested = randomBoolean();
String infoString = createInfoString(isPositionsRequested, isOffsetRequested, optionString);
for (int i = 0; i < 10; i++) {
TermVectorsRequestBuilder resp = client().prepareTermVectors("test", "type1", Integer.toString(i))
.setOffsets(isOffsetRequested).setPositions(isPositionsRequested).setSelectedFields();
TermVectorsResponse response = resp.execute().actionGet();
assertThat(infoString + "doc id: " + i + " doesn't exists but should", response.isExists(), equalTo(true));
Fields fields = response.getFields();
assertThat(fields.size(), equalTo(ft.storeTermVectors() ? 1 : 0));
if (ft.storeTermVectors()) {
Terms terms = fields.terms("field");
assertThat(terms.size(), equalTo(8L));
TermsEnum iterator = terms.iterator();
for (int j = 0; j < values.length; j++) {
String string = values[j];
BytesRef next = iterator.next();
assertThat(infoString, next, notNullValue());
assertThat(infoString + "expected " + string, string, equalTo(next.utf8ToString()));
assertThat(infoString, next, notNullValue());
// do not test ttf or doc frequency, because here we have
// many shards and do not know how documents are distributed
PostingsEnum docsAndPositions = iterator.postings(null, PostingsEnum.ALL);
// docs and pos only returns something if positions or
// payloads or offsets are stored / requestd Otherwise use
// DocsEnum?
assertThat(infoString, docsAndPositions.nextDoc(), equalTo(0));
assertThat(infoString, freq[j], equalTo(docsAndPositions.freq()));
int[] termPos = pos[j];
int[] termStartOffset = startOffset[j];
int[] termEndOffset = endOffset[j];
if (isPositionsRequested && storePositions) {
assertThat(infoString, termPos.length, equalTo(freq[j]));
}
if (isOffsetRequested && storeOffsets) {
assertThat(termStartOffset.length, equalTo(freq[j]));
assertThat(termEndOffset.length, equalTo(freq[j]));
}
for (int k = 0; k < freq[j]; k++) {
int nextPosition = docsAndPositions.nextPosition();
// only return something useful if requested and stored
if (isPositionsRequested && storePositions) {
assertThat(infoString + "positions for term: " + string, nextPosition, equalTo(termPos[k]));
} else {
assertThat(infoString + "positions for term: ", nextPosition, equalTo(-1));
}
// payloads are never made by the mapping in this test
assertNull(infoString + "payloads for term: " + string, docsAndPositions.getPayload());
// only return something useful if requested and stored
if (isOffsetRequested && storeOffsets) {
assertThat(infoString + "startOffsets term: " + string, docsAndPositions.startOffset(),
equalTo(termStartOffset[k]));
assertThat(infoString + "endOffsets term: " + string, docsAndPositions.endOffset(), equalTo(termEndOffset[k]));
} else {
assertThat(infoString + "startOffsets term: " + string, docsAndPositions.startOffset(), equalTo(-1));
assertThat(infoString + "endOffsets term: " + string, docsAndPositions.endOffset(), equalTo(-1));
}
}
}
assertThat(iterator.next(), nullValue());
}
}
}
private String createInfoString(boolean isPositionsRequested, boolean isOffsetRequested, String optionString) {
String ret = "Store config: " + optionString + "\n" + "Requested: pos-"
+ (isPositionsRequested ? "yes" : "no") + ", offsets-" + (isOffsetRequested ? "yes" : "no") + "\n";
return ret;
}
public void testDuelESLucene() throws Exception {
TestFieldSetting[] testFieldSettings = getFieldSettings();
createIndexBasedOnFieldSettings("test", "alias", testFieldSettings);
//we generate as many docs as many shards we have
TestDoc[] testDocs = generateTestDocs("test", testFieldSettings);
DirectoryReader directoryReader = indexDocsWithLucene(testDocs);
TestConfig[] testConfigs = generateTestConfigs(20, testDocs, testFieldSettings);
for (TestConfig test : testConfigs) {
TermVectorsRequestBuilder request = getRequestForConfig(test);
if (test.expectedException != null) {
assertThrows(request, test.expectedException);
continue;
}
TermVectorsResponse response = request.get();
Fields luceneTermVectors = getTermVectorsFromLucene(directoryReader, test.doc);
validateResponse(response, luceneTermVectors, test);
}
}
// like testSimpleTermVectors but we create fields with no term vectors
public void testSimpleTermVectorsWithGenerate() throws IOException {
String[] fieldNames = new String[10];
for (int i = 0; i < fieldNames.length; i++) {
fieldNames[i] = "field" + String.valueOf(i);
}
XContentBuilder mapping = jsonBuilder().startObject().startObject("type1").startObject("properties");
XContentBuilder source = jsonBuilder().startObject();
for (String field : fieldNames) {
mapping.startObject(field)
.field("type", "text")
.field("term_vector", randomBoolean() ? "with_positions_offsets_payloads" : "no")
.field("analyzer", "tv_test")
.endObject();
source.field(field, "the quick brown fox jumps over the lazy dog");
}
mapping.endObject().endObject().endObject();
source.endObject();
assertAcked(prepareCreate("test")
.addMapping("type1", mapping)
.setSettings(Settings.builder()
.put(indexSettings())
.put("index.analysis.analyzer.tv_test.tokenizer", "whitespace")
.putList("index.analysis.analyzer.tv_test.filter", "lowercase")));
ensureGreen();
for (int i = 0; i < 10; i++) {
client().prepareIndex("test", "type1", Integer.toString(i))
.setSource(source)
.execute().actionGet();
refresh();
}
for (int i = 0; i < 10; i++) {
TermVectorsResponse response = client().prepareTermVectors("test", "type1", Integer.toString(i))
.setPayloads(true)
.setOffsets(true)
.setPositions(true)
.setSelectedFields(fieldNames)
.execute().actionGet();
assertThat("doc id: " + i + " doesn't exists but should", response.isExists(), equalTo(true));
Fields fields = response.getFields();
assertThat(fields.size(), equalTo(fieldNames.length));
for (String fieldName : fieldNames) {
// MemoryIndex does not support payloads
checkBrownFoxTermVector(fields, fieldName, false);
}
}
}
private void checkBrownFoxTermVector(Fields fields, String fieldName, boolean withPayloads) throws IOException {
String[] values = {"brown", "dog", "fox", "jumps", "lazy", "over", "quick", "the"};
int[] freq = {1, 1, 1, 1, 1, 1, 1, 2};
int[][] pos = {{2}, {8}, {3}, {4}, {7}, {5}, {1}, {0, 6}};
int[][] startOffset = {{10}, {40}, {16}, {20}, {35}, {26}, {4}, {0, 31}};
int[][] endOffset = {{15}, {43}, {19}, {25}, {39}, {30}, {9}, {3, 34}};
Terms terms = fields.terms(fieldName);
assertThat(terms.size(), equalTo(8L));
TermsEnum iterator = terms.iterator();
for (int j = 0; j < values.length; j++) {
String string = values[j];
BytesRef next = iterator.next();
assertThat(next, notNullValue());
assertThat("expected " + string, string, equalTo(next.utf8ToString()));
assertThat(next, notNullValue());
// do not test ttf or doc frequency, because here we have many
// shards and do not know how documents are distributed
PostingsEnum docsAndPositions = iterator.postings(null, PostingsEnum.ALL);
assertThat(docsAndPositions.nextDoc(), equalTo(0));
assertThat(freq[j], equalTo(docsAndPositions.freq()));
int[] termPos = pos[j];
int[] termStartOffset = startOffset[j];
int[] termEndOffset = endOffset[j];
assertThat(termPos.length, equalTo(freq[j]));
assertThat(termStartOffset.length, equalTo(freq[j]));
assertThat(termEndOffset.length, equalTo(freq[j]));
for (int k = 0; k < freq[j]; k++) {
int nextPosition = docsAndPositions.nextPosition();
assertThat("term: " + string, nextPosition, equalTo(termPos[k]));
assertThat("term: " + string, docsAndPositions.startOffset(), equalTo(termStartOffset[k]));
assertThat("term: " + string, docsAndPositions.endOffset(), equalTo(termEndOffset[k]));
// We never configure an analyzer with payloads for this test so this is never returned
assertNull("term: " + string, docsAndPositions.getPayload());
}
}
assertThat(iterator.next(), nullValue());
}
public void testDuelWithAndWithoutTermVectors() throws IOException, ExecutionException, InterruptedException {
// setup indices
String[] indexNames = new String[] {"with_tv", "without_tv"};
assertAcked(prepareCreate(indexNames[0])
.addMapping("type1", "field1", "type=text,term_vector=with_positions_offsets,analyzer=keyword"));
assertAcked(prepareCreate(indexNames[1])
.addMapping("type1", "field1", "type=text,term_vector=no,analyzer=keyword"));
ensureGreen();
// index documents with and without term vectors
String[] content = new String[]{
"Generating a random permutation of a sequence (such as when shuffling cards).",
"Selecting a random sample of a population (important in statistical sampling).",
"Allocating experimental units via random assignment to a treatment or control condition.",
"Generating random numbers: see Random number generation.",
"Selecting a random sample of a population (important in statistical sampling).",
"Allocating experimental units via random assignment to a treatment or control condition.",
"Transforming a data stream (such as when using a scrambler in telecommunications)."};
List<IndexRequestBuilder> indexBuilders = new ArrayList<>();
for (String indexName : indexNames) {
for (int id = 0; id < content.length; id++) {
indexBuilders.add(client().prepareIndex()
.setIndex(indexName)
.setType("type1")
.setId(String.valueOf(id))
.setSource("field1", content[id]));
}
}
indexRandom(true, indexBuilders);
// request tvs and compare from each index
for (int id = 0; id < content.length; id++) {
Fields[] fields = new Fields[2];
for (int j = 0; j < indexNames.length; j++) {
TermVectorsResponse resp = client().prepareTermVector(indexNames[j], "type1", String.valueOf(id))
.setOffsets(true)
.setPositions(true)
.setSelectedFields("field1")
.get();
assertThat("doc with index: " + indexNames[j] + ", type1 and id: " + id, resp.isExists(), equalTo(true));
fields[j] = resp.getFields();
}
compareTermVectors("field1", fields[0], fields[1]);
}
}
private void compareTermVectors(String fieldName, Fields fields0, Fields fields1) throws IOException {
Terms terms0 = fields0.terms(fieldName);
Terms terms1 = fields1.terms(fieldName);
assertThat(terms0, notNullValue());
assertThat(terms1, notNullValue());
assertThat(terms0.size(), equalTo(terms1.size()));
TermsEnum iter0 = terms0.iterator();
TermsEnum iter1 = terms1.iterator();
for (int i = 0; i < terms0.size(); i++) {
BytesRef next0 = iter0.next();
assertThat(next0, notNullValue());
BytesRef next1 = iter1.next();
assertThat(next1, notNullValue());
// compare field value
String string0 = next0.utf8ToString();
String string1 = next1.utf8ToString();
assertThat("expected: " + string0, string0, equalTo(string1));
// compare df and ttf
assertThat("term: " + string0, iter0.docFreq(), equalTo(iter1.docFreq()));
assertThat("term: " + string0, iter0.totalTermFreq(), equalTo(iter1.totalTermFreq()));
// compare freq and docs
PostingsEnum docsAndPositions0 = iter0.postings(null, PostingsEnum.ALL);
PostingsEnum docsAndPositions1 = iter1.postings(null, PostingsEnum.ALL);
assertThat("term: " + string0, docsAndPositions0.nextDoc(), equalTo(docsAndPositions1.nextDoc()));
assertThat("term: " + string0, docsAndPositions0.freq(), equalTo(docsAndPositions1.freq()));
// compare position, start offsets and end offsets
for (int j = 0; j < docsAndPositions0.freq(); j++) {
assertThat("term: " + string0, docsAndPositions0.nextPosition(), equalTo(docsAndPositions1.nextPosition()));
assertThat("term: " + string0, docsAndPositions0.startOffset(), equalTo(docsAndPositions1.startOffset()));
assertThat("term: " + string0, docsAndPositions0.endOffset(), equalTo(docsAndPositions1.endOffset()));
}
}
assertThat(iter0.next(), nullValue());
assertThat(iter1.next(), nullValue());
}
public void testSimpleWildCards() throws IOException {
int numFields = 25;
XContentBuilder mapping = jsonBuilder().startObject().startObject("type1").startObject("properties");
XContentBuilder source = jsonBuilder().startObject();
for (int i = 0; i < numFields; i++) {
mapping.startObject("field" + i)
.field("type", "text")
.field("term_vector", randomBoolean() ? "yes" : "no")
.endObject();
source.field("field" + i, "some text here");
}
source.endObject();
mapping.endObject().endObject().endObject();
assertAcked(prepareCreate("test").addAlias(new Alias("alias")).addMapping("type1", mapping));
ensureGreen();
client().prepareIndex("test", "type1", "0").setSource(source).get();
refresh();
TermVectorsResponse response = client().prepareTermVectors(indexOrAlias(), "type1", "0").setSelectedFields("field*").get();
assertThat("Doc doesn't exists but should", response.isExists(), equalTo(true));
assertThat(response.getIndex(), equalTo("test"));
assertThat("All term vectors should have been generated", response.getFields().size(), equalTo(numFields));
}
public void testArtificialVsExisting() throws ExecutionException, InterruptedException, IOException {
// setup indices
Settings.Builder settings = Settings.builder()
.put(indexSettings())
.put("index.analysis.analyzer", "standard");
assertAcked(prepareCreate("test")
.setSettings(settings)
.addMapping("type1", "field1", "type=text,term_vector=with_positions_offsets"));
ensureGreen();
// index documents existing document
String[] content = new String[]{
"Generating a random permutation of a sequence (such as when shuffling cards).",
"Selecting a random sample of a population (important in statistical sampling).",
"Allocating experimental units via random assignment to a treatment or control condition.",
"Generating random numbers: see Random number generation."};
List<IndexRequestBuilder> indexBuilders = new ArrayList<>();
for (int i = 0; i < content.length; i++) {
indexBuilders.add(client().prepareIndex()
.setIndex("test")
.setType("type1")
.setId(String.valueOf(i))
.setSource("field1", content[i]));
}
indexRandom(true, indexBuilders);
for (int i = 0; i < content.length; i++) {
// request tvs from existing document
TermVectorsResponse respExisting = client().prepareTermVectors("test", "type1", String.valueOf(i))
.setOffsets(true)
.setPositions(true)
.setFieldStatistics(true)
.setTermStatistics(true)
.get();
assertThat("doc with index: test, type1 and id: existing", respExisting.isExists(), equalTo(true));
// request tvs from artificial document
TermVectorsResponse respArtificial = client().prepareTermVectors()
.setIndex("test")
.setType("type1")
.setRouting(String.valueOf(i)) // ensure we get the stats from the same shard as existing doc
.setDoc(jsonBuilder()
.startObject()
.field("field1", content[i])
.endObject())
.setOffsets(true)
.setPositions(true)
.setFieldStatistics(true)
.setTermStatistics(true)
.get();
assertThat("doc with index: test, type1 and id: " + String.valueOf(i), respArtificial.isExists(), equalTo(true));
// compare existing tvs with artificial
compareTermVectors("field1", respExisting.getFields(), respArtificial.getFields());
}
}
public void testArtificialNoDoc() throws IOException {
// setup indices
Settings.Builder settings = Settings.builder()
.put(indexSettings())
.put("index.analysis.analyzer", "standard");
assertAcked(prepareCreate("test")
.setSettings(settings)
.addMapping("type1", "field1", "type=text"));
ensureGreen();
// request tvs from artificial document
String text = "the quick brown fox jumps over the lazy dog";
TermVectorsResponse resp = client().prepareTermVectors()
.setIndex("test")
.setType("type1")
.setDoc(jsonBuilder()
.startObject()
.field("field1", text)
.endObject())
.setOffsets(true)
.setPositions(true)
.setFieldStatistics(true)
.setTermStatistics(true)
.get();
assertThat(resp.isExists(), equalTo(true));
checkBrownFoxTermVector(resp.getFields(), "field1", false);
// Since the index is empty, all of artificial document's "term_statistics" should be 0/absent
Terms terms = resp.getFields().terms("field1");
assertEquals("sumDocFreq should be 0 for a non-existing field!", 0, terms.getSumDocFreq());
assertEquals("sumTotalTermFreq should be 0 for a non-existing field!", 0, terms.getSumTotalTermFreq());
TermsEnum termsEnum = terms.iterator(); // we're guaranteed to receive terms for that field
while (termsEnum.next() != null) {
String term = termsEnum.term().utf8ToString();
assertEquals("term [" + term + "] does not exist in the index; ttf should be 0!", 0, termsEnum.totalTermFreq());
}
}
public void testPerFieldAnalyzer() throws IOException {
int numFields = 25;
// setup mapping and document source
Set<String> withTermVectors = new HashSet<>();
XContentBuilder mapping = jsonBuilder().startObject().startObject("type1").startObject("properties");
XContentBuilder source = jsonBuilder().startObject();
for (int i = 0; i < numFields; i++) {
String fieldName = "field" + i;
if (randomBoolean()) {
withTermVectors.add(fieldName);
}
mapping.startObject(fieldName)
.field("type", "text")
.field("term_vector", withTermVectors.contains(fieldName) ? "yes" : "no")
.endObject();
source.field(fieldName, "some text here");
}
source.endObject();
mapping.endObject().endObject().endObject();
// setup indices with mapping
Settings.Builder settings = Settings.builder()
.put(indexSettings())
.put("index.analysis.analyzer", "standard");
assertAcked(prepareCreate("test")
.addAlias(new Alias("alias"))
.setSettings(settings)
.addMapping("type1", mapping));
ensureGreen();
// index a single document with prepared source
client().prepareIndex("test", "type1", "0").setSource(source).get();
refresh();
// create random per_field_analyzer and selected fields
Map<String, String> perFieldAnalyzer = new HashMap<>();
Set<String> selectedFields = new HashSet<>();
for (int i = 0; i < numFields; i++) {
if (randomBoolean()) {
perFieldAnalyzer.put("field" + i, "keyword");
}
if (randomBoolean()) {
perFieldAnalyzer.put("non_existing" + i, "keyword");
}
if (randomBoolean()) {
selectedFields.add("field" + i);
}
if (randomBoolean()) {
selectedFields.add("non_existing" + i);
}
}
// selected fields not specified
TermVectorsResponse response = client().prepareTermVectors(indexOrAlias(), "type1", "0")
.setPerFieldAnalyzer(perFieldAnalyzer)
.get();
// should return all fields that have terms vectors, some with overridden analyzer
checkAnalyzedFields(response.getFields(), withTermVectors, perFieldAnalyzer);
// selected fields specified including some not in the mapping
response = client().prepareTermVectors(indexOrAlias(), "type1", "0")
.setSelectedFields(selectedFields.toArray(Strings.EMPTY_ARRAY))
.setPerFieldAnalyzer(perFieldAnalyzer)
.get();
// should return only the specified valid fields, with some with overridden analyzer
checkAnalyzedFields(response.getFields(), selectedFields, perFieldAnalyzer);
}
private void checkAnalyzedFields(Fields fieldsObject, Set<String> fieldNames, Map<String, String> perFieldAnalyzer) throws IOException {
Set<String> validFields = new HashSet<>();
for (String fieldName : fieldNames){
if (fieldName.startsWith("non_existing")) {
assertThat("Non existing field\"" + fieldName + "\" should not be returned!", fieldsObject.terms(fieldName), nullValue());
continue;
}
Terms terms = fieldsObject.terms(fieldName);
assertThat("Existing field " + fieldName + "should have been returned", terms, notNullValue());
// check overridden by keyword analyzer ...
if (perFieldAnalyzer.containsKey(fieldName)) {
TermsEnum iterator = terms.iterator();
assertThat("Analyzer for " + fieldName + " should have been overridden!", iterator.next().utf8ToString(), equalTo("some text here"));
assertThat(iterator.next(), nullValue());
}
validFields.add(fieldName);
}
// ensure no other fields are returned
assertThat("More fields than expected are returned!", fieldsObject.size(), equalTo(validFields.size()));
}
private static String indexOrAlias() {
return randomBoolean() ? "test" : "alias";
}
public void testTermVectorsWithVersion() {
assertAcked(prepareCreate("test").addAlias(new Alias("alias"))
.setSettings(Settings.builder().put("index.refresh_interval", -1)));
ensureGreen();
TermVectorsResponse response = client().prepareTermVectors("test", "type1", "1").get();
assertThat(response.isExists(), equalTo(false));
logger.info("--> index doc 1");
client().prepareIndex("test", "type1", "1").setSource("field1", "value1", "field2", "value2").get();
// From translog:
// version 0 means ignore version, which is the default
response = client().prepareTermVectors(indexOrAlias(), "type1", "1").setVersion(Versions.MATCH_ANY).get();
assertThat(response.isExists(), equalTo(true));
assertThat(response.getId(), equalTo("1"));
assertThat(response.getVersion(), equalTo(1L));
response = client().prepareTermVectors(indexOrAlias(), "type1", "1").setVersion(1).get();
assertThat(response.isExists(), equalTo(true));
assertThat(response.getId(), equalTo("1"));
assertThat(response.getVersion(), equalTo(1L));
try {
client().prepareGet(indexOrAlias(), "type1", "1").setVersion(2).get();
fail();
} catch (VersionConflictEngineException e) {
//all good
}
// From Lucene index:
refresh();
// version 0 means ignore version, which is the default
response = client().prepareTermVectors(indexOrAlias(), "type1", "1").setVersion(Versions.MATCH_ANY).setRealtime(false).get();
assertThat(response.isExists(), equalTo(true));
assertThat(response.getId(), equalTo("1"));
assertThat(response.getIndex(), equalTo("test"));
assertThat(response.getVersion(), equalTo(1L));
response = client().prepareTermVectors(indexOrAlias(), "type1", "1").setVersion(1).setRealtime(false).get();
assertThat(response.isExists(), equalTo(true));
assertThat(response.getId(), equalTo("1"));
assertThat(response.getIndex(), equalTo("test"));
assertThat(response.getVersion(), equalTo(1L));
try {
client().prepareGet(indexOrAlias(), "type1", "1").setVersion(2).setRealtime(false).get();
fail();
} catch (VersionConflictEngineException e) {
//all good
}
logger.info("--> index doc 1 again, so increasing the version");
client().prepareIndex("test", "type1", "1").setSource("field1", "value1", "field2", "value2").get();
// From translog:
// version 0 means ignore version, which is the default
response = client().prepareTermVectors(indexOrAlias(), "type1", "1").setVersion(Versions.MATCH_ANY).get();
assertThat(response.isExists(), equalTo(true));
assertThat(response.getId(), equalTo("1"));
assertThat(response.getIndex(), equalTo("test"));
assertThat(response.getVersion(), equalTo(2L));
try {
client().prepareGet(indexOrAlias(), "type1", "1").setVersion(1).get();
fail();
} catch (VersionConflictEngineException e) {
//all good
}
response = client().prepareTermVectors(indexOrAlias(), "type1", "1").setVersion(2).get();
assertThat(response.isExists(), equalTo(true));
assertThat(response.getId(), equalTo("1"));
assertThat(response.getIndex(), equalTo("test"));
assertThat(response.getVersion(), equalTo(2L));
// From Lucene index:
refresh();
// version 0 means ignore version, which is the default
response = client().prepareTermVectors(indexOrAlias(), "type1", "1").setVersion(Versions.MATCH_ANY).setRealtime(false).get();
assertThat(response.isExists(), equalTo(true));
assertThat(response.getId(), equalTo("1"));
assertThat(response.getIndex(), equalTo("test"));
assertThat(response.getVersion(), equalTo(2L));
try {
client().prepareGet(indexOrAlias(), "type1", "1").setVersion(1).setRealtime(false).get();
fail();
} catch (VersionConflictEngineException e) {
//all good
}
response = client().prepareTermVectors(indexOrAlias(), "type1", "1").setVersion(2).setRealtime(false).get();
assertThat(response.isExists(), equalTo(true));
assertThat(response.getId(), equalTo("1"));
assertThat(response.getIndex(), equalTo("test"));
assertThat(response.getVersion(), equalTo(2L));
}
public void testFilterLength() throws ExecutionException, InterruptedException, IOException {
logger.info("Setting up the index ...");
Settings.Builder settings = Settings.builder()
.put(indexSettings())
.put("index.analysis.analyzer", "keyword");
assertAcked(prepareCreate("test")
.setSettings(settings)
.addMapping("type1", "tags", "type=text"));
int numTerms = scaledRandomIntBetween(10, 50);
logger.info("Indexing one document with tags of increasing length ...");
List<String> tags = new ArrayList<>();
for (int i = 0; i < numTerms; i++) {
String tag = "a";
for (int j = 0; j < i; j++) {
tag += "a";
}
tags.add(tag);
}
indexRandom(true, client().prepareIndex("test", "type1", "1").setSource("tags", tags));
logger.info("Checking best tags by longest to shortest size ...");
TermVectorsRequest.FilterSettings filterSettings = new TermVectorsRequest.FilterSettings();
filterSettings.maxNumTerms = numTerms;
TermVectorsResponse response;
for (int i = 0; i < numTerms; i++) {
filterSettings.minWordLength = numTerms - i;
response = client().prepareTermVectors("test", "type1", "1")
.setSelectedFields("tags")
.setFieldStatistics(true)
.setTermStatistics(true)
.setFilterSettings(filterSettings)
.get();
checkBestTerms(response.getFields().terms("tags"), tags.subList((numTerms - i - 1), numTerms));
}
}
public void testFilterTermFreq() throws ExecutionException, InterruptedException, IOException {
logger.info("Setting up the index ...");
Settings.Builder settings = Settings.builder()
.put(indexSettings())
.put("index.analysis.analyzer", "keyword");
assertAcked(prepareCreate("test")
.setSettings(settings)
.addMapping("type1", "tags", "type=text"));
logger.info("Indexing one document with tags of increasing frequencies ...");
int numTerms = scaledRandomIntBetween(10, 50);
List<String> tags = new ArrayList<>();
List<String> uniqueTags = new ArrayList<>();
String tag;
for (int i = 0; i < numTerms; i++) {
tag = "tag_" + i;
tags.add(tag);
for (int j = 0; j < i; j++) {
tags.add(tag);
}
uniqueTags.add(tag);
}
indexRandom(true, client().prepareIndex("test", "type1", "1").setSource("tags", tags));
logger.info("Checking best tags by highest to lowest term freq ...");
TermVectorsRequest.FilterSettings filterSettings = new TermVectorsRequest.FilterSettings();
TermVectorsResponse response;
for (int i = 0; i < numTerms; i++) {
filterSettings.maxNumTerms = i + 1;
response = client().prepareTermVectors("test", "type1", "1")
.setSelectedFields("tags")
.setFieldStatistics(true)
.setTermStatistics(true)
.setFilterSettings(filterSettings)
.get();
checkBestTerms(response.getFields().terms("tags"), uniqueTags.subList((numTerms - i - 1), numTerms));
}
}
public void testFilterDocFreq() throws ExecutionException, InterruptedException, IOException {
logger.info("Setting up the index ...");
Settings.Builder settings = Settings.builder()
.put(indexSettings())
.put("index.analysis.analyzer", "keyword")
.put("index.number_of_shards", 1); // no dfs
assertAcked(prepareCreate("test")
.setSettings(settings)
.addMapping("type1", "tags", "type=text"));
int numDocs = scaledRandomIntBetween(10, 50); // as many terms as there are docs
logger.info("Indexing {} documents with tags of increasing dfs ...", numDocs);
List<IndexRequestBuilder> builders = new ArrayList<>();
List<String> tags = new ArrayList<>();
for (int i = 0; i < numDocs; i++) {
tags.add("tag_" + i);
builders.add(client().prepareIndex("test", "type1", i + "").setSource("tags", tags));
}
indexRandom(true, builders);
logger.info("Checking best terms by highest to lowest idf ...");
TermVectorsRequest.FilterSettings filterSettings = new TermVectorsRequest.FilterSettings();
TermVectorsResponse response;
for (int i = 0; i < numDocs; i++) {
filterSettings.maxNumTerms = i + 1;
response = client().prepareTermVectors("test", "type1", (numDocs - 1) + "")
.setSelectedFields("tags")
.setFieldStatistics(true)
.setTermStatistics(true)
.setFilterSettings(filterSettings)
.get();
checkBestTerms(response.getFields().terms("tags"), tags.subList((numDocs - i - 1), numDocs));
}
}
public void testArtificialDocWithPreference() throws ExecutionException, InterruptedException, IOException {
// setup indices
Settings.Builder settings = Settings.builder()
.put(indexSettings())
.put("index.analysis.analyzer", "standard");
assertAcked(prepareCreate("test")
.setSettings(settings)
.addMapping("type1", "field1", "type=text,term_vector=with_positions_offsets"));
ensureGreen();
// index document
indexRandom(true, client().prepareIndex("test", "type1", "1").setSource("field1", "random permutation"));
// Get search shards
ClusterSearchShardsResponse searchShardsResponse = client().admin().cluster().prepareSearchShards("test").get();
List<Integer> shardIds = Arrays.stream(searchShardsResponse.getGroups()).map(s -> s.getShardId().id()).collect(Collectors.toList());
// request termvectors of artificial document from each shard
int sumTotalTermFreq = 0;
int sumDocFreq = 0;
for (Integer shardId : shardIds) {
TermVectorsResponse tvResponse = client().prepareTermVectors()
.setIndex("test")
.setType("type1")
.setPreference("_shards:" + shardId)
.setDoc(jsonBuilder().startObject().field("field1", "random permutation").endObject())
.setFieldStatistics(true)
.setTermStatistics(true)
.get();
Fields fields = tvResponse.getFields();
Terms terms = fields.terms("field1");
assertNotNull(terms);
TermsEnum termsEnum = terms.iterator();
while (termsEnum.next() != null) {
sumTotalTermFreq += termsEnum.totalTermFreq();
sumDocFreq += termsEnum.docFreq();
}
}
assertEquals("expected to find term statistics in exactly one shard!", 2, sumTotalTermFreq);
assertEquals("expected to find term statistics in exactly one shard!", 2, sumDocFreq);
}
public void testWithKeywordAndNormalizer() throws IOException, ExecutionException, InterruptedException {
// setup indices
String[] indexNames = new String[] {"with_tv", "without_tv"};
Settings.Builder builder = Settings.builder()
.put(indexSettings())
.put("index.analysis.analyzer.my_analyzer.tokenizer", "keyword")
.putList("index.analysis.analyzer.my_analyzer.filter", "lowercase")
.putList("index.analysis.normalizer.my_normalizer.filter", "lowercase");
assertAcked(prepareCreate(indexNames[0]).setSettings(builder.build())
.addMapping("type1", "field1", "type=text,term_vector=with_positions_offsets,analyzer=my_analyzer",
"field2", "type=text,term_vector=with_positions_offsets,analyzer=keyword"));
assertAcked(prepareCreate(indexNames[1]).setSettings(builder.build())
.addMapping("type1", "field1", "type=keyword,normalizer=my_normalizer", "field2", "type=keyword"));
ensureGreen();
// index documents with and without term vectors
String[] content = new String[] { "Hello World", "hello world", "HELLO WORLD" };
List<IndexRequestBuilder> indexBuilders = new ArrayList<>();
for (String indexName : indexNames) {
for (int id = 0; id < content.length; id++) {
indexBuilders.add(client().prepareIndex()
.setIndex(indexName)
.setType("type1")
.setId(String.valueOf(id))
.setSource("field1", content[id], "field2", content[id]));
}
}
indexRandom(true, indexBuilders);
// request tvs and compare from each index
for (int id = 0; id < content.length; id++) {
Fields[] fields = new Fields[2];
for (int j = 0; j < indexNames.length; j++) {
TermVectorsResponse resp = client().prepareTermVector(indexNames[j], "type1", String.valueOf(id))
.setOffsets(true)
.setPositions(true)
.setSelectedFields("field1", "field2")
.get();
assertThat("doc with index: " + indexNames[j] + ", type1 and id: " + id, resp.isExists(), equalTo(true));
fields[j] = resp.getFields();
}
compareTermVectors("field1", fields[0], fields[1]);
compareTermVectors("field2", fields[0], fields[1]);
}
}
private void checkBestTerms(Terms terms, List<String> expectedTerms) throws IOException {
final TermsEnum termsEnum = terms.iterator();
List<String> bestTerms = new ArrayList<>();
BytesRef text;
while((text = termsEnum.next()) != null) {
bestTerms.add(text.utf8ToString());
}
Collections.sort(expectedTerms);
Collections.sort(bestTerms);
assertArrayEquals(expectedTerms.toArray(), bestTerms.toArray());
}
}
| apache-2.0 |
vorce/es-metrics | src/main/java/org/elasticsearch/action/suggest/SuggestAction.java | 1505 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.suggest;
import org.elasticsearch.action.Action;
import org.elasticsearch.client.Client;
import org.elasticsearch.search.suggest.Suggest;
/**
*/
public class SuggestAction extends Action<SuggestRequest, SuggestResponse, SuggestRequestBuilder> {
public static final SuggestAction INSTANCE = new SuggestAction();
public static final String NAME = "suggest";
private SuggestAction() {
super(NAME);
}
@Override
public SuggestResponse newResponse() {
return new SuggestResponse(new Suggest());
}
@Override
public SuggestRequestBuilder newRequestBuilder(Client client) {
return new SuggestRequestBuilder(client);
}
}
| apache-2.0 |
adimania/kubernetes | Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/accounts/delegate_test.go | 794 | package accounts
import (
"testing"
os "github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts"
th "github.com/rackspace/gophercloud/testhelper"
fake "github.com/rackspace/gophercloud/testhelper/client"
)
func TestGetAccounts(t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()
os.HandleGetAccountSuccessfully(t)
options := &UpdateOpts{Metadata: map[string]string{"gophercloud-test": "accounts"}}
res := Update(fake.ServiceClient(), options)
th.CheckNoErr(t, res.Err)
}
func TestUpdateAccounts(t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()
os.HandleUpdateAccountSuccessfully(t)
expected := map[string]string{"Foo": "bar"}
actual, err := Get(fake.ServiceClient()).ExtractMetadata()
th.CheckNoErr(t, err)
th.CheckDeepEquals(t, expected, actual)
}
| apache-2.0 |
jkotas/roslyn | src/Compilers/Core/Portable/SymbolDisplay/AbstractSymbolDisplayVisitor.cs | 11226 | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SymbolDisplay
{
internal abstract partial class AbstractSymbolDisplayVisitor : SymbolVisitor
{
protected readonly ArrayBuilder<SymbolDisplayPart> builder;
protected readonly SymbolDisplayFormat format;
protected readonly bool isFirstSymbolVisited;
protected readonly SemanticModel semanticModelOpt;
protected readonly int positionOpt;
private AbstractSymbolDisplayVisitor _lazyNotFirstVisitor;
protected AbstractSymbolDisplayVisitor(
ArrayBuilder<SymbolDisplayPart> builder,
SymbolDisplayFormat format,
bool isFirstSymbolVisited,
SemanticModel semanticModelOpt,
int positionOpt)
{
Debug.Assert(format != null);
this.builder = builder;
this.format = format;
this.isFirstSymbolVisited = isFirstSymbolVisited;
this.semanticModelOpt = semanticModelOpt;
this.positionOpt = positionOpt;
// If we're not the first symbol visitor, then we will just recurse into ourselves.
if (!isFirstSymbolVisited)
{
_lazyNotFirstVisitor = this;
}
}
protected AbstractSymbolDisplayVisitor NotFirstVisitor
{
get
{
if (_lazyNotFirstVisitor == null)
{
_lazyNotFirstVisitor = MakeNotFirstVisitor();
}
return _lazyNotFirstVisitor;
}
}
protected abstract AbstractSymbolDisplayVisitor MakeNotFirstVisitor();
protected abstract void AddLiteralValue(SpecialType type, object value);
protected abstract void AddExplicitlyCastedLiteralValue(INamedTypeSymbol namedType, SpecialType type, object value);
protected abstract void AddSpace();
protected abstract void AddBitwiseOr();
/// <summary>
/// Append a default argument (i.e. the default argument of an optional parameter).
/// Assumed to be non-null.
/// </summary>
protected void AddNonNullConstantValue(ITypeSymbol type, object constantValue, bool preferNumericValueOrExpandedFlagsForEnum = false)
{
Debug.Assert(constantValue != null);
if (type.TypeKind == TypeKind.Enum)
{
AddEnumConstantValue((INamedTypeSymbol)type, constantValue, preferNumericValueOrExpandedFlagsForEnum);
}
else
{
AddLiteralValue(type.SpecialType, constantValue);
}
}
private void AddEnumConstantValue(INamedTypeSymbol enumType, object constantValue, bool preferNumericValueOrExpandedFlags)
{
// Code copied from System.Enum
var isFlagsEnum = IsFlagsEnum(enumType);
if (isFlagsEnum)
{
AddFlagsEnumConstantValue(enumType, constantValue, preferNumericValueOrExpandedFlags);
}
else if (preferNumericValueOrExpandedFlags)
{
// This isn't a flags enum, so just add the numeric value.
AddLiteralValue(enumType.EnumUnderlyingType.SpecialType, constantValue);
}
else
{
// Try to see if its one of the enum values. If so, add that. Otherwise, just add
// the literal value of the enum.
AddNonFlagsEnumConstantValue(enumType, constantValue);
}
}
/// <summary>
/// Check if the given type is an enum with System.FlagsAttribute.
/// </summary>
/// <remarks>
/// TODO: Can/should this be done using WellKnownAttributes?
/// </remarks>
private static bool IsFlagsEnum(ITypeSymbol typeSymbol)
{
Debug.Assert(typeSymbol != null);
if (typeSymbol.TypeKind != TypeKind.Enum)
{
return false;
}
foreach (var attribute in typeSymbol.GetAttributes())
{
var ctor = attribute.AttributeConstructor;
if (ctor != null)
{
var type = ctor.ContainingType;
if (!ctor.Parameters.Any() && type.Name == "FlagsAttribute")
{
var containingSymbol = type.ContainingSymbol;
if (containingSymbol.Kind == SymbolKind.Namespace &&
containingSymbol.Name == "System" &&
((INamespaceSymbol)containingSymbol.ContainingSymbol).IsGlobalNamespace)
{
return true;
}
}
}
}
return false;
}
private void AddFlagsEnumConstantValue(INamedTypeSymbol enumType, object constantValue, bool preferNumericValueOrExpandedFlags)
{
// These values are sorted by value. Don't change this.
var allFieldsAndValues = ArrayBuilder<EnumField>.GetInstance();
GetSortedEnumFields(enumType, allFieldsAndValues);
var usedFieldsAndValues = ArrayBuilder<EnumField>.GetInstance();
try
{
AddFlagsEnumConstantValue(enumType, constantValue, allFieldsAndValues, usedFieldsAndValues, preferNumericValueOrExpandedFlags);
}
finally
{
allFieldsAndValues.Free();
usedFieldsAndValues.Free();
}
}
private void AddFlagsEnumConstantValue(
INamedTypeSymbol enumType, object constantValue,
ArrayBuilder<EnumField> allFieldsAndValues,
ArrayBuilder<EnumField> usedFieldsAndValues,
bool preferNumericValueOrExpandedFlags)
{
var underlyingSpecialType = enumType.EnumUnderlyingType.SpecialType;
var constantValueULong = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(constantValue, underlyingSpecialType);
var result = constantValueULong;
// We will not optimize this code further to keep it maintainable. There are some
// boundary checks that can be applied to minimize the comparisons required. This code
// works the same for the best/worst case. In general the number of items in an enum are
// sufficiently small and not worth the optimization.
if (result != 0)
{
foreach (EnumField fieldAndValue in allFieldsAndValues)
{
var valueAtIndex = fieldAndValue.Value;
// In the case that we prefer a numeric value or expanded flags, we don't want to add the
// field matching this precise value because we'd rather see the constituent parts.
if (preferNumericValueOrExpandedFlags && valueAtIndex == constantValueULong)
{
continue;
}
if (valueAtIndex != 0 && (result & valueAtIndex) == valueAtIndex)
{
usedFieldsAndValues.Add(fieldAndValue);
result -= valueAtIndex;
if (result == 0) break;
}
}
}
// We were able to represent this number as a bitwise or of valid flags.
if (result == 0 && usedFieldsAndValues.Count > 0)
{
// We want to emit the fields in lower to higher value. So we walk backward.
for (int i = usedFieldsAndValues.Count - 1; i >= 0; i--)
{
if (i != (usedFieldsAndValues.Count - 1))
{
AddSpace();
AddBitwiseOr();
AddSpace();
}
((IFieldSymbol)usedFieldsAndValues[i].IdentityOpt).Accept(this.NotFirstVisitor);
}
}
else
{
// We couldn't find fields to OR together to make the value.
if (preferNumericValueOrExpandedFlags)
{
AddLiteralValue(underlyingSpecialType, constantValue);
return;
}
// If we had 0 as the value, and there's an enum value equal to 0, then use that.
var zeroField = constantValueULong == 0
? EnumField.FindValue(allFieldsAndValues, 0)
: default(EnumField);
if (!zeroField.IsDefault)
{
((IFieldSymbol)zeroField.IdentityOpt).Accept(this.NotFirstVisitor);
}
else
{
// Add anything else in as a literal value.
AddExplicitlyCastedLiteralValue(enumType, underlyingSpecialType, constantValue);
}
}
}
private static void GetSortedEnumFields(
INamedTypeSymbol enumType,
ArrayBuilder<EnumField> enumFields)
{
var underlyingSpecialType = enumType.EnumUnderlyingType.SpecialType;
foreach (var member in enumType.GetMembers())
{
if (member.Kind == SymbolKind.Field)
{
var field = (IFieldSymbol)member;
if (field.HasConstantValue)
{
var enumField = new EnumField(field.Name, EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(field.ConstantValue, underlyingSpecialType), field);
enumFields.Add(enumField);
}
}
}
enumFields.Sort(EnumField.Comparer);
}
private void AddNonFlagsEnumConstantValue(INamedTypeSymbol enumType, object constantValue)
{
var underlyingSpecialType = enumType.EnumUnderlyingType.SpecialType;
var constantValueULong = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(constantValue, underlyingSpecialType);
var enumFields = ArrayBuilder<EnumField>.GetInstance();
GetSortedEnumFields(enumType, enumFields);
// See if there's a member with this value. If so, then use that.
var match = EnumField.FindValue(enumFields, constantValueULong);
if (!match.IsDefault)
{
((IFieldSymbol)match.IdentityOpt).Accept(this.NotFirstVisitor);
}
else
{
// Otherwise, just add the enum as a literal.
AddExplicitlyCastedLiteralValue(enumType, underlyingSpecialType, constantValue);
}
enumFields.Free();
}
}
}
| apache-2.0 |
chetanmeh/jackrabbit-oak | oak-core/src/test/java/org/apache/jackrabbit/oak/security/user/UserImporterMembershipBesteffortTest.java | 1882 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.security.user;
import com.google.common.collect.ImmutableList;
import org.apache.jackrabbit.oak.spi.xml.ImportBehavior;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class UserImporterMembershipBesteffortTest extends UserImporterMembershipIgnoreTest {
@Override
String getImportBehavior() {
return ImportBehavior.NAME_BESTEFFORT;
}
@Test
public void testUnknownMember() throws Exception {
importer.startChildInfo(createNodeInfo("memberRef", NT_REP_MEMBER_REFERENCES), ImmutableList.of(createPropInfo(REP_MEMBERS, unknownContentId)));
importer.processReferences();
assertTrue(groupTree.hasProperty(REP_MEMBERS));
}
@Test
public void testMixedMembers() throws Exception {
importer.startChildInfo(createNodeInfo("memberRef", NT_REP_MEMBER_REFERENCES), ImmutableList.of(createPropInfo(REP_MEMBERS, unknownContentId, knownMemberContentId)));
importer.processReferences();
assertTrue(groupTree.hasProperty(REP_MEMBERS));
}
} | apache-2.0 |
weswigham/TypeScript | tests/cases/fourslash/completionAfterAtChar.ts | 118 | /// <reference path='fourslash.ts'/>
////@a/**/
verify.completions({ marker: "", exact: completion.globals });
| apache-2.0 |
dongjoon-hyun/elasticsearch | modules/lang-painless/src/main/java/org/elasticsearch/painless/node/ELambda.java | 10387 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.painless.node;
import org.elasticsearch.painless.Definition.Type;
import org.elasticsearch.painless.Locals;
import org.elasticsearch.painless.Locals.Variable;
import org.elasticsearch.painless.Location;
import org.elasticsearch.painless.MethodWriter;
import org.elasticsearch.painless.Definition.Method;
import org.elasticsearch.painless.node.SFunction.FunctionReserved;
import org.elasticsearch.painless.Definition;
import org.elasticsearch.painless.FunctionRef;
import org.elasticsearch.painless.Globals;
import org.objectweb.asm.Opcodes;
import java.lang.invoke.LambdaMetafactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import static org.elasticsearch.painless.WriterConstants.LAMBDA_BOOTSTRAP_HANDLE;
/**
* Lambda expression node.
* <p>
* This can currently only be the direct argument of a call (method/constructor).
* When the argument is of a known type, it uses
* <a href="http://cr.openjdk.java.net/~briangoetz/lambda/lambda-translation.html">
* Java's lambda translation</a>. However, if its a def call, then we don't have
* enough information, and have to defer this until link time. In that case a placeholder
* and all captures are pushed onto the stack and folded into the signature of the parent call.
* <p>
* For example:
* <br>
* {@code def list = new ArrayList(); int capture = 0; list.sort((x,y) -> x - y + capture)}
* <br>
* is converted into a call (pseudocode) such as:
* <br>
* {@code sort(list, lambda$0, capture)}
* <br>
* At link time, when we know the interface type, this is decomposed with MethodHandle
* combinators back into (pseudocode):
* <br>
* {@code sort(list, lambda$0(capture))}
*/
public final class ELambda extends AExpression implements ILambda {
private final String name;
private final FunctionReserved reserved;
private final List<String> paramTypeStrs;
private final List<String> paramNameStrs;
private final List<AStatement> statements;
// desugared synthetic method (lambda body)
private SFunction desugared;
// captured variables
private List<Variable> captures;
// static parent, static lambda
private FunctionRef ref;
// dynamic parent, deferred until link time
private String defPointer;
public ELambda(String name, FunctionReserved reserved,
Location location, List<String> paramTypes, List<String> paramNames,
List<AStatement> statements) {
super(location);
this.name = Objects.requireNonNull(name);
this.reserved = Objects.requireNonNull(reserved);
this.paramTypeStrs = Collections.unmodifiableList(paramTypes);
this.paramNameStrs = Collections.unmodifiableList(paramNames);
this.statements = Collections.unmodifiableList(statements);
}
@Override
void extractVariables(Set<String> variables) {
for (AStatement statement : statements) {
statement.extractVariables(variables);
}
}
@Override
void analyze(Locals locals) {
final Type returnType;
final List<String> actualParamTypeStrs;
Method interfaceMethod;
// inspect the target first, set interface method if we know it.
if (expected == null) {
interfaceMethod = null;
// we don't know anything: treat as def
returnType = Definition.DEF_TYPE;
// don't infer any types
actualParamTypeStrs = paramTypeStrs;
} else {
// we know the method statically, infer return type and any unknown/def types
interfaceMethod = expected.struct.getFunctionalMethod();
if (interfaceMethod == null) {
throw createError(new IllegalArgumentException("Cannot pass lambda to [" + expected.name +
"], not a functional interface"));
}
// check arity before we manipulate parameters
if (interfaceMethod.arguments.size() != paramTypeStrs.size())
throw new IllegalArgumentException("Incorrect number of parameters for [" + interfaceMethod.name +
"] in [" + expected.clazz + "]");
// for method invocation, its allowed to ignore the return value
if (interfaceMethod.rtn == Definition.VOID_TYPE) {
returnType = Definition.DEF_TYPE;
} else {
returnType = interfaceMethod.rtn;
}
// replace any def types with the actual type (which could still be def)
actualParamTypeStrs = new ArrayList<String>();
for (int i = 0; i < paramTypeStrs.size(); i++) {
String paramType = paramTypeStrs.get(i);
if (paramType.equals(Definition.DEF_TYPE.name)) {
actualParamTypeStrs.add(interfaceMethod.arguments.get(i).name);
} else {
actualParamTypeStrs.add(paramType);
}
}
}
// gather any variables used by the lambda body first.
Set<String> variables = new HashSet<>();
for (AStatement statement : statements) {
statement.extractVariables(variables);
}
// any of those variables defined in our scope need to be captured
captures = new ArrayList<>();
for (String variable : variables) {
if (locals.hasVariable(variable)) {
captures.add(locals.getVariable(location, variable));
}
}
// prepend capture list to lambda's arguments
List<String> paramTypes = new ArrayList<>();
List<String> paramNames = new ArrayList<>();
for (Variable var : captures) {
paramTypes.add(var.type.name);
paramNames.add(var.name);
}
paramTypes.addAll(actualParamTypeStrs);
paramNames.addAll(paramNameStrs);
// desugar lambda body into a synthetic method
desugared = new SFunction(reserved, location, returnType.name, name,
paramTypes, paramNames, statements, true);
desugared.generateSignature();
desugared.analyze(Locals.newLambdaScope(locals.getProgramScope(), returnType, desugared.parameters,
captures.size(), reserved.getMaxLoopCounter()));
// setup method reference to synthetic method
if (expected == null) {
ref = null;
actual = Definition.getType("String");
defPointer = "Sthis." + name + "," + captures.size();
} else {
defPointer = null;
try {
ref = new FunctionRef(expected, interfaceMethod, desugared.method, captures.size());
} catch (IllegalArgumentException e) {
throw createError(e);
}
actual = expected;
}
}
@Override
void write(MethodWriter writer, Globals globals) {
writer.writeDebugInfo(location);
if (ref != null) {
writer.writeDebugInfo(location);
// load captures
for (Variable capture : captures) {
writer.visitVarInsn(capture.type.type.getOpcode(Opcodes.ILOAD), capture.getSlot());
}
// convert MethodTypes to asm Type for the constant pool.
String invokedType = ref.invokedType.toMethodDescriptorString();
org.objectweb.asm.Type samMethodType =
org.objectweb.asm.Type.getMethodType(ref.samMethodType.toMethodDescriptorString());
org.objectweb.asm.Type interfaceType =
org.objectweb.asm.Type.getMethodType(ref.interfaceMethodType.toMethodDescriptorString());
if (ref.needsBridges()) {
writer.invokeDynamic(ref.invokedName,
invokedType,
LAMBDA_BOOTSTRAP_HANDLE,
samMethodType,
ref.implMethodASM,
samMethodType,
LambdaMetafactory.FLAG_BRIDGES,
1,
interfaceType);
} else {
writer.invokeDynamic(ref.invokedName,
invokedType,
LAMBDA_BOOTSTRAP_HANDLE,
samMethodType,
ref.implMethodASM,
samMethodType,
0);
}
} else {
// placeholder
writer.push((String)null);
// load captures
for (Variable capture : captures) {
writer.visitVarInsn(capture.type.type.getOpcode(Opcodes.ILOAD), capture.getSlot());
}
}
// add synthetic method to the queue to be written
globals.addSyntheticMethod(desugared);
}
@Override
public String getPointer() {
return defPointer;
}
@Override
public org.objectweb.asm.Type[] getCaptures() {
org.objectweb.asm.Type[] types = new org.objectweb.asm.Type[captures.size()];
for (int i = 0; i < types.length; i++) {
types[i] = captures.get(i).type.type;
}
return types;
}
}
| apache-2.0 |
enj/origin | vendor/google.golang.org/genproto/googleapis/ads/googleads/v0/enums/criterion_type.pb.go | 10354 | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/ads/googleads/v0/enums/criterion_type.proto
package enums // import "google.golang.org/genproto/googleapis/ads/googleads/v0/enums"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
// Enum describing possible criterion types.
type CriterionTypeEnum_CriterionType int32
const (
// Not specified.
CriterionTypeEnum_UNSPECIFIED CriterionTypeEnum_CriterionType = 0
// Used for return value only. Represents value unknown in this version.
CriterionTypeEnum_UNKNOWN CriterionTypeEnum_CriterionType = 1
// Keyword. e.g. 'mars cruise'.
CriterionTypeEnum_KEYWORD CriterionTypeEnum_CriterionType = 2
// Placement, aka Website. e.g. 'www.flowers4sale.com'
CriterionTypeEnum_PLACEMENT CriterionTypeEnum_CriterionType = 3
// Mobile application categories to target.
CriterionTypeEnum_MOBILE_APP_CATEGORY CriterionTypeEnum_CriterionType = 4
// Devices to target.
CriterionTypeEnum_DEVICE CriterionTypeEnum_CriterionType = 6
// Locations to target.
CriterionTypeEnum_LOCATION CriterionTypeEnum_CriterionType = 7
// Listing groups to target.
CriterionTypeEnum_LISTING_GROUP CriterionTypeEnum_CriterionType = 8
// Ad Schedule.
CriterionTypeEnum_AD_SCHEDULE CriterionTypeEnum_CriterionType = 9
// Age range.
CriterionTypeEnum_AGE_RANGE CriterionTypeEnum_CriterionType = 10
// Gender.
CriterionTypeEnum_GENDER CriterionTypeEnum_CriterionType = 11
// Income Range.
CriterionTypeEnum_INCOME_RANGE CriterionTypeEnum_CriterionType = 12
// Parental status.
CriterionTypeEnum_PARENTAL_STATUS CriterionTypeEnum_CriterionType = 13
// YouTube Video.
CriterionTypeEnum_YOUTUBE_VIDEO CriterionTypeEnum_CriterionType = 14
// YouTube Channel.
CriterionTypeEnum_YOUTUBE_CHANNEL CriterionTypeEnum_CriterionType = 15
// User list.
CriterionTypeEnum_USER_LIST CriterionTypeEnum_CriterionType = 16
// Proximity.
CriterionTypeEnum_PROXIMITY CriterionTypeEnum_CriterionType = 17
// A topic target on the display network (e.g. "Pets & Animals").
CriterionTypeEnum_TOPIC CriterionTypeEnum_CriterionType = 18
// Listing scope to target.
CriterionTypeEnum_LISTING_SCOPE CriterionTypeEnum_CriterionType = 19
// Language.
CriterionTypeEnum_LANGUAGE CriterionTypeEnum_CriterionType = 20
// IpBlock.
CriterionTypeEnum_IP_BLOCK CriterionTypeEnum_CriterionType = 21
// Content Label for category exclusion.
CriterionTypeEnum_CONTENT_LABEL CriterionTypeEnum_CriterionType = 22
// Carrier.
CriterionTypeEnum_CARRIER CriterionTypeEnum_CriterionType = 23
// A category the user is interested in.
CriterionTypeEnum_USER_INTEREST CriterionTypeEnum_CriterionType = 24
// Webpage criterion for dynamic search ads.
CriterionTypeEnum_WEBPAGE CriterionTypeEnum_CriterionType = 25
// Operating system version.
CriterionTypeEnum_OPERATING_SYSTEM_VERSION CriterionTypeEnum_CriterionType = 26
// App payment model.
CriterionTypeEnum_APP_PAYMENT_MODEL CriterionTypeEnum_CriterionType = 27
)
var CriterionTypeEnum_CriterionType_name = map[int32]string{
0: "UNSPECIFIED",
1: "UNKNOWN",
2: "KEYWORD",
3: "PLACEMENT",
4: "MOBILE_APP_CATEGORY",
6: "DEVICE",
7: "LOCATION",
8: "LISTING_GROUP",
9: "AD_SCHEDULE",
10: "AGE_RANGE",
11: "GENDER",
12: "INCOME_RANGE",
13: "PARENTAL_STATUS",
14: "YOUTUBE_VIDEO",
15: "YOUTUBE_CHANNEL",
16: "USER_LIST",
17: "PROXIMITY",
18: "TOPIC",
19: "LISTING_SCOPE",
20: "LANGUAGE",
21: "IP_BLOCK",
22: "CONTENT_LABEL",
23: "CARRIER",
24: "USER_INTEREST",
25: "WEBPAGE",
26: "OPERATING_SYSTEM_VERSION",
27: "APP_PAYMENT_MODEL",
}
var CriterionTypeEnum_CriterionType_value = map[string]int32{
"UNSPECIFIED": 0,
"UNKNOWN": 1,
"KEYWORD": 2,
"PLACEMENT": 3,
"MOBILE_APP_CATEGORY": 4,
"DEVICE": 6,
"LOCATION": 7,
"LISTING_GROUP": 8,
"AD_SCHEDULE": 9,
"AGE_RANGE": 10,
"GENDER": 11,
"INCOME_RANGE": 12,
"PARENTAL_STATUS": 13,
"YOUTUBE_VIDEO": 14,
"YOUTUBE_CHANNEL": 15,
"USER_LIST": 16,
"PROXIMITY": 17,
"TOPIC": 18,
"LISTING_SCOPE": 19,
"LANGUAGE": 20,
"IP_BLOCK": 21,
"CONTENT_LABEL": 22,
"CARRIER": 23,
"USER_INTEREST": 24,
"WEBPAGE": 25,
"OPERATING_SYSTEM_VERSION": 26,
"APP_PAYMENT_MODEL": 27,
}
func (x CriterionTypeEnum_CriterionType) String() string {
return proto.EnumName(CriterionTypeEnum_CriterionType_name, int32(x))
}
func (CriterionTypeEnum_CriterionType) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_criterion_type_1788cefd19f0a90c, []int{0, 0}
}
// The possible types of a criterion.
type CriterionTypeEnum struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *CriterionTypeEnum) Reset() { *m = CriterionTypeEnum{} }
func (m *CriterionTypeEnum) String() string { return proto.CompactTextString(m) }
func (*CriterionTypeEnum) ProtoMessage() {}
func (*CriterionTypeEnum) Descriptor() ([]byte, []int) {
return fileDescriptor_criterion_type_1788cefd19f0a90c, []int{0}
}
func (m *CriterionTypeEnum) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_CriterionTypeEnum.Unmarshal(m, b)
}
func (m *CriterionTypeEnum) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_CriterionTypeEnum.Marshal(b, m, deterministic)
}
func (dst *CriterionTypeEnum) XXX_Merge(src proto.Message) {
xxx_messageInfo_CriterionTypeEnum.Merge(dst, src)
}
func (m *CriterionTypeEnum) XXX_Size() int {
return xxx_messageInfo_CriterionTypeEnum.Size(m)
}
func (m *CriterionTypeEnum) XXX_DiscardUnknown() {
xxx_messageInfo_CriterionTypeEnum.DiscardUnknown(m)
}
var xxx_messageInfo_CriterionTypeEnum proto.InternalMessageInfo
func init() {
proto.RegisterType((*CriterionTypeEnum)(nil), "google.ads.googleads.v0.enums.CriterionTypeEnum")
proto.RegisterEnum("google.ads.googleads.v0.enums.CriterionTypeEnum_CriterionType", CriterionTypeEnum_CriterionType_name, CriterionTypeEnum_CriterionType_value)
}
func init() {
proto.RegisterFile("google/ads/googleads/v0/enums/criterion_type.proto", fileDescriptor_criterion_type_1788cefd19f0a90c)
}
var fileDescriptor_criterion_type_1788cefd19f0a90c = []byte{
// 557 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x52, 0xdd, 0x4e, 0x1b, 0x3d,
0x10, 0xfd, 0x48, 0xbe, 0xf2, 0x63, 0x48, 0x99, 0x98, 0x52, 0xe8, 0x0f, 0x17, 0xf0, 0x00, 0x9b,
0xa8, 0xbd, 0xdb, 0x5e, 0x79, 0xbd, 0xd3, 0xc5, 0x62, 0x63, 0x5b, 0x5e, 0x6f, 0x68, 0xaa, 0x48,
0x16, 0x25, 0xd1, 0x0a, 0x09, 0xb2, 0x51, 0x16, 0x90, 0x78, 0x9d, 0x5e, 0xf6, 0x51, 0xfa, 0x02,
0x7d, 0x84, 0x4a, 0x95, 0xfa, 0x0e, 0x95, 0x77, 0x9b, 0xa8, 0x5c, 0xb4, 0x37, 0xd6, 0x78, 0xce,
0x99, 0x39, 0xe3, 0xf1, 0x21, 0x6f, 0x8a, 0xb2, 0x2c, 0xae, 0xa7, 0xbd, 0x8b, 0x49, 0xd5, 0x6b,
0x42, 0x1f, 0xdd, 0xf7, 0x7b, 0xd3, 0xd9, 0xdd, 0x4d, 0xd5, 0xbb, 0x5c, 0x5c, 0xdd, 0x4e, 0x17,
0x57, 0xe5, 0xcc, 0xdd, 0x3e, 0xcc, 0xa7, 0xc1, 0x7c, 0x51, 0xde, 0x96, 0xf4, 0xa8, 0x21, 0x06,
0x17, 0x93, 0x2a, 0x58, 0xd5, 0x04, 0xf7, 0xfd, 0xa0, 0xae, 0x39, 0xf9, 0xd9, 0x26, 0x5d, 0xbe,
0xac, 0xb3, 0x0f, 0xf3, 0x29, 0xce, 0xee, 0x6e, 0x4e, 0xbe, 0xb5, 0x49, 0xe7, 0x51, 0x96, 0xee,
0x92, 0xed, 0x5c, 0x66, 0x1a, 0xb9, 0x78, 0x2f, 0x30, 0x86, 0xff, 0xe8, 0x36, 0xd9, 0xc8, 0xe5,
0x99, 0x54, 0xe7, 0x12, 0xd6, 0xfc, 0xe5, 0x0c, 0x47, 0xe7, 0xca, 0xc4, 0xd0, 0xa2, 0x1d, 0xb2,
0xa5, 0x53, 0xc6, 0x71, 0x80, 0xd2, 0x42, 0x9b, 0x1e, 0x90, 0xbd, 0x81, 0x8a, 0x44, 0x8a, 0x8e,
0x69, 0xed, 0x38, 0xb3, 0x98, 0x28, 0x33, 0x82, 0xff, 0x29, 0x21, 0xeb, 0x31, 0x0e, 0x05, 0x47,
0x58, 0xa7, 0x3b, 0x64, 0x33, 0x55, 0x9c, 0x59, 0xa1, 0x24, 0x6c, 0xd0, 0x2e, 0xe9, 0xa4, 0x22,
0xb3, 0x42, 0x26, 0x2e, 0x31, 0x2a, 0xd7, 0xb0, 0xe9, 0xf5, 0x59, 0xec, 0x32, 0x7e, 0x8a, 0x71,
0x9e, 0x22, 0x6c, 0x79, 0x15, 0x96, 0xa0, 0x33, 0x4c, 0x26, 0x08, 0xc4, 0x37, 0x4b, 0x50, 0xc6,
0x68, 0x60, 0x9b, 0x02, 0xd9, 0x11, 0x92, 0xab, 0xc1, 0x12, 0xdd, 0xa1, 0x7b, 0x64, 0x57, 0x33,
0x83, 0xd2, 0xb2, 0xd4, 0x65, 0x96, 0xd9, 0x3c, 0x83, 0x8e, 0x57, 0x19, 0xa9, 0xdc, 0xe6, 0x11,
0xba, 0xa1, 0x88, 0x51, 0xc1, 0x53, 0xcf, 0x5b, 0xa6, 0xf8, 0x29, 0x93, 0x12, 0x53, 0xd8, 0xf5,
0x4a, 0x79, 0x86, 0xc6, 0xf9, 0x91, 0x00, 0xea, 0xe7, 0x19, 0xf5, 0x41, 0x0c, 0x84, 0x1d, 0x41,
0x97, 0x6e, 0x91, 0x27, 0x56, 0x69, 0xc1, 0x81, 0xfe, 0x39, 0x76, 0xc6, 0x95, 0x46, 0xd8, 0xab,
0xdf, 0xc5, 0x64, 0x92, 0xb3, 0x04, 0xe1, 0x99, 0xbf, 0x09, 0xed, 0xa2, 0x54, 0xf1, 0x33, 0xd8,
0xf7, 0x74, 0xae, 0xa4, 0x45, 0x69, 0x5d, 0xca, 0x22, 0x4c, 0xe1, 0xb9, 0xdf, 0x23, 0x67, 0xc6,
0x08, 0x34, 0x70, 0xe0, 0xf1, 0x5a, 0x57, 0x48, 0x8b, 0x06, 0x33, 0x0b, 0x87, 0x1e, 0x3f, 0xc7,
0x48, 0xfb, 0x6e, 0x2f, 0xe8, 0x6b, 0x72, 0xa8, 0x34, 0x1a, 0xd6, 0x08, 0x8e, 0x32, 0x8b, 0x03,
0x37, 0x44, 0x93, 0xf9, 0x1d, 0xbe, 0xa4, 0xfb, 0xa4, 0xeb, 0xf7, 0xad, 0xd9, 0xc8, 0xff, 0x83,
0x1b, 0xa8, 0x18, 0x53, 0x78, 0x15, 0x7d, 0x5f, 0x23, 0xc7, 0x97, 0xe5, 0x4d, 0xf0, 0x4f, 0x57,
0x44, 0xf4, 0xd1, 0xe7, 0x6b, 0x6f, 0x24, 0xbd, 0xf6, 0x31, 0xfa, 0x5d, 0x54, 0x94, 0xd7, 0x17,
0xb3, 0x22, 0x28, 0x17, 0x45, 0xaf, 0x98, 0xce, 0x6a, 0x9b, 0x2d, 0xed, 0x38, 0xbf, 0xaa, 0xfe,
0xe2, 0xce, 0x77, 0xf5, 0xf9, 0xb9, 0xd5, 0x4e, 0x18, 0xfb, 0xd2, 0x3a, 0x4a, 0x9a, 0x56, 0x6c,
0x52, 0x05, 0x4d, 0xe8, 0xa3, 0x61, 0x3f, 0xf0, 0xf6, 0xab, 0xbe, 0x2e, 0xf1, 0x31, 0x9b, 0x54,
0xe3, 0x15, 0x3e, 0x1e, 0xf6, 0xc7, 0x35, 0xfe, 0xa3, 0x75, 0xdc, 0x24, 0xc3, 0x90, 0x4d, 0xaa,
0x30, 0x5c, 0x31, 0xc2, 0x70, 0xd8, 0x0f, 0xc3, 0x9a, 0xf3, 0x69, 0xbd, 0x1e, 0xec, 0xed, 0xaf,
0x00, 0x00, 0x00, 0xff, 0xff, 0xfb, 0x3e, 0x82, 0x01, 0x35, 0x03, 0x00, 0x00,
}
| apache-2.0 |
SlimRoms/android_external_chromium_org | cc/test/pixel_test_utils.cc | 2143 | // 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 "cc/test/pixel_test_utils.h"
#include <string>
#include <vector>
#include "base/file_util.h"
#include "base/logging.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/codec/png_codec.h"
namespace cc {
bool WritePNGFile(const SkBitmap& bitmap, const base::FilePath& file_path,
bool discard_transparency) {
std::vector<unsigned char> png_data;
if (gfx::PNGCodec::EncodeBGRASkBitmap(bitmap,
discard_transparency,
&png_data) &&
base::CreateDirectory(file_path.DirName())) {
char* data = reinterpret_cast<char*>(&png_data[0]);
int size = static_cast<int>(png_data.size());
return base::WriteFile(file_path, data, size) == size;
}
return false;
}
bool ReadPNGFile(const base::FilePath& file_path, SkBitmap* bitmap) {
DCHECK(bitmap);
std::string png_data;
return base::ReadFileToString(file_path, &png_data) &&
gfx::PNGCodec::Decode(reinterpret_cast<unsigned char*>(&png_data[0]),
png_data.length(),
bitmap);
}
bool MatchesPNGFile(const SkBitmap& gen_bmp, base::FilePath ref_img_path,
const PixelComparator& comparator) {
SkBitmap ref_bmp;
if (!ReadPNGFile(ref_img_path, &ref_bmp)) {
LOG(ERROR) << "Cannot read reference image: " << ref_img_path.value();
return false;
}
// Check if images size matches
if (gen_bmp.width() != ref_bmp.width() ||
gen_bmp.height() != ref_bmp.height()) {
LOG(ERROR)
<< "Dimensions do not match! "
<< "Actual: " << gen_bmp.width() << "x" << gen_bmp.height()
<< "; "
<< "Expected: " << ref_bmp.width() << "x" << ref_bmp.height();
return false;
}
// Shortcut for empty images. They are always equal.
if (gen_bmp.width() == 0 || gen_bmp.height() == 0)
return true;
return comparator.Compare(gen_bmp, ref_bmp);
}
} // namespace cc
| bsd-3-clause |
cuheguevara/zendframework2 | library/Zend/I18n/Translator/Plural/Parser.php | 9694 | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @package Zend_I18n
*/
namespace Zend\I18n\Translator\Plural;
use Zend\I18n\Exception;
/**
* Plural rule parser.
*
* This plural rule parser is implemented after the article "Top Down Operator
* Precedence" described in <http://javascript.crockford.com/tdop/tdop.html>.
*
* @category Zend
* @package Zend_I18n
* @subpackage Translator
*/
class Parser
{
/**
* String to parse.
*
* @var string
*/
protected $string;
/**
* Current lexer position in the string.
*
* @var integer
*/
protected $currentPos;
/**
* Current token.
*
* @var Symbol
*/
protected $currentToken;
/**
* Table of symbols.
*
* @var array
*/
protected $symbolTable = array();
/**
* Create a new plural parser.
*
*/
public function __construct()
{
$this->populateSymbolTable();
}
/**
* Populate the symbol table.
*
* @return void
*/
protected function populateSymbolTable()
{
// Ternary operators
$this->registerSymbol('?', 20)->setLeftDenotationGetter(
function (Symbol $self, Symbol $left) {
$self->first = $left;
$self->second = $self->parser->expression();
$self->parser->advance(':');
$self->third = $self->parser->expression();
return $self;
}
);
$this->registerSymbol(':');
// Boolean operators
$this->registerLeftInfixSymbol('||', 30);
$this->registerLeftInfixSymbol('&&', 40);
// Equal operators
$this->registerLeftInfixSymbol('==', 50);
$this->registerLeftInfixSymbol('!=', 50);
// Compare operators
$this->registerLeftInfixSymbol('>', 50);
$this->registerLeftInfixSymbol('<', 50);
$this->registerLeftInfixSymbol('>=', 50);
$this->registerLeftInfixSymbol('<=', 50);
// Add operators
$this->registerLeftInfixSymbol('-', 60);
$this->registerLeftInfixSymbol('+', 60);
// Multiply operators
$this->registerLeftInfixSymbol('*', 70);
$this->registerLeftInfixSymbol('/', 70);
$this->registerLeftInfixSymbol('%', 70);
// Not operator
$this->registerPrefixSymbol('!', 80);
// Literals
$this->registerSymbol('n')->setNullDenotationGetter(
function (Symbol $self) {
return $self;
}
);
$this->registerSymbol('number')->setNullDenotationGetter(
function (Symbol $self) {
return $self;
}
);
// Parentheses
$this->registerSymbol('(')->setNullDenotationGetter(
function (Symbol $self) {
$expression = $self->parser->expression();
$self->parser->advance(')');
return $expression;
}
);
$this->registerSymbol(')');
// Eof
$this->registerSymbol('eof');
}
/**
* Register a left infix symbol.
*
* @param string $id
* @param integer $leftBindingPower
* @return void
*/
protected function registerLeftInfixSymbol($id, $leftBindingPower)
{
$this->registerSymbol($id, $leftBindingPower)->setLeftDenotationGetter(
function (Symbol $self, Symbol $left) use ($leftBindingPower) {
$self->first = $left;
$self->second = $self->parser->expression($leftBindingPower);
return $self;
}
);
}
/**
* Register a right infix symbol.
*
* @param string $id
* @param integer $leftBindingPower
* @return void
*/
protected function registerRightInfixSymbol($id, $leftBindingPower)
{
$this->registerSymbol($id, $leftBindingPower)->setLeftDenotationGetter(
function (Symbol $self, Symbol $left) use ($leftBindingPower) {
$self->first = $left;
$self->second = $self->parser->expression($leftBindingPower - 1);
return $self;
}
);
}
/**
* Register a prefix symbol.
*
* @param string $id
* @param integer $leftBindingPower
* @return void
*/
protected function registerPrefixSymbol($id, $leftBindingPower)
{
$this->registerSymbol($id, $leftBindingPower)->setNullDenotationGetter(
function (Symbol $self) use ($leftBindingPower) {
$self->first = $self->parser->expression($leftBindingPower);
$self->second = null;
return $self;
}
);
}
/**
* Register a symbol.
*
* @param string $id
* @param integer $leftBindingPower
* @return Symbol
*/
protected function registerSymbol($id, $leftBindingPower = 0)
{
if (isset($this->symbolTable[$id])) {
$symbol = $this->symbolTable[$id];
$symbol->leftBindingPower = max(
$symbol->leftBindingPower,
$leftBindingPower
);
} else {
$symbol = new Symbol($this, $id, $leftBindingPower);
$this->symbolTable[$id] = $symbol;
}
return $symbol;
}
/**
* Get a new symbol.
*
* @param string $id
*/
protected function getSymbol($id)
{
if (!isset($this->symbolTable[$id])) {
// Unkown symbol exception
}
return clone $this->symbolTable[$id];
}
/**
* Parse a string.
*
* @param string $string
* @return array
*/
public function parse($string)
{
$this->string = $string . "\0";
$this->currentPos = 0;
$this->currentToken = $this->getNextToken();
return $this->expression();
}
/**
* Parse an expression.
*
* @param integer $rightBindingPower
* @return Symbol
*/
public function expression($rightBindingPower = 0)
{
$token = $this->currentToken;
$this->currentToken = $this->getNextToken();
$left = $token->getNullDenotation();
while ($rightBindingPower < $this->currentToken->leftBindingPower) {
$token = $this->currentToken;
$this->currentToken = $this->getNextToken();
$left = $token->getLeftDenotation($left);
}
return $left;
}
/**
* Advance the current token and optionally check the old token id.
*
* @param string $id
* @return void
* @throws Exception\ParseException
*/
public function advance($id = null)
{
if ($id !== null && $this->currentToken->id !== $id) {
throw new Exception\ParseException(sprintf(
'Expected token with id %s but received %s',
$id, $this->currentToken->id
));
}
$this->currentToken = $this->getNextToken();
}
/**
* Get the next token.
*
* @return array
* @throws Exception\ParseException
*/
protected function getNextToken()
{
$token = array();
while ($this->string[$this->currentPos] === ' ' || $this->string[$this->currentPos] === "\t") {
$this->currentPos++;
}
$result = $this->string[$this->currentPos++];
$value = null;
switch ($result) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
while (ctype_digit($this->string[$this->currentPos])) {
$result .= $this->string[$this->currentPos++];
}
$id = 'number';
$value = (int) $result;
break;
case '=':
case '&':
case '|':
if ($this->string[$this->currentPos] === $result) {
$this->currentPos++;
$id = $result . $result;
} else {
// Yield error
}
break;
case '!':
case '<':
case '>':
if ($this->string[$this->currentPos] === '=') {
$this->currentPos++;
$result .= '=';
}
$id = $result;
break;
case '*':
case '/':
case '%':
case '+':
case '-':
case 'n':
case '?':
case ':':
case '(':
case ')':
$id = $result;
break;
case ';':
case "\n":
case "\0":
$id = 'eof';
$this->currentPos--;
break;
default:
throw new Exception\ParseException(sprintf(
'Found invalid character "%s" in input stream',
$result
));
break;
}
$token = $this->getSymbol($id);
$token->value = $value;
return $token;
}
}
| bsd-3-clause |
biplobice/concrete5 | concrete/src/Permission/Key/CalendarKey.php | 81 | <?php
namespace Concrete\Core\Permission\Key;
class CalendarKey extends Key
{
}
| mit |
pcclarke/civ-techs | node_modules/renderkid/lib/tools.js | 2597 | // Generated by CoffeeScript 1.9.3
var htmlparser, object, objectToDom, self;
htmlparser = require('htmlparser2');
object = require('utila').object;
objectToDom = require('dom-converter').objectToDom;
module.exports = self = {
repeatString: function(str, times) {
var i, j, output, ref;
output = '';
for (i = j = 0, ref = times; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
output += str;
}
return output;
},
toDom: function(subject) {
if (typeof subject === 'string') {
return self.stringToDom(subject);
} else if (object.isBareObject(subject)) {
return self._objectToDom(subject);
} else {
throw Error("tools.toDom() only supports strings and objects");
}
},
stringToDom: function(string) {
var handler, parser;
handler = new htmlparser.DomHandler;
parser = new htmlparser.Parser(handler);
parser.write(string);
parser.end();
return handler.dom;
},
_fixQuotesInDom: function(input) {
var j, len, node;
if (Array.isArray(input)) {
for (j = 0, len = input.length; j < len; j++) {
node = input[j];
self._fixQuotesInDom(node);
}
return input;
}
node = input;
if (node.type === 'text') {
return node.data = self._quoteNodeText(node.data);
} else {
return self._fixQuotesInDom(node.children);
}
},
objectToDom: function(o) {
if (!Array.isArray(o)) {
if (!object.isBareObject(o)) {
throw Error("objectToDom() only accepts a bare object or an array");
}
}
return self._fixQuotesInDom(objectToDom(o));
},
quote: function(str) {
return String(str).replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"').replace(/\ /g, '&sp;').replace(/\n/g, '<br />');
},
_quoteNodeText: function(text) {
return String(text).replace(/\&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"').replace(/\ /g, '&sp;').replace(/\n/g, "&nl;");
},
getCols: function() {
var cols, tty;
tty = require('tty');
cols = (function() {
try {
if (tty.isatty(1) && tty.isatty(2)) {
if (process.stdout.getWindowSize) {
return process.stdout.getWindowSize(1)[0];
} else if (tty.getWindowSize) {
return tty.getWindowSize()[1];
} else if (process.stdout.columns) {
return process.stdout.columns;
}
}
} catch (_error) {}
})();
if (typeof cols === 'number' && cols > 30) {
return cols;
} else {
return 80;
}
}
};
| mit |
EdwardStudy/myghostblog | versions/1.25.7/core/server/apps/amp/lib/helpers/index.js | 462 | // Dirty require!
const ghostHead = require('../../../../helpers/ghost_head');
function registerAmpHelpers(ghost) {
ghost.helpers.registerAsync('amp_content', require('./amp_content'));
ghost.helpers.register('amp_components', require('./amp_components'));
// we use the {{ghost_head}} helper, but call it {{amp_ghost_head}}, so it's consistent
ghost.helpers.registerAsync('amp_ghost_head', ghostHead);
}
module.exports = registerAmpHelpers;
| mit |
zacblazic/wingtip-toys | WingtipToys/ProductList.aspx.designer.cs | 768 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WingtipToys {
public partial class ProductList {
/// <summary>
/// productList control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ListView productList;
}
}
| mit |
inbreak/java-design-patterns | fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterableTest.java | 1631 | /**
* The MIT License
* Copyright (c) 2014-2016 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.fluentinterface.fluentiterable.lazy;
import com.iluwatar.fluentinterface.fluentiterable.FluentIterable;
import com.iluwatar.fluentinterface.fluentiterable.FluentIterableTest;
/**
* Date: 12/12/15 - 7:56 PM
*
* @author Jeroen Meulemeester
*/
public class LazyFluentIterableTest extends FluentIterableTest {
@Override
protected FluentIterable<Integer> createFluentIterable(Iterable<Integer> integers) {
return LazyFluentIterable.from(integers);
}
}
| mit |
ericfennis/RUNCMD | app/system/languages/tr_TR/messages.php | 24013 | <?php return array (
25 => '25',
'Invalid Password.' => 'Şifre Geçersiz.',
'Permissions' => 'İzinler',
'Add Folder' => 'Klasör Ekle',
'Rename' => 'Yeniden Adlandır',
'Changelog' => 'Değişiklik günlüğü',
'Removed selected.' => 'Seçililer çıkarıldı.',
'Whoops, looks like something went wrong.' => 'Bir şeyler ters gitti gibi görünüyor.',
'Enable' => 'Etkinleştir',
'Manage media files' => 'Ortam dosyaları yönetimi',
'Update' => 'Güncelle',
'Next' => 'Sonraki',
'SMTP User' => 'SMTP Kullanıcısı',
'Hide in menu' => 'Menüde gizlensin',
'User Settings' => 'Kullanıcı Ayarları',
'Modified' => 'Son Değişiklik',
'Last registered' => 'Son kayıt olan',
'Welcome to %site%!' => '%site% sitesine hoşgeldiniz!',
'Check Connection' => 'Bağlantıyı Denetle',
'Invalid type.' => 'Tip geçersiz.',
'Poster Image' => 'Poster Görseli',
'Path' => 'Yol',
'Unable to upload.' => 'Yüklenemedi.',
'Value' => 'Değer',
'Username' => 'Kullanıcı Adı',
'Is your language not available? Please help out by translating Pagekit into your own language on %link%.' => 'Dilinizi bulamadınız mı? Pagekit çevirisine yardımcı olmak için %link% bağlantısına bakabilirsiniz. ',
'No Limit' => 'Sınırlama Yok',
'Code' => 'Kod',
'Positions' => 'Konumlar',
'Your user account has been created and is pending approval by the site administrator.' => 'Kullanıcı hesabınız oluşturuldu ve onaylanmak üzere site yöneticisine iletildi.',
'Invalid url.' => 'İnternet adresi geçersiz.',
'Remember Me' => 'Beni Hatırla',
'Info' => 'Bilgiler',
'Permission' => 'İzin',
'Database name cannot be blank.' => 'Veritabanı adı boş bırakılamaz.',
7 => '7',
'System' => 'Sistem',
'Unable to remove.' => 'Silinemedi.',
'Latest registered Users' => 'Son kayıt olan kullanıcılar',
'Approve an account at %site%.' => '%site% sitesindeki bir hesabı onaylayın.',
'Developer' => 'Geliştirici',
'Logo' => 'Logo',
'Cannot connect to the server. Please try again later.' => 'Sunucu ile bağlantı kurulamıyor. Lütfen bir süre sonra yeniden deneyin.',
'Install' => 'Yükle',
'Don\'t show' => 'Görüntülenmesin',
'Missing order data.' => 'Sıralama verisi eksik.',
'Warning: Give to trusted roles only; this permission has security implications.' => 'Uyarı: Yalnız güvendiğiniz kullanıcılara izin verin. Bu yetki güvenlikle ilgilidir.',
'Removing package folder.' => 'Paket klasörü siliniyor.',
'Offline' => 'Çevrimdışı',
'Add %type%' => '%type% ekle',
'User Login' => 'Oturum Açın',
'Confirm' => 'Onayla',
'Setup your site' => 'Sitenizi kurun',
'Apply system updates' => 'Sistem güncellemelerini uygula',
'Extensions' => 'Eklentiler',
'Uploaded file invalid. (%s)' => 'Yüklenen dosya geçersiz. (%s)',
'Forgot Password' => 'Parolamı Unuttum',
'Unable to send verification link.' => 'Doğrulama bağlantısı gönderilemedi.',
'Sub Items' => 'Alt Ögeler',
'Your database is up to date.' => 'Veritabanınız güncel.',
'User Registration' => 'Kayıt Olun',
'TLS' => 'TLS',
'Invalid key.' => 'Anahtar geçersiz.',
'Favicon' => 'Simge',
'Name cannot be blank.' => 'Ad boş bırakılamaz.',
'Roles' => 'Roller',
'Connection not established! (%s)' => 'Bağlantı kurulamadı! (%s)',
'Reset password' => 'Parolamı sıfırla',
'Database' => 'Veritabanı',
'Imperial' => 'İngiliz-Amerikan',
'Activate Account' => 'Hesabı Etkinleştir',
'Menu' => 'Menü',
'Message' => 'İleti',
'Add Widget' => 'Araç Ekle',
'None' => 'Yok',
'Visit Site' => 'Siteyi Ziyaret Et',
'Testemail' => 'Epostasina',
'URL' => 'İnternet adresi',
'Depth' => 'Derinlik',
'Invalid name.' => 'Ad geçersiz.',
'Selected' => 'Seçilmiş',
'Request password' => 'Parolamı Unuttum',
'Thank you for signing up for %site%. Just one more step! Please click the button below to activate your account.' => '%site% sitesine kayıt olduğunuz için teşekkür ederiz. Son adım olarak, hesabınızı etkinleştirmek için aşağıdaki düğmeye tıklayın.',
'Site Locale' => 'Site Dili',
'Session expired. Please log in again.' => 'Oturumunuzun süresi dolmuş. Lütfen yeniden oturum açın.',
'"%title%" enabled.' => '"%title%" etkin.',
'"%name%" has not been loaded.' => '"%name%" yüklenemedi.',
4 => '4',
'Type' => 'Tip',
'Manage extensions' => 'Eklenti yönetimi',
'Your account has been activated.' => 'Hesabınız etkinleştirildi.',
'Disable cache' => 'Önbelleği devre dışı bırak',
'Can\'t load json file from package.' => 'Paketteki json dosyası yüklenemedi.',
'Manage widgets' => 'Araç yönetimi',
'Hi %name%!' => 'Merhaba %name%!',
'Menu Title' => 'Menü Başlığı',
'Total Users' => 'Toplam Kullanıcı',
'Email address is invalid.' => 'E-posta adresi geçersiz.',
'Logout Redirect' => 'Oturum Kapatma Yönlendirmesi',
9 => '9',
'No pages found.' => 'Henüz bir sayfa yok.',
'Cache' => 'Önbellek',
'Pagekit %version% is available.' => 'Pagekit %version% sürümü yayınlanmış.',
'Choose a title and create the administrator account.' => 'Bir başık seçin ve yönetici hesabı oluşturun.',
'Database Name' => 'Veritabanı Adı',
'Number of Posts' => 'Yazıların Sayısı',
'All' => 'Tümü',
'Already have an account?' => 'Zaten bir hesabınız var mı?',
'Please enable the SQLite database extension.' => 'Lütfen SQLite veritabanı eklentisini etkinleştirin.',
'Enabled, but approval is required.' => 'Etkinleştirilmiş, ancak onay gerekli.',
'Description' => 'Açıklama',
'Logged in' => 'Oturum açıldı',
'Unknown' => 'Bilinmeyen',
'You have the latest version of Pagekit. You do not need to update. However, if you want to re-install version %version%, you can download the package and re-install manually.' => 'Son Pagekit sürümünü kullanıyorsunuz. Herhangi bir güncelleme gerekmiyor. Bununla birlikte %version% sürümünü yeniden yüklemek istiyorsanız, paketi indirip el ile yeniden yükleyebilirsiniz.',
'Reset' => 'Sıfırla',
'Height' => 'Yükseklik',
'Pagekit Version' => 'Pagekit Sürümü',
'A new user signed up for %site% with the username %username%. Please click the button below to approve the account.' => '%site% sitesinde, %username% kullanıcı adıyla yeni bir hesap açıldı. Lütfen hesabı onaylamak için aşağıdaki düğmeye tıklayın.',
'Dashboard' => 'Kontrol Paneli',
'Widget deleted.' => 'Araç silindi.',
'Access admin area' => 'Yönetim alanına erişim',
'New Password' => 'Yeni Şifre',
'Unable to rename.' => 'Yeniden adlandırılamadı.',
'Change password' => 'Şifre değiştir',
'password' => 'şifre',
'PHP Mailer' => 'PHP Postalayıcı',
3 => '3',
'There is an update available for the package.' => 'Paket için bir güncelleme yayınlanmış.',
'Select Cache to Clear' => 'Temizlenecek Önbellekleri Seçin',
'Add User' => 'Kullanıcı Ekle',
'(Currently set to: %menu%)' => '(Şu anda %menu% olarak ayarlı)',
'Pages' => 'Sayfa',
'%d TB' => '%d TB',
'Mail' => 'E-posta',
'{0} %count% Users|{1} %count% User|]1,Inf[ %count% Users' => '{0} %count% Kullanıcı|{1} %count% Kullanıcı|]1,Inf[ %count% Kullanıcı',
'Invalid id.' => 'Kod geçersiz.',
'Upload' => 'Yükle',
'Logout' => 'Çıkış',
'- Menu -' => '- Menü -',
'Storage' => 'Depolama',
'{1} %count% Widget moved|]1,Inf[ %count% Widgets moved' => '{1} %count% Araç silindi|]1,Inf[ %count% Araç silindi',
'User Logout' => 'Oturumu Kapat',
1 => '1',
'Reset Password' => 'Şifre Sıfırla',
'Duplicate Menu Id.' => 'Çift Menü Kodu.',
'Email:' => 'E-posta:',
'Enable debug mode' => 'Hata ayıklama kipi kullanılsın',
'Invalid file name.' => 'Dosya adı geçersiz.',
'Your account has not been activated.' => 'Hesabınız henüz etkinleştirilmemiş.',
'Hide' => 'Gizle',
'No theme found.' => 'Herhangi bir tema bulunamadı.',
'There is an update available.' => 'Bir güncelleme yayınlanmış.',
'Installing %title% %version%' => '%title% %version% yükleniyor...',
'Connection established!' => 'Bağlantı kuruldu!',
'Settings' => 'Ayarlar',
'Image' => 'Görsel',
'Request Password' => 'Parolamı Unuttum',
'Slug' => 'Kısaltma',
'Renamed.' => 'Yeniden adlandırıldı.',
'Url' => 'İnternet adresi',
'No Pagekit %type%' => 'Pagekit %type% yok',
'Hidden' => 'Gizli',
'Select Link' => 'Bağlantı Seçin',
'Display' => 'Görünüm',
'Show all' => 'Tümünü görüntüle',
'Title cannot be blank.' => 'Başlık boş bırakılamaz.',
'User cannot be blank.' => 'Kullanıcı adı boş bırakılamaz.',
'No Frontpage assigned.' => 'Herhangi bir önsayfa atanmamış.',
'Name required.' => 'Ad zorunludur.',
'Select Image' => 'Görsel Seçin',
'Password must be 6 characters or longer.' => 'Parola en az 6 karakter uzunluğunda olmalıdır.',
'Table Prefix' => 'Tablo Öneki',
'Node not found.' => 'Düğüm bulunamadı.',
'Send Test Email' => 'Sınama E-postası Gönder',
'Driver' => 'Sürücü',
'Muted' => 'Kısılmış',
'Last login' => 'Son oturum açma',
'Choose language' => 'Dili seçin',
'We got a request to reset your %site% password for %username%. If you ignore this message, your password won\'t be changed.' => ' %site% sitesindeki %username% hesap parolanızın sıfırlanması için bir istek aldık. Bu iletiyi göz ardı ederseniz, parolanız değiştirilmez.',
'Invalid slug.' => 'Kısaltma geçersiz.',
'Setting' => 'Ayar',
'No file uploaded.' => 'Karşıya bir dosya yüklenmedi.',
'Prefix must start with a letter and can only contain alphanumeric characters (A-Z, 0-9) and underscore (_)' => 'Ön ek bir harf ile başlamalıdır ve yalnız alfasayısal karakterler (A-Z, 0-9) ile alt çizgi karakteri (_) kullanılabilir.',
'Close' => 'Kapat',
'Latest logged in Users' => 'Son oturum açan kullanıcılar',
'List' => 'Liste',
'Invalid token. Please try again.' => 'Pinkodu geçersiz. Lütfen yeniden deneyin.',
'Homepage:' => 'Anasayfa:',
'Login Now' => 'Oturum Açın',
'Connect database' => 'Veritabanına bağlan',
'Show on all posts' => 'Tüm yazılarda görüntülensin',
'You may not call this step directly.' => 'Doğrudan bu adıma atlanamaz.',
'Folder already exists.' => 'Klasör zaten var.',
'Use the site in maintenance mode' => 'Site bakım kipine geçirilsin',
'Successfully removed.' => 'Silindi.',
'Access' => 'Erişim',
'{0} Registered Users|{1} Registered User|]1,Inf[ Registered Users' => '{0} Kayıtlı Kullanıcı|{1} Kayıtlı Kullanıcı|]1,Inf[ Kayıtlı Kullanıcı',
'Version %version%' => 'Sürüm %version%',
'Client' => 'İstemci',
'Enter a valid email address.' => 'Geçerli bir e-posta adresi yazın.',
'Folder Name' => 'Klasör Adı',
'Enter password.' => 'Şifrenizi yazın.',
'Unassigned' => 'Atanmamış',
'Password' => 'Şifre',
'Loop' => 'Çevrim',
'Installed' => 'Yüklü',
'_subset' => '_subset',
'Your account has not been activated or is blocked.' => 'Hesabınız etkinleştirilmemiş ya da engellenmiş.',
'Cannot obtain versions. Please try again later.' => 'Sürüm bilgileri alınamadı. Lütfen daha sonra yeniden deneyin.',
100 => '100',
'Invalid path.' => 'Geçersiz yol.',
'Your account is blocked.' => 'Hesabınız engellenmiş.',
'Thumbnail' => 'Küçük Görsel',
'Your Pagekit database has been updated successfully.' => 'Pagekit veritabanı güncellendi.',
'Whoops, something went wrong.' => 'Hay aksi, bir şeyler ters gitti.',
'Widgets reordered.' => 'Araçlar yeniden sıralandı.',
'Password required.' => 'Şifre zorunludur.',
'Manage themes' => 'Tema yönetimi',
'Enable Markdown' => 'Markdown Kullanılsın',
'%d MB' => '%d MB',
'Temporary Files' => 'Geçici Dosyalar',
'Mail delivery failed! (%s)' => 'E-posta gönderilemedi! (%s)',
'Username cannot be blank and may only contain alphanumeric characters (A-Z, 0-9) and some special characters ("._-")' => 'Kullanıcı adı boş bırakılamaz ve yalnız alfasayısal karakterler (A-Z, 0-9) ile bazı özel karakterler ("._-") kullanılabilir.',
'Error' => 'Hata',
'Please enter your email address. You will receive a link to create a new password via email.' => 'Lütfen e-posta adresinizi yazın. E-posta adresinize yeni parola oluşturma bağlantısını içeren bir ileti göndereceğiz.',
40 => '40',
'%d PB' => '%d PB',
'Web Server' => 'Web Sunucu',
'Hello!' => 'Merhaba!',
'Link' => 'Bağlantı',
'Restrict Access' => 'Erişimi Kısıtla',
'Trash' => 'Çöp',
'Password Confirmation' => 'Parola Onayı',
33 => '33',
'Email is invalid.' => 'E-posta geçersiz.',
'SMTP Mailer' => 'SMTP Postalayıcı',
'Unit' => 'Birim',
'Disabled' => 'Devre Dışı',
'Email not available.' => 'E-posta bulunamadı.',
'%d KB' => '%d KB',
'No account yet?' => 'Henüz hesabınız yok mu?',
'Account activation' => 'Hesap etkinleştirme',
'Add Page' => 'Sayfa Ekle',
'Host cannot be blank.' => 'Sunucu adı boş bırakılamaz.',
'Test email!' => 'E-postayı sına!',
'Manage user permissions' => 'Kullanıcı izinleri yönetimi',
'Database error: %error%' => 'Veritabanı hatası: %error%',
'SMTP Encryption' => 'SMTP Şifreleme',
'{1} %count% User selected|]1,Inf[ %count% Users selected' => '{1} %count% Kullanıcı seçildi|]1,Inf[ %count% Kullanıcı seçildi',
'Field must be a valid email address.' => 'Alanda geçerli bir e-posta adresi olmalıdır.',
'Approve Account' => 'Hesabı Onayla',
'Complete your registration by clicking the link provided in the mail that has been sent to you.' => 'Adresinize gönderilecek e-posta içindeki bağlantıya tıklayarak kayıt işleminizi tamamlayabilirsiniz.',
'Order saved.' => 'Sıralama kaydedildi.',
'Download %version%' => '%version% sürümünü indirin',
'Unwritable' => 'Yazılamaz',
'Title' => 'Başlık',
'Sign in to your account' => 'Hesabınıza oturum açın',
'Create an account' => 'Kayıt olun',
'User' => 'Kullanıcı',
'Password cannot be blank.' => 'Parola boş bırakılamaz.',
'Autoplay' => 'Otomatik Oynatma',
'Position' => 'Konum',
'Start Level' => 'Başlangıç Düzeyi',
'SMTP Host' => 'SMTP Sunucusu',
'Retry' => 'Yeniden Dene',
'n/a' => 'yok',
'SMTP Port' => 'SMTP Kapısı',
'Login' => 'Oturum Açın',
'Home' => 'Anasayfa',
'Reset Confirm' => 'Sıfırlamayı Onaylayın',
'Enabled' => 'Etkin',
'Unable to find "%name%".' => '"%name%" bulunamadı.',
'No widgets found.' => 'Herhangi bir araç bulunamadı.',
'Themes' => 'Temalar',
'%d Bytes' => '%d Bayt',
'Unable to block yourself.' => 'Kendinizi engelleyemezsiniz.',
'You do not have access to the administration area of this site.' => 'Bu sitenin yönetim bölümüne erişme izniniz yok.',
'{0} %count% Files|{1} %count% File|]1,Inf[ %count% Files' => '{0} %count% Dosya|{1} %count% Dosya|]1,Inf[ %count% Dosya',
'No location found.' => 'Herhangi bir konum seçilmemiş.',
'No URL given.' => 'İnternet adresi yazılmamış.',
5 => '5',
'Access system settings' => 'Sistem ayarlarına erişim',
'Folder' => 'Klasör',
'Check your email for the confirmation link.' => 'Doğrulama bağlantısı için e-postanızı denetleyin.',
'Enable debug toolbar' => 'Hata ayıklama araç çubuğu kullanılsın',
'Save' => 'Kaydet',
'We\'ll be back soon.' => 'Yakında döneceğiz.',
'Menus' => 'Menüler',
'Cancel' => 'İptal',
15 => '15',
'Select Video' => 'Görüntü Seçin',
'Version' => 'Sürüm',
'Database connection failed!' => 'Veritabanı ile bağlantı kurulamadı!',
'Current Password' => 'Geçerli Şifre',
'Number of Users' => 'Kullanıcı Sayısı',
'Directory created.' => 'Klasör oluşturuldu.',
'Alt' => 'Alt',
'Enter your database connection details.' => 'Veritabanı bağlantı bilgilerinizi yazın.',
'Writable' => 'Yazılabilir',
'Active' => 'Etkin',
'Add Role' => 'Rol Ekle',
'Support' => 'Destek',
'Registered since' => 'Kayıt tarihi',
'Manage menus' => 'Menü yönetimi',
'Successfully installed.' => 'Yüklendi.',
'Admin Locale' => 'Yönetim Dili',
'Removing %title% %version%' => '%title% %version% siliniyor',
'Menu Positions' => 'Menü Konumları',
'The user\'s account has been activated and the user has been notified about it.' => 'Kullanıcı hesabı etkinleştirildi ve kullanıcıya bilgilendirme e-postası gönderildi.',
'Marketplace' => 'Mağaza',
'%d GB' => '%d GB',
'{1} %count% Widget selected|]1,Inf[ %count% Widgets selected' => '{1} %count% Araç seçildi|]1,Inf[ %count% Araç seçildi',
'Invalid password.' => 'Şifre geçersiz.',
'Edit %type%' => '%type% düzenle',
'From Email' => 'Kimden E-posta Adresi',
'Put the site offline and show the offline message.' => 'Site çevrimdışı yapılarak çevrimdışı iletisi görüntülensin.',
'Cannot connect to the marketplace. Please try again later.' => 'Mağaza ile bağlantı kurulamadı. Lütfen bir süre sonra yeniden deneyin.',
'Insufficient User Rights.' => 'Kullanıcı İzinleri Yetersiz',
'Copy' => 'Kopyala',
'Upload complete.' => 'Karşıya yükleme tamamlandı.',
'Clear' => 'Temizle',
'Documentation' => 'Belgeler',
'Invalid Email.' => 'E-posta adresi geçersiz.',
'Extension' => 'Eklenti',
'Widgets' => 'Araçlar',
'Pages moved to %menu%.' => 'Sayfalar %menu% üzerine taşındı.',
'Database access denied!' => 'Veritabanına erişilemedi!',
'Controls' => 'Denetimler',
'Slow down a bit.' => 'Biraz yavaşlayın.',
'Require e-mail verification when a guest creates an account.' => 'Ziyaretçi bir hesap oluşturduğunda e-posta doğrulaması istenir.',
'%d ZB' => '%d ZB',
'Manage users' => 'Kullanıcı yönetimi',
'Pagekit Installer' => 'Pagekit Yükleyicisi',
'%d YB' => '%d YB',
'Login!' => 'Oturum Açın!',
'\'composer.json\' is missing.' => '\'composer.json\' eksik.',
'Clear Cache' => 'Önbelleği Temizle',
'PHP' => 'PHP',
'Show' => 'Göster',
'SMTP Password' => 'SMTP Parolası',
'No extension found.' => 'Herhangi bir eklenti bulunamadı.',
'Invalid username or password.' => 'Kullanıcı adı veya şifre geçersiz.',
'Location' => 'Konum',
'Header' => 'Üstbilgi',
'Sign up now' => 'Kayıt Olun',
'Users' => 'Kullanıcılar',
'Hi %username%' => 'Merhaba %username%',
'URL Alias' => 'İnternet Adresi Kısaltması',
50 => '50',
'Filter by' => 'Şuna göre süz',
'Username not available.' => 'Kullanıcı adı bulunamadı.',
'Add Video' => 'Görüntü Ekle',
'Existing Pagekit installation detected. Choose different table prefix?' => 'Varolan bir Pagekit kurulumu algılandı. Farklı bir tablo öneki seçmek ister misiniz?',
'View' => 'Görünüm',
'Login Redirect' => 'Oturum Açma Yönlendirmesi',
'General' => 'Genel',
'Pagekit has been updated! Before we send you on your way, we have to update your database to the newest version.' => 'Pagekit güncellendi. Kullanmaya başlamadan önce veritabanınızın da güncellenmesi gerekiyor. ',
'%d EB' => '%d EB',
6 => '6',
'- Assign -' => '- Ata -',
'Hostname' => 'Sunucu Adı',
'Unable to enable "%name%".' => '"%name%" etkinleştirilemedi.',
'Mailer' => 'Postalayıcı',
'User not found.' => 'Kullanıcı bulunamadı.',
'Unable to retrieve feed data.' => 'Akış verisi alınamadı.',
'Permission denied.' => 'İzin reddedildi.',
'Username is invalid.' => 'Kullanıcı adı geçersiz.',
'We\'re really happy to have you, %name%! Just login with the username %username%.' => 'Sizinle olmaktan gerçekten mutluyuz, %name%! Artık %username% kullanıcı adınız ile oturum açabilirsiniz.',
'Your email has been verified. Once an administrator approves your account, you will be notified by email.' => 'E-posta adresiniz doğrulandı. Hesabınız yönetici tarafından onaylandığında bir bilgilendirme e-postası alacaksınız.',
20 => '20',
'Package path is missing.' => 'Paket yolu eksik.',
'No files uploaded.' => 'Karşıya bir dosya yüklenemedi.',
'User Type' => 'Kullanıcı Tipi',
'Unable to delete yourself.' => 'Kendi kendinizi silemezsiniz.',
'User Agent' => 'Kullanıcı Aracısı',
8 => '8',
'Ok' => 'Tamam',
'No files found.' => 'Herhangi bir dosya bulunamadı.',
'Activate your %site% account.' => '%site% sitesindeki hesabınızı etkinleştirin.',
'Size' => 'Boyut',
'"composer.json" file not valid.' => '"composer.json" dosyası geçersiz.',
'License:' => 'Lisans:',
'Unable to create directory.' => 'Klasör oluşturulamadı.',
'Blocked' => 'Engellendi',
'Add Link' => 'Bağlantı Ekle',
'Metric' => 'Metrik',
'Only show on first post.' => 'Yalnız ilk yazıda görüntülensin.',
'Sign up' => 'Kayıt olun',
'"%title%" disabled.' => '"%title%" devre dışı.',
'Reset password for %site%.' => '%site% sitesindeki parolanızı sıfırlayın.',
10 => '10',
'Add Image' => 'Görsel Ekle',
'Post Content' => 'Yazı İçeriği',
'Unknown email address.' => 'E-posta adresi bilinmiyor.',
'Site Title' => 'Site Başlığı',
'Registration' => 'Kayıt',
'Mail successfully sent!' => 'E-posta gönderildi!',
'Status' => 'Durum',
'Maintenance' => 'Bakım',
'Built On' => 'Yapım',
'User Password Reset' => 'Kullanıcı Parolası Sıfırlama',
'Meta' => 'Üst Veri',
'username' => 'kullanıcı adı',
'Localization' => 'Yerelleştirme',
'Unable to activate "%name%".<br>A fatal error occured.' => '"%name%" etkinleştirilemedi.<br>Ciddi bir sorun çıktı.',
'Invalid node type.' => 'Düğüm tipi geçersiz.',
'{1} %count% File selected|]1,Inf[ %count% Files selected' => '{1} %count% Dosya seçildi|]1,Inf[ %count% Dosya seçildi',
'Demo' => 'Tanıtım',
'Select' => 'Seçin',
'Sign in' => 'Oturum Açın',
'Installation failed!' => 'Yüklenemedi!',
'%type% saved.' => '%type% kaydedildi.',
'Unable to send confirmation link.' => 'Doğrulama bağlantısı gönderilemedi.',
'Footer' => 'Altbilgi',
'Update Pagekit' => 'Pagekit Yazılımını Güncelle',
'From Name' => 'Kimden Adı',
'You have the latest version of Pagekit.' => 'Son Pagekit sürümünü kullanıyorsunuz.',
'Your password has been reset.' => 'Şifreniz sıfırlandı.',
'No database connection.' => 'Veritabanı bağlantısı yok.',
'Your user account has been created.' => 'Kullanıcı hesabınız oluşturuldu.',
'Appicon' => 'Uygulama Simgesi',
'Your Profile' => 'Profiliniz',
'File' => 'Dosya',
'SSL' => 'SSL',
'User Profile' => 'Kullanıcı Profili',
'Select your site language.' => 'Sitenizin dilini seçin.',
'Can\'t write config.' => 'Ayarlar dosyasına yazılamadı.',
'Insert code in the header and footer of your theme. This is useful for tracking codes and meta tags.' => 'Temanızın üstbilgi ve altbilgi alanına kod ekleyin. Bu kodlar sitenizi izlemek ve meta etiketlerini belirtmek için yararlıdır.',
'Width' => 'Genişlik',
'Site title cannot be blank.' => 'Site adı boş bırakılamaz.',
'{0} Logged in Users|{1} Logged in User|]1,Inf[ Logged in Users' => '{0} Kayıtlı Kullanıcı|{1} Kayıtlı Kullanıcı|]1,Inf[ Kayıtlı Kullanıcı',
'Show only for active item' => 'Yalnızca etkin öge için görüntüle',
'Verification' => 'Doğrulama',
'Handler' => 'İşleyici',
'Unauthorized' => 'İzinsiz',
'Email' => 'E-posta',
'New' => 'Yeni',
'Forgot Password?' => 'Şifremi Unuttum?',
'No user found.' => 'Hiç bir kullanıcı bulunamadı.',
'Mail delivery failed!' => 'E-posta gönderilemedi!',
'Add Menu' => 'Menü Ekle',
30 => '30',
2 => '2',
'Redirect' => 'Yönlendirme',
'Nothing found.' => 'Hiçbir şey bulunamadı.',
'System Cache' => 'Sistem Önbelleği',
'Edit User' => 'Kullanıcıyı Düzenle',
'Role not found.' => 'Rol bulunamadı.',
'Edit Widget' => 'Aracı Düzenle',
'Name' => 'Ad',
'Page not found.' => 'Sayfa bulunamadı.',
'Please enable the PHP Open SSL extension.' => 'Lütfen PHP Open SSL eklentisini etkinleştirin.',
); | mit |
iamnader/mongoid-2 | lib/mongoid/fields/serializable/time.rb | 624 | # encoding: utf-8
module Mongoid #:nodoc:
module Fields #:nodoc:
module Serializable #:nodoc:
# Defines the behaviour for date fields.
class Time
include Serializable
include Timekeeping
# When reading the field do we need to cast the value? This holds true when
# times are stored or for big decimals which are stored as strings.
#
# @example Typecast on a read?
# field.cast_on_read?
#
# @return [ true ] Date fields cast on read.
#
# @since 2.1.0
def cast_on_read?; true; end
end
end
end
end
| mit |
keygod/java-design-patterns | chain/src/main/java/com/iluwatar/chain/Request.java | 2976 | /**
* The MIT License
* Copyright (c) 2014-2016 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.chain;
import java.util.Objects;
/**
* Request
*/
public class Request {
/**
* The type of this request, used by each item in the chain to see if they should or can handle
* this particular request
*/
private final RequestType requestType;
/**
* A description of the request
*/
private final String requestDescription;
/**
* Indicates if the request is handled or not. A request can only switch state from unhandled to
* handled, there's no way to 'unhandle' a request
*/
private boolean handled;
/**
* Create a new request of the given type and accompanied description.
*
* @param requestType The type of request
* @param requestDescription The description of the request
*/
public Request(final RequestType requestType, final String requestDescription) {
this.requestType = Objects.requireNonNull(requestType);
this.requestDescription = Objects.requireNonNull(requestDescription);
}
/**
* Get a description of the request
*
* @return A human readable description of the request
*/
public String getRequestDescription() {
return requestDescription;
}
/**
* Get the type of this request, used by each person in the chain of command to see if they should
* or can handle this particular request
*
* @return The request type
*/
public RequestType getRequestType() {
return requestType;
}
/**
* Mark the request as handled
*/
public void markHandled() {
this.handled = true;
}
/**
* Indicates if this request is handled or not
*
* @return <tt>true</tt> when the request is handled, <tt>false</tt> if not
*/
public boolean isHandled() {
return this.handled;
}
@Override
public String toString() {
return getRequestDescription();
}
}
| mit |
webmasterersm/rsmsite | wp-content/plugins/advanced-custom-fields-pro/includes/fields/class-acf-field-true_false.php | 5282 | <?php
if( ! class_exists('acf_field_true_false') ) :
class acf_field_true_false extends acf_field {
/*
* __construct
*
* This function will setup the field type data
*
* @type function
* @date 5/03/2014
* @since 5.0.0
*
* @param n/a
* @return n/a
*/
function initialize() {
// vars
$this->name = 'true_false';
$this->label = __('True / False','acf');
$this->category = 'choice';
$this->defaults = array(
'default_value' => 0,
'message' => '',
'ui' => 0,
'ui_on_text' => '',
'ui_off_text' => '',
);
}
/*
* render_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function render_field( $field ) {
// vars
$input = array(
'type' => 'checkbox',
'id' => $field['id'],
'name' => $field['name'],
'value' => '1',
'class' => $field['class'],
'autocomplete' => 'off'
);
$hidden = array(
'name' => $field['name'],
'value' => 0
);
$active = $field['value'] ? true : false;
$switch = '';
// checked
if( $active ) $input['checked'] = 'checked';
// ui
if( $field['ui'] ) {
// vars
if( $field['ui_on_text'] === '' ) $field['ui_on_text'] = __('Yes', 'acf');
if( $field['ui_off_text'] === '' ) $field['ui_off_text'] = __('No', 'acf');
// update input
$input['class'] .= ' acf-switch-input';
//$input['style'] = 'display:none;';
$switch .= '<div class="acf-switch' . ($active ? ' -on' : '') . '">';
$switch .= '<span class="acf-switch-on">'.$field['ui_on_text'].'</span>';
$switch .= '<span class="acf-switch-off">'.$field['ui_off_text'].'</span>';
$switch .= '<div class="acf-switch-slider"></div>';
$switch .= '</div>';
}
?>
<div class="acf-true-false">
<?php acf_hidden_input($hidden); ?>
<label>
<input <?php echo acf_esc_attr($input); ?>/>
<?php if( $switch ) echo $switch; ?>
<?php if( $field['message'] ): ?><span><?php echo $field['message']; ?></span><?php endif; ?>
</label>
</div>
<?php
}
/*
* render_field_settings()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function render_field_settings( $field ) {
// message
acf_render_field_setting( $field, array(
'label' => __('Message','acf'),
'instructions' => __('Displays text alongside the checkbox','acf'),
'type' => 'text',
'name' => 'message',
));
// default_value
acf_render_field_setting( $field, array(
'label' => __('Default Value','acf'),
'instructions' => '',
'type' => 'true_false',
'name' => 'default_value',
));
// ui
acf_render_field_setting( $field, array(
'label' => __('Stylised UI','acf'),
'instructions' => '',
'type' => 'true_false',
'name' => 'ui',
'ui' => 1,
'class' => 'acf-field-object-true-false-ui'
));
// on_text
acf_render_field_setting( $field, array(
'label' => __('On Text','acf'),
'instructions' => __('Text shown when active','acf'),
'type' => 'text',
'name' => 'ui_on_text',
'placeholder' => __('Yes', 'acf')
));
// on_text
acf_render_field_setting( $field, array(
'label' => __('Off Text','acf'),
'instructions' => __('Text shown when inactive','acf'),
'type' => 'text',
'name' => 'ui_off_text',
'placeholder' => __('No', 'acf')
));
}
/*
* format_value()
*
* This filter is appied to the $value after it is loaded from the db and before it is returned to the template
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value (mixed) the value which was loaded from the database
* @param $post_id (mixed) the $post_id from which the value was loaded
* @param $field (array) the field array holding all the field options
*
* @return $value (mixed) the modified value
*/
function format_value( $value, $post_id, $field ) {
return empty($value) ? false : true;
}
/*
* validate_value
*
* description
*
* @type function
* @date 11/02/2014
* @since 5.0.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
function validate_value( $valid, $value, $field, $input ){
// bail early if not required
if( ! $field['required'] ) {
return $valid;
}
// value may be '0'
if( !$value ) {
return false;
}
// return
return $valid;
}
/*
* translate_field
*
* This function will translate field settings
*
* @type function
* @date 8/03/2016
* @since 5.3.2
*
* @param $field (array)
* @return $field
*/
function translate_field( $field ) {
// translate
$field['message'] = acf_translate( $field['message'] );
$field['ui_on_text'] = acf_translate( $field['ui_on_text'] );
$field['ui_off_text'] = acf_translate( $field['ui_off_text'] );
// return
return $field;
}
}
// initialize
acf_register_field_type( 'acf_field_true_false' );
endif; // class_exists check
?> | mit |
tal-m/capsule | capsule-util/src/test/java/co/paralleluniverse/capsule/JarTest.java | 23138 | /*
* Capsule
* Copyright (c) 2014-2015, Parallel Universe Software Co. and Contributors. All rights reserved.
*
* This program and the accompanying materials are licensed under the terms
* of the Eclipse Public License v1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package co.paralleluniverse.capsule;
import co.paralleluniverse.common.JarClassLoader;
import co.paralleluniverse.common.ZipFS;
import com.google.common.jimfs.Jimfs;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author pron
*/
public class JarTest {
@Test
public void testCreateJar() throws Exception {
ByteArrayOutputStream res = new Jar()
.setAttribute("Foo", "1234")
.setAttribute("Bar", "5678")
.addEntry(Paths.get("foo.txt"), Jar.toInputStream("I am foo!\n", UTF_8))
.addEntry(Paths.get("dir", "bar.txt"), Jar.toInputStream("I am bar!\n", UTF_8))
.write(new ByteArrayOutputStream());
// printEntries(toInput(res));
assertEquals("I am foo!\n", getEntryAsString(toInput(res), Paths.get("foo.txt"), UTF_8));
assertEquals("I am bar!\n", getEntryAsString(toInput(res), Paths.get("dir", "bar.txt"), UTF_8));
Manifest man2 = toInput(res).getManifest();
assertEquals("1234", man2.getMainAttributes().getValue("Foo"));
assertEquals("5678", man2.getMainAttributes().getValue("Bar"));
}
@Test
public void testUpdateJar() throws Exception {
FileSystem fs = Jimfs.newFileSystem();
Path jarPath = fs.getPath("test.jar");
try {
// create
new Jar()
.setAttribute("Foo", "1234")
.setAttribute("Bar", "5678")
.setListAttribute("List", Arrays.asList("a", "b"))
.setMapAttribute("Map", new HashMap<String, String>() {
{
put("x", "1");
put("y", "2");
}
})
.addEntry(Paths.get("foo.txt"), Jar.toInputStream("I am foo!\n", UTF_8))
.addEntry(Paths.get("dir", "bar.txt"), Jar.toInputStream("I am bar!\n", UTF_8))
.write(jarPath);
// update
Jar jar = new Jar(jarPath);
ByteArrayOutputStream res = jar
.setAttribute("Baz", "hi!")
.setAttribute("Bar", "8765")
.setListAttribute("List", addLast(addFirst(jar.getListAttribute("List"), "0"), "c"))
.setMapAttribute("Map", put(put(jar.getMapAttribute("Map", null), "z", "3"), "x", "0"))
.addEntry(Paths.get("dir", "baz.txt"), Jar.toInputStream("And I am baz!\n", UTF_8))
.write(new ByteArrayOutputStream());
// test
// printEntries(toInput(res));
assertEquals("I am foo!\n", getEntryAsString(toInput(res), Paths.get("foo.txt"), UTF_8));
assertEquals("I am bar!\n", getEntryAsString(toInput(res), Paths.get("dir", "bar.txt"), UTF_8));
assertEquals("And I am baz!\n", getEntryAsString(toInput(res), Paths.get("dir", "baz.txt"), UTF_8));
Manifest man2 = toInput(res).getManifest();
assertEquals("1234", man2.getMainAttributes().getValue("Foo"));
assertEquals("8765", man2.getMainAttributes().getValue("Bar"));
assertEquals("hi!", man2.getMainAttributes().getValue("Baz"));
assertEquals(Arrays.asList("0", "a", "b", "c"), new Jar(toInput(res)).getListAttribute("List"));
assertEquals(new HashMap<String, String>() {
{
put("x", "0");
put("y", "2");
put("z", "3");
}
}, new Jar(toInput(res)).getMapAttribute("Map", null));
} finally {
Files.delete(jarPath);
}
}
@Test
public void testUpdateJar2() throws Exception {
// create
ByteArrayOutputStream baos = new Jar()
.setAttribute("Foo", "1234")
.setAttribute("Bar", "5678")
.addEntry(Paths.get("foo.txt"), Jar.toInputStream("I am foo!\n", UTF_8))
.addEntry(Paths.get("dir", "bar.txt"), Jar.toInputStream("I am bar!\n", UTF_8))
.write(new ByteArrayOutputStream());
// update
ByteArrayOutputStream res = new Jar(toInput(baos))
.setAttribute("Baz", "hi!")
.setAttribute("Bar", "8765")
.addEntry(Paths.get("dir", "baz.txt"), Jar.toInputStream("And I am baz!\n", UTF_8))
.write(new ByteArrayOutputStream());
// test
// printEntries(toInput(res));
assertEquals("I am foo!\n", getEntryAsString(toInput(res), Paths.get("foo.txt"), UTF_8));
assertEquals("I am bar!\n", getEntryAsString(toInput(res), Paths.get("dir", "bar.txt"), UTF_8));
assertEquals("And I am baz!\n", getEntryAsString(toInput(res), Paths.get("dir", "baz.txt"), UTF_8));
Manifest man2 = toInput(res).getManifest();
assertEquals("1234", man2.getMainAttributes().getValue("Foo"));
assertEquals("8765", man2.getMainAttributes().getValue("Bar"));
assertEquals("hi!", man2.getMainAttributes().getValue("Baz"));
}
@Test
public void testUpdateJar3() throws Exception {
// create
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new Jar()
.setOutputStream(baos)
.setAttribute("Foo", "1234")
.setAttribute("Bar", "5678")
.addEntry(Paths.get("foo.txt"), Jar.toInputStream("I am foo!\n", UTF_8))
.addEntry(Paths.get("dir", "bar.txt"), Jar.toInputStream("I am bar!\n", UTF_8))
.close();
// update
ByteArrayOutputStream res = new Jar(toInput(baos))
.setAttribute("Baz", "hi!")
.setAttribute("Bar", "8765")
.addEntry(Paths.get("dir", "baz.txt"), Jar.toInputStream("And I am baz!\n", UTF_8))
.write(new ByteArrayOutputStream());
// test
// printEntries(toInput(res));
assertEquals("I am foo!\n", getEntryAsString(toInput(res), Paths.get("foo.txt"), UTF_8));
assertEquals("I am bar!\n", getEntryAsString(toInput(res), Paths.get("dir", "bar.txt"), UTF_8));
assertEquals("And I am baz!\n", getEntryAsString(toInput(res), Paths.get("dir", "baz.txt"), UTF_8));
Manifest man2 = toInput(res).getManifest();
assertEquals("1234", man2.getMainAttributes().getValue("Foo"));
assertEquals("8765", man2.getMainAttributes().getValue("Bar"));
assertEquals("hi!", man2.getMainAttributes().getValue("Baz"));
}
@Test
public void testAddDirectory1() throws Exception {
FileSystem fs = Jimfs.newFileSystem();
Path myDir = fs.getPath("dir1", "dir2");
Files.createDirectories(myDir.resolve("da"));
Files.createDirectories(myDir.resolve("db"));
Files.createFile(myDir.resolve("da").resolve("x"));
Files.createFile(myDir.resolve("da").resolve("y"));
Files.createFile(myDir.resolve("db").resolve("w"));
Files.createFile(myDir.resolve("db").resolve("z"));
ByteArrayOutputStream res = new Jar()
.setAttribute("Foo", "1234")
.addEntries((Path) null, myDir, Jar.notMatches("db/w"))
.write(new ByteArrayOutputStream());
// printEntries(toInput(res));
assertTrue(getEntry(toInput(res), Paths.get("da", "x")) != null);
assertTrue(getEntry(toInput(res), Paths.get("da", "y")) != null);
assertTrue(getEntry(toInput(res), Paths.get("db", "w")) == null);
assertTrue(getEntry(toInput(res), Paths.get("db", "z")) != null);
Manifest man2 = toInput(res).getManifest();
assertEquals("1234", man2.getMainAttributes().getValue("Foo"));
}
@Test
public void testAddDirectory2() throws Exception {
FileSystem fs = Jimfs.newFileSystem();
Path myDir = fs.getPath("dir1", "dir2");
Files.createDirectories(myDir.resolve("da"));
Files.createDirectories(myDir.resolve("db"));
Files.createFile(myDir.resolve("da").resolve("x"));
Files.createFile(myDir.resolve("da").resolve("y"));
Files.createFile(myDir.resolve("db").resolve("w"));
Files.createFile(myDir.resolve("db").resolve("z"));
ByteArrayOutputStream res = new Jar()
.setAttribute("Foo", "1234")
.addEntries(Paths.get("d1", "d2"), myDir, Jar.notMatches("d1/d2/db/w"))
.write(new ByteArrayOutputStream());
// printEntries(toInput(res));
assertTrue(getEntry(toInput(res), Paths.get("d1", "d2", "da", "x")) != null);
assertTrue(getEntry(toInput(res), Paths.get("d1", "d2", "da", "y")) != null);
assertTrue(getEntry(toInput(res), Paths.get("d1", "d2", "db", "w")) == null);
assertTrue(getEntry(toInput(res), Paths.get("d1", "d2", "db", "z")) != null);
Manifest man2 = toInput(res).getManifest();
assertEquals("1234", man2.getMainAttributes().getValue("Foo"));
}
@Test
public void testAddZip1() throws Exception {
FileSystem fs = Jimfs.newFileSystem();
Path myZip = fs.getPath("zip1");
new Jar().addEntry(Paths.get("foo.txt"), Jar.toInputStream("I am foo!\n", UTF_8))
.addEntry(Paths.get("dir", "bar.txt"), Jar.toInputStream("I am bar!\n", UTF_8))
.write(myZip);
ByteArrayOutputStream res = new Jar()
.setAttribute("Foo", "1234")
.addEntries((String) null, myZip)
.write(new ByteArrayOutputStream());
// printEntries(toInput(res));
assertEquals("I am foo!\n", getEntryAsString(toInput(res), Paths.get("foo.txt"), UTF_8));
assertEquals("I am bar!\n", getEntryAsString(toInput(res), Paths.get("dir", "bar.txt"), UTF_8));
Manifest man2 = toInput(res).getManifest();
assertEquals("1234", man2.getMainAttributes().getValue("Foo"));
}
@Test
public void testAddZip2() throws Exception {
FileSystem fs = Jimfs.newFileSystem();
Path myZip = fs.getPath("zip1");
new Jar().addEntry(Paths.get("foo.txt"), Jar.toInputStream("I am foo!\n", UTF_8))
.addEntry(Paths.get("dir", "bar.txt"), Jar.toInputStream("I am bar!\n", UTF_8))
.write(myZip);
ByteArrayOutputStream res = new Jar()
.setAttribute("Foo", "1234")
.addEntries(Paths.get("d1", "d2"), myZip)
.write(new ByteArrayOutputStream());
// printEntries(toInput(res));
assertEquals("I am foo!\n", getEntryAsString(toInput(res), Paths.get("d1", "d2", "foo.txt"), UTF_8));
assertEquals("I am bar!\n", getEntryAsString(toInput(res), Paths.get("d1", "d2", "dir", "bar.txt"), UTF_8));
Manifest man2 = toInput(res).getManifest();
assertEquals("1234", man2.getMainAttributes().getValue("Foo"));
}
@Test
public void testAddZip3() throws Exception {
ByteArrayOutputStream myZip = new Jar()
.addEntry(Paths.get("foo.txt"), Jar.toInputStream("I am foo!\n", UTF_8))
.addEntry(Paths.get("dir", "bar.txt"), Jar.toInputStream("I am bar!\n", UTF_8))
.write(new ByteArrayOutputStream());
ByteArrayOutputStream res = new Jar()
.setAttribute("Foo", "1234")
.addEntries((Path) null, toInput(myZip))
.write(new ByteArrayOutputStream());
// printEntries(toInput(res));
assertEquals("I am foo!\n", getEntryAsString(toInput(res), Paths.get("foo.txt"), UTF_8));
assertEquals("I am bar!\n", getEntryAsString(toInput(res), Paths.get("dir", "bar.txt"), UTF_8));
Manifest man2 = toInput(res).getManifest();
assertEquals("1234", man2.getMainAttributes().getValue("Foo"));
}
@Test
public void testAddZip4() throws Exception {
ByteArrayOutputStream myZip = new Jar()
.addEntry(Paths.get("foo.txt"), Jar.toInputStream("I am foo!\n", UTF_8))
.addEntry(Paths.get("dir", "bar.txt"), Jar.toInputStream("I am bar!\n", UTF_8))
.write(new ByteArrayOutputStream());
ByteArrayOutputStream res = new Jar()
.setAttribute("Foo", "1234")
.addEntries(Paths.get("d1", "d2"), toInput(myZip))
.write(new ByteArrayOutputStream());
// printEntries(toInput(res));
assertEquals("I am foo!\n", getEntryAsString(toInput(res), Paths.get("d1", "d2", "foo.txt"), UTF_8));
assertEquals("I am bar!\n", getEntryAsString(toInput(res), Paths.get("d1", "d2", "dir", "bar.txt"), UTF_8));
Manifest man2 = toInput(res).getManifest();
assertEquals("1234", man2.getMainAttributes().getValue("Foo"));
}
@Test
public void testAddPackage() throws Exception {
final Class clazz = JarClassLoader.class;
ByteArrayOutputStream res = new Jar()
.setAttribute("Foo", "1234")
.addPackageOf(clazz, new Jar.Filter() {
@Override
public boolean filter(String entryName) {
return !"co/paralleluniverse/common/FlexibleClassLoader.class".equals(entryName);
}
})
.write(new ByteArrayOutputStream());
// printEntries(toInput(res));
final Path pp = Paths.get(clazz.getPackage().getName().replace('.', '/'));
assertTrue(getEntry(toInput(res), pp.resolve(clazz.getSimpleName() + ".class")) != null);
assertTrue(getEntry(toInput(res), pp.resolve("ProcessUtil.class")) != null);
assertTrue(getEntry(toInput(res), pp.resolve("FlexibleClassLoader.class")) == null);
Manifest man2 = toInput(res).getManifest();
assertEquals("1234", man2.getMainAttributes().getValue("Foo"));
}
@Test
public void testAddPackage2() throws Exception {
FileSystem fs = Jimfs.newFileSystem();
Path jarPath = fs.getPath("test.jar");
final Class clazz = JarClassLoader.class;
new Jar().addPackageOf(clazz).write(jarPath);
ByteArrayOutputStream res = new Jar()
.setAttribute("Foo", "1234")
.addPackageOf(new JarClassLoader(jarPath, true).loadClass(clazz.getName()), new Jar.Filter() {
@Override
public boolean filter(String entryName) {
return !"co/paralleluniverse/common/FlexibleClassLoader.class".equals(entryName);
}
})
.write(new ByteArrayOutputStream());
// printEntries(toInput(res));
final Path pp = Paths.get(clazz.getPackage().getName().replace('.', '/'));
assertTrue(getEntry(toInput(res), pp.resolve(clazz.getSimpleName() + ".class")) != null);
assertTrue(getEntry(toInput(res), pp.resolve("ProcessUtil.class")) != null);
assertTrue(getEntry(toInput(res), pp.resolve("FlexibleClassLoader.class")) == null);
Manifest man2 = toInput(res).getManifest();
assertEquals("1234", man2.getMainAttributes().getValue("Foo"));
}
@Test
public void testReallyExecutableJar() throws Exception {
FileSystem fs = Jimfs.newFileSystem();
Path jarPath = fs.getPath("test.jar");
new Jar()
.setAttribute("Foo", "1234")
.setAttribute("Bar", "5678")
.setReallyExecutable(true)
.addEntry(Paths.get("foo.txt"), Jar.toInputStream("I am foo!\n", UTF_8))
.addEntry(Paths.get("dir", "bar.txt"), Jar.toInputStream("I am bar!\n", UTF_8))
.write(jarPath);
// printEntries(toInput(res));
BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(jarPath), UTF_8), 10); // Files.newBufferedReader(jarPath, UTF_8);
String firstLine = reader.readLine();
assertEquals("#!/bin/sh", firstLine);
}
@Test
public void testStringPrefix() throws Exception {
FileSystem fs = Jimfs.newFileSystem();
Path jarPath = fs.getPath("test.jar");
new Jar()
.setAttribute("Foo", "1234")
.setAttribute("Bar", "5678")
.setJarPrefix("I'm the prefix!")
.addEntry(Paths.get("foo.txt"), Jar.toInputStream("I am foo!\n", UTF_8))
.addEntry(Paths.get("dir", "bar.txt"), Jar.toInputStream("I am bar!\n", UTF_8))
.write(jarPath);
// printEntries(toInput(res));
BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(jarPath), UTF_8), 10); // Files.newBufferedReader(jarPath, UTF_8);
String firstLine = reader.readLine();
assertEquals("I'm the prefix!", firstLine);
}
@Test
public void testFilePrefix() throws Exception {
FileSystem fs = Jimfs.newFileSystem();
Path jarPath = fs.getPath("test.jar");
Path prefixPath = fs.getPath("prefix.dat");
Files.copy(toInputStream("I'm the prefix!", UTF_8), prefixPath);
new Jar()
.setAttribute("Foo", "1234")
.setAttribute("Bar", "5678")
.setJarPrefix(prefixPath)
.addEntry(Paths.get("foo.txt"), Jar.toInputStream("I am foo!\n", UTF_8))
.addEntry(Paths.get("dir", "bar.txt"), Jar.toInputStream("I am bar!\n", UTF_8))
.write(jarPath);
// printEntries(toInput(res));
BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(jarPath), UTF_8), 10); // Files.newBufferedReader(jarPath, UTF_8);
String firstLine = reader.readLine();
assertEquals("I'm the prefix!", firstLine);
}
//<editor-fold defaultstate="collapsed" desc="Utilities">
/////////// Utilities ///////////////////////////////////
private static JarInputStream toInput(JarOutputStream jos) {
try {
Field outField = FilterOutputStream.class.getDeclaredField("out");
outField.setAccessible(true);
jos.close();
return toInput((ByteArrayOutputStream) outField.get(jos));
} catch (Exception e) {
throw new AssertionError(e);
}
}
private static JarInputStream toInput(ByteArrayOutputStream baos) {
try {
baos.close();
byte[] bytes = baos.toByteArray();
return new JarInputStream(new ByteArrayInputStream(bytes));
} catch (Exception e) {
throw new AssertionError(e);
}
}
private static <T> List<T> addLast(List<T> list, T value) {
list.add(value);
return list;
}
private static <T> List<T> addFirst(List<T> list, T value) {
list.add(0, value);
return list;
}
private static <K, V> Map<K, V> put(Map<K, V> map, K key, V value) {
map.put(key, value);
return map;
}
private static String getEntryAsString(JarInputStream jar, Path entry, Charset charset) throws IOException {
byte[] buffer = getEntry(jar, entry);
return buffer != null ? new String(buffer, charset) : null;
}
private static String getEntryAsString(JarFile jar, Path entry, Charset charset) throws IOException {
byte[] buffer = getEntry(jar, entry);
return buffer != null ? new String(buffer, charset) : null;
}
private static String getEntryAsString(Path jar, Path entry, Charset charset) throws IOException {
byte[] buffer = getEntry(jar, entry);
return buffer != null ? new String(buffer, charset) : null;
}
private static byte[] getEntry(Path jar, Path entry) throws IOException {
try (FileSystem zipfs = ZipFS.newZipFileSystem(jar)) {
return Files.readAllBytes(zipfs.getPath(entry.toString()));
}
}
private static InputStream toInputStream(String s, Charset charset) {
return new ByteArrayInputStream(s.getBytes(charset));
}
private static Manifest getManifest(Path jar, boolean useZipfs) throws IOException {
if (useZipfs) {
try (FileSystem zipfs = ZipFS.newZipFileSystem(jar)) {
return new Manifest(Files.newInputStream(zipfs.getPath(JarFile.MANIFEST_NAME)));
}
} else
return new JarInputStream(Files.newInputStream(jar)).getManifest();
}
private static byte[] getEntry(JarFile jar, Path entry) throws IOException {
final Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
final JarEntry je = entries.nextElement();
if (je.getName().equals(entry.toString())) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
copy(jar.getInputStream(je), baos);
baos.close();
return baos.toByteArray();
}
}
return null;
}
private static byte[] getEntry(JarInputStream jar, Path entry) throws IOException {
JarEntry je;
while ((je = jar.getNextJarEntry()) != null) {
if (je.getName().equals(entry.toString())) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
copy(jar, baos);
baos.close();
return baos.toByteArray();
}
}
return null;
}
private static void printEntries(JarInputStream jar) throws IOException {
JarEntry je;
while ((je = jar.getNextJarEntry()) != null)
System.out.println(je.getName());
System.out.println();
}
private static void copy(InputStream is, OutputStream os) throws IOException {
try {
final byte[] buffer = new byte[1024];
for (int bytesRead; (bytesRead = is.read(buffer)) != -1;)
os.write(buffer, 0, bytesRead);
} finally {
is.close();
}
}
//</editor-fold>
}
| epl-1.0 |
Gurgel100/gcc | gcc/testsuite/g++.dg/init/union2.C | 267 | // PR c++/15938
// { dg-do compile }
// { dg-options "" }
typedef union
{
struct { int i; };
struct { char c; };
} A;
A a = { 0 };
A b = {{ 0 }};
A c = {{{ 0 }}}; // { dg-error "braces" "" { target c++98_only } }
A d = {{{{ 0 }}}}; // { dg-error "braces" }
| gpl-2.0 |
lzpfmh/oceanbase | oceanbase_0.4/src/proxyserver/ob_proxy_service.cpp | 20980 | /*
* (C) 2007-2010 Taobao Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* ????.cpp is for what ...
*
* Version: $Id: ipvsadm.c,v 1.27 2005/12/10 16:00:07 wensong Exp $
*
* Authors:
* Author Name <email address>
* - some work details if you want
*/
#include "ob_proxy_service.h"
#include "ob_proxy_server.h"
#include "common/ob_atomic.h"
#include "common/utility.h"
#include "common/ob_define.h"
#include "common/data_buffer.h"
#include "common/ob_packet.h"
#include "common/ob_read_common_data.h"
#include "common/ob_scanner.h"
#include "common/ob_new_scanner.h"
#include "common/ob_range2.h"
#include "common/ob_result.h"
#include "common/file_directory_utils.h"
#include "common/ob_trace_log.h"
#include "common/ob_schema_manager.h"
#include "common/ob_version.h"
#include "common/ob_profile_log.h"
#include "ob_proxy_server_main.h"
#include "common/ob_common_stat.h"
#include "ob_proxy_reader.h"
using namespace oceanbase::common;
namespace oceanbase
{
namespace proxyserver
{
ObProxyService::ObProxyService()
: proxy_server_(NULL), inited_(false)
{
}
ObProxyService::~ObProxyService()
{
destroy();
}
/**
* use ObChunkService after initialized.
*/
int ObProxyService::initialize(ObProxyServer* proxy_server)
{
int ret = OB_SUCCESS;
std::vector<std::string> proxy_names;
if (inited_)
{
ret = OB_INIT_TWICE;
}
else if (NULL == proxy_server)
{
ret = OB_INVALID_ARGUMENT;
}
else if(OB_SUCCESS != (ret = yunti_proxy_.initialize()))
{
TBSYS_LOG(ERROR, "yunti has some problem, check it, ret:%d", ret);
ret = OB_ERROR;
}
else if(0 >= proxy_server->get_config().get_all_proxy_name(proxy_names))
{
TBSYS_LOG(ERROR, "config has some problem, check it, ret:%d", ret);
ret = OB_ERROR;
}
else
{
proxy_map_.create(DEFAULT_PROXY_NUM);
for(uint32_t i = 0; i < proxy_names.size(); i++)
{
if(0 == strcmp(ObProxyServerConfig::YUNTI_PROXY, proxy_names[i].c_str()))
{
proxy_map_.set(proxy_names[i].c_str(), &yunti_proxy_);
}
}
proxy_server_ = proxy_server;
}
inited_ = true;
return ret;
}
int ObProxyService::destroy()
{
int rc = OB_SUCCESS;
if (inited_)
{
inited_ = false;
proxy_server_ = NULL;
}
else
{
rc = OB_NOT_INIT;
}
return rc;
}
int ObProxyService::start()
{
int rc = OB_SUCCESS;
if (!inited_)
{
rc = OB_NOT_INIT;
}
return rc;
}
/*
* after initialize() & start(), then can handle the request.
*/
int ObProxyService::do_request(
const int64_t receive_time,
const int32_t packet_code,
const int32_t version,
const int32_t channel_id,
easy_request_t* req,
common::ObDataBuffer& in_buffer,
common::ObDataBuffer& out_buffer,
const int64_t timeout_time)
{
UNUSED(receive_time);
int rc = OB_SUCCESS;
if (!inited_)
{
TBSYS_LOG(ERROR, "service not initialized, cannot accept any message.");
rc = OB_NOT_INIT;
}
if (OB_SUCCESS != rc)
{
common::ObResultCode result;
result.result_code_ = rc;
// send response.
int serialize_ret = result.serialize(out_buffer.get_data(),
out_buffer.get_capacity(), out_buffer.get_position());
if (OB_SUCCESS != serialize_ret)
{
TBSYS_LOG(ERROR, "serialize result code object failed.");
}
else
{
proxy_server_->send_response(
packet_code + 1, version,
out_buffer, req, channel_id);
}
}
else
{
switch(packet_code)
{
case OB_CS_FETCH_DATA:
rc = proxy_fetch_data(version, channel_id, req, in_buffer, out_buffer, timeout_time);
break;
case OB_FETCH_RANGE_TABLE :
rc = proxy_fetch_range(version, channel_id, req, in_buffer, out_buffer, timeout_time);
break;
default:
rc = OB_ERROR;
TBSYS_LOG(WARN, "not support packet code[%d]", packet_code);
break;
}
}
return rc;
}
int ObProxyService::get_yunti_reader(
YuntiProxy* proxy,
ObDataSourceDesc &desc,
const char* sstable_dir,
int64_t &local_tablet_version,
int16_t &local_sstable_version,
int64_t sstable_type,
ProxyReader* &proxy_reader)
{
int ret = OB_SUCCESS;
YuntiFileReader* yunti_reader = GET_TSI_MULT(YuntiFileReader, TSI_YUNTI_PROXY_READER_1);
if (NULL == yunti_reader)
{
TBSYS_LOG(ERROR, "failed to get thread local migrate_reader, "
"migrate_reader=%p", proxy_reader);
ret = OB_ALLOCATE_MEMORY_FAILED;
}
else
{
yunti_reader->reset();
//open sstable scanner
if(OB_SUCCESS != (ret = yunti_reader->prepare(proxy, desc.range_, desc.tablet_version_, static_cast<int16_t>(desc.sstable_version_), sstable_dir)))
{
TBSYS_LOG(WARN, "prepare yunti reader failed, ret:%d", ret);
}
else if(OB_SUCCESS != (ret = yunti_reader->get_sstable_version(sstable_dir, local_sstable_version)))
{
TBSYS_LOG(WARN, "get sstable version, ret:%d", ret);
}
else if(OB_SUCCESS != (ret = yunti_reader->get_tablet_version(local_tablet_version)))
{
TBSYS_LOG(WARN, "get tablet version, ret:%d", ret);
}
else if(OB_SUCCESS != (ret = yunti_reader->get_sstable_type(sstable_type)))
{
TBSYS_LOG(WARN, "get sstable type, ret:%d", ret);
}
else
{
proxy_reader = yunti_reader;
}
}
return ret;
}
int ObProxyService::proxy_fetch_data(
const int32_t version,
const int32_t channel_id,
easy_request_t* req,
common::ObDataBuffer& in_buffer,
common::ObDataBuffer& out_buffer,
const int64_t timeout_time)
{
const int32_t PROXY_FETCH_DATA_VERSION = 1;
common::ObResultCode rc;
rc.result_code_ = OB_SUCCESS;
int64_t session_id = 0;
int32_t response_cid = channel_id;
int64_t packet_cnt = 0;
bool is_last_packet = false;
int serialize_ret = OB_SUCCESS;
ObPacket* next_request = NULL;
ObPacketQueueThread& queue_thread =
proxy_server_->get_default_task_queue_thread();
UNUSED(timeout_time);
if (version != PROXY_FETCH_DATA_VERSION)
{
rc.result_code_ = OB_ERROR_FUNC_VERSION;
}
ObDataSourceDesc desc;
ProxyReader* proxy_reader = NULL;
int16_t local_sstable_version = 0;
int64_t local_tablet_version = 0;
int64_t local_sstable_type = 0;
if (OB_SUCCESS == rc.result_code_)
{
rc.result_code_ = desc.deserialize(in_buffer.get_data(), in_buffer.get_capacity(),
in_buffer.get_position());
if (OB_SUCCESS != rc.result_code_)
{
TBSYS_LOG(ERROR, "parse data source param error.");
}
}
if (OB_SUCCESS == rc.result_code_)
{
TBSYS_LOG(INFO, "begin fetch_data, %s", to_cstring(desc));
//get proxy
char* split_pos = NULL;
char* data_source_name = strtok_r(desc.uri_.ptr(), ":", &split_pos);
Proxy* proxy = NULL;
int hash_ret = OB_SUCCESS;
if(data_source_name == NULL)
{
TBSYS_LOG(ERROR, "data source name miss");
rc.result_code_ = OB_INVALID_ARGUMENT;
}
else if(hash::HASH_EXIST != (hash_ret = proxy_map_.get(data_source_name, proxy)) || NULL == proxy)
{
TBSYS_LOG(ERROR, "data source:%s proxy not exist", data_source_name);
rc.result_code_ = OB_DATA_SOURCE_NOT_EXIST;
}
else if(strcmp(data_source_name, ObProxyServerConfig::YUNTI_PROXY) == 0)
{
char* sstable_dir = strtok_r(NULL, ":", &split_pos);
if(NULL == sstable_dir)
{
TBSYS_LOG(ERROR, "sstable dir miss");
rc.result_code_ = OB_INVALID_ARGUMENT;
}
else
{
rc.result_code_ = get_yunti_reader(dynamic_cast<YuntiProxy*>(proxy), desc, sstable_dir + 1, local_tablet_version, local_sstable_version, local_sstable_type, proxy_reader);
}
}
else
{
TBSYS_LOG(ERROR, "not support this data source:%s", data_source_name);
rc.result_code_ = OB_DATA_SOURCE_NOT_EXIST;
}
}
out_buffer.get_position() = rc.get_serialize_size();
int64_t sequence_num = 0;
int64_t row_checksum = 0;
if(OB_SUCCESS != (serialize_ret = serialization::encode_i16(out_buffer.get_data(), out_buffer.get_capacity(), out_buffer.get_position(), local_sstable_version)))
{
TBSYS_LOG(ERROR, "serialize sstable version object failed, ret:%d", serialize_ret);
}
else if(OB_SUCCESS != (serialize_ret = serialization::encode_vi64(out_buffer.get_data(), out_buffer.get_capacity(), out_buffer.get_position(), sequence_num)))
{
TBSYS_LOG(ERROR, "serialize sequence object failed, ret:%d", serialize_ret);
}
else if(OB_SUCCESS != (serialize_ret = serialization::encode_vi64(out_buffer.get_data(), out_buffer.get_capacity(), out_buffer.get_position(), row_checksum)))
{
TBSYS_LOG(ERROR, "serialize row_checksum object failed, ret:%d", serialize_ret);
}
else if(OB_SUCCESS != (serialize_ret = serialization::encode_vi64(out_buffer.get_data(), out_buffer.get_capacity(), out_buffer.get_position(), local_sstable_type)))
{
TBSYS_LOG(ERROR, "serialize sstable type failed, ret:%d", serialize_ret);
}
if(OB_SUCCESS == rc.result_code_ && OB_SUCCESS == serialize_ret)
{
rc.result_code_ = proxy_reader->read_next(out_buffer);
if (proxy_reader->has_new_data())
{
session_id = queue_thread.generate_session_id();
}
}
int64_t tmp_pos = 0;
if(OB_SUCCESS != (serialize_ret = rc.serialize(out_buffer.get_data(), out_buffer.get_capacity(), tmp_pos)))
{
TBSYS_LOG(ERROR, "serialize rc code failed, ret:%d", serialize_ret);
}
do
{
if (OB_SUCCESS == rc.result_code_ &&
proxy_reader->has_new_data() &&
!is_last_packet)
{
rc.result_code_ = queue_thread.prepare_for_next_request(session_id);
if (OB_SUCCESS != rc.result_code_)
{
TBSYS_LOG(WARN, "failed to prepare_for_next_request:err[%d]", rc.result_code_);
}
}
// send response.
if(OB_SUCCESS == serialize_ret)
{
proxy_server_->send_response(
is_last_packet ? OB_SESSION_END : OB_CS_FETCH_DATA_RESPONSE, PROXY_FETCH_DATA_VERSION,
out_buffer, req, response_cid, session_id);
packet_cnt++;
}
if (OB_SUCCESS == rc.result_code_ && proxy_reader->has_new_data())
{
rc.result_code_ = queue_thread.wait_for_next_request(
session_id, next_request, THE_PROXY_SERVER.get_config().get_network_timeout());
if (OB_NET_SESSION_END == rc.result_code_)
{
//end this session
rc.result_code_ = OB_SUCCESS;
if (NULL != next_request)
{
req = next_request->get_request();
easy_request_wakeup(req);
}
break;
}
else if (OB_SUCCESS != rc.result_code_)
{
TBSYS_LOG(WARN, "failed to wait for next reques timeout, ret=%d",
rc.result_code_);
break;
}
else
{
response_cid = next_request->get_channel_id();
req = next_request->get_request();
out_buffer.get_position() = rc.get_serialize_size();
rc.result_code_ = proxy_reader->read_next(out_buffer);
if(!proxy_reader->has_new_data())
{
is_last_packet = true;
}
int64_t tmp_pos = 0;
if(OB_SUCCESS != (serialize_ret = rc.serialize(out_buffer.get_data(), out_buffer.get_capacity(), tmp_pos)))
{
TBSYS_LOG(ERROR, "serialize rc code failed, ret:%d", serialize_ret);
break;
}
}
}
else
{
//error happen or fullfilled or sent last packet
break;
}
} while (true);
int ret = 0;
if(NULL != proxy_reader && OB_SUCCESS != (ret = proxy_reader->close()))
{
TBSYS_LOG(ERROR, "proxy reader close fail, ret:%d", ret);
}
TBSYS_LOG(INFO, "fetch data finish, rc:%d", rc.result_code_);
//reset initernal status for next scan operator
if (session_id > 0)
{
queue_thread.destroy_session(session_id);
}
return rc.result_code_;
}
int ObProxyService::get_yunti_range_reader(YuntiProxy* proxy, const char* sstable_dir, ProxyReader* &proxy_reader)
{
int ret = OB_SUCCESS;
YuntiRangeReader* range_reader = GET_TSI_MULT(YuntiRangeReader, TSI_YUNTI_PROXY_READER_2);
if (NULL == range_reader)
{
TBSYS_LOG(ERROR, "failed to get thread local migrate_reader, "
"migrate_reader=%p", proxy_reader);
ret = OB_ALLOCATE_MEMORY_FAILED;
}
else
{
range_reader->reset();
if(OB_SUCCESS != (ret = range_reader->prepare(proxy, sstable_dir)))
{
TBSYS_LOG(WARN, "prepare yunti range reader failed, ret:%d", ret);
}
else
{
proxy_reader = range_reader;
}
}
return ret;
}
int ObProxyService::proxy_fetch_range(
const int32_t version,
const int32_t channel_id,
easy_request_t* req,
common::ObDataBuffer& in_buffer,
common::ObDataBuffer& out_buffer,
const int64_t timeout_time)
{
const int32_t PROXY_FETCH_RANGE_VERSION = 1;
common::ObResultCode rc;
rc.result_code_ = OB_SUCCESS;
int64_t session_id = 0;
int32_t response_cid = channel_id;
int64_t packet_cnt = 0;
bool is_last_packet = false;
int serialize_ret = OB_SUCCESS;
ObPacket* next_request = NULL;
ObPacketQueueThread& queue_thread =
proxy_server_->get_default_task_queue_thread();
UNUSED(timeout_time);
if (version != PROXY_FETCH_RANGE_VERSION)
{
rc.result_code_ = OB_ERROR_FUNC_VERSION;
}
ProxyReader* proxy_reader = NULL;
char table_name[OB_MAX_TABLE_NAME_LENGTH];
memset(table_name, 0, sizeof(table_name));
char uri[OB_MAX_FILE_NAME_LENGTH];
memset(uri, 0, sizeof(uri));
int64_t uri_len = 0;
int64_t table_name_len = 0;
if(NULL == serialization::decode_vstr(in_buffer.get_data(), in_buffer.get_capacity(), in_buffer.get_position(), table_name, OB_MAX_TABLE_NAME_LENGTH, &table_name_len))
{
TBSYS_LOG(ERROR, "deserialize the table_name error, ret:%d", rc.result_code_);
rc.result_code_ = OB_DESERIALIZE_ERROR;
}
if(NULL == serialization::decode_vstr(in_buffer.get_data(), in_buffer.get_capacity(), in_buffer.get_position(), uri, OB_MAX_FILE_NAME_LENGTH, &uri_len))
{
TBSYS_LOG(ERROR, "deserialize the uri error, ret:%d", rc.result_code_);
rc.result_code_ = OB_DESERIALIZE_ERROR;
}
if (OB_SUCCESS == rc.result_code_)
{
TBSYS_LOG(INFO, "begin fetch_range, uri:%s table_name:%s", uri, table_name);
//get proxy
char* split_pos = NULL;
char* data_source_name = strtok_r(uri, ":", &split_pos);
Proxy* proxy = NULL;
int hash_ret = OB_SUCCESS;
if(data_source_name == NULL)
{
TBSYS_LOG(ERROR, "data source name miss");
rc.result_code_ = OB_INVALID_ARGUMENT;
}
else if(hash::HASH_EXIST != (hash_ret = proxy_map_.get(data_source_name, proxy)) || NULL == proxy)
{
TBSYS_LOG(ERROR, "data source:%s proxy not exist", data_source_name);
rc.result_code_ = OB_DATA_SOURCE_NOT_EXIST;
}
else if(strcmp(data_source_name, ObProxyServerConfig::YUNTI_PROXY) == 0)
{
char* sstable_dir = strtok_r(NULL, ":", &split_pos);
if(NULL == sstable_dir)
{
TBSYS_LOG(ERROR, "sstable dir miss");
rc.result_code_ = OB_INVALID_ARGUMENT;
}
else
{
TBSYS_LOG(INFO, "sstable dir:%s", sstable_dir);
rc.result_code_ = get_yunti_range_reader(dynamic_cast<YuntiProxy*>(proxy), sstable_dir + 1, proxy_reader);
}
}
else
{
TBSYS_LOG(ERROR, "not support this data source:%s", data_source_name);
rc.result_code_ = OB_DATA_SOURCE_NOT_EXIST;
}
}
out_buffer.get_position() = rc.get_serialize_size();
if(OB_SUCCESS == rc.result_code_)
{
rc.result_code_ = proxy_reader->read_next(out_buffer);
}
int64_t tmp_pos = 0;
if(OB_SUCCESS != (serialize_ret = rc.serialize(out_buffer.get_data(), out_buffer.get_capacity(), tmp_pos)))
{
TBSYS_LOG(ERROR, "serialize rc code failed, ret:%d", serialize_ret);
}
if(OB_SUCCESS != rc.result_code_)
{
out_buffer.get_position() = tmp_pos;
}
if (OB_SUCCESS == rc.result_code_)
{
if (proxy_reader->has_new_data())
{
session_id = queue_thread.generate_session_id();
}
}
do
{
if (OB_SUCCESS == rc.result_code_ &&
proxy_reader->has_new_data() &&
!is_last_packet)
{
rc.result_code_ = queue_thread.prepare_for_next_request(session_id);
if (OB_SUCCESS != rc.result_code_)
{
TBSYS_LOG(WARN, "failed to prepare_for_next_request:err[%d]", rc.result_code_);
}
}
// send response.
if(OB_SUCCESS == serialize_ret)
{
proxy_server_->send_response(
is_last_packet ? OB_SESSION_END : OB_FETCH_RANGE_TABLE_RESPONSE, PROXY_FETCH_RANGE_VERSION,
out_buffer, req, response_cid, session_id);
packet_cnt++;
}
if (OB_SUCCESS == rc.result_code_ && proxy_reader->has_new_data())
{
rc.result_code_ = queue_thread.wait_for_next_request(
session_id, next_request, THE_PROXY_SERVER.get_config().get_network_timeout());
if (OB_NET_SESSION_END == rc.result_code_)
{
//end this session
rc.result_code_ = OB_SUCCESS;
if (NULL != next_request)
{
req = next_request->get_request();
easy_request_wakeup(req);
}
break;
}
else if (OB_SUCCESS != rc.result_code_)
{
TBSYS_LOG(WARN, "failed to wait for next reques timeout, ret=%d",
rc.result_code_);
break;
}
else
{
response_cid = next_request->get_channel_id();
req = next_request->get_request();
out_buffer.get_position() = rc.get_serialize_size();
rc.result_code_ = proxy_reader->read_next(out_buffer);
int64_t tmp_pos = 0;
if(OB_SUCCESS != (serialize_ret = rc.serialize(out_buffer.get_data(), out_buffer.get_capacity(), tmp_pos)))
{
TBSYS_LOG(ERROR, "serialize rc code failed, ret:%d", serialize_ret);
break;
}
if(OB_SUCCESS != rc.result_code_)
{
out_buffer.get_position() = tmp_pos;
}
if(!proxy_reader->has_new_data())
{
is_last_packet = true;
}
}
}
else
{
//error happen or fullfilled or sent last packet
break;
}
} while (true);
int ret = 0;
if(NULL != proxy_reader && OB_SUCCESS != (ret = proxy_reader->close()))
{
TBSYS_LOG(ERROR, "proxy reader close fail, ret:%d", ret);
}
TBSYS_LOG(INFO, "fetch data finish, rc:%d", rc.result_code_);
//reset initernal status for next scan operator
if (session_id > 0)
{
queue_thread.destroy_session(session_id);
}
return rc.result_code_;
}
} // end namespace chunkserver
} // end namespace oceanbase
| gpl-2.0 |
iherak/ezpublish-kernel | eZ/Publish/Core/FieldType/DateAndTime/Value.php | 2143 | <?php
/**
* File containing the DateAndTime Value class.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*
* @version //autogentag//
*/
namespace eZ\Publish\Core\FieldType\DateAndTime;
use eZ\Publish\Core\FieldType\Value as BaseValue;
use eZ\Publish\Core\Base\Exceptions\InvalidArgumentValue;
use Exception;
use DateTime;
/**
* Value for DateAndTime field type.
*/
class Value extends BaseValue
{
/**
* Date content.
*
* @var \DateTime
*/
public $value;
/**
* Date format to be used by {@link __toString()}.
*
* @var string
*/
public $stringFormat = 'U';
/**
* Construct a new Value object and initialize with $dateTime.
*
* @param \DateTime|null $dateTime Date/Time as a DateTime object
*/
public function __construct(DateTime $dateTime = null)
{
$this->value = $dateTime;
}
/**
* Creates a Value from the given $dateString.
*
* @param string $dateString
*
* @return \eZ\Publish\Core\FieldType\DateAndTime\Value
*/
public static function fromString($dateString)
{
try {
return new static(new DateTime($dateString));
} catch (Exception $e) {
throw new InvalidArgumentValue('$dateString', $dateString, __CLASS__, $e);
}
}
/**
* Creates a Value from the given $timestamp.
*
* @param int $timestamp
*
* @return \eZ\Publish\Core\FieldType\DateAndTime\Value
*/
public static function fromTimestamp($timestamp)
{
try {
return new static(new DateTime("@{$timestamp}"));
} catch (Exception $e) {
throw new InvalidArgumentValue('$timestamp', $timestamp, __CLASS__, $e);
}
}
/**
* @see \eZ\Publish\Core\FieldType\Value
*/
public function __toString()
{
if (!$this->value instanceof DateTime) {
return '';
}
return $this->value->format($this->stringFormat);
}
}
| gpl-2.0 |
vanfanel/scummvm | engines/glk/level9/detection.cpp | 21133 | /* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "glk/level9/detection.h"
#include "glk/level9/detection_tables.h"
#include "glk/level9/level9_main.h"
#include "glk/level9/os_glk.h"
#include "glk/blorb.h"
#include "glk/detection.h"
#include "common/debug.h"
#include "common/file.h"
#include "common/md5.h"
#include "engines/game.h"
namespace Glk {
namespace Level9 {
long Scanner::scanner(byte *startFile, uint32 size, byte **dictData, byte **aCodePtr) {
_dictData = dictData;
_aCodePtr = aCodePtr;
#ifdef FULLSCAN
FullScan(startfile, FileSize);
#endif
int offset = scan(startFile, size);
if (offset < 0) {
offset = ScanV2(startFile, size);
_gameType = L9_V2;
if (offset < 0) {
offset = ScanV1(startFile, size);
_gameType = L9_V1;
if (offset < 0) {
return -1;
}
}
}
return offset;
}
const L9V1GameInfo &Scanner::v1Game() const {
assert(_gameType == L9_V1);
return L9_V1_GAMES[_l9V1Game];
}
long Scanner::scan(byte *startFile, uint32 size) {
uint32 i, num, Size, MaxSize = 0;
int j;
uint16 d0 = 0, l9, md, ml, dd, dl;
uint32 Min, Max;
long offset = -1;
bool JumpKill, DriverV4;
if (size < 33)
return -1;
byte *Chk = (byte *)malloc(size + 1);
byte *Image = (byte *)calloc(size, 1);
if ((Chk == nullptr) || (Image == nullptr)) {
error("Unable to allocate memory for game scan! Exiting...");
}
Chk[0] = 0;
for (i = 1; i <= size; i++)
Chk[i] = Chk[i - 1] + startFile[i - 1];
for (i = 0; i < size - 33; i++) {
num = L9WORD(startFile + i) + 1;
/*
Chk[i] = 0 +...+ i-1
Chk[i+n] = 0 +...+ i+n-1
Chk[i+n] - Chk[i] = i + ... + i+n
*/
if (num > 0x2000 && i + num <= size && Chk[i + num] == Chk[i]) {
md = L9WORD(startFile + i + 0x2);
ml = L9WORD(startFile + i + 0x4);
dd = L9WORD(startFile + i + 0xa);
dl = L9WORD(startFile + i + 0xc);
if (ml > 0 && md > 0 && i + md + ml <= size && dd > 0 && dl > 0 && i + dd + dl * 4 <= size) {
/* v4 files may have acodeptr in 8000-9000, need to fix */
for (j = 0; j < 12; j++) {
d0 = L9WORD(startFile + i + 0x12 + j * 2);
if (j != 11 && d0 >= 0x8000 && d0 < 0x9000) {
if (d0 >= 0x8000 + LISTAREASIZE) break;
} else if (i + d0 > size) break;
}
/* list9 ptr must be in listarea, acode ptr in data */
if (j < 12 /*|| (d0>=0x8000 && d0<0x9000)*/) continue;
l9 = L9WORD(startFile + i + 0x12 + 10 * 2);
if (l9 < 0x8000 || l9 >= 0x8000 + LISTAREASIZE) continue;
Size = 0;
Min = Max = i + d0;
DriverV4 = 0;
if (ValidateSequence(startFile, Image, i + d0, i + d0, &Size, size, &Min, &Max, false, &JumpKill, &DriverV4)) {
if (Size > MaxSize && Size > 100) {
offset = i;
MaxSize = Size;
_gameType = DriverV4 ? L9_V4 : L9_V3;
}
}
}
}
}
free(Chk);
free(Image);
return offset;
}
long Scanner::ScanV2(byte *startFile, uint32 size) {
uint32 i, Size, MaxSize = 0, num;
int j;
uint16 d0 = 0, l9;
uint32 Min, Max;
long offset = -1;
bool JumpKill;
if (size < 28)
return -1;
byte *Chk = (byte *)malloc(size + 1);
byte *Image = (byte *)calloc(size, 1);
if ((Chk == nullptr) || (Image == nullptr)) {
error("Unable to allocate memory for game scan! Exiting...");
}
Chk[0] = 0;
for (i = 1; i <= size; i++)
Chk[i] = Chk[i - 1] + startFile[i - 1];
for (i = 0; i < size - 28; i++) {
num = L9WORD(startFile + i + 28) + 1;
if ((i + num) <= size && i < (size - 32) && ((Chk[i + num] - Chk[i + 32]) & 0xff) == startFile[i + 0x1e]) {
for (j = 0; j < 14; j++) {
d0 = L9WORD(startFile + i + j * 2);
if (j != 13 && d0 >= 0x8000 && d0 < 0x9000) {
if (d0 >= 0x8000 + LISTAREASIZE) break;
} else if (i + d0 > size) break;
}
/* list9 ptr must be in listarea, acode ptr in data */
if (j < 14 /*|| (d0>=0x8000 && d0<0x9000)*/) continue;
l9 = L9WORD(startFile + i + 6 + 9 * 2);
if (l9 < 0x8000 || l9 >= 0x8000 + LISTAREASIZE) continue;
Size = 0;
Min = Max = i + d0;
if (ValidateSequence(startFile, Image, i + d0, i + d0, &Size, size, &Min, &Max, false, &JumpKill, nullptr)) {
#ifdef L9DEBUG
printf("Found valid V2 header at %ld, code size %ld", i, Size);
#endif
if (Size > MaxSize && Size > 100) {
offset = i;
MaxSize = Size;
}
}
}
}
free(Chk);
free(Image);
return offset;
}
long Scanner::ScanV1(byte *startFile, uint32 size) {
uint32 i, Size;
int Replace;
byte *ImagePtr;
long MaxPos = -1;
uint32 MaxCount = 0;
uint32 Min, Max; //, MaxMax, MaxMin;
bool JumpKill; // , MaxJK;
int dictOff1 = 0, dictOff2 = 0;
byte dictVal1 = 0xff, dictVal2 = 0xff;
if (size < 20)
return -1;
byte *Image = (byte *)calloc(size, 1);
if (Image == nullptr) {
error("Unable to allocate memory for game scan! Exiting...");
}
for (i = 0; i < size; i++) {
if ((startFile[i] == 0 && startFile[i + 1] == 6) || (startFile[i] == 32 && startFile[i + 1] == 4)) {
Size = 0;
Min = Max = i;
Replace = 0;
if (ValidateSequence(startFile, Image, i, i, &Size, size, &Min, &Max, false, &JumpKill, nullptr)) {
if (Size > MaxCount && Size > 100 && Size < 10000) {
MaxCount = Size;
//MaxMin = Min;
//MaxMax = Max;
MaxPos = i;
//MaxJK = JumpKill;
}
Replace = 0;
}
for (ImagePtr = Image + Min; ImagePtr <= Image + Max; ImagePtr++) {
if (*ImagePtr == 2)
*ImagePtr = Replace;
}
}
}
/* V1 dictionary detection from L9Cut by Paul David Doherty */
for (i = 0; i < size - 20; i++) {
if (startFile[i] == 'A') {
if (startFile[i + 1] == 'T' && startFile[i + 2] == 'T' && startFile[i + 3] == 'A' && startFile[i + 4] == 'C' && startFile[i + 5] == 0xcb) {
dictOff1 = i;
dictVal1 = startFile[dictOff1 + 6];
break;
}
}
}
for (i = dictOff1; i < size - 20; i++) {
if (startFile[i] == 'B') {
if (startFile[i + 1] == 'U' && startFile[i + 2] == 'N' && startFile[i + 3] == 'C' && startFile[i + 4] == 0xc8) {
dictOff2 = i;
dictVal2 = startFile[dictOff2 + 5];
break;
}
}
}
_l9V1Game = -1;
if (_dictData && (dictVal1 != 0xff || dictVal2 != 0xff)) {
for (i = 0; i < sizeof L9_V1_GAMES / sizeof L9_V1_GAMES[0]; i++) {
if ((L9_V1_GAMES[i].dictVal1 == dictVal1) && (L9_V1_GAMES[i].dictVal2 == dictVal2)) {
_l9V1Game = i;
(*_dictData) = startFile + dictOff1 - L9_V1_GAMES[i].dictStart;
}
}
}
free(Image);
if (MaxPos > 0 && _aCodePtr) {
(*_aCodePtr) = startFile + MaxPos;
return 0;
}
return -1;
}
bool Scanner::ValidateSequence(byte *Base, byte *Image, uint32 iPos, uint32 acode, uint32 *Size, uint32 size, uint32 *Min, uint32 *Max, bool Rts, bool *JumpKill, bool *DriverV4) {
uint32 Pos;
bool Finished = false, Valid;
uint32 Strange = 0;
int ScanCodeMask;
int Code;
*JumpKill = false;
if (iPos >= size)
return false;
Pos = iPos;
if (Pos < *Min) *Min = Pos;
if (Image[Pos]) return true; /* hit valid code */
do {
Code = Base[Pos];
Valid = true;
if (Image[Pos]) break; /* converged to found code */
Image[Pos++] = 2;
if (Pos > *Max) *Max = Pos;
ScanCodeMask = 0x9f;
if (Code & 0x80) {
ScanCodeMask = 0xff;
if ((Code & 0x1f) > 0xa)
Valid = false;
Pos += 2;
}
else switch (Code & 0x1f) {
case 0: { /* goto */
uint32 Val = scangetaddr(Code, Base, &Pos, acode, &ScanCodeMask);
Valid = ValidateSequence(Base, Image, Val, acode, Size, size, Min, Max, true/*Rts*/, JumpKill, DriverV4);
Finished = true;
break;
}
case 1: { /* intgosub */
uint32 Val = scangetaddr(Code, Base, &Pos, acode, &ScanCodeMask);
Valid = ValidateSequence(Base, Image, Val, acode, Size, size, Min, Max, true, JumpKill, DriverV4);
break;
}
case 2: /* intreturn */
Valid = Rts;
Finished = true;
break;
case 3: /* printnumber */
Pos++;
break;
case 4: /* messagev */
Pos++;
break;
case 5: /* messagec */
scangetcon(Code, &Pos, &ScanCodeMask);
break;
case 6: /* function */
switch (Base[Pos++]) {
case 2:/* random */
Pos++;
break;
case 1:/* calldriver */
if (DriverV4) {
if (CheckCallDriverV4(Base, Pos - 2))
*DriverV4 = true;
}
break;
case 3:/* save */
case 4:/* restore */
case 5:/* clearworkspace */
case 6:/* clear stack */
break;
case 250: /* printstr */
while (Base[Pos++]);
break;
default:
Valid = false;
break;
}
break;
case 7: /* input */
Pos += 4;
break;
case 8: /* varcon */
scangetcon(Code, &Pos, &ScanCodeMask);
Pos++;
break;
case 9: /* varvar */
Pos += 2;
break;
case 10: /* _add */
Pos += 2;
break;
case 11: /* _sub */
Pos += 2;
break;
case 14: /* jump */
*JumpKill = true;
Finished = true;
break;
case 15: /* exit */
Pos += 4;
break;
case 16: /* ifeqvt */
case 17: /* ifnevt */
case 18: /* ifltvt */
case 19: { /* ifgtvt */
uint32 Val;
Pos += 2;
Val = scangetaddr(Code, Base, &Pos, acode, &ScanCodeMask);
Valid = ValidateSequence(Base, Image, Val, acode, Size, size, Min, Max, Rts, JumpKill, DriverV4);
break;
}
case 20: /* screen */
if (Base[Pos++]) Pos++;
break;
case 21: /* cleartg */
Pos++;
break;
case 22: /* picture */
Pos++;
break;
case 23: /* getnextobject */
Pos += 6;
break;
case 24: /* ifeqct */
case 25: /* ifnect */
case 26: /* ifltct */
case 27: { /* ifgtct */
uint32 Val;
Pos++;
scangetcon(Code, &Pos, &ScanCodeMask);
Val = scangetaddr(Code, Base, &Pos, acode, &ScanCodeMask);
Valid = ValidateSequence(Base, Image, Val, acode, Size, size, Min, Max, Rts, JumpKill, DriverV4);
break;
}
case 28: /* printinput */
break;
case 12: /* ilins */
case 13: /* ilins */
case 29: /* ilins */
case 30: /* ilins */
case 31: /* ilins */
Valid = false;
break;
}
if (Valid && (Code & ~ScanCodeMask))
Strange++;
} while (Valid && !Finished && Pos < size); /* && Strange==0); */
(*Size) += Pos - iPos;
return Valid; /* && Strange==0; */
}
uint16 Scanner::scanmovewa5d0(byte *Base, uint32 *Pos) {
uint16 ret = L9WORD(Base + *Pos);
(*Pos) += 2;
return ret;
}
uint32 Scanner::scangetaddr(int Code, byte *Base, uint32 *Pos, uint32 acode, int *Mask) {
(*Mask) |= 0x20;
if (Code & 0x20) {
/* getaddrshort */
signed char diff = Base[*Pos];
(*Pos)++;
return (*Pos) + diff - 1;
} else {
return acode + scanmovewa5d0(Base, Pos);
}
}
void Scanner::scangetcon(int Code, uint32 *Pos, int *Mask) {
(*Pos)++;
if (!(Code & 64))(*Pos)++;
(*Mask) |= 0x40;
}
bool Scanner::CheckCallDriverV4(byte *Base, uint32 Pos) {
int i, j;
// Look back for an assignment from a variable to list9[0], which is used
// to specify the driver call.
for (i = 0; i < 2; i++) {
int x = Pos - ((i + 1) * 3);
if ((Base[x] == 0x89) && (Base[x + 1] == 0x00)) {
// Get the variable being copied to list9[0]
int var = Base[x + 2];
// Look back for an assignment to the variable
for (j = 0; j < 2; j++) {
int y = x - ((j + 1) * 3);
if ((Base[y] == 0x48) && (Base[y + 2] == var)) {
// If this a V4 driver call?
switch (Base[y + 1]) {
case 0x0E:
case 0x20:
case 0x22:
return TRUE;
}
return FALSE;
}
}
}
}
return FALSE;
}
#ifdef FULLSCAN
void Scanner::fullScan(byte *startFile, uint32 size) {
byte *Image = (byte *)calloc(size, 1);
uint32 i, Size;
int Replace;
byte *ImagePtr;
uint32 MaxPos = 0;
uint32 MaxCount = 0;
uint32 Min, Max, MaxMin, MaxMax;
int offset;
bool JumpKill, MaxJK;
for (i = 0; i < size; i++) {
Size = 0;
Min = Max = i;
Replace = 0;
if (ValidateSequence(startFile, Image, i, i, &Size, size, &Min, &Max, FALSE, &JumpKill, nullptr)) {
if (Size > MaxCount) {
MaxCount = Size;
MaxMin = Min;
MaxMax = Max;
MaxPos = i;
MaxJK = JumpKill;
}
Replace = 0;
}
for (ImagePtr = Image + Min; ImagePtr <= Image + Max; ImagePtr++) {
if (*ImagePtr == 2)
*ImagePtr = Replace;
}
}
printf("%ld %ld %ld %ld %s", MaxPos, MaxCount, MaxMin, MaxMax, MaxJK ? "jmp killed" : "");
/* search for reference to MaxPos */
offset = 0x12 + 11 * 2;
for (i = 0; i < size - offset - 1; i++) {
if ((L9WORD(startFile + i + offset)) + i == MaxPos) {
printf("possible v3,4 Code reference at : %ld", i);
/* startdata=startFile+i; */
}
}
offset = 13 * 2;
for (i = 0; i < size - offset - 1; i++) {
if ((L9WORD(startFile + i + offset)) + i == MaxPos)
printf("possible v2 Code reference at : %ld", i);
}
free(Image);
}
#endif
/*----------------------------------------------------------------------*/
GameDetection::GameDetection(byte *&startData, uint32 &fileSize) :
_startData(startData), _fileSize(fileSize), _crcInitialized(false), _gameName(nullptr) {
Common::fill(&_crcTable[0], &_crcTable[256], 0);
}
gln_game_tableref_t GameDetection::gln_gameid_identify_game() {
uint16 length, crc;
byte checksum;
int is_version2;
gln_game_tableref_t game;
gln_patch_tableref_t patch;
/* If the data file appears too short for a header, give up now. */
if (_fileSize < 30)
return nullptr;
/*
* Find the version of the game, and the length of game data. This logic
* is taken from L9cut, with calcword() replaced by simple byte comparisons.
* If the length exceeds the available data, fail.
*/
assert(_startData);
is_version2 = _startData[4] == 0x20 && _startData[5] == 0x00
&& _startData[10] == 0x00 && _startData[11] == 0x80
&& _startData[20] == _startData[22]
&& _startData[21] == _startData[23];
length = is_version2
? _startData[28] | _startData[29] << BITS_PER_BYTE
: _startData[0] | _startData[1] << BITS_PER_BYTE;
if (length >= _fileSize)
return nullptr;
/* Calculate or retrieve the checksum, in a version specific way. */
if (is_version2) {
int index;
checksum = 0;
for (index = 0; index < length + 1; index++)
checksum += _startData[index];
}
else
checksum = _startData[length];
/*
* Generate a CRC for this data. When L9cut calculates a CRC, it's using a
* copy taken up to length + 1 and then padded with two NUL bytes, so we
* mimic that here.
*/
crc = gln_get_buffer_crc(_startData, length + 1, 2);
/*
* See if this is a patched file. If it is, look up the game based on the
* original CRC and checksum. If not, use the current CRC and checksum.
*/
patch = gln_gameid_lookup_patch(length, checksum, crc);
game = gln_gameid_lookup_game(length,
patch ? patch->orig_checksum : checksum,
patch ? patch->orig_crc : crc,
false);
/* If no game identified, retry without the CRC. This is guesswork. */
if (!game)
game = gln_gameid_lookup_game(length, checksum, crc, true);
return game;
}
// CRC table initialization polynomial
static const uint16 GLN_CRC_POLYNOMIAL = 0xa001;
uint16 GameDetection::gln_get_buffer_crc(const void *void_buffer, size_t length, size_t padding) {
const char *buffer = (const char *)void_buffer;
uint16 crc;
size_t index;
/* Build the static CRC lookup table on first call. */
if (!_crcInitialized) {
for (index = 0; index < BYTE_MAX + 1; index++) {
int bit;
crc = (uint16)index;
for (bit = 0; bit < BITS_PER_BYTE; bit++)
crc = crc & 1 ? GLN_CRC_POLYNOMIAL ^ (crc >> 1) : crc >> 1;
_crcTable[index] = crc;
}
_crcInitialized = true;
/* CRC lookup table self-test, after is_initialized set -- recursion. */
assert(gln_get_buffer_crc("123456789", 9, 0) == 0xbb3d);
}
/* Start with zero in the crc, then update using table entries. */
crc = 0;
for (index = 0; index < length; index++)
crc = _crcTable[(crc ^ buffer[index]) & BYTE_MAX] ^ (crc >> BITS_PER_BYTE);
/* Add in any requested NUL padding bytes. */
for (index = 0; index < padding; index++)
crc = _crcTable[crc & BYTE_MAX] ^ (crc >> BITS_PER_BYTE);
return crc;
}
gln_game_tableref_t GameDetection::gln_gameid_lookup_game(uint16 length, byte checksum, uint16 crc, int ignore_crc) const {
gln_game_tableref_t game;
for (game = GLN_GAME_TABLE; game->length; game++) {
if (game->length == length && game->checksum == checksum
&& (ignore_crc || game->crc == crc))
break;
}
return game->length ? game : nullptr;
}
gln_patch_tableref_t GameDetection::gln_gameid_lookup_patch(uint16 length, byte checksum, uint16 crc) const {
gln_patch_tableref_t patch;
for (patch = GLN_PATCH_TABLE; patch->length; patch++) {
if (patch->length == length && patch->patch_checksum == checksum
&& patch->patch_crc == crc)
break;
}
return patch->length ? patch : nullptr;
}
const char *GameDetection::gln_gameid_get_game_name() {
/*
* If no game name yet known, attempt to identify the game. If it can't
* be identified, set the cached game name to "" -- this special value
* indicates that the game is an unknown one, but suppresses repeated
* attempts to identify it on successive calls.
*/
if (!_gameName) {
gln_game_tableref_t game;
/*
* If the interpreter hasn't yet loaded a game, startdata is nullptr
* (uninitialized, global). In this case, we return nullptr, allowing
* for retries until a game is loaded.
*/
if (!_startData)
return nullptr;
game = gln_gameid_identify_game();
_gameName = game ? game->name : "";
}
/* Return the game's name, or nullptr if it was unidentifiable. */
assert(_gameName);
return strlen(_gameName) > 0 ? _gameName : nullptr;
}
/**
* Clear the saved game name, forcing a new lookup when next queried. This
* function should be called by actions that may cause the interpreter to
* change game file, for example os_set_filenumber().
*/
void GameDetection::gln_gameid_game_name_reset() {
_gameName = nullptr;
}
/*----------------------------------------------------------------------*/
void Level9MetaEngine::getSupportedGames(PlainGameList &games) {
const char *prior_id = nullptr;
for (const gln_game_table_t *pd = GLN_GAME_TABLE; pd->name; ++pd) {
if (prior_id == nullptr || strcmp(pd->gameId, prior_id)) {
PlainGameDescriptor gd;
gd.gameId = pd->gameId;
gd.description = pd->name;
games.push_back(gd);
prior_id = pd->gameId;
}
}
}
GameDescriptor Level9MetaEngine::findGame(const char *gameId) {
for (const gln_game_table_t *pd = GLN_GAME_TABLE; pd->gameId; ++pd) {
if (!strcmp(gameId, pd->gameId)) {
GameDescriptor gd(pd->gameId, pd->name, 0);
return gd;
}
}
return PlainGameDescriptor();
}
bool Level9MetaEngine::detectGames(const Common::FSList &fslist, DetectedGames &gameList) {
// Loop through the files of the folder
for (Common::FSList::const_iterator file = fslist.begin(); file != fslist.end(); ++file) {
// Check for a recognised filename
if (file->isDirectory())
continue;
Common::String filename = file->getName();
if (!filename.hasSuffixIgnoreCase(".l9") && !filename.hasSuffixIgnoreCase(".dat"))
continue;
// Open up the file so we can get it's size
Common::File gameFile;
if (!gameFile.open(*file))
continue;
uint32 fileSize = gameFile.size();
if (fileSize == 0 || fileSize > 0xffff) {
// Too big or too small to possibly be a Level 9 game
gameFile.close();
continue;
}
// Read in the game data
Common::Array<byte> data;
data.resize(fileSize + 1);
gameFile.read(&data[0], fileSize);
gameFile.close();
// Check if it's a valid Level 9 game
byte *startFile = &data[0];
Scanner scanner;
int offset = scanner.scanner(&data[0], fileSize) < 0;
if (offset < 0)
continue;
// Check for the specific game
byte *startData = startFile + offset;
GameDetection detection(startData, fileSize);
const gln_game_tableref_t game = detection.gln_gameid_identify_game();
if (!game)
continue;
// Found the game, add a detection entry
DetectedGame gd = DetectedGame("glk", game->gameId, game->name, Common::UNK_LANG,
Common::kPlatformUnknown, game->extra);
gd.addExtraEntry("filename", filename);
gameList.push_back(gd);
}
return !gameList.empty();
}
void Level9MetaEngine::detectClashes(Common::StringMap &map) {
const char *prior_id = nullptr;
for (const gln_game_table_t *pd = GLN_GAME_TABLE; pd->name; ++pd) {
if (prior_id == nullptr || strcmp(pd->gameId, prior_id)) {
prior_id = pd->gameId;
if (map.contains(pd->gameId))
error("Duplicate game Id found - %s", pd->gameId);
map[pd->gameId] = "";
}
}
}
} // End of namespace Level9
} // End of namespace Glk
| gpl-2.0 |
blashbrook/epublishorbust | sites/all/modules/contrib/openlayers/tests/src/Plugin/Interaction/InlineJS/InlineJSTest.php | 1201 | <?php
/**
* @file
* Contains \Drupal\Tests\openlayers\Openlayers\Interaction\InlineJS\InlineJSTest;
*/
namespace Drupal\Tests\openlayers\Plugin\Interaction\InlineJS;
use Drupal\openlayers\Plugin\Interaction\InlineJS\InlineJS;
/**
* @coversDefaultClass \Drupal\openlayers\Plugin\Interaction\InlineJS\InlineJS
* @group openlayers
*/
class InlineJSTest extends \PHPUnit_Framework_TestCase {
public function setUp() {
$this->moduleHandler = \Mockery::mock('\Drupal\Core\Extension\ModuleHandlerInterface');
$this->messenger = \Mockery::mock('\Drupal\service_container\Messenger\MessengerInterface');
$this->drupal7 = \Mockery::mock('\Drupal\service_container\Legacy\Drupal7');
$configuration = array(
'plugin module' => 'openlayers',
'plugin type' => 'Interaction',
'name' => 'openlayers.interaction', // @todo check the name.
);
$this->inlineJS = new InlineJS($configuration, 'InkineJS', array(), $this->moduleHandler, $this->messenger, $this->drupal7);
}
/**
* @covers ::__construct
*/
public function test_construct() {
$this->assertInstanceOf('\Drupal\openlayers\Plugin\Interaction\InlineJS\InlineJS', $this->inlineJS);
}
}
| gpl-2.0 |
dmlloyd/openjdk-modules | langtools/test/com/sun/javadoc/testInterface/TestInterface.java | 4990 | /*
* Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4682448 4947464 5029946 8025633 8026567
* @summary Verify that the public modifier does not show up in the
* documentation for public methods, as recommended by the JLS.
* If A implements I and B extends A, B should be in the list of
* implementing classes in the documentation for I.
* @author jamieh
* @library ../lib
* @modules jdk.javadoc
* @build JavadocTester
* @run main TestInterface
*/
public class TestInterface extends JavadocTester {
public static void main(String... args) throws Exception {
TestInterface tester = new TestInterface();
tester.runTests();
}
@Test
void test() {
javadoc("-d", "out",
"-sourcepath", testSrc,
"pkg");
checkExit(Exit.OK);
checkOutput("pkg/Interface.html", true,
"<pre>int method()</pre>",
"<pre>static final int field</pre>",
// Make sure known implementing class list is correct and omits type parameters.
"<dl>\n"
+ "<dt>All Known Implementing Classes:</dt>\n"
+ "<dd><a href=\"../pkg/Child.html\" title=\"class in pkg\">Child"
+ "</a>, <a href=\"../pkg/Parent.html\" title=\"class in pkg\">Parent"
+ "</a></dd>\n"
+ "</dl>");
checkOutput("pkg/Child.html", true,
// Make sure "All Implemented Interfaces": has substituted type parameters
"<dl>\n"
+ "<dt>All Implemented Interfaces:</dt>\n"
+ "<dd><a href=\"../pkg/Interface.html\" title=\"interface in pkg\">"
+ "Interface</a><T></dd>\n"
+ "</dl>",
//Make sure Class Tree has substituted type parameters.
"<ul class=\"inheritance\">\n"
+ "<li>java.lang.Object</li>\n"
+ "<li>\n"
+ "<ul class=\"inheritance\">\n"
+ "<li><a href=\"../pkg/Parent.html\" title=\"class in pkg\">"
+ "pkg.Parent</a><T></li>\n"
+ "<li>\n"
+ "<ul class=\"inheritance\">\n"
+ "<li>pkg.Child<T></li>\n"
+ "</ul>\n"
+ "</li>\n"
+ "</ul>\n"
+ "</li>\n"
+ "</ul>",
//Make sure "Specified By" has substituted type parameters.
"<dt><span class=\"overrideSpecifyLabel\">Specified by:</span></dt>\n"
+ "<dd><code><a href=\"../pkg/Interface.html#method--\">method</a>"
+ "</code> in interface <code>"
+ "<a href=\"../pkg/Interface.html\" title=\"interface in pkg\">"
+ "Interface</a><<a href=\"../pkg/Child.html\" title=\"type parameter in Child\">"
+ "T</a>></code></dd>",
//Make sure "Overrides" has substituted type parameters.
"<dt><span class=\"overrideSpecifyLabel\">Overrides:</span></dt>\n"
+ "<dd><code><a href=\"../pkg/Parent.html#method--\">method</a>"
+ "</code> in class <code><a href=\"../pkg/Parent.html\" "
+ "title=\"class in pkg\">Parent</a><<a href=\"../pkg/Child.html\" "
+ "title=\"type parameter in Child\">T</a>></code></dd>");
checkOutput("pkg/Parent.html", true,
//Make sure "Direct Know Subclasses" omits type parameters
"<dl>\n"
+ "<dt>Direct Known Subclasses:</dt>\n"
+ "<dd><a href=\"../pkg/Child.html\" title=\"class in pkg\">Child"
+ "</a></dd>\n"
+ "</dl>");
checkOutput("pkg/Interface.html", false,
"public int method()",
"public static final int field");
}
}
| gpl-2.0 |
simplechen/oceanbase | oceanbase_0.4/src/common/ob_rpc_client.cpp | 5979 | #include <tbnet.h>
#include "packet.h"
#include "ob_result.h"
#include "ob_scanner.h"
#include "ob_scan_param.h"
#include "ob_define.h"
#include "ob_rpc_client.h"
#include "ob_client_packet.h"
using namespace tbnet;
using namespace oceanbase::common;
ObRpcClient::ObRpcClient(const ObServer & server):init_(false), ready_(false)
{
retry_times_ = 0;
retry_interval_ = DEFAULT_RETRY_INTERVAL;
server_ = server;
param_buffer_ = NULL;
}
ObRpcClient::~ObRpcClient()
{
if (param_buffer_ != NULL)
{
delete []param_buffer_;
param_buffer_ = NULL;
}
close();
}
int ObRpcClient::init(void)
{
int ret = OB_SUCCESS;
param_buffer_ = new(std::nothrow) char[MAX_PARAM_LEN];
if (NULL == param_buffer_)
{
ret = OB_ERROR;
TBSYS_LOG(ERROR, "alloc param temp buffer failed");
}
/// init receive buffer
if (OB_SUCCESS == ret)
{
char hostname[MAX_ADDR_LEN] = "";
int32_t port = server_.get_port();
server_.set_port(0);
server_.ip_to_string(hostname, sizeof(hostname));
socket_.setAddress(hostname, port);
server_.set_port(port);
init_ = true;
}
return ret;
}
int ObRpcClient::construct_request(const int64_t timeout, const ObScanParam & param)
{
ObDataBuffer data;
data.set_data(param_buffer_, MAX_PARAM_LEN);
int64_t len = 0;
int ret = param.serialize(data.get_data(), data.get_capacity(), len);
if (ret != OB_SUCCESS)
{
TBSYS_LOG(WARN, "param serialize failed:ret[%d]", ret);
}
else
{
rpc_packet_.set_data(data);
rpc_packet_.set_packet_code(OB_SCAN_REQUEST);
rpc_packet_.setChannelId(0);
rpc_packet_.set_source_timeout(timeout);
rpc_packet_.set_api_version(1);
ret = rpc_packet_.serialize();
if (ret != OB_SUCCESS)
{
TBSYS_LOG(WARN, "serialize packet failed:ret[%d]", ret);
}
}
if (OB_SUCCESS == ret)
{
request_buffer_.ensureFree(MAX_PARAM_LEN);
if (!stream_.encode(&rpc_packet_, &request_buffer_))
{
ret = OB_ERROR;
TBSYS_LOG(WARN, "encode packet failed:ret[%d]", ret);
}
}
return ret;
}
int ObRpcClient::parse_response(ObScanner & result, int & code)
{
int ret = OB_SUCCESS;
PacketHeader header;
bool broken = false;
if (!stream_.getPacketInfo(&response_buffer_, &header, &broken))
{
TBSYS_LOG(WARN, "get packet info failed:ret[%d]", ret);
}
else
{
if (!response_packet_.decode(&response_buffer_, &header))
{
ret = OB_ERROR;
TBSYS_LOG(WARN, "decode packet failed:ret[%d]", ret);
}
else
{
ret = response_packet_.deserialize();
if (ret != OB_SUCCESS)
{
TBSYS_LOG(WARN, "deserialize packet failed:ret[%d]", ret);
}
}
}
if (OB_SUCCESS == ret)
{
ret = parse_packet(result, code);
}
return ret;
}
int ObRpcClient::parse_packet(ObScanner & result, int & code)
{
ObResultCode result_code;
int64_t len = response_packet_.get_data_length();
int64_t pos = 0;
ObDataBuffer * data = response_packet_.get_buffer();
assert(data != NULL);
int ret = result_code.deserialize(data->get_data(), len, pos);
if (ret != OB_SUCCESS)
{
TBSYS_LOG(WARN, "deserialize result code failed:ret[%d]", ret);
}
else if (OB_SUCCESS == (code = result_code.result_code_))
{
ret = result.deserialize(data->get_data(), len, pos);
if (ret != OB_SUCCESS)
{
TBSYS_LOG(WARN, "deserialize result failed:ret[%d]", ret);
}
}
return ret;
}
int ObRpcClient::scan(const ObScanParam & param, const int64_t timeout, ObScanner & result)
{
int ret = OB_ERROR;
if (init_)
{
ret = construct_request(timeout, param);
if (OB_SUCCESS == ret)
{
ret = request(retry_times_, timeout);
if (ret != OB_SUCCESS)
{
TBSYS_LOG(WARN, "rquest failed:ret[%d]", ret);
}
}
// parse response
if (OB_SUCCESS == ret)
{
int code = OB_SUCCESS;
ret = parse_response(result, code);
if (ret != OB_SUCCESS)
{
TBSYS_LOG(WARN, "parse response failed:server[%s], ret[%d]", to_cstring(server_), ret);
close();
}
if (code != OB_SUCCESS)
{
ret = code;
}
}
}
else
{
TBSYS_LOG(WARN, "not init ready");
}
return ret;
}
int ObRpcClient::request(const int64_t retry_times, const int64_t timeout)
{
int ret = OB_SUCCESS;
for (int64_t i = 0; i <= retry_times; ++i)
{
ret = connect();
if (ret != OB_SUCCESS)
{
TBSYS_LOG(WARN, "connect failed");
break;
}
else
{
ret = write();
if (OB_SUCCESS == ret)
{
ret = read(timeout);
if (OB_SUCCESS == ret)
{
break;
}
}
}
usleep(retry_interval_);
}
return ret;
}
int ObRpcClient::write(void)
{
int ret = socket_.write(request_buffer_.getData(), request_buffer_.getDataLen());
if (ret != OB_SUCCESS)
{
close();
TBSYS_LOG(WARN, "socket write failed:server[%s], len[%d], ret[%d]",
to_cstring(server_), request_buffer_.getDataLen(), ret);
}
return ret;
}
int ObRpcClient::read(const int64_t timeout)
{
////////////////for timeout check///////////////////////////////
UNUSED(timeout);
PacketHeader packet;
int ret = socket_.read(&packet, sizeof(packet));
if (OB_SUCCESS == ret)
{
ret = socket_.read(response_buffer_.getData(), packet._dataLen);
if (ret != OB_SUCCESS)
{
TBSYS_LOG(WARN, "socket read failed:server[%s], ret[%d]", to_cstring(server_), ret);
close();
}
}
return ret;
}
int ObRpcClient::connect(void)
{
int ret = OB_SUCCESS;
if (!init_)
{
ret = OB_ERROR;
TBSYS_LOG(WARN, "stauts error not init");
}
else if (!ready_)
{
if (true == socket_.connect())
{
ready_ = true;
}
else
{
ret = OB_ERROR;
TBSYS_LOG(WARN, "connect failed:server[%s]", to_cstring(server_));
}
}
return ret;
}
void ObRpcClient::close(void)
{
if (init_ && ready_)
{
ready_ = false;
socket_.close();
}
}
| gpl-2.0 |
freshfrog/tr9823.es | libraries/gantry/admin/widgets/fonts/js/fonts.js | 672 | /*
* @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2012 RocketTheme, LLC
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*/
var GantryFonts={init:function(a,e,f){var d=document.id(GantryParamsPrefix+a),c=document.id(GantryParamsPrefix+e),b=document.id(GantryParamsPrefix+f);if(d&&c){d.addEvent("onChange",function(){var h=c.value;
if(b){var g=b.getElements("."+h);if(this.value=="1"){b.getPrevious().getElements("li."+h).removeClass("disabled");g.removeProperty("disabled");}else{b.getPrevious().getElements("li."+h).addClass("disabled");
g.setProperty("disabled","disabled");}}});d.fireEvent("onChange");}}}; | gpl-2.0 |
domderen/ripple-cs | Ripple/BouncyCastle/test/src/test/MacTest.cs | 5246 | using System;
using System.Text;
using NUnit.Framework;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.Tests
{
/// <remarks>
/// MAC tester - vectors from
/// <a href="http://www.itl.nist.gov/fipspubs/fip81.htm">FIP 81</a> and
/// <a href="http://www.itl.nist.gov/fipspubs/fip113.htm">FIP 113</a>.
/// </remarks>
[TestFixture]
public class MacTest
: SimpleTest
{
private static readonly byte[] keyBytes = Hex.Decode("0123456789abcdef");
private static readonly byte[] ivBytes = Hex.Decode("1234567890abcdef");
private static readonly byte[] input = Hex.Decode("37363534333231204e6f77206973207468652074696d6520666f7220");
private static readonly byte[] output1 = Hex.Decode("f1d30f68");
private static readonly byte[] output2 = Hex.Decode("58d2e77e");
private static readonly byte[] output3 = Hex.Decode("cd647403");
private static readonly byte[] keyBytesISO9797 = Hex.Decode("7CA110454A1A6E570131D9619DC1376E");
private static readonly byte[] inputISO9797 = Encoding.ASCII.GetBytes("Hello World !!!!");
private static readonly byte[] outputISO9797 = Hex.Decode("F09B856213BAB83B");
private static readonly byte[] inputDesEDE64 = Encoding.ASCII.GetBytes("Hello World !!!!");
private static readonly byte[] outputDesEDE64 = Hex.Decode("862304d33af01096");
private void aliasTest(
KeyParameter key,
string primary,
params string[] aliases)
{
IMac mac = MacUtilities.GetMac(primary);
//
// standard DAC - zero IV
//
mac.Init(key);
mac.BlockUpdate(input, 0, input.Length);
byte[] refBytes = new byte[mac.GetMacSize()];
mac.DoFinal(refBytes, 0);
for (int i = 0; i != aliases.Length; i++)
{
mac = MacUtilities.GetMac(aliases[i]);
mac.Init(key);
mac.BlockUpdate(input, 0, input.Length);
byte[] outBytes = new byte[mac.GetMacSize()];
mac.DoFinal(outBytes, 0);
if (!AreEqual(outBytes, refBytes))
{
Fail("Failed - expected "
+ Hex.ToHexString(refBytes) + " got "
+ Hex.ToHexString(outBytes));
}
}
}
public override void PerformTest()
{
KeyParameter key = new DesParameters(keyBytes);
IMac mac = MacUtilities.GetMac("DESMac");
//
// standard DAC - zero IV
//
mac.Init(key);
mac.BlockUpdate(input, 0, input.Length);
//byte[] outBytes = mac.DoFinal();
byte[] outBytes = new byte[mac.GetMacSize()];
mac.DoFinal(outBytes, 0);
if (!AreEqual(outBytes, output1))
{
Fail("Failed - expected "
+ Hex.ToHexString(output1) + " got "
+ Hex.ToHexString(outBytes));
}
//
// mac with IV.
//
mac.Init(new ParametersWithIV(key, ivBytes));
mac.BlockUpdate(input, 0, input.Length);
//outBytes = mac.DoFinal();
outBytes = new byte[mac.GetMacSize()];
mac.DoFinal(outBytes, 0);
if (!AreEqual(outBytes, output2))
{
Fail("Failed - expected "
+ Hex.ToHexString(output2) + " got "
+ Hex.ToHexString(outBytes));
}
//
// CFB mac with IV - 8 bit CFB mode
//
mac = MacUtilities.GetMac("DESMac/CFB8");
mac.Init(new ParametersWithIV(key, ivBytes));
mac.BlockUpdate(input, 0, input.Length);
//outBytes = mac.DoFinal();
outBytes = new byte[mac.GetMacSize()];
mac.DoFinal(outBytes, 0);
if (!AreEqual(outBytes, output3))
{
Fail("Failed - expected "
+ Hex.ToHexString(output3) + " got "
+ Hex.ToHexString(outBytes));
}
//
// ISO9797 algorithm 3 using DESEDE
//
key = new DesEdeParameters(keyBytesISO9797);
mac = MacUtilities.GetMac("ISO9797ALG3");
mac.Init(key);
mac.BlockUpdate(inputISO9797, 0, inputISO9797.Length);
//outBytes = mac.DoFinal();
outBytes = new byte[mac.GetMacSize()];
mac.DoFinal(outBytes, 0);
if (!AreEqual(outBytes, outputISO9797))
{
Fail("Failed - expected "
+ Hex.ToHexString(outputISO9797) + " got "
+ Hex.ToHexString(outBytes));
}
//
// 64bit DESede Mac
//
key = new DesEdeParameters(keyBytesISO9797);
mac = MacUtilities.GetMac("DESEDE64");
mac.Init(key);
mac.BlockUpdate(inputDesEDE64, 0, inputDesEDE64.Length);
//outBytes = mac.DoFinal();
outBytes = new byte[mac.GetMacSize()];
mac.DoFinal(outBytes, 0);
if (!AreEqual(outBytes, outputDesEDE64))
{
Fail("Failed - expected "
+ Hex.ToHexString(outputDesEDE64) + " got "
+ Hex.ToHexString(outBytes));
}
aliasTest(
ParameterUtilities.CreateKeyParameter("DESede", keyBytesISO9797),
"DESedeMac64withISO7816-4Padding",
"DESEDE64WITHISO7816-4PADDING",
"DESEDEISO9797ALG1MACWITHISO7816-4PADDING",
"DESEDEISO9797ALG1WITHISO7816-4PADDING");
aliasTest(
ParameterUtilities.CreateKeyParameter("DESede", keyBytesISO9797),
"ISO9797ALG3WITHISO7816-4PADDING",
"ISO9797ALG3MACWITHISO7816-4PADDING");
}
public override string Name
{
get { return "Mac"; }
}
public static void Main(
string[] args)
{
RunTest(new MacTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| gpl-2.0 |
Qalthos/ansible | lib/ansible/modules/cloud/google/gcp_compute_router.py | 16935 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
# ----------------------------------------------------------------------------
#
# This file is automatically generated by Magic Modules and manual
# changes will be clobbered when the file is regenerated.
#
# Please read more about how to change this file at
# https://www.github.com/GoogleCloudPlatform/magic-modules
#
# ----------------------------------------------------------------------------
from __future__ import absolute_import, division, print_function
__metaclass__ = type
################################################################################
# Documentation
################################################################################
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'}
DOCUMENTATION = '''
---
module: gcp_compute_router
description:
- Represents a Router resource.
short_description: Creates a GCP Router
version_added: 2.7
author: Google Inc. (@googlecloudplatform)
requirements:
- python >= 2.6
- requests >= 2.18.4
- google-auth >= 1.3.0
options:
state:
description:
- Whether the given object should exist in GCP
choices:
- present
- absent
default: present
name:
description:
- Name of the resource. The name must be 1-63 characters long, and comply with
RFC1035. Specifically, the name must be 1-63 characters long and match the regular
expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must
be a lowercase letter, and all following characters must be a dash, lowercase
letter, or digit, except the last character, which cannot be a dash.
required: true
description:
description:
- An optional description of this resource.
required: false
network:
description:
- A reference to the network to which this router belongs.
- 'This field represents a link to a Network resource in GCP. It can be specified
in two ways. First, you can place a dictionary with key ''selfLink'' and value
of your resource''s selfLink Alternatively, you can add `register: name-of-resource`
to a gcp_compute_network task and then set this network field to "{{ name-of-resource
}}"'
required: true
bgp:
description:
- BGP information specific to this router.
required: false
suboptions:
asn:
description:
- Local BGP Autonomous System Number (ASN). Must be an RFC6996 private ASN,
either 16-bit or 32-bit. The value will be fixed for this router resource.
All VPN tunnels that link to this router will have the same local ASN.
required: true
advertise_mode:
description:
- User-specified flag to indicate which mode to use for advertisement.
- 'Valid values of this enum field are: DEFAULT, CUSTOM .'
required: false
default: DEFAULT
choices:
- DEFAULT
- CUSTOM
advertised_groups:
description:
- User-specified list of prefix groups to advertise in custom mode.
- This field can only be populated if advertiseMode is CUSTOM and is advertised
to all peers of the router. These groups will be advertised in addition
to any specified prefixes. Leave this field blank to advertise no custom
groups.
- 'This enum field has the one valid value: ALL_SUBNETS .'
required: false
advertised_ip_ranges:
description:
- User-specified list of individual IP ranges to advertise in custom mode.
This field can only be populated if advertiseMode is CUSTOM and is advertised
to all peers of the router. These IP ranges will be advertised in addition
to any specified groups.
- Leave this field blank to advertise no custom IP ranges.
required: false
suboptions:
range:
description:
- The IP range to advertise. The value must be a CIDR-formatted string.
required: false
description:
description:
- User-specified description for the IP range.
required: false
region:
description:
- Region where the router resides.
required: true
extends_documentation_fragment: gcp
notes:
- 'API Reference: U(https://cloud.google.com/compute/docs/reference/rest/v1/routers)'
- 'Google Cloud Router: U(https://cloud.google.com/router/docs/)'
'''
EXAMPLES = '''
- name: create a network
gcp_compute_network:
name: network-router
project: "{{ gcp_project }}"
auth_kind: "{{ gcp_cred_kind }}"
service_account_file: "{{ gcp_cred_file }}"
state: present
register: network
- name: create a router
gcp_compute_router:
name: test_object
network: "{{ network }}"
bgp:
asn: 64514
advertise_mode: CUSTOM
advertised_groups:
- ALL_SUBNETS
advertised_ip_ranges:
- range: 1.2.3.4
- range: 6.7.0.0/16
region: us-central1
project: test_project
auth_kind: serviceaccount
service_account_file: "/tmp/auth.pem"
state: present
'''
RETURN = '''
id:
description:
- The unique identifier for the resource.
returned: success
type: int
creationTimestamp:
description:
- Creation timestamp in RFC3339 text format.
returned: success
type: str
name:
description:
- Name of the resource. The name must be 1-63 characters long, and comply with RFC1035.
Specifically, the name must be 1-63 characters long and match the regular expression
`[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase
letter, and all following characters must be a dash, lowercase letter, or digit,
except the last character, which cannot be a dash.
returned: success
type: str
description:
description:
- An optional description of this resource.
returned: success
type: str
network:
description:
- A reference to the network to which this router belongs.
returned: success
type: dict
bgp:
description:
- BGP information specific to this router.
returned: success
type: complex
contains:
asn:
description:
- Local BGP Autonomous System Number (ASN). Must be an RFC6996 private ASN,
either 16-bit or 32-bit. The value will be fixed for this router resource.
All VPN tunnels that link to this router will have the same local ASN.
returned: success
type: int
advertiseMode:
description:
- User-specified flag to indicate which mode to use for advertisement.
- 'Valid values of this enum field are: DEFAULT, CUSTOM .'
returned: success
type: str
advertisedGroups:
description:
- User-specified list of prefix groups to advertise in custom mode.
- This field can only be populated if advertiseMode is CUSTOM and is advertised
to all peers of the router. These groups will be advertised in addition to
any specified prefixes. Leave this field blank to advertise no custom groups.
- 'This enum field has the one valid value: ALL_SUBNETS .'
returned: success
type: list
advertisedIpRanges:
description:
- User-specified list of individual IP ranges to advertise in custom mode. This
field can only be populated if advertiseMode is CUSTOM and is advertised to
all peers of the router. These IP ranges will be advertised in addition to
any specified groups.
- Leave this field blank to advertise no custom IP ranges.
returned: success
type: complex
contains:
range:
description:
- The IP range to advertise. The value must be a CIDR-formatted string.
returned: success
type: str
description:
description:
- User-specified description for the IP range.
returned: success
type: str
region:
description:
- Region where the router resides.
returned: success
type: str
'''
################################################################################
# Imports
################################################################################
from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest, remove_nones_from_dict, replace_resource_dict
import json
import time
################################################################################
# Main
################################################################################
def main():
"""Main function"""
module = GcpModule(
argument_spec=dict(
state=dict(default='present', choices=['present', 'absent'], type='str'),
name=dict(required=True, type='str'),
description=dict(type='str'),
network=dict(required=True, type='dict'),
bgp=dict(
type='dict',
options=dict(
asn=dict(required=True, type='int'),
advertise_mode=dict(default='DEFAULT', type='str', choices=['DEFAULT', 'CUSTOM']),
advertised_groups=dict(type='list', elements='str'),
advertised_ip_ranges=dict(type='list', elements='dict', options=dict(range=dict(type='str'), description=dict(type='str'))),
),
),
region=dict(required=True, type='str'),
)
)
if not module.params['scopes']:
module.params['scopes'] = ['https://www.googleapis.com/auth/compute']
state = module.params['state']
kind = 'compute#router'
fetch = fetch_resource(module, self_link(module), kind)
changed = False
if fetch:
if state == 'present':
if is_different(module, fetch):
update(module, self_link(module), kind)
fetch = fetch_resource(module, self_link(module), kind)
changed = True
else:
delete(module, self_link(module), kind)
fetch = {}
changed = True
else:
if state == 'present':
fetch = create(module, collection(module), kind)
changed = True
else:
fetch = {}
fetch.update({'changed': changed})
module.exit_json(**fetch)
def create(module, link, kind):
auth = GcpSession(module, 'compute')
return wait_for_operation(module, auth.post(link, resource_to_request(module)))
def update(module, link, kind):
auth = GcpSession(module, 'compute')
return wait_for_operation(module, auth.patch(link, resource_to_request(module)))
def delete(module, link, kind):
auth = GcpSession(module, 'compute')
return wait_for_operation(module, auth.delete(link))
def resource_to_request(module):
request = {
u'kind': 'compute#router',
u'region': module.params.get('region'),
u'name': module.params.get('name'),
u'description': module.params.get('description'),
u'network': replace_resource_dict(module.params.get(u'network', {}), 'selfLink'),
u'bgp': RouterBgp(module.params.get('bgp', {}), module).to_request(),
}
return_vals = {}
for k, v in request.items():
if v or v is False:
return_vals[k] = v
return return_vals
def fetch_resource(module, link, kind, allow_not_found=True):
auth = GcpSession(module, 'compute')
return return_if_object(module, auth.get(link), kind, allow_not_found)
def self_link(module):
return "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/routers/{name}".format(**module.params)
def collection(module):
return "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/routers".format(**module.params)
def return_if_object(module, response, kind, allow_not_found=False):
# If not found, return nothing.
if allow_not_found and response.status_code == 404:
return None
# If no content, return nothing.
if response.status_code == 204:
return None
try:
module.raise_for_status(response)
result = response.json()
except getattr(json.decoder, 'JSONDecodeError', ValueError):
module.fail_json(msg="Invalid JSON response with error: %s" % response.text)
if navigate_hash(result, ['error', 'errors']):
module.fail_json(msg=navigate_hash(result, ['error', 'errors']))
return result
def is_different(module, response):
request = resource_to_request(module)
response = response_to_hash(module, response)
# Remove all output-only from response.
response_vals = {}
for k, v in response.items():
if k in request:
response_vals[k] = v
request_vals = {}
for k, v in request.items():
if k in response:
request_vals[k] = v
return GcpRequest(request_vals) != GcpRequest(response_vals)
# Remove unnecessary properties from the response.
# This is for doing comparisons with Ansible's current parameters.
def response_to_hash(module, response):
return {
u'id': response.get(u'id'),
u'creationTimestamp': response.get(u'creationTimestamp'),
u'name': module.params.get('name'),
u'description': response.get(u'description'),
u'network': replace_resource_dict(module.params.get(u'network', {}), 'selfLink'),
u'bgp': RouterBgp(response.get(u'bgp', {}), module).from_response(),
}
def async_op_url(module, extra_data=None):
if extra_data is None:
extra_data = {}
url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/operations/{op_id}"
combined = extra_data.copy()
combined.update(module.params)
return url.format(**combined)
def wait_for_operation(module, response):
op_result = return_if_object(module, response, 'compute#operation')
if op_result is None:
return {}
status = navigate_hash(op_result, ['status'])
wait_done = wait_for_completion(status, op_result, module)
return fetch_resource(module, navigate_hash(wait_done, ['targetLink']), 'compute#router')
def wait_for_completion(status, op_result, module):
op_id = navigate_hash(op_result, ['name'])
op_uri = async_op_url(module, {'op_id': op_id})
while status != 'DONE':
raise_if_errors(op_result, ['error', 'errors'], module)
time.sleep(1.0)
op_result = fetch_resource(module, op_uri, 'compute#operation', False)
status = navigate_hash(op_result, ['status'])
return op_result
def raise_if_errors(response, err_path, module):
errors = navigate_hash(response, err_path)
if errors is not None:
module.fail_json(msg=errors)
class RouterBgp(object):
def __init__(self, request, module):
self.module = module
if request:
self.request = request
else:
self.request = {}
def to_request(self):
return remove_nones_from_dict(
{
u'asn': self.request.get('asn'),
u'advertiseMode': self.request.get('advertise_mode'),
u'advertisedGroups': self.request.get('advertised_groups'),
u'advertisedIpRanges': RouterAdvertisediprangesArray(self.request.get('advertised_ip_ranges', []), self.module).to_request(),
}
)
def from_response(self):
return remove_nones_from_dict(
{
u'asn': self.request.get(u'asn'),
u'advertiseMode': self.request.get(u'advertiseMode'),
u'advertisedGroups': self.request.get(u'advertisedGroups'),
u'advertisedIpRanges': RouterAdvertisediprangesArray(self.request.get(u'advertisedIpRanges', []), self.module).from_response(),
}
)
class RouterAdvertisediprangesArray(object):
def __init__(self, request, module):
self.module = module
if request:
self.request = request
else:
self.request = []
def to_request(self):
items = []
for item in self.request:
items.append(self._request_for_item(item))
return items
def from_response(self):
items = []
for item in self.request:
items.append(self._response_from_item(item))
return items
def _request_for_item(self, item):
return remove_nones_from_dict({u'range': item.get('range'), u'description': item.get('description')})
def _response_from_item(self, item):
return remove_nones_from_dict({u'range': item.get(u'range'), u'description': item.get(u'description')})
if __name__ == '__main__':
main()
| gpl-3.0 |
McLoo/RedPhone | src/org/thoughtcrime/redphone/util/FilteredCursor.java | 10219 | /*
* Copyright (C) 2014 Clover Network, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thoughtcrime.redphone.util;
import android.database.CharArrayBuffer;
import android.database.Cursor;
import android.database.CursorWrapper;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
/**
* Wraps a Cursor and allowing its positions to be filtered out, repeated, or reordered. Common ways of creating
* FilteredCursor objects are provided by the {@link FilteredCursorFactory}.
*
* Note that if the source Cursor exceeds the size of the {@link android.database.CursorWindow} the FilteredCursor
* may end up having extremely poor performance due to frequent CursorWindow cache misses. In those cases it is
* recommended that source Cursor contain less data.
*
* @author Jacob Whitaker Abrams
*/
public class FilteredCursor extends CursorWrapper {
// Globally map master Cursor to FilteredCursors, when all FilteredCursors are closed go ahead and close the master
// This would need to go into a singleton if other classes similar to FilteredCursor exist
// private static final Map<Cursor, Set<FilteredCursor>> sMasterCursorMap =
// Collections.synchronizedMap(new WeakHashMap<Cursor, Set<FilteredCursor>>());
private int[] mFilterMap;
private int mPos = -1;
private final Cursor mCursor;
private boolean mClosed;
// /**
// * Create a FilteredCursor that appears identical to its wrapped Cursor.
// */
// public static FilteredCursor createUsingIdentityFilter(Cursor cursor) {
// if (cursor == null) {
// return null;
// }
// return new FilteredCursor(cursor);
// }
/**
* Create a new FilteredCursor using the given filter. The filter specifies where rows of the given Cursor should
* appear in the FilteredCursor. For example if filter = { 5, 9 } then the FilteredCursor will have two rows, the
* first row maps to row 5 in the source Cursor and the second row maps to row 9 in the source cursor. Returns null
* if the provided cursor is null. A value of -1 in the filter is treated as an empty row in the Cursor with no data,
* see {@link FilteredCursor#isPositionEmpty()}.
*/
public static FilteredCursor createUsingFilter(Cursor cursor, int[] filter) {
if (cursor == null) {
return null;
}
if (filter == null) {
throw new NullPointerException();
}
return new FilteredCursor(cursor, filter);
}
// private FilteredCursor(Cursor cursor) {
// this(cursor, null);
// resetToIdentityFilter();
// }
private FilteredCursor(Cursor cursor, int[] filterMap) {
super(cursor);
mCursor = cursor;
mFilterMap = filterMap;
// attachToMasterCursor();
}
public int[] getFilterMap() {
return mFilterMap;
}
// /**
// * Reset the filter so it appears identical to its wrapped Cursor.
// */
// public FilteredCursor resetToIdentityFilter() {
// int count = mCursor.getCount();
// int[] filterMap = new int[count];
//
// for (int i = 0; i < count; i++) {
// filterMap[i] = i;
// }
//
// mFilterMap = filterMap;
// mPos = -1;
// return this;
// }
// /**
// * Returns true if the FilteredCursor appears identical to its wrapped Cursor.
// */
// public boolean isIdentityFilter() {
// int count = mCursor.getCount();
// if (mFilterMap.length != count) {
// return false;
// }
//
// for (int i = 0; i < count; i++) {
// if (mFilterMap[i] != i) {
// return false;
// }
// }
//
// return true;
// }
// /**
// * Rearrange the filter. The new arrangement is based on the current filter arrangement, not on the source Cursor's
// * arrangement.
// */
// public FilteredCursor refilter(int[] newArrangement) {
// final int newMapSize = newArrangement.length;
// int[] newMap = new int[newMapSize];
// for (int i = 0; i < newMapSize; i++) {
// newMap[i] = mFilterMap[newArrangement[i]];
// }
//
// mFilterMap = newMap;
// mPos = -1;
// return this;
// }
/**
* True if the current cursor position has no data. Attempting to access data in an empty row with any of the getters
* will throw {@link UnsupportedOperationException}.
*/
public boolean isPositionEmpty() {
return mFilterMap[mPos] == -1;
}
private void throwIfEmptyRow() {
if (isPositionEmpty()) {
throw new UnsupportedOperationException("Cannot access data in an empty row");
}
}
// public void swapItems(int itemOne, int itemTwo) {
// int temp = mFilterMap[itemOne];
// mFilterMap[itemOne] = mFilterMap[itemTwo];
// mFilterMap[itemTwo] = temp;
// }
@Override
public int getCount() {
return mFilterMap.length;
}
@Override
public int getPosition() {
return mPos;
}
@Override
public boolean moveToPosition(int position) {
// Make sure position isn't past the end of the cursor
final int count = getCount();
if (position >= count) {
mPos = count;
return false;
}
// Make sure position isn't before the beginning of the cursor
if (position < 0) {
mPos = -1;
return false;
}
final int realPosition = mFilterMap[position];
// When moving to an empty position, just pretend we did it
boolean moved = realPosition == -1 ? true : super.moveToPosition(realPosition);
if (moved) {
mPos = position;
} else {
mPos = -1;
}
return moved;
}
@Override
public final boolean move(int offset) {
return moveToPosition(mPos + offset);
}
@Override
public final boolean moveToFirst() {
return moveToPosition(0);
}
@Override
public final boolean moveToLast() {
return moveToPosition(getCount() - 1);
}
@Override
public final boolean moveToNext() {
return moveToPosition(mPos + 1);
}
@Override
public final boolean moveToPrevious() {
return moveToPosition(mPos - 1);
}
@Override
public final boolean isFirst() {
return mPos == 0 && getCount() != 0;
}
@Override
public final boolean isLast() {
int count = getCount();
return mPos == (count - 1) && count != 0;
}
@Override
public final boolean isBeforeFirst() {
if (getCount() == 0) {
return true;
}
return mPos == -1;
}
@Override
public final boolean isAfterLast() {
if (getCount() == 0) {
return true;
}
return mPos == getCount();
}
@Override
public boolean isNull(int columnIndex) {
throwIfEmptyRow();
return mCursor.isNull(columnIndex);
}
@Override
public void copyStringToBuffer(int columnIndex, CharArrayBuffer buffer) {
throwIfEmptyRow();
mCursor.copyStringToBuffer(columnIndex, buffer);
}
@Override
public byte[] getBlob(int columnIndex) {
throwIfEmptyRow();
return mCursor.getBlob(columnIndex);
}
@Override
public double getDouble(int columnIndex) {
throwIfEmptyRow();
return mCursor.getDouble(columnIndex);
}
@Override
public float getFloat(int columnIndex) {
throwIfEmptyRow();
return mCursor.getFloat(columnIndex);
}
@Override
public int getInt(int columnIndex) {
throwIfEmptyRow();
return mCursor.getInt(columnIndex);
}
@Override
public long getLong(int columnIndex) {
throwIfEmptyRow();
return mCursor.getLong(columnIndex);
}
@Override
public short getShort(int columnIndex) {
throwIfEmptyRow();
return mCursor.getShort(columnIndex);
}
@Override
public String getString(int columnIndex) {
throwIfEmptyRow();
return mCursor.getString(columnIndex);
}
@Override
public boolean isClosed() {
return mClosed || getMasterCursor().isClosed();
}
@Override
public void close() {
// Mark this Cursor as closed
mClosed = true;
// Find the master Cursor and close it if all linked cursors are closed
Cursor masterCursor = getMasterCursor();
// Set<FilteredCursor> linkedFilteredCursorSet = sMasterCursorMap.get(masterCursor);
// if (linkedFilteredCursorSet == null) {
masterCursor.close(); // Shouldn't ever happen?
// } else {
// linkedFilteredCursorSet.remove(this);
// if (linkedFilteredCursorSet.isEmpty()) {
// masterCursor.close();
// }
// }
// if (masterCursor.isClosed()) {
// sMasterCursorMap.remove(masterCursor);
// }
}
@Override
@Deprecated
public boolean requery() {
throw new UnsupportedOperationException();
}
// private void attachToMasterCursor() {
// Cursor masterCursor = getMasterCursor();
// Set<FilteredCursor> filteredCursorSet = sMasterCursorMap.get(masterCursor);
// if (filteredCursorSet == null) {
// filteredCursorSet = Collections.synchronizedSet(new HashSet<FilteredCursor>());
// sMasterCursorMap.put(masterCursor, filteredCursorSet);
// }
// filteredCursorSet.add(this);
// }
// /** Returns the first non-CursorWrapper instance contained within this object. */
// public Cursor getMasterCursor() {
// Cursor cursor = mCursor;
//
// while (cursor instanceof CursorWrapper) {
// cursor = ((CursorWrapper) cursor).getWrappedCursor();
// }
//
// return cursor;
// }
public Cursor getMasterCursor() {
return mCursor;
}
// /** Returns the first FilteredCursor wrapped by the provided cursor or null if no FilteredCursor is found. */
// public static FilteredCursor unwrapFilteredCursor(Cursor cursor) {
// while (cursor instanceof CursorWrapper) {
// if (cursor instanceof FilteredCursor) {
// return (FilteredCursor)cursor;
// } else {
// cursor = ((CursorWrapper) cursor).getWrappedCursor();
// }
// }
//
// return null;
// }
} | gpl-3.0 |
Acidburn0zzz/servo | tests/wpt/web-platform-tests/fetch/api/redirect/redirect-mode.any.js | 2190 | // META: script=/common/get-host-info.sub.js
var redirectLocation = "cors-top.txt";
function testRedirect(origin, redirectStatus, redirectMode, corsMode) {
var url = new URL("../resources/redirect.py", self.location);
if (origin === "cross-origin") {
url.host = get_host_info().REMOTE_HOST;
url.port = get_host_info().HTTP_PORT;
}
var urlParameters = "?redirect_status=" + redirectStatus;
urlParameters += "&location=" + encodeURIComponent(redirectLocation);
var requestInit = {redirect: redirectMode, mode: corsMode};
promise_test(function(test) {
if (redirectMode === "error" ||
(corsMode === "no-cors" && redirectMode !== "follow" && origin !== "same-origin"))
return promise_rejects_js(test, TypeError, fetch(url + urlParameters, requestInit));
if (redirectMode === "manual")
return fetch(url + urlParameters, requestInit).then(function(resp) {
assert_equals(resp.status, 0, "Response's status is 0");
assert_equals(resp.type, "opaqueredirect", "Response's type is opaqueredirect");
assert_equals(resp.statusText, "", "Response's statusText is \"\"");
assert_equals(resp.url, url + urlParameters, "Response URL should be the original one");
});
if (redirectMode === "follow")
return fetch(url + urlParameters, requestInit).then(function(resp) {
if (corsMode !== "no-cors" || origin === "same-origin") {
assert_true(new URL(resp.url).pathname.endsWith(redirectLocation), "Response's url should be the redirected one");
assert_equals(resp.status, 200, "Response's status is 200");
} else {
assert_equals(resp.type, "opaque", "Response is opaque");
}
});
assert_unreached(redirectMode + " is no a valid redirect mode");
}, origin + " redirect " + redirectStatus + " in " + redirectMode + " redirect and " + corsMode + " mode");
}
for (var origin of ["same-origin", "cross-origin"]) {
for (var statusCode of [301, 302, 303, 307, 308]) {
for (var redirect of ["error", "manual", "follow"]) {
for (var mode of ["cors", "no-cors"])
testRedirect(origin, statusCode, redirect, mode);
}
}
}
done();
| mpl-2.0 |
sainaen/rhino | testsrc/tests/lc2/jsref.js | 4737 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var completed = false;
var testcases;
SECTION = "";
VERSION = "";
BUGNUMBER="";
EXCLUDE = "";
var TT = "";
var TT_ = "";
var BR = "";
var NBSP = " ";
var CR = "\n";
var FONT = "";
var FONT_ = "";
var FONT_RED = "";
var FONT_GREEN = "";
var B = "";
var B_ = ""
var H2 = "";
var H2_ = "";
var HR = "";
// version("130");
var PASSED = " PASSED!"
var FAILED = " FAILED! expected: ";
function TestCase( n, d, e, a ) {
this.name = n;
this.description = d;
this.expect = e;
this.actual = a;
this.passed = true;
this.reason = "";
this.bugnumber = BUGNUMBER;
this.passed = getTestCaseResult( this.expect, this.actual );
}
function startTest() {
// JavaScript 1.3 is supposed to be compliant ecma version 1.0
if ( VERSION == "ECMA_1" ) {
version ( "130" );
}
if ( VERSION == "JS_1.3" ) {
version ( "130" );
}
if ( VERSION == "JS_1.2" ) {
version ( "120" );
}
if ( VERSION == "JS_1.1" ) {
version ( "110" );
}
// for ecma version 2.0, we will leave the javascript version to
// the default ( for now ).
}
function getTestCaseResult( expect, actual ) {
// because ( NaN == NaN ) always returns false, need to do
// a special compare to see if we got the right result.
if ( actual != actual ) {
if ( typeof actual == "object" ) {
actual = "NaN object";
} else {
actual = "NaN number";
}
}
if ( expect != expect ) {
if ( typeof expect == "object" ) {
expect = "NaN object";
} else {
expect = "NaN number";
}
}
var passed = ( expect == actual ) ? true : false;
// if both objects are numbers
// need to replace w/ IEEE standard for rounding
if ( !passed
&& typeof(actual) == "number"
&& typeof(expect) == "number"
) {
if ( Math.abs(actual-expect) < 0.0000001 ) {
passed = true;
}
}
// verify type is the same
if ( typeof(expect) != typeof(actual) ) {
passed = false;
}
return passed;
}
function writeTestCaseResult( expect, actual, string ) {
var passed = getTestCaseResult( expect, actual );
writeFormattedResult( expect, actual, string, passed );
return passed;
}
function writeFormattedResult( expect, actual, string, passed ) {
var s = TT + string ;
for ( k = 0;
k < (60 - string.length >= 0 ? 60 - string.length : 5) ;
k++ ) {
// s += NBSP;
}
s += B ;
s += ( passed ) ? FONT_GREEN + NBSP + PASSED : FONT_RED + NBSP + FAILED + expect + TT_ ;
print( s + FONT_ + B_ + TT_ );
return passed;
}
function writeHeaderToLog( string ) {
print( H2 + string + H2_ );
}
function stopTest()
{
var sizeTag = "<#TEST CASES SIZE>";
var doneTag = "<#TEST CASES DONE>";
var beginTag = "<#TEST CASE ";
var endTag = ">";
print(sizeTag);
print(testcases.length);
for (tc = 0; tc < testcases.length; tc++)
{
print(beginTag + 'PASSED' + endTag);
print(testcases[tc].passed);
print(beginTag + 'NAME' + endTag);
print(testcases[tc].name);
print(beginTag + 'EXPECTED' + endTag);
print(testcases[tc].expect);
print(beginTag + 'ACTUAL' + endTag);
print(testcases[tc].actual);
print(beginTag + 'DESCRIPTION' + endTag);
print(testcases[tc].description);
print(beginTag + 'REASON' + endTag);
print(( testcases[tc].passed ) ? "" : "wrong value ");
print(beginTag + 'BUGNUMBER' + endTag);
print( BUGNUMBER );
}
print(doneTag);
print( HR );
gc();
}
function getFailedCases() {
for ( var i = 0; i < testcases.length; i++ ) {
if ( ! testcases[i].passed ) {
print( testcases[i].description +" = " +testcases[i].actual +" expected: "+ testcases[i].expect );
}
}
}
function err( msg, page, line ) {
testcases[tc].actual = "error";
testcases[tc].reason = msg;
writeTestCaseResult( testcases[tc].expect,
testcases[tc].actual,
testcases[tc].description +" = "+ testcases[tc].actual +
": " + testcases[tc].reason );
stopTest();
return true;
}
| mpl-2.0 |
AlexTrotsenko/rhino | testsrc/tests/js1_5/extensions/regress-353214.js | 1045 | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var gTestfile = 'regress-353214.js';
//-----------------------------------------------------------------------------
var BUGNUMBER = 353214;
var summary = 'decompilation of |function() { (function ([x]) { })(); eval("return 3;") }|';
var actual = '';
var expect = '';
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
var f = function() { (function ([x]) { })(); eval('return 3;') }
expect = 'function() { (function ([x]) { }()); eval("return 3;"); }';
actual = f + '';
compareSource(expect, actual, summary);
exitFunc ('test');
}
| mpl-2.0 |
elandau/karyon | karyon2-eureka/src/main/java/netflix/karyon/eureka/EurekaHealthCheckHandler.java | 1599 | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package netflix.karyon.eureka;
import com.netflix.appinfo.InstanceInfo;
import netflix.karyon.health.HealthCheckHandler;
import javax.inject.Inject;
/**
* @author Nitesh Kant
*/
public class EurekaHealthCheckHandler implements com.netflix.appinfo.HealthCheckHandler {
private final HealthCheckHandler healthCheckHandler;
private final EurekaKaryonStatusBridge eurekaKaryonStatusBridge;
@Inject
public EurekaHealthCheckHandler(HealthCheckHandler healthCheckHandler,
EurekaKaryonStatusBridge eurekaKaryonStatusBridge) {
this.healthCheckHandler = healthCheckHandler;
this.eurekaKaryonStatusBridge = eurekaKaryonStatusBridge;
}
@Override
public InstanceInfo.InstanceStatus getStatus(InstanceInfo.InstanceStatus currentStatus) {
int healthStatus = healthCheckHandler.getStatus();
return eurekaKaryonStatusBridge.interpretKaryonStatus(healthStatus);
}
}
| apache-2.0 |
alangrafu/lodspeakr | lib/Haanga/contrib/meneame_pagination.php | 1511 | <?php
class Haanga_Extension_Tag_MeneamePagination
{
public $is_block = FALSE;
static function generator($cmp, $args, $redirected)
{
if (count($args) != 3 && count($args) != 4) {
throw new Haanga_CompilerException("Memeame_Pagination requires 3 or 4 parameters");
}
if (count($args) == 3) {
$args[3] = 5;
}
$current = hvar('mnm_current');
$total = hvar('mnm_total');
$start = hvar('mnm_start');
$end = hvar('mnm_end');
$prev = hvar('mnm_prev');
$next = hvar('mnm_next');
$pages = 'mnm_pages';
$code = hcode();
$code->decl($current, $args[0]);
$code->decl($total, hexec('ceil', hexpr($args[2], '/', $args[1])) );
$code->decl($start, hexec('max', hexpr($current, '-', hexec('intval', hexpr($args[3],'/', 2))), 1));
$code->decl($end, hexpr($start, '+', $args[3], '-', 1));
$code->decl($prev, hexpr_cond( hexpr(1, '==', $current), FALSE, hexpr($current, '-', 1)) );
$code->decl($next, hexpr_cond( hexpr($args[2], '<', 0, '||', $current, '<', $total), hexpr($current, '+', 1), FALSE));
$code->decl('mnm_pages', hexec('range', $start, hexpr_cond(hexpr($end,'<', $total), $end, $total)));
$cmp->set_safe($current);
$cmp->set_safe($total);
$cmp->set_safe($prev);
$cmp->set_safe($next);
$cmp->set_safe($pages);
return $code;
}
}
| apache-2.0 |
triggerNZ/intellij-scala | src/org/jetbrains/plugins/scala/lang/psi/stubs/elements/ScPackagingElementType.scala | 619 | package org.jetbrains.plugins.scala
package lang
package psi
package stubs
package elements
import _root_.org.jetbrains.plugins.scala.lang.psi.impl.toplevel.packaging.ScPackagingImpl
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.packaging.ScPackaging
/**
* @author ilyas
*/
class ScPackagingElementType extends ScPackageContainerElementType[ScPackaging]("packaging") {
def createElement(node: ASTNode): PsiElement = new ScPackagingImpl(node)
def createPsi(stub: ScPackageContainerStub): ScPackaging = new ScPackagingImpl(stub)
}
| apache-2.0 |
jppope/alloy | Alloy/template/app.js | 283 | /**
* Alloy for Titanium by Appcelerator
* This is generated code, DO NOT MODIFY - changes will be lost!
* Copyright (c) 2012 by Appcelerator, Inc.
*/
var Alloy = require('alloy'),
_ = Alloy._,
Backbone = Alloy.Backbone;
__MAPMARKER_ALLOY_JS__
Alloy.createController('index'); | apache-2.0 |
ern/elasticsearch | plugins/analysis-icu/src/main/java/org/elasticsearch/index/analysis/IcuCollationTokenFilterFactory.java | 6909 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.index.analysis;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import org.apache.lucene.analysis.TokenStream;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.IndexSettings;
import com.ibm.icu.text.Collator;
import com.ibm.icu.text.RuleBasedCollator;
import com.ibm.icu.util.ULocale;
/**
* An ICU based collation token filter. There are two ways to configure collation:
* <p>The first is simply specifying the locale (defaults to the default
* locale). The {@code language} parameter is the lowercase two-letter
* ISO-639 code. An additional {@code country} and {@code variant}
* can be provided.
* <p>The second option is to specify collation rules as defined in the
* <a href="http://www.icu-project.org/userguide/Collate_Customization.html">
* Collation customization</a> chapter in icu docs. The {@code rules}
* parameter can either embed the rules definition
* in the settings or refer to an external location (preferable located under
* the {@code config} location, relative to it).
*/
public class IcuCollationTokenFilterFactory extends AbstractTokenFilterFactory {
private final Collator collator;
public IcuCollationTokenFilterFactory(IndexSettings indexSettings, Environment environment, String name, Settings settings) {
super(indexSettings, name, settings);
Collator collator;
String rules = settings.get("rules");
if (rules != null) {
Exception failureToResolve = null;
try {
rules = Streams.copyToString(Files.newBufferedReader(environment.configFile().resolve(rules), Charset.forName("UTF-8")));
} catch (IOException | SecurityException | InvalidPathException e) {
failureToResolve = e;
}
try {
collator = new RuleBasedCollator(rules);
} catch (Exception e) {
if (failureToResolve != null) {
throw new IllegalArgumentException("Failed to resolve collation rules location", failureToResolve);
} else {
throw new IllegalArgumentException("Failed to parse collation rules", e);
}
}
} else {
String language = settings.get("language");
if (language != null) {
ULocale locale;
String country = settings.get("country");
if (country != null) {
String variant = settings.get("variant");
if (variant != null) {
locale = new ULocale(language, country, variant);
} else {
locale = new ULocale(language, country);
}
} else {
locale = new ULocale(language);
}
collator = Collator.getInstance(locale);
} else {
collator = Collator.getInstance(ULocale.ROOT);
}
}
// set the strength flag, otherwise it will be the default.
String strength = settings.get("strength");
if (strength != null) {
if (strength.equalsIgnoreCase("primary")) {
collator.setStrength(Collator.PRIMARY);
} else if (strength.equalsIgnoreCase("secondary")) {
collator.setStrength(Collator.SECONDARY);
} else if (strength.equalsIgnoreCase("tertiary")) {
collator.setStrength(Collator.TERTIARY);
} else if (strength.equalsIgnoreCase("quaternary")) {
collator.setStrength(Collator.QUATERNARY);
} else if (strength.equalsIgnoreCase("identical")) {
collator.setStrength(Collator.IDENTICAL);
} else {
throw new IllegalArgumentException("Invalid strength: " + strength);
}
}
// set the decomposition flag, otherwise it will be the default.
String decomposition = settings.get("decomposition");
if (decomposition != null) {
if (decomposition.equalsIgnoreCase("no")) {
collator.setDecomposition(Collator.NO_DECOMPOSITION);
} else if (decomposition.equalsIgnoreCase("canonical")) {
collator.setDecomposition(Collator.CANONICAL_DECOMPOSITION);
} else {
throw new IllegalArgumentException("Invalid decomposition: " + decomposition);
}
}
// expert options: concrete subclasses are always a RuleBasedCollator
RuleBasedCollator rbc = (RuleBasedCollator) collator;
String alternate = settings.get("alternate");
if (alternate != null) {
if (alternate.equalsIgnoreCase("shifted")) {
rbc.setAlternateHandlingShifted(true);
} else if (alternate.equalsIgnoreCase("non-ignorable")) {
rbc.setAlternateHandlingShifted(false);
} else {
throw new IllegalArgumentException("Invalid alternate: " + alternate);
}
}
Boolean caseLevel = settings.getAsBoolean("caseLevel", null);
if (caseLevel != null) {
rbc.setCaseLevel(caseLevel);
}
String caseFirst = settings.get("caseFirst");
if (caseFirst != null) {
if (caseFirst.equalsIgnoreCase("lower")) {
rbc.setLowerCaseFirst(true);
} else if (caseFirst.equalsIgnoreCase("upper")) {
rbc.setUpperCaseFirst(true);
} else {
throw new IllegalArgumentException("Invalid caseFirst: " + caseFirst);
}
}
Boolean numeric = settings.getAsBoolean("numeric", null);
if (numeric != null) {
rbc.setNumericCollation(numeric);
}
String variableTop = settings.get("variableTop");
if (variableTop != null) {
rbc.setVariableTop(variableTop);
}
Boolean hiraganaQuaternaryMode = settings.getAsBoolean("hiraganaQuaternaryMode", null);
if (hiraganaQuaternaryMode != null) {
rbc.setHiraganaQuaternary(hiraganaQuaternaryMode);
}
this.collator = collator;
}
@Override
public TokenStream create(TokenStream tokenStream) {
return new ICUCollationKeyFilter(tokenStream, collator);
}
}
| apache-2.0 |
nvoron23/arangodb | UnitTests/Basics/json-utilities-test.cpp | 24628 | ////////////////////////////////////////////////////////////////////////////////
/// @brief test suite for json-utilities.c
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include <boost/test/unit_test.hpp>
#include "Basics/string-buffer.h"
#include "Basics/json-utilities.h"
// -----------------------------------------------------------------------------
// --SECTION-- private macros
// -----------------------------------------------------------------------------
#define JSON_CHECK(expected, func, lValue, rValue) \
l = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, lValue); \
r = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, rValue); \
if (l && r) { \
BOOST_CHECK_EQUAL(expected, func(l, r)); \
TRI_FreeJson(TRI_UNKNOWN_MEM_ZONE, l); \
TRI_FreeJson(TRI_UNKNOWN_MEM_ZONE, r); \
}
#define INIT_BUFFER TRI_string_buffer_t* sb = TRI_CreateStringBuffer(TRI_UNKNOWN_MEM_ZONE);
#define FREE_BUFFER TRI_FreeStringBuffer(TRI_UNKNOWN_MEM_ZONE, sb);
#define STRINGIFY TRI_StringifyJson(sb, json);
#define STRING_VALUE sb->_buffer
#define FREE_JSON TRI_FreeJson(TRI_UNKNOWN_MEM_ZONE, json);
// -----------------------------------------------------------------------------
// --SECTION-- setup / tear-down
// -----------------------------------------------------------------------------
struct CJsonUtilitiesSetup {
CJsonUtilitiesSetup () {
BOOST_TEST_MESSAGE("setup json utilities test");
}
~CJsonUtilitiesSetup () {
BOOST_TEST_MESSAGE("tear-down json utilities test");
}
};
// -----------------------------------------------------------------------------
// --SECTION-- test suite
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief setup
////////////////////////////////////////////////////////////////////////////////
BOOST_FIXTURE_TEST_SUITE(CJsonUtilitiesTest, CJsonUtilitiesSetup)
////////////////////////////////////////////////////////////////////////////////
/// @brief test compare values with equal values
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE (tst_compare_values_equal) {
TRI_json_t* l;
TRI_json_t* r;
// With Utf8-mode:
JSON_CHECK(0, TRI_CompareValuesJson, "null", "null");
JSON_CHECK(0, TRI_CompareValuesJson, "false", "false");
JSON_CHECK(0, TRI_CompareValuesJson, "true", "true");
JSON_CHECK(0, TRI_CompareValuesJson, "0", "0");
JSON_CHECK(0, TRI_CompareValuesJson, "1", "1");
JSON_CHECK(0, TRI_CompareValuesJson, "1.5", "1.5");
JSON_CHECK(0, TRI_CompareValuesJson, "-43.2", "-43.2");
JSON_CHECK(0, TRI_CompareValuesJson, "\"\"", "\"\"");
JSON_CHECK(0, TRI_CompareValuesJson, "\" \"", "\" \"");
JSON_CHECK(0, TRI_CompareValuesJson, "\"the quick brown fox\"", "\"the quick brown fox\"");
JSON_CHECK(0, TRI_CompareValuesJson, "[]", "[]");
JSON_CHECK(0, TRI_CompareValuesJson, "[-1]", "[-1]");
JSON_CHECK(0, TRI_CompareValuesJson, "[0]", "[0]");
JSON_CHECK(0, TRI_CompareValuesJson, "[1]", "[1]");
JSON_CHECK(0, TRI_CompareValuesJson, "[true]", "[true]");
JSON_CHECK(0, TRI_CompareValuesJson, "{}", "{}");
}
////////////////////////////////////////////////////////////////////////////////
/// @brief test compare values with unequal values
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE (tst_compare_values_unequal) {
TRI_json_t* l;
TRI_json_t* r;
JSON_CHECK(-1, TRI_CompareValuesJson, "null", "false");
JSON_CHECK(-1, TRI_CompareValuesJson, "null", "true");
JSON_CHECK(-1, TRI_CompareValuesJson, "null", "-1");
JSON_CHECK(-1, TRI_CompareValuesJson, "null", "0");
JSON_CHECK(-1, TRI_CompareValuesJson, "null", "1");
JSON_CHECK(-1, TRI_CompareValuesJson, "null", "-10");
JSON_CHECK(-1, TRI_CompareValuesJson, "null", "\"\"");
JSON_CHECK(-1, TRI_CompareValuesJson, "null", "\"0\"");
JSON_CHECK(-1, TRI_CompareValuesJson, "null", "\" \"");
JSON_CHECK(-1, TRI_CompareValuesJson, "null", "[]");
JSON_CHECK(-1, TRI_CompareValuesJson, "null", "[null]");
JSON_CHECK(-1, TRI_CompareValuesJson, "null", "[false]");
JSON_CHECK(-1, TRI_CompareValuesJson, "null", "[true]");
JSON_CHECK(-1, TRI_CompareValuesJson, "null", "[0]");
JSON_CHECK(-1, TRI_CompareValuesJson, "null", "{}");
JSON_CHECK(-1, TRI_CompareValuesJson, "false", "true");
JSON_CHECK(-1, TRI_CompareValuesJson, "false", "-1");
JSON_CHECK(-1, TRI_CompareValuesJson, "false", "0");
JSON_CHECK(-1, TRI_CompareValuesJson, "false", "1");
JSON_CHECK(-1, TRI_CompareValuesJson, "false", "-10");
JSON_CHECK(-1, TRI_CompareValuesJson, "false", "\"\"");
JSON_CHECK(-1, TRI_CompareValuesJson, "false", "\"0\"");
JSON_CHECK(-1, TRI_CompareValuesJson, "false", "\" \"");
JSON_CHECK(-1, TRI_CompareValuesJson, "false", "[]");
JSON_CHECK(-1, TRI_CompareValuesJson, "false", "[null]");
JSON_CHECK(-1, TRI_CompareValuesJson, "false", "[false]");
JSON_CHECK(-1, TRI_CompareValuesJson, "false", "[true]");
JSON_CHECK(-1, TRI_CompareValuesJson, "false", "[0]");
JSON_CHECK(-1, TRI_CompareValuesJson, "false", "{}");
JSON_CHECK(-1, TRI_CompareValuesJson, "true", "-1");
JSON_CHECK(-1, TRI_CompareValuesJson, "true", "0");
JSON_CHECK(-1, TRI_CompareValuesJson, "true", "1");
JSON_CHECK(-1, TRI_CompareValuesJson, "true", "-10");
JSON_CHECK(-1, TRI_CompareValuesJson, "true", "\"\"");
JSON_CHECK(-1, TRI_CompareValuesJson, "true", "\"0\"");
JSON_CHECK(-1, TRI_CompareValuesJson, "true", "\" \"");
JSON_CHECK(-1, TRI_CompareValuesJson, "true", "[]");
JSON_CHECK(-1, TRI_CompareValuesJson, "true", "[null]");
JSON_CHECK(-1, TRI_CompareValuesJson, "true", "[false]");
JSON_CHECK(-1, TRI_CompareValuesJson, "true", "[true]");
JSON_CHECK(-1, TRI_CompareValuesJson, "true", "[0]");
JSON_CHECK(-1, TRI_CompareValuesJson, "true", "{}");
JSON_CHECK(-1, TRI_CompareValuesJson, "-2", "-1");
JSON_CHECK(-1, TRI_CompareValuesJson, "-10", "-9");
JSON_CHECK(-1, TRI_CompareValuesJson, "-20", "-5");
JSON_CHECK(-1, TRI_CompareValuesJson, "-5", "-2");
JSON_CHECK(-1, TRI_CompareValuesJson, "true", "1");
JSON_CHECK(-1, TRI_CompareValuesJson, "1.5", "1.6");
JSON_CHECK(-1, TRI_CompareValuesJson, "10.5", "10.51");
JSON_CHECK(-1, TRI_CompareValuesJson, "0", "\"\"");
JSON_CHECK(-1, TRI_CompareValuesJson, "0", "\"0\"");
JSON_CHECK(-1, TRI_CompareValuesJson, "0", "\"-1\"");
JSON_CHECK(-1, TRI_CompareValuesJson, "1", "\"-1\"");
JSON_CHECK(-1, TRI_CompareValuesJson, "1", "\" \"");
JSON_CHECK(-1, TRI_CompareValuesJson, "0", "[]");
JSON_CHECK(-1, TRI_CompareValuesJson, "0", "[-1]");
JSON_CHECK(-1, TRI_CompareValuesJson, "0", "[0]");
JSON_CHECK(-1, TRI_CompareValuesJson, "0", "[1]");
JSON_CHECK(-1, TRI_CompareValuesJson, "0", "[null]");
JSON_CHECK(-1, TRI_CompareValuesJson, "0", "[false]");
JSON_CHECK(-1, TRI_CompareValuesJson, "0", "[true]");
JSON_CHECK(-1, TRI_CompareValuesJson, "0", "{}");
JSON_CHECK(-1, TRI_CompareValuesJson, "1", "[]");
JSON_CHECK(-1, TRI_CompareValuesJson, "1", "[-1]");
JSON_CHECK(-1, TRI_CompareValuesJson, "1", "[0]");
JSON_CHECK(-1, TRI_CompareValuesJson, "1", "[1]");
JSON_CHECK(-1, TRI_CompareValuesJson, "1", "[null]");
JSON_CHECK(-1, TRI_CompareValuesJson, "1", "[false]");
JSON_CHECK(-1, TRI_CompareValuesJson, "1", "[true]");
JSON_CHECK(-1, TRI_CompareValuesJson, "1", "{}");
// TODO: add more tests
}
// TODO: add tests for
// TRI_CheckSameValueJson
// TRI_UniquifyArrayJson
// TRI_SortArrayJson
////////////////////////////////////////////////////////////////////////////////
/// @brief test duplicate keys
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE (tst_duplicate_keys) {
INIT_BUFFER
TRI_json_t* json;
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "[\"a\",\"a\"]");
BOOST_CHECK_EQUAL(false, TRI_HasDuplicateKeyJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{}");
BOOST_CHECK_EQUAL(false, TRI_HasDuplicateKeyJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{\"a\":1}");
BOOST_CHECK_EQUAL(false, TRI_HasDuplicateKeyJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{\"a\":1,\"b\":1}");
BOOST_CHECK_EQUAL(false, TRI_HasDuplicateKeyJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{\"a\":1,\"b\":1,\"A\":1}");
BOOST_CHECK_EQUAL(false, TRI_HasDuplicateKeyJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{\"a\":1,\"b\":1,\"a\":1}");
BOOST_CHECK_EQUAL(true, TRI_HasDuplicateKeyJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{\"a\":1,\"b\":1,\"c\":1,\"d\":{},\"c\":1}");
BOOST_CHECK_EQUAL(true, TRI_HasDuplicateKeyJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{\"a\":{}}");
BOOST_CHECK_EQUAL(false, TRI_HasDuplicateKeyJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{\"a\":{\"a\":1}}");
BOOST_CHECK_EQUAL(false, TRI_HasDuplicateKeyJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{\"a\":{\"a\":1,\"b\":1},\"b\":1}");
BOOST_CHECK_EQUAL(false, TRI_HasDuplicateKeyJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{\"a\":{\"a\":1,\"b\":1,\"a\":3},\"b\":1}");
BOOST_CHECK_EQUAL(true, TRI_HasDuplicateKeyJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{\"a\":{\"a\":1,\"b\":1,\"a\":3}}");
BOOST_CHECK_EQUAL(true, TRI_HasDuplicateKeyJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{\"a\":{\"a\":{\"a\":{}}}}");
BOOST_CHECK_EQUAL(false, TRI_HasDuplicateKeyJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{\"a\":{\"a\":{\"a\":{},\"a\":2}}}");
BOOST_CHECK_EQUAL(true, TRI_HasDuplicateKeyJson(json));
FREE_JSON
FREE_BUFFER
}
////////////////////////////////////////////////////////////////////////////////
/// @brief test hashing
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE (tst_json_hash_utf8) {
TRI_json_t* json;
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "\"äöüßÄÖÜ€µ\"");
BOOST_CHECK_EQUAL(17926322495289827824ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "\"코리아닷컴 메일알리미 서비스 중단안내 [안내] 개인정보취급방침 변경 안내 회사소개 | 광고안내 | 제휴안내 | 개인정보취급방침 | 청소년보호정책 | 스팸방지정책 | 사이버고객센터 | 약관안내 | 이메일 무단수집거부 | 서비스 전체보기\"");
BOOST_CHECK_EQUAL(11647939066062684691ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "\"بان يأسف لمقتل لاجئين سوريين بتركيا المرزوقي يندد بعنف الأمن التونسي تنديد بقتل الجيش السوري مصورا تلفزيونيا 14 قتيلا وعشرات الجرحى بانفجار بالصومال\"");
BOOST_CHECK_EQUAL(9773937585298648628ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "\"中华网以中国的市场为核心,致力为当地用户提供流动增值服务、网上娱乐及互联网服务。本公司亦推出网上游戏,及透过其门户网站提供包罗万有的网上产品及服务。\"");
BOOST_CHECK_EQUAL(5348732066920102360ULL, TRI_HashJson(json));
FREE_JSON
}
////////////////////////////////////////////////////////////////////////////////
/// @brief test hashing
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE (tst_json_hash) {
TRI_json_t* json;
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "null");
BOOST_CHECK_EQUAL(6601085983368743140ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "false");
BOOST_CHECK_EQUAL(13113042584710199672ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "true");
BOOST_CHECK_EQUAL(6583304908937478053ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "0");
BOOST_CHECK_EQUAL(12161962213042174405ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "123");
BOOST_CHECK_EQUAL(3423744850239007323ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "\"\"");
BOOST_CHECK_EQUAL(12638153115695167455ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "\" \"");
BOOST_CHECK_EQUAL(560073664097094349ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "\"foobar\"");
BOOST_CHECK_EQUAL(3770388817002598200ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "\"Foobar\"");
BOOST_CHECK_EQUAL(6228943802847363544ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "\"FOOBAR\"");
BOOST_CHECK_EQUAL(7710850877466186488ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "[]");
BOOST_CHECK_EQUAL(13796666053062066497ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "[ null ]");
BOOST_CHECK_EQUAL(12579909069687325360ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "[ 0 ]");
BOOST_CHECK_EQUAL(10101894954932532065ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "[ false ]");
BOOST_CHECK_EQUAL(4554324570636443940ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "[ \"false\" ]");
BOOST_CHECK_EQUAL(295270779373686828ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "[ [ ] ]");
BOOST_CHECK_EQUAL(3935687115999630221ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "[ { } ]");
BOOST_CHECK_EQUAL(13595004369025342186ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "[ [ false, 0 ] ]");
BOOST_CHECK_EQUAL(8026218647638185280ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{}");
BOOST_CHECK_EQUAL(5737045748118630438ULL, TRI_HashJson(json));
FREE_JSON
// the following hashes should be identical
const uint64_t a = 5721494255658103046ULL;
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": \"1\", \"b\": \"2\" }");
BOOST_CHECK_EQUAL(a, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"b\": \"2\", \"a\": \"1\" }");
BOOST_CHECK_EQUAL(a, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": \"2\", \"b\": \"1\" }");
BOOST_CHECK_EQUAL(a, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": null, \"b\": \"1\" }");
BOOST_CHECK_EQUAL(2549570315580563109ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"b\": \"1\" }");
BOOST_CHECK_EQUAL(5635413490308263533ULL, TRI_HashJson(json));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": 123, \"b\": [ ] }");
BOOST_CHECK_EQUAL(9398364376493393319ULL, TRI_HashJson(json));
FREE_JSON
}
////////////////////////////////////////////////////////////////////////////////
/// @brief test hashing by attribute names
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE (tst_json_hashattributes_single) {
TRI_json_t* json;
const char* v1[] = { "_key" };
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ }");
const uint64_t h1 = TRI_HashJsonByAttributes(json, v1, 1, true, NULL);
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"_key\": null }");
BOOST_CHECK_EQUAL(h1, TRI_HashJsonByAttributes(json, v1, 1, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": \"foobar\" }");
BOOST_CHECK_EQUAL(h1, TRI_HashJsonByAttributes(json, v1, 1, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": \"foobar\", \"_key\": null }");
BOOST_CHECK_EQUAL(h1, TRI_HashJsonByAttributes(json, v1, 1, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": \"foobar\", \"keys\": { \"_key\": \"foobar\" } }");
BOOST_CHECK_EQUAL(h1, TRI_HashJsonByAttributes(json, v1, 1, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": \"foobar\", \"KEY\": 1234, \"_KEY\": \"foobar\" }");
BOOST_CHECK_EQUAL(h1, TRI_HashJsonByAttributes(json, v1, 1, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"_key\": \"i-am-a-foo\" }");
const uint64_t h2 = TRI_HashJsonByAttributes(json, v1, 1, true, NULL);
BOOST_CHECK(h1 != h2);
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": \"foobar\", \"KEY\": 1234, \"_key\": \"i-am-a-foo\" }");
BOOST_CHECK_EQUAL(h2, TRI_HashJsonByAttributes(json, v1, 1, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": [ \"foobar\" ], \"KEY\": { }, \"_key\": \"i-am-a-foo\" }");
BOOST_CHECK_EQUAL(h2, TRI_HashJsonByAttributes(json, v1, 1, true, NULL));
FREE_JSON
}
////////////////////////////////////////////////////////////////////////////////
/// @brief test hashing by attribute names
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE (tst_json_hashattributes_mult1) {
TRI_json_t* json;
const char* v1[] = { "a", "b" };
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ }");
const uint64_t h1 = TRI_HashJsonByAttributes(json, v1, 2, true, NULL);
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": null, \"b\": null }");
BOOST_CHECK_EQUAL(h1, TRI_HashJsonByAttributes(json, v1, 2, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"b\": null, \"a\": null }");
BOOST_CHECK_EQUAL(h1, TRI_HashJsonByAttributes(json, v1, 2, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": null }");
BOOST_CHECK_EQUAL(h1, TRI_HashJsonByAttributes(json, v1, 2, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"b\": null }");
BOOST_CHECK_EQUAL(h1, TRI_HashJsonByAttributes(json, v1, 2, true, NULL));
FREE_JSON
// test if non-relevant attributes influence our hash
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": null, \"B\": 123 }");
BOOST_CHECK_EQUAL(h1, TRI_HashJsonByAttributes(json, v1, 2, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"B\": 1234, \"a\": null }");
BOOST_CHECK_EQUAL(h1, TRI_HashJsonByAttributes(json, v1, 2, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": null, \"A\": 123, \"B\": \"hihi\" }");
BOOST_CHECK_EQUAL(h1, TRI_HashJsonByAttributes(json, v1, 2, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"c\": null, \"d\": null }");
BOOST_CHECK_EQUAL(h1, TRI_HashJsonByAttributes(json, v1, 2, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"A\": 1, \"B\": 2, \" a\": \"bar\" }");
BOOST_CHECK_EQUAL(h1, TRI_HashJsonByAttributes(json, v1, 2, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"ab\": 1, \"ba\": 2 }");
BOOST_CHECK_EQUAL(h1, TRI_HashJsonByAttributes(json, v1, 2, true, NULL));
FREE_JSON
}
////////////////////////////////////////////////////////////////////////////////
/// @brief test hashing by attribute names
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE (tst_json_hashattributes_mult2) {
TRI_json_t* json;
const char* v1[] = { "a", "b" };
const uint64_t h1 = 6369173190757857502ULL;
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": \"foo\", \"b\": \"bar\" }");
BOOST_CHECK_EQUAL(h1, TRI_HashJsonByAttributes(json, v1, 2, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"b\": \"bar\", \"a\": \"foo\" }");
BOOST_CHECK_EQUAL(h1, TRI_HashJsonByAttributes(json, v1, 2, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": \"food\", \"b\": \"bar\" }");
BOOST_CHECK_EQUAL(720060016857102700ULL, TRI_HashJsonByAttributes(json, v1, 2, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": \"foo\", \"b\": \"baz\" }");
BOOST_CHECK_EQUAL(6361520589827022742ULL, TRI_HashJsonByAttributes(json, v1, 2, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": \"FOO\", \"b\": \"BAR\" }");
BOOST_CHECK_EQUAL(3595137217367956894ULL, TRI_HashJsonByAttributes(json, v1, 2, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": \"foo\" }");
BOOST_CHECK_EQUAL(12739237936894360852ULL, TRI_HashJsonByAttributes(json, v1, 2, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": \"foo\", \"b\": \"meow\" }");
BOOST_CHECK_EQUAL(13378327204915572311ULL, TRI_HashJsonByAttributes(json, v1, 2, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"b\": \"bar\" }");
BOOST_CHECK_EQUAL(10085884912118216755ULL, TRI_HashJsonByAttributes(json, v1, 2, true, NULL));
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"b\": \"bar\", \"a\": \"meow\" }");
BOOST_CHECK_EQUAL(15753579192430387496ULL, TRI_HashJsonByAttributes(json, v1, 2, true, NULL));
FREE_JSON
}
////////////////////////////////////////////////////////////////////////////////
/// @brief test hashing by attribute names with incomplete docs
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE (tst_json_hashattributes_mult3) {
TRI_json_t* json;
const char* v1[] = { "a", "b" };
int error;
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": \"foo\", \"b\": \"bar\" }");
TRI_HashJsonByAttributes(json, v1, 2, false, &error);
BOOST_CHECK_EQUAL(TRI_ERROR_NO_ERROR, error);
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": \"foo\" }");
TRI_HashJsonByAttributes(json, v1, 2, false, &error);
BOOST_CHECK_EQUAL(TRI_ERROR_CLUSTER_NOT_ALL_SHARDING_ATTRIBUTES_GIVEN, error);
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"b\": \"bar\" }");
TRI_HashJsonByAttributes(json, v1, 2, false, &error);
BOOST_CHECK_EQUAL(TRI_ERROR_CLUSTER_NOT_ALL_SHARDING_ATTRIBUTES_GIVEN, error);
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ }");
TRI_HashJsonByAttributes(json, v1, 2, false, &error);
BOOST_CHECK_EQUAL(TRI_ERROR_CLUSTER_NOT_ALL_SHARDING_ATTRIBUTES_GIVEN, error);
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"c\": 12 }");
TRI_HashJsonByAttributes(json, v1, 2, false, &error);
BOOST_CHECK_EQUAL(TRI_ERROR_CLUSTER_NOT_ALL_SHARDING_ATTRIBUTES_GIVEN, error);
FREE_JSON
json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, "{ \"a\": 1, \"b\": null }");
TRI_HashJsonByAttributes(json, v1, 2, false, &error);
BOOST_CHECK_EQUAL(TRI_ERROR_NO_ERROR, error);
FREE_JSON
}
////////////////////////////////////////////////////////////////////////////////
/// @brief generate tests
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_SUITE_END ()
// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:
| apache-2.0 |
drcarter/scouter | scouter.server/src/scouter/server/db/io/zip/CountBoard.java | 1781 | /*
* Copyright 2015 LG CNS.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package scouter.server.db.io.zip;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import scouter.util.FileUtil;
import scouter.util.IClose;
public class CountBoard implements IClose {
private RandomAccessFile raf = null;
public long counts;
protected File file;
public CountBoard(String date) throws IOException {
String filename = (GZipCtr.createPath(date) + "/count.dat");
this.file = new File(filename);
this.raf = new RandomAccessFile(file, "rw");
if (this.raf.length() >=8) {
try {
load();
} catch (IOException e) {
counts = 0;
e.printStackTrace();
}
} else {
counts = 0;
}
}
public long add(long cnt) {
return set(this.counts + cnt);
}
public long set(long cnt) {
this.counts = cnt;
try {
raf.seek(0);
raf.writeLong(counts);
} catch (Exception e) {
e.printStackTrace();
}
return this.counts;
}
private void load() throws IOException {
raf.seek(0);
counts = raf.readLong();
}
public long getCount() {
return this.counts;
}
public void close() {
FileUtil.close(this.raf);
this.raf=null;
}
} | apache-2.0 |
ern/elasticsearch | server/src/main/java/org/elasticsearch/index/analysis/AnalyzerComponents.java | 4056 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.index.analysis;
import org.elasticsearch.common.settings.Settings;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* A class that groups analysis components necessary to produce a custom analyzer.
* See {@link ReloadableCustomAnalyzer} for an example usage.
*/
public final class AnalyzerComponents {
private final TokenizerFactory tokenizerFactory;
private final CharFilterFactory[] charFilters;
private final TokenFilterFactory[] tokenFilters;
private final AnalysisMode analysisMode;
AnalyzerComponents(TokenizerFactory tokenizerFactory, CharFilterFactory[] charFilters,
TokenFilterFactory[] tokenFilters) {
this.tokenizerFactory = tokenizerFactory;
this.charFilters = charFilters;
this.tokenFilters = tokenFilters;
AnalysisMode mode = AnalysisMode.ALL;
for (TokenFilterFactory f : tokenFilters) {
mode = mode.merge(f.getAnalysisMode());
}
this.analysisMode = mode;
}
static AnalyzerComponents createComponents(String name, Settings analyzerSettings, final Map<String, TokenizerFactory> tokenizers,
final Map<String, CharFilterFactory> charFilters, final Map<String, TokenFilterFactory> tokenFilters) {
String tokenizerName = analyzerSettings.get("tokenizer");
if (tokenizerName == null) {
throw new IllegalArgumentException("Custom Analyzer [" + name + "] must be configured with a tokenizer");
}
TokenizerFactory tokenizer = tokenizers.get(tokenizerName);
if (tokenizer == null) {
throw new IllegalArgumentException(
"Custom Analyzer [" + name + "] failed to find tokenizer under name " + "[" + tokenizerName + "]");
}
List<String> charFilterNames = analyzerSettings.getAsList("char_filter");
List<CharFilterFactory> charFiltersList = new ArrayList<>(charFilterNames.size());
for (String charFilterName : charFilterNames) {
CharFilterFactory charFilter = charFilters.get(charFilterName);
if (charFilter == null) {
throw new IllegalArgumentException(
"Custom Analyzer [" + name + "] failed to find char_filter under name " + "[" + charFilterName + "]");
}
charFiltersList.add(charFilter);
}
List<String> tokenFilterNames = analyzerSettings.getAsList("filter");
List<TokenFilterFactory> tokenFilterList = new ArrayList<>(tokenFilterNames.size());
for (String tokenFilterName : tokenFilterNames) {
TokenFilterFactory tokenFilter = tokenFilters.get(tokenFilterName);
if (tokenFilter == null) {
throw new IllegalArgumentException(
"Custom Analyzer [" + name + "] failed to find filter under name " + "[" + tokenFilterName + "]");
}
tokenFilter = tokenFilter.getChainAwareTokenFilterFactory(tokenizer, charFiltersList, tokenFilterList, tokenFilters::get);
tokenFilterList.add(tokenFilter);
}
return new AnalyzerComponents(tokenizer, charFiltersList.toArray(new CharFilterFactory[charFiltersList.size()]),
tokenFilterList.toArray(new TokenFilterFactory[tokenFilterList.size()]));
}
public TokenizerFactory getTokenizerFactory() {
return tokenizerFactory;
}
public TokenFilterFactory[] getTokenFilters() {
return tokenFilters;
}
public CharFilterFactory[] getCharFilters() {
return charFilters;
}
public AnalysisMode analysisMode() {
return this.analysisMode;
}
}
| apache-2.0 |
colincross/ninja | src/depfile_parser_test.cc | 4462 | // Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "depfile_parser.h"
#include "test.h"
struct DepfileParserTest : public testing::Test {
bool Parse(const char* input, string* err);
DepfileParser parser_;
string input_;
};
bool DepfileParserTest::Parse(const char* input, string* err) {
input_ = input;
return parser_.Parse(&input_, err);
}
TEST_F(DepfileParserTest, Basic) {
string err;
EXPECT_TRUE(Parse(
"build/ninja.o: ninja.cc ninja.h eval_env.h manifest_parser.h\n",
&err));
ASSERT_EQ("", err);
EXPECT_EQ("build/ninja.o", parser_.out_.AsString());
EXPECT_EQ(4u, parser_.ins_.size());
}
TEST_F(DepfileParserTest, EarlyNewlineAndWhitespace) {
string err;
EXPECT_TRUE(Parse(
" \\\n"
" out: in\n",
&err));
ASSERT_EQ("", err);
}
TEST_F(DepfileParserTest, Continuation) {
string err;
EXPECT_TRUE(Parse(
"foo.o: \\\n"
" bar.h baz.h\n",
&err));
ASSERT_EQ("", err);
EXPECT_EQ("foo.o", parser_.out_.AsString());
EXPECT_EQ(2u, parser_.ins_.size());
}
TEST_F(DepfileParserTest, CarriageReturnContinuation) {
string err;
EXPECT_TRUE(Parse(
"foo.o: \\\r\n"
" bar.h baz.h\r\n",
&err));
ASSERT_EQ("", err);
EXPECT_EQ("foo.o", parser_.out_.AsString());
EXPECT_EQ(2u, parser_.ins_.size());
}
TEST_F(DepfileParserTest, BackSlashes) {
string err;
EXPECT_TRUE(Parse(
"Project\\Dir\\Build\\Release8\\Foo\\Foo.res : \\\n"
" Dir\\Library\\Foo.rc \\\n"
" Dir\\Library\\Version\\Bar.h \\\n"
" Dir\\Library\\Foo.ico \\\n"
" Project\\Thing\\Bar.tlb \\\n",
&err));
ASSERT_EQ("", err);
EXPECT_EQ("Project\\Dir\\Build\\Release8\\Foo\\Foo.res",
parser_.out_.AsString());
EXPECT_EQ(4u, parser_.ins_.size());
}
TEST_F(DepfileParserTest, Spaces) {
string err;
EXPECT_TRUE(Parse(
"a\\ bc\\ def: a\\ b c d",
&err));
ASSERT_EQ("", err);
EXPECT_EQ("a bc def",
parser_.out_.AsString());
ASSERT_EQ(3u, parser_.ins_.size());
EXPECT_EQ("a b",
parser_.ins_[0].AsString());
EXPECT_EQ("c",
parser_.ins_[1].AsString());
EXPECT_EQ("d",
parser_.ins_[2].AsString());
}
TEST_F(DepfileParserTest, Escapes) {
// Put backslashes before a variety of characters, see which ones make
// it through.
string err;
EXPECT_TRUE(Parse(
"\\!\\@\\#$$\\%\\^\\&\\\\:",
&err));
ASSERT_EQ("", err);
EXPECT_EQ("\\!\\@#$\\%\\^\\&\\",
parser_.out_.AsString());
ASSERT_EQ(0u, parser_.ins_.size());
}
TEST_F(DepfileParserTest, SpecialChars) {
// See filenames like istreambuf.iterator_op!= in
// https://github.com/google/libcxx/tree/master/test/iterators/stream.iterators/istreambuf.iterator/
string err;
EXPECT_TRUE(Parse(
"C:/Program\\ Files\\ (x86)/Microsoft\\ crtdefs.h: \n"
" en@quot.header~ t+t-x!=1 \n"
" openldap/slapd.d/cn=config/cn=schema/cn={0}core.ldif",
&err));
ASSERT_EQ("", err);
EXPECT_EQ("C:/Program Files (x86)/Microsoft crtdefs.h",
parser_.out_.AsString());
ASSERT_EQ(3u, parser_.ins_.size());
EXPECT_EQ("en@quot.header~",
parser_.ins_[0].AsString());
EXPECT_EQ("t+t-x!=1",
parser_.ins_[1].AsString());
EXPECT_EQ("openldap/slapd.d/cn=config/cn=schema/cn={0}core.ldif",
parser_.ins_[2].AsString());
}
TEST_F(DepfileParserTest, UnifyMultipleOutputs) {
// check that multiple duplicate targets are properly unified
string err;
EXPECT_TRUE(Parse("foo foo: x y z", &err));
ASSERT_EQ("foo", parser_.out_.AsString());
ASSERT_EQ(3u, parser_.ins_.size());
EXPECT_EQ("x", parser_.ins_[0].AsString());
EXPECT_EQ("y", parser_.ins_[1].AsString());
EXPECT_EQ("z", parser_.ins_[2].AsString());
}
TEST_F(DepfileParserTest, RejectMultipleDifferentOutputs) {
// check that multiple different outputs are rejected by the parser
string err;
EXPECT_FALSE(Parse("foo bar: x y z", &err));
ASSERT_EQ("depfile has multiple output paths", err);
}
| apache-2.0 |
googlevr/daydream-elements | Assets/GoogleVR/Editor/GvrBuildProcessor.cs | 3347 | // Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Only invoke custom build processor when building for Android or iOS.
#if UNITY_ANDROID || UNITY_IOS
using UnityEngine;
using UnityEditor;
using UnityEditor.Build;
using System.Linq;
#if UNITY_2017_2_OR_NEWER
using UnityEngine.XR;
#else
using XRSettings = UnityEngine.VR.VRSettings;
#endif // UNITY_2017_2_OR_NEWER
// Notifies users if they build for Android or iOS without Cardboard or Daydream enabled.
class GvrBuildProcessor : IPreprocessBuild {
private const string VR_SETTINGS_NOT_ENABLED_ERROR_MESSAGE_FORMAT =
"To use the Google VR SDK on {0}, 'Player Settings > Virtual Reality Supported' setting must be checked.\n" +
"Please fix this setting and rebuild your app.";
private const string IOS_MISSING_GVR_SDK_ERROR_MESSAGE =
"To use the Google VR SDK on iOS, 'Player Settings > Virtual Reality SDKs' must include 'Cardboard'.\n" +
"Please fix this setting and rebuild your app.";
private const string ANDROID_MISSING_GVR_SDK_ERROR_MESSAGE =
"To use the Google VR SDK on Android, 'Player Settings > Virtual Reality SDKs' must include 'Daydream' or 'Cardboard'.\n" +
"Please fix this setting and rebuild your app.";
public int callbackOrder {
get { return 0; }
}
public void OnPreprocessBuild (BuildTarget target, string path)
{
if (target != BuildTarget.Android && target != BuildTarget.iOS) {
// Do nothing when not building for Android or iOS.
return;
}
// 'Player Settings > Virtual Reality Supported' must be enabled.
if (!IsVRSupportEnabled()) {
Debug.LogErrorFormat(VR_SETTINGS_NOT_ENABLED_ERROR_MESSAGE_FORMAT, target);
}
if (target == BuildTarget.Android) {
// When building for Android at least one VR SDK must be included.
// For Google VR valid VR SDKs are 'Daydream' and/or 'Cardboard'.
if (!IsSDKOtherThanNoneIncluded()) {
Debug.LogError(ANDROID_MISSING_GVR_SDK_ERROR_MESSAGE);
}
}
if (target == BuildTarget.iOS) {
// When building for iOS at least one VR SDK must be included.
// For Google VR only 'Cardboard' is supported.
if (!IsSDKOtherThanNoneIncluded()) {
Debug.LogError(IOS_MISSING_GVR_SDK_ERROR_MESSAGE);
}
}
}
// 'Player Settings > Virtual Reality Supported' enabled?
private bool IsVRSupportEnabled() {
return PlayerSettings.virtualRealitySupported;
}
// 'Player Settings > Virtual Reality SDKs' includes any VR SDK other than 'None'?
private bool IsSDKOtherThanNoneIncluded() {
bool containsNone = XRSettings.supportedDevices.Contains(GvrSettings.VR_SDK_NONE);
int numSdks = XRSettings.supportedDevices.Length;
return containsNone ? numSdks > 1 : numSdks > 0;
}
}
#endif // UNITY_ANDROID || UNITY_IOS
| apache-2.0 |
bykoianko/omim | traffic/traffic_info.hpp | 5584 | #pragma once
#include "traffic/speed_groups.hpp"
#include "indexer/mwm_set.hpp"
#include "std/cstdint.hpp"
#include "std/map.hpp"
#include "std/shared_ptr.hpp"
#include "std/vector.hpp"
namespace platform
{
class HttpClient;
}
namespace traffic
{
// This class is responsible for providing the real-time
// information about road traffic for one mwm file.
class TrafficInfo
{
public:
static uint8_t const kLatestKeysVersion;
static uint8_t const kLatestValuesVersion;
enum class Availability
{
IsAvailable,
NoData,
ExpiredData,
ExpiredApp,
Unknown
};
struct RoadSegmentId
{
// m_dir can be kForwardDirection or kReverseDirection.
static uint8_t constexpr kForwardDirection = 0;
static uint8_t constexpr kReverseDirection = 1;
RoadSegmentId();
RoadSegmentId(uint32_t fid, uint16_t idx, uint8_t dir);
bool operator==(RoadSegmentId const & o) const
{
return m_fid == o.m_fid && m_idx == o.m_idx && m_dir == o.m_dir;
}
bool operator<(RoadSegmentId const & o) const
{
if (m_fid != o.m_fid)
return m_fid < o.m_fid;
if (m_idx != o.m_idx)
return m_idx < o.m_idx;
return m_dir < o.m_dir;
}
uint32_t GetFid() const { return m_fid; }
uint16_t GetIdx() const { return m_idx; }
uint8_t GetDir() const { return m_dir; }
// The ordinal number of feature this segment belongs to.
uint32_t m_fid;
// The ordinal number of this segment in the list of
// its feature's segments.
uint16_t m_idx : 15;
// The direction of the segment.
uint8_t m_dir : 1;
};
// todo(@m) unordered_map?
using Coloring = map<RoadSegmentId, SpeedGroup>;
TrafficInfo() = default;
TrafficInfo(MwmSet::MwmId const & mwmId, int64_t currentDataVersion);
static TrafficInfo BuildForTesting(Coloring && coloring);
void SetTrafficKeysForTesting(vector<RoadSegmentId> const & keys);
// Fetches the latest traffic data from the server and updates the coloring and ETag.
// Construct the url by passing an MwmId.
// The ETag or entity tag is part of HTTP, the protocol for the World Wide Web.
// It is one of several mechanisms that HTTP provides for web cache validation,
// which allows a client to make conditional requests.
// *NOTE* This method must not be called on the UI thread.
bool ReceiveTrafficData(string & etag);
// Returns the latest known speed group by a feature segment's id
// or SpeedGroup::Unknown if there is no information about the segment.
SpeedGroup GetSpeedGroup(RoadSegmentId const & id) const;
MwmSet::MwmId const & GetMwmId() const { return m_mwmId; }
Coloring const & GetColoring() const { return m_coloring; }
Availability GetAvailability() const { return m_availability; }
// Extracts RoadSegmentIds from mwm and stores them in a sorted order.
static void ExtractTrafficKeys(string const & mwmPath, vector<RoadSegmentId> & result);
// Adds the unknown values to the partially known coloring map |knownColors|
// so that the keys of the resulting map are exactly |keys|.
static void CombineColorings(vector<TrafficInfo::RoadSegmentId> const & keys,
TrafficInfo::Coloring const & knownColors,
TrafficInfo::Coloring & result);
// Serializes the keys of the coloring map to |result|.
// The keys are road segments ids which do not change during
// an mwm's lifetime so there's no point in downloading them every time.
// todo(@m) Document the format.
static void SerializeTrafficKeys(vector<RoadSegmentId> const & keys, vector<uint8_t> & result);
static void DeserializeTrafficKeys(vector<uint8_t> const & data, vector<RoadSegmentId> & result);
static void SerializeTrafficValues(vector<SpeedGroup> const & values, vector<uint8_t> & result);
static void DeserializeTrafficValues(vector<uint8_t> const & data, vector<SpeedGroup> & result);
private:
enum class ServerDataStatus
{
New,
NotChanged,
NotFound,
Error,
};
friend void UnitTest_TrafficInfo_UpdateTrafficData();
// todo(@m) A temporary method. Remove it once the keys are added
// to the generator and the data is regenerated.
bool ReceiveTrafficKeys();
// Tries to read the values of the Coloring map from server into |values|.
// Returns result of communicating with server as ServerDataStatus.
// Otherwise, returns false and does not change m_coloring.
ServerDataStatus ReceiveTrafficValues(string & etag, vector<SpeedGroup> & values);
// Updates the coloring and changes the availability status if needed.
bool UpdateTrafficData(vector<SpeedGroup> const & values);
ServerDataStatus ProcessFailure(platform::HttpClient const & request, int64_t const mwmVersion);
// The mapping from feature segments to speed groups (see speed_groups.hpp).
Coloring m_coloring;
// The keys of the coloring map. The values are downloaded periodically
// and combined with the keys to form m_coloring.
// *NOTE* The values must be received in the exact same order that the
// keys are saved in.
vector<RoadSegmentId> m_keys;
MwmSet::MwmId m_mwmId;
Availability m_availability = Availability::Unknown;
int64_t m_currentDataVersion = 0;
};
class TrafficObserver
{
public:
virtual ~TrafficObserver() = default;
virtual void OnTrafficInfoClear() = 0;
virtual void OnTrafficInfoAdded(traffic::TrafficInfo && info) = 0;
virtual void OnTrafficInfoRemoved(MwmSet::MwmId const & mwmId) = 0;
};
string DebugPrint(TrafficInfo::RoadSegmentId const & id);
} // namespace traffic
| apache-2.0 |
hanpanpan200/google-api-ruby-client | generated/google/apis/taskqueue_v1beta2/representations.rb | 3989 | # Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'date'
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module TaskqueueV1beta2
class Task
class Representation < Google::Apis::Core::JsonRepresentation; end
end
class TaskQueue
class Representation < Google::Apis::Core::JsonRepresentation; end
class Acl
class Representation < Google::Apis::Core::JsonRepresentation; end
end
class Stats
class Representation < Google::Apis::Core::JsonRepresentation; end
end
end
class Tasks
class Representation < Google::Apis::Core::JsonRepresentation; end
end
class Tasks2
class Representation < Google::Apis::Core::JsonRepresentation; end
end
class Task
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :enqueue_timestamp, as: 'enqueueTimestamp'
property :id, as: 'id'
property :kind, as: 'kind'
property :lease_timestamp, as: 'leaseTimestamp'
property :payload_base64, as: 'payloadBase64'
property :queue_name, as: 'queueName'
property :retry_count, as: 'retry_count'
property :tag, as: 'tag'
end
end
class TaskQueue
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :acl, as: 'acl', class: Google::Apis::TaskqueueV1beta2::TaskQueue::Acl, decorator: Google::Apis::TaskqueueV1beta2::TaskQueue::Acl::Representation
property :id, as: 'id'
property :kind, as: 'kind'
property :max_leases, as: 'maxLeases'
property :stats, as: 'stats', class: Google::Apis::TaskqueueV1beta2::TaskQueue::Stats, decorator: Google::Apis::TaskqueueV1beta2::TaskQueue::Stats::Representation
end
class Acl
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :admin_emails, as: 'adminEmails'
collection :consumer_emails, as: 'consumerEmails'
collection :producer_emails, as: 'producerEmails'
end
end
class Stats
# @private
class Representation < Google::Apis::Core::JsonRepresentation
property :leased_last_hour, as: 'leasedLastHour'
property :leased_last_minute, as: 'leasedLastMinute'
property :oldest_task, as: 'oldestTask'
property :total_tasks, as: 'totalTasks'
end
end
end
class Tasks
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :items, as: 'items', class: Google::Apis::TaskqueueV1beta2::Task, decorator: Google::Apis::TaskqueueV1beta2::Task::Representation
property :kind, as: 'kind'
end
end
class Tasks2
# @private
class Representation < Google::Apis::Core::JsonRepresentation
collection :items, as: 'items', class: Google::Apis::TaskqueueV1beta2::Task, decorator: Google::Apis::TaskqueueV1beta2::Task::Representation
property :kind, as: 'kind'
end
end
end
end
end
| apache-2.0 |
MaTriXy/assertj-android | assertj-android/src/main/java/org/assertj/android/api/telephony/CellSignalStrengthWcdmaAssert.java | 498 | package org.assertj.android.api.telephony;
import android.annotation.TargetApi;
import android.telephony.CellSignalStrengthWcdma;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR2;
@TargetApi(JELLY_BEAN_MR2)
public class CellSignalStrengthWcdmaAssert extends AbstractCellSignalStrengthAssert<CellSignalStrengthWcdmaAssert, CellSignalStrengthWcdma> {
public CellSignalStrengthWcdmaAssert(CellSignalStrengthWcdma actual) {
super(actual, CellSignalStrengthWcdmaAssert.class);
}
}
| apache-2.0 |
allenzhang010/comment-hadoop-2.7.1 | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/mover/TestStorageMover.java | 27756 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.mover;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.StorageType;
import org.apache.hadoop.hdfs.protocol.BlockStoragePolicy;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSOutputStream;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.protocol.DirectoryListing;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.protocol.HdfsLocatedFileStatus;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferProtocol;
import org.apache.hadoop.hdfs.server.balancer.Dispatcher;
import org.apache.hadoop.hdfs.server.balancer.ExitStatus;
import org.apache.hadoop.hdfs.server.balancer.TestBalancer;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockPlacementPolicy;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockStoragePolicySuite;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.server.datanode.DataNodeTestUtils;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsVolumeSpi;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsVolumeImpl;
import org.apache.hadoop.hdfs.server.namenode.snapshot.SnapshotTestHelper;
import org.apache.hadoop.io.IOUtils;
import org.apache.log4j.Level;
import org.junit.Assert;
import org.junit.Test;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_LAZY_WRITER_INTERVAL_SEC;
/**
* Test the data migration tool (for Archival Storage)
*/
public class TestStorageMover {
static final Log LOG = LogFactory.getLog(TestStorageMover.class);
static {
((Log4JLogger)LogFactory.getLog(BlockPlacementPolicy.class)
).getLogger().setLevel(Level.ALL);
((Log4JLogger)LogFactory.getLog(Dispatcher.class)
).getLogger().setLevel(Level.ALL);
((Log4JLogger)LogFactory.getLog(DataTransferProtocol.class)).getLogger()
.setLevel(Level.ALL);
}
private static final int BLOCK_SIZE = 1024;
private static final short REPL = 3;
private static final int NUM_DATANODES = 6;
private static final Configuration DEFAULT_CONF = new HdfsConfiguration();
private static final BlockStoragePolicySuite DEFAULT_POLICIES;
private static final BlockStoragePolicy HOT;
private static final BlockStoragePolicy WARM;
private static final BlockStoragePolicy COLD;
static {
DEFAULT_CONF.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE);
DEFAULT_CONF.setLong(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1L);
DEFAULT_CONF.setLong(DFSConfigKeys.DFS_NAMENODE_REPLICATION_INTERVAL_KEY,
2L);
DEFAULT_CONF.setLong(DFSConfigKeys.DFS_MOVER_MOVEDWINWIDTH_KEY, 2000L);
DEFAULT_POLICIES = BlockStoragePolicySuite.createDefaultSuite();
HOT = DEFAULT_POLICIES.getPolicy(HdfsConstants.HOT_STORAGE_POLICY_NAME);
WARM = DEFAULT_POLICIES.getPolicy(HdfsConstants.WARM_STORAGE_POLICY_NAME);
COLD = DEFAULT_POLICIES.getPolicy(HdfsConstants.COLD_STORAGE_POLICY_NAME);
TestBalancer.initTestSetup();
Dispatcher.setDelayAfterErrors(1000L);
}
/**
* This scheme defines files/directories and their block storage policies. It
* also defines snapshots.
*/
static class NamespaceScheme {
final List<Path> dirs;
final List<Path> files;
final long fileSize;
final Map<Path, List<String>> snapshotMap;
final Map<Path, BlockStoragePolicy> policyMap;
NamespaceScheme(List<Path> dirs, List<Path> files, long fileSize,
Map<Path,List<String>> snapshotMap,
Map<Path, BlockStoragePolicy> policyMap) {
this.dirs = dirs == null? Collections.<Path>emptyList(): dirs;
this.files = files == null? Collections.<Path>emptyList(): files;
this.fileSize = fileSize;
this.snapshotMap = snapshotMap == null ?
Collections.<Path, List<String>>emptyMap() : snapshotMap;
this.policyMap = policyMap;
}
/**
* Create files/directories/snapshots.
*/
void prepare(DistributedFileSystem dfs, short repl) throws Exception {
for (Path d : dirs) {
dfs.mkdirs(d);
}
for (Path file : files) {
DFSTestUtil.createFile(dfs, file, fileSize, repl, 0L);
}
for (Map.Entry<Path, List<String>> entry : snapshotMap.entrySet()) {
for (String snapshot : entry.getValue()) {
SnapshotTestHelper.createSnapshot(dfs, entry.getKey(), snapshot);
}
}
}
/**
* Set storage policies according to the corresponding scheme.
*/
void setStoragePolicy(DistributedFileSystem dfs) throws Exception {
for (Map.Entry<Path, BlockStoragePolicy> entry : policyMap.entrySet()) {
dfs.setStoragePolicy(entry.getKey(), entry.getValue().getName());
}
}
}
/**
* This scheme defines DataNodes and their storage, including storage types
* and remaining capacities.
*/
static class ClusterScheme {
final Configuration conf;
final int numDataNodes;
final short repl;
final StorageType[][] storageTypes;
final long[][] storageCapacities;
ClusterScheme() {
this(DEFAULT_CONF, NUM_DATANODES, REPL,
genStorageTypes(NUM_DATANODES), null);
}
ClusterScheme(Configuration conf, int numDataNodes, short repl,
StorageType[][] types, long[][] capacities) {
Preconditions.checkArgument(types == null || types.length == numDataNodes);
Preconditions.checkArgument(capacities == null || capacities.length ==
numDataNodes);
this.conf = conf;
this.numDataNodes = numDataNodes;
this.repl = repl;
this.storageTypes = types;
this.storageCapacities = capacities;
}
}
class MigrationTest {
private final ClusterScheme clusterScheme;
private final NamespaceScheme nsScheme;
private final Configuration conf;
private MiniDFSCluster cluster;
private DistributedFileSystem dfs;
private final BlockStoragePolicySuite policies;
MigrationTest(ClusterScheme cScheme, NamespaceScheme nsScheme) {
this.clusterScheme = cScheme;
this.nsScheme = nsScheme;
this.conf = clusterScheme.conf;
this.policies = DEFAULT_POLICIES;
}
/**
* Set up the cluster and start NameNode and DataNodes according to the
* corresponding scheme.
*/
void setupCluster() throws Exception {
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(clusterScheme
.numDataNodes).storageTypes(clusterScheme.storageTypes)
.storageCapacities(clusterScheme.storageCapacities).build();
cluster.waitActive();
dfs = cluster.getFileSystem();
}
private void runBasicTest(boolean shutdown) throws Exception {
setupCluster();
try {
prepareNamespace();
verify(true);
setStoragePolicy();
migrate();
verify(true);
} finally {
if (shutdown) {
shutdownCluster();
}
}
}
void shutdownCluster() throws Exception {
IOUtils.cleanup(null, dfs);
if (cluster != null) {
cluster.shutdown();
}
}
/**
* Create files/directories and set their storage policies according to the
* corresponding scheme.
*/
void prepareNamespace() throws Exception {
nsScheme.prepare(dfs, clusterScheme.repl);
}
void setStoragePolicy() throws Exception {
nsScheme.setStoragePolicy(dfs);
}
/**
* Run the migration tool.
*/
void migrate() throws Exception {
runMover();
Thread.sleep(5000); // let the NN finish deletion
}
/**
* Verify block locations after running the migration tool.
*/
void verify(boolean verifyAll) throws Exception {
for (DataNode dn : cluster.getDataNodes()) {
DataNodeTestUtils.triggerBlockReport(dn);
}
if (verifyAll) {
verifyNamespace();
}
}
private void runMover() throws Exception {
Collection<URI> namenodes = DFSUtil.getNsServiceRpcUris(conf);
Map<URI, List<Path>> nnMap = Maps.newHashMap();
for (URI nn : namenodes) {
nnMap.put(nn, null);
}
int result = Mover.run(nnMap, conf);
Assert.assertEquals(ExitStatus.SUCCESS.getExitCode(), result);
}
private void verifyNamespace() throws Exception {
HdfsFileStatus status = dfs.getClient().getFileInfo("/");
verifyRecursively(null, status);
}
private void verifyRecursively(final Path parent,
final HdfsFileStatus status) throws Exception {
if (status.isDir()) {
Path fullPath = parent == null ?
new Path("/") : status.getFullPath(parent);
DirectoryListing children = dfs.getClient().listPaths(
fullPath.toString(), HdfsFileStatus.EMPTY_NAME, true);
for (HdfsFileStatus child : children.getPartialListing()) {
verifyRecursively(fullPath, child);
}
} else if (!status.isSymlink()) { // is file
verifyFile(parent, status, null);
}
}
void verifyFile(final Path file, final Byte expectedPolicyId)
throws Exception {
final Path parent = file.getParent();
DirectoryListing children = dfs.getClient().listPaths(
parent.toString(), HdfsFileStatus.EMPTY_NAME, true);
for (HdfsFileStatus child : children.getPartialListing()) {
if (child.getLocalName().equals(file.getName())) {
verifyFile(parent, child, expectedPolicyId);
return;
}
}
Assert.fail("File " + file + " not found.");
}
private void verifyFile(final Path parent, final HdfsFileStatus status,
final Byte expectedPolicyId) throws Exception {
HdfsLocatedFileStatus fileStatus = (HdfsLocatedFileStatus) status;
byte policyId = fileStatus.getStoragePolicy();
BlockStoragePolicy policy = policies.getPolicy(policyId);
if (expectedPolicyId != null) {
Assert.assertEquals((byte)expectedPolicyId, policy.getId());
}
final List<StorageType> types = policy.chooseStorageTypes(
status.getReplication());
for(LocatedBlock lb : fileStatus.getBlockLocations().getLocatedBlocks()) {
final Mover.StorageTypeDiff diff = new Mover.StorageTypeDiff(types,
lb.getStorageTypes());
Assert.assertTrue(fileStatus.getFullName(parent.toString())
+ " with policy " + policy + " has non-empty overlap: " + diff
+ ", the corresponding block is " + lb.getBlock().getLocalBlock(),
diff.removeOverlap(true));
}
}
Replication getReplication(Path file) throws IOException {
return getOrVerifyReplication(file, null);
}
Replication verifyReplication(Path file, int expectedDiskCount,
int expectedArchiveCount) throws IOException {
final Replication r = new Replication();
r.disk = expectedDiskCount;
r.archive = expectedArchiveCount;
return getOrVerifyReplication(file, r);
}
private Replication getOrVerifyReplication(Path file, Replication expected)
throws IOException {
final List<LocatedBlock> lbs = dfs.getClient().getLocatedBlocks(
file.toString(), 0).getLocatedBlocks();
Assert.assertEquals(1, lbs.size());
LocatedBlock lb = lbs.get(0);
StringBuilder types = new StringBuilder();
final Replication r = new Replication();
for(StorageType t : lb.getStorageTypes()) {
types.append(t).append(", ");
if (t == StorageType.DISK) {
r.disk++;
} else if (t == StorageType.ARCHIVE) {
r.archive++;
} else {
Assert.fail("Unexpected storage type " + t);
}
}
if (expected != null) {
final String s = "file = " + file + "\n types = [" + types + "]";
Assert.assertEquals(s, expected, r);
}
return r;
}
}
static class Replication {
int disk;
int archive;
@Override
public int hashCode() {
return disk ^ archive;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (obj == null || !(obj instanceof Replication)) {
return false;
}
final Replication that = (Replication)obj;
return this.disk == that.disk && this.archive == that.archive;
}
@Override
public String toString() {
return "[disk=" + disk + ", archive=" + archive + "]";
}
}
private static StorageType[][] genStorageTypes(int numDataNodes) {
return genStorageTypes(numDataNodes, 0, 0, 0);
}
private static StorageType[][] genStorageTypes(int numDataNodes,
int numAllDisk, int numAllArchive) {
return genStorageTypes(numDataNodes, numAllDisk, numAllArchive, 0);
}
private static StorageType[][] genStorageTypes(int numDataNodes,
int numAllDisk, int numAllArchive, int numRamDisk) {
Preconditions.checkArgument(
(numAllDisk + numAllArchive + numRamDisk) <= numDataNodes);
StorageType[][] types = new StorageType[numDataNodes][];
int i = 0;
for (; i < numRamDisk; i++)
{
types[i] = new StorageType[]{StorageType.RAM_DISK, StorageType.DISK};
}
for (; i < numRamDisk + numAllDisk; i++) {
types[i] = new StorageType[]{StorageType.DISK, StorageType.DISK};
}
for (; i < numRamDisk + numAllDisk + numAllArchive; i++) {
types[i] = new StorageType[]{StorageType.ARCHIVE, StorageType.ARCHIVE};
}
for (; i < types.length; i++) {
types[i] = new StorageType[]{StorageType.DISK, StorageType.ARCHIVE};
}
return types;
}
private static long[][] genCapacities(int nDatanodes, int numAllDisk,
int numAllArchive, int numRamDisk, long diskCapacity,
long archiveCapacity, long ramDiskCapacity) {
final long[][] capacities = new long[nDatanodes][];
int i = 0;
for (; i < numRamDisk; i++) {
capacities[i] = new long[]{ramDiskCapacity, diskCapacity};
}
for (; i < numRamDisk + numAllDisk; i++) {
capacities[i] = new long[]{diskCapacity, diskCapacity};
}
for (; i < numRamDisk + numAllDisk + numAllArchive; i++) {
capacities[i] = new long[]{archiveCapacity, archiveCapacity};
}
for(; i < capacities.length; i++) {
capacities[i] = new long[]{diskCapacity, archiveCapacity};
}
return capacities;
}
private static class PathPolicyMap {
final Map<Path, BlockStoragePolicy> map = Maps.newHashMap();
final Path hot = new Path("/hot");
final Path warm = new Path("/warm");
final Path cold = new Path("/cold");
final List<Path> files;
PathPolicyMap(int filesPerDir){
map.put(hot, HOT);
map.put(warm, WARM);
map.put(cold, COLD);
files = new ArrayList<Path>();
for(Path dir : map.keySet()) {
for(int i = 0; i < filesPerDir; i++) {
files.add(new Path(dir, "file" + i));
}
}
}
NamespaceScheme newNamespaceScheme() {
return new NamespaceScheme(Arrays.asList(hot, warm, cold),
files, BLOCK_SIZE/2, null, map);
}
/**
* Move hot files to warm and cold, warm files to hot and cold,
* and cold files to hot and warm.
*/
void moveAround(DistributedFileSystem dfs) throws Exception {
for(Path srcDir : map.keySet()) {
int i = 0;
for(Path dstDir : map.keySet()) {
if (!srcDir.equals(dstDir)) {
final Path src = new Path(srcDir, "file" + i++);
final Path dst = new Path(dstDir, srcDir.getName() + "2" + dstDir.getName());
LOG.info("rename " + src + " to " + dst);
dfs.rename(src, dst);
}
}
}
}
}
/**
* A normal case for Mover: move a file into archival storage
*/
@Test
public void testMigrateFileToArchival() throws Exception {
LOG.info("testMigrateFileToArchival");
final Path foo = new Path("/foo");
Map<Path, BlockStoragePolicy> policyMap = Maps.newHashMap();
policyMap.put(foo, COLD);
NamespaceScheme nsScheme = new NamespaceScheme(null, Arrays.asList(foo),
2*BLOCK_SIZE, null, policyMap);
ClusterScheme clusterScheme = new ClusterScheme(DEFAULT_CONF,
NUM_DATANODES, REPL, genStorageTypes(NUM_DATANODES), null);
new MigrationTest(clusterScheme, nsScheme).runBasicTest(true);
}
/**
* Print a big banner in the test log to make debug easier.
*/
static void banner(String string) {
LOG.info("\n\n\n\n================================================\n" +
string + "\n" +
"==================================================\n\n");
}
/**
* Run Mover with arguments specifying files and directories
*/
@Test
public void testMoveSpecificPaths() throws Exception {
LOG.info("testMoveSpecificPaths");
final Path foo = new Path("/foo");
final Path barFile = new Path(foo, "bar");
final Path foo2 = new Path("/foo2");
final Path bar2File = new Path(foo2, "bar2");
Map<Path, BlockStoragePolicy> policyMap = Maps.newHashMap();
policyMap.put(foo, COLD);
policyMap.put(foo2, WARM);
NamespaceScheme nsScheme = new NamespaceScheme(Arrays.asList(foo, foo2),
Arrays.asList(barFile, bar2File), BLOCK_SIZE, null, policyMap);
ClusterScheme clusterScheme = new ClusterScheme(DEFAULT_CONF,
NUM_DATANODES, REPL, genStorageTypes(NUM_DATANODES), null);
MigrationTest test = new MigrationTest(clusterScheme, nsScheme);
test.setupCluster();
try {
test.prepareNamespace();
test.setStoragePolicy();
Map<URI, List<Path>> map = Mover.Cli.getNameNodePathsToMove(test.conf,
"-p", "/foo/bar", "/foo2");
int result = Mover.run(map, test.conf);
Assert.assertEquals(ExitStatus.SUCCESS.getExitCode(), result);
Thread.sleep(5000);
test.verify(true);
} finally {
test.shutdownCluster();
}
}
/**
* Move an open file into archival storage
*/
@Test
public void testMigrateOpenFileToArchival() throws Exception {
LOG.info("testMigrateOpenFileToArchival");
final Path fooDir = new Path("/foo");
Map<Path, BlockStoragePolicy> policyMap = Maps.newHashMap();
policyMap.put(fooDir, COLD);
NamespaceScheme nsScheme = new NamespaceScheme(Arrays.asList(fooDir), null,
BLOCK_SIZE, null, policyMap);
ClusterScheme clusterScheme = new ClusterScheme(DEFAULT_CONF,
NUM_DATANODES, REPL, genStorageTypes(NUM_DATANODES), null);
MigrationTest test = new MigrationTest(clusterScheme, nsScheme);
test.setupCluster();
// create an open file
banner("writing to file /foo/bar");
final Path barFile = new Path(fooDir, "bar");
DFSTestUtil.createFile(test.dfs, barFile, BLOCK_SIZE, (short) 1, 0L);
FSDataOutputStream out = test.dfs.append(barFile);
out.writeBytes("hello, ");
((DFSOutputStream) out.getWrappedStream()).hsync();
try {
banner("start data migration");
test.setStoragePolicy(); // set /foo to COLD
test.migrate();
// make sure the under construction block has not been migrated
LocatedBlocks lbs = test.dfs.getClient().getLocatedBlocks(
barFile.toString(), BLOCK_SIZE);
LOG.info("Locations: " + lbs);
List<LocatedBlock> blks = lbs.getLocatedBlocks();
Assert.assertEquals(1, blks.size());
Assert.assertEquals(1, blks.get(0).getLocations().length);
banner("finish the migration, continue writing");
// make sure the writing can continue
out.writeBytes("world!");
((DFSOutputStream) out.getWrappedStream()).hsync();
IOUtils.cleanup(LOG, out);
lbs = test.dfs.getClient().getLocatedBlocks(
barFile.toString(), BLOCK_SIZE);
LOG.info("Locations: " + lbs);
blks = lbs.getLocatedBlocks();
Assert.assertEquals(1, blks.size());
Assert.assertEquals(1, blks.get(0).getLocations().length);
banner("finish writing, starting reading");
// check the content of /foo/bar
FSDataInputStream in = test.dfs.open(barFile);
byte[] buf = new byte[13];
// read from offset 1024
in.readFully(BLOCK_SIZE, buf, 0, buf.length);
IOUtils.cleanup(LOG, in);
Assert.assertEquals("hello, world!", new String(buf));
} finally {
test.shutdownCluster();
}
}
/**
* Test directories with Hot, Warm and Cold polices.
*/
@Test
public void testHotWarmColdDirs() throws Exception {
LOG.info("testHotWarmColdDirs");
PathPolicyMap pathPolicyMap = new PathPolicyMap(3);
NamespaceScheme nsScheme = pathPolicyMap.newNamespaceScheme();
ClusterScheme clusterScheme = new ClusterScheme();
MigrationTest test = new MigrationTest(clusterScheme, nsScheme);
try {
test.runBasicTest(false);
pathPolicyMap.moveAround(test.dfs);
test.migrate();
test.verify(true);
} finally {
test.shutdownCluster();
}
}
private void waitForAllReplicas(int expectedReplicaNum, Path file,
DistributedFileSystem dfs) throws Exception {
for (int i = 0; i < 5; i++) {
LocatedBlocks lbs = dfs.getClient().getLocatedBlocks(file.toString(), 0,
BLOCK_SIZE);
LocatedBlock lb = lbs.get(0);
if (lb.getLocations().length >= expectedReplicaNum) {
return;
} else {
Thread.sleep(1000);
}
}
}
private void setVolumeFull(DataNode dn, StorageType type) {
List<? extends FsVolumeSpi> volumes = dn.getFSDataset().getVolumes();
for (FsVolumeSpi v : volumes) {
FsVolumeImpl volume = (FsVolumeImpl) v;
if (volume.getStorageType() == type) {
LOG.info("setCapacity to 0 for [" + volume.getStorageType() + "]"
+ volume.getStorageID());
volume.setCapacityForTesting(0);
}
}
}
/**
* Test DISK is running out of spaces.
*/
@Test
public void testNoSpaceDisk() throws Exception {
LOG.info("testNoSpaceDisk");
final PathPolicyMap pathPolicyMap = new PathPolicyMap(0);
final NamespaceScheme nsScheme = pathPolicyMap.newNamespaceScheme();
Configuration conf = new Configuration(DEFAULT_CONF);
final ClusterScheme clusterScheme = new ClusterScheme(conf,
NUM_DATANODES, REPL, genStorageTypes(NUM_DATANODES), null);
final MigrationTest test = new MigrationTest(clusterScheme, nsScheme);
try {
test.runBasicTest(false);
// create 2 hot files with replication 3
final short replication = 3;
for (int i = 0; i < 2; i++) {
final Path p = new Path(pathPolicyMap.hot, "file" + i);
DFSTestUtil.createFile(test.dfs, p, BLOCK_SIZE, replication, 0L);
waitForAllReplicas(replication, p, test.dfs);
}
// set all the DISK volume to full
for (DataNode dn : test.cluster.getDataNodes()) {
setVolumeFull(dn, StorageType.DISK);
DataNodeTestUtils.triggerHeartbeat(dn);
}
// test increasing replication. Since DISK is full,
// new replicas should be stored in ARCHIVE as a fallback storage.
final Path file0 = new Path(pathPolicyMap.hot, "file0");
final Replication r = test.getReplication(file0);
final short newReplication = (short) 5;
test.dfs.setReplication(file0, newReplication);
Thread.sleep(10000);
test.verifyReplication(file0, r.disk, newReplication - r.disk);
// test creating a cold file and then increase replication
final Path p = new Path(pathPolicyMap.cold, "foo");
DFSTestUtil.createFile(test.dfs, p, BLOCK_SIZE, replication, 0L);
test.verifyReplication(p, 0, replication);
test.dfs.setReplication(p, newReplication);
Thread.sleep(10000);
test.verifyReplication(p, 0, newReplication);
//test move a hot file to warm
final Path file1 = new Path(pathPolicyMap.hot, "file1");
test.dfs.rename(file1, pathPolicyMap.warm);
test.migrate();
test.verifyFile(new Path(pathPolicyMap.warm, "file1"), WARM.getId());
} finally {
test.shutdownCluster();
}
}
/**
* Test ARCHIVE is running out of spaces.
*/
@Test
public void testNoSpaceArchive() throws Exception {
LOG.info("testNoSpaceArchive");
final PathPolicyMap pathPolicyMap = new PathPolicyMap(0);
final NamespaceScheme nsScheme = pathPolicyMap.newNamespaceScheme();
final ClusterScheme clusterScheme = new ClusterScheme(DEFAULT_CONF,
NUM_DATANODES, REPL, genStorageTypes(NUM_DATANODES), null);
final MigrationTest test = new MigrationTest(clusterScheme, nsScheme);
try {
test.runBasicTest(false);
// create 2 hot files with replication 3
final short replication = 3;
for (int i = 0; i < 2; i++) {
final Path p = new Path(pathPolicyMap.cold, "file" + i);
DFSTestUtil.createFile(test.dfs, p, BLOCK_SIZE, replication, 0L);
waitForAllReplicas(replication, p, test.dfs);
}
// set all the ARCHIVE volume to full
for (DataNode dn : test.cluster.getDataNodes()) {
setVolumeFull(dn, StorageType.ARCHIVE);
DataNodeTestUtils.triggerHeartbeat(dn);
}
{ // test increasing replication but new replicas cannot be created
// since no more ARCHIVE space.
final Path file0 = new Path(pathPolicyMap.cold, "file0");
final Replication r = test.getReplication(file0);
Assert.assertEquals(0, r.disk);
final short newReplication = (short) 5;
test.dfs.setReplication(file0, newReplication);
Thread.sleep(10000);
test.verifyReplication(file0, 0, r.archive);
}
{ // test creating a hot file
final Path p = new Path(pathPolicyMap.hot, "foo");
DFSTestUtil.createFile(test.dfs, p, BLOCK_SIZE, (short) 3, 0L);
}
{ //test move a cold file to warm
final Path file1 = new Path(pathPolicyMap.cold, "file1");
test.dfs.rename(file1, pathPolicyMap.warm);
test.migrate();
test.verify(true);
}
} finally {
test.shutdownCluster();
}
}
}
| apache-2.0 |
GunoH/intellij-community | java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/normalizeRecordComponent/beforeSimple.java | 81 | // "Replace with Java-style array declaration" "true"
record X (int a[<caret>]){} | apache-2.0 |
jgsqware/clair | vendor/github.com/hashicorp/golang-lru/2q.go | 5023 | package lru
import (
"fmt"
"sync"
"github.com/hashicorp/golang-lru/simplelru"
)
const (
// Default2QRecentRatio is the ratio of the 2Q cache dedicated
// to recently added entries that have only been accessed once.
Default2QRecentRatio = 0.25
// Default2QGhostEntries is the default ratio of ghost
// entries kept to track entries recently evicted
Default2QGhostEntries = 0.50
)
// TwoQueueCache is a thread-safe fixed size 2Q cache.
// 2Q is an enhancement over the standard LRU cache
// in that it tracks both frequently and recently used
// entries seperately. This avoids a burst in access to new
// entries from evicting frequently used entries. It adds some
// additional tracking overhead to the standard LRU cache, and is
// computationally about 2x the cost, and adds some metadata over
// head. The ARCCache is similar, but does not require setting any
// parameters.
type TwoQueueCache struct {
size int
recentSize int
recent *simplelru.LRU
frequent *simplelru.LRU
recentEvict *simplelru.LRU
lock sync.RWMutex
}
// New2Q creates a new TwoQueueCache using the default
// values for the parameters.
func New2Q(size int) (*TwoQueueCache, error) {
return New2QParams(size, Default2QRecentRatio, Default2QGhostEntries)
}
// New2QParams creates a new TwoQueueCache using the provided
// parameter values.
func New2QParams(size int, recentRatio float64, ghostRatio float64) (*TwoQueueCache, error) {
if size <= 0 {
return nil, fmt.Errorf("invalid size")
}
if recentRatio < 0.0 || recentRatio > 1.0 {
return nil, fmt.Errorf("invalid recent ratio")
}
if ghostRatio < 0.0 || ghostRatio > 1.0 {
return nil, fmt.Errorf("invalid ghost ratio")
}
// Determine the sub-sizes
recentSize := int(float64(size) * recentRatio)
evictSize := int(float64(size) * ghostRatio)
// Allocate the LRUs
recent, err := simplelru.NewLRU(size, nil)
if err != nil {
return nil, err
}
frequent, err := simplelru.NewLRU(size, nil)
if err != nil {
return nil, err
}
recentEvict, err := simplelru.NewLRU(evictSize, nil)
if err != nil {
return nil, err
}
// Initialize the cache
c := &TwoQueueCache{
size: size,
recentSize: recentSize,
recent: recent,
frequent: frequent,
recentEvict: recentEvict,
}
return c, nil
}
func (c *TwoQueueCache) Get(key interface{}) (interface{}, bool) {
c.lock.Lock()
defer c.lock.Unlock()
// Check if this is a frequent value
if val, ok := c.frequent.Get(key); ok {
return val, ok
}
// If the value is contained in recent, then we
// promote it to frequent
if val, ok := c.recent.Peek(key); ok {
c.recent.Remove(key)
c.frequent.Add(key, val)
return val, ok
}
// No hit
return nil, false
}
func (c *TwoQueueCache) Add(key, value interface{}) {
c.lock.Lock()
defer c.lock.Unlock()
// Check if the value is frequently used already,
// and just update the value
if c.frequent.Contains(key) {
c.frequent.Add(key, value)
return
}
// Check if the value is recently used, and promote
// the value into the frequent list
if c.recent.Contains(key) {
c.recent.Remove(key)
c.frequent.Add(key, value)
return
}
// If the value was recently evicted, add it to the
// frequently used list
if c.recentEvict.Contains(key) {
c.ensureSpace(true)
c.recentEvict.Remove(key)
c.frequent.Add(key, value)
return
}
// Add to the recently seen list
c.ensureSpace(false)
c.recent.Add(key, value)
return
}
// ensureSpace is used to ensure we have space in the cache
func (c *TwoQueueCache) ensureSpace(recentEvict bool) {
// If we have space, nothing to do
recentLen := c.recent.Len()
freqLen := c.frequent.Len()
if recentLen+freqLen < c.size {
return
}
// If the recent buffer is larger than
// the target, evict from there
if recentLen > 0 && (recentLen > c.recentSize || (recentLen == c.recentSize && !recentEvict)) {
k, _, _ := c.recent.RemoveOldest()
c.recentEvict.Add(k, nil)
return
}
// Remove from the frequent list otherwise
c.frequent.RemoveOldest()
}
func (c *TwoQueueCache) Len() int {
c.lock.RLock()
defer c.lock.RUnlock()
return c.recent.Len() + c.frequent.Len()
}
func (c *TwoQueueCache) Keys() []interface{} {
c.lock.RLock()
defer c.lock.RUnlock()
k1 := c.frequent.Keys()
k2 := c.recent.Keys()
return append(k1, k2...)
}
func (c *TwoQueueCache) Remove(key interface{}) {
c.lock.Lock()
defer c.lock.Unlock()
if c.frequent.Remove(key) {
return
}
if c.recent.Remove(key) {
return
}
if c.recentEvict.Remove(key) {
return
}
}
func (c *TwoQueueCache) Purge() {
c.lock.Lock()
defer c.lock.Unlock()
c.recent.Purge()
c.frequent.Purge()
c.recentEvict.Purge()
}
func (c *TwoQueueCache) Contains(key interface{}) bool {
c.lock.RLock()
defer c.lock.RUnlock()
return c.frequent.Contains(key) || c.recent.Contains(key)
}
func (c *TwoQueueCache) Peek(key interface{}) (interface{}, bool) {
c.lock.RLock()
defer c.lock.RUnlock()
if val, ok := c.frequent.Peek(key); ok {
return val, ok
}
return c.recent.Peek(key)
}
| apache-2.0 |
shyamnamboodiripad/roslyn | src/Features/CSharp/Portable/Wrapping/SeparatedSyntaxList/CSharpArgumentWrapper.cs | 5126 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Wrapping.SeparatedSyntaxList
{
internal partial class CSharpArgumentWrapper
: AbstractCSharpSeparatedSyntaxListWrapper<BaseArgumentListSyntax, ArgumentSyntax>
{
protected override string Align_wrapped_items => FeaturesResources.Align_wrapped_arguments;
protected override string Indent_all_items => FeaturesResources.Indent_all_arguments;
protected override string Indent_wrapped_items => FeaturesResources.Indent_wrapped_arguments;
protected override string Unwrap_all_items => FeaturesResources.Unwrap_all_arguments;
protected override string Unwrap_and_indent_all_items => FeaturesResources.Unwrap_and_indent_all_arguments;
protected override string Unwrap_list => FeaturesResources.Unwrap_argument_list;
protected override string Wrap_every_item => FeaturesResources.Wrap_every_argument;
protected override string Wrap_long_list => FeaturesResources.Wrap_long_argument_list;
protected override SeparatedSyntaxList<ArgumentSyntax> GetListItems(BaseArgumentListSyntax listSyntax)
=> listSyntax.Arguments;
protected override BaseArgumentListSyntax TryGetApplicableList(SyntaxNode node)
=> node switch
{
InvocationExpressionSyntax invocationExpression => invocationExpression.ArgumentList,
ElementAccessExpressionSyntax elementAccessExpression => elementAccessExpression.ArgumentList,
ObjectCreationExpressionSyntax objectCreationExpression => objectCreationExpression.ArgumentList,
ConstructorInitializerSyntax constructorInitializer => constructorInitializer.ArgumentList,
_ => (BaseArgumentListSyntax)null,
};
protected override bool PositionIsApplicable(
SyntaxNode root, int position,
SyntaxNode declaration, BaseArgumentListSyntax listSyntax)
{
var startToken = listSyntax.GetFirstToken();
if (declaration is InvocationExpressionSyntax ||
declaration is ElementAccessExpressionSyntax)
{
// If we have something like Foo(...) or this.Foo(...) allow anywhere in the Foo(...)
// section.
var expr = (declaration as InvocationExpressionSyntax)?.Expression ??
(declaration as ElementAccessExpressionSyntax).Expression;
var name = TryGetInvokedName(expr);
startToken = name == null ? listSyntax.GetFirstToken() : name.GetFirstToken();
}
else if (declaration is ObjectCreationExpressionSyntax)
{
// allow anywhere in `new Foo(...)`
startToken = declaration.GetFirstToken();
}
else if (declaration is ConstructorInitializerSyntax constructorInitializer)
{
// allow anywhere in `this(...)` or `base(...)`
startToken = constructorInitializer.ThisOrBaseKeyword;
}
var endToken = listSyntax.GetLastToken();
var span = TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End);
if (!span.IntersectsWith(position))
{
return false;
}
// allow anywhere in the arg list, as long we don't end up walking through something
// complex like a lambda/anonymous function.
var token = root.FindToken(position);
if (token.Parent.Ancestors().Contains(listSyntax))
{
for (var current = token.Parent; current != listSyntax; current = current.Parent)
{
if (CSharpSyntaxFacts.Instance.IsAnonymousFunction(current))
{
return false;
}
}
}
return true;
}
private static ExpressionSyntax TryGetInvokedName(ExpressionSyntax expr)
{
// `Foo(...)`. Allow up through the 'Foo' portion
if (expr is NameSyntax name)
{
return name;
}
// `this[...]`. Allow up through the 'this' token.
if (expr is ThisExpressionSyntax || expr is BaseExpressionSyntax)
{
return expr;
}
// expr.Foo(...) or expr?.Foo(...)
// All up through the 'Foo' portion.
//
// Otherwise, only allow in the arg list.
return (expr as MemberAccessExpressionSyntax)?.Name ??
(expr as MemberBindingExpressionSyntax)?.Name;
}
}
}
| apache-2.0 |
Jasig/SSP-Platform | uportal-war/src/main/java/org/jasig/portal/dao/usertype/NullSafeStringType.java | 1202 | /**
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.portal.dao.usertype;
import org.jadira.usertype.spi.shared.AbstractSingleColumnUserType;
/**
* UserType for mapping strings that can be both null or empty
*
* @author Eric Dalquist
* @version $Revision$
*/
public class NullSafeStringType extends AbstractSingleColumnUserType<String, String, NullSafeStringColumnMapper> {
private static final long serialVersionUID = 1L;
}
| apache-2.0 |
tomerf/kubernetes | vendor/github.com/cilium/ebpf/abi.go | 3743 | package ebpf
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"syscall"
"github.com/pkg/errors"
)
// MapABI are the attributes of a Map which are available across all supported kernels.
type MapABI struct {
Type MapType
KeySize uint32
ValueSize uint32
MaxEntries uint32
Flags uint32
}
func newMapABIFromSpec(spec *MapSpec) *MapABI {
return &MapABI{
spec.Type,
spec.KeySize,
spec.ValueSize,
spec.MaxEntries,
spec.Flags,
}
}
func newMapABIFromFd(fd *bpfFD) (string, *MapABI, error) {
info, err := bpfGetMapInfoByFD(fd)
if err != nil {
if errors.Cause(err) == syscall.EINVAL {
abi, err := newMapABIFromProc(fd)
return "", abi, err
}
return "", nil, err
}
return "", &MapABI{
MapType(info.mapType),
info.keySize,
info.valueSize,
info.maxEntries,
info.flags,
}, nil
}
func newMapABIFromProc(fd *bpfFD) (*MapABI, error) {
var abi MapABI
err := scanFdInfo(fd, map[string]interface{}{
"map_type": &abi.Type,
"key_size": &abi.KeySize,
"value_size": &abi.ValueSize,
"max_entries": &abi.MaxEntries,
"map_flags": &abi.Flags,
})
if err != nil {
return nil, err
}
return &abi, nil
}
// Equal returns true if two ABIs have the same values.
func (abi *MapABI) Equal(other *MapABI) bool {
switch {
case abi.Type != other.Type:
return false
case abi.KeySize != other.KeySize:
return false
case abi.ValueSize != other.ValueSize:
return false
case abi.MaxEntries != other.MaxEntries:
return false
case abi.Flags != other.Flags:
return false
default:
return true
}
}
// ProgramABI are the attributes of a Program which are available across all supported kernels.
type ProgramABI struct {
Type ProgramType
}
func newProgramABIFromSpec(spec *ProgramSpec) *ProgramABI {
return &ProgramABI{
spec.Type,
}
}
func newProgramABIFromFd(fd *bpfFD) (string, *ProgramABI, error) {
info, err := bpfGetProgInfoByFD(fd)
if err != nil {
if errors.Cause(err) == syscall.EINVAL {
return newProgramABIFromProc(fd)
}
return "", nil, err
}
var name string
if bpfName := convertCString(info.name[:]); bpfName != "" {
name = bpfName
} else {
name = convertCString(info.tag[:])
}
return name, &ProgramABI{
Type: ProgramType(info.progType),
}, nil
}
func newProgramABIFromProc(fd *bpfFD) (string, *ProgramABI, error) {
var (
abi ProgramABI
name string
)
err := scanFdInfo(fd, map[string]interface{}{
"prog_type": &abi.Type,
"prog_tag": &name,
})
if err != nil {
return "", nil, err
}
return name, &abi, nil
}
func scanFdInfo(fd *bpfFD, fields map[string]interface{}) error {
raw, err := fd.value()
if err != nil {
return err
}
fh, err := os.Open(fmt.Sprintf("/proc/self/fdinfo/%d", raw))
if err != nil {
return err
}
defer fh.Close()
return errors.Wrap(scanFdInfoReader(fh, fields), fh.Name())
}
func scanFdInfoReader(r io.Reader, fields map[string]interface{}) error {
var (
scanner = bufio.NewScanner(r)
scanned int
)
for scanner.Scan() {
parts := bytes.SplitN(scanner.Bytes(), []byte("\t"), 2)
if len(parts) != 2 {
continue
}
name := bytes.TrimSuffix(parts[0], []byte(":"))
field, ok := fields[string(name)]
if !ok {
continue
}
if n, err := fmt.Fscanln(bytes.NewReader(parts[1]), field); err != nil || n != 1 {
return errors.Wrapf(err, "can't parse field %s", name)
}
scanned++
}
if err := scanner.Err(); err != nil {
return err
}
if scanned != len(fields) {
return errors.Errorf("parsed %d instead of %d fields", scanned, len(fields))
}
return nil
}
// Equal returns true if two ABIs have the same values.
func (abi *ProgramABI) Equal(other *ProgramABI) bool {
switch {
case abi.Type != other.Type:
return false
default:
return true
}
}
| apache-2.0 |
azmodii/aifh | vol1/scala-examples/src/main/scala/com/heatonresearch/aifh/normalize/package.scala | 104 | /**
* Support classes from: Chapter 2: Normalizing Data
*/
package com.heatonresearch.aifh.normalize;
| apache-2.0 |
rgoldberg/guava | android/guava/src/com/google/common/graph/DirectedNetworkConnections.java | 2210 | /*
* Copyright (C) 2016 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.graph;
import static com.google.common.graph.GraphConstants.EXPECTED_DEGREE;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableBiMap;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
/**
* An implementation of {@link NetworkConnections} for directed networks.
*
* @author James Sexton
* @param <N> Node parameter type
* @param <E> Edge parameter type
*/
final class DirectedNetworkConnections<N, E> extends AbstractDirectedNetworkConnections<N, E> {
protected DirectedNetworkConnections(
Map<E, N> inEdgeMap, Map<E, N> outEdgeMap, int selfLoopCount) {
super(inEdgeMap, outEdgeMap, selfLoopCount);
}
static <N, E> DirectedNetworkConnections<N, E> of() {
return new DirectedNetworkConnections<>(
HashBiMap.<E, N>create(EXPECTED_DEGREE), HashBiMap.<E, N>create(EXPECTED_DEGREE), 0);
}
static <N, E> DirectedNetworkConnections<N, E> ofImmutable(
Map<E, N> inEdges, Map<E, N> outEdges, int selfLoopCount) {
return new DirectedNetworkConnections<>(
ImmutableBiMap.copyOf(inEdges), ImmutableBiMap.copyOf(outEdges), selfLoopCount);
}
@Override
public Set<N> predecessors() {
return Collections.unmodifiableSet(((BiMap<E, N>) inEdgeMap).values());
}
@Override
public Set<N> successors() {
return Collections.unmodifiableSet(((BiMap<E, N>) outEdgeMap).values());
}
@Override
public Set<E> edgesConnecting(N node) {
return new EdgesConnecting<E>(((BiMap<E, N>) outEdgeMap).inverse(), node);
}
}
| apache-2.0 |
weolar/miniblink49 | third_party/WebKit/Source/modules/accessibility/AXObjectTest.cpp | 2722 | // 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 "modules/accessibility/AXObject.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/testing/DummyPageHolder.h"
#include <gtest/gtest.h>
namespace blink {
class AXObjectTest : public testing::Test {
protected:
Document& document() { return m_pageHolder->document(); }
private:
void SetUp() override;
OwnPtr<DummyPageHolder> m_pageHolder;
};
void AXObjectTest::SetUp()
{
m_pageHolder = DummyPageHolder::create(IntSize(800, 600));
}
TEST_F(AXObjectTest, IsARIAWidget)
{
String testContent = "<body>"
"<span id=\"plain\">plain</span><br>"
"<span id=\"button\" role=\"button\">button</span><br>"
"<span id=\"button-parent\" role=\"button\"><span>button-parent</span></span><br>"
"<span id=\"button-caps\" role=\"BUTTON\">button-caps</span><br>"
"<span id=\"button-second\" role=\"another-role button\">button-second</span><br>"
"<span id=\"aria-bogus\" aria-bogus=\"bogus\">aria-bogus</span><br>"
"<span id=\"aria-selected\" aria-selected>aria-selected</span><br>"
"<span id=\"haspopup\" aria-haspopup=\"true\">aria-haspopup-true</span><br>"
"<div id=\"focusable\" tabindex=\"1\">focusable</div><br>"
"<div tabindex=\"2\"><div id=\"focusable-parent\">focusable-parent</div></div><br>"
"</body>";
document().documentElement()->setInnerHTML(testContent, ASSERT_NO_EXCEPTION);
document().updateLayout();
Element* root(document().documentElement());
EXPECT_FALSE(AXObject::isInsideFocusableElementOrARIAWidget(*root->getElementById("plain")));
EXPECT_TRUE(AXObject::isInsideFocusableElementOrARIAWidget(*root->getElementById("button")));
EXPECT_TRUE(AXObject::isInsideFocusableElementOrARIAWidget(*root->getElementById("button-parent")));
EXPECT_TRUE(AXObject::isInsideFocusableElementOrARIAWidget(*root->getElementById("button-caps")));
EXPECT_TRUE(AXObject::isInsideFocusableElementOrARIAWidget(*root->getElementById("button-second")));
EXPECT_FALSE(AXObject::isInsideFocusableElementOrARIAWidget(*root->getElementById("aria-bogus")));
EXPECT_TRUE(AXObject::isInsideFocusableElementOrARIAWidget(*root->getElementById("aria-selected")));
EXPECT_TRUE(AXObject::isInsideFocusableElementOrARIAWidget(*root->getElementById("haspopup")));
EXPECT_TRUE(AXObject::isInsideFocusableElementOrARIAWidget(*root->getElementById("focusable")));
EXPECT_TRUE(AXObject::isInsideFocusableElementOrARIAWidget(*root->getElementById("focusable-parent")));
}
}
| apache-2.0 |
gsaslis/java | recipes/oracle.rb | 2615 | #
# Author:: Bryan W. Berry (<bryan.berry@gmail.com>)
# Cookbook Name:: java
# Recipe:: oracle
#
# Copyright 2011, Bryan w. Berry
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
unless node.recipe?('java::default')
Chef::Log.warn("Using java::default instead is recommended.")
# Even if this recipe is included by itself, a safety check is nice...
if node['java']['java_home'].nil? or node['java']['java_home'].empty?
include_recipe "java::set_attributes_from_version"
end
end
java_home = node['java']["java_home"]
arch = node['java']['arch']
case node['java']['jdk_version'].to_s
when "6"
tarball_url = node['java']['jdk']['6'][arch]['url']
tarball_checksum = node['java']['jdk']['6'][arch]['checksum']
bin_cmds = node['java']['jdk']['6']['bin_cmds']
when "7"
tarball_url = node['java']['jdk']['7'][arch]['url']
tarball_checksum = node['java']['jdk']['7'][arch]['checksum']
bin_cmds = node['java']['jdk']['7']['bin_cmds']
when "8"
tarball_url = node['java']['jdk']['8'][arch]['url']
tarball_checksum = node['java']['jdk']['8'][arch]['checksum']
bin_cmds = node['java']['jdk']['8']['bin_cmds']
end
if tarball_url =~ /example.com/
Chef::Application.fatal!("You must change the download link to your private repository. You can no longer download java directly from http://download.oracle.com without a web broswer")
end
include_recipe "java::set_java_home"
package "tar"
java_ark "jdk" do
url tarball_url
default node['java']['set_default']
checksum tarball_checksum
app_home java_home
bin_cmds bin_cmds
alternatives_priority node['java']['alternatives_priority']
retries node['java']['ark_retries']
retry_delay node['java']['ark_retry_delay']
connect_timeout node['java']['ark_timeout']
use_alt_suffix node['java']['use_alt_suffix']
reset_alternatives node['java']['reset_alternatives']
download_timeout node['java']['ark_download_timeout']
action :install
end
if node['java']['set_default'] and platform_family?('debian')
include_recipe 'java::default_java_symlink'
end
include_recipe 'java::oracle_jce' if node['java']['oracle']['jce']['enabled']
| apache-2.0 |
tgautier/tomighty | tomighty-swing/src/test/java/org/tomighty/time/TimerTest.java | 3802 | package org.tomighty.time;
import org.junit.Before;
import org.junit.Test;
import org.tomighty.Phase;
import org.tomighty.bus.messages.timer.TimerFinished;
import org.tomighty.bus.messages.timer.TimerInterrupted;
import org.tomighty.bus.messages.timer.TimerStarted;
import org.tomighty.bus.messages.timer.TimerTick;
import org.tomighty.mock.bus.MockBus;
import java.util.List;
import static junit.framework.Assert.*;
public class TimerTest {
private MockBus bus;
private Timer timer;
@Before
public void setUp() throws Exception {
bus = new MockBus();
timer = new DefaultTimer(bus);
}
@Test(timeout = 5000)
public void startTimerAndWaitToFinish() {
timer.start(Time.seconds(3), Phase.POMODORO);
List<Object> messages = bus.waitUntilNumberOfMessagesReach(5);
assertEquals("Amount of published messages", 5, messages.size());
assertEquals("First message", TimerStarted.class, messages.get(0).getClass());
assertEquals("Second message", TimerTick.class, messages.get(1).getClass());
assertEquals("Third message", TimerTick.class, messages.get(2).getClass());
assertEquals("Fourth message", TimerTick.class, messages.get(3).getClass());
assertEquals("Fifth message", TimerFinished.class, messages.get(4).getClass());
TimerStarted timerStarted = (TimerStarted) messages.get(0);
assertEquals("Initial time", Time.seconds(3), timerStarted.getTime());
assertEquals("Phase when timer started", Phase.POMODORO, timerStarted.getPhase());
TimerTick firstTick = (TimerTick) messages.get(1);
assertEquals("First tick's time", Time.seconds(2), firstTick.getTime());
assertEquals("First tick's phase", Phase.POMODORO, firstTick.getPhase());
TimerTick secondTick = (TimerTick) messages.get(2);
assertEquals("Second tick's time", Time.seconds(1), secondTick.getTime());
assertEquals("Second tick's phase", Phase.POMODORO, secondTick.getPhase());
TimerTick thirdTick = (TimerTick) messages.get(3);
assertEquals("Third tick's time", Time.seconds(0), thirdTick.getTime());
assertEquals("Third tick's phase", Phase.POMODORO, thirdTick.getPhase());
TimerFinished timerFinished = (TimerFinished) messages.get(4);
assertEquals("Phase when timer finished", Phase.POMODORO, timerFinished.getPhase());
}
@Test(timeout = 5000)
public void startTimerAndInterruptAfterFirstTick() {
timer.start(Time.seconds(3), Phase.BREAK);
List<Object> messages = bus.waitUntilNumberOfMessagesReach(2);
timer.interrupt();
assertEquals("Amount of published messages", 3, messages.size());
assertEquals("First message", TimerStarted.class, messages.get(0).getClass());
assertEquals("Second message", TimerTick.class, messages.get(1).getClass());
assertEquals("Third message", TimerInterrupted.class, messages.get(2).getClass());
TimerStarted timerStarted = (TimerStarted) messages.get(0);
assertEquals("Initial time", Time.seconds(3), timerStarted.getTime());
assertEquals("Phase when timer started", Phase.BREAK, timerStarted.getPhase());
TimerTick tick = (TimerTick) messages.get(1);
assertEquals("Tick's time", Time.seconds(2), tick.getTime());
assertEquals("Tick's phase", Phase.BREAK, tick.getPhase());
TimerInterrupted timerInterrupted = (TimerInterrupted) messages.get(2);
assertEquals("Time when timer was interrupted", Time.seconds(2), timerInterrupted.getTime());
assertEquals("Phase when timer was interrupted", Phase.BREAK, timerInterrupted.getPhase());
}
}
| apache-2.0 |
ASU-Capstone/uPortal | uportal-war/src/main/java/org/jasig/portal/jmx/FrameworkMBeanImpl.java | 4395 | /**
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.portal.jmx;
import java.util.Date;
import org.jasig.portal.RDBMServices;
import org.jasig.portal.services.Authentication;
import org.jasig.portal.utils.MovingAverageSample;
/**
* uPortal metrics to make available via JMX.
*
* @author George Lindholm <a href="mailto:George.Lindholm@ubc.ca">George.Lindholm@ubc.ca</a>
* @version $Revision$ $Date$
* @since uPortal 2.5
*/
public class FrameworkMBeanImpl implements FrameworkMBean {
public FrameworkMBeanImpl() {
}
/**
* Time/Data uPortal was started
* @return Date
*/
@Override
public Date getStartedAt() {
return new Date(0); //PortalSessionManager.STARTED_AT;
}
/*
* Track framework rendering performance
*/
@Override
public long getRenderAverage() {
return this.getLastRender().average;
}
@Override
public long getRenderHighMax() {
return this.getLastRender().highMax;
}
@Override
public long getRenderLast() {
return this.getLastRender().lastSample;
}
@Override
public long getRenderMin() {
return this.getLastRender().min;
}
@Override
public long getRenderMax() {
return this.getLastRender().max;
}
@Override
public long getRenderTotalRenders() {
return this.getLastRender().totalSamples;
}
public MovingAverageSample getLastRender() {
return null;//StaticRenderingPipeline.getLastRenderSample();
}
/*
* Track framework database performance
*/
public MovingAverageSample getLastDatabase() {
return RDBMServices.getLastDatabase();
}
@Override
public long getDatabaseAverage() {
return this.getLastDatabase().average;
}
@Override
public long getDatabaseHighMax() {
return this.getLastDatabase().highMax;
}
@Override
public long getDatabaseLast() {
return this.getLastDatabase().lastSample;
}
@Override
public long getDatabaseMin() {
return this.getLastDatabase().min;
}
@Override
public long getDatabaseMax() {
return this.getLastDatabase().max;
}
@Override
public long getDatabaseTotalConnections() {
return this.getLastDatabase().totalSamples;
}
@Override
public int getRDBMActiveConnectionCount() {
return RDBMServices.getActiveConnectionCount();
}
@Override
public int getRDBMMaxConnectionCount() {
return RDBMServices.getMaxConnectionCount();
}
/*
* Track framework Authentication performance
*/
public MovingAverageSample getLastAuthentication() {
return Authentication.lastAuthentication;
}
@Override
public long getAuthenticationAverage() {
return Authentication.lastAuthentication.average;
}
@Override
public long getAuthenticationHighMax() {
return Authentication.lastAuthentication.highMax;
}
@Override
public long getAuthenticationLast() {
return Authentication.lastAuthentication.lastSample;
}
@Override
public long getAuthenticationMin() {
return Authentication.lastAuthentication.min;
}
@Override
public long getAuthenticationMax() {
return Authentication.lastAuthentication.max;
}
@Override
public long getAuthenticationTotalLogins() {
return Authentication.lastAuthentication.totalSamples;
}
// Threads
@Override
public long getThreadCount() {
return -1;//PortalSessionManager.getThreadGroup().activeCount();
}
}
| apache-2.0 |
tcrossland/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/jobexecutor/TimerActivateJobDefinitionHandler.java | 2088 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.impl.jobexecutor;
import org.camunda.bpm.engine.impl.cmd.AbstractSetJobDefinitionStateCmd;
import org.camunda.bpm.engine.impl.cmd.ActivateJobDefinitionCmd;
import org.camunda.bpm.engine.impl.util.json.JSONObject;
/**
* @author roman.smirnov
*/
public class TimerActivateJobDefinitionHandler extends TimerChangeJobDefinitionSuspensionStateJobHandler {
public static final String TYPE = "activate-job-definition";
public String getType() {
return TYPE;
}
protected AbstractSetJobDefinitionStateCmd getCommand(String configuration) {
JSONObject config = new JSONObject(configuration);
boolean activateJobs = getIncludeJobs(config);
ActivateJobDefinitionCmd cmd = null;
String by = getBy(config);
if (by.equals(JOB_HANDLER_CFG_JOB_DEFINITION_ID)) {
String jobDefinitionId = getJobDefinitionId(config);
cmd = new ActivateJobDefinitionCmd(jobDefinitionId, null, null, activateJobs, null);
} else
if (by.equals(JOB_HANDLER_CFG_PROCESS_DEFINITION_ID)) {
String processDefinitionId = getProcessDefinitionId(config);
cmd = new ActivateJobDefinitionCmd(null, processDefinitionId, null, activateJobs, null);
} else
if (by.equals(JOB_HANDLER_CFG_PROCESS_DEFINITION_KEY)) {
String processDefinitionKey = getProcessDefinitionKey(config);
cmd = new ActivateJobDefinitionCmd(null, null, processDefinitionKey, activateJobs, null);
}
return cmd;
}
}
| apache-2.0 |
kostasdizas/homebrew-fonts | Casks/font-m-plus.rb | 2460 | cask :v1 => 'font-m-plus' do
version '1.059'
sha256 '7862e113e04986646117267c4baee30aea163d43a382c14693f15287f16bbf25'
url 'http://dl.sourceforge.jp/mplus-fonts/62344/mplus-TESTFLIGHT-059.tar.xz'
homepage 'http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/design/index-en.html'
license :oss
depends_on :formula => 'xz'
font 'mplus-TESTFLIGHT-059/mplus-1c-black.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1c-bold.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1c-heavy.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1c-light.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1c-medium.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1c-regular.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1c-thin.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1m-bold.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1m-light.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1m-medium.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1m-regular.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1m-thin.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1mn-bold.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1mn-light.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1mn-medium.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1mn-regular.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1mn-thin.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1p-black.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1p-bold.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1p-heavy.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1p-light.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1p-medium.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1p-regular.ttf'
font 'mplus-TESTFLIGHT-059/mplus-1p-thin.ttf'
font 'mplus-TESTFLIGHT-059/mplus-2c-black.ttf'
font 'mplus-TESTFLIGHT-059/mplus-2c-bold.ttf'
font 'mplus-TESTFLIGHT-059/mplus-2c-heavy.ttf'
font 'mplus-TESTFLIGHT-059/mplus-2c-light.ttf'
font 'mplus-TESTFLIGHT-059/mplus-2c-medium.ttf'
font 'mplus-TESTFLIGHT-059/mplus-2c-regular.ttf'
font 'mplus-TESTFLIGHT-059/mplus-2c-thin.ttf'
font 'mplus-TESTFLIGHT-059/mplus-2m-bold.ttf'
font 'mplus-TESTFLIGHT-059/mplus-2m-light.ttf'
font 'mplus-TESTFLIGHT-059/mplus-2m-medium.ttf'
font 'mplus-TESTFLIGHT-059/mplus-2m-regular.ttf'
font 'mplus-TESTFLIGHT-059/mplus-2m-thin.ttf'
font 'mplus-TESTFLIGHT-059/mplus-2p-black.ttf'
font 'mplus-TESTFLIGHT-059/mplus-2p-bold.ttf'
font 'mplus-TESTFLIGHT-059/mplus-2p-heavy.ttf'
font 'mplus-TESTFLIGHT-059/mplus-2p-light.ttf'
font 'mplus-TESTFLIGHT-059/mplus-2p-medium.ttf'
font 'mplus-TESTFLIGHT-059/mplus-2p-regular.ttf'
font 'mplus-TESTFLIGHT-059/mplus-2p-thin.ttf'
end
| bsd-2-clause |
DrOctogon/Satchmo | satchmo/apps/payment/__init__.py | 469 | def active_gateways():
"""Get a list of activated payment gateways, in the form of
[(module, config module name),...]
"""
from django.db import models
gateways = []
for app in models.get_apps():
if hasattr(app, 'PAYMENT_PROCESSOR'):
parts = app.__name__.split('.')[:-1]
module = ".".join(parts)
group = 'PAYMENT_%s' % parts[-1].upper()
gateways.append((module, group))
return gateways
| bsd-3-clause |
MetSystem/EntityFramework.Extended | Source/EntityFramework.Extended.Test/Caching/CachePolicyTest.cs | 2346 | using System.Runtime.Caching;
using EntityFramework.Caching;
using FluentAssertions;
using Xunit;
using System;
namespace EntityFramework.Test.Caching
{
public class CachePolicyTest
{
[Fact]
public void CachePolicyConstructorTest()
{
var cachePolicy = new CachePolicy();
cachePolicy.Should().NotBeNull();
cachePolicy.Mode.Should().Be(CacheExpirationMode.None);
cachePolicy.AbsoluteExpiration.Should().Be(ObjectCache.InfiniteAbsoluteExpiration);
cachePolicy.SlidingExpiration.Should().Be(ObjectCache.NoSlidingExpiration);
}
[Fact]
public void WithAbsoluteExpirationTest()
{
var absoluteExpiration = new DateTimeOffset(2012, 1, 1, 12, 0, 0, TimeSpan.Zero);
var cachePolicy = CachePolicy.WithAbsoluteExpiration(absoluteExpiration);
cachePolicy.Should().NotBeNull();
cachePolicy.Mode.Should().Be(CacheExpirationMode.Absolute);
cachePolicy.AbsoluteExpiration.Should().Be(absoluteExpiration);
cachePolicy.SlidingExpiration.Should().Be(ObjectCache.NoSlidingExpiration);
}
[Fact]
public void WithSlidingExpirationTest()
{
TimeSpan slidingExpiration = TimeSpan.FromMinutes(5);
var cachePolicy = CachePolicy.WithSlidingExpiration(slidingExpiration);
cachePolicy.Should().NotBeNull();
cachePolicy.Mode.Should().Be(CacheExpirationMode.Sliding);
cachePolicy.AbsoluteExpiration.Should().Be(ObjectCache.InfiniteAbsoluteExpiration);
cachePolicy.SlidingExpiration.Should().Be(slidingExpiration);
}
[Fact]
public void WithDurationExpirationTest()
{
TimeSpan expirationSpan = TimeSpan.FromSeconds(30);
var cachePolicy = CachePolicy.WithDurationExpiration(expirationSpan);
cachePolicy.Should().NotBeNull();
cachePolicy.Mode.Should().Be(CacheExpirationMode.Duration);
cachePolicy.AbsoluteExpiration.Should().Be(ObjectCache.InfiniteAbsoluteExpiration);
cachePolicy.SlidingExpiration.Should().Be(ObjectCache.NoSlidingExpiration);
cachePolicy.Duration.Should().Be(expirationSpan);
}
}
}
| bsd-3-clause |
takaaptech/sky_engine | gpu/perftests/texture_upload_perftest.cc | 20046 | // 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 <algorithm>
#include <vector>
#include "base/containers/small_map.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/stringprintf.h"
#include "gpu/perftests/measurements.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/perf/perf_test.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/vector2d_f.h"
#include "ui/gl/gl_bindings.h"
#include "ui/gl/gl_context.h"
#include "ui/gl/gl_enums.h"
#include "ui/gl/gl_surface.h"
#include "ui/gl/gl_version_info.h"
#include "ui/gl/gpu_timing.h"
#include "ui/gl/scoped_make_current.h"
namespace gpu {
namespace {
const int kUploadPerfWarmupRuns = 5;
const int kUploadPerfTestRuns = 30;
#define SHADER(Src) #Src
// clang-format off
const char kVertexShader[] =
SHADER(
uniform vec2 translation;
attribute vec2 a_position;
attribute vec2 a_texCoord;
varying vec2 v_texCoord;
void main() {
gl_Position = vec4(
translation.x + a_position.x, translation.y + a_position.y, 0.0, 1.0);
v_texCoord = a_texCoord;
}
);
const char kShaderDefaultFloatPrecision[] =
SHADER(
precision mediump float;
);
const char kFragmentShader[] =
SHADER(
uniform sampler2D a_texture;
varying vec2 v_texCoord;
void main() {
gl_FragColor = texture2D(a_texture, v_texCoord);
}
);
// clang-format on
void CheckNoGlError(const std::string& msg) {
CHECK_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError()) << " " << msg;
}
// Utility function to compile a shader from a string.
GLuint LoadShader(const GLenum type, const char* const src) {
GLuint shader = 0;
shader = glCreateShader(type);
CHECK_NE(0u, shader);
glShaderSource(shader, 1, &src, NULL);
glCompileShader(shader);
GLint compiled = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
if (compiled == 0) {
GLint len = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len);
if (len > 1) {
scoped_ptr<char> error_log(new char[len]);
glGetShaderInfoLog(shader, len, NULL, error_log.get());
LOG(ERROR) << "Error compiling shader: " << error_log.get();
}
}
CHECK_NE(0, compiled);
return shader;
}
int GLFormatBytePerPixel(GLenum format) {
DCHECK(format == GL_RGBA || format == GL_LUMINANCE || format == GL_RED_EXT);
return format == GL_RGBA ? 4 : 1;
}
GLenum GLFormatToInternalFormat(GLenum format) {
return format == GL_RED ? GL_R8 : format;
}
GLenum GLFormatToStorageFormat(GLenum format) {
switch (format) {
case GL_RGBA:
return GL_RGBA8;
case GL_LUMINANCE:
return GL_LUMINANCE8;
case GL_RED:
return GL_R8;
default:
NOTREACHED();
}
return 0;
}
void GenerateTextureData(const gfx::Size& size,
int bytes_per_pixel,
const int seed,
std::vector<uint8>* const pixels) {
// Row bytes has to be multiple of 4 (GL_PACK_ALIGNMENT defaults to 4).
int stride = ((size.width() * bytes_per_pixel) + 3) & ~0x3;
pixels->resize(size.height() * stride);
for (int y = 0; y < size.height(); ++y) {
for (int x = 0; x < size.width(); ++x) {
for (int channel = 0; channel < bytes_per_pixel; ++channel) {
int index = y * stride + x * bytes_per_pixel;
pixels->at(index) = (index + (seed << 2)) % (0x20 << channel);
}
}
}
}
// Compare a buffer containing pixels in a specified format to GL_RGBA buffer
// where the former buffer have been uploaded as a texture and drawn on the
// RGBA buffer.
bool CompareBufferToRGBABuffer(GLenum format,
const gfx::Size& size,
const std::vector<uint8>& pixels,
const std::vector<uint8>& rgba) {
int bytes_per_pixel = GLFormatBytePerPixel(format);
int pixels_stride = ((size.width() * bytes_per_pixel) + 3) & ~0x3;
int rgba_stride = size.width() * GLFormatBytePerPixel(GL_RGBA);
for (int y = 0; y < size.height(); ++y) {
for (int x = 0; x < size.width(); ++x) {
int rgba_index = y * rgba_stride + x * GLFormatBytePerPixel(GL_RGBA);
int pixels_index = y * pixels_stride + x * bytes_per_pixel;
uint8 expected[4] = {0};
switch (format) {
case GL_LUMINANCE: // (L_t, L_t, L_t, 1)
expected[1] = pixels[pixels_index];
expected[2] = pixels[pixels_index];
case GL_RED: // (R_t, 0, 0, 1)
expected[0] = pixels[pixels_index];
expected[3] = 255;
break;
case GL_RGBA: // (R_t, G_t, B_t, A_t)
memcpy(expected, &pixels[pixels_index], 4);
break;
default:
NOTREACHED();
}
if (memcmp(&rgba[rgba_index], expected, 4)) {
return false;
}
}
}
return true;
}
// PerfTest to check costs of texture upload at different stages
// on different platforms.
class TextureUploadPerfTest : public testing::Test {
public:
TextureUploadPerfTest() : fbo_size_(1024, 1024) {}
// Overridden from testing::Test
void SetUp() override {
static bool gl_initialized = gfx::GLSurface::InitializeOneOff();
DCHECK(gl_initialized);
// Initialize an offscreen surface and a gl context.
surface_ = gfx::GLSurface::CreateOffscreenGLSurface(gfx::Size(4, 4));
gl_context_ = gfx::GLContext::CreateGLContext(NULL, // share_group
surface_.get(),
gfx::PreferIntegratedGpu);
ui::ScopedMakeCurrent smc(gl_context_.get(), surface_.get());
glGenTextures(1, &color_texture_);
glBindTexture(GL_TEXTURE_2D, color_texture_);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, fbo_size_.width(),
fbo_size_.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glGenFramebuffersEXT(1, &framebuffer_object_);
glBindFramebufferEXT(GL_FRAMEBUFFER, framebuffer_object_);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, color_texture_, 0);
DCHECK_EQ(static_cast<GLenum>(GL_FRAMEBUFFER_COMPLETE),
glCheckFramebufferStatusEXT(GL_FRAMEBUFFER));
glViewport(0, 0, fbo_size_.width(), fbo_size_.height());
gpu_timing_client_ = gl_context_->CreateGPUTimingClient();
if (gpu_timing_client_->IsAvailable()) {
LOG(INFO) << "Gpu timing initialized with timer type: "
<< gpu_timing_client_->GetTimerTypeName();
gpu_timing_client_->InvalidateTimerOffset();
} else {
LOG(WARNING) << "Can't initialize gpu timing";
}
// Prepare a simple program and a vertex buffer that will be
// used to draw a quad on the offscreen surface.
vertex_shader_ = LoadShader(GL_VERTEX_SHADER, kVertexShader);
bool is_gles = gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2;
fragment_shader_ = LoadShader(
GL_FRAGMENT_SHADER,
base::StringPrintf("%s%s", is_gles ? kShaderDefaultFloatPrecision : "",
kFragmentShader).c_str());
program_object_ = glCreateProgram();
CHECK_NE(0u, program_object_);
glAttachShader(program_object_, vertex_shader_);
glAttachShader(program_object_, fragment_shader_);
glBindAttribLocation(program_object_, 0, "a_position");
glBindAttribLocation(program_object_, 1, "a_texCoord");
glLinkProgram(program_object_);
GLint linked = -1;
glGetProgramiv(program_object_, GL_LINK_STATUS, &linked);
CHECK_NE(0, linked);
glUseProgram(program_object_);
glUniform1i(sampler_location_, 0);
translation_location_ =
glGetUniformLocation(program_object_, "translation");
DCHECK_NE(-1, translation_location_);
glUniform2f(translation_location_, 0.0f, 0.0f);
sampler_location_ = glGetUniformLocation(program_object_, "a_texture");
CHECK_NE(-1, sampler_location_);
glGenBuffersARB(1, &vertex_buffer_);
CHECK_NE(0u, vertex_buffer_);
DCHECK_NE(0u, vertex_buffer_);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 4, 0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 4,
reinterpret_cast<void*>(sizeof(GLfloat) * 2));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
CheckNoGlError("glEnableVertexAttribArray");
has_texture_storage_ =
gl_context_->GetVersionInfo()->is_es3 ||
gl_context_->HasExtension("GL_EXT_texture_storage") ||
gl_context_->HasExtension("GL_ARB_texture_storage");
}
void GenerateVertexBuffer(const gfx::Size& size) {
DCHECK_NE(0u, vertex_buffer_);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_);
// right and top are in clipspace
float right = -1.f + 2.f * size.width() / fbo_size_.width();
float top = -1.f + 2.f * size.height() / fbo_size_.height();
// Four vertexes, one per line. Each vertex has two components per
// position and two per texcoord.
// It represents a quad formed by two triangles if interpreted
// as a tristrip.
// clang-format off
GLfloat data[16] = {
-1.f, -1.f, 0.f, 0.f,
right, -1.f, 1.f, 0.f,
-1.f, top, 0.f, 1.f,
right, top, 1.f, 1.f};
// clang-format on
glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW);
CheckNoGlError("glBufferData");
}
void TearDown() override {
ui::ScopedMakeCurrent smc(gl_context_.get(), surface_.get());
glDeleteProgram(program_object_);
glDeleteShader(vertex_shader_);
glDeleteShader(fragment_shader_);
glDeleteBuffersARB(1, &vertex_buffer_);
glBindFramebufferEXT(GL_FRAMEBUFFER, 0);
glDeleteFramebuffersEXT(1, &framebuffer_object_);
glDeleteTextures(1, &color_texture_);
CheckNoGlError("glDeleteTextures");
gpu_timing_client_ = nullptr;
gl_context_ = nullptr;
surface_ = nullptr;
}
protected:
GLuint CreateGLTexture(const GLenum format,
const gfx::Size& size,
const bool specify_storage) {
GLuint texture_id = 0;
glActiveTexture(GL_TEXTURE0);
glGenTextures(1, &texture_id);
glBindTexture(GL_TEXTURE_2D, texture_id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
if (specify_storage) {
if (has_texture_storage_) {
glTexStorage2DEXT(GL_TEXTURE_2D, 1, GLFormatToStorageFormat(format),
size.width(), size.height());
CheckNoGlError("glTexStorage2DEXT");
} else {
glTexImage2D(GL_TEXTURE_2D, 0, GLFormatToInternalFormat(format),
size.width(), size.height(), 0, format, GL_UNSIGNED_BYTE,
nullptr);
CheckNoGlError("glTexImage2D");
}
}
return texture_id;
}
void UploadTexture(GLuint texture_id,
const gfx::Size& size,
const std::vector<uint8>& pixels,
GLenum format,
const bool subimage) {
if (subimage) {
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size.width(), size.height(),
format, GL_UNSIGNED_BYTE, &pixels[0]);
CheckNoGlError("glTexSubImage2D");
} else {
glTexImage2D(GL_TEXTURE_2D, 0, GLFormatToInternalFormat(format),
size.width(), size.height(), 0, format, GL_UNSIGNED_BYTE,
&pixels[0]);
CheckNoGlError("glTexImage2D");
}
}
// Upload and draw on the offscren surface.
// Return a list of pair. Each pair describe a gl operation and the wall
// time elapsed in milliseconds.
std::vector<Measurement> UploadAndDraw(GLuint texture_id,
const gfx::Size& size,
const std::vector<uint8>& pixels,
const GLenum format,
const bool subimage) {
MeasurementTimers tex_timers(gpu_timing_client_.get());
UploadTexture(texture_id, size, pixels, format, subimage);
tex_timers.Record();
MeasurementTimers draw_timers(gpu_timing_client_.get());
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
draw_timers.Record();
MeasurementTimers finish_timers(gpu_timing_client_.get());
glFinish();
CheckNoGlError("glFinish");
finish_timers.Record();
std::vector<uint8> pixels_rendered(size.GetArea() * 4);
glReadPixels(0, 0, size.width(), size.height(), GL_RGBA, GL_UNSIGNED_BYTE,
&pixels_rendered[0]);
CheckNoGlError("glReadPixels");
EXPECT_TRUE(
CompareBufferToRGBABuffer(format, size, pixels, pixels_rendered))
<< "Format is: " << gfx::GLEnums::GetStringEnum(format);
std::vector<Measurement> measurements;
bool gpu_timer_errors =
gpu_timing_client_->IsAvailable() &&
gpu_timing_client_->CheckAndResetTimerErrors();
if (!gpu_timer_errors) {
measurements.push_back(tex_timers.GetAsMeasurement(
subimage ? "texsubimage2d" : "teximage2d"));
measurements.push_back(draw_timers.GetAsMeasurement("drawarrays"));
measurements.push_back(finish_timers.GetAsMeasurement("finish"));
}
return measurements;
}
void RunUploadAndDrawMultipleTimes(const gfx::Size& size,
const GLenum format,
const bool subimage) {
std::vector<uint8> pixels;
base::SmallMap<std::map<std::string, Measurement>>
aggregates; // indexed by name
int successful_runs = 0;
GLuint texture_id = CreateGLTexture(format, size, subimage);
for (int i = 0; i < kUploadPerfWarmupRuns + kUploadPerfTestRuns; ++i) {
GenerateTextureData(size, GLFormatBytePerPixel(format), i + 1, &pixels);
auto run = UploadAndDraw(texture_id, size, pixels, format, subimage);
if (i < kUploadPerfWarmupRuns || !run.size()) {
continue;
}
successful_runs++;
for (const Measurement& measurement : run) {
auto& aggregate = aggregates[measurement.name];
aggregate.name = measurement.name;
aggregate.Increment(measurement);
}
}
glDeleteTextures(1, &texture_id);
std::string graph_name = base::StringPrintf(
"%d_%s", size.width(), gfx::GLEnums::GetStringEnum(format).c_str());
if (subimage) {
graph_name += "_sub";
}
if (successful_runs) {
for (const auto& entry : aggregates) {
const auto m = entry.second.Divide(successful_runs);
m.PrintResult(graph_name);
}
}
perf_test::PrintResult("sample_runs", "", graph_name,
static_cast<size_t>(successful_runs), "laps", true);
}
const gfx::Size fbo_size_; // for the fbo
scoped_refptr<gfx::GLContext> gl_context_;
scoped_refptr<gfx::GLSurface> surface_;
scoped_refptr<gfx::GPUTimingClient> gpu_timing_client_;
GLuint color_texture_ = 0;
GLuint framebuffer_object_ = 0;
GLuint vertex_shader_ = 0;
GLuint fragment_shader_ = 0;
GLuint program_object_ = 0;
GLint sampler_location_ = -1;
GLint translation_location_ = -1;
GLuint vertex_buffer_ = 0;
bool has_texture_storage_ = false;
};
// Perf test that generates, uploads and draws a texture on a surface repeatedly
// and prints out aggregated measurements for all the runs.
TEST_F(TextureUploadPerfTest, upload) {
int sizes[] = {21, 128, 256, 512, 1024};
std::vector<GLenum> formats;
formats.push_back(GL_RGBA);
if (!gl_context_->GetVersionInfo()->is_es3) {
// Used by default for ResourceProvider::yuv_resource_format_.
formats.push_back(GL_LUMINANCE);
}
ui::ScopedMakeCurrent smc(gl_context_.get(), surface_.get());
const bool has_texture_rg = gl_context_->GetVersionInfo()->is_es3 ||
gl_context_->HasExtension("GL_EXT_texture_rg") ||
gl_context_->HasExtension("GL_ARB_texture_rg");
if (has_texture_rg) {
// Used as ResourceProvider::yuv_resource_format_ if
// {ARB,EXT}_texture_rg are available.
formats.push_back(GL_RED);
}
for (int side : sizes) {
ASSERT_GE(fbo_size_.width(), side);
ASSERT_GE(fbo_size_.height(), side);
gfx::Size size(side, side);
GenerateVertexBuffer(size);
for (GLenum format : formats) {
RunUploadAndDrawMultipleTimes(size, format, true); // use glTexSubImage2D
RunUploadAndDrawMultipleTimes(size, format, false); // use glTexImage2D
}
}
}
// Perf test to check if the driver is doing texture renaming.
// This test creates one GL texture_id and four different images. For
// every image it uploads it using texture_id and it draws multiple
// times. The cpu/wall time and the gpu time for all the uploads and
// draws, but before glFinish, is computed and is printed out at the end as
// "upload_and_draw". If the gpu time is >> than the cpu/wall time we expect the
// driver to do texture renaming: this means that while the gpu is drawing using
// texture_id it didn't block cpu side the texture upload using the same
// texture_id.
TEST_F(TextureUploadPerfTest, renaming) {
gfx::Size texture_size(fbo_size_.width() / 2, fbo_size_.height() / 2);
std::vector<uint8> pixels[4];
for (int i = 0; i < 4; ++i) {
GenerateTextureData(texture_size, 4, i + 1, &pixels[i]);
}
ui::ScopedMakeCurrent smc(gl_context_.get(), surface_.get());
GenerateVertexBuffer(texture_size);
gfx::Vector2dF positions[] = {gfx::Vector2dF(0.f, 0.f),
gfx::Vector2dF(1.f, 0.f),
gfx::Vector2dF(0.f, 1.f),
gfx::Vector2dF(1.f, 1.f)};
GLuint texture_id = CreateGLTexture(GL_RGBA, texture_size, true);
MeasurementTimers upload_and_draw_timers(gpu_timing_client_.get());
for (int i = 0; i < 4; ++i) {
UploadTexture(texture_id, texture_size, pixels[i % 4], GL_RGBA, true);
DCHECK_NE(-1, translation_location_);
glUniform2f(translation_location_, positions[i % 4].x(),
positions[i % 4].y());
// Draw the same quad multiple times to make sure that the time spent on the
// gpu is more than the cpu time.
for (int draw = 0; draw < 128; ++draw) {
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
}
upload_and_draw_timers.Record();
MeasurementTimers finish_timers(gpu_timing_client_.get());
glFinish();
CheckNoGlError("glFinish");
finish_timers.Record();
glDeleteTextures(1, &texture_id);
for (int i = 0; i < 4; ++i) {
std::vector<uint8> pixels_rendered(texture_size.GetArea() * 4);
glReadPixels(texture_size.width() * positions[i].x(),
texture_size.height() * positions[i].y(), texture_size.width(),
texture_size.height(), GL_RGBA, GL_UNSIGNED_BYTE,
&pixels_rendered[0]);
CheckNoGlError("glReadPixels");
ASSERT_EQ(pixels[i].size(), pixels_rendered.size());
EXPECT_EQ(pixels[i], pixels_rendered);
}
bool gpu_timer_errors = gpu_timing_client_->IsAvailable() &&
gpu_timing_client_->CheckAndResetTimerErrors();
if (!gpu_timer_errors) {
upload_and_draw_timers.GetAsMeasurement("upload_and_draw")
.PrintResult("renaming");
finish_timers.GetAsMeasurement("finish").PrintResult("renaming");
}
}
} // namespace
} // namespace gpu
| bsd-3-clause |
mtscout6/fluent-nhibernate | src/FluentNHibernate/MappingModel/Output/XmlElementWriter.cs | 1415 | using System.Xml;
using FluentNHibernate.MappingModel.Collections;
using FluentNHibernate.Utils;
using FluentNHibernate.Visitors;
namespace FluentNHibernate.MappingModel.Output
{
public class XmlElementWriter : NullMappingModelVisitor, IXmlWriter<ElementMapping>
{
private readonly IXmlWriterServiceLocator serviceLocator;
private XmlDocument document;
public XmlElementWriter(IXmlWriterServiceLocator serviceLocator)
{
this.serviceLocator = serviceLocator;
}
public XmlDocument Write(ElementMapping mappingModel)
{
document = null;
mappingModel.AcceptVisitor(this);
return document;
}
public override void ProcessElement(ElementMapping mapping)
{
document = new XmlDocument();
var element = document.AddElement("element");
if (mapping.IsSpecified("Type"))
element.WithAtt("type", mapping.Type);
if (mapping.IsSpecified("Formula"))
element.WithAtt("formula", mapping.Formula);
}
public override void Visit(ColumnMapping columnMapping)
{
var writer = serviceLocator.GetWriter<ColumnMapping>();
var xml = writer.Write(columnMapping);
document.ImportAndAppendChild(xml);
}
}
} | bsd-3-clause |
lindenerkan/questioning | vendor/zendframework/zendframework/library/Zend/Code/Reflection/DocBlock/Tag/AuthorTag.php | 1508 | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Reflection\DocBlock\Tag;
class AuthorTag implements TagInterface
{
/**
* @var string
*/
protected $authorName = null;
/**
* @var string
*/
protected $authorEmail = null;
/**
* @return string
*/
public function getName()
{
return 'author';
}
/**
* Initializer
*
* @param string $tagDocblockLine
*/
public function initialize($tagDocblockLine)
{
$match = array();
if (!preg_match('/^([^\<]*)(\<([^\>]*)\>)?(.*)$/u', $tagDocblockLine, $match)) {
return;
}
if ($match[1] !== '') {
$this->authorName = rtrim($match[1]);
}
if (isset($match[3]) && $match[3] !== '') {
$this->authorEmail = $match[3];
}
}
/**
* @return null|string
*/
public function getAuthorName()
{
return $this->authorName;
}
/**
* @return null|string
*/
public function getAuthorEmail()
{
return $this->authorEmail;
}
public function __toString()
{
return 'DocBlock Tag [ * @' . $this->getName() . ' ]' . PHP_EOL;
}
}
| bsd-3-clause |
Baebeca/OutlookPrivacyPlugin | 3rdParty/bccrypto-net-05282015/crypto/src/crypto/digests/Sha256Digest.cs | 8100 | using System;
using Org.BouncyCastle.Crypto.Utilities;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto.Digests
{
/**
* Draft FIPS 180-2 implementation of SHA-256. <b>Note:</b> As this is
* based on a draft this implementation is subject to change.
*
* <pre>
* block word digest
* SHA-1 512 32 160
* SHA-256 512 32 256
* SHA-384 1024 64 384
* SHA-512 1024 64 512
* </pre>
*/
public class Sha256Digest
: GeneralDigest
{
private const int DigestLength = 32;
private uint H1, H2, H3, H4, H5, H6, H7, H8;
private uint[] X = new uint[64];
private int xOff;
public Sha256Digest()
{
initHs();
}
/**
* Copy constructor. This will copy the state of the provided
* message digest.
*/
public Sha256Digest(Sha256Digest t) : base(t)
{
CopyIn(t);
}
private void CopyIn(Sha256Digest t)
{
base.CopyIn(t);
H1 = t.H1;
H2 = t.H2;
H3 = t.H3;
H4 = t.H4;
H5 = t.H5;
H6 = t.H6;
H7 = t.H7;
H8 = t.H8;
Array.Copy(t.X, 0, X, 0, t.X.Length);
xOff = t.xOff;
}
public override string AlgorithmName
{
get { return "SHA-256"; }
}
public override int GetDigestSize()
{
return DigestLength;
}
internal override void ProcessWord(
byte[] input,
int inOff)
{
X[xOff] = Pack.BE_To_UInt32(input, inOff);
if (++xOff == 16)
{
ProcessBlock();
}
}
internal override void ProcessLength(
long bitLength)
{
if (xOff > 14)
{
ProcessBlock();
}
X[14] = (uint)((ulong)bitLength >> 32);
X[15] = (uint)((ulong)bitLength);
}
public override int DoFinal(
byte[] output,
int outOff)
{
Finish();
Pack.UInt32_To_BE((uint)H1, output, outOff);
Pack.UInt32_To_BE((uint)H2, output, outOff + 4);
Pack.UInt32_To_BE((uint)H3, output, outOff + 8);
Pack.UInt32_To_BE((uint)H4, output, outOff + 12);
Pack.UInt32_To_BE((uint)H5, output, outOff + 16);
Pack.UInt32_To_BE((uint)H6, output, outOff + 20);
Pack.UInt32_To_BE((uint)H7, output, outOff + 24);
Pack.UInt32_To_BE((uint)H8, output, outOff + 28);
Reset();
return DigestLength;
}
/**
* reset the chaining variables
*/
public override void Reset()
{
base.Reset();
initHs();
xOff = 0;
Array.Clear(X, 0, X.Length);
}
private void initHs()
{
/* SHA-256 initial hash value
* The first 32 bits of the fractional parts of the square roots
* of the first eight prime numbers
*/
H1 = 0x6a09e667;
H2 = 0xbb67ae85;
H3 = 0x3c6ef372;
H4 = 0xa54ff53a;
H5 = 0x510e527f;
H6 = 0x9b05688c;
H7 = 0x1f83d9ab;
H8 = 0x5be0cd19;
}
internal override void ProcessBlock()
{
//
// expand 16 word block into 64 word blocks.
//
for (int ti = 16; ti <= 63; ti++)
{
X[ti] = Theta1(X[ti - 2]) + X[ti - 7] + Theta0(X[ti - 15]) + X[ti - 16];
}
//
// set up working variables.
//
uint a = H1;
uint b = H2;
uint c = H3;
uint d = H4;
uint e = H5;
uint f = H6;
uint g = H7;
uint h = H8;
int t = 0;
for(int i = 0; i < 8; ++i)
{
// t = 8 * i
h += Sum1Ch(e, f, g) + K[t] + X[t];
d += h;
h += Sum0Maj(a, b, c);
++t;
// t = 8 * i + 1
g += Sum1Ch(d, e, f) + K[t] + X[t];
c += g;
g += Sum0Maj(h, a, b);
++t;
// t = 8 * i + 2
f += Sum1Ch(c, d, e) + K[t] + X[t];
b += f;
f += Sum0Maj(g, h, a);
++t;
// t = 8 * i + 3
e += Sum1Ch(b, c, d) + K[t] + X[t];
a += e;
e += Sum0Maj(f, g, h);
++t;
// t = 8 * i + 4
d += Sum1Ch(a, b, c) + K[t] + X[t];
h += d;
d += Sum0Maj(e, f, g);
++t;
// t = 8 * i + 5
c += Sum1Ch(h, a, b) + K[t] + X[t];
g += c;
c += Sum0Maj(d, e, f);
++t;
// t = 8 * i + 6
b += Sum1Ch(g, h, a) + K[t] + X[t];
f += b;
b += Sum0Maj(c, d, e);
++t;
// t = 8 * i + 7
a += Sum1Ch(f, g, h) + K[t] + X[t];
e += a;
a += Sum0Maj(b, c, d);
++t;
}
H1 += a;
H2 += b;
H3 += c;
H4 += d;
H5 += e;
H6 += f;
H7 += g;
H8 += h;
//
// reset the offset and clean out the word buffer.
//
xOff = 0;
Array.Clear(X, 0, 16);
}
private static uint Sum1Ch(
uint x,
uint y,
uint z)
{
// return Sum1(x) + Ch(x, y, z);
return (((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7)))
+ ((x & y) ^ ((~x) & z));
}
private static uint Sum0Maj(
uint x,
uint y,
uint z)
{
// return Sum0(x) + Maj(x, y, z);
return (((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10)))
+ ((x & y) ^ (x & z) ^ (y & z));
}
// /* SHA-256 functions */
// private static uint Ch(
// uint x,
// uint y,
// uint z)
// {
// return ((x & y) ^ ((~x) & z));
// }
//
// private static uint Maj(
// uint x,
// uint y,
// uint z)
// {
// return ((x & y) ^ (x & z) ^ (y & z));
// }
//
// private static uint Sum0(
// uint x)
// {
// return ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10));
// }
//
// private static uint Sum1(
// uint x)
// {
// return ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7));
// }
private static uint Theta0(
uint x)
{
return ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3);
}
private static uint Theta1(
uint x)
{
return ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10);
}
/* SHA-256 Constants
* (represent the first 32 bits of the fractional parts of the
* cube roots of the first sixty-four prime numbers)
*/
private static readonly uint[] K = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
public override IMemoable Copy()
{
return new Sha256Digest(this);
}
public override void Reset(IMemoable other)
{
Sha256Digest d = (Sha256Digest)other;
CopyIn(d);
}
}
}
| bsd-3-clause |
anhth12/semanticvectors | src/main/java/pitt/search/semanticvectors/utils/StatUtils.java | 796 | package pitt.search.semanticvectors.utils;
import java.util.List;
/**
* Statistical utility functions.
*
* @author dwiddows
*/
public class StatUtils {
/**
* Returns the mean of all the numbers in the list.
*/
public static double getMean(List<Double> numbers) {
double sum = 0;
for (double number : numbers) {
sum += number;
}
return sum / numbers.size();
}
/**
* Returns the variance of all the numbers in the list.
*/
public static double getVariance(List<Double> numbers) {
double mean = getMean(numbers);
double sumSquareDiffs = 0;
for (double number : numbers) {
double diff = number - mean;
sumSquareDiffs += diff * diff;
}
return sumSquareDiffs / numbers.size();
}
}
| bsd-3-clause |
vadimtk/chrome4sdp | chrome/browser/themes/theme_service_factory.cc | 3490 | // 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/themes/theme_service_factory.h"
#include "base/logging.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/profiles/incognito_helpers.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/common/pref_names.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_registry_factory.h"
#if defined(USE_AURA) && defined(USE_X11) && !defined(OS_CHROMEOS)
#include "chrome/browser/themes/theme_service_aurax11.h"
#include "ui/views/linux_ui/linux_ui.h"
#endif
// static
ThemeService* ThemeServiceFactory::GetForProfile(Profile* profile) {
return static_cast<ThemeService*>(
GetInstance()->GetServiceForBrowserContext(profile, true));
}
// static
const extensions::Extension* ThemeServiceFactory::GetThemeForProfile(
Profile* profile) {
std::string id = GetForProfile(profile)->GetThemeID();
if (id == ThemeService::kDefaultThemeID)
return NULL;
return extensions::ExtensionRegistry::Get(
profile)->enabled_extensions().GetByID(id);
}
// static
ThemeServiceFactory* ThemeServiceFactory::GetInstance() {
return Singleton<ThemeServiceFactory>::get();
}
ThemeServiceFactory::ThemeServiceFactory()
: BrowserContextKeyedServiceFactory(
"ThemeService",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(extensions::ExtensionRegistryFactory::GetInstance());
}
ThemeServiceFactory::~ThemeServiceFactory() {}
KeyedService* ThemeServiceFactory::BuildServiceInstanceFor(
content::BrowserContext* profile) const {
ThemeService* provider = NULL;
#if defined(USE_AURA) && defined(USE_X11) && !defined(OS_CHROMEOS)
provider = new ThemeServiceAuraX11;
#else
provider = new ThemeService;
#endif
provider->Init(static_cast<Profile*>(profile));
return provider;
}
void ThemeServiceFactory::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
#if defined(USE_X11) && !defined(OS_CHROMEOS)
bool default_uses_system_theme = false;
#if defined(USE_AURA) && defined(USE_X11) && !defined(OS_CHROMEOS)
const views::LinuxUI* linux_ui = views::LinuxUI::instance();
if (linux_ui)
default_uses_system_theme = linux_ui->GetDefaultUsesSystemTheme();
#endif
registry->RegisterBooleanPref(prefs::kUsesSystemTheme,
default_uses_system_theme);
#endif
registry->RegisterFilePathPref(prefs::kCurrentThemePackFilename,
base::FilePath());
registry->RegisterStringPref(prefs::kCurrentThemeID,
ThemeService::kDefaultThemeID);
registry->RegisterDictionaryPref(prefs::kCurrentThemeImages);
registry->RegisterDictionaryPref(prefs::kCurrentThemeColors);
registry->RegisterDictionaryPref(prefs::kCurrentThemeTints);
registry->RegisterDictionaryPref(prefs::kCurrentThemeDisplayProperties);
}
content::BrowserContext* ThemeServiceFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return chrome::GetBrowserContextRedirectedInIncognito(context);
}
bool ThemeServiceFactory::ServiceIsCreatedWithBrowserContext() const {
return true;
}
| bsd-3-clause |
dednal/chromium.src | tools/gn/pattern.cc | 5935 | // Copyright (c) 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 "tools/gn/pattern.h"
#include "tools/gn/value.h"
namespace {
void ParsePattern(const std::string& s, std::vector<Pattern::Subrange>* out) {
// Set when the last subrange is a literal so we can just append when we
// find another literal.
Pattern::Subrange* last_literal = nullptr;
for (size_t i = 0; i < s.size(); i++) {
if (s[i] == '*') {
// Don't allow two **.
if (out->size() == 0 ||
(*out)[out->size() - 1].type != Pattern::Subrange::ANYTHING)
out->push_back(Pattern::Subrange(Pattern::Subrange::ANYTHING));
last_literal = nullptr;
} else if (s[i] == '\\') {
if (i < s.size() - 1 && s[i + 1] == 'b') {
// "\b" means path boundary.
i++;
out->push_back(Pattern::Subrange(Pattern::Subrange::PATH_BOUNDARY));
last_literal = nullptr;
} else {
// Backslash + anything else means that literal char.
if (!last_literal) {
out->push_back(Pattern::Subrange(Pattern::Subrange::LITERAL));
last_literal = &(*out)[out->size() - 1];
}
if (i < s.size() - 1) {
i++;
last_literal->literal.push_back(s[i]);
} else {
// Single backslash at end, use literal backslash.
last_literal->literal.push_back('\\');
}
}
} else {
if (!last_literal) {
out->push_back(Pattern::Subrange(Pattern::Subrange::LITERAL));
last_literal = &(*out)[out->size() - 1];
}
last_literal->literal.push_back(s[i]);
}
}
}
} // namespace
Pattern::Pattern(const std::string& s) {
ParsePattern(s, &subranges_);
is_suffix_ =
(subranges_.size() == 2 &&
subranges_[0].type == Subrange::ANYTHING &&
subranges_[1].type == Subrange::LITERAL);
}
Pattern::~Pattern() {
}
bool Pattern::MatchesString(const std::string& s) const {
// Empty pattern matches only empty string.
if (subranges_.empty())
return s.empty();
if (is_suffix_) {
const std::string& suffix = subranges_[1].literal;
if (suffix.size() > s.size())
return false; // Too short.
return s.compare(s.size() - suffix.size(), suffix.size(), suffix) == 0;
}
return RecursiveMatch(s, 0, 0, true);
}
// We assume the number of ranges is small so recursive is always reasonable.
// Could be optimized to only be recursive for *.
bool Pattern::RecursiveMatch(const std::string& s,
size_t begin_char,
size_t subrange_index,
bool allow_implicit_path_boundary) const {
if (subrange_index >= subranges_.size()) {
// Hit the end of our subranges, the text should also be at the end for a
// match.
return begin_char == s.size();
}
const Subrange& sr = subranges_[subrange_index];
switch (sr.type) {
case Subrange::LITERAL: {
if (s.size() - begin_char < sr.literal.size())
return false; // Not enough room.
if (s.compare(begin_char, sr.literal.size(), sr.literal) != 0)
return false; // Literal doesn't match.
// Recursively check the next one.
return RecursiveMatch(s, begin_char + sr.literal.size(),
subrange_index + 1, true);
}
case Subrange::PATH_BOUNDARY: {
// When we can accept an implicit path boundary, we have to check both
// a match of the literal and the implicit one.
if (allow_implicit_path_boundary &&
(begin_char == 0 || begin_char == s.size())) {
// At implicit path boundary, see if the rest of the pattern matches.
if (RecursiveMatch(s, begin_char, subrange_index + 1, false))
return true;
}
// Check for a literal "/".
if (begin_char < s.size() && s[begin_char] == '/') {
// At explicit boundary, see if the rest of the pattern matches.
if (RecursiveMatch(s, begin_char + 1, subrange_index + 1, true))
return true;
}
return false;
}
case Subrange::ANYTHING: {
if (subrange_index == subranges_.size() - 1)
return true; // * at the end, consider it matching.
size_t min_next_size = sr.MinSize();
// We don't care about exactly what matched as long as there was a match,
// so we can do this front-to-back. If we needed the match, we would
// normally want "*" to be greedy so would work backwards.
for (size_t i = begin_char; i < s.size() - min_next_size; i++) {
// Note: this could probably be faster by detecting the type of the
// next match in advance and checking for a match in this loop rather
// than doing a full recursive call for each character.
if (RecursiveMatch(s, i, subrange_index + 1, true))
return true;
}
return false;
}
default:
NOTREACHED();
}
return false;
}
PatternList::PatternList() {
}
PatternList::~PatternList() {
}
void PatternList::Append(const Pattern& pattern) {
patterns_.push_back(pattern);
}
void PatternList::SetFromValue(const Value& v, Err* err) {
patterns_.clear();
if (v.type() != Value::LIST) {
*err = Err(v.origin(), "This value must be a list.");
return;
}
const std::vector<Value>& list = v.list_value();
for (size_t i = 0; i < list.size(); i++) {
if (!list[i].VerifyTypeIs(Value::STRING, err))
return;
patterns_.push_back(Pattern(list[i].string_value()));
}
}
bool PatternList::MatchesString(const std::string& s) const {
for (size_t i = 0; i < patterns_.size(); i++) {
if (patterns_[i].MatchesString(s))
return true;
}
return false;
}
bool PatternList::MatchesValue(const Value& v) const {
if (v.type() == Value::STRING)
return MatchesString(v.string_value());
return false;
}
| bsd-3-clause |