code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php function detect() { // Note: I originally found this script at: http://us2.php.net/manual/en/function.get-browser.php // Temporary Variables // The useragent string (lowercase to simplify testing) $_nw_ua = strtolower(@$_SERVER["HTTP_USER_AGENT"]); // Browser Detection { ====================================================== // Version checking, each one of these will take a float value describing the // version number, or - if the user is not using that browser - zero. // Generic code-name "Mozilla" version define("NW_MOZ_VERSION", preg_match('/mozilla\/(\d+\.\d+)/', $_nw_ua, $_nw_v) ? (float)$_nw_v[1] : 0); // KDE's Konqueror define("NW_IS_KONQ", preg_match('/konqueror\/(\d+\.\d+)/', $_nw_ua, $_nw_v) ? (float) $_nw_v[1] : 0); // Opera software Opera define("NW_IS_OPERA", preg_match('/opera[\s\/](\d+\.\d+)/', $_nw_ua, $_nw_v) ? (float) $_nw_v[1] : 0); // Microsoft Internet Explorer define("NW_IS_IE", !NW_IS_OPERA && preg_match('/msie (\d+\.\d+)/', $_nw_ua, $_nw_v) ? (float) $_nw_v[1] : 0); // Gecko-based browsers, such as Mozilla, Netscape 6, DocZilla, // K-Meleon, etc. define("NW_IS_GECKO", preg_match('/gecko\/(\d+)/', $_nw_ua, $_nw_v) ? (float) $_nw_v[1] : 0); // Netscape Navigator (all versions, including Gecko-based browsers) define("NW_IS_NN", NW_IS_GECKO ? (preg_match('/netscape6*\/(\d+.\d+)/', $_nw_ua, $_nw_v) ? (float) $_nw_v[1] : 0) : ((!NW_IS_OPERA && !NW_IS_KONQ && !NW_IS_IE) ? NW_MOZ_VERSION : 0)); // An old 3rd generation web browser define("NW_IS_GEN3", NW_IS_NN < 4 && NW_IS_OPERA < 4 && NW_IS_IE < 4 && NW_MOZ_VERSION < 4); // } Browser Detection ====================================================== // Generic Platform Detection { ============================================= define("NW_IS_LINUX", strstr($_nw_ua, "linux") !== false); define("NW_IS_MAC", strstr($_nw_ua, "mac") !== false); define("NW_IS_SOLARIS", (strstr($_nw_ua, "solaris") !== false) || (strstr($_nw_ua, "sunos") !== false)); define("NW_IS_X11", strstr($_nw_ua, "x11") !== false); define("NW_IS_WINDOWS", strstr($_nw_ua, "win") !== false); define("NW_IS_OS2", strstr($_nw_ua, "os2") !== false); // } Generic Platform Detection ============================================= unset($_nw_ua, $_nw_v); // clean-up } ?>
certik/libmesh
doc/html/detect.php
PHP
lgpl-2.1
2,371
<?php class Provider_Ucloud extends Provider { var $url_prefix = 'https://openapi.ucloud.com/ucloud/oauth/1.0a/'; function __construct($provider,$oauth_config){ parent::__construct($provider,$oauth_config); } function _getRequestTokenURL(){ return $url = $this->url_prefix.'request_token' ; } function _getAccessTokenURL(){ return $url = $this->url_prefix.'access_token' ; } function _getAuthorizeURL(){ return $url = $this->url_prefix.'authorize' ; } function _getAPIUrl($api_name){ $url_prefix = 'https://openapi.ucloud.com/ucloud/api/1.0/'; $url = $url_prefix.'ucloud/basic/getuserinfo.json' ; if($api_name == 'getUserInfo'){ $url = $url_prefix.'ucloud/basic/getuserinfo.json' ; }else if($api_name == 'getContents'){ $url = $url_prefix.'ucloud/basic/getContents.json' ; }else if($api_name == 'createfiletoken'){ $url = $url_prefix.'ucloud/basic/createfiletoken.json' ; }else if($api_name == 'getsyncfolder'){ $url = $url_prefix.'ucloud/basic/getsyncfolder.json' ; }else if($api_name == 'createfile'){ $url = $url_prefix.'ucloud/basic/createfile.json' ; }else if($api_name == 'createfiletoken'){ $url = $url_prefix.'ucloud/basic/createfiletoken.json' ; }else if($api_name == 'deletefile'){ $url = $url_prefix.'ucloud/basic/deletefile.json' ; }else if($api_name == 'createfolder'){ $url = $url_prefix.'ucloud/basic/createfolder.json' ; }else if($api_name == 'deletefolder'){ $url = $url_prefix.'ucloud/basic/deletefolder.json' ; } return $url ; } public function api_call(& $consumer,$api_name,$request_header,$request_body,$method='GET'){ $param = array() ; $url = $this->_getAPIUrl($api_name); get_instance()->load->helper('string'); //$param['oauth_callback'] = $consumer->get('callback_url') ; $param['oauth_consumer_key'] = $consumer->get('api_key') ; // $param['api_token'] = $request_body['api_token'] ; $param['oauth_nonce'] = random_string('alnum', 32); $param['oauth_signature_method'] = $this->getSignatureMethod() ; $param['oauth_timestamp'] = time(); $param['oauth_token'] = $request_header['oauth_token']; $param['oauth_version'] = $this->getOAuthVersion() ; //$param['oauth_verifier'] = $request_header['oauth_verifier']; $base_string = OAuthUtil::base_string($method,$url,$param=array_merge($param,$request_body)) ; $key_arr = array(($consumer->get('secret_key')),($request_header['oauth_token_secret'])) ; $key = OAuthUtil::urlencode($key_arr) ; $key = implode('&',$key_arr) ; $param['oauth_signature'] = OAuthUtil::make_signature($base_string,$key) ; $response = OAuthUtil::call($url,$method,$param,$request_body) ; //$response = OAuthUtil::parse_param($response) ; return $response ; } public function getRequestToken(& $consumer,$params,$method='GET'){ $param = array() ; $url = $this->_getRequestTokenURL(); get_instance()->load->helper('string'); $param['oauth_callback'] = $consumer->get('callback_url') ; $param['oauth_consumer_key'] = $consumer->get('api_key') ; $param['oauth_nonce'] = random_string('alnum', 32); $param['oauth_signature_method'] = $this->getSignatureMethod() ; $param['oauth_timestamp'] = time(); $param['oauth_version'] = $this->getOAuthVersion() ; $base_string = OAuthUtil::base_string($method,$url,$param ) ; $key_arr = array($consumer->get('secret_key'),'' ) ; $key = OAuthUtil::urlencode($key_arr) ; $key = implode('&',$key) ; $param['oauth_signature'] = OAuthUtil::make_signature($base_string,$key) ; $response = OAuthUtil::call($url,$method,$param) ; return OAuthUtil::parse_param($response) ; } public function getAccessToken(& $consumer,$params=array(),$method='GET'){ $param = array() ; $url = $this->_getAccessTokenURL(); get_instance()->load->helper('string'); $param['oauth_callback'] = $consumer->get('callback_url') ; $param['oauth_consumer_key'] = $consumer->get('api_key') ; $param['oauth_nonce'] = random_string('alnum', 32); $param['oauth_signature_method'] = $this->getSignatureMethod() ; $param['oauth_timestamp'] = time(); $param['oauth_token'] = $params['oauth_token']; $param['oauth_version'] = $this->getOAuthVersion() ; $param['oauth_verifier'] = $params['oauth_verifier']; $base_string = OAuthUtil::base_string($method,$url,$param ) ; $key_arr = array($consumer->get('secret_key'),$params['oauth_token_secret'] ) ; $key = OAuthUtil::urlencode($key_arr) ; $key = implode('&',$key) ; $param['oauth_signature'] = OAuthUtil::make_signature($base_string,$key) ; $response = OAuthUtil::call($url,$method,$param) ; $response = OAuthUtil::parse_param($response) ; $response['api_token'] = $this->getAPIToken($consumer->get('api_key'),$consumer->get('secret_key')) ; return $response ; } public function getAPIToken($api_key,$secret_key){ $ts = time() ; $base_string = $api_key.';'.$ts ; $signature=base64_encode(hash_hmac('sha1', $base_string, $secret_key, TRUE)); return OAuthUtil::urlencode(base64_encode($api_key.';'.$ts.';'.$signature)); } public function authorize($param){ get_instance()->load->helper('url') ; redirect($this->_getAuthorizeUrl().'?oauth_token='.$param['oauth_token']) ; } } /* end of Provider_Ucloud.php */
saegeul/saegeul
application/libraries/oauth/provider/Provider_Ucloud.php
PHP
lgpl-2.1
5,256
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtDeclarative module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "private/qpacketprotocol_p.h" #include <QBuffer> #include <QElapsedTimer> QT_BEGIN_NAMESPACE #define MAX_PACKET_SIZE 0x7FFFFFFF /*! \class QPacketProtocol \internal \brief The QPacketProtocol class encapsulates communicating discrete packets across fragmented IO channels, such as TCP sockets. QPacketProtocol makes it simple to send arbitrary sized data "packets" across fragmented transports such as TCP and UDP. As transmission boundaries are not respected, sending packets over protocols like TCP frequently involves "stitching" them back together at the receiver. QPacketProtocol makes this easier by performing this task for you. Packet data sent using QPacketProtocol is prepended with a 4-byte size header allowing the receiving QPacketProtocol to buffer the packet internally until it has all been received. QPacketProtocol does not perform any sanity checking on the size or on the data, so this class should only be used in prototyping or trusted situations where DOS attacks are unlikely. QPacketProtocol does not perform any communications itself. Instead it can operate on any QIODevice that supports the QIODevice::readyRead() signal. A logical "packet" is encapsulated by the companion QPacket class. The following example shows two ways to send data using QPacketProtocol. The transmitted data is equivalent in both. \code QTcpSocket socket; // ... connect socket ... QPacketProtocol protocol(&socket); // Send packet the quick way protocol.send() << "Hello world" << 123; // Send packet the longer way QPacket packet; packet << "Hello world" << 123; protocol.send(packet); \endcode Likewise, the following shows how to read data from QPacketProtocol, assuming that the QPacketProtocol::readyRead() signal has been emitted. \code // ... QPacketProtocol::readyRead() is emitted ... int a; QByteArray b; // Receive packet the quick way protocol.read() >> a >> b; // Receive packet the longer way QPacket packet = protocol.read(); p >> a >> b; \endcode \ingroup io \sa QPacket */ class QPacketProtocolPrivate : public QObject { Q_OBJECT public: QPacketProtocolPrivate(QPacketProtocol * parent, QIODevice * _dev) : QObject(parent), inProgressSize(-1), maxPacketSize(MAX_PACKET_SIZE), waitingForPacket(false), dev(_dev) { Q_ASSERT(4 == sizeof(qint32)); QObject::connect(this, SIGNAL(readyRead()), parent, SIGNAL(readyRead())); QObject::connect(this, SIGNAL(packetWritten()), parent, SIGNAL(packetWritten())); QObject::connect(this, SIGNAL(invalidPacket()), parent, SIGNAL(invalidPacket())); QObject::connect(dev, SIGNAL(readyRead()), this, SLOT(readyToRead())); QObject::connect(dev, SIGNAL(aboutToClose()), this, SLOT(aboutToClose())); QObject::connect(dev, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWritten(qint64))); } Q_SIGNALS: void readyRead(); void packetWritten(); void invalidPacket(); public Q_SLOTS: void aboutToClose() { inProgress.clear(); sendingPackets.clear(); inProgressSize = -1; } void bytesWritten(qint64 bytes) { Q_ASSERT(!sendingPackets.isEmpty()); while(bytes) { if(sendingPackets.at(0) > bytes) { sendingPackets[0] -= bytes; bytes = 0; } else { bytes -= sendingPackets.at(0); sendingPackets.removeFirst(); emit packetWritten(); } } } void readyToRead() { bool gotPackets = false; while (true) { // Get size header (if not in progress) if (-1 == inProgressSize) { // We need a size header of sizeof(qint32) if (sizeof(qint32) > (uint)dev->bytesAvailable()) { if (gotPackets) emit readyRead(); return; // no more data available } // Read size header int read = dev->read((char *)&inProgressSize, sizeof(qint32)); Q_ASSERT(read == sizeof(qint32)); Q_UNUSED(read); // Check sizing constraints if (inProgressSize > maxPacketSize) { QObject::disconnect(dev, SIGNAL(readyRead()), this, SLOT(readyToRead())); QObject::disconnect(dev, SIGNAL(aboutToClose()), this, SLOT(aboutToClose())); QObject::disconnect(dev, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWritten(qint64))); dev = 0; emit invalidPacket(); return; } inProgressSize -= sizeof(qint32); } else { inProgress.append(dev->read(inProgressSize - inProgress.size())); if (inProgressSize == inProgress.size()) { // Packet has arrived! packets.append(inProgress); inProgressSize = -1; inProgress.clear(); waitingForPacket = false; gotPackets = true; } else { if (gotPackets) emit readyRead(); return; // packet in progress is not yet complete } } } } public: QList<qint64> sendingPackets; QList<QByteArray> packets; QByteArray inProgress; qint32 inProgressSize; qint32 maxPacketSize; bool waitingForPacket; QIODevice * dev; }; /*! Construct a QPacketProtocol instance that works on \a dev with the specified \a parent. */ QPacketProtocol::QPacketProtocol(QIODevice * dev, QObject * parent) : QObject(parent), d(new QPacketProtocolPrivate(this, dev)) { Q_ASSERT(dev); } /*! Destroys the QPacketProtocol instance. */ QPacketProtocol::~QPacketProtocol() { } /*! Returns the maximum packet size allowed. By default this is 2,147,483,647 bytes. If a packet claiming to be larger than the maximum packet size is received, the QPacketProtocol::invalidPacket() signal is emitted. \sa QPacketProtocol::setMaximumPacketSize() */ qint32 QPacketProtocol::maximumPacketSize() const { return d->maxPacketSize; } /*! Sets the maximum allowable packet size to \a max. \sa QPacketProtocol::maximumPacketSize() */ qint32 QPacketProtocol::setMaximumPacketSize(qint32 max) { if(max > (signed)sizeof(qint32)) d->maxPacketSize = max; return d->maxPacketSize; } /*! Returns a streamable object that is transmitted on destruction. For example \code protocol.send() << "Hello world" << 123; \endcode will send a packet containing "Hello world" and 123. To construct more complex packets, explicitly construct a QPacket instance. */ QPacketAutoSend QPacketProtocol::send() { return QPacketAutoSend(this); } /*! \fn void QPacketProtocol::send(const QPacket & packet) Transmit the \a packet. */ void QPacketProtocol::send(const QPacket & p) { if(p.b.isEmpty()) return; // We don't send empty packets qint64 sendSize = p.b.size() + sizeof(qint32); d->sendingPackets.append(sendSize); qint32 sendSize32 = sendSize; qint64 writeBytes = d->dev->write((char *)&sendSize32, sizeof(qint32)); Q_ASSERT(writeBytes == sizeof(qint32)); writeBytes = d->dev->write(p.b); Q_ASSERT(writeBytes == p.b.size()); Q_UNUSED(writeBytes); } /*! Returns the number of received packets yet to be read. */ qint64 QPacketProtocol::packetsAvailable() const { return d->packets.count(); } /*! Discard any unread packets. */ void QPacketProtocol::clear() { d->packets.clear(); } /*! Return the next unread packet, or an invalid QPacket instance if no packets are available. This method does NOT block. */ QPacket QPacketProtocol::read() { if(0 == d->packets.count()) return QPacket(); QPacket rv(d->packets.at(0)); d->packets.removeFirst(); return rv; } /* Returns the difference between msecs and elapsed. If msecs is -1, however, -1 is returned. */ static int qt_timeout_value(int msecs, int elapsed) { if (msecs == -1) return -1; int timeout = msecs - elapsed; return timeout < 0 ? 0 : timeout; } /*! This function locks until a new packet is available for reading and the \l{QIODevice::}{readyRead()} signal has been emitted. The function will timeout after \a msecs milliseconds; the default timeout is 30000 milliseconds. The function returns true if the readyRead() signal is emitted and there is new data available for reading; otherwise it returns false (if an error occurred or the operation timed out). */ bool QPacketProtocol::waitForReadyRead(int msecs) { if (!d->packets.isEmpty()) return true; QElapsedTimer stopWatch; stopWatch.start(); d->waitingForPacket = true; do { if (!d->dev->waitForReadyRead(msecs)) return false; if (!d->waitingForPacket) return true; msecs = qt_timeout_value(msecs, stopWatch.elapsed()); } while (true); } /*! Return the QIODevice passed to the QPacketProtocol constructor. */ QIODevice * QPacketProtocol::device() { return d->dev; } /*! \fn void QPacketProtocol::readyRead() Emitted whenever a new packet is received. Applications may use QPacketProtocol::read() to retrieve this packet. */ /*! \fn void QPacketProtocol::invalidPacket() A packet larger than the maximum allowable packet size was received. The packet will be discarded and, as it indicates corruption in the protocol, no further packets will be received. */ /*! \fn void QPacketProtocol::packetWritten() Emitted each time a packet is completing written to the device. This signal may be used for communications flow control. */ /*! \class QPacket \internal \brief The QPacket class encapsulates an unfragmentable packet of data to be transmitted by QPacketProtocol. The QPacket class works together with QPacketProtocol to make it simple to send arbitrary sized data "packets" across fragmented transports such as TCP and UDP. QPacket provides a QDataStream interface to an unfragmentable packet. Applications should construct a QPacket, propagate it with data and then transmit it over a QPacketProtocol instance. For example: \code QPacketProtocol protocol(...); QPacket myPacket; myPacket << "Hello world!" << 123; protocol.send(myPacket); \endcode As long as both ends of the connection are using the QPacketProtocol class, the data within this packet will be delivered unfragmented at the other end, ready for extraction. \code QByteArray greeting; int count; QPacket myPacket = protocol.read(); myPacket >> greeting >> count; \endcode Only packets returned from QPacketProtocol::read() may be read from. QPacket instances constructed by directly by applications are for transmission only and are considered "write only". Attempting to read data from them will result in undefined behavior. \ingroup io \sa QPacketProtocol */ /*! Constructs an empty write-only packet. */ QPacket::QPacket() : QDataStream(), buf(0) { buf = new QBuffer(&b); buf->open(QIODevice::WriteOnly); setDevice(buf); setVersion(QDataStream::Qt_4_7); } /*! Destroys the QPacket instance. */ QPacket::~QPacket() { if(buf) { delete buf; buf = 0; } } /*! Creates a copy of \a other. The initial stream positions are shared, but the two packets are otherwise independent. */ QPacket::QPacket(const QPacket & other) : QDataStream(), b(other.b), buf(0) { buf = new QBuffer(&b); buf->open(other.buf->openMode()); setDevice(buf); } /*! \internal */ QPacket::QPacket(const QByteArray & ba) : QDataStream(), b(ba), buf(0) { buf = new QBuffer(&b); buf->open(QIODevice::ReadOnly); setDevice(buf); } /*! Returns true if this packet is empty - that is, contains no data. */ bool QPacket::isEmpty() const { return b.isEmpty(); } /*! Returns raw packet data. */ QByteArray QPacket::data() const { return b; } /*! Clears data in the packet. This is useful for reusing one writable packet. For example \code QPacketProtocol protocol(...); QPacket packet; packet << "Hello world!" << 123; protocol.send(packet); packet.clear(); packet << "Goodbyte world!" << 789; protocol.send(packet); \endcode */ void QPacket::clear() { QBuffer::OpenMode oldMode = buf->openMode(); buf->close(); b.clear(); buf->setBuffer(&b); // reset QBuffer internals with new size of b. buf->open(oldMode); } /*! \class QPacketAutoSend \internal \internal */ QPacketAutoSend::QPacketAutoSend(QPacketProtocol * _p) : QPacket(), p(_p) { } QPacketAutoSend::~QPacketAutoSend() { if(!b.isEmpty()) p->send(*this); } QT_END_NAMESPACE #include <qpacketprotocol.moc>
kobolabs/qtquick1
src/declarative/debugger/qpacketprotocol.cpp
C++
lgpl-2.1
15,319
package com.digitalcraftinghabitat.forgemod.util; import org.apache.logging.log4j.Level; import cpw.mods.fml.relauncher.FMLRelaunchLog; /** * Created by christopher on 02/08/15. */ public class DCHLog { public static final FMLRelaunchLog INSTANCE = FMLRelaunchLog.log; private DCHLog(){ } public static void warning( String format, Object... data ) { log( Level.WARN, format, data ); } private static void log( Level level, String format, Object... data ) { FMLRelaunchLog.log( "DCH:", level, format, data ); } public static void error( Throwable e ) { severe( "Error: " + e.getClass().getName() + " : " + e.getMessage() ); e.printStackTrace(); } public static void severe( String format, Object... data ) { log( Level.ERROR, format, data ); } public static void blockUpdate( int xCoord, int yCoord, int zCoord, String title) { info( title + " @ " + xCoord + ", " + yCoord + ", " + zCoord ); } public static void info( String format, Object... data ) { log( Level.INFO, format, data ); } public static void crafting( String format, Object... data ) { log( Level.INFO, format, data ); } }
digital-crafting-habitat/dch_forge_mod
src/main/java/com/digitalcraftinghabitat/forgemod/util/DCHLog.java
Java
lgpl-2.1
1,264
<?php // (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id: pagination.php 39469 2012-01-12 21:13:48Z changi67 $ function prefs_pagination_list() { return array( 'pagination_firstlast' => array( 'name' => tra("Display 'First' and 'Last' links"), 'type' => 'flag', 'default' => 'y', ), 'pagination_fastmove_links' => array( 'name' => tra('Display fast move links (by 10 percent of the total number of pages) '), 'type' => 'flag', 'default' => 'y', ), 'pagination_hide_if_one_page' => array( 'name' => tra('Hide pagination when there is only one page'), 'type' => 'flag', 'default' => 'y', ), 'pagination_icons' => array( 'name' => tra('Use Icons'), 'type' => 'flag', 'default' => 'y', ), ); }
railfuture/tiki-website
lib/prefs/pagination.php
PHP
lgpl-2.1
955
/* -*- mode: C++ ; c-file-style: "stroustrup" -*- ***************************** * Qwt Widget Library * Copyright (C) 1997 Josef Wilgen * Copyright (C) 2002 Uwe Rathmann * * This library is free software; you can redistribute it and/or * modify it under the terms of the Qwt License, Version 1.0 *****************************************************************************/ #include "qwt_spline.h" #include "qwt_spline_parametrization.h" #include "qwt_math.h" #include <qstack.h> namespace QwtSplineBezier { class BezierData { public: inline BezierData() { // default constructor with unitialized points } inline BezierData( const QPointF &p1, const QPointF &cp1, const QPointF &cp2, const QPointF &p2 ): d_x1( p1.x() ), d_y1( p1.y() ), d_cx1( cp1.x() ), d_cy1( cp1.y() ), d_cx2( cp2.x() ), d_cy2( cp2.y() ), d_x2( p2.x() ), d_y2( p2.y() ) { } inline double flatness() const { // algo by Roger Willcocks ( http://www.rops.org ) const double ux = 3.0 * d_cx1 - 2.0 * d_x1 - d_x2; const double uy = 3.0 * d_cy1 - 2.0 * d_y1 - d_y2; const double vx = 3.0 * d_cx2 - 2.0 * d_x2 - d_x1; const double vy = 3.0 * d_cy2 - 2.0 * d_y2 - d_y1; const double ux2 = ux * ux; const double uy2 = uy * uy; const double vx2 = vx * vx; const double vy2 = vy * vy; return qMax( ux2, vx2 ) + qMax( uy2, vy2 ); } inline BezierData subdivided() { BezierData bz; const double c1 = midValue( d_cx1, d_cx2 ); bz.d_cx1 = midValue( d_x1, d_cx1 ); d_cx2 = midValue( d_cx2, d_x2 ); bz.d_x1 = d_x1; bz.d_cx2 = midValue( bz.d_cx1, c1 ); d_cx1 = midValue( c1, d_cx2 ); bz.d_x2 = d_x1 = midValue( bz.d_cx2, d_cx1 ); const double c2 = midValue( d_cy1, d_cy2 ); bz.d_cy1 = midValue( d_y1, d_cy1 ); d_cy2 = midValue( d_cy2, d_y2 ); bz.d_y1 = d_y1; bz.d_cy2 = midValue( bz.d_cy1, c2 ); d_cy1 = midValue( d_cy2, c2 ); bz.d_y2 = d_y1 = midValue( bz.d_cy2, d_cy1 ); return bz; } inline QPointF p2() const { return QPointF( d_x2, d_y2 ); } private: inline double midValue( double v1, double v2 ) { return 0.5 * ( v1 + v2 ); } double d_x1, d_y1; double d_cx1, d_cy1; double d_cx2, d_cy2; double d_x2, d_y2; }; inline double minFlatness( double tolerance ) { // according to QwtSplineBezier::flatness return 16 * ( tolerance * tolerance ); } inline void toPolygon( double minFlatness, const QPointF &p1, const QPointF &cp1, const QPointF &cp2, const QPointF &p2, QPolygonF &polygon ) { polygon += p1; // to avoid deep stacks we convert the recursive algo // to something iterative, where the parameters of the // recursive calss are pushed to bezierStack instead QStack<BezierData> bezierStack; bezierStack.push( BezierData( p1, cp1, cp2, p2 ) ); while( true ) { BezierData &bz = bezierStack.top(); if ( bz.flatness() < minFlatness ) { if ( bezierStack.size() == 1 ) return; polygon += bz.p2(); bezierStack.pop(); } else { bezierStack.push( bz.subdivided() ); } } } inline QPointF pointAt( const QPointF &p1, const QPointF &cp1, const QPointF &cp2, const QPointF &p2, double t ) { const double d1 = 3.0 * t; const double d2 = 3.0 * t * t; const double d3 = t * t * t; const double s = 1.0 - t; const double x = (( s * p1.x() + d1 * cp1.x() ) * s + d2 * cp2.x() ) * s + d3 * p2.x(); const double y = (( s * p1.y() + d1 * cp1.y() ) * s + d2 * cp2.y() ) * s + d3 * p2.y(); return QPointF( x, y ); } } namespace QwtSplineC1P { struct param { param( const QwtSplineParametrization *p ): parameter( p ) { } inline double operator()( const QPointF &p1, const QPointF &p2 ) const { return parameter->valueIncrement( p1, p2 ); } const QwtSplineParametrization *parameter; }; struct paramY { inline double operator()( const QPointF &p1, const QPointF &p2 ) const { return QwtSplineParametrization::valueIncrementY( p1, p2 ); } }; struct paramUniform { inline double operator()( const QPointF &p1, const QPointF &p2 ) const { return QwtSplineParametrization::valueIncrementUniform( p1, p2 ); } }; struct paramCentripetal { inline double operator()( const QPointF &p1, const QPointF &p2 ) const { return QwtSplineParametrization::valueIncrementCentripetal( p1, p2 ); } }; struct paramChordal { inline double operator()( const QPointF &p1, const QPointF &p2 ) const { return QwtSplineParametrization::valueIncrementChordal( p1, p2 ); } }; struct paramManhattan { inline double operator()( const QPointF &p1, const QPointF &p2 ) const { return QwtSplineParametrization::valueIncrementManhattan( p1, p2 ); } }; class PathStore { public: inline void init( int size ) { Q_UNUSED(size); } inline void start( double x1, double y1 ) { path.moveTo( x1, y1 ); } inline void addCubic( double cx1, double cy1, double cx2, double cy2, double x2, double y2 ) { path.cubicTo( cx1, cy1, cx2, cy2, x2, y2 ); } inline void end() { path.closeSubpath(); } QPainterPath path; }; class ControlPointsStore { public: inline ControlPointsStore(): d_cp( NULL ) { } inline void init( int size ) { controlPoints.resize( size ); d_cp = controlPoints.data(); } inline void start( double x1, double y1 ) { Q_UNUSED( x1 ); Q_UNUSED( y1 ); } inline void addCubic( double cx1, double cy1, double cx2, double cy2, double x2, double y2 ) { Q_UNUSED( x2 ); Q_UNUSED( y2 ); QLineF &l = *d_cp++; l.setLine( cx1, cy1, cx2, cy2 ); } inline void end() { } QVector<QLineF> controlPoints; private: QLineF* d_cp; }; double slopeBoundary( int boundaryCondition, double boundaryValue, const QPointF &p1, const QPointF &p2, double slope1 ) { const double dx = p2.x() - p1.x(); const double dy = p2.y() - p1.y(); double m = 0.0; switch( boundaryCondition ) { case QwtSpline::Clamped1: { m = boundaryValue; break; } case QwtSpline::Clamped2: { const double c2 = 0.5 * boundaryValue; const double c1 = slope1; m = 0.5 * ( 3.0 * dy / dx - c1 - c2 * dx ); break; } case QwtSpline::Clamped3: { const double c3 = boundaryValue / 6.0; m = c3 * dx * dx + 2 * dy / dx - slope1; break; } case QwtSpline::LinearRunout: { const double s = dy / dx; const double r = qBound( 0.0, boundaryValue, 1.0 ); m = s - r * ( s - slope1 ); break; } default: { m = dy / dx; // something } } return m; } } template< class SplineStore > static inline SplineStore qwtSplineC1PathParamX( const QwtSplineC1 *spline, const QPolygonF &points ) { const int n = points.size(); const QVector<double> m = spline->slopes( points ); if ( m.size() != n ) return SplineStore(); const QPointF *pd = points.constData(); const double *md = m.constData(); SplineStore store; store.init( m.size() - 1 ); store.start( pd[0].x(), pd[0].y() ); for ( int i = 0; i < n - 1; i++ ) { const double dx3 = ( pd[i+1].x() - pd[i].x() ) / 3.0; store.addCubic( pd[i].x() + dx3, pd[i].y() + md[i] * dx3, pd[i+1].x() - dx3, pd[i+1].y() - md[i+1] * dx3, pd[i+1].x(), pd[i+1].y() ); } return store; } template< class SplineStore > static inline SplineStore qwtSplineC1PathParamY( const QwtSplineC1 *spline, const QPolygonF &points ) { const int n = points.size(); QPolygonF pointsFlipped( n ); for ( int i = 0; i < n; i++ ) { pointsFlipped[i].setX( points[i].y() ); pointsFlipped[i].setY( points[i].x() ); } const QVector<double> m = spline->slopes( pointsFlipped ); if ( m.size() != n ) return SplineStore(); const QPointF *pd = pointsFlipped.constData(); const double *md = m.constData(); SplineStore store; store.init( m.size() - 1 ); store.start( pd[0].y(), pd[0].x() ); QVector<QLineF> lines( n ); for ( int i = 0; i < n - 1; i++ ) { const double dx3 = ( pd[i+1].x() - pd[i].x() ) / 3.0; store.addCubic( pd[i].y() + md[i] * dx3, pd[i].x() + dx3, pd[i+1].y() - md[i+1] * dx3, pd[i+1].x() - dx3, pd[i+1].y(), pd[i+1].x() ); } return store; } template< class SplineStore, class Param > static inline SplineStore qwtSplineC1PathParametric( const QwtSplineC1 *spline, const QPolygonF &points, Param param ) { const bool isClosing = ( spline->boundaryType() == QwtSplineApproximation::ClosedPolygon ); const int n = points.size(); QPolygonF pointsX, pointsY; pointsX.resize( isClosing ? n + 1 : n ); pointsY.resize( isClosing ? n + 1 : n ); QPointF *px = pointsX.data(); QPointF *py = pointsY.data(); const QPointF *p = points.constData(); double t = 0.0; px[0].rx() = py[0].rx() = t; px[0].ry() = p[0].x(); py[0].ry() = p[0].y(); int numParamPoints = 1; for ( int i = 1; i < n; i++ ) { const double td = param( points[i-1], points[i] ); if ( td > 0.0 ) { t += td; px[numParamPoints].rx() = py[numParamPoints].rx() = t; px[numParamPoints].ry() = p[i].x(); py[numParamPoints].ry() = p[i].y(); numParamPoints++; } } if ( isClosing ) { const double td = param( points[n-1], points[0] ); if ( td > 0.0 ) { t += td; px[numParamPoints].rx() = py[numParamPoints].rx() = t; px[numParamPoints].ry() = p[0].x(); py[numParamPoints].ry() = p[0].y(); numParamPoints++; } } if ( pointsX.size() != numParamPoints ) { pointsX.resize( numParamPoints ); pointsY.resize( numParamPoints ); } const QVector<double> slopesX = spline->slopes( pointsX ); const QVector<double> slopesY = spline->slopes( pointsY ); const double *mx = slopesX.constData(); const double *my = slopesY.constData(); // we don't need it anymore pointsX.clear(); pointsY.clear(); SplineStore store; store.init( isClosing ? n : n - 1 ); store.start( points[0].x(), points[0].y() ); int j = 0; for ( int i = 0; i < n - 1; i++ ) { const QPointF &p1 = p[i]; const QPointF &p2 = p[i+1]; const double td = param( p1, p2 ); if ( td != 0.0 ) { const double t3 = td / 3.0; const double cx1 = p1.x() + mx[j] * t3; const double cy1 = p1.y() + my[j] * t3; const double cx2 = p2.x() - mx[j+1] * t3; const double cy2 = p2.y() - my[j+1] * t3; store.addCubic( cx1, cy1, cx2, cy2, p2.x(), p2.y() ); j++; } else { // setting control points to the ends store.addCubic( p1.x(), p1.y(), p2.x(), p2.y(), p2.x(), p2.y() ); } } if ( isClosing ) { const QPointF &p1 = p[n-1]; const QPointF &p2 = p[0]; const double td = param( p1, p2 ); if ( td != 0.0 ) { const double t3 = td / 3.0; const double cx1 = p1.x() + mx[j] * t3; const double cy1 = p1.y() + my[j] * t3; const double cx2 = p2.x() - mx[0] * t3; const double cy2 = p2.y() - my[0] * t3; store.addCubic( cx1, cy1, cx2, cy2, p2.x(), p2.y() ); } else { store.addCubic( p1.x(), p1.y(), p2.x(), p2.y(), p2.x(), p2.y() ); } store.end(); } return store; } template< QwtSplinePolynomial toPolynomial( const QPointF &, double, const QPointF &, double ) > static QPolygonF qwtPolygonParametric( double distance, const QPolygonF &points, const QVector<double> values, bool withNodes ) { QPolygonF fittedPoints; const QPointF *p = points.constData(); const double *v = values.constData(); fittedPoints += p[0]; double t = distance; const int n = points.size(); for ( int i = 0; i < n - 1; i++ ) { const QPointF &p1 = p[i]; const QPointF &p2 = p[i+1]; const QwtSplinePolynomial polynomial = toPolynomial( p1, v[i], p2, v[i+1] ); const double l = p2.x() - p1.x(); while ( t < l ) { fittedPoints += QPointF( p1.x() + t, p1.y() + polynomial.valueAt( t ) ); t += distance; } if ( withNodes ) { if ( qFuzzyCompare( fittedPoints.last().x(), p2.x() ) ) fittedPoints.last() = p2; else fittedPoints += p2; } else { t -= l; } } return fittedPoints; } class QwtSpline::PrivateData { public: PrivateData() { // parabolic runout at both ends boundaryConditions[0].type = QwtSpline::Clamped3; boundaryConditions[0].value = 0.0; boundaryConditions[1].type = QwtSpline::Clamped3; boundaryConditions[1].value = 0.0; } struct { int type; double value; } boundaryConditions[2]; }; /*! \brief Constructor The default setting is a non closing spline with chordal parametrization \sa setParametrization(), setClosing() */ QwtSpline::QwtSpline() { d_data = new PrivateData; } //! Destructor QwtSpline::~QwtSpline() { delete d_data; } void QwtSpline::setBoundaryCondition( BoundaryPosition position, int condition ) { if ( ( position == QwtSpline::AtBeginning ) || ( position == QwtSpline::AtEnd ) ) d_data->boundaryConditions[position].type = condition; } int QwtSpline::boundaryCondition( BoundaryPosition position ) const { if ( ( position == QwtSpline::AtBeginning ) || ( position == QwtSpline::AtEnd ) ) return d_data->boundaryConditions[position].type; return d_data->boundaryConditions[0].type; // should never happen } void QwtSpline::setBoundaryValue( BoundaryPosition position, double value ) { if ( ( position == QwtSpline::AtBeginning ) || ( position == QwtSpline::AtEnd ) ) d_data->boundaryConditions[position].value = value; } double QwtSpline::boundaryValue( BoundaryPosition position ) const { if ( ( position == QwtSpline::AtBeginning ) || ( position == QwtSpline::AtEnd ) ) return d_data->boundaryConditions[position].value; return d_data->boundaryConditions[0].value; // should never happen } void QwtSpline::setBoundaryConditions( int condition, double valueBegin, double valueEnd ) { setBoundaryCondition( QwtSpline::AtBeginning, condition ); setBoundaryValue( QwtSpline::AtBeginning, valueBegin ); setBoundaryCondition( QwtSpline::AtEnd, condition ); setBoundaryValue( QwtSpline::AtEnd, valueEnd ); } /*! \fn QVector<QLineF> bezierControlLines( const QPolygonF &points ) const \brief Interpolate a curve with Bezier curves Interpolates a polygon piecewise with cubic Bezier curves and returns the 2 control points of each curve as QLineF. \param points Control points \return Control points of the interpolating Bezier curves */ /*! \brief Interpolate a curve with Bezier curves Interpolates a polygon piecewise with cubic Bezier curves and returns them as QPainterPath. The implementation calculates the Bezier control lines first and converts them into painter path elements in an additional loop. \param points Control points \return Painter path, that can be rendered by QPainter \note Derived spline classes might overload painterPath() to avoid the extra loops for converting results into a QPainterPath \sa bezierControlLines() */ QPainterPath QwtSpline::painterPath( const QPolygonF &points ) const { const int n = points.size(); QPainterPath path; if ( n == 0 ) return path; if ( n == 1 ) { path.moveTo( points[0] ); return path; } if ( n == 2 ) { path.addPolygon( points ); return path; } const QVector<QLineF> controlLines = bezierControlLines( points ); if ( controlLines.size() < n - 1 ) return path; const QPointF *p = points.constData(); const QLineF *l = controlLines.constData(); path.moveTo( p[0] ); for ( int i = 0; i < n - 1; i++ ) path.cubicTo( l[i].p1(), l[i].p2(), p[i+1] ); if ( ( boundaryType() == QwtSplineApproximation::ClosedPolygon ) && ( controlLines.size() >= n ) ) { path.cubicTo( l[n-1].p1(), l[n-1].p2(), p[0] ); path.closeSubpath(); } return path; } QPolygonF QwtSpline::polygon( const QPolygonF &points, double tolerance ) { if ( tolerance <= 0.0 ) return QPolygonF(); const QVector<QLineF> controlLines = bezierControlLines( points ); if ( controlLines.isEmpty() ) return QPolygonF(); const bool isClosed = boundaryType() == QwtSplineApproximation::ClosedPolygon; // we can make checking the tolerance criterion check in the subdivison loop // cheaper, by translating it into some flatness value. const double minFlatness = QwtSplineBezier::minFlatness( tolerance ); const QPointF *p = points.constData(); const QLineF *cl = controlLines.constData(); const int n = controlLines.size(); QPolygonF path; for ( int i = 0; i < n - 1; i++ ) { const QLineF &l = cl[i]; QwtSplineBezier::toPolygon( minFlatness, p[i], l.p1(), l.p2(), p[i+1], path ); } const QPointF &pn = isClosed ? p[0] : p[n]; const QLineF &l = cl[n-1]; QwtSplineBezier::toPolygon( minFlatness, p[n-1], l.p1(), l.p2(), pn, path ); path += pn; return path; } /*! \brief Find an interpolated polygon with "equidistant" points When withNodes is disabled all points of the resulting polygon will be equidistant according to the parametrization. When withNodes is enabled the resulting polygon will also include the control points and the interpolated points are always aligned to the control point before ( points[i] + i * distance ). The implementation calculates bezier curves first and calculates the interpolated points in a second run. \param points Control nodes of the spline \param distance Distance between 2 points according to the parametrization \param withNodes When true, also add the control nodes ( even if not being equidistant ) \sa bezierControlLines() */ QPolygonF QwtSpline::equidistantPolygon( const QPolygonF &points, double distance, bool withNodes ) const { if ( distance <= 0.0 ) return QPolygonF(); const int n = points.size(); if ( n <= 1 ) return points; if ( n == 2 ) { // TODO return points; } QPolygonF path; const QVector<QLineF> controlLines = bezierControlLines( points ); if ( controlLines.size() < n - 1 ) return path; path += points.first(); double t = distance; const QPointF *p = points.constData(); const QLineF *cl = controlLines.constData(); const QwtSplineParametrization *param = parametrization(); for ( int i = 0; i < n - 1; i++ ) { const double l = param->valueIncrement( p[i], p[i+1] ); while ( t < l ) { path += QwtSplineBezier::pointAt( p[i], cl[i].p1(), cl[i].p2(), p[i+1], t / l ); t += distance; } if ( withNodes ) { if ( qFuzzyCompare( path.last().x(), p[i+1].x() ) ) path.last() = p[i+1]; else path += p[i+1]; t = distance; } else { t -= l; } } if ( ( boundaryType() == QwtSplineApproximation::ClosedPolygon ) && ( controlLines.size() >= n ) ) { const double l = param->valueIncrement( p[n-1], p[0] ); while ( t < l ) { path += QwtSplineBezier::pointAt( p[n-1], cl[n-1].p1(), cl[n-1].p2(), p[0], t / l ); t += distance; } if ( qFuzzyCompare( path.last().x(), p[0].x() ) ) path.last() = p[0]; else path += p[0]; } return path; } //! Constructor QwtSplineG1::QwtSplineG1() { } //! Destructor QwtSplineG1::~QwtSplineG1() { } QwtSplineC1::QwtSplineC1() { setParametrization( QwtSplineParametrization::ParameterX ); } //! Destructor QwtSplineC1::~QwtSplineC1() { } double QwtSplineC1::slopeAtBeginning( const QPolygonF &points, double slopeNext ) const { if ( points.size() < 2 ) return 0.0; return QwtSplineC1P::slopeBoundary( boundaryCondition( QwtSpline::AtBeginning ), boundaryValue( QwtSpline::AtBeginning ), points[0], points[1], slopeNext ); } double QwtSplineC1::slopeAtEnd( const QPolygonF &points, double slopeBefore ) const { const int n = points.size(); const QPointF p1( points[n-1].x(), -points[n-1].y() ); const QPointF p2( points[n-2].x(), -points[n-2].y() ); const int condition = boundaryCondition( QwtSpline::AtEnd ); double value = boundaryValue( QwtSpline::AtEnd ); if ( condition != QwtSpline::LinearRunout ) { // beside LinearRunout the boundaryValue is a slope or curvature // and needs to be inverted too value = -value; } const double slope = QwtSplineC1P::slopeBoundary( condition, value, p1, p2, -slopeBefore ); return -slope; } /*! \brief Calculate an interpolated painter path Interpolates a polygon piecewise into cubic Bezier curves and returns them as QPainterPath. The implementation calculates the slopes at the control points and converts them into painter path elements in an additional loop. \param points Control points \return QPainterPath Painter path, that can be rendered by QPainter \note Derived spline classes might overload painterPath() to avoid the extra loops for converting results into a QPainterPath \sa slopesParametric() */ QPainterPath QwtSplineC1::painterPath( const QPolygonF &points ) const { const int n = points.size(); if ( n <= 2 ) return QwtSpline::painterPath( points ); using namespace QwtSplineC1P; PathStore store; switch( parametrization()->type() ) { case QwtSplineParametrization::ParameterX: { store = qwtSplineC1PathParamX<PathStore>( this, points ); break; } case QwtSplineParametrization::ParameterY: { store = qwtSplineC1PathParamY<PathStore>( this, points ); break; } case QwtSplineParametrization::ParameterUniform: { store = qwtSplineC1PathParametric<PathStore>( this, points, paramUniform() ); break; } case QwtSplineParametrization::ParameterCentripetal: { store = qwtSplineC1PathParametric<PathStore>( this, points, paramCentripetal() ); break; } case QwtSplineParametrization::ParameterChordal: { store = qwtSplineC1PathParametric<PathStore>( this, points, paramChordal() ); break; } default: { store = qwtSplineC1PathParametric<PathStore>( this, points, param( parametrization() ) ); } } return store.path; } /*! \brief Interpolate a curve with Bezier curves Interpolates a polygon piecewise with cubic Bezier curves and returns the 2 control points of each curve as QLineF. \param points Control points \return Control points of the interpolating Bezier curves */ QVector<QLineF> QwtSplineC1::bezierControlLines( const QPolygonF &points ) const { using namespace QwtSplineC1P; const int n = points.size(); if ( n <= 2 ) return QVector<QLineF>(); ControlPointsStore store; switch( parametrization()->type() ) { case QwtSplineParametrization::ParameterX: { store = qwtSplineC1PathParamX<ControlPointsStore>( this, points ); break; } case QwtSplineParametrization::ParameterY: { store = qwtSplineC1PathParamY<ControlPointsStore>( this, points ); break; } case QwtSplineParametrization::ParameterUniform: { store = qwtSplineC1PathParametric<ControlPointsStore>( this, points, paramUniform() ); break; } case QwtSplineParametrization::ParameterCentripetal: { store = qwtSplineC1PathParametric<ControlPointsStore>( this, points, paramCentripetal() ); break; } case QwtSplineParametrization::ParameterChordal: { store = qwtSplineC1PathParametric<ControlPointsStore>( this, points, paramChordal() ); break; } default: { store = qwtSplineC1PathParametric<ControlPointsStore>( this, points, param( parametrization() ) ); } } return store.controlPoints; } QPolygonF QwtSplineC1::equidistantPolygon( const QPolygonF &points, double distance, bool withNodes ) const { if ( parametrization()->type() == QwtSplineParametrization::ParameterX ) { if ( points.size() > 2 ) { const QVector<double> m = slopes( points ); if ( m.size() != points.size() ) return QPolygonF(); return qwtPolygonParametric<QwtSplinePolynomial::fromSlopes>( distance, points, m, withNodes ); } } return QwtSplineG1::equidistantPolygon( points, distance, withNodes ); } QVector<QwtSplinePolynomial> QwtSplineC1::polynomials( const QPolygonF &points ) const { QVector<QwtSplinePolynomial> polynomials; const QVector<double> m = slopes( points ); if ( m.size() < 2 ) return polynomials; for ( int i = 1; i < m.size(); i++ ) { polynomials += QwtSplinePolynomial::fromSlopes( points[i-1], m[i-1], points[i], m[i] ); } return polynomials; } QwtSplineC2::QwtSplineC2() { } //! Destructor QwtSplineC2::~QwtSplineC2() { } /*! \brief Interpolate a curve with Bezier curves Interpolates a polygon piecewise with cubic Bezier curves and returns them as QPainterPath. \param points Control points \return Painter path, that can be rendered by QPainter */ QPainterPath QwtSplineC2::painterPath( const QPolygonF &points ) const { // could be implemented from curvaturesX without the extra // loop for calculating the slopes vector. TODO ... return QwtSplineC1::painterPath( points ); } /*! \brief Interpolate a curve with Bezier curves Interpolates a polygon piecewise with cubic Bezier curves and returns the 2 control points of each curve as QLineF. \param points Control points \return Control points of the interpolating Bezier curves */ QVector<QLineF> QwtSplineC2::bezierControlLines( const QPolygonF &points ) const { // could be implemented from curvaturesX without the extra // loop for calculating the slopes vector. TODO ... return QwtSplineC1::bezierControlLines( points ); } QPolygonF QwtSplineC2::equidistantPolygon( const QPolygonF &points, double distance, bool withNodes ) const { if ( parametrization()->type() == QwtSplineParametrization::ParameterX ) { if ( points.size() > 2 ) { const QVector<double> cv = curvatures( points ); if ( cv.size() != points.size() ) return QPolygonF(); return qwtPolygonParametric<QwtSplinePolynomial::fromCurvatures>( distance, points, cv, withNodes ); } } return QwtSplineC1::equidistantPolygon( points, distance, withNodes ); } QVector<double> QwtSplineC2::slopes( const QPolygonF &points ) const { const QVector<double> curvatures = this->curvatures( points ); if ( curvatures.size() < 2 ) return QVector<double>(); QVector<double> slopes( curvatures.size() ); const double *cv = curvatures.constData(); double *m = slopes.data(); const int n = points.size(); const QPointF *p = points.constData(); QwtSplinePolynomial polynomial; for ( int i = 0; i < n - 1; i++ ) { polynomial = QwtSplinePolynomial::fromCurvatures( p[i], cv[i], p[i+1], cv[i+1] ); m[i] = polynomial.c1; } m[n-1] = polynomial.slopeAt( p[n-1].x() - p[n-2].x() ); return slopes; } QVector<QwtSplinePolynomial> QwtSplineC2::polynomials( const QPolygonF &points ) const { QVector<QwtSplinePolynomial> polynomials; const QVector<double> curvatures = this->curvatures( points ); if ( curvatures.size() < 2 ) return polynomials; const QPointF *p = points.constData(); const double *cv = curvatures.constData(); const int n = curvatures.size(); for ( int i = 1; i < n; i++ ) { polynomials += QwtSplinePolynomial::fromCurvatures( p[i-1], cv[i-1], p[i], cv[i] ); } return polynomials; }
spetroce/qwt
src/qwt_spline.cpp
C++
lgpl-2.1
31,139
/** * Encodes and decodes to and from Base64 notation. * * <p> * Change Log: * </p> * <ul> * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added * some convenience methods for reading and writing to and from files.</li> * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems * with other encodings (like EBCDIC).</li> * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the * encoded data was a single byte.</li> * <li>v2.0 - I got rid of methods that used booleans to set options. * Now everything is more consolidated and cleaner. The code now detects * when data that's being decoded is gzip-compressed and will decompress it * automatically. Generally things are cleaner. You'll probably have to * change some method calls that you were making to support the new * options format (<tt>int</tt>s that you "OR" together).</li> * <li>v1.5.1 - Fixed bug when decompressing and decoding to a * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>. * Added the ability to "suspend" encoding in the Output Stream so * you can turn on and off the encoding if you need to embed base64 * data in an otherwise "normal" stream (like an XML file).</li> * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself. * This helps when using GZIP streams. * Added the ability to GZip-compress objects before encoding them.</li> * <li>v1.4 - Added helper methods to read/write files.</li> * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li> * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream * where last buffer being read, if not completely full, was not returned.</li> * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li> * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li> * </ul> * * <p> * I am placing this code in the Public Domain. Do with it as you will. * This software comes with no guarantees or warranties but with * plenty of well-wishing instead! * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a> * periodically to check for updates or to contribute improvements. * </p> * * @author Robert Harder * @author rob@iharder.net * @version 2.1 */ public class Base64 { /* ******** P U B L I C F I E L D S ******** */ /** No options specified. Value is zero. */ public final static int NO_OPTIONS = 0; /** Specify encoding. */ public final static int ENCODE = 1; /** Specify decoding. */ public final static int DECODE = 0; /** Specify that data should be gzip-compressed. */ public final static int GZIP = 2; /** Don't break lines when encoding (violates strict Base64 specification) */ public final static int DONT_BREAK_LINES = 8; /* ******** P R I V A T E F I E L D S ******** */ /** Maximum line length (76) of Base64 output. */ private final static int MAX_LINE_LENGTH = 76; /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte)'='; /** The new line character (\n) as a byte. */ private final static byte NEW_LINE = (byte)'\n'; /** Preferred encoding. */ private final static String PREFERRED_ENCODING = "UTF-8"; /** The 64 valid Base64 values. */ private final static byte[] ALPHABET; private final static byte[] _NATIVE_ALPHABET = /* May be something funny like EBCDIC */ { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' }; /** Determine which ALPHABET to use. */ static { byte[] __bytes; try { __bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".getBytes( PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException use) { __bytes = _NATIVE_ALPHABET; // Fall back to native encoding } // end catch ALPHABET = __bytes; } // end static /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. **/ private final static byte[] DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9,-9,-9, // Decimal 44 - 46 63, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9 // Decimal 123 - 126 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; // I think I end up not using the BAD_ENCODING indicator. //private final static byte BAD_ENCODING = -9; // Indicates error in encoding private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding /** Defeats instantiation. */ private Base64(){} /* ******** E N C O D I N G M E T H O D S ******** */ /** * Encodes up to the first three bytes of array <var>threeBytes</var> * and returns a four-byte array in Base64 notation. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * The array <var>threeBytes</var> needs only be as big as * <var>numSigBytes</var>. * Code can reuse a byte array by passing a four-byte array as <var>b4</var>. * * @param b4 A reusable byte array to reduce array instantiation * @param threeBytes the array to convert * @param numSigBytes the number of significant bytes in your array * @return four byte array in Base64 notation. * @since 1.5.1 */ private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes ) { encode3to4( threeBytes, 0, numSigBytes, b4, 0 ); return b4; } // end encode3to4 /** * Encodes up to three bytes of the array <var>source</var> * and writes the resulting four Base64 bytes to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 3 for * the <var>source</var> array or <var>destOffset</var> + 4 for * the <var>destination</var> array. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4( byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset ) { // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index ALPHABET // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); switch( numSigBytes ) { case 3: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ]; return destination; case 2: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; case 1: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = EQUALS_SIGN; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Serializes an object and returns the Base64-encoded * version of that serialized object. If the object * cannot be serialized or there is another error, * the method will return <tt>null</tt>. * The object is not GZip-compressed before being encoded. * * @param serializableObject The object to encode * @return The Base64-encoded object * @since 1.4 */ public static String encodeObject( java.io.Serializable serializableObject ) { return encodeObject( serializableObject, NO_OPTIONS ); } // end encodeObject /** * Serializes an object and returns the Base64-encoded * version of that serialized object. If the object * cannot be serialized or there is another error, * the method will return <tt>null</tt>. * <p> * Valid options:<pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or * <p> * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> * * @param serializableObject The object to encode * @param options Specified options * @return The Base64-encoded object * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeObject( java.io.Serializable serializableObject, int options ) { // Streams java.io.ByteArrayOutputStream baos = null; java.io.OutputStream b64os = null; java.io.ObjectOutputStream oos = null; java.util.zip.GZIPOutputStream gzos = null; // Isolate options int gzip = (options & GZIP); int dontBreakLines = (options & DONT_BREAK_LINES); try { // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines ); // GZip? if( gzip == GZIP ) { gzos = new java.util.zip.GZIPOutputStream( b64os ); oos = new java.io.ObjectOutputStream( gzos ); } // end if: gzip else oos = new java.io.ObjectOutputStream( b64os ); oos.writeObject( serializableObject ); } // end try catch( java.io.IOException e ) { e.printStackTrace(); return null; } // end catch finally { try{ oos.close(); } catch( Exception e ){} try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( baos.toByteArray() ); } // end catch } // end encode /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * @param source The data to convert * @since 1.4 */ public static String encodeBytes( byte[] source ) { return encodeBytes( source, 0, source.length, NO_OPTIONS ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Valid options:<pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> * * * @param source The data to convert * @param options Specified options * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeBytes( byte[] source, int options ) { return encodeBytes( source, 0, source.length, options ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @since 1.4 */ public static String encodeBytes( byte[] source, int off, int len ) { return encodeBytes( source, off, len, NO_OPTIONS ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Valid options:<pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @param options Specified options * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeBytes( byte[] source, int off, int len, int options ) { // Isolate options int dontBreakLines = ( options & DONT_BREAK_LINES ); int gzip = ( options & GZIP ); // Compress? if( gzip == GZIP ) { java.io.ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines ); gzos = new java.util.zip.GZIPOutputStream( b64os ); gzos.write( source, off, len ); gzos.close(); } // end try catch( java.io.IOException e ) { e.printStackTrace(); return null; } // end catch finally { try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( baos.toByteArray() ); } // end catch } // end if: compress // Else, don't compress. Better not to use streams at all then. else { // Convert option to boolean in way that code likes it. boolean breakLines = dontBreakLines == 0; int len43 = len * 4 / 3; byte[] outBuff = new byte[ ( len43 ) // Main 4:3 + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for( ; d < len2; d+=3, e+=4 ) { encode3to4( source, d+off, 3, outBuff, e ); lineLength += 4; if( breakLines && lineLength == MAX_LINE_LENGTH ) { outBuff[e+4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array if( d < len ) { encode3to4( source, d+off, len - d, outBuff, e ); e += 4; } // end if: some padding needed // Return value according to relevant encoding. try { return new String( outBuff, 0, e, PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( outBuff, 0, e ); } // end catch } // end else: don't compress } // end encodeBytes /* ******** D E C O D I N G M E T H O D S ******** */ /** * Decodes four bytes from array <var>source</var> * and writes the resulting bytes (up to three of them) * to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 4 for * the <var>source</var> array or <var>destOffset</var> + 3 for * the <var>destination</var> array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the number of decoded bytes converted * @since 1.3 */ private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset ) { // Example: Dk== if( source[ srcOffset + 2] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); return 1; } // Example: DkL= else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); return 2; } // Example: DkLE else { try{ // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); destination[ destOffset ] = (byte)( outBuff >> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); destination[ destOffset + 2 ] = (byte)( outBuff ); return 3; }catch( Exception e){ System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) ); System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) ); System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) ); System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) ); return -1; } //e nd catch } } // end decodeToBytes /** * Very low-level access to decoding ASCII characters in * the form of a byte array. Does not support automatically * gunzipping or any other "fancy" features. * * @param source The Base64 encoded data * @param off The offset of where to begin decoding * @param len The length of characters to decode * @return decoded data * @since 1.3 */ public static byte[] decode( byte[] source, int off, int len ) { int len34 = len * 3 / 4; byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output int outBuffPosn = 0; byte[] b4 = new byte[4]; int b4Posn = 0; int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; for( i = off; i < off+len; i++ ) { sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits sbiDecode = DECODABET[ sbiCrop ]; if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better { if( sbiDecode >= EQUALS_SIGN_ENC ) { b4[ b4Posn++ ] = sbiCrop; if( b4Posn > 3 ) { outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn ); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if( sbiCrop == EQUALS_SIGN ) break; } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better else { //System.err.println( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" ); return null; } // end else: } // each input character byte[] out = new byte[ outBuffPosn ]; System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); return out; } // end decode /** * Decodes data from Base64 notation, automatically * detecting gzip-compressed data and decompressing it. * * @param s the string to decode * @return the decoded data * @since 1.4 */ public static byte[] decode( String s ) { byte[] bytes; try { bytes = s.getBytes( PREFERRED_ENCODING ); } // end try catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); } // end catch //</change> // Decode bytes = decode( bytes, 0, bytes.length ); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) if( bytes != null && bytes.length >= 4 ) { int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream( bytes ); gzis = new java.util.zip.GZIPInputStream( bais ); while( ( length = gzis.read( buffer ) ) >= 0 ) { baos.write(buffer,0,length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch( java.io.IOException e ) { // Just return originally-decoded bytes } // end catch finally { try{ baos.close(); } catch( Exception e ){} try{ gzis.close(); } catch( Exception e ){} try{ bais.close(); } catch( Exception e ){} } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; } // end decode /** * Attempts to decode Base64 data and deserialize a Java * Object within. Returns <tt>null</tt> if there was an error. * * @param encodedObject The Base64 data to decode * @return The decoded and deserialized object * @since 1.5 */ public static Object decodeToObject( String encodedObject ) { // Decode and gunzip if necessary byte[] objBytes = decode( encodedObject ); java.io.ByteArrayInputStream bais = null; java.io.ObjectInputStream ois = null; Object obj = null; try { bais = new java.io.ByteArrayInputStream( objBytes ); ois = new java.io.ObjectInputStream( bais ); obj = ois.readObject(); } // end try catch( java.io.IOException e ) { e.printStackTrace(); obj = null; } // end catch catch( java.lang.ClassNotFoundException e ) { e.printStackTrace(); obj = null; } // end catch finally { try{ bais.close(); } catch( Exception e ){} try{ ois.close(); } catch( Exception e ){} } // end finally return obj; } // end decodeObject /** * Convenience method for encoding data to a file. * * @param dataToEncode byte array of data to encode in base64 form * @param filename Filename for saving encoded data * @return <tt>true</tt> if successful, <tt>false</tt> otherwise * * @since 2.1 */ public static boolean encodeToFile( byte[] dataToEncode, String filename ) { boolean success = false; Base64.OutputStream bos = null; try { bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.ENCODE ); bos.write( dataToEncode ); success = true; } // end try catch( java.io.IOException e ) { success = false; } // end catch: IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally return success; } // end encodeToFile /** * Convenience method for decoding data to a file. * * @param dataToDecode Base64-encoded data as a string * @param filename Filename for saving decoded data * @return <tt>true</tt> if successful, <tt>false</tt> otherwise * * @since 2.1 */ public static boolean decodeToFile( String dataToDecode, String filename ) { boolean success = false; Base64.OutputStream bos = null; try { bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.DECODE ); bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) ); success = true; } // end try catch( java.io.IOException e ) { success = false; } // end catch: IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally return success; } // end decodeToFile /** * Convenience method for reading a base64-encoded * file and decoding it. * * @param filename Filename for reading encoded data * @return decoded byte array or null if unsuccessful * * @since 2.1 */ public static byte[] decodeFromFile( String filename ) { byte[] decodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = null; int length = 0; int numBytes = 0; // Check for size of file if( file.length() > Integer.MAX_VALUE ) { System.err.println( "File is too big for this convenience method (" + file.length() + " bytes)." ); return null; } // end if: file too big for int index buffer = new byte[ (int)file.length() ]; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.DECODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) length += numBytes; // Save in a variable to return decodedData = new byte[ length ]; System.arraycopy( buffer, 0, decodedData, 0, length ); } // end try catch( java.io.IOException e ) { System.err.println( "Error decoding from file " + filename ); } // end catch: IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return decodedData; } // end decodeFromFile /** * Convenience method for reading a binary file * and base64-encoding it. * * @param filename Filename for reading binary data * @return base64-encoded string or null if unsuccessful * * @since 2.1 */ public static String encodeFromFile( String filename ) { String encodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = new byte[ (int)(file.length() * 1.4) ]; int length = 0; int numBytes = 0; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.ENCODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) length += numBytes; // Save in a variable to return encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING ); } // end try catch( java.io.IOException e ) { System.err.println( "Error encoding from file " + filename ); } // end catch: IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return encodedData; } // end encodeFromFile /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ /** * A {@link Base64.InputStream} will read data from another * <tt>java.io.InputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class InputStream extends java.io.FilterInputStream { private boolean encode; // Encoding or decoding private int position; // Current position in the buffer private byte[] buffer; // Small buffer holding converted data private int bufferLength; // Length of buffer (3 or 4) private int numSigBytes; // Number of meaningful bytes in the buffer private int lineLength; private boolean breakLines; // Break lines at less than 80 characters /** * Constructs a {@link Base64.InputStream} in DECODE mode. * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @since 1.3 */ public InputStream( java.io.InputStream in ) { this( in, DECODE ); } // end constructor /** * Constructs a {@link Base64.InputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DONT_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding) * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code> * * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @param options Specified options * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public InputStream( java.io.InputStream in, int options ) { super( in ); this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; this.encode = (options & ENCODE) == ENCODE; this.bufferLength = encode ? 4 : 3; this.buffer = new byte[ bufferLength ]; this.position = -1; this.lineLength = 0; } // end constructor /** * Reads enough of the input stream to convert * to/from Base64 and returns the next byte. * * @return next byte * @since 1.3 */ public int read() throws java.io.IOException { // Do we need to get data? if( position < 0 ) { if( encode ) { byte[] b3 = new byte[3]; int numBinaryBytes = 0; for( int i = 0; i < 3; i++ ) { try { int b = in.read(); // If end of stream, b is -1. if( b >= 0 ) { b3[i] = (byte)b; numBinaryBytes++; } // end if: not end of stream } // end try: read catch( java.io.IOException e ) { // Only a problem if we got no data at all. if( i == 0 ) throw e; } // end catch } // end for: each needed input byte if( numBinaryBytes > 0 ) { encode3to4( b3, 0, numBinaryBytes, buffer, 0 ); position = 0; numSigBytes = 4; } // end if: got data else { return -1; } // end else } // end if: encoding // Else decoding else { byte[] b4 = new byte[4]; int i = 0; for( i = 0; i < 4; i++ ) { // Read four "meaningful" bytes: int b = 0; do{ b = in.read(); } while( b >= 0 && DECODABET[ b & 0x7f ] <= WHITE_SPACE_ENC ); if( b < 0 ) break; // Reads a -1 if end of stream b4[i] = (byte)b; } // end for: each needed input byte if( i == 4 ) { numSigBytes = decode4to3( b4, 0, buffer, 0 ); position = 0; } // end if: got four characters else if( i == 0 ){ return -1; } // end else if: also padded correctly else { // Must have broken out from above. throw new java.io.IOException( "Improperly padded Base64 input." ); } // end } // end else: decode } // end else: get data // Got data? if( position >= 0 ) { // End of relevant data? if( /*!encode &&*/ position >= numSigBytes ) return -1; if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) { lineLength = 0; return '\n'; } // end if else { lineLength++; // This isn't important when decoding // but throwing an extra "if" seems // just as wasteful. int b = buffer[ position++ ]; if( position >= bufferLength ) position = -1; return b & 0xFF; // This is how you "cast" a byte that's // intended to be unsigned. } // end else } // end if: position >= 0 // Else error else { // When JDK1.4 is more accepted, use an assertion here. throw new java.io.IOException( "Error in Base64 code reading stream." ); } // end else } // end read /** * Calls {@link #read()} repeatedly until the end of stream * is reached or <var>len</var> bytes are read. * Returns number of bytes read into array or -1 if * end of stream is encountered. * * @param dest array to hold values * @param off offset for array * @param len max number of bytes to read into array * @return bytes read into array or -1 if end of stream is encountered. * @since 1.3 */ public int read( byte[] dest, int off, int len ) throws java.io.IOException { int i; int b; for( i = 0; i < len; i++ ) { b = read(); //if( b < 0 && i == 0 ) // return -1; if( b >= 0 ) dest[off + i] = (byte)b; else if( i == 0 ) return -1; else break; // Out of 'for' loop } // end for: each byte read return i; } // end read } // end inner class InputStream /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ /** * A {@link Base64.OutputStream} will write data to another * <tt>java.io.OutputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class OutputStream extends java.io.FilterOutputStream { private boolean encode; private int position; private byte[] buffer; private int bufferLength; private int lineLength; private boolean breakLines; private byte[] b4; // Scratch used in a few places private boolean suspendEncoding; /** * Constructs a {@link Base64.OutputStream} in ENCODE mode. * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @since 1.3 */ public OutputStream( java.io.OutputStream out ) { this( out, ENCODE ); } // end constructor /** * Constructs a {@link Base64.OutputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DONT_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding) * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code> * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @param options Specified options. * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DONT_BREAK_LINES * @since 1.3 */ public OutputStream( java.io.OutputStream out, int options ) { super( out ); this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; this.encode = (options & ENCODE) == ENCODE; this.bufferLength = encode ? 3 : 4; this.buffer = new byte[ bufferLength ]; this.position = 0; this.lineLength = 0; this.suspendEncoding = false; this.b4 = new byte[4]; } // end constructor /** * Writes the byte to the output stream after * converting to/from Base64 notation. * When encoding, bytes are buffered three * at a time before the output stream actually * gets a write() call. * When decoding, bytes are buffered four * at a time. * * @param theByte the byte to write * @since 1.3 */ public void write(int theByte) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { super.out.write( theByte ); return; } // end if: supsended // Encode? if( encode ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) // Enough to encode. { out.write( encode3to4( b4, buffer, bufferLength ) ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { out.write( NEW_LINE ); lineLength = 0; } // end if: end of line position = 0; } // end if: enough to output } // end if: encoding // Else, Decoding else { // Meaningful Base64 character? if( DECODABET[ theByte & 0x7f ] > WHITE_SPACE_ENC ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) // Enough to output. { int len = Base64.decode4to3( buffer, 0, b4, 0 ); out.write( b4, 0, len ); //out.write( Base64.decode4to3( buffer ) ); position = 0; } // end if: enough to output } // end if: meaningful base64 character else if( DECODABET[ theByte & 0x7f ] != WHITE_SPACE_ENC ) { throw new java.io.IOException( "Invalid character in Base64 data." ); } // end else: not white space either } // end else: decoding } // end write /** * Calls {@link #write(int)} repeatedly until <var>len</var> * bytes are written. * * @param theBytes array from which to read bytes * @param off offset for array * @param len max number of bytes to read into array * @since 1.3 */ public void write( byte[] theBytes, int off, int len ) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { super.out.write( theBytes, off, len ); return; } // end if: supsended for( int i = 0; i < len; i++ ) { write( theBytes[ off + i ] ); } // end for: each byte written } // end write /** * Method added by PHIL. [Thanks, PHIL. -Rob] * This pads the buffer without closing the stream. */ public void flushBase64() throws java.io.IOException { if( position > 0 ) { if( encode ) { out.write( encode3to4( b4, buffer, position ) ); position = 0; } // end if: encoding else { throw new java.io.IOException( "Base64 input not properly padded." ); } // end else: decoding } // end if: buffer partially full } // end flush /** * Flushes and closes (I think, in the superclass) the stream. * * @since 1.3 */ public void close() throws java.io.IOException { // 1. Ensure that pending characters are written flushBase64(); // 2. Actually close the stream // Base class both flushes and closes. super.close(); buffer = null; out = null; } // end close /** * Suspends encoding of the stream. * May be helpful if you need to embed a piece of * base640-encoded data in a stream. * * @since 1.5.1 */ public void suspendEncoding() throws java.io.IOException { flushBase64(); this.suspendEncoding = true; } // end suspendEncoding /** * Resumes encoding of the stream. * May be helpful if you need to embed a piece of * base640-encoded data in a stream. * * @since 1.5.1 */ public void resumeEncoding() { this.suspendEncoding = false; } // end resumeEncoding } // end inner class OutputStream } // end class Base64
Chandrashar/jradius
applet/src/main/java/Base64.java
Java
lgpl-2.1
53,360
// Copyright (c) 2012-2013 The Cryptonote developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <vector> #include <iostream> #include <sstream> #include "include_base_utils.h" #include "console_handler.h" #include "p2p/net_node.h" #include "currency_core/currency_basic.h" #include "currency_core/currency_basic_impl.h" #include "currency_core/currency_format_utils.h" #include "currency_core/miner.h" #include "chaingen.h" using namespace std; using namespace epee; using namespace currency; #define DIFF_UP_TIMESTAMP_DELTA 90 void test_generator::get_block_chain(std::vector<const block_info*>& blockchain, const crypto::hash& head, size_t n) const { crypto::hash curr = head; while (null_hash != curr && blockchain.size() < n) { auto it = m_blocks_info.find(curr); if (m_blocks_info.end() == it) { throw std::runtime_error("block hash wasn't found"); } blockchain.push_back(&it->second); curr = it->second.b.prev_id; } std::reverse(blockchain.begin(), blockchain.end()); } void test_generator::get_last_n_block_sizes(std::vector<size_t>& block_sizes, const crypto::hash& head, size_t n) const { std::vector<const block_info*> blockchain; get_block_chain(blockchain, head, n); BOOST_FOREACH(auto& bi, blockchain) { block_sizes.push_back(bi->block_size); } } uint64_t test_generator::get_already_generated_coins(const crypto::hash& blk_id) const { auto it = m_blocks_info.find(blk_id); if (it == m_blocks_info.end()) throw std::runtime_error("block hash wasn't found"); return it->second.already_generated_coins; } uint64_t test_generator::get_already_donated_coins(const crypto::hash& blk_id) const { auto it = m_blocks_info.find(blk_id); if (it == m_blocks_info.end()) throw std::runtime_error("block hash wasn't found"); return it->second.already_donated; } currency::wide_difficulty_type test_generator::get_block_difficulty(const crypto::hash& blk_id) const { auto it = m_blocks_info.find(blk_id); if (it == m_blocks_info.end()) throw std::runtime_error("block hash wasn't found"); auto it_prev = m_blocks_info.find(it->second.b.prev_id); if (it_prev == m_blocks_info.end()) throw std::runtime_error("block hash wasn't found"); return it->second.cumul_difficulty - it_prev->second.cumul_difficulty; } uint64_t test_generator::get_already_generated_coins(const currency::block& blk) const { crypto::hash blk_hash; get_block_hash(blk, blk_hash); return get_already_generated_coins(blk_hash); } void test_generator::add_block(const currency::block& blk, size_t tsx_size, std::vector<size_t>& block_sizes, uint64_t already_generated_coins, uint64_t already_donated_coins, wide_difficulty_type cum_diff) { const size_t block_size = tsx_size + get_object_blobsize(blk.miner_tx); uint64_t block_reward; uint64_t max_donation; get_block_reward(misc_utils::median(block_sizes), block_size, already_generated_coins, already_donated_coins, block_reward, max_donation); uint64_t donation_for_block = 0; m_blocks_info[get_block_hash(blk)] = block_info(blk, already_generated_coins + block_reward, already_donated_coins + donation_for_block, block_size, cum_diff); } bool test_generator::construct_block(currency::block& blk, uint64_t height, const crypto::hash& prev_id, const currency::account_base& miner_acc, uint64_t timestamp, uint64_t already_generated_coins, uint64_t already_donated_coins, std::vector<size_t>& block_sizes, const std::list<currency::transaction>& tx_list, const currency::alias_info& ai) { blk.major_version = CURRENT_BLOCK_MAJOR_VERSION; blk.minor_version = CURRENT_BLOCK_MINOR_VERSION; blk.flags = BLOCK_FLAGS_SUPPRESS_DONATION; blk.timestamp = timestamp; blk.prev_id = prev_id; blk.tx_hashes.reserve(tx_list.size()); BOOST_FOREACH(const transaction &tx, tx_list) { crypto::hash tx_hash; get_transaction_hash(tx, tx_hash); blk.tx_hashes.push_back(tx_hash); } uint64_t total_fee = 0; size_t txs_size = 0; BOOST_FOREACH(auto& tx, tx_list) { uint64_t fee = 0; bool r = get_tx_fee(tx, fee); CHECK_AND_ASSERT_MES(r, false, "wrong transaction passed to construct_block"); total_fee += fee; txs_size += get_object_blobsize(tx); } account_keys donation_acc = AUTO_VAL_INIT(donation_acc); account_keys royalty_acc = AUTO_VAL_INIT(royalty_acc); get_donation_accounts(donation_acc, royalty_acc); blk.miner_tx = AUTO_VAL_INIT(blk.miner_tx); size_t target_block_size = txs_size + get_object_blobsize(blk.miner_tx); while (true) { if (!construct_miner_tx(height, misc_utils::median(block_sizes), already_generated_coins, already_donated_coins, target_block_size, total_fee, miner_acc.get_keys().m_account_address, donation_acc.m_account_address, royalty_acc.m_account_address, blk.miner_tx, blobdata(), 10, 0, ai)) return false; size_t actual_block_size = txs_size + get_object_blobsize(blk.miner_tx); if (target_block_size < actual_block_size) { target_block_size = actual_block_size; } else if (actual_block_size < target_block_size) { size_t delta = target_block_size - actual_block_size; blk.miner_tx.extra.resize(blk.miner_tx.extra.size() + delta, 0); actual_block_size = txs_size + get_object_blobsize(blk.miner_tx); if (actual_block_size == target_block_size) { break; } else { CHECK_AND_ASSERT_MES(target_block_size < actual_block_size, false, "Unexpected block size"); delta = actual_block_size - target_block_size; blk.miner_tx.extra.resize(blk.miner_tx.extra.size() - delta); actual_block_size = txs_size + get_object_blobsize(blk.miner_tx); if (actual_block_size == target_block_size) { break; } else { CHECK_AND_ASSERT_MES(actual_block_size < target_block_size, false, "Unexpected block size"); blk.miner_tx.extra.resize(blk.miner_tx.extra.size() + delta, 0); target_block_size = txs_size + get_object_blobsize(blk.miner_tx); } } } else { break; } } //blk.tree_root_hash = get_tx_tree_hash(blk); std::vector<const block_info*> blocks; get_block_chain(blocks, blk.prev_id, std::numeric_limits<size_t>::max()); wide_difficulty_type a_diffic = get_difficulty_for_next_block(blocks); // Nonce search... blk.nonce = 0; while (!find_nounce(blk, blocks, a_diffic, height)) blk.timestamp++; add_block(blk, txs_size, block_sizes, already_generated_coins, already_donated_coins, blocks.size() ? blocks.back()->cumul_difficulty + a_diffic: a_diffic); return true; } currency::wide_difficulty_type test_generator::get_difficulty_for_next_block(const crypto::hash& head_id) { std::vector<const block_info*> blocks; get_block_chain(blocks, head_id, std::numeric_limits<size_t>::max()); return get_difficulty_for_next_block(blocks); } currency::wide_difficulty_type test_generator::get_difficulty_for_next_block(const std::vector<const block_info*>& blocks) { std::vector<uint64_t> timestamps; std::vector<wide_difficulty_type> commulative_difficulties; size_t offset = blocks.size() - std::min(blocks.size(), static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT)); if(!offset) ++offset;//skip genesis block for(; offset < blocks.size(); offset++) { timestamps.push_back(blocks[offset]->b.timestamp); commulative_difficulties.push_back(blocks[offset]->cumul_difficulty); } return next_difficulty(timestamps, commulative_difficulties); } bool test_generator::find_nounce(block& blk, std::vector<const block_info*>& blocks, wide_difficulty_type dif, uint64_t height) { if(height != blocks.size()) throw std::runtime_error("wrong height in find_nounce"); std::vector<crypto::hash> scratchpad_local; size_t count = 1; for(auto& i: blocks) { push_block_scratchpad_data(i->b, scratchpad_local); #ifdef ENABLE_HASHING_DEBUG LOG_PRINT2("block_generation.log", "SCRATCHPAD_SHOT FOR H=" << count << ENDL << dump_scratchpad(scratchpad_local), LOG_LEVEL_3); #endif ++count; } bool r = miner::find_nonce_for_given_block(blk, dif, height, [&](uint64_t index) -> crypto::hash& { return scratchpad_local[index%scratchpad_local.size()]; }); #ifdef ENABLE_HASHING_DEBUG size_t call_no = 0; std::stringstream ss; crypto::hash pow = get_block_longhash(blk, height, [&](uint64_t index) -> crypto::hash& { ss << "[" << call_no << "][" << index << "%" << scratchpad_local.size() <<"(" << index%scratchpad_local.size() << ")]" << scratchpad_local[index%scratchpad_local.size()] << ENDL; ++call_no; return scratchpad_local[index%scratchpad_local.size()]; }); LOG_PRINT2("block_generation.log", "ID: " << get_block_hash(blk) << "[" << height << "]" << ENDL << "POW:" << pow << ENDL << ss.str(), LOG_LEVEL_3); #endif return r; } bool test_generator::construct_block(currency::block& blk, const currency::account_base& miner_acc, uint64_t timestamp, const currency::alias_info& ai) { std::vector<size_t> block_sizes; std::list<currency::transaction> tx_list; return construct_block(blk, 0, null_hash, miner_acc, timestamp, 0, 0, block_sizes, tx_list, ai); } bool test_generator::construct_block(currency::block& blk, const currency::block& blk_prev, const currency::account_base& miner_acc, const std::list<currency::transaction>& tx_list, const currency::alias_info& ai) { uint64_t height = boost::get<txin_gen>(blk_prev.miner_tx.vin.front()).height + 1; crypto::hash prev_id = get_block_hash(blk_prev); // Keep push difficulty little up to be sure about PoW hash success uint64_t timestamp = height > 10 ? blk_prev.timestamp + DIFFICULTY_BLOCKS_ESTIMATE_TIMESPAN: blk_prev.timestamp + DIFFICULTY_BLOCKS_ESTIMATE_TIMESPAN - DIFF_UP_TIMESTAMP_DELTA; uint64_t already_generated_coins = get_already_generated_coins(prev_id); uint64_t already_donated_coins = get_already_donated_coins(prev_id); std::vector<size_t> block_sizes; get_last_n_block_sizes(block_sizes, prev_id, CURRENCY_REWARD_BLOCKS_WINDOW); return construct_block(blk, height, prev_id, miner_acc, timestamp, already_generated_coins, already_donated_coins, block_sizes, tx_list, ai); } bool test_generator::construct_block_manually(block& blk, const block& prev_block, const account_base& miner_acc, int actual_params/* = bf_none*/, uint8_t major_ver/* = 0*/, uint8_t minor_ver/* = 0*/, uint64_t timestamp/* = 0*/, const crypto::hash& prev_id/* = crypto::hash()*/, const wide_difficulty_type& diffic/* = 1*/, const transaction& miner_tx/* = transaction()*/, const std::vector<crypto::hash>& tx_hashes/* = std::vector<crypto::hash>()*/, size_t txs_sizes/* = 0*/) { size_t height = get_block_height(prev_block) + 1; blk.flags = BLOCK_FLAGS_SUPPRESS_DONATION; blk.major_version = actual_params & bf_major_ver ? major_ver : CURRENT_BLOCK_MAJOR_VERSION; blk.minor_version = actual_params & bf_minor_ver ? minor_ver : CURRENT_BLOCK_MINOR_VERSION; blk.timestamp = actual_params & bf_timestamp ? timestamp : (height > 10 ? prev_block.timestamp + DIFFICULTY_BLOCKS_ESTIMATE_TIMESPAN: prev_block.timestamp + DIFFICULTY_BLOCKS_ESTIMATE_TIMESPAN-DIFF_UP_TIMESTAMP_DELTA); // Keep difficulty unchanged blk.prev_id = actual_params & bf_prev_id ? prev_id : get_block_hash(prev_block); blk.tx_hashes = actual_params & bf_tx_hashes ? tx_hashes : std::vector<crypto::hash>(); uint64_t already_generated_coins = get_already_generated_coins(prev_block); uint64_t already_donated_coins = get_already_donated_coins(get_block_hash(prev_block)); std::vector<size_t> block_sizes; get_last_n_block_sizes(block_sizes, get_block_hash(prev_block), CURRENCY_REWARD_BLOCKS_WINDOW); if (actual_params & bf_miner_tx) { blk.miner_tx = miner_tx; } else { size_t current_block_size = txs_sizes + get_object_blobsize(blk.miner_tx); // TODO: This will work, until size of constructed block is less then CURRENCY_BLOCK_GRANTED_FULL_REWARD_ZONE if (!construct_miner_tx(height, misc_utils::median(block_sizes), already_generated_coins, current_block_size, 0, miner_acc.get_keys().m_account_address, blk.miner_tx, blobdata(), 1)) return false; } //blk.tree_root_hash = get_tx_tree_hash(blk); std::vector<const block_info*> blocks; get_block_chain(blocks, blk.prev_id, std::numeric_limits<size_t>::max()); wide_difficulty_type a_diffic = actual_params & bf_diffic ? diffic : get_difficulty_for_next_block(blocks); find_nounce(blk, blocks, a_diffic, height); add_block(blk, txs_sizes, block_sizes, already_generated_coins, already_donated_coins, blocks.size() ? blocks.back()->cumul_difficulty + a_diffic: a_diffic); return true; } bool test_generator::construct_block_manually_tx(currency::block& blk, const currency::block& prev_block, const currency::account_base& miner_acc, const std::vector<crypto::hash>& tx_hashes, size_t txs_size) { return construct_block_manually(blk, prev_block, miner_acc, bf_tx_hashes, 0, 0, 0, crypto::hash(), 0, transaction(), tx_hashes, txs_size); } struct output_index { const currency::txout_target_v out; uint64_t amount; size_t blk_height; // block height size_t tx_no; // index of transaction in block size_t out_no; // index of out in transaction size_t idx; bool spent; const currency::block *p_blk; const currency::transaction *p_tx; output_index(const currency::txout_target_v &_out, uint64_t _a, size_t _h, size_t tno, size_t ono, const currency::block *_pb, const currency::transaction *_pt) : out(_out), amount(_a), blk_height(_h), tx_no(tno), out_no(ono), idx(0), spent(false), p_blk(_pb), p_tx(_pt) { } output_index(const output_index &other) : out(other.out), amount(other.amount), blk_height(other.blk_height), tx_no(other.tx_no), out_no(other.out_no), idx(other.idx), spent(other.spent), p_blk(other.p_blk), p_tx(other.p_tx) { } const std::string toString() const { std::stringstream ss; ss << "output_index{blk_height=" << blk_height << " tx_no=" << tx_no << " out_no=" << out_no << " amount=" << amount << " idx=" << idx << " spent=" << spent << "}"; return ss.str(); } output_index& operator=(const output_index& other) { new(this) output_index(other); return *this; } }; typedef std::map<uint64_t, std::vector<size_t> > map_output_t; typedef std::map<uint64_t, std::vector<output_index> > map_output_idx_t; typedef pair<uint64_t, size_t> outloc_t; namespace { uint64_t get_inputs_amount(const vector<tx_source_entry> &s) { uint64_t r = 0; BOOST_FOREACH(const tx_source_entry &e, s) { r += e.amount; } return r; } } bool init_output_indices(map_output_idx_t& outs, std::map<uint64_t, std::vector<size_t> >& outs_mine, const std::vector<currency::block>& blockchain, const map_hash2tx_t& mtx, const currency::account_base& from) { BOOST_FOREACH (const block& blk, blockchain) { vector<const transaction*> vtx; vtx.push_back(&blk.miner_tx); BOOST_FOREACH(const crypto::hash &h, blk.tx_hashes) { const map_hash2tx_t::const_iterator cit = mtx.find(h); if (mtx.end() == cit) throw std::runtime_error("block contains an unknown tx hash"); vtx.push_back(cit->second); } //vtx.insert(vtx.end(), blk.); // TODO: add all other txes for (size_t i = 0; i < vtx.size(); i++) { const transaction &tx = *vtx[i]; for (size_t j = 0; j < tx.vout.size(); ++j) { const tx_out &out = tx.vout[j]; output_index oi(out.target, out.amount, boost::get<txin_gen>(*blk.miner_tx.vin.begin()).height, i, j, &blk, vtx[i]); if (2 == out.target.which()) { // out_to_key outs[out.amount].push_back(oi); size_t tx_global_idx = outs[out.amount].size() - 1; outs[out.amount][tx_global_idx].idx = tx_global_idx; // Is out to me? if (is_out_to_acc(from.get_keys(), boost::get<txout_to_key>(out.target), get_tx_pub_key_from_extra(tx), j)) { outs_mine[out.amount].push_back(tx_global_idx); } } } } } return true; } bool init_spent_output_indices(map_output_idx_t& outs, map_output_t& outs_mine, const std::vector<currency::block>& blockchain, const map_hash2tx_t& mtx, const currency::account_base& from) { BOOST_FOREACH (const map_output_t::value_type &o, outs_mine) { for (size_t i = 0; i < o.second.size(); ++i) { output_index &oi = outs[o.first][o.second[i]]; // construct key image for this output crypto::key_image img; keypair in_ephemeral; generate_key_image_helper(from.get_keys(), get_tx_pub_key_from_extra(*oi.p_tx), oi.out_no, in_ephemeral, img); // lookup for this key image in the events vector BOOST_FOREACH(auto& tx_pair, mtx) { const transaction& tx = *tx_pair.second; BOOST_FOREACH(const txin_v &in, tx.vin) { if (typeid(txin_to_key) == in.type()) { const txin_to_key &itk = boost::get<txin_to_key>(in); if (itk.k_image == img) { oi.spent = true; } } } } } } return true; } bool fill_output_entries(std::vector<output_index>& out_indices, size_t sender_out, size_t nmix, uint64_t& real_entry_idx, std::vector<tx_source_entry::output_entry>& output_entries) { if (out_indices.size() <= nmix) return false; bool sender_out_found = false; size_t rest = nmix; for (size_t i = 0; i < out_indices.size() && (0 < rest || !sender_out_found); ++i) { const output_index& oi = out_indices[i]; if (oi.spent) continue; bool append = false; if (i == sender_out) { append = true; sender_out_found = true; real_entry_idx = output_entries.size(); } else if (0 < rest) { if(boost::get<txout_to_key>(oi.out).mix_attr == CURRENCY_TO_KEY_OUT_FORCED_NO_MIX || boost::get<txout_to_key>(oi.out).mix_attr > nmix+1) continue; --rest; append = true; } if (append) { const txout_to_key& otk = boost::get<txout_to_key>(oi.out); output_entries.push_back(tx_source_entry::output_entry(oi.idx, otk.key)); } } return 0 == rest && sender_out_found; } bool fill_tx_sources(std::vector<tx_source_entry>& sources, const std::vector<test_event_entry>& events, const block& blk_head, const currency::account_base& from, uint64_t amount, size_t nmix, bool check_for_spends = true) { map_output_idx_t outs; map_output_t outs_mine; std::vector<currency::block> blockchain; map_hash2tx_t mtx; if (!find_block_chain(events, blockchain, mtx, get_block_hash(blk_head))) return false; if (!init_output_indices(outs, outs_mine, blockchain, mtx, from)) return false; if(check_for_spends) { if (!init_spent_output_indices(outs, outs_mine, blockchain, mtx, from)) return false; } // Iterate in reverse is more efficiency uint64_t sources_amount = 0; bool sources_found = false; BOOST_REVERSE_FOREACH(const map_output_t::value_type o, outs_mine) { for (size_t i = 0; i < o.second.size() && !sources_found; ++i) { size_t sender_out = o.second[i]; const output_index& oi = outs[o.first][sender_out]; if (oi.spent) continue; currency::tx_source_entry ts; ts.amount = oi.amount; ts.real_output_in_tx_index = oi.out_no; ts.real_out_tx_key = get_tx_pub_key_from_extra(*oi.p_tx); // incoming tx public key if (!fill_output_entries(outs[o.first], sender_out, nmix, ts.real_output, ts.outputs)) continue; sources.push_back(ts); sources_amount += ts.amount; sources_found = amount <= sources_amount; } if (sources_found) break; } return sources_found; } bool fill_tx_destination(tx_destination_entry &de, const currency::account_base &to, uint64_t amount) { de.addr = to.get_keys().m_account_address; de.amount = amount; return true; } void fill_tx_sources_and_destinations(const std::vector<test_event_entry>& events, const block& blk_head, const currency::account_base& from, const currency::account_base& to, uint64_t amount, uint64_t fee, size_t nmix, std::vector<tx_source_entry>& sources, std::vector<tx_destination_entry>& destinations, bool check_for_spends) { sources.clear(); destinations.clear(); if (!fill_tx_sources(sources, events, blk_head, from, amount + fee, nmix, check_for_spends)) throw std::runtime_error("couldn't fill transaction sources"); tx_destination_entry de; if (!fill_tx_destination(de, to, amount)) throw std::runtime_error("couldn't fill transaction destination"); destinations.push_back(de); tx_destination_entry de_change; uint64_t cache_back = get_inputs_amount(sources) - (amount + fee); if (0 < cache_back) { if (!fill_tx_destination(de_change, from, cache_back)) throw std::runtime_error("couldn't fill transaction cache back destination"); destinations.push_back(de_change); } } /* void fill_nonce(currency::block& blk, const wide_difficulty_type& diffic, uint64_t height) { blk.nonce = 0; while (!miner::find_nonce_for_given_block(blk, diffic, height)) blk.timestamp++; }*/ bool construct_miner_tx_manually(size_t height, uint64_t already_generated_coins, const account_public_address& miner_address, transaction& tx, uint64_t fee, keypair* p_txkey/* = 0*/) { keypair txkey; txkey = keypair::generate(); add_tx_pub_key_to_extra(tx, txkey.pub); if (0 != p_txkey) *p_txkey = txkey; txin_gen in; in.height = height; tx.vin.push_back(in); // This will work, until size of constructed block is less then CURRENCY_BLOCK_GRANTED_FULL_REWARD_ZONE uint64_t block_reward; uint64_t max_donation; if (!get_block_reward(0, 0, already_generated_coins, 0, block_reward, max_donation)) { LOG_PRINT_L0("Block is too big"); return false; } block_reward += fee; crypto::key_derivation derivation; crypto::public_key out_eph_public_key; crypto::generate_key_derivation(miner_address.m_view_public_key, txkey.sec, derivation); crypto::derive_public_key(derivation, 0, miner_address.m_spend_public_key, out_eph_public_key); tx_out out; out.amount = block_reward; out.target = txout_to_key(out_eph_public_key); tx.vout.push_back(out); tx.version = CURRENT_TRANSACTION_VERSION; tx.unlock_time = height + CURRENCY_MINED_MONEY_UNLOCK_WINDOW; return true; } bool construct_tx_to_key(const std::vector<test_event_entry>& events, currency::transaction& tx, const block& blk_head, const currency::account_base& from, const currency::account_base& to, uint64_t amount, uint64_t fee, size_t nmix, uint8_t mix_attr, bool check_for_spends) { vector<tx_source_entry> sources; vector<tx_destination_entry> destinations; fill_tx_sources_and_destinations(events, blk_head, from, to, amount, fee, nmix, sources, destinations, check_for_spends); return construct_tx(from.get_keys(), sources, destinations, tx, 0, mix_attr); } transaction construct_tx_with_fee(std::vector<test_event_entry>& events, const block& blk_head, const account_base& acc_from, const account_base& acc_to, uint64_t amount, uint64_t fee) { transaction tx; construct_tx_to_key(events, tx, blk_head, acc_from, acc_to, amount, fee, 0); events.push_back(tx); return tx; } uint64_t get_balance(const currency::account_base& addr, const std::vector<currency::block>& blockchain, const map_hash2tx_t& mtx) { uint64_t res = 0; std::map<uint64_t, std::vector<output_index> > outs; std::map<uint64_t, std::vector<size_t> > outs_mine; map_hash2tx_t confirmed_txs; get_confirmed_txs(blockchain, mtx, confirmed_txs); if (!init_output_indices(outs, outs_mine, blockchain, confirmed_txs, addr)) return false; if (!init_spent_output_indices(outs, outs_mine, blockchain, confirmed_txs, addr)) return false; BOOST_FOREACH (const map_output_t::value_type &o, outs_mine) { for (size_t i = 0; i < o.second.size(); ++i) { if (outs[o.first][o.second[i]].spent) continue; res += outs[o.first][o.second[i]].amount; } } return res; } void get_confirmed_txs(const std::vector<currency::block>& blockchain, const map_hash2tx_t& mtx, map_hash2tx_t& confirmed_txs) { std::unordered_set<crypto::hash> confirmed_hashes; BOOST_FOREACH(const block& blk, blockchain) { BOOST_FOREACH(const crypto::hash& tx_hash, blk.tx_hashes) { confirmed_hashes.insert(tx_hash); } } BOOST_FOREACH(const auto& tx_pair, mtx) { if (0 != confirmed_hashes.count(tx_pair.first)) { confirmed_txs.insert(tx_pair); } } } bool find_block_chain(const std::vector<test_event_entry>& events, std::vector<currency::block>& blockchain, map_hash2tx_t& mtx, const crypto::hash& head) { std::unordered_map<crypto::hash, const block*> block_index; BOOST_FOREACH(const test_event_entry& ev, events) { if (typeid(block) == ev.type()) { const block* blk = &boost::get<block>(ev); block_index[get_block_hash(*blk)] = blk; } else if (typeid(transaction) == ev.type()) { const transaction& tx = boost::get<transaction>(ev); mtx[get_transaction_hash(tx)] = &tx; } } bool b_success = false; crypto::hash id = head; for (auto it = block_index.find(id); block_index.end() != it; it = block_index.find(id)) { blockchain.push_back(*it->second); id = it->second->prev_id; if (null_hash == id) { b_success = true; break; } } reverse(blockchain.begin(), blockchain.end()); return b_success; } void test_chain_unit_base::register_callback(const std::string& cb_name, verify_callback cb) { m_callbacks[cb_name] = cb; } bool test_chain_unit_base::verify(const std::string& cb_name, currency::core& c, size_t ev_index, const std::vector<test_event_entry> &events) { auto cb_it = m_callbacks.find(cb_name); if(cb_it == m_callbacks.end()) { LOG_ERROR("Failed to find callback " << cb_name); return false; } return cb_it->second(c, ev_index, events); }
1blockologist/boolberry
tests/core_tests/chaingen.cpp
C++
lgpl-3.0
28,375
// -*- mode: c++; c-basic-style: "bsd"; c-basic-offset: 4; -*- /* * ecore/EParameterImpl.cpp * Copyright (C) Cátedra SAES-UMU 2010 <andres.senac@um.es> * * EMF4CPP is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EMF4CPP is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "EParameter.hpp" #include <ecore/EcorePackage.hpp> #include <ecore/ETypedElement.hpp> #include <ecore/EAnnotation.hpp> #include <ecore/EClassifier.hpp> #include <ecore/EGenericType.hpp> #include <ecore/EOperation.hpp> #include <ecore/EObject.hpp> #include <ecore/EClass.hpp> #include <ecore/EStructuralFeature.hpp> #include <ecore/EReference.hpp> #include <ecore/EObject.hpp> #include <ecorecpp/mapping.hpp> using namespace ::ecore; /*PROTECTED REGION ID(EParameterImpl.cpp) START*/ // Please, enable the protected region if you add manually written code. // To do this, add the keyword ENABLED before START. /*PROTECTED REGION END*/ void EParameter::_initialize() { // Supertypes ::ecore::ETypedElement::_initialize(); // Rerefences /*PROTECTED REGION ID(EParameterImpl__initialize) START*/ // Please, enable the protected region if you add manually written code. // To do this, add the keyword ENABLED before START. /*PROTECTED REGION END*/ } // Operations // EObject ::ecore::EJavaObject EParameter::eGet(::ecore::EInt _featureID, ::ecore::EBoolean _resolve) { ::ecore::EJavaObject _any; switch (_featureID) { case ::ecore::EcorePackage::EMODELELEMENT__EANNOTATIONS: { _any = m_eAnnotations->asEListOf< ::ecore::EObject > (); } return _any; case ::ecore::EcorePackage::ENAMEDELEMENT__NAME: { ::ecorecpp::mapping::any_traits< ::ecore::EString >::toAny(_any, m_name); } return _any; case ::ecore::EcorePackage::ETYPEDELEMENT__ORDERED: { ::ecorecpp::mapping::any_traits< ::ecore::EBoolean >::toAny(_any, m_ordered); } return _any; case ::ecore::EcorePackage::ETYPEDELEMENT__UNIQUE: { ::ecorecpp::mapping::any_traits< ::ecore::EBoolean >::toAny(_any, m_unique); } return _any; case ::ecore::EcorePackage::ETYPEDELEMENT__LOWERBOUND: { ::ecorecpp::mapping::any_traits< ::ecore::EInt >::toAny(_any, m_lowerBound); } return _any; case ::ecore::EcorePackage::ETYPEDELEMENT__UPPERBOUND: { ::ecorecpp::mapping::any_traits< ::ecore::EInt >::toAny(_any, m_upperBound); } return _any; case ::ecore::EcorePackage::ETYPEDELEMENT__ETYPE: { _any = static_cast< ::ecore::EObject* > (m_eType); } return _any; case ::ecore::EcorePackage::ETYPEDELEMENT__EGENERICTYPE: { _any = static_cast< ::ecore::EObject* > (m_eGenericType); } return _any; case ::ecore::EcorePackage::EPARAMETER__EOPERATION: { _any = static_cast< ::ecore::EObject* > (m_eOperation); } return _any; } throw "Error"; } void EParameter::eSet(::ecore::EInt _featureID, ::ecore::EJavaObject const& _newValue) { switch (_featureID) { case ::ecore::EcorePackage::EMODELELEMENT__EANNOTATIONS: { ::ecorecpp::mapping::EList_ptr _t0 = ::ecorecpp::mapping::any::any_cast< ::ecorecpp::mapping::EList_ptr >(_newValue); ::ecore::EModelElement::getEAnnotations().clear(); ::ecore::EModelElement::getEAnnotations().insert_all(*_t0); } return; case ::ecore::EcorePackage::ENAMEDELEMENT__NAME: { ::ecorecpp::mapping::any_traits< ::ecore::EString >::fromAny(_newValue, m_name); } return; case ::ecore::EcorePackage::ETYPEDELEMENT__ORDERED: { ::ecorecpp::mapping::any_traits< ::ecore::EBoolean >::fromAny( _newValue, m_ordered); } return; case ::ecore::EcorePackage::ETYPEDELEMENT__UNIQUE: { ::ecorecpp::mapping::any_traits< ::ecore::EBoolean >::fromAny( _newValue, m_unique); } return; case ::ecore::EcorePackage::ETYPEDELEMENT__LOWERBOUND: { ::ecorecpp::mapping::any_traits< ::ecore::EInt >::fromAny(_newValue, m_lowerBound); } return; case ::ecore::EcorePackage::ETYPEDELEMENT__UPPERBOUND: { ::ecorecpp::mapping::any_traits< ::ecore::EInt >::fromAny(_newValue, m_upperBound); } return; case ::ecore::EcorePackage::ETYPEDELEMENT__ETYPE: { ::ecore::EObject_ptr _t0 = ::ecorecpp::mapping::any::any_cast< ::ecore::EObject_ptr >(_newValue); ::ecore::EClassifier_ptr _t1 = dynamic_cast< ::ecore::EClassifier_ptr > (_t0); ::ecore::ETypedElement::setEType(_t1); } return; case ::ecore::EcorePackage::ETYPEDELEMENT__EGENERICTYPE: { ::ecore::EObject_ptr _t0 = ::ecorecpp::mapping::any::any_cast< ::ecore::EObject_ptr >(_newValue); ::ecore::EGenericType_ptr _t1 = dynamic_cast< ::ecore::EGenericType_ptr > (_t0); ::ecore::ETypedElement::setEGenericType(_t1); } return; case ::ecore::EcorePackage::EPARAMETER__EOPERATION: { ::ecore::EObject_ptr _t0 = ::ecorecpp::mapping::any::any_cast< ::ecore::EObject_ptr >(_newValue); ::ecore::EOperation_ptr _t1 = dynamic_cast< ::ecore::EOperation_ptr > (_t0); ::ecore::EParameter::setEOperation(_t1); } return; } throw "Error"; } ::ecore::EBoolean EParameter::eIsSet(::ecore::EInt _featureID) { switch (_featureID) { case ::ecore::EcorePackage::EMODELELEMENT__EANNOTATIONS: return m_eAnnotations && m_eAnnotations->size(); case ::ecore::EcorePackage::ENAMEDELEMENT__NAME: return ::ecorecpp::mapping::set_traits< ::ecore::EString >::is_set( m_name); case ::ecore::EcorePackage::ETYPEDELEMENT__ORDERED: return m_ordered != true; case ::ecore::EcorePackage::ETYPEDELEMENT__UNIQUE: return m_unique != true; case ::ecore::EcorePackage::ETYPEDELEMENT__LOWERBOUND: return ::ecorecpp::mapping::set_traits< ::ecore::EInt >::is_set( m_lowerBound); case ::ecore::EcorePackage::ETYPEDELEMENT__UPPERBOUND: return m_upperBound != 1; case ::ecore::EcorePackage::ETYPEDELEMENT__MANY: return ::ecorecpp::mapping::set_traits< ::ecore::EBoolean >::is_set( m_many); case ::ecore::EcorePackage::ETYPEDELEMENT__REQUIRED: return ::ecorecpp::mapping::set_traits< ::ecore::EBoolean >::is_set( m_required); case ::ecore::EcorePackage::ETYPEDELEMENT__ETYPE: return m_eType; case ::ecore::EcorePackage::ETYPEDELEMENT__EGENERICTYPE: return m_eGenericType; case ::ecore::EcorePackage::EPARAMETER__EOPERATION: return m_eOperation; } throw "Error"; } void EParameter::eUnset(::ecore::EInt _featureID) { switch (_featureID) { } throw "Error"; } ::ecore::EClass_ptr EParameter::_eClass() { static ::ecore::EClass_ptr _eclass = dynamic_cast< ::ecore::EcorePackage_ptr > (::ecore::EcorePackage::_instance())->getEParameter(); return _eclass; }
wurfkeks/emf4cpp
emf4cpp/ecore/EParameterImpl.cpp
C++
lgpl-3.0
7,909
/* This source file is part of KBEngine For the latest info, see http://www.kbengine.org/ Copyright (c) 2008-2012 KBEngine. KBEngine is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. KBEngine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with KBEngine. If not, see <http://www.gnu.org/licenses/>. */ #ifndef KBE_INSTALL_PY_DLLS_HPP #define KBE_INSTALL_PY_DLLS_HPP namespace KBEngine{ namespace script{ bool install_py_dlls(void); bool uninstall_py_dlls(void); } } #endif // KBE_INSTALL_PY_DLLS_HPP
75651/kbengine_cloud
kbe/src/lib/pyscript/install_py_dlls.hpp
C++
lgpl-3.0
954
package com.samepage.view; import java.util.List; import com.samepage.model.EmpDTO; public class EmpView { public static void print(String title, List<EmpDTO> emplist){ System.out.println(title + ">>========== ¿©·¯°Ç Ãâ·Â ===========<<"); for (EmpDTO empDTO : emplist) { System.out.println(empDTO); } } public static void printOne(String title, EmpDTO empDTO){ System.out.println(title + ">>========== ÇÑ°Ç Ãâ·Â ===========<<"); System.out.println(empDTO); } public static void sysMessage(String message){ System.out.println(message); } }
qfactor2013/BizStudyParallel
DB/Day5/src/com/samepage/view/EmpView.java
Java
lgpl-3.0
569
/* * FindBugs - Find bugs in Java programs * Copyright (C) 2003,2004 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.detect; import java.util.*; import edu.umd.cs.findbugs.*; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.visitclass.AnnotationVisitor; import org.apache.bcel.Repository; import org.apache.bcel.classfile.*; import edu.umd.cs.findbugs.visitclass.Constants2; import static edu.umd.cs.findbugs.visitclass.Constants2.*; public class NoteSuppressedWarnings extends AnnotationVisitor implements Detector, Constants2 { private static Set<String> packages = new HashSet<String>(); private SuppressionMatcher suppressionMatcher; private BugReporter bugReporter; private AnalysisContext analysisContext; private NoteSuppressedWarnings recursiveDetector; public NoteSuppressedWarnings(BugReporter bugReporter) { this(bugReporter, false); } public NoteSuppressedWarnings(BugReporter bugReporter, boolean recursive) { if (!recursive) { DelegatingBugReporter b = (DelegatingBugReporter) bugReporter; BugReporter origBugReporter = b.getRealBugReporter(); suppressionMatcher = new SuppressionMatcher(); BugReporter filterBugReporter = new FilterBugReporter(origBugReporter, suppressionMatcher, false); b.setRealBugReporter(filterBugReporter); recursiveDetector = new NoteSuppressedWarnings(bugReporter,true); recursiveDetector.suppressionMatcher = suppressionMatcher; } this.bugReporter = bugReporter; } public void setAnalysisContext(AnalysisContext analysisContext) { this.analysisContext = analysisContext; } public void visitClassContext(ClassContext classContext) { classContext.getJavaClass().accept(this); } public void visit(JavaClass obj) { if (recursiveDetector == null) return; try { if (getClassName().endsWith("package-info")) return; String packageName = getPackageName().replace('/', '.'); if (!packages.add(packageName)) return; String packageInfo = "package-info"; if (packageName.length() > 0) packageInfo = packageName + "." + packageInfo; JavaClass packageInfoClass = Repository.lookupClass(packageInfo); recursiveDetector.visitJavaClass(packageInfoClass); } catch (ClassNotFoundException e) { // ignore } } public void visitAnnotation(String annotationClass, Map<String, Object> map, boolean runtimeVisible) { if (!annotationClass.endsWith("SuppressWarnings")) return; Object value = map.get("value"); if (value == null || !(value instanceof Object[])) { suppressWarning(null); return; } Object [] suppressedWarnings = (Object[]) value; if (suppressedWarnings.length == 0) suppressWarning(null); else for(int i = 0; i < suppressedWarnings.length; i++) suppressWarning((String)suppressedWarnings[i]); } private void suppressWarning(String pattern) { String className = getDottedClassName(); ClassAnnotation clazz = new ClassAnnotation(getDottedClassName()); if (className.endsWith("package-info") && recursiveDetector == null) suppressionMatcher.addPackageSuppressor( new PackageWarningSuppressor(pattern, getPackageName().replace('/', '.'))); else if (visitingMethod()) suppressionMatcher.addSuppressor( new MethodWarningSuppressor(pattern, clazz, MethodAnnotation.fromVisitedMethod(this))); else if (visitingField()) suppressionMatcher.addSuppressor( new FieldWarningSuppressor(pattern, clazz, FieldAnnotation.fromVisitedField(this))); else suppressionMatcher.addSuppressor( new ClassWarningSuppressor(pattern, clazz)); } public void report() { } }
simeshev/parabuild-ci
3rdparty/findbugs086src/src/java/edu/umd/cs/findbugs/detect/NoteSuppressedWarnings.java
Java
lgpl-3.0
4,473
using System; using System.Net; using System.Net.Sockets; using JetBrains.Annotations; using NetMQ.Sockets; namespace NetMQ { /// <summary> /// A NetMQBeaconEventArgs is an EventArgs that provides a property that holds a NetMQBeacon. /// </summary> public class NetMQBeaconEventArgs : EventArgs { /// <summary> /// Create a new NetMQBeaconEventArgs object containing the given NetMQBeacon. /// </summary> /// <param name="beacon">the NetMQBeacon object to hold a reference to</param> public NetMQBeaconEventArgs([NotNull] NetMQBeacon beacon) { Beacon = beacon; } /// <summary> /// Get the NetMQBeacon object that this holds. /// </summary> [NotNull] public NetMQBeacon Beacon { get; private set; } } public class NetMQBeacon : IDisposable, ISocketPollable { public const int UdpFrameMax = 255; public const string ConfigureCommand = "CONFIGURE"; public const string PublishCommand = "PUBLISH"; public const string SilenceCommand = "SILENCE"; /// <summary> /// Command to subscribe a socket to messages that have the given topic. This is valid only for Subscriber and XSubscriber sockets. /// </summary> public const string SubscribeCommand = "SUBSCRIBE"; /// <summary> /// Command to un-subscribe a socket from messages that have the given topic. This is valid only for Subscriber and XSubscriber sockets. /// </summary> public const string UnsubscribeCommand = "UNSUBSCRIBE"; #region Nested class: Shim private sealed class Shim : IShimHandler { private NetMQSocket m_pipe; private Socket m_udpSocket; private int m_udpPort; private EndPoint m_broadcastAddress; private NetMQFrame m_transmit; private NetMQFrame m_filter; private NetMQTimer m_pingTimer; private NetMQPoller m_poller; private void Configure([NotNull] string interfaceName, int port) { // In case the beacon was configured twice if (m_udpSocket != null) { m_poller.Remove(m_udpSocket); m_udpSocket.Close(); } m_udpPort = port; m_udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); m_poller.Add(m_udpSocket, OnUdpReady); // Ask operating system for broadcast permissions on socket m_udpSocket.EnableBroadcast = true; // Allow multiple owners to bind to socket; incoming // messages will replicate to each owner m_udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); IPAddress bindTo = null; IPAddress sendTo = null; if (interfaceName == "*") { bindTo = IPAddress.Any; sendTo = IPAddress.Broadcast; } else if (interfaceName == "loopback") { bindTo = IPAddress.Loopback; sendTo = IPAddress.Broadcast; } else { var interfaceCollection = new InterfaceCollection(); var interfaceAddress = !string.IsNullOrEmpty(interfaceName) ? IPAddress.Parse(interfaceName) : null; foreach (var @interface in interfaceCollection) { if (interfaceAddress == null || @interface.Address.Equals(interfaceAddress)) { sendTo = @interface.BroadcastAddress; bindTo = @interface.Address; break; } } } if (bindTo != null) { m_broadcastAddress = new IPEndPoint(sendTo, m_udpPort); m_udpSocket.Bind(new IPEndPoint(bindTo, m_udpPort)); } m_pipe.SendFrame(bindTo == null ? "" : bindTo.ToString()); } private static bool Compare([NotNull] NetMQFrame a, [NotNull] NetMQFrame b, int size) { for (int i = 0; i < size; i++) { if (a.Buffer[i] != b.Buffer[i]) return false; } return true; } public void Run(PairSocket shim) { m_pipe = shim; shim.SignalOK(); m_pipe.ReceiveReady += OnPipeReady; m_pingTimer = new NetMQTimer(interval: TimeSpan.Zero); m_pingTimer.Elapsed += PingElapsed; m_pingTimer.Enable = false; using (m_poller = new NetMQPoller { m_pipe, m_pingTimer }) { m_poller.Run(); } // the beacon might never been configured if (m_udpSocket != null) m_udpSocket.Close(); } private void PingElapsed(object sender, NetMQTimerEventArgs e) { SendUdpFrame(m_transmit); } private void OnUdpReady(Socket socket) { string peerName; var frame = ReceiveUdpFrame(out peerName); // If filter is set, check that beacon matches it bool isValid = false; if (m_filter != null) { if (frame.MessageSize >= m_filter.MessageSize && Compare(frame, m_filter, m_filter.MessageSize)) { isValid = true; } } // If valid, discard our own broadcasts, which UDP echoes to us if (isValid && m_transmit != null) { if (frame.MessageSize == m_transmit.MessageSize && Compare(frame, m_transmit, m_transmit.MessageSize)) { isValid = false; } } // If still a valid beacon, send on to the API if (isValid) { m_pipe.SendMoreFrame(peerName).SendFrame(frame.Buffer, frame.MessageSize); } } private void OnPipeReady(object sender, NetMQSocketEventArgs e) { NetMQMessage message = m_pipe.ReceiveMultipartMessage(); string command = message.Pop().ConvertToString(); switch (command) { case ConfigureCommand: string interfaceName = message.Pop().ConvertToString(); int port = message.Pop().ConvertToInt32(); Configure(interfaceName, port); break; case PublishCommand: m_transmit = message.Pop(); m_pingTimer.Interval = message.Pop().ConvertToInt32(); m_pingTimer.Enable = true; SendUdpFrame(m_transmit); break; case SilenceCommand: m_transmit = null; m_pingTimer.Enable = false; break; case SubscribeCommand: m_filter = message.Pop(); break; case UnsubscribeCommand: m_filter = null; break; case NetMQActor.EndShimMessage: m_poller.Stop(); break; default: throw new ArgumentOutOfRangeException(); } } private void SendUdpFrame(NetMQFrame frame) { m_udpSocket.SendTo(frame.Buffer, 0, frame.MessageSize, SocketFlags.None, m_broadcastAddress); } private NetMQFrame ReceiveUdpFrame(out string peerName) { var buffer = new byte[UdpFrameMax]; EndPoint peer = new IPEndPoint(IPAddress.Any, 0); int bytesRead = m_udpSocket.ReceiveFrom(buffer, ref peer); var frame = new NetMQFrame(bytesRead); Buffer.BlockCopy(buffer, 0, frame.Buffer, 0, bytesRead); peerName = peer.ToString(); return frame; } } #endregion private readonly NetMQActor m_actor; private readonly EventDelegator<NetMQBeaconEventArgs> m_receiveEvent; [CanBeNull] private string m_boundTo; /// <summary> /// Create a new NetMQBeacon, contained within the given context. /// </summary> /// <param name="context">the NetMQContext to contain this new socket</param> [Obsolete("Use non context version. This will be removed in NetMQ 4.0.")] public NetMQBeacon([NotNull] NetMQContext context) { m_actor = NetMQActor.Create(context, new Shim()); EventHandler<NetMQActorEventArgs> onReceive = (sender, e) => m_receiveEvent.Fire(this, new NetMQBeaconEventArgs(this)); m_receiveEvent = new EventDelegator<NetMQBeaconEventArgs>( () => m_actor.ReceiveReady += onReceive, () => m_actor.ReceiveReady -= onReceive); } /// <summary> /// Create a new NetMQBeacon. /// </summary> public NetMQBeacon() { m_actor = NetMQActor.Create(new Shim()); EventHandler<NetMQActorEventArgs> onReceive = (sender, e) => m_receiveEvent.Fire(this, new NetMQBeaconEventArgs(this)); m_receiveEvent = new EventDelegator<NetMQBeaconEventArgs>( () => m_actor.ReceiveReady += onReceive, () => m_actor.ReceiveReady -= onReceive); } /// <summary> /// Get the host name this beacon is bound to. /// </summary> /// <remarks> /// This may involve a reverse DNS lookup which can take a second or two. /// <para/> /// An empty string is returned if: /// <list type="bullet"> /// <item>the beacon is not bound,</item> /// <item>the beacon is bound to all interfaces,</item> /// <item>an error occurred during reverse DNS lookup.</item> /// </list> /// </remarks> [CanBeNull] public string HostName { get { // create a copy for thread safety var boundTo = m_boundTo; if (boundTo == null) return null; if (IPAddress.Any.ToString() == boundTo || IPAddress.IPv6Any.ToString() == boundTo) return string.Empty; try { return Dns.GetHostEntry(boundTo).HostName; } catch { return string.Empty; } } } /// <summary> /// Get the socket of the contained actor. /// </summary> NetMQSocket ISocketPollable.Socket { get { return ((ISocketPollable)m_actor).Socket; } } /// <summary> /// This event occurs when at least one message may be received from the socket without blocking. /// </summary> public event EventHandler<NetMQBeaconEventArgs> ReceiveReady { add { m_receiveEvent.Event += value; } remove { m_receiveEvent.Event -= value; } } /// <summary> /// Configure beacon to bind to all interfaces /// </summary> /// <param name="port">Port to bind to</param> public void ConfigureAllInterfaces(int port) { Configure("*", port); } /// <summary> /// Configure beacon to bind to default interface /// </summary> /// <param name="port">Port to bind to</param> public void Configure(int port) { Configure("", port); } /// <summary> /// Configure beacon to bind to specific interface /// </summary> /// <param name="interfaceName">One of the ip address of the interface</param> /// <param name="port">Port to bind to</param> public void Configure([NotNull] string interfaceName, int port) { var message = new NetMQMessage(); message.Append(ConfigureCommand); message.Append(interfaceName); message.Append(port); m_actor.SendMultipartMessage(message); m_boundTo = m_actor.ReceiveFrameString(); } /// <summary> /// Publish beacon immediately and continue to publish when interval elapsed /// </summary> /// <param name="transmit">Beacon to transmit</param> /// <param name="interval">Interval to transmit beacon</param> public void Publish([NotNull] string transmit, TimeSpan interval) { var message = new NetMQMessage(); message.Append(PublishCommand); message.Append(transmit); message.Append((int)interval.TotalMilliseconds); m_actor.SendMultipartMessage(message); } /// <summary> /// Publish beacon immediately and continue to publish when interval elapsed /// </summary> /// <param name="transmit">Beacon to transmit</param> /// <param name="interval">Interval to transmit beacon</param> public void Publish([NotNull] byte[] transmit, TimeSpan interval) { var message = new NetMQMessage(); message.Append(PublishCommand); message.Append(transmit); message.Append((int)interval.TotalMilliseconds); m_actor.SendMultipartMessage(message); } /// <summary> /// Publish beacon immediately and continue to publish every second /// </summary> /// <param name="transmit">Beacon to transmit</param> public void Publish([NotNull] string transmit) { Publish(transmit, TimeSpan.FromSeconds(1)); } /// <summary> /// Publish beacon immediately and continue to publish every second /// </summary> /// <param name="transmit">Beacon to transmit</param> public void Publish([NotNull] byte[] transmit) { Publish(transmit, TimeSpan.FromSeconds(1)); } /// <summary> /// Stop publish messages /// </summary> public void Silence() { m_actor.SendFrame(SilenceCommand); } /// <summary> /// Subscribe to beacon messages, will replace last subscribe call /// </summary> /// <param name="filter">Beacon will be filtered by this</param> public void Subscribe([NotNull] string filter) { m_actor.SendMoreFrame(SubscribeCommand).SendFrame(filter); } /// <summary> /// Unsubscribe to beacon messages /// </summary> public void Unsubscribe() { m_actor.SendFrame(UnsubscribeCommand); } /// <summary> /// Blocks until a string is received. As the returning of this method is uncontrollable, it's /// normally safer to call <see cref="TryReceiveString"/> instead and pass a timeout. /// </summary> /// <param name="peerName">the name of the peer, which should come before the actual message, is written to this string</param> /// <returns>the string that was received</returns> [NotNull] public string ReceiveString(out string peerName) { peerName = m_actor.ReceiveFrameString(); return m_actor.ReceiveFrameString(); } /// <summary> /// Attempt to receive a message from the specified peer for the specified amount of time. /// </summary> /// <param name="timeout">The maximum amount of time the call should wait for a message before returning.</param> /// <param name="peerName">the name of the peer that the message comes from is written to this string</param> /// <param name="message">the string to write the received message into</param> /// <returns><c>true</c> if a message was received before <paramref name="timeout"/> elapsed, /// otherwise <c>false</c>.</returns> public bool TryReceiveString(TimeSpan timeout, out string peerName, out string message) { if (!m_actor.TryReceiveFrameString(timeout, out peerName)) { message = null; return false; } return m_actor.TryReceiveFrameString(timeout, out message); } /// <summary> /// Blocks until a message is received. As the returning of this method is uncontrollable, it's /// normally safer to call <see cref="TryReceiveString"/> instead and pass a timeout. /// </summary> /// <param name="peerName">the name of the peer, which should come before the actual message, is written to this string</param> /// <returns>the byte-array of data that was received</returns> [NotNull] public byte[] Receive(out string peerName) { peerName = m_actor.ReceiveFrameString(); return m_actor.ReceiveFrameBytes(); } /// <summary> /// Release any contained resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Release any contained resources. /// </summary> /// <param name="disposing">true if managed resources are to be released</param> protected virtual void Dispose(bool disposing) { if (!disposing) return; m_actor.Dispose(); m_receiveEvent.Dispose(); } } }
NetMQ/NetMQ3-x
src/NetMQ/NetMQBeacon.cs
C#
lgpl-3.0
18,652
package org.xacml4j.v30.pdp; /* * #%L * Xacml4J Core Engine Implementation * %% * Copyright (C) 2009 - 2014 Xacml4J.org * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ import java.util.ListIterator; import org.xacml4j.v30.Expression; import org.xacml4j.v30.ValueType; import org.xacml4j.v30.spi.function.FunctionParamSpecVisitor; public interface FunctionParamSpec { /** * Validates if the "sequence" of expressions * from the current position is valid according * this specification. Iterator will be advanced to * the next expression after "sequence" * * @param it an iterator * @return {@code true} if sequence of * expressions starting at the current position * is valid according this spec */ boolean validate(ListIterator<Expression> it); Expression getDefaultValue(); boolean isOptional(); /** * Tests if instances of a given value type * can be used as values for a function * parameter specified by this specification * * @param type a value type * @return {@code true} */ boolean isValidParamType(ValueType type); /** * Tests if this parameter is variadic * * @return {@code true} if a function * parameter represented by this object is * variadic */ boolean isVariadic(); void accept(FunctionParamSpecVisitor v); }
snmaher/xacml4j
xacml-core/src/main/java/org/xacml4j/v30/pdp/FunctionParamSpec.java
Java
lgpl-3.0
1,952
/////////////////////////////////////////////////////////////////////////////// // Name: src/msw/gdiplus.cpp // Purpose: implements wrappers for GDI+ flat API // Author: Vadim Zeitlin // Created: 2007-03-14 // Copyright: (c) 2007 Vadim Zeitlin <vadim@wxwindows.org> // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // for compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_GRAPHICS_CONTEXT #ifndef WX_PRECOMP #include "wx/cpp.h" #include "wx/log.h" #include "wx/module.h" #include "wx/string.h" #endif // WX_PRECOMP #include "wx/dynload.h" #include "wx/msw/wrapgdip.h" // w32api headers used by both MinGW and Cygwin wrongly define UINT16 inside // Gdiplus namespace in gdiplus.h which results in ambiguity errors when using // this type as UINT16 is also defined in global scope by windows.h (or rather // basetsd.h included from it), so we redefine it to work around this problem. #if defined(__CYGWIN__) || defined(__MINGW32__) #define UINT16 unsigned short #endif // ---------------------------------------------------------------------------- // helper macros // ---------------------------------------------------------------------------- // return the name we use for the type of the function with the given name // (without "Gdip" prefix) #define wxGDIPLUS_FUNC_T(name) Gdip##name##_t // to avoid repeating all (several hundreds) of GDI+ functions names several // times in this file, we define a macro which allows us to apply another macro // to all (or almost all, as we sometimes have to handle functions not // returning GpStatus separately) these functions at once // this macro expands into an invocation of the given macro m for all GDI+ // functions returning standard GpStatus // // m is called with the name of the function without "Gdip" prefix as the first // argument, the list of function parameters with their names as the second one // and the list of just the parameter names as the third one #define wxFOR_ALL_GDIPLUS_STATUS_FUNCS(m) \ m(CreatePath, (GpFillMode brushMode, GpPath **path), (brushMode, path)) \ m(CreatePath2, (GDIPCONST GpPointF* a1, GDIPCONST BYTE* a2, INT a3, GpFillMode a4, GpPath **path), (a1, a2, a3, a4, path)) \ m(CreatePath2I, (GDIPCONST GpPoint* a1, GDIPCONST BYTE* a2, INT a3, GpFillMode a4, GpPath **path), (a1, a2, a3, a4, path)) \ m(ClonePath, (GpPath* path, GpPath **clonePath), (path, clonePath)) \ m(DeletePath, (GpPath* path), (path)) \ m(ResetPath, (GpPath* path), (path)) \ m(GetPointCount, (GpPath* path, INT* count), (path, count)) \ m(GetPathTypes, (GpPath* path, BYTE* types, INT count), (path, types, count)) \ m(GetPathPoints, (GpPath* a1, GpPointF* points, INT count), (a1, points, count)) \ m(GetPathPointsI, (GpPath* a1, GpPoint* points, INT count), (a1, points, count)) \ m(GetPathFillMode, (GpPath *path, GpFillMode *fillmode), (path, fillmode)) \ m(SetPathFillMode, (GpPath *path, GpFillMode fillmode), (path, fillmode)) \ m(GetPathData, (GpPath *path, GpPathData* pathData), (path, pathData)) \ m(StartPathFigure, (GpPath *path), (path)) \ m(ClosePathFigure, (GpPath *path), (path)) \ m(ClosePathFigures, (GpPath *path), (path)) \ m(SetPathMarker, (GpPath* path), (path)) \ m(ClearPathMarkers, (GpPath* path), (path)) \ m(ReversePath, (GpPath* path), (path)) \ m(GetPathLastPoint, (GpPath* path, GpPointF* lastPoint), (path, lastPoint)) \ m(AddPathLine, (GpPath *path, REAL x1, REAL y1, REAL x2, REAL y2), (path, x1, y1, x2, y2)) \ m(AddPathLine2, (GpPath *path, GDIPCONST GpPointF *points, INT count), (path, points, count)) \ m(AddPathArc, (GpPath *path, REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle), (path, x, y, width, height, startAngle, sweepAngle)) \ m(AddPathBezier, (GpPath *path, REAL x1, REAL y1, REAL x2, REAL y2, REAL x3, REAL y3, REAL x4, REAL y4), (path, x1, y1, x2, y2, x3, y3, x4, y4)) \ m(AddPathBeziers, (GpPath *path, GDIPCONST GpPointF *points, INT count), (path, points, count)) \ m(AddPathCurve, (GpPath *path, GDIPCONST GpPointF *points, INT count), (path, points, count)) \ m(AddPathCurve2, (GpPath *path, GDIPCONST GpPointF *points, INT count, REAL tension), (path, points, count, tension)) \ m(AddPathCurve3, (GpPath *path, GDIPCONST GpPointF *points, INT count, INT offset, INT numberOfSegments, REAL tension), (path, points, count, offset, numberOfSegments, tension)) \ m(AddPathClosedCurve, (GpPath *path, GDIPCONST GpPointF *points, INT count), (path, points, count)) \ m(AddPathClosedCurve2, (GpPath *path, GDIPCONST GpPointF *points, INT count, REAL tension), (path, points, count, tension)) \ m(AddPathRectangle, (GpPath *path, REAL x, REAL y, REAL width, REAL height), (path, x, y, width, height)) \ m(AddPathRectangles, (GpPath *path, GDIPCONST GpRectF *rects, INT count), (path, rects, count)) \ m(AddPathEllipse, (GpPath *path, REAL x, REAL y, REAL width, REAL height), (path, x, y, width, height)) \ m(AddPathPie, (GpPath *path, REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle), (path, x, y, width, height, startAngle, sweepAngle)) \ m(AddPathPolygon, (GpPath *path, GDIPCONST GpPointF *points, INT count), (path, points, count)) \ m(AddPathPath, (GpPath *path, GDIPCONST GpPath* addingPath, BOOL connect), (path, addingPath, connect)) \ m(AddPathString, (GpPath *path, GDIPCONST WCHAR *string, INT length, GDIPCONST GpFontFamily *family, INT style, REAL emSize, GDIPCONST RectF *layoutRect, GDIPCONST GpStringFormat *format), (path, string, length, family, style, emSize, layoutRect, format)) \ m(AddPathStringI, (GpPath *path, GDIPCONST WCHAR *string, INT length, GDIPCONST GpFontFamily *family, INT style, REAL emSize, GDIPCONST Rect *layoutRect, GDIPCONST GpStringFormat *format), (path, string, length, family, style, emSize, layoutRect, format)) \ m(AddPathLineI, (GpPath *path, INT x1, INT y1, INT x2, INT y2), (path, x1, y1, x2, y2)) \ m(AddPathLine2I, (GpPath *path, GDIPCONST GpPoint *points, INT count), (path, points, count)) \ m(AddPathArcI, (GpPath *path, INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle), (path, x, y, width, height, startAngle, sweepAngle)) \ m(AddPathBezierI, (GpPath *path, INT x1, INT y1, INT x2, INT y2, INT x3, INT y3, INT x4, INT y4), (path, x1, y1, x2, y2, x3, y3, x4, y4)) \ m(AddPathBeziersI, (GpPath *path, GDIPCONST GpPoint *points, INT count), (path, points, count)) \ m(AddPathCurveI, (GpPath *path, GDIPCONST GpPoint *points, INT count), (path, points, count)) \ m(AddPathCurve2I, (GpPath *path, GDIPCONST GpPoint *points, INT count, REAL tension), (path, points, count, tension)) \ m(AddPathCurve3I, (GpPath *path, GDIPCONST GpPoint *points, INT count, INT offset, INT numberOfSegments, REAL tension), (path, points, count, offset, numberOfSegments, tension)) \ m(AddPathClosedCurveI, (GpPath *path, GDIPCONST GpPoint *points, INT count), (path, points, count)) \ m(AddPathClosedCurve2I, (GpPath *path, GDIPCONST GpPoint *points, INT count, REAL tension), (path, points, count, tension)) \ m(AddPathRectangleI, (GpPath *path, INT x, INT y, INT width, INT height), (path, x, y, width, height)) \ m(AddPathRectanglesI, (GpPath *path, GDIPCONST GpRect *rects, INT count), (path, rects, count)) \ m(AddPathEllipseI, (GpPath *path, INT x, INT y, INT width, INT height), (path, x, y, width, height)) \ m(AddPathPieI, (GpPath *path, INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle), (path, x, y, width, height, startAngle, sweepAngle)) \ m(AddPathPolygonI, (GpPath *path, GDIPCONST GpPoint *points, INT count), (path, points, count)) \ m(FlattenPath, (GpPath *path, GpMatrix* matrix, REAL flatness), (path, matrix, flatness)) \ m(WindingModeOutline, (GpPath *path, GpMatrix *matrix, REAL flatness), (path, matrix, flatness)) \ m(WidenPath, (GpPath *nativePath, GpPen *pen, GpMatrix *matrix, REAL flatness), (nativePath, pen, matrix, flatness)) \ m(WarpPath, (GpPath *path, GpMatrix* matrix, GDIPCONST GpPointF *points, INT count, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight, WarpMode warpMode, REAL flatness), (path, matrix, points, count, srcx, srcy, srcwidth, srcheight, warpMode, flatness)) \ m(TransformPath, (GpPath* path, GpMatrix* matrix), (path, matrix)) \ m(GetPathWorldBounds, (GpPath* path, GpRectF* bounds, GDIPCONST GpMatrix *matrix, GDIPCONST GpPen *pen), (path, bounds, matrix, pen)) \ m(GetPathWorldBoundsI, (GpPath* path, GpRect* bounds, GDIPCONST GpMatrix *matrix, GDIPCONST GpPen *pen), (path, bounds, matrix, pen)) \ m(IsVisiblePathPoint, (GpPath* path, REAL x, REAL y, GpGraphics *graphics, BOOL *result), (path, x, y, graphics, result)) \ m(IsVisiblePathPointI, (GpPath* path, INT x, INT y, GpGraphics *graphics, BOOL *result), (path, x, y, graphics, result)) \ m(IsOutlineVisiblePathPoint, (GpPath* path, REAL x, REAL y, GpPen *pen, GpGraphics *graphics, BOOL *result), (path, x, y, pen, graphics, result)) \ m(IsOutlineVisiblePathPointI, (GpPath* path, INT x, INT y, GpPen *pen, GpGraphics *graphics, BOOL *result), (path, x, y, pen, graphics, result)) \ m(CreatePathIter, (GpPathIterator **iterator, GpPath* path), (iterator, path)) \ m(DeletePathIter, (GpPathIterator *iterator), (iterator)) \ m(PathIterNextSubpath, (GpPathIterator* iterator, INT *resultCount, INT* startIndex, INT* endIndex, BOOL* isClosed), (iterator, resultCount, startIndex, endIndex, isClosed)) \ m(PathIterNextSubpathPath, (GpPathIterator* iterator, INT* resultCount, GpPath* path, BOOL* isClosed), (iterator, resultCount, path, isClosed)) \ m(PathIterNextPathType, (GpPathIterator* iterator, INT* resultCount, BYTE* pathType, INT* startIndex, INT* endIndex), (iterator, resultCount, pathType, startIndex, endIndex)) \ m(PathIterNextMarker, (GpPathIterator* iterator, INT *resultCount, INT* startIndex, INT* endIndex), (iterator, resultCount, startIndex, endIndex)) \ m(PathIterNextMarkerPath, (GpPathIterator* iterator, INT* resultCount, GpPath* path), (iterator, resultCount, path)) \ m(PathIterGetCount, (GpPathIterator* iterator, INT* count), (iterator, count)) \ m(PathIterGetSubpathCount, (GpPathIterator* iterator, INT* count), (iterator, count)) \ m(PathIterIsValid, (GpPathIterator* iterator, BOOL* valid), (iterator, valid)) \ m(PathIterHasCurve, (GpPathIterator* iterator, BOOL* hasCurve), (iterator, hasCurve)) \ m(PathIterRewind, (GpPathIterator* iterator), (iterator)) \ m(PathIterEnumerate, (GpPathIterator* iterator, INT* resultCount, GpPointF *points, BYTE *types, INT count), (iterator, resultCount, points, types, count)) \ m(PathIterCopyData, (GpPathIterator* iterator, INT* resultCount, GpPointF* points, BYTE* types, INT startIndex, INT endIndex), (iterator, resultCount, points, types, startIndex, endIndex)) \ m(CreateMatrix, (GpMatrix **matrix), (matrix)) \ m(CreateMatrix2, (REAL m11, REAL m12, REAL m21, REAL m22, REAL dx, REAL dy, GpMatrix **matrix), (m11, m12, m21, m22, dx, dy, matrix)) \ m(CreateMatrix3, (GDIPCONST GpRectF *rect, GDIPCONST GpPointF *dstplg, GpMatrix **matrix), (rect, dstplg, matrix)) \ m(CreateMatrix3I, (GDIPCONST GpRect *rect, GDIPCONST GpPoint *dstplg, GpMatrix **matrix), (rect, dstplg, matrix)) \ m(CloneMatrix, (GpMatrix *matrix, GpMatrix **cloneMatrix), (matrix, cloneMatrix)) \ m(DeleteMatrix, (GpMatrix *matrix), (matrix)) \ m(SetMatrixElements, (GpMatrix *matrix, REAL m11, REAL m12, REAL m21, REAL m22, REAL dx, REAL dy), (matrix, m11, m12, m21, m22, dx, dy)) \ m(MultiplyMatrix, (GpMatrix *matrix, GpMatrix* matrix2, GpMatrixOrder order), (matrix, matrix2, order)) \ m(TranslateMatrix, (GpMatrix *matrix, REAL offsetX, REAL offsetY, GpMatrixOrder order), (matrix, offsetX, offsetY, order)) \ m(ScaleMatrix, (GpMatrix *matrix, REAL scaleX, REAL scaleY, GpMatrixOrder order), (matrix, scaleX, scaleY, order)) \ m(RotateMatrix, (GpMatrix *matrix, REAL angle, GpMatrixOrder order), (matrix, angle, order)) \ m(ShearMatrix, (GpMatrix *matrix, REAL shearX, REAL shearY, GpMatrixOrder order), (matrix, shearX, shearY, order)) \ m(InvertMatrix, (GpMatrix *matrix), (matrix)) \ m(TransformMatrixPoints, (GpMatrix *matrix, GpPointF *pts, INT count), (matrix, pts, count)) \ m(TransformMatrixPointsI, (GpMatrix *matrix, GpPoint *pts, INT count), (matrix, pts, count)) \ m(VectorTransformMatrixPoints, (GpMatrix *matrix, GpPointF *pts, INT count), (matrix, pts, count)) \ m(VectorTransformMatrixPointsI, (GpMatrix *matrix, GpPoint *pts, INT count), (matrix, pts, count)) \ m(GetMatrixElements, (GDIPCONST GpMatrix *matrix, REAL *matrixOut), (matrix, matrixOut)) \ m(IsMatrixInvertible, (GDIPCONST GpMatrix *matrix, BOOL *result), (matrix, result)) \ m(IsMatrixIdentity, (GDIPCONST GpMatrix *matrix, BOOL *result), (matrix, result)) \ m(IsMatrixEqual, (GDIPCONST GpMatrix *matrix, GDIPCONST GpMatrix *matrix2, BOOL *result), (matrix, matrix2, result)) \ m(CreateRegion, (GpRegion **region), (region)) \ m(CreateRegionRect, (GDIPCONST GpRectF *rect, GpRegion **region), (rect, region)) \ m(CreateRegionRectI, (GDIPCONST GpRect *rect, GpRegion **region), (rect, region)) \ m(CreateRegionPath, (GpPath *path, GpRegion **region), (path, region)) \ m(CreateRegionRgnData, (GDIPCONST BYTE *regionData, INT size, GpRegion **region), (regionData, size, region)) \ m(CreateRegionHrgn, (HRGN hRgn, GpRegion **region), (hRgn, region)) \ m(CloneRegion, (GpRegion *region, GpRegion **cloneRegion), (region, cloneRegion)) \ m(DeleteRegion, (GpRegion *region), (region)) \ m(SetInfinite, (GpRegion *region), (region)) \ m(SetEmpty, (GpRegion *region), (region)) \ m(CombineRegionRect, (GpRegion *region, GDIPCONST GpRectF *rect, CombineMode combineMode), (region, rect, combineMode)) \ m(CombineRegionRectI, (GpRegion *region, GDIPCONST GpRect *rect, CombineMode combineMode), (region, rect, combineMode)) \ m(CombineRegionPath, (GpRegion *region, GpPath *path, CombineMode combineMode), (region, path, combineMode)) \ m(CombineRegionRegion, (GpRegion *region, GpRegion *region2, CombineMode combineMode), (region, region2, combineMode)) \ m(TranslateRegion, (GpRegion *region, REAL dx, REAL dy), (region, dx, dy)) \ m(TranslateRegionI, (GpRegion *region, INT dx, INT dy), (region, dx, dy)) \ m(TransformRegion, (GpRegion *region, GpMatrix *matrix), (region, matrix)) \ m(GetRegionBounds, (GpRegion *region, GpGraphics *graphics, GpRectF *rect), (region, graphics, rect)) \ m(GetRegionBoundsI, (GpRegion *region, GpGraphics *graphics, GpRect *rect), (region, graphics, rect)) \ m(GetRegionHRgn, (GpRegion *region, GpGraphics *graphics, HRGN *hRgn), (region, graphics, hRgn)) \ m(IsEmptyRegion, (GpRegion *region, GpGraphics *graphics, BOOL *result), (region, graphics, result)) \ m(IsInfiniteRegion, (GpRegion *region, GpGraphics *graphics, BOOL *result), (region, graphics, result)) \ m(IsEqualRegion, (GpRegion *region, GpRegion *region2, GpGraphics *graphics, BOOL *result), (region, region2, graphics, result)) \ m(GetRegionDataSize, (GpRegion *region, UINT *bufferSize), (region, bufferSize)) \ m(GetRegionData, (GpRegion *region, BYTE *buffer, UINT bufferSize, UINT *sizeFilled), (region, buffer, bufferSize, sizeFilled)) \ m(IsVisibleRegionPoint, (GpRegion *region, REAL x, REAL y, GpGraphics *graphics, BOOL *result), (region, x, y, graphics, result)) \ m(IsVisibleRegionPointI, (GpRegion *region, INT x, INT y, GpGraphics *graphics, BOOL *result), (region, x, y, graphics, result)) \ m(IsVisibleRegionRect, (GpRegion *region, REAL x, REAL y, REAL width, REAL height, GpGraphics *graphics, BOOL *result), (region, x, y, width, height, graphics, result)) \ m(IsVisibleRegionRectI, (GpRegion *region, INT x, INT y, INT width, INT height, GpGraphics *graphics, BOOL *result), (region, x, y, width, height, graphics, result)) \ m(GetRegionScansCount, (GpRegion *region, UINT* count, GpMatrix* matrix), (region, count, matrix)) \ m(GetRegionScans, (GpRegion *region, GpRectF* rects, INT* count, GpMatrix* matrix), (region, rects, count, matrix)) \ m(GetRegionScansI, (GpRegion *region, GpRect* rects, INT* count, GpMatrix* matrix), (region, rects, count, matrix)) \ m(CloneBrush, (GpBrush *brush, GpBrush **cloneBrush), (brush, cloneBrush)) \ m(DeleteBrush, (GpBrush *brush), (brush)) \ m(GetBrushType, (GpBrush *brush, GpBrushType *type), (brush, type)) \ m(CreateHatchBrush, (GpHatchStyle hatchstyle, ARGB forecol, ARGB backcol, GpHatch **brush), (hatchstyle, forecol, backcol, brush)) \ m(GetHatchStyle, (GpHatch *brush, GpHatchStyle *hatchstyle), (brush, hatchstyle)) \ m(GetHatchForegroundColor, (GpHatch *brush, ARGB* forecol), (brush, forecol)) \ m(GetHatchBackgroundColor, (GpHatch *brush, ARGB* backcol), (brush, backcol)) \ m(CreateTexture, (GpImage *image, GpWrapMode wrapmode, GpTexture **texture), (image, wrapmode, texture)) \ m(CreateTexture2, (GpImage *image, GpWrapMode wrapmode, REAL x, REAL y, REAL width, REAL height, GpTexture **texture), (image, wrapmode, x, y, width, height, texture)) \ m(CreateTextureIA, (GpImage *image, GDIPCONST GpImageAttributes *imageAttributes, REAL x, REAL y, REAL width, REAL height, GpTexture **texture), (image, imageAttributes, x, y, width, height, texture)) \ m(CreateTexture2I, (GpImage *image, GpWrapMode wrapmode, INT x, INT y, INT width, INT height, GpTexture **texture), (image, wrapmode, x, y, width, height, texture)) \ m(CreateTextureIAI, (GpImage *image, GDIPCONST GpImageAttributes *imageAttributes, INT x, INT y, INT width, INT height, GpTexture **texture), (image, imageAttributes, x, y, width, height, texture)) \ m(GetTextureTransform, (GpTexture *brush, GpMatrix *matrix), (brush, matrix)) \ m(SetTextureTransform, (GpTexture *brush, GDIPCONST GpMatrix *matrix), (brush, matrix)) \ m(ResetTextureTransform, (GpTexture* brush), (brush)) \ m(MultiplyTextureTransform, (GpTexture* brush, GDIPCONST GpMatrix *matrix, GpMatrixOrder order), (brush, matrix, order)) \ m(TranslateTextureTransform, (GpTexture* brush, REAL dx, REAL dy, GpMatrixOrder order), (brush, dx, dy, order)) \ m(ScaleTextureTransform, (GpTexture* brush, REAL sx, REAL sy, GpMatrixOrder order), (brush, sx, sy, order)) \ m(RotateTextureTransform, (GpTexture* brush, REAL angle, GpMatrixOrder order), (brush, angle, order)) \ m(SetTextureWrapMode, (GpTexture *brush, GpWrapMode wrapmode), (brush, wrapmode)) \ m(GetTextureWrapMode, (GpTexture *brush, GpWrapMode *wrapmode), (brush, wrapmode)) \ m(GetTextureImage, (GpTexture *brush, GpImage **image), (brush, image)) \ m(CreateSolidFill, (ARGB color, GpSolidFill **brush), (color, brush)) \ m(SetSolidFillColor, (GpSolidFill *brush, ARGB color), (brush, color)) \ m(GetSolidFillColor, (GpSolidFill *brush, ARGB *color), (brush, color)) \ m(CreateLineBrush, (GDIPCONST GpPointF* point1, GDIPCONST GpPointF* point2, ARGB color1, ARGB color2, GpWrapMode wrapMode, GpLineGradient **lineGradient), (point1, point2, color1, color2, wrapMode, lineGradient)) \ m(CreateLineBrushI, (GDIPCONST GpPoint* point1, GDIPCONST GpPoint* point2, ARGB color1, ARGB color2, GpWrapMode wrapMode, GpLineGradient **lineGradient), (point1, point2, color1, color2, wrapMode, lineGradient)) \ m(CreateLineBrushFromRect, (GDIPCONST GpRectF* rect, ARGB color1, ARGB color2, LinearGradientMode mode, GpWrapMode wrapMode, GpLineGradient **lineGradient), (rect, color1, color2, mode, wrapMode, lineGradient)) \ m(CreateLineBrushFromRectI, (GDIPCONST GpRect* rect, ARGB color1, ARGB color2, LinearGradientMode mode, GpWrapMode wrapMode, GpLineGradient **lineGradient), (rect, color1, color2, mode, wrapMode, lineGradient)) \ m(CreateLineBrushFromRectWithAngle, (GDIPCONST GpRectF* rect, ARGB color1, ARGB color2, REAL angle, BOOL isAngleScalable, GpWrapMode wrapMode, GpLineGradient **lineGradient), (rect, color1, color2, angle, isAngleScalable, wrapMode, lineGradient)) \ m(CreateLineBrushFromRectWithAngleI, (GDIPCONST GpRect* rect, ARGB color1, ARGB color2, REAL angle, BOOL isAngleScalable, GpWrapMode wrapMode, GpLineGradient **lineGradient), (rect, color1, color2, angle, isAngleScalable, wrapMode, lineGradient)) \ m(SetLineColors, (GpLineGradient *brush, ARGB color1, ARGB color2), (brush, color1, color2)) \ m(GetLineColors, (GpLineGradient *brush, ARGB* colors), (brush, colors)) \ m(GetLineRect, (GpLineGradient *brush, GpRectF *rect), (brush, rect)) \ m(GetLineRectI, (GpLineGradient *brush, GpRect *rect), (brush, rect)) \ m(SetLineGammaCorrection, (GpLineGradient *brush, BOOL useGammaCorrection), (brush, useGammaCorrection)) \ m(GetLineGammaCorrection, (GpLineGradient *brush, BOOL *useGammaCorrection), (brush, useGammaCorrection)) \ m(GetLineBlendCount, (GpLineGradient *brush, INT *count), (brush, count)) \ m(GetLineBlend, (GpLineGradient *brush, REAL *blend, REAL* positions, INT count), (brush, blend, positions, count)) \ m(SetLineBlend, (GpLineGradient *brush, GDIPCONST REAL *blend, GDIPCONST REAL* positions, INT count), (brush, blend, positions, count)) \ m(GetLinePresetBlendCount, (GpLineGradient *brush, INT *count), (brush, count)) \ m(GetLinePresetBlend, (GpLineGradient *brush, ARGB *blend, REAL* positions, INT count), (brush, blend, positions, count)) \ m(SetLinePresetBlend, (GpLineGradient *brush, GDIPCONST ARGB *blend, GDIPCONST REAL* positions, INT count), (brush, blend, positions, count)) \ m(SetLineSigmaBlend, (GpLineGradient *brush, REAL focus, REAL scale), (brush, focus, scale)) \ m(SetLineLinearBlend, (GpLineGradient *brush, REAL focus, REAL scale), (brush, focus, scale)) \ m(SetLineWrapMode, (GpLineGradient *brush, GpWrapMode wrapmode), (brush, wrapmode)) \ m(GetLineWrapMode, (GpLineGradient *brush, GpWrapMode *wrapmode), (brush, wrapmode)) \ m(GetLineTransform, (GpLineGradient *brush, GpMatrix *matrix), (brush, matrix)) \ m(SetLineTransform, (GpLineGradient *brush, GDIPCONST GpMatrix *matrix), (brush, matrix)) \ m(ResetLineTransform, (GpLineGradient* brush), (brush)) \ m(MultiplyLineTransform, (GpLineGradient* brush, GDIPCONST GpMatrix *matrix, GpMatrixOrder order), (brush, matrix, order)) \ m(TranslateLineTransform, (GpLineGradient* brush, REAL dx, REAL dy, GpMatrixOrder order), (brush, dx, dy, order)) \ m(ScaleLineTransform, (GpLineGradient* brush, REAL sx, REAL sy, GpMatrixOrder order), (brush, sx, sy, order)) \ m(RotateLineTransform, (GpLineGradient* brush, REAL angle, GpMatrixOrder order), (brush, angle, order)) \ m(CreatePathGradient, (GDIPCONST GpPointF* points, INT count, GpWrapMode wrapMode, GpPathGradient **polyGradient), (points, count, wrapMode, polyGradient)) \ m(CreatePathGradientI, (GDIPCONST GpPoint* points, INT count, GpWrapMode wrapMode, GpPathGradient **polyGradient), (points, count, wrapMode, polyGradient)) \ m(CreatePathGradientFromPath, (GDIPCONST GpPath* path, GpPathGradient **polyGradient), (path, polyGradient)) \ m(GetPathGradientCenterColor, (GpPathGradient *brush, ARGB* colors), (brush, colors)) \ m(SetPathGradientCenterColor, (GpPathGradient *brush, ARGB colors), (brush, colors)) \ m(GetPathGradientSurroundColorsWithCount, (GpPathGradient *brush, ARGB* color, INT* count), (brush, color, count)) \ m(SetPathGradientSurroundColorsWithCount, (GpPathGradient *brush, GDIPCONST ARGB* color, INT* count), (brush, color, count)) \ m(GetPathGradientPath, (GpPathGradient *brush, GpPath *path), (brush, path)) \ m(SetPathGradientPath, (GpPathGradient *brush, GDIPCONST GpPath *path), (brush, path)) \ m(GetPathGradientCenterPoint, (GpPathGradient *brush, GpPointF* points), (brush, points)) \ m(GetPathGradientCenterPointI, (GpPathGradient *brush, GpPoint* points), (brush, points)) \ m(SetPathGradientCenterPoint, (GpPathGradient *brush, GDIPCONST GpPointF* points), (brush, points)) \ m(SetPathGradientCenterPointI, (GpPathGradient *brush, GDIPCONST GpPoint* points), (brush, points)) \ m(GetPathGradientRect, (GpPathGradient *brush, GpRectF *rect), (brush, rect)) \ m(GetPathGradientRectI, (GpPathGradient *brush, GpRect *rect), (brush, rect)) \ m(GetPathGradientPointCount, (GpPathGradient *brush, INT* count), (brush, count)) \ m(GetPathGradientSurroundColorCount, (GpPathGradient *brush, INT* count), (brush, count)) \ m(SetPathGradientGammaCorrection, (GpPathGradient *brush, BOOL useGammaCorrection), (brush, useGammaCorrection)) \ m(GetPathGradientGammaCorrection, (GpPathGradient *brush, BOOL *useGammaCorrection), (brush, useGammaCorrection)) \ m(GetPathGradientBlendCount, (GpPathGradient *brush, INT *count), (brush, count)) \ m(GetPathGradientBlend, (GpPathGradient *brush, REAL *blend, REAL *positions, INT count), (brush, blend, positions, count)) \ m(SetPathGradientBlend, (GpPathGradient *brush, GDIPCONST REAL *blend, GDIPCONST REAL *positions, INT count), (brush, blend, positions, count)) \ m(GetPathGradientPresetBlendCount, (GpPathGradient *brush, INT *count), (brush, count)) \ m(GetPathGradientPresetBlend, (GpPathGradient *brush, ARGB *blend, REAL* positions, INT count), (brush, blend, positions, count)) \ m(SetPathGradientPresetBlend, (GpPathGradient *brush, GDIPCONST ARGB *blend, GDIPCONST REAL* positions, INT count), (brush, blend, positions, count)) \ m(SetPathGradientSigmaBlend, (GpPathGradient *brush, REAL focus, REAL scale), (brush, focus, scale)) \ m(SetPathGradientLinearBlend, (GpPathGradient *brush, REAL focus, REAL scale), (brush, focus, scale)) \ m(GetPathGradientWrapMode, (GpPathGradient *brush, GpWrapMode *wrapmode), (brush, wrapmode)) \ m(SetPathGradientWrapMode, (GpPathGradient *brush, GpWrapMode wrapmode), (brush, wrapmode)) \ m(GetPathGradientTransform, (GpPathGradient *brush, GpMatrix *matrix), (brush, matrix)) \ m(SetPathGradientTransform, (GpPathGradient *brush, GpMatrix *matrix), (brush, matrix)) \ m(ResetPathGradientTransform, (GpPathGradient* brush), (brush)) \ m(MultiplyPathGradientTransform, (GpPathGradient* brush, GDIPCONST GpMatrix *matrix, GpMatrixOrder order), (brush, matrix, order)) \ m(TranslatePathGradientTransform, (GpPathGradient* brush, REAL dx, REAL dy, GpMatrixOrder order), (brush, dx, dy, order)) \ m(ScalePathGradientTransform, (GpPathGradient* brush, REAL sx, REAL sy, GpMatrixOrder order), (brush, sx, sy, order)) \ m(RotatePathGradientTransform, (GpPathGradient* brush, REAL angle, GpMatrixOrder order), (brush, angle, order)) \ m(GetPathGradientFocusScales, (GpPathGradient *brush, REAL* xScale, REAL* yScale), (brush, xScale, yScale)) \ m(SetPathGradientFocusScales, (GpPathGradient *brush, REAL xScale, REAL yScale), (brush, xScale, yScale)) \ m(CreatePen1, (ARGB color, REAL width, GpUnit unit, GpPen **pen), (color, width, unit, pen)) \ m(CreatePen2, (GpBrush *brush, REAL width, GpUnit unit, GpPen **pen), (brush, width, unit, pen)) \ m(ClonePen, (GpPen *pen, GpPen **clonepen), (pen, clonepen)) \ m(DeletePen, (GpPen *pen), (pen)) \ m(SetPenWidth, (GpPen *pen, REAL width), (pen, width)) \ m(GetPenWidth, (GpPen *pen, REAL *width), (pen, width)) \ m(SetPenUnit, (GpPen *pen, GpUnit unit), (pen, unit)) \ m(GetPenUnit, (GpPen *pen, GpUnit *unit), (pen, unit)) \ m(SetPenLineCap197819, (GpPen *pen, GpLineCap startCap, GpLineCap endCap, GpDashCap dashCap), (pen, startCap, endCap, dashCap)) \ m(SetPenStartCap, (GpPen *pen, GpLineCap startCap), (pen, startCap)) \ m(SetPenEndCap, (GpPen *pen, GpLineCap endCap), (pen, endCap)) \ m(SetPenDashCap197819, (GpPen *pen, GpDashCap dashCap), (pen, dashCap)) \ m(GetPenStartCap, (GpPen *pen, GpLineCap *startCap), (pen, startCap)) \ m(GetPenEndCap, (GpPen *pen, GpLineCap *endCap), (pen, endCap)) \ m(GetPenDashCap197819, (GpPen *pen, GpDashCap *dashCap), (pen, dashCap)) \ m(SetPenLineJoin, (GpPen *pen, GpLineJoin lineJoin), (pen, lineJoin)) \ m(GetPenLineJoin, (GpPen *pen, GpLineJoin *lineJoin), (pen, lineJoin)) \ m(SetPenCustomStartCap, (GpPen *pen, GpCustomLineCap* customCap), (pen, customCap)) \ m(GetPenCustomStartCap, (GpPen *pen, GpCustomLineCap** customCap), (pen, customCap)) \ m(SetPenCustomEndCap, (GpPen *pen, GpCustomLineCap* customCap), (pen, customCap)) \ m(GetPenCustomEndCap, (GpPen *pen, GpCustomLineCap** customCap), (pen, customCap)) \ m(SetPenMiterLimit, (GpPen *pen, REAL miterLimit), (pen, miterLimit)) \ m(GetPenMiterLimit, (GpPen *pen, REAL *miterLimit), (pen, miterLimit)) \ m(SetPenMode, (GpPen *pen, GpPenAlignment penMode), (pen, penMode)) \ m(GetPenMode, (GpPen *pen, GpPenAlignment *penMode), (pen, penMode)) \ m(SetPenTransform, (GpPen *pen, GpMatrix *matrix), (pen, matrix)) \ m(GetPenTransform, (GpPen *pen, GpMatrix *matrix), (pen, matrix)) \ m(ResetPenTransform, (GpPen *pen), (pen)) \ m(MultiplyPenTransform, (GpPen *pen, GDIPCONST GpMatrix *matrix, GpMatrixOrder order), (pen, matrix, order)) \ m(TranslatePenTransform, (GpPen *pen, REAL dx, REAL dy, GpMatrixOrder order), (pen, dx, dy, order)) \ m(ScalePenTransform, (GpPen *pen, REAL sx, REAL sy, GpMatrixOrder order), (pen, sx, sy, order)) \ m(RotatePenTransform, (GpPen *pen, REAL angle, GpMatrixOrder order), (pen, angle, order)) \ m(SetPenColor, (GpPen *pen, ARGB argb), (pen, argb)) \ m(GetPenColor, (GpPen *pen, ARGB *argb), (pen, argb)) \ m(SetPenBrushFill, (GpPen *pen, GpBrush *brush), (pen, brush)) \ m(GetPenBrushFill, (GpPen *pen, GpBrush **brush), (pen, brush)) \ m(GetPenFillType, (GpPen *pen, GpPenType* type), (pen, type)) \ m(GetPenDashStyle, (GpPen *pen, GpDashStyle *dashstyle), (pen, dashstyle)) \ m(SetPenDashStyle, (GpPen *pen, GpDashStyle dashstyle), (pen, dashstyle)) \ m(GetPenDashOffset, (GpPen *pen, REAL *offset), (pen, offset)) \ m(SetPenDashOffset, (GpPen *pen, REAL offset), (pen, offset)) \ m(GetPenDashCount, (GpPen *pen, INT *count), (pen, count)) \ m(SetPenDashArray, (GpPen *pen, GDIPCONST REAL *dash, INT count), (pen, dash, count)) \ m(GetPenDashArray, (GpPen *pen, REAL *dash, INT count), (pen, dash, count)) \ m(GetPenCompoundCount, (GpPen *pen, INT *count), (pen, count)) \ m(SetPenCompoundArray, (GpPen *pen, GDIPCONST REAL *dash, INT count), (pen, dash, count)) \ m(GetPenCompoundArray, (GpPen *pen, REAL *dash, INT count), (pen, dash, count)) \ m(CreateCustomLineCap, (GpPath* fillPath, GpPath* strokePath, GpLineCap baseCap, REAL baseInset, GpCustomLineCap **customCap), (fillPath, strokePath, baseCap, baseInset, customCap)) \ m(DeleteCustomLineCap, (GpCustomLineCap* customCap), (customCap)) \ m(CloneCustomLineCap, (GpCustomLineCap* customCap, GpCustomLineCap** clonedCap), (customCap, clonedCap)) \ m(GetCustomLineCapType, (GpCustomLineCap* customCap, CustomLineCapType* capType), (customCap, capType)) \ m(SetCustomLineCapStrokeCaps, (GpCustomLineCap* customCap, GpLineCap startCap, GpLineCap endCap), (customCap, startCap, endCap)) \ m(GetCustomLineCapStrokeCaps, (GpCustomLineCap* customCap, GpLineCap* startCap, GpLineCap* endCap), (customCap, startCap, endCap)) \ m(SetCustomLineCapStrokeJoin, (GpCustomLineCap* customCap, GpLineJoin lineJoin), (customCap, lineJoin)) \ m(GetCustomLineCapStrokeJoin, (GpCustomLineCap* customCap, GpLineJoin* lineJoin), (customCap, lineJoin)) \ m(SetCustomLineCapBaseCap, (GpCustomLineCap* customCap, GpLineCap baseCap), (customCap, baseCap)) \ m(GetCustomLineCapBaseCap, (GpCustomLineCap* customCap, GpLineCap* baseCap), (customCap, baseCap)) \ m(SetCustomLineCapBaseInset, (GpCustomLineCap* customCap, REAL inset), (customCap, inset)) \ m(GetCustomLineCapBaseInset, (GpCustomLineCap* customCap, REAL* inset), (customCap, inset)) \ m(SetCustomLineCapWidthScale, (GpCustomLineCap* customCap, REAL widthScale), (customCap, widthScale)) \ m(GetCustomLineCapWidthScale, (GpCustomLineCap* customCap, REAL* widthScale), (customCap, widthScale)) \ m(CreateAdjustableArrowCap, (REAL height, REAL width, BOOL isFilled, GpAdjustableArrowCap **cap), (height, width, isFilled, cap)) \ m(SetAdjustableArrowCapHeight, (GpAdjustableArrowCap* cap, REAL height), (cap, height)) \ m(GetAdjustableArrowCapHeight, (GpAdjustableArrowCap* cap, REAL* height), (cap, height)) \ m(SetAdjustableArrowCapWidth, (GpAdjustableArrowCap* cap, REAL width), (cap, width)) \ m(GetAdjustableArrowCapWidth, (GpAdjustableArrowCap* cap, REAL* width), (cap, width)) \ m(SetAdjustableArrowCapMiddleInset, (GpAdjustableArrowCap* cap, REAL middleInset), (cap, middleInset)) \ m(GetAdjustableArrowCapMiddleInset, (GpAdjustableArrowCap* cap, REAL* middleInset), (cap, middleInset)) \ m(SetAdjustableArrowCapFillState, (GpAdjustableArrowCap* cap, BOOL fillState), (cap, fillState)) \ m(GetAdjustableArrowCapFillState, (GpAdjustableArrowCap* cap, BOOL* fillState), (cap, fillState)) \ m(LoadImageFromStream, (IStream* stream, GpImage **image), (stream, image)) \ m(LoadImageFromFile, (GDIPCONST WCHAR* filename, GpImage **image), (filename, image)) \ m(LoadImageFromStreamICM, (IStream* stream, GpImage **image), (stream, image)) \ m(LoadImageFromFileICM, (GDIPCONST WCHAR* filename, GpImage **image), (filename, image)) \ m(CloneImage, (GpImage *image, GpImage **cloneImage), (image, cloneImage)) \ m(DisposeImage, (GpImage *image), (image)) \ m(SaveImageToFile, (GpImage *image, GDIPCONST WCHAR* filename, GDIPCONST CLSID* clsidEncoder, GDIPCONST EncoderParameters* encoderParams), (image, filename, clsidEncoder, encoderParams)) \ m(SaveImageToStream, (GpImage *image, IStream* stream, GDIPCONST CLSID* clsidEncoder, GDIPCONST EncoderParameters* encoderParams), (image, stream, clsidEncoder, encoderParams)) \ m(SaveAdd, (GpImage *image, GDIPCONST EncoderParameters* encoderParams), (image, encoderParams)) \ m(SaveAddImage, (GpImage *image, GpImage* newImage, GDIPCONST EncoderParameters* encoderParams), (image, newImage, encoderParams)) \ m(GetImageGraphicsContext, (GpImage *image, GpGraphics **graphics), (image, graphics)) \ m(GetImageBounds, (GpImage *image, GpRectF *srcRect, GpUnit *srcUnit), (image, srcRect, srcUnit)) \ m(GetImageDimension, (GpImage *image, REAL *width, REAL *height), (image, width, height)) \ m(GetImageType, (GpImage *image, ImageType *type), (image, type)) \ m(GetImageWidth, (GpImage *image, UINT *width), (image, width)) \ m(GetImageHeight, (GpImage *image, UINT *height), (image, height)) \ m(GetImageHorizontalResolution, (GpImage *image, REAL *resolution), (image, resolution)) \ m(GetImageVerticalResolution, (GpImage *image, REAL *resolution), (image, resolution)) \ m(GetImageFlags, (GpImage *image, UINT *flags), (image, flags)) \ m(GetImageRawFormat, (GpImage *image, GUID *format), (image, format)) \ m(GetImagePixelFormat, (GpImage *image, PixelFormat *format), (image, format)) \ m(GetImageThumbnail, (GpImage *image, UINT thumbWidth, UINT thumbHeight, GpImage **thumbImage, GetThumbnailImageAbort callback, VOID *callbackData), (image, thumbWidth, thumbHeight, thumbImage, callback, callbackData)) \ m(GetEncoderParameterListSize, (GpImage *image, GDIPCONST CLSID* clsidEncoder, UINT* size), (image, clsidEncoder, size)) \ m(GetEncoderParameterList, (GpImage *image, GDIPCONST CLSID* clsidEncoder, UINT size, EncoderParameters* buffer), (image, clsidEncoder, size, buffer)) \ m(ImageGetFrameDimensionsCount, (GpImage* image, UINT* count), (image, count)) \ m(ImageGetFrameDimensionsList, (GpImage* image, GUID* dimensionIDs, UINT count), (image, dimensionIDs, count)) \ m(ImageGetFrameCount, (GpImage *image, GDIPCONST GUID* dimensionID, UINT* count), (image, dimensionID, count)) \ m(ImageSelectActiveFrame, (GpImage *image, GDIPCONST GUID* dimensionID, UINT frameIndex), (image, dimensionID, frameIndex)) \ m(ImageRotateFlip, (GpImage *image, RotateFlipType rfType), (image, rfType)) \ m(GetImagePalette, (GpImage *image, ColorPalette *palette, INT size), (image, palette, size)) \ m(SetImagePalette, (GpImage *image, GDIPCONST ColorPalette *palette), (image, palette)) \ m(GetImagePaletteSize, (GpImage *image, INT *size), (image, size)) \ m(GetPropertyCount, (GpImage *image, UINT* numOfProperty), (image, numOfProperty)) \ m(GetPropertyIdList, (GpImage *image, UINT numOfProperty, PROPID* list), (image, numOfProperty, list)) \ m(GetPropertyItemSize, (GpImage *image, PROPID propId, UINT* size), (image, propId, size)) \ m(GetPropertyItem, (GpImage *image, PROPID propId,UINT propSize, PropertyItem* buffer), (image, propId, propSize, buffer)) \ m(GetPropertySize, (GpImage *image, UINT* totalBufferSize, UINT* numProperties), (image, totalBufferSize, numProperties)) \ m(GetAllPropertyItems, (GpImage *image, UINT totalBufferSize, UINT numProperties, PropertyItem* allItems), (image, totalBufferSize, numProperties, allItems)) \ m(RemovePropertyItem, (GpImage *image, PROPID propId), (image, propId)) \ m(SetPropertyItem, (GpImage *image, GDIPCONST PropertyItem* item), (image, item)) \ m(ImageForceValidation, (GpImage *image), (image)) \ m(CreateBitmapFromStream, (IStream* stream, GpBitmap **bitmap), (stream, bitmap)) \ m(CreateBitmapFromFile, (GDIPCONST WCHAR* filename, GpBitmap **bitmap), (filename, bitmap)) \ m(CreateBitmapFromStreamICM, (IStream* stream, GpBitmap **bitmap), (stream, bitmap)) \ m(CreateBitmapFromFileICM, (GDIPCONST WCHAR* filename, GpBitmap **bitmap), (filename, bitmap)) \ m(CreateBitmapFromScan0, (INT width, INT height, INT stride, PixelFormat format, BYTE* scan0, GpBitmap** bitmap), (width, height, stride, format, scan0, bitmap)) \ m(CreateBitmapFromGraphics, (INT width, INT height, GpGraphics* target, GpBitmap** bitmap), (width, height, target, bitmap)) \ m(CreateBitmapFromDirectDrawSurface, (IDirectDrawSurface7* surface, GpBitmap** bitmap), (surface, bitmap)) \ m(CreateBitmapFromGdiDib, (GDIPCONST BITMAPINFO* gdiBitmapInfo, VOID* gdiBitmapData, GpBitmap** bitmap), (gdiBitmapInfo, gdiBitmapData, bitmap)) \ m(CreateBitmapFromHBITMAP, (HBITMAP hbm, HPALETTE hpal, GpBitmap** bitmap), (hbm, hpal, bitmap)) \ m(CreateHBITMAPFromBitmap, (GpBitmap* bitmap, HBITMAP* hbmReturn, ARGB background), (bitmap, hbmReturn, background)) \ m(CreateBitmapFromHICON, (HICON hicon, GpBitmap** bitmap), (hicon, bitmap)) \ m(CreateHICONFromBitmap, (GpBitmap* bitmap, HICON* hbmReturn), (bitmap, hbmReturn)) \ m(CreateBitmapFromResource, (HINSTANCE hInstance, GDIPCONST WCHAR* lpBitmapName, GpBitmap** bitmap), (hInstance, lpBitmapName, bitmap)) \ m(CloneBitmapArea, (REAL x, REAL y, REAL width, REAL height, PixelFormat format, GpBitmap *srcBitmap, GpBitmap **dstBitmap), (x, y, width, height, format, srcBitmap, dstBitmap)) \ m(CloneBitmapAreaI, (INT x, INT y, INT width, INT height, PixelFormat format, GpBitmap *srcBitmap, GpBitmap **dstBitmap), (x, y, width, height, format, srcBitmap, dstBitmap)) \ m(BitmapLockBits, (GpBitmap* bitmap, GDIPCONST GpRect* rect, UINT flags, PixelFormat format, BitmapData* lockedBitmapData), (bitmap, rect, flags, format, lockedBitmapData)) \ m(BitmapUnlockBits, (GpBitmap* bitmap, BitmapData* lockedBitmapData), (bitmap, lockedBitmapData)) \ m(BitmapGetPixel, (GpBitmap* bitmap, INT x, INT y, ARGB *color), (bitmap, x, y, color)) \ m(BitmapSetPixel, (GpBitmap* bitmap, INT x, INT y, ARGB color), (bitmap, x, y, color)) \ m(BitmapSetResolution, (GpBitmap* bitmap, REAL xdpi, REAL ydpi), (bitmap, xdpi, ydpi)) \ m(CreateImageAttributes, (GpImageAttributes **imageattr), (imageattr)) \ m(CloneImageAttributes, (GDIPCONST GpImageAttributes *imageattr, GpImageAttributes **cloneImageattr), (imageattr, cloneImageattr)) \ m(DisposeImageAttributes, (GpImageAttributes *imageattr), (imageattr)) \ m(SetImageAttributesToIdentity, (GpImageAttributes *imageattr, ColorAdjustType type), (imageattr, type)) \ m(ResetImageAttributes, (GpImageAttributes *imageattr, ColorAdjustType type), (imageattr, type)) \ m(SetImageAttributesColorMatrix, (GpImageAttributes *imageattr, ColorAdjustType type, BOOL enableFlag, GDIPCONST ColorMatrix* colorMatrix, GDIPCONST ColorMatrix* grayMatrix, ColorMatrixFlags flags), (imageattr, type, enableFlag, colorMatrix, grayMatrix, flags)) \ m(SetImageAttributesThreshold, (GpImageAttributes *imageattr, ColorAdjustType type, BOOL enableFlag, REAL threshold), (imageattr, type, enableFlag, threshold)) \ m(SetImageAttributesGamma, (GpImageAttributes *imageattr, ColorAdjustType type, BOOL enableFlag, REAL gamma), (imageattr, type, enableFlag, gamma)) \ m(SetImageAttributesNoOp, (GpImageAttributes *imageattr, ColorAdjustType type, BOOL enableFlag), (imageattr, type, enableFlag)) \ m(SetImageAttributesColorKeys, (GpImageAttributes *imageattr, ColorAdjustType type, BOOL enableFlag, ARGB colorLow, ARGB colorHigh), (imageattr, type, enableFlag, colorLow, colorHigh)) \ m(SetImageAttributesOutputChannel, (GpImageAttributes *imageattr, ColorAdjustType type, BOOL enableFlag, ColorChannelFlags channelFlags), (imageattr, type, enableFlag, channelFlags)) \ m(SetImageAttributesOutputChannelColorProfile, (GpImageAttributes *imageattr, ColorAdjustType type, BOOL enableFlag, GDIPCONST WCHAR *colorProfileFilename), (imageattr, type, enableFlag, colorProfileFilename)) \ m(SetImageAttributesRemapTable, (GpImageAttributes *imageattr, ColorAdjustType type, BOOL enableFlag, UINT mapSize, GDIPCONST ColorMap *map), (imageattr, type, enableFlag, mapSize, map)) \ m(SetImageAttributesWrapMode, (GpImageAttributes *imageAttr, WrapMode wrap, ARGB argb, BOOL clamp), (imageAttr, wrap, argb, clamp)) \ m(GetImageAttributesAdjustedPalette, (GpImageAttributes *imageAttr, ColorPalette *colorPalette, ColorAdjustType colorAdjustType), (imageAttr, colorPalette, colorAdjustType)) \ m(Flush, (GpGraphics *graphics, GpFlushIntention intention), (graphics, intention)) \ m(CreateFromHDC, (HDC hdc, GpGraphics **graphics), (hdc, graphics)) \ m(CreateFromHDC2, (HDC hdc, HANDLE hDevice, GpGraphics **graphics), (hdc, hDevice, graphics)) \ m(CreateFromHWND, (HWND hwnd, GpGraphics **graphics), (hwnd, graphics)) \ m(CreateFromHWNDICM, (HWND hwnd, GpGraphics **graphics), (hwnd, graphics)) \ m(DeleteGraphics, (GpGraphics *graphics), (graphics)) \ m(GetDC, (GpGraphics* graphics, HDC *hdc), (graphics, hdc)) \ m(ReleaseDC, (GpGraphics* graphics, HDC hdc), (graphics, hdc)) \ m(SetCompositingMode, (GpGraphics *graphics, CompositingMode compositingMode), (graphics, compositingMode)) \ m(GetCompositingMode, (GpGraphics *graphics, CompositingMode *compositingMode), (graphics, compositingMode)) \ m(SetRenderingOrigin, (GpGraphics *graphics, INT x, INT y), (graphics, x, y)) \ m(GetRenderingOrigin, (GpGraphics *graphics, INT *x, INT *y), (graphics, x, y)) \ m(SetCompositingQuality, (GpGraphics *graphics, CompositingQuality compositingQuality), (graphics, compositingQuality)) \ m(GetCompositingQuality, (GpGraphics *graphics, CompositingQuality *compositingQuality), (graphics, compositingQuality)) \ m(SetSmoothingMode, (GpGraphics *graphics, SmoothingMode smoothingMode), (graphics, smoothingMode)) \ m(GetSmoothingMode, (GpGraphics *graphics, SmoothingMode *smoothingMode), (graphics, smoothingMode)) \ m(SetPixelOffsetMode, (GpGraphics* graphics, PixelOffsetMode pixelOffsetMode), (graphics, pixelOffsetMode)) \ m(GetPixelOffsetMode, (GpGraphics *graphics, PixelOffsetMode *pixelOffsetMode), (graphics, pixelOffsetMode)) \ m(SetTextRenderingHint, (GpGraphics *graphics, TextRenderingHint mode), (graphics, mode)) \ m(GetTextRenderingHint, (GpGraphics *graphics, TextRenderingHint *mode), (graphics, mode)) \ m(SetTextContrast, (GpGraphics *graphics, UINT contrast), (graphics, contrast)) \ m(GetTextContrast, (GpGraphics *graphics, UINT *contrast), (graphics, contrast)) \ m(SetInterpolationMode, (GpGraphics *graphics, InterpolationMode interpolationMode), (graphics, interpolationMode)) \ m(GetInterpolationMode, (GpGraphics *graphics, InterpolationMode *interpolationMode), (graphics, interpolationMode)) \ m(SetWorldTransform, (GpGraphics *graphics, GpMatrix *matrix), (graphics, matrix)) \ m(ResetWorldTransform, (GpGraphics *graphics), (graphics)) \ m(MultiplyWorldTransform, (GpGraphics *graphics, GDIPCONST GpMatrix *matrix, GpMatrixOrder order), (graphics, matrix, order)) \ m(TranslateWorldTransform, (GpGraphics *graphics, REAL dx, REAL dy, GpMatrixOrder order), (graphics, dx, dy, order)) \ m(ScaleWorldTransform, (GpGraphics *graphics, REAL sx, REAL sy, GpMatrixOrder order), (graphics, sx, sy, order)) \ m(RotateWorldTransform, (GpGraphics *graphics, REAL angle, GpMatrixOrder order), (graphics, angle, order)) \ m(GetWorldTransform, (GpGraphics *graphics, GpMatrix *matrix), (graphics, matrix)) \ m(ResetPageTransform, (GpGraphics *graphics), (graphics)) \ m(GetPageUnit, (GpGraphics *graphics, GpUnit *unit), (graphics, unit)) \ m(GetPageScale, (GpGraphics *graphics, REAL *scale), (graphics, scale)) \ m(SetPageUnit, (GpGraphics *graphics, GpUnit unit), (graphics, unit)) \ m(SetPageScale, (GpGraphics *graphics, REAL scale), (graphics, scale)) \ m(GetDpiX, (GpGraphics *graphics, REAL* dpi), (graphics, dpi)) \ m(GetDpiY, (GpGraphics *graphics, REAL* dpi), (graphics, dpi)) \ m(TransformPoints, (GpGraphics *graphics, GpCoordinateSpace destSpace, GpCoordinateSpace srcSpace, GpPointF *points, INT count), (graphics, destSpace, srcSpace, points, count)) \ m(TransformPointsI, (GpGraphics *graphics, GpCoordinateSpace destSpace, GpCoordinateSpace srcSpace, GpPoint *points, INT count), (graphics, destSpace, srcSpace, points, count)) \ m(GetNearestColor, (GpGraphics *graphics, ARGB* argb), (graphics, argb)) \ m(DrawLine, (GpGraphics *graphics, GpPen *pen, REAL x1, REAL y1, REAL x2, REAL y2), (graphics, pen, x1, y1, x2, y2)) \ m(DrawLineI, (GpGraphics *graphics, GpPen *pen, INT x1, INT y1, INT x2, INT y2), (graphics, pen, x1, y1, x2, y2)) \ m(DrawLines, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPointF *points, INT count), (graphics, pen, points, count)) \ m(DrawLinesI, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPoint *points, INT count), (graphics, pen, points, count)) \ m(DrawArc, (GpGraphics *graphics, GpPen *pen, REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle), (graphics, pen, x, y, width, height, startAngle, sweepAngle)) \ m(DrawArcI, (GpGraphics *graphics, GpPen *pen, INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle), (graphics, pen, x, y, width, height, startAngle, sweepAngle)) \ m(DrawBezier, (GpGraphics *graphics, GpPen *pen, REAL x1, REAL y1, REAL x2, REAL y2, REAL x3, REAL y3, REAL x4, REAL y4), (graphics, pen, x1, y1, x2, y2, x3, y3, x4, y4)) \ m(DrawBezierI, (GpGraphics *graphics, GpPen *pen, INT x1, INT y1, INT x2, INT y2, INT x3, INT y3, INT x4, INT y4), (graphics, pen, x1, y1, x2, y2, x3, y3, x4, y4)) \ m(DrawBeziers, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPointF *points, INT count), (graphics, pen, points, count)) \ m(DrawBeziersI, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPoint *points, INT count), (graphics, pen, points, count)) \ m(DrawRectangle, (GpGraphics *graphics, GpPen *pen, REAL x, REAL y, REAL width, REAL height), (graphics, pen, x, y, width, height)) \ m(DrawRectangleI, (GpGraphics *graphics, GpPen *pen, INT x, INT y, INT width, INT height), (graphics, pen, x, y, width, height)) \ m(DrawRectangles, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpRectF *rects, INT count), (graphics, pen, rects, count)) \ m(DrawRectanglesI, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpRect *rects, INT count), (graphics, pen, rects, count)) \ m(DrawEllipse, (GpGraphics *graphics, GpPen *pen, REAL x, REAL y, REAL width, REAL height), (graphics, pen, x, y, width, height)) \ m(DrawEllipseI, (GpGraphics *graphics, GpPen *pen, INT x, INT y, INT width, INT height), (graphics, pen, x, y, width, height)) \ m(DrawPie, (GpGraphics *graphics, GpPen *pen, REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle), (graphics, pen, x, y, width, height, startAngle, sweepAngle)) \ m(DrawPieI, (GpGraphics *graphics, GpPen *pen, INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle), (graphics, pen, x, y, width, height, startAngle, sweepAngle)) \ m(DrawPolygon, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPointF *points, INT count), (graphics, pen, points, count)) \ m(DrawPolygonI, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPoint *points, INT count), (graphics, pen, points, count)) \ m(DrawPath, (GpGraphics *graphics, GpPen *pen, GpPath *path), (graphics, pen, path)) \ m(DrawCurve, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPointF *points, INT count), (graphics, pen, points, count)) \ m(DrawCurveI, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPoint *points, INT count), (graphics, pen, points, count)) \ m(DrawCurve2, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPointF *points, INT count, REAL tension), (graphics, pen, points, count, tension)) \ m(DrawCurve2I, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPoint *points, INT count, REAL tension), (graphics, pen, points, count, tension)) \ m(DrawCurve3, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPointF *points, INT count, INT offset, INT numberOfSegments, REAL tension), (graphics, pen, points, count, offset, numberOfSegments, tension)) \ m(DrawCurve3I, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPoint *points, INT count, INT offset, INT numberOfSegments, REAL tension), (graphics, pen, points, count, offset, numberOfSegments, tension)) \ m(DrawClosedCurve, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPointF *points, INT count), (graphics, pen, points, count)) \ m(DrawClosedCurveI, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPoint *points, INT count), (graphics, pen, points, count)) \ m(DrawClosedCurve2, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPointF *points, INT count, REAL tension), (graphics, pen, points, count, tension)) \ m(DrawClosedCurve2I, (GpGraphics *graphics, GpPen *pen, GDIPCONST GpPoint *points, INT count, REAL tension), (graphics, pen, points, count, tension)) \ m(GraphicsClear, (GpGraphics *graphics, ARGB color), (graphics, color)) \ m(FillRectangle, (GpGraphics *graphics, GpBrush *brush, REAL x, REAL y, REAL width, REAL height), (graphics, brush, x, y, width, height)) \ m(FillRectangleI, (GpGraphics *graphics, GpBrush *brush, INT x, INT y, INT width, INT height), (graphics, brush, x, y, width, height)) \ m(FillRectangles, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpRectF *rects, INT count), (graphics, brush, rects, count)) \ m(FillRectanglesI, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpRect *rects, INT count), (graphics, brush, rects, count)) \ m(FillPolygon, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpPointF *points, INT count, GpFillMode fillMode), (graphics, brush, points, count, fillMode)) \ m(FillPolygonI, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpPoint *points, INT count, GpFillMode fillMode), (graphics, brush, points, count, fillMode)) \ m(FillPolygon2, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpPointF *points, INT count), (graphics, brush, points, count)) \ m(FillPolygon2I, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpPoint *points, INT count), (graphics, brush, points, count)) \ m(FillEllipse, (GpGraphics *graphics, GpBrush *brush, REAL x, REAL y, REAL width, REAL height), (graphics, brush, x, y, width, height)) \ m(FillEllipseI, (GpGraphics *graphics, GpBrush *brush, INT x, INT y, INT width, INT height), (graphics, brush, x, y, width, height)) \ m(FillPie, (GpGraphics *graphics, GpBrush *brush, REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle), (graphics, brush, x, y, width, height, startAngle, sweepAngle)) \ m(FillPieI, (GpGraphics *graphics, GpBrush *brush, INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle), (graphics, brush, x, y, width, height, startAngle, sweepAngle)) \ m(FillPath, (GpGraphics *graphics, GpBrush *brush, GpPath *path), (graphics, brush, path)) \ m(FillClosedCurve, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpPointF *points, INT count), (graphics, brush, points, count)) \ m(FillClosedCurveI, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpPoint *points, INT count), (graphics, brush, points, count)) \ m(FillClosedCurve2, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpPointF *points, INT count, REAL tension, GpFillMode fillMode), (graphics, brush, points, count, tension, fillMode)) \ m(FillClosedCurve2I, (GpGraphics *graphics, GpBrush *brush, GDIPCONST GpPoint *points, INT count, REAL tension, GpFillMode fillMode), (graphics, brush, points, count, tension, fillMode)) \ m(FillRegion, (GpGraphics *graphics, GpBrush *brush, GpRegion *region), (graphics, brush, region)) \ m(DrawImage, (GpGraphics *graphics, GpImage *image, REAL x, REAL y), (graphics, image, x, y)) \ m(DrawImageI, (GpGraphics *graphics, GpImage *image, INT x, INT y), (graphics, image, x, y)) \ m(DrawImageRect, (GpGraphics *graphics, GpImage *image, REAL x, REAL y, REAL width, REAL height), (graphics, image, x, y, width, height)) \ m(DrawImageRectI, (GpGraphics *graphics, GpImage *image, INT x, INT y, INT width, INT height), (graphics, image, x, y, width, height)) \ m(DrawImagePoints, (GpGraphics *graphics, GpImage *image, GDIPCONST GpPointF *dstpoints, INT count), (graphics, image, dstpoints, count)) \ m(DrawImagePointsI, (GpGraphics *graphics, GpImage *image, GDIPCONST GpPoint *dstpoints, INT count), (graphics, image, dstpoints, count)) \ m(DrawImagePointRect, (GpGraphics *graphics, GpImage *image, REAL x, REAL y, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight, GpUnit srcUnit), (graphics, image, x, y, srcx, srcy, srcwidth, srcheight, srcUnit)) \ m(DrawImagePointRectI, (GpGraphics *graphics, GpImage *image, INT x, INT y, INT srcx, INT srcy, INT srcwidth, INT srcheight, GpUnit srcUnit), (graphics, image, x, y, srcx, srcy, srcwidth, srcheight, srcUnit)) \ m(DrawImageRectRect, (GpGraphics *graphics, GpImage *image, REAL dstx, REAL dsty, REAL dstwidth, REAL dstheight, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight, GpUnit srcUnit, GDIPCONST GpImageAttributes* imageAttributes, DrawImageAbort callback, VOID *callbackData), (graphics, image, dstx, dsty, dstwidth, dstheight, srcx, srcy, srcwidth, srcheight, srcUnit, imageAttributes, callback, callbackData)) \ m(DrawImageRectRectI, (GpGraphics *graphics, GpImage *image, INT dstx, INT dsty, INT dstwidth, INT dstheight, INT srcx, INT srcy, INT srcwidth, INT srcheight, GpUnit srcUnit, GDIPCONST GpImageAttributes* imageAttributes, DrawImageAbort callback, VOID *callbackData), (graphics, image, dstx, dsty, dstwidth, dstheight, srcx, srcy, srcwidth, srcheight, srcUnit, imageAttributes, callback, callbackData)) \ m(DrawImagePointsRect, (GpGraphics *graphics, GpImage *image, GDIPCONST GpPointF *points, INT count, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight, GpUnit srcUnit, GDIPCONST GpImageAttributes* imageAttributes, DrawImageAbort callback, VOID *callbackData), (graphics, image, points, count, srcx, srcy, srcwidth, srcheight, srcUnit, imageAttributes, callback, callbackData)) \ m(DrawImagePointsRectI, (GpGraphics *graphics, GpImage *image, GDIPCONST GpPoint *points, INT count, INT srcx, INT srcy, INT srcwidth, INT srcheight, GpUnit srcUnit, GDIPCONST GpImageAttributes* imageAttributes, DrawImageAbort callback, VOID *callbackData), (graphics, image, points, count, srcx, srcy, srcwidth, srcheight, srcUnit, imageAttributes, callback, callbackData)) \ m(EnumerateMetafileDestPoint, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST PointF & destPoint, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destPoint, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileDestPointI, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST Point & destPoint, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destPoint, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileDestRect, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST RectF & destRect, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destRect, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileDestRectI, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST Rect & destRect, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destRect, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileDestPoints, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST PointF *destPoints, INT count, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destPoints, count, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileDestPointsI, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST Point *destPoints, INT count, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destPoints, count, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileSrcRectDestPoint, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST PointF & destPoint, GDIPCONST RectF & srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destPoint, srcRect, srcUnit, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileSrcRectDestPointI, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST Point & destPoint, GDIPCONST Rect & srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destPoint, srcRect, srcUnit, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileSrcRectDestRect, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST RectF & destRect, GDIPCONST RectF & srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destRect, srcRect, srcUnit, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileSrcRectDestRectI, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST Rect & destRect, GDIPCONST Rect & srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destRect, srcRect, srcUnit, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileSrcRectDestPoints, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST PointF *destPoints, INT count, GDIPCONST RectF & srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destPoints, count, srcRect, srcUnit, callback, callbackData, imageAttributes)) \ m(EnumerateMetafileSrcRectDestPointsI, (GpGraphics *graphics, GDIPCONST GpMetafile *metafile, GDIPCONST Point *destPoints, INT count, GDIPCONST Rect & srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID *callbackData, GDIPCONST GpImageAttributes *imageAttributes), (graphics, metafile, destPoints, count, srcRect, srcUnit, callback, callbackData, imageAttributes)) \ m(PlayMetafileRecord, (GDIPCONST GpMetafile *metafile, EmfPlusRecordType recordType, UINT flags, UINT dataSize, GDIPCONST BYTE *data), (metafile, recordType, flags, dataSize, data)) \ m(SetClipGraphics, (GpGraphics *graphics, GpGraphics *srcgraphics, CombineMode combineMode), (graphics, srcgraphics, combineMode)) \ m(SetClipRect, (GpGraphics *graphics, REAL x, REAL y, REAL width, REAL height, CombineMode combineMode), (graphics, x, y, width, height, combineMode)) \ m(SetClipRectI, (GpGraphics *graphics, INT x, INT y, INT width, INT height, CombineMode combineMode), (graphics, x, y, width, height, combineMode)) \ m(SetClipPath, (GpGraphics *graphics, GpPath *path, CombineMode combineMode), (graphics, path, combineMode)) \ m(SetClipRegion, (GpGraphics *graphics, GpRegion *region, CombineMode combineMode), (graphics, region, combineMode)) \ m(SetClipHrgn, (GpGraphics *graphics, HRGN hRgn, CombineMode combineMode), (graphics, hRgn, combineMode)) \ m(ResetClip, (GpGraphics *graphics), (graphics)) \ m(TranslateClip, (GpGraphics *graphics, REAL dx, REAL dy), (graphics, dx, dy)) \ m(TranslateClipI, (GpGraphics *graphics, INT dx, INT dy), (graphics, dx, dy)) \ m(GetClip, (GpGraphics *graphics, GpRegion *region), (graphics, region)) \ m(GetClipBounds, (GpGraphics *graphics, GpRectF *rect), (graphics, rect)) \ m(GetClipBoundsI, (GpGraphics *graphics, GpRect *rect), (graphics, rect)) \ m(IsClipEmpty, (GpGraphics *graphics, BOOL *result), (graphics, result)) \ m(GetVisibleClipBounds, (GpGraphics *graphics, GpRectF *rect), (graphics, rect)) \ m(GetVisibleClipBoundsI, (GpGraphics *graphics, GpRect *rect), (graphics, rect)) \ m(IsVisibleClipEmpty, (GpGraphics *graphics, BOOL *result), (graphics, result)) \ m(IsVisiblePoint, (GpGraphics *graphics, REAL x, REAL y, BOOL *result), (graphics, x, y, result)) \ m(IsVisiblePointI, (GpGraphics *graphics, INT x, INT y, BOOL *result), (graphics, x, y, result)) \ m(IsVisibleRect, (GpGraphics *graphics, REAL x, REAL y, REAL width, REAL height, BOOL *result), (graphics, x, y, width, height, result)) \ m(IsVisibleRectI, (GpGraphics *graphics, INT x, INT y, INT width, INT height, BOOL *result), (graphics, x, y, width, height, result)) \ m(SaveGraphics, (GpGraphics *graphics, GraphicsState *state), (graphics, state)) \ m(RestoreGraphics, (GpGraphics *graphics, GraphicsState state), (graphics, state)) \ m(BeginContainer, (GpGraphics *graphics, GDIPCONST GpRectF* dstrect, GDIPCONST GpRectF *srcrect, GpUnit unit, GraphicsContainer *state), (graphics, dstrect, srcrect, unit, state)) \ m(BeginContainerI, (GpGraphics *graphics, GDIPCONST GpRect* dstrect, GDIPCONST GpRect *srcrect, GpUnit unit, GraphicsContainer *state), (graphics, dstrect, srcrect, unit, state)) \ m(BeginContainer2, (GpGraphics *graphics, GraphicsContainer* state), (graphics, state)) \ m(EndContainer, (GpGraphics *graphics, GraphicsContainer state), (graphics, state)) \ m(GetMetafileHeaderFromEmf, (HENHMETAFILE hEmf, MetafileHeader *header), (hEmf, header)) \ m(GetMetafileHeaderFromFile, (GDIPCONST WCHAR* filename, MetafileHeader *header), (filename, header)) \ m(GetMetafileHeaderFromStream, (IStream *stream, MetafileHeader *header), (stream, header)) \ m(GetMetafileHeaderFromMetafile, (GpMetafile *metafile, MetafileHeader *header), (metafile, header)) \ m(GetHemfFromMetafile, (GpMetafile *metafile, HENHMETAFILE *hEmf), (metafile, hEmf)) \ m(CreateStreamOnFile, (GDIPCONST WCHAR *filename, UINT access, IStream **stream), (filename, access, stream)) \ m(CreateMetafileFromWmf, (HMETAFILE hWmf, BOOL deleteWmf, GDIPCONST WmfPlaceableFileHeader *wmfPlaceableFileHeader, GpMetafile **metafile), (hWmf, deleteWmf, wmfPlaceableFileHeader, metafile)) \ m(CreateMetafileFromEmf, (HENHMETAFILE hEmf, BOOL deleteEmf, GpMetafile **metafile), (hEmf, deleteEmf, metafile)) \ m(CreateMetafileFromFile, (GDIPCONST WCHAR* file, GpMetafile **metafile), (file, metafile)) \ m(CreateMetafileFromWmfFile, (GDIPCONST WCHAR* file, GDIPCONST WmfPlaceableFileHeader *wmfPlaceableFileHeader, GpMetafile **metafile), (file, wmfPlaceableFileHeader, metafile)) \ m(CreateMetafileFromStream, (IStream *stream, GpMetafile **metafile), (stream, metafile)) \ m(RecordMetafile, (HDC referenceHdc, EmfType type, GDIPCONST GpRectF *frameRect, MetafileFrameUnit frameUnit, GDIPCONST WCHAR *description, GpMetafile ** metafile), (referenceHdc, type, frameRect, frameUnit, description, metafile)) \ m(RecordMetafileI, (HDC referenceHdc, EmfType type, GDIPCONST GpRect *frameRect, MetafileFrameUnit frameUnit, GDIPCONST WCHAR *description, GpMetafile ** metafile), (referenceHdc, type, frameRect, frameUnit, description, metafile)) \ m(RecordMetafileFileName, (GDIPCONST WCHAR* fileName, HDC referenceHdc, EmfType type, GDIPCONST GpRectF *frameRect, MetafileFrameUnit frameUnit, GDIPCONST WCHAR *description, GpMetafile ** metafile), (fileName, referenceHdc, type, frameRect, frameUnit, description, metafile)) \ m(RecordMetafileFileNameI, (GDIPCONST WCHAR* fileName, HDC referenceHdc, EmfType type, GDIPCONST GpRect *frameRect, MetafileFrameUnit frameUnit, GDIPCONST WCHAR *description, GpMetafile ** metafile), (fileName, referenceHdc, type, frameRect, frameUnit, description, metafile)) \ m(RecordMetafileStream, (IStream *stream, HDC referenceHdc, EmfType type, GDIPCONST GpRectF *frameRect, MetafileFrameUnit frameUnit, GDIPCONST WCHAR *description, GpMetafile ** metafile), (stream, referenceHdc, type, frameRect, frameUnit, description, metafile)) \ m(RecordMetafileStreamI, (IStream *stream, HDC referenceHdc, EmfType type, GDIPCONST GpRect *frameRect, MetafileFrameUnit frameUnit, GDIPCONST WCHAR *description, GpMetafile ** metafile), (stream, referenceHdc, type, frameRect, frameUnit, description, metafile)) \ m(SetMetafileDownLevelRasterizationLimit, (GpMetafile *metafile, UINT metafileRasterizationLimitDpi), (metafile, metafileRasterizationLimitDpi)) \ m(GetMetafileDownLevelRasterizationLimit, (GDIPCONST GpMetafile *metafile, UINT *metafileRasterizationLimitDpi), (metafile, metafileRasterizationLimitDpi)) \ m(GetImageDecodersSize, (UINT *numDecoders, UINT *size), (numDecoders, size)) \ m(GetImageDecoders, (UINT numDecoders, UINT size, ImageCodecInfo *decoders), (numDecoders, size, decoders)) \ m(GetImageEncodersSize, (UINT *numEncoders, UINT *size), (numEncoders, size)) \ m(GetImageEncoders, (UINT numEncoders, UINT size, ImageCodecInfo *encoders), (numEncoders, size, encoders)) \ m(Comment, (GpGraphics* graphics, UINT sizeData, GDIPCONST BYTE *data), (graphics, sizeData, data)) \ m(CreateFontFamilyFromName, (GDIPCONST WCHAR *name, GpFontCollection *fontCollection, GpFontFamily **FontFamily), (name, fontCollection, FontFamily)) \ m(DeleteFontFamily, (GpFontFamily *FontFamily), (FontFamily)) \ m(CloneFontFamily, (GpFontFamily *FontFamily, GpFontFamily **clonedFontFamily), (FontFamily, clonedFontFamily)) \ m(GetGenericFontFamilySansSerif, (GpFontFamily **nativeFamily), (nativeFamily)) \ m(GetGenericFontFamilySerif, (GpFontFamily **nativeFamily), (nativeFamily)) \ m(GetGenericFontFamilyMonospace, (GpFontFamily **nativeFamily), (nativeFamily)) \ m(GetFamilyName, (GDIPCONST GpFontFamily *family, WCHAR name[LF_FACESIZE], LANGID language), (family, name, language)) \ m(IsStyleAvailable, (GDIPCONST GpFontFamily *family, INT style, BOOL *IsStyleAvailable), (family, style, IsStyleAvailable)) \ m(GetEmHeight, (GDIPCONST GpFontFamily *family, INT style, UINT16 *EmHeight), (family, style, EmHeight)) \ m(GetCellAscent, (GDIPCONST GpFontFamily *family, INT style, UINT16 *CellAscent), (family, style, CellAscent)) \ m(GetCellDescent, (GDIPCONST GpFontFamily *family, INT style, UINT16 *CellDescent), (family, style, CellDescent)) \ m(GetLineSpacing, (GDIPCONST GpFontFamily *family, INT style, UINT16 *LineSpacing), (family, style, LineSpacing)) \ m(CreateFontFromDC, (HDC hdc, GpFont **font), (hdc, font)) \ m(CreateFontFromLogfontA, (HDC hdc, GDIPCONST LOGFONTA *logfont, GpFont **font), (hdc, logfont, font)) \ m(CreateFontFromLogfontW, (HDC hdc, GDIPCONST LOGFONTW *logfont, GpFont **font), (hdc, logfont, font)) \ m(CreateFont, (GDIPCONST GpFontFamily *fontFamily, REAL emSize, INT style, Unit unit, GpFont **font), (fontFamily, emSize, style, unit, font)) \ m(CloneFont, (GpFont* font, GpFont** cloneFont), (font, cloneFont)) \ m(DeleteFont, (GpFont* font), (font)) \ m(GetFamily, (GpFont *font, GpFontFamily **family), (font, family)) \ m(GetFontStyle, (GpFont *font, INT *style), (font, style)) \ m(GetFontSize, (GpFont *font, REAL *size), (font, size)) \ m(GetFontUnit, (GpFont *font, Unit *unit), (font, unit)) \ m(GetFontHeight, (GDIPCONST GpFont *font, GDIPCONST GpGraphics *graphics, REAL *height), (font, graphics, height)) \ m(GetFontHeightGivenDPI, (GDIPCONST GpFont *font, REAL dpi, REAL *height), (font, dpi, height)) \ m(GetLogFontA, (GpFont *font, GpGraphics *graphics, LOGFONTA *logfontA), (font, graphics, logfontA)) \ m(GetLogFontW, (GpFont *font, GpGraphics *graphics, LOGFONTW *logfontW), (font, graphics, logfontW)) \ m(NewInstalledFontCollection, (GpFontCollection** fontCollection), (fontCollection)) \ m(NewPrivateFontCollection, (GpFontCollection** fontCollection), (fontCollection)) \ m(DeletePrivateFontCollection, (GpFontCollection** fontCollection), (fontCollection)) \ m(GetFontCollectionFamilyCount, (GpFontCollection* fontCollection, INT *numFound), (fontCollection, numFound)) \ m(GetFontCollectionFamilyList, (GpFontCollection* fontCollection, INT numSought, GpFontFamily* gpfamilies[], INT* numFound), (fontCollection, numSought, gpfamilies, numFound)) \ m(PrivateAddFontFile, (GpFontCollection* fontCollection, GDIPCONST WCHAR* filename), (fontCollection, filename)) \ m(PrivateAddMemoryFont, (GpFontCollection* fontCollection, GDIPCONST void* memory, INT length), (fontCollection, memory, length)) \ m(DrawString, (GpGraphics *graphics, GDIPCONST WCHAR *string, INT length, GDIPCONST GpFont *font, GDIPCONST RectF *layoutRect, GDIPCONST GpStringFormat *stringFormat, GDIPCONST GpBrush *brush), (graphics, string, length, font, layoutRect, stringFormat, brush)) \ m(MeasureString, (GpGraphics *graphics, GDIPCONST WCHAR *string, INT length, GDIPCONST GpFont *font, GDIPCONST RectF *layoutRect, GDIPCONST GpStringFormat *stringFormat, RectF *boundingBox, INT *codepointsFitted, INT *linesFilled), (graphics, string, length, font, layoutRect, stringFormat, boundingBox, codepointsFitted, linesFilled)) \ m(MeasureCharacterRanges, (GpGraphics *graphics, GDIPCONST WCHAR *string, INT length, GDIPCONST GpFont *font, GDIPCONST RectF &layoutRect, GDIPCONST GpStringFormat *stringFormat, INT regionCount, GpRegion **regions), (graphics, string, length, font, layoutRect, stringFormat, regionCount, regions)) \ m(DrawDriverString, (GpGraphics *graphics, GDIPCONST UINT16 *text, INT length, GDIPCONST GpFont *font, GDIPCONST GpBrush *brush, GDIPCONST PointF *positions, INT flags, GDIPCONST GpMatrix *matrix), (graphics, text, length, font, brush, positions, flags, matrix)) \ m(MeasureDriverString, (GpGraphics *graphics, GDIPCONST UINT16 *text, INT length, GDIPCONST GpFont *font, GDIPCONST PointF *positions, INT flags, GDIPCONST GpMatrix *matrix, RectF *boundingBox), (graphics, text, length, font, positions, flags, matrix, boundingBox)) \ m(CreateStringFormat, (INT formatAttributes, LANGID language, GpStringFormat **format), (formatAttributes, language, format)) \ m(StringFormatGetGenericDefault, (GpStringFormat **format), (format)) \ m(StringFormatGetGenericTypographic, (GpStringFormat **format), (format)) \ m(DeleteStringFormat, (GpStringFormat *format), (format)) \ m(CloneStringFormat, (GDIPCONST GpStringFormat *format, GpStringFormat **newFormat), (format, newFormat)) \ m(SetStringFormatFlags, (GpStringFormat *format, INT flags), (format, flags)) \ m(GetStringFormatFlags, (GDIPCONST GpStringFormat *format, INT *flags), (format, flags)) \ m(SetStringFormatAlign, (GpStringFormat *format, StringAlignment align), (format, align)) \ m(GetStringFormatAlign, (GDIPCONST GpStringFormat *format, StringAlignment *align), (format, align)) \ m(SetStringFormatLineAlign, (GpStringFormat *format, StringAlignment align), (format, align)) \ m(GetStringFormatLineAlign, (GDIPCONST GpStringFormat *format, StringAlignment *align), (format, align)) \ m(SetStringFormatTrimming, (GpStringFormat *format, StringTrimming trimming), (format, trimming)) \ m(GetStringFormatTrimming, (GDIPCONST GpStringFormat *format, StringTrimming *trimming), (format, trimming)) \ m(SetStringFormatHotkeyPrefix, (GpStringFormat *format, INT hotkeyPrefix), (format, hotkeyPrefix)) \ m(GetStringFormatHotkeyPrefix, (GDIPCONST GpStringFormat *format, INT *hotkeyPrefix), (format, hotkeyPrefix)) \ m(SetStringFormatTabStops, (GpStringFormat *format, REAL firstTabOffset, INT count, GDIPCONST REAL *tabStops), (format, firstTabOffset, count, tabStops)) \ m(GetStringFormatTabStops, (GDIPCONST GpStringFormat *format, INT count, REAL *firstTabOffset, REAL *tabStops), (format, count, firstTabOffset, tabStops)) \ m(GetStringFormatTabStopCount, (GDIPCONST GpStringFormat *format, INT *count), (format, count)) \ m(SetStringFormatDigitSubstitution, (GpStringFormat *format, LANGID language, StringDigitSubstitute substitute), (format, language, substitute)) \ m(GetStringFormatDigitSubstitution, (GDIPCONST GpStringFormat *format, LANGID *language, StringDigitSubstitute *substitute), (format, language, substitute)) \ m(GetStringFormatMeasurableCharacterRangeCount, (GDIPCONST GpStringFormat *format, INT *count), (format, count)) \ m(SetStringFormatMeasurableCharacterRanges, (GpStringFormat *format, INT rangeCount, GDIPCONST CharacterRange *ranges), (format, rangeCount, ranges)) \ m(CreateCachedBitmap, (GpBitmap *bitmap, GpGraphics *graphics, GpCachedBitmap **cachedBitmap), (bitmap, graphics, cachedBitmap)) \ m(DeleteCachedBitmap, (GpCachedBitmap *cachedBitmap), (cachedBitmap)) \ m(DrawCachedBitmap, (GpGraphics *graphics, GpCachedBitmap *cachedBitmap, INT x, INT y), (graphics, cachedBitmap, x, y)) \ m(SetImageAttributesCachedBackground, (GpImageAttributes *imageattr, BOOL enableFlag), (imageattr, enableFlag)) \ m(TestControl, (GpTestControlEnum control, void *param), (control, param)) \ // non-standard/problematic functions, to review later if needed #if 0 // these functions don't seem to exist in the DLL even though they are // declared in the header m(SetImageAttributesICMMode, (GpImageAttributes *imageAttr, BOOL on), (imageAttr, on)) \ m(FontCollectionEnumerable, (GpFontCollection* fontCollection, GpGraphics* graphics, INT *numFound), (fontCollection, graphics, numFound)) \ m(FontCollectionEnumerate, (GpFontCollection* fontCollection, INT numSought, GpFontFamily* gpfamilies[], INT* numFound, GpGraphics* graphics), (fontCollection, numSought, gpfamilies, numFound, graphics)) \ GpStatus GdipGetMetafileHeaderFromWmf( HMETAFILE hWmf, GDIPCONST WmfPlaceableFileHeader * wmfPlaceableFileHeader, MetafileHeader * header ); HPALETTE WINGDIPAPI GdipCreateHalftonePalette(); UINT WINGDIPAPI GdipEmfToWmfBits( HENHMETAFILE hemf, UINT cbData16, LPBYTE pData16, INT iMapMode, INT eFlags ); #endif // 0 // this macro expands into an invocation of the given macro m for all GDI+ // functions: m is called with the name of the function without "Gdip" prefix #define wxFOR_ALL_GDIP_FUNCNAMES(m) \ m(Alloc, (size_t size), (size)) \ m(Free, (void *ptr), (ptr)) \ wxFOR_ALL_GDIPLUS_STATUS_FUNCS(m) // unfortunately we need a separate macro for these functions as they have // "Gdiplus" prefix instead of "Gdip" for (almost) all the others (and also // WINAPI calling convention instead of WINGDIPAPI although they happen to be // both stdcall in fact) #define wxFOR_ALL_GDIPLUS_FUNCNAMES(m) \ m(Startup, (ULONG_PTR *token, \ const GdiplusStartupInput *input, \ GdiplusStartupOutput *output), \ (token, input, output)) \ m(Shutdown, (ULONG_PTR token), (token)) \ m(NotificationHook, (ULONG_PTR *token), (token)) \ m(NotificationUnhook, (ULONG_PTR token), (token)) \ #define wxFOR_ALL_FUNCNAMES(m) \ wxFOR_ALL_GDIP_FUNCNAMES(m) \ wxFOR_ALL_GDIPLUS_FUNCNAMES(m) // ---------------------------------------------------------------------------- // declare typedefs for types of all GDI+ functions // ---------------------------------------------------------------------------- extern "C" { typedef void* (WINGDIPAPI *wxGDIPLUS_FUNC_T(Alloc))(size_t size); typedef void (WINGDIPAPI *wxGDIPLUS_FUNC_T(Free))(void* ptr); typedef Status (WINAPI *wxGDIPLUS_FUNC_T(Startup))(ULONG_PTR *token, const GdiplusStartupInput *input, GdiplusStartupOutput *output); typedef void (WINAPI *wxGDIPLUS_FUNC_T(Shutdown))(ULONG_PTR token); typedef GpStatus (WINAPI *wxGDIPLUS_FUNC_T(NotificationHook))(ULONG_PTR *token); typedef void (WINAPI *wxGDIPLUS_FUNC_T(NotificationUnhook))(ULONG_PTR token); #define wxDECL_GDIPLUS_FUNC_TYPE(name, params, args) \ typedef GpStatus (WINGDIPAPI *wxGDIPLUS_FUNC_T(name)) params ; wxFOR_ALL_GDIPLUS_STATUS_FUNCS(wxDECL_GDIPLUS_FUNC_TYPE) #undef wxDECL_GDIPLUS_FUNC_TYPE // Special hack for w32api headers that reference this variable which is // normally defined in w32api-specific gdiplus.lib but as we don't link with it // and load gdiplus.dll dynamically, it's not defined in our case resulting in // linking errors -- so just provide it ourselves, it doesn't matter where it // is and if Cygwin headers are modified to not use it in the future, it's not // a big deal neither, we'll just have an unused pointer. #if defined(__CYGWIN__) || defined(__MINGW32__) void *_GdipStringFormatCachedGenericTypographic = NULL; #endif // __CYGWIN__ || __MINGW32__ } // extern "C" // ============================================================================ // wxGdiPlus helper class // ============================================================================ class wxGdiPlus { public: // load GDI+ DLL when we're called for the first time, return true on // success or false on failure static bool Initialize() { if ( m_initialized == -1 ) m_initialized = DoInit(); return m_initialized == 1; } // check if we're initialized without loading the GDI+ DLL static bool IsInitialized() { return m_initialized == 1; } // shutdown: should be called on termination to unload the GDI+ DLL, safe // to call even if we hadn't loaded it static void Terminate() { if ( m_hdll ) { wxDynamicLibrary::Unload(m_hdll); m_hdll = 0; } m_initialized = -1; } // define function pointers as members #define wxDECL_GDIPLUS_FUNC_MEMBER(name, params, args) \ static wxGDIPLUS_FUNC_T(name) name; wxFOR_ALL_FUNCNAMES(wxDECL_GDIPLUS_FUNC_MEMBER) #undef wxDECL_GDIPLUS_FUNC_MEMBER private: // do load the GDI+ DLL and bind all the functions static bool DoInit(); // initially -1 meaning unknown, set to false or true by Initialize() static int m_initialized; // handle of the GDI+ DLL if we loaded it successfully static wxDllType m_hdll; }; #define wxINIT_GDIPLUS_FUNC(name, params, args) \ wxGDIPLUS_FUNC_T(name) wxGdiPlus::name = NULL; wxFOR_ALL_FUNCNAMES(wxINIT_GDIPLUS_FUNC) #undef wxINIT_GDIPLUS_FUNC int wxGdiPlus::m_initialized = -1; wxDllType wxGdiPlus::m_hdll = 0; /* static */ bool wxGdiPlus::DoInit() { // we're prepared to handler errors so suppress log messages about them wxLogNull noLog; wxDynamicLibrary dllGdip(wxT("gdiplus.dll"), wxDL_VERBATIM); if ( !dllGdip.IsLoaded() ) return false; // use RawGetSymbol() for efficiency, we have ~600 functions to load... #define wxDO_LOAD_FUNC(name, namedll) \ name = (wxGDIPLUS_FUNC_T(name))dllGdip.RawGetSymbol(namedll); \ if ( !name ) \ return false; #define wxLOAD_GDIPLUS_FUNC(name, params, args) \ wxDO_LOAD_FUNC(name, wxT("Gdiplus") wxSTRINGIZE_T(name)) wxFOR_ALL_GDIPLUS_FUNCNAMES(wxLOAD_GDIPLUS_FUNC) #undef wxLOAD_GDIPLUS_FUNC #define wxLOAD_GDIP_FUNC(name, params, args) \ wxDO_LOAD_FUNC(name, wxT("Gdip") wxSTRINGIZE_T(name)) wxFOR_ALL_GDIP_FUNCNAMES(wxLOAD_GDIP_FUNC) #undef wxLOAD_GDIP_FUNC // ok, prevent the DLL from being unloaded right now, we'll do it later m_hdll = dllGdip.Detach(); return true; } // ============================================================================ // module to unload GDI+ DLL on program termination // ============================================================================ class wxGdiPlusModule : public wxModule { public: virtual bool OnInit() { return true; } virtual void OnExit() { wxGdiPlus::Terminate(); } DECLARE_DYNAMIC_CLASS(wxGdiPlusModule) }; IMPLEMENT_DYNAMIC_CLASS(wxGdiPlusModule, wxModule) // ============================================================================ // implementation of the functions themselves // ============================================================================ extern "C" { void* WINGDIPAPI GdipAlloc(size_t size) { return wxGdiPlus::Initialize() ? wxGdiPlus::Alloc(size) : NULL; } void WINGDIPAPI GdipFree(void* ptr) { if ( wxGdiPlus::Initialize() ) wxGdiPlus::Free(ptr); } Status WINAPI GdiplusStartup(ULONG_PTR *token, const GdiplusStartupInput *input, GdiplusStartupOutput *output) { return wxGdiPlus::Initialize() ? wxGdiPlus::Startup(token, input, output) : GdiplusNotInitialized; } void WINAPI GdiplusShutdown(ULONG_PTR token) { if ( wxGdiPlus::IsInitialized() ) wxGdiPlus::Shutdown(token); } #define wxIMPL_GDIPLUS_FUNC(name, params, args) \ GpStatus WINGDIPAPI \ Gdip##name params \ { \ return wxGdiPlus::Initialize() ? wxGdiPlus::name args \ : GdiplusNotInitialized; \ } wxFOR_ALL_GDIPLUS_STATUS_FUNCS(wxIMPL_GDIPLUS_FUNC) #undef wxIMPL_GDIPLUS_FUNC } // extern "C" #endif // wxUSE_GRAPHICS_CONTEXT
dariusliep/LogViewer
thirdparty/wxWidgets-3.0.0/src/msw/gdiplus.cpp
C++
lgpl-3.0
85,342
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtNetwork of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ //#define QNETWORKINTERFACE_DEBUG #include "qnetworkinterface.h" #include "qnetworkinterface_p.h" #include <private/qcore_symbian_p.h> #ifndef QT_NO_NETWORKINTERFACE #include <in_sock.h> #include <in_iface.h> #include <es_sock.h> QT_BEGIN_NAMESPACE static QNetworkInterface::InterfaceFlags convertFlags(const TSoInetInterfaceInfo& aInfo) { QNetworkInterface::InterfaceFlags flags = 0; flags |= (aInfo.iState == EIfUp) ? QNetworkInterface::IsUp : QNetworkInterface::InterfaceFlag(0); // We do not have separate flag for running in Symbian OS flags |= (aInfo.iState == EIfUp) ? QNetworkInterface::IsRunning : QNetworkInterface::InterfaceFlag(0); flags |= (aInfo.iFeatures & KIfCanBroadcast) ? QNetworkInterface::CanBroadcast : QNetworkInterface::InterfaceFlag(0); flags |= (aInfo.iFeatures & KIfIsLoopback) ? QNetworkInterface::IsLoopBack : QNetworkInterface::InterfaceFlag(0); flags |= (aInfo.iFeatures & KIfIsPointToPoint) ? QNetworkInterface::IsPointToPoint : QNetworkInterface::InterfaceFlag(0); flags |= (aInfo.iFeatures & KIfCanMulticast) ? QNetworkInterface::CanMulticast : QNetworkInterface::InterfaceFlag(0); return flags; } static QList<QNetworkInterfacePrivate *> interfaceListing() { TInt err(KErrNone); QList<QNetworkInterfacePrivate *> interfaces; // Connect to Native socket server RSocketServ socketServ; err = socketServ.Connect(); if (err) return interfaces; // Open dummy socket for interface queries RSocket socket; err = socket.Open(socketServ, _L("udp")); if (err) { socketServ.Close(); return interfaces; } // Ask socket to start enumerating interfaces err = socket.SetOpt(KSoInetEnumInterfaces, KSolInetIfCtrl); if (err) { socket.Close(); socketServ.Close(); return interfaces; } int ifindex = 0; TPckgBuf<TSoInetInterfaceInfo> infoPckg; TSoInetInterfaceInfo &info = infoPckg(); while (socket.GetOpt(KSoInetNextInterface, KSolInetIfCtrl, infoPckg) == KErrNone) { // Do not include IPv6 addresses because netmask and broadcast address cannot be determined correctly if (info.iName != KNullDesC && info.iAddress.IsV4Mapped()) { TName address; QNetworkAddressEntry entry; QNetworkInterfacePrivate *iface = 0; iface = new QNetworkInterfacePrivate; iface->index = ifindex++; interfaces << iface; iface->name = qt_TDesC2QString(info.iName); iface->flags = convertFlags(info); if (/*info.iFeatures&KIfHasHardwareAddr &&*/ info.iHwAddr.Family() != KAFUnspec) { for (TInt i = sizeof(SSockAddr); i < sizeof(SSockAddr) + info.iHwAddr.GetUserLen(); i++) { address.AppendNumFixedWidth(info.iHwAddr[i], EHex, 2); if ((i + 1) < sizeof(SSockAddr) + info.iHwAddr.GetUserLen()) address.Append(_L(":")); } address.UpperCase(); iface->hardwareAddress = qt_TDesC2QString(address); } // Get the address of the interface info.iAddress.Output(address); entry.setIp(QHostAddress(qt_TDesC2QString(address))); // Get the interface netmask // For some reason netmask is always 0.0.0.0 // info.iNetMask.Output(address); // entry.setNetmask( QHostAddress( qt_TDesC2QString( address ) ) ); // Workaround: Let Symbian determine netmask based on IP address class // TODO: Works only for IPv4 - Task: 259128 Implement IPv6 support TInetAddr netmask; netmask.NetMask(info.iAddress); netmask.Output(address); entry.setNetmask(QHostAddress(qt_TDesC2QString(address))); // Get the interface broadcast address if (iface->flags & QNetworkInterface::CanBroadcast) { // For some reason broadcast address is always 0.0.0.0 // info.iBrdAddr.Output(address); // entry.setBroadcast( QHostAddress( qt_TDesC2QString( address ) ) ); // Workaround: Let Symbian determine broadcast address based on IP address // TODO: Works only for IPv4 - Task: 259128 Implement IPv6 support TInetAddr broadcast; broadcast.NetBroadcast(info.iAddress); broadcast.Output(address); entry.setBroadcast(QHostAddress(qt_TDesC2QString(address))); } // Add new entry to interface address entries iface->addressEntries << entry; #if defined(QNETWORKINTERFACE_DEBUG) printf("\n Found network interface %s, interface flags:\n\ IsUp = %d, IsRunning = %d, CanBroadcast = %d,\n\ IsLoopBack = %d, IsPointToPoint = %d, CanMulticast = %d, \n\ ip = %s, netmask = %s, broadcast = %s,\n\ hwaddress = %s", iface->name.toLatin1().constData(), iface->flags & QNetworkInterface::IsUp, iface->flags & QNetworkInterface::IsRunning, iface->flags & QNetworkInterface::CanBroadcast, iface->flags & QNetworkInterface::IsLoopBack, iface->flags & QNetworkInterface::IsPointToPoint, iface->flags & QNetworkInterface::CanMulticast, entry.ip().toString().toLatin1().constData(), entry.netmask().toString().toLatin1().constData(), entry.broadcast().toString().toLatin1().constData(), iface->hardwareAddress.toLatin1().constData()); #endif } } // we will try to use routing info to detect more precisely // netmask and then ::postProcess() should calculate // broadcast addresses // use dummy socket to start enumerating routes err = socket.SetOpt(KSoInetEnumRoutes, KSolInetRtCtrl); if (err) { socket.Close(); socketServ.Close(); // return what we have // up to this moment return interfaces; } TSoInetRouteInfo routeInfo; TPckg<TSoInetRouteInfo> routeInfoPkg(routeInfo); while (socket.GetOpt(KSoInetNextRoute, KSolInetRtCtrl, routeInfoPkg) == KErrNone) { TName address; // get interface address routeInfo.iIfAddr.Output(address); QHostAddress ifAddr(qt_TDesC2QString(address)); if (ifAddr.isNull()) continue; routeInfo.iDstAddr.Output(address); QHostAddress destination(qt_TDesC2QString(address)); if (destination.isNull() || destination != ifAddr) continue; // search interfaces for (int ifindex = 0; ifindex < interfaces.size(); ++ifindex) { QNetworkInterfacePrivate *iface = interfaces.at(ifindex); for (int eindex = 0; eindex < iface->addressEntries.size(); ++eindex) { QNetworkAddressEntry entry = iface->addressEntries.at(eindex); if (entry.ip() != ifAddr) { continue; } else if (entry.ip().protocol() != QAbstractSocket::IPv4Protocol) { // skip if not IPv4 address (e.g. IPv6) // as results not reliable on Symbian continue; } else { routeInfo.iNetMask.Output(address); QHostAddress netmask(qt_TDesC2QString(address)); entry.setNetmask(netmask); // NULL boradcast address for // ::postProcess to have effect entry.setBroadcast(QHostAddress()); iface->addressEntries.replace(eindex, entry); } } } } socket.Close(); socketServ.Close(); return interfaces; } QList<QNetworkInterfacePrivate *> QNetworkInterfaceManager::scan() { return interfaceListing(); } QT_END_NAMESPACE #endif // QT_NO_NETWORKINTERFACE
ssangkong/NVRAM_KWU
qt-everywhere-opensource-src-4.7.4/src/network/kernel/qnetworkinterface_symbian.cpp
C++
lgpl-3.0
9,698
<?php class boxberryShippingSettingsCountriesValidateController extends waJsonController { public function execute() { $selected_countries = waRequest::post('selected_countries', array(), waRequest::TYPE_ARRAY); $all_countries = waRequest::post('all_countries', 1, waRequest::TYPE_INT); $countries = ''; $allowed_countries = boxberryShippingCountriesAdapter::getAllowedCountries(); if ($all_countries == false && !empty($selected_countries)) { foreach ($selected_countries as $country_code) { if (!isset($allowed_countries[$country_code])) { unset($selected_countries[$country_code]); } } } if ($all_countries || empty($selected_countries) || count($selected_countries) == count($allowed_countries)) { $bxb = waShipping::factory('boxberry'); $this->response['list_saved_countries'] = $bxb->_w('All countries'); } else { $countries = $selected_countries; $saved_countries = boxberryShippingCountriesAdapter::getCountries($selected_countries); $list_saved_countries = array(); foreach ($saved_countries as $country) { $list_saved_countries[] = $country['name']; $this->response['country_codes'][] = $country['iso3letter']; } $this->response['list_saved_countries'] = implode(', ', $list_saved_countries); } $this->response['countries'] = !empty($countries) ? json_encode($countries) : ''; } }
webasyst/webasyst-framework
wa-plugins/shipping/boxberry/lib/actions/settings/boxberryShippingSettingsCountriesValidate.controller.php
PHP
lgpl-3.0
1,590
// Catalano Imaging Library // The Catalano Framework // // Copyright © Diego Catalano, 2015 // diego.catalano at live.com // // Copyright © Andrew Kirillov, 2007-2008 // andrew.kirillov@gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // package Catalano.Imaging.Filters; import Catalano.Core.IntRange; import Catalano.Math.ComplexNumber; /** * Filtering of frequencies outside of specified range in complex Fourier transformed image. * @author Diego Catalano */ public class FrequencyFilter { private IntRange freq = new IntRange(0, 1024); /** * Initializes a new instance of the FrequencyFilter class. */ public FrequencyFilter() {} /** * Initializes a new instance of the FrequencyFilter class. * @param min Minimum value for to keep. * @param max Maximum value for to keep. */ public FrequencyFilter(int min, int max){ this.freq = new IntRange(min, max); } /** * Initializes a new instance of the FrequencyFilter class.S * @param range IntRange. */ public FrequencyFilter(IntRange range) { this.freq = range; } /** * Get range of frequencies to keep. * @return IntRange. */ public IntRange getFrequencyRange() { return freq; } /** * Set range of frequencies to keep. * @param freq IntRange. */ public void setFrequencyRange(IntRange freq) { this.freq = freq; } /** * Apply filter to an fourierTransform. * @param fourierTransform Fourier transformed. */ public void ApplyInPlace(FourierTransform fourierTransform){ if (!fourierTransform.isFourierTransformed()) { try { throw new Exception("the image should be fourier transformed."); } catch (Exception e) { e.printStackTrace(); } } int width = fourierTransform.getWidth(); int height = fourierTransform.getHeight(); int halfWidth = width / 2; int halfHeight = height / 2; int min = freq.getMin(); int max = freq.getMax(); ComplexNumber[][] c = fourierTransform.getData(); for ( int i = 0; i < height; i++ ){ int y = i - halfHeight; for ( int j = 0; j < width; j++ ){ int x = j - halfWidth; int d = (int) Math.sqrt( x * x + y * y ); // filter values outside the range if ( ( d > max ) || ( d < min ) ){ c[i][j].real = 0; c[i][j].imaginary = 0; } } } } }
cswaroop/Catalano-Framework
Catalano.Image/src/Catalano/Imaging/Filters/FrequencyFilter.java
Java
lgpl-3.0
3,543
#__all__ = [ 'search', 'ham_distance', 'lev_distance', 'distance', 'distance_matrix' ]
vfulco/scalpel
lib/gravity/tae/match/__init__.py
Python
lgpl-3.0
94
/* * Copyright 2009-2014 PrimeTek. * * 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.primefaces.adamantium.view.data.datatable; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.ViewScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import org.primefaces.adamantium.domain.Car; import org.primefaces.adamantium.service.CarService; @ManagedBean(name="dtColumnsView") @ViewScoped public class ColumnsView implements Serializable { private final static List<String> VALID_COLUMN_KEYS = Arrays.asList("id", "brand", "year", "color", "price"); private String columnTemplate = "id brand year"; private List<ColumnModel> columns; private List<Car> cars; private List<Car> filteredCars; @ManagedProperty("#{carService}") private CarService service; @PostConstruct public void init() { cars = service.createCars(10); createDynamicColumns(); } public List<Car> getCars() { return cars; } public List<Car> getFilteredCars() { return filteredCars; } public void setFilteredCars(List<Car> filteredCars) { this.filteredCars = filteredCars; } public void setService(CarService service) { this.service = service; } public String getColumnTemplate() { return columnTemplate; } public void setColumnTemplate(String columnTemplate) { this.columnTemplate = columnTemplate; } public List<ColumnModel> getColumns() { return columns; } private void createDynamicColumns() { String[] columnKeys = columnTemplate.split(" "); columns = new ArrayList<ColumnModel>(); for(String columnKey : columnKeys) { String key = columnKey.trim(); if(VALID_COLUMN_KEYS.contains(key)) { columns.add(new ColumnModel(columnKey.toUpperCase(), columnKey)); } } } public void updateColumns() { //reset table state UIComponent table = FacesContext.getCurrentInstance().getViewRoot().findComponent(":form:cars"); table.setValueExpression("sortBy", null); //update columns createDynamicColumns(); } static public class ColumnModel implements Serializable { private String header; private String property; public ColumnModel(String header, String property) { this.header = header; this.property = property; } public String getHeader() { return header; } public String getProperty() { return property; } } }
salviof/SBJSFComp
htmlOffiline/Volverine/tag/src/main/java/org/primefaces/adamantium/view/data/datatable/ColumnsView.java
Java
lgpl-3.0
3,441
/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Copyright (c) 2016,2017 The plumed team (see the PEOPLE file at the root of the distribution for a list of names) See http://www.plumed.org for more information. This file is part of plumed, version 2. plumed is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. plumed is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with plumed. If not, see <http://www.gnu.org/licenses/>. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ #include "DRMSD.h" #include "MetricRegister.h" namespace PLMD { class IntermolecularDRMSD : public DRMSD { private: unsigned nblocks; std::vector<unsigned> blocks; public: explicit IntermolecularDRMSD( const ReferenceConfigurationOptions& ro ); void read( const PDB& pdb ); void setup_targets(); }; PLUMED_REGISTER_METRIC(IntermolecularDRMSD,"INTER-DRMSD") IntermolecularDRMSD::IntermolecularDRMSD( const ReferenceConfigurationOptions& ro ): ReferenceConfiguration( ro ), DRMSD( ro ), nblocks(0) { } void IntermolecularDRMSD::read( const PDB& pdb ) { readAtomsFromPDB( pdb, true ); nblocks = pdb.getNumberOfAtomBlocks(); blocks.resize( nblocks+1 ); if( nblocks==1 ) error("Trying to compute intermolecular rmsd but found no TERs in input PDB"); blocks[0]=0; for(unsigned i=0; i<nblocks; ++i) blocks[i+1]=pdb.getAtomBlockEnds()[i]; readBounds(); setup_targets(); } void IntermolecularDRMSD::setup_targets() { plumed_massert( bounds_were_set, "I am missing a call to DRMSD::setBoundsOnDistances"); for(unsigned i=1; i<nblocks; ++i) { for(unsigned j=0; j<i; ++j) { for(unsigned iatom=blocks[i]; iatom<blocks[i+1]; ++iatom) { for(unsigned jatom=blocks[j]; jatom<blocks[j+1]; ++jatom) { double distance = delta( getReferencePosition(iatom), getReferencePosition(jatom) ).modulo(); if(distance < upper && distance > lower ) targets[std::make_pair(iatom,jatom)] = distance; } } } } } }
JFDama/plumed2
src/reference/IntermolecularDRMSD.cpp
C++
lgpl-3.0
2,489
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.batch; import org.apache.commons.io.IOUtils; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.batch.protocol.input.GlobalRepositories; import org.sonar.db.metric.MetricDto; import org.sonar.core.permission.GlobalPermissions; import org.sonar.db.DbSession; import org.sonar.db.MyBatis; import org.sonar.db.property.PropertiesDao; import org.sonar.db.property.PropertyDto; import org.sonar.server.db.DbClient; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.plugins.MimeTypes; import org.sonar.server.user.UserSession; public class GlobalAction implements BatchWsAction { private final DbClient dbClient; private final PropertiesDao propertiesDao; private final UserSession userSession; public GlobalAction(DbClient dbClient, PropertiesDao propertiesDao, UserSession userSession) { this.dbClient = dbClient; this.propertiesDao = propertiesDao; this.userSession = userSession; } @Override public void define(WebService.NewController controller) { controller.createAction("global") .setDescription("Return metrics and global properties") .setSince("4.5") .setInternal(true) .setHandler(this); } @Override public void handle(Request request, Response response) throws Exception { boolean hasScanPerm = userSession.hasGlobalPermission(GlobalPermissions.SCAN_EXECUTION); boolean hasPreviewPerm = userSession.hasGlobalPermission(GlobalPermissions.PREVIEW_EXECUTION); if (!hasPreviewPerm && !hasScanPerm) { throw new ForbiddenException(Messages.NO_PERMISSION); } DbSession session = dbClient.openSession(false); try { GlobalRepositories ref = new GlobalRepositories(); addMetrics(ref, session); addSettings(ref, hasScanPerm, hasPreviewPerm, session); response.stream().setMediaType(MimeTypes.JSON); IOUtils.write(ref.toJson(), response.stream().output()); } finally { MyBatis.closeQuietly(session); } } private void addMetrics(GlobalRepositories ref, DbSession session) { for (MetricDto metric : dbClient.metricDao().selectEnabled(session)) { ref.addMetric( new org.sonar.batch.protocol.input.Metric(metric.getId(), metric.getKey(), metric.getValueType(), metric.getDescription(), metric.getDirection(), metric.getKey(), metric.isQualitative(), metric.isUserManaged(), metric.getWorstValue(), metric.getBestValue(), metric.isOptimizedBestValue())); } } private void addSettings(GlobalRepositories ref, boolean hasScanPerm, boolean hasPreviewPerm, DbSession session) { for (PropertyDto propertyDto : propertiesDao.selectGlobalProperties(session)) { String key = propertyDto.getKey(); String value = propertyDto.getValue(); if (isPropertyAllowed(key, hasScanPerm, hasPreviewPerm)) { ref.addGlobalSetting(key, value); } } } private static boolean isPropertyAllowed(String key, boolean hasScanPerm, boolean hasPreviewPerm) { return !key.contains(".secured") || hasScanPerm || (key.contains(".license") && hasPreviewPerm); } }
ayondeep/sonarqube
server/sonar-server/src/main/java/org/sonar/server/batch/GlobalAction.java
Java
lgpl-3.0
4,163
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.ce.configuration; import javax.annotation.ParametersAreNonnullByDefault;
SonarSource/sonarqube
server/sonar-ce/src/main/java/org/sonar/ce/configuration/package-info.java
Java
lgpl-3.0
966
using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using Sustainsys.Saml2.AspNetCore2; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Extensions methods for adding Saml2 authentication /// </summary> public static class Saml2AuthExtensions { /// <summary> /// Register Saml2 Authentication with default scheme name. /// </summary> /// <param name="builder">Authentication Builder</param> /// <param name="configureOptions">Action that configures the Saml2 Options</param> /// <returns></returns> public static AuthenticationBuilder AddSaml2( this AuthenticationBuilder builder, Action<Saml2Options> configureOptions) => builder.AddSaml2(Saml2Defaults.Scheme, configureOptions); /// <summary> /// Register Saml2 Authentication with a custom scheme name. /// </summary> /// <param name="builder">Authentication Builder</param> /// <param name="scheme">Name of the authentication scheme</param> /// <param name="configureOptions">Action that configures Saml2 Options</param> /// <returns>Authentication Builder</returns> public static AuthenticationBuilder AddSaml2( this AuthenticationBuilder builder, string scheme, Action<Saml2Options> configureOptions) => builder.AddSaml2(scheme, Saml2Defaults.DisplayName, configureOptions); /// <summary> /// Register Saml2 Authentication with a custom scheme name. /// </summary> /// <param name="builder">Authentication Builder</param> /// <param name="scheme">Name of the authentication scheme</param> /// <param name="configureOptions">Action that configures Saml2 Options</param> /// <param name="displayName">Display name of scheme</param> /// <returns>Authentication Builder</returns> public static AuthenticationBuilder AddSaml2( this AuthenticationBuilder builder, string scheme, string displayName, Action<Saml2Options> configureOptions) { if(builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IPostConfigureOptions<Saml2Options>, PostConfigureSaml2Options>()); builder.Services.Configure<AuthenticationOptions>(o => { o.AddScheme(scheme, s => { s.HandlerType = typeof(Saml2Handler); s.DisplayName = displayName; }); }); if (configureOptions != null) { builder.Services.Configure(scheme, configureOptions); } builder.Services.AddTransient<Saml2Handler>(); return builder; } } }
KentorIT/authservices
Sustainsys.Saml2.AspNetCore2/Saml2AuthExtensions.cs
C#
lgpl-3.0
3,185
// <copyright file="ExpansionCase.cs" company="Allors bvba"> // Copyright (c) Allors bvba. All rights reserved. // Licensed under the LGPL license. See LICENSE file in the project root for full license information. // </copyright> namespace Autotest.Html { using System.Linq; using Autotest.Angular; using Newtonsoft.Json.Linq; public partial class ExpansionCase : INode { public ExpansionCase(JToken json, Template template, INode parent) { this.Json = json; this.Template = template; this.Parent = parent; } public INode[] Expression { get; set; } public JToken Json { get; } public Template Template { get; } public INode Parent { get; set; } public string Value { get; set; } public Scope InScope { get; set; } public void BaseLoad() { this.Value = this.Json["value"]?.Value<string>(); var expressionChildren = this.Json["expression"]; this.Expression = expressionChildren != null ? expressionChildren.Select(v => { var node = NodeFactory.Create(v, this.Template, this); node.BaseLoad(); return node; }).ToArray() : new INode[0]; } public void SetInScope(Scope scope) { this.InScope = scope; scope.Nodes.Add(this); } } }
Allors/platform
Core/Workspace/Scaffold/Model/Core/Html/ExpansionCase.cs
C#
lgpl-3.0
1,468
<?php header("Content-type:text/html;charset=utf-8"); define('IC_VERNAME', '中文版'); $lang = array( 'Install guide' => 'IBOS 安装引导', 'None' => '无', 'Env check' => '环境检查', 'Env test' => '环境检测', 'Icenter required' => '所需配置', 'Recommended' => '推荐配置', 'Curr server' => '当前服务器', 'Priv check' => '目录、文件权限检查', 'Writeable' => '可写', 'Unwriteable' => '不可写', 'Nodir' => '目录不存在', 'Directory file' => '目录文件', 'Required state' => '所需状态', 'Current status' => '当前状态', 'Func depend' => '函数依赖性检查', 'Failed to pass' => '未能通过!', 'Func name' => '函数名称', 'Check result' => '检查结果', 'Suggestion' => '建议', 'Supportted' => '支持', 'Unsupportted' => '不支持', 'Check again' => '重新检测', 'Pack up' => '收起', 'Open up' => '展开', 'os' => '操作系统', 'php' => 'PHP 版本', 'attachmentupload' => '附件上传', 'unlimit' => '不限制', 'version' => '版本', 'gdversion' => 'GD 库', 'allow' => '允许 ', 'unix' => '类Unix', 'diskspace' => '磁盘空间', 'notset' => '不限制', 'install' => '安装', 'installed' => '已安装', 'uninstalled' => '未安装', 'Db info' => '数据库信息', 'Db username' => '数据库用户名', 'Db password' => '数据库密码', 'Password not empty' => '密码不能为空!', 'Show more' => '显示更多信息', 'Db host' => '数据库服务器', 'Db host tip' => '数据库服务器:地址,一般为localhost', 'Db name' => '数据库名', 'Db pre' => '数据表前缀', 'Db pre tip' => '修改前缀与其他数据库区分', 'Admin info' => '管理员信息', 'Admin account' => '管理员账号', 'Admin account tip' => '管理员账号不能为空!', 'Password' => '密码', 'Password tip' => '请填写6到32位数字或者字母!', 'I have read and agree' => '我已阅读并同意', 'Ibos agreement' => '《IBOS协同办公平台用户协议》', 'Custom module' => '自定义模块', 'Install now' => '立即安装', 'Advice_mysql_connect' => '请检查 mysql 模块是否正确加载', 'Advice_gethostbyname' => '是否 PHP 配置中禁止了 gethostbyname 函数。请联系空间商,确定开启了此项功能', 'Advice_file_get_contents' => '该函数需要 php.ini 中 allow_url_fopen 选项开启。请联系空间商,确定开启了此项功能', 'Advice_scandir' => '是否 PHP 配置中禁止了 scandir 函数', 'Advice_bcmul' => '该函数需要 php.ini 中 bcmath 选项开启。请联系空间商,确定开启了此项功能', 'Advice_xml_parser_create' => '该函数需要 PHP 支持 XML。请联系空间商,确定开启了此项功能', 'Advice_fsockopen' => '该函数需要 php.ini 中 allow_url_fopen 选项开启。请联系空间商,确定开启了此项功能', 'Advice_pfsockopen' => '该函数需要 php.ini 中 allow_url_fopen 选项开启。请联系空间商,确定开启了此项功能', 'Advice_stream_socket_client' => '是否 PHP 配置中禁止了 stream_socket_client 函数', 'Advice_curl_init' => '是否 PHP 配置中禁止了 curl_init 函数', 'Advice_mysql' => '是否配置中禁止了php_mysql扩展。请联系空间商,确定开启了此项功能', 'Advice_pdo_mysql' => '是否配置中禁止了php_pdo_mysql扩展。请联系空间商,确定开启了此项功能', 'Advice_mbstring' => '是否配置中禁止了php_mbstring扩展。请联系空间商,确定开启了此项功能', 'Dbaccount not empty' => '数据库用户名不能为空', 'Dbpassword not empty' => '数据库密码不能为空', 'Adminaccount not empty' => '管理员账号不能为空', 'Mobile incorrect format' => '手机号格式不正确', 'Adminpassword incorrect format' => '密码格式不正确!请填写6到32位数字或者字母', 'Database errno 1045' => '无法连接数据库,请检查数据库用户名或者密码是否正确', 'Database errno 2003' => '无法连接数据库,请检查数据库是否启动,数据库服务器地址是否正确', 'Database errno 1049' => '数据库不存在', 'Database errno 2002' => '无法链接数据库,请检查数据库端口是否设置正确', //这个有待考证 'Database connect error' => '数据库连接错误', 'Database errno 1044' => '无法创建新的数据库,请检查数据库名称填写是否正确', 'Database error info' => "数据库连接错误信息:", 'func not exist' => '方法不存在', 'Dbinfo forceinstall invalid' => '当前数据库当中已经含有同样表前缀的数据表,您可以修改“表名前缀(企业代码)”来避免删除旧的数据,或者选择强制安装。强制安装会删除旧数据,且无法恢复', 'Install module failed' => '模块安装失败', 'Install failed message' => '安装失败信息:', 'Install locked' => '安装锁定,已经安装过了,如果您确定要重新安装,请到服务器上删除', 'Suc tip' => '使用演示数据体验', 'Return' => '返回', 'Previous' => '上一步', 'Next' => '下一步', 'Sys module' => '系统模块', 'Fun module' => '功能模块', 'Installing' => '正在安装...', 'Installing info' => '正在安装 "<span id="mod_name"></span>" ,请稍等...', 'Installing tip' => '<p class="mbs fsm">启用全新系统核心架构,IBOS2.0现已全面升级,</p> <p class="fsm">更高效、更健壮、更便捷。</p>', 'Complete' => '安装完成,登录IBOS', 'Install complete' => '模块安装完成,正在初始化系统...', 'Mandatory installation' => '强制安装', 'Del data' => '我要删除数据,强制安装 !!!', 'UpdateSQL locked' => '升级数据库锁定,已经升级过了,如果您确定要重新升级,请到服务器上删除', 'convertUser' => '用户数据', 'convertDept' => '部门数据', 'convertPosition' => '岗位数据', 'convertMail' => '邮件数据', 'convertDiary' => '日志数据', 'convertAtt' => '附件数据', 'convertCal' => '日程数据', 'convertNews' => '新闻数据', 'Sure modify' => '确认修改', 'Modify table prefix' => '我要修改ibos1数据表前缀 !!!', 'Modify table prefix tip' => '本操作将会把以前的数据库所有表前缀改为"old_",为了安全起见,请确保将原来数据库备份再选中此项继续安装', 'Modify old table prefix' => '修改旧数据库表前缀', 'New db pre tip' => '请输入新数据表前缀', 'Continue' => '继续', 'Request tainting' => '非法请求', 'Invalid corp code' => '企业代码格式错误,请输入 4-20 位字母或数字', );
SeekArt/IBOS
install/include/installLang.php
PHP
lgpl-3.0
6,984
// // System.Drawing.Design.ToolboxService // // Authors: // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if NET_2_0 using System.Collections; using System.ComponentModel.Design; using System.Reflection; using System.Windows.Forms; namespace System.Drawing.Design { public abstract class ToolboxService : IComponentDiscoveryService, IToolboxService { [MonoTODO] protected ToolboxService () { throw new NotImplementedException (); } protected abstract CategoryNameCollection CategoryNames { get; } protected abstract string SelectedCategory { get; set; } protected abstract ToolboxItemContainer SelectedItemContainer { get; set; } [MonoTODO] protected virtual ToolboxItemContainer CreateItemContainer (IDataObject dataObject) { throw new NotImplementedException (); } [MonoTODO] protected virtual ToolboxItemContainer CreateItemContainer (ToolboxItem item, IDesignerHost link) { throw new NotImplementedException (); } [MonoTODO] protected virtual void FilterChanged () { throw new NotImplementedException (); } protected abstract IList GetItemContainers (); protected abstract IList GetItemContainers (string categoryName); [MonoTODO] protected virtual bool IsItemContainer (IDataObject dataObject, IDesignerHost host) { throw new NotImplementedException (); } [MonoTODO] protected bool IsItemContainerSupported (ToolboxItemContainer container, IDesignerHost host) { throw new NotImplementedException (); } protected abstract void Refresh (); [MonoTODO] protected virtual void SelectedItemContainerUsed () { throw new NotImplementedException (); } [MonoTODO] protected virtual bool SetCursor () { throw new NotImplementedException (); } [MonoTODO] public static void UnloadToolboxItems () { throw new NotImplementedException (); } [MonoTODO] public static ToolboxItem GetToolboxItem (Type toolType) { throw new NotImplementedException (); } [MonoTODO] public static ToolboxItem GetToolboxItem (Type toolType, bool nonPublic) { throw new NotImplementedException (); } [MonoTODO] public static ICollection GetToolboxItems (AssemblyName an) { throw new NotImplementedException (); } [MonoTODO] public static ICollection GetToolboxItems (AssemblyName an, bool throwOnError) { throw new NotImplementedException (); } [MonoTODO] public static ICollection GetToolboxItems (Assembly a, string newCodeBase) { throw new NotImplementedException (); } [MonoTODO] public static ICollection GetToolboxItems (Assembly a, string newCodeBase, bool throwOnError) { throw new NotImplementedException (); } // IComponentDiscoveryService ICollection IComponentDiscoveryService.GetComponentTypes (IDesignerHost designerHost, Type baseType) { throw new NotImplementedException (); } // IToolboxService CategoryNameCollection IToolboxService.CategoryNames { get { throw new NotImplementedException (); } } string IToolboxService.SelectedCategory { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } void IToolboxService.AddCreator (ToolboxItemCreatorCallback creator, string format) { throw new NotImplementedException (); } void IToolboxService.AddCreator (ToolboxItemCreatorCallback creator, string format, IDesignerHost host) { throw new NotImplementedException (); } void IToolboxService.AddLinkedToolboxItem (ToolboxItem toolboxItem, IDesignerHost host) { throw new NotImplementedException (); } void IToolboxService.AddLinkedToolboxItem (ToolboxItem toolboxItem, string category, IDesignerHost host) { throw new NotImplementedException (); } void IToolboxService.AddToolboxItem (ToolboxItem toolboxItem, String category) { throw new NotImplementedException (); } void IToolboxService.AddToolboxItem (ToolboxItem toolboxItem) { throw new NotImplementedException (); } ToolboxItem IToolboxService.DeserializeToolboxItem (object serializedObject) { throw new NotImplementedException (); } ToolboxItem IToolboxService.DeserializeToolboxItem (object serializedObject, IDesignerHost host) { throw new NotImplementedException (); } ToolboxItem IToolboxService.GetSelectedToolboxItem () { throw new NotImplementedException (); } ToolboxItem IToolboxService.GetSelectedToolboxItem (IDesignerHost host) { throw new NotImplementedException (); } ToolboxItemCollection IToolboxService.GetToolboxItems () { throw new NotImplementedException (); } ToolboxItemCollection IToolboxService.GetToolboxItems (IDesignerHost host) { throw new NotImplementedException (); } ToolboxItemCollection IToolboxService.GetToolboxItems (String category) { throw new NotImplementedException (); } ToolboxItemCollection IToolboxService.GetToolboxItems (String category, IDesignerHost host) { throw new NotImplementedException (); } bool IToolboxService.IsSupported (object serializedObject, ICollection filterAttributes) { throw new NotImplementedException (); } bool IToolboxService.IsSupported (object serializedObject, IDesignerHost host) { throw new NotImplementedException (); } bool IToolboxService.IsToolboxItem (object serializedObject) { throw new NotImplementedException (); } bool IToolboxService.IsToolboxItem (object serializedObject, IDesignerHost host) { throw new NotImplementedException (); } void IToolboxService.Refresh () { throw new NotImplementedException (); } void IToolboxService.RemoveCreator (string format) { throw new NotImplementedException (); } void IToolboxService.RemoveCreator (string format, IDesignerHost host) { throw new NotImplementedException (); } void IToolboxService.RemoveToolboxItem (ToolboxItem toolboxItem) { throw new NotImplementedException (); } void IToolboxService.RemoveToolboxItem (ToolboxItem toolboxItem, string category) { throw new NotImplementedException (); } void IToolboxService.SelectedToolboxItemUsed () { throw new NotImplementedException (); } object IToolboxService.SerializeToolboxItem (ToolboxItem toolboxItem) { throw new NotImplementedException (); } bool IToolboxService.SetCursor () { throw new NotImplementedException (); } void IToolboxService.SetSelectedToolboxItem (ToolboxItem toolboxItem) { throw new NotImplementedException (); } } } #endif
edwinspire/VSharp
class/System.Drawing.Design/System.Drawing.Design/ToolboxService.cs
C#
lgpl-3.0
7,694
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ declare(strict_types=1); namespace pocketmine\item; use pocketmine\block\Block; use pocketmine\block\VanillaBlocks; class Potato extends Food{ public function getBlock(?int $clickedFace = null) : Block{ return VanillaBlocks::POTATOES(); } public function getFoodRestore() : int{ return 1; } public function getSaturationRestore() : float{ return 0.6; } }
JackNoordhuis/PocketMine-MP
src/item/Potato.php
PHP
lgpl-3.0
1,081
declare module org { module kevoree { module modeling { class KActionType { static CALL: KActionType; static CALL_RESPONSE: KActionType; static SET: KActionType; static ADD: KActionType; static REMOVE: KActionType; static NEW: KActionType; equals(other: any): boolean; static _KActionTypeVALUES: KActionType[]; static values(): KActionType[]; } interface KCallback<A> { on(a: A): void; } class KConfig { static TREE_CACHE_SIZE: number; static CALLBACK_HISTORY: number; static LONG_SIZE: number; static PREFIX_SIZE: number; static BEGINNING_OF_TIME: number; static END_OF_TIME: number; static NULL_LONG: number; static KEY_PREFIX_MASK: number; static KEY_SEP: string; static KEY_SIZE: number; static CACHE_INIT_SIZE: number; static CACHE_LOAD_FACTOR: number; } class KContentKey { universe: number; time: number; obj: number; constructor(p_universeID: number, p_timeID: number, p_objID: number); static createUniverseTree(p_objectID: number): org.kevoree.modeling.KContentKey; static createTimeTree(p_universeID: number, p_objectID: number): org.kevoree.modeling.KContentKey; static createObject(p_universeID: number, p_quantaID: number, p_objectID: number): org.kevoree.modeling.KContentKey; static createGlobalUniverseTree(): org.kevoree.modeling.KContentKey; static createRootUniverseTree(): org.kevoree.modeling.KContentKey; static createRootTimeTree(universeID: number): org.kevoree.modeling.KContentKey; static createLastPrefix(): org.kevoree.modeling.KContentKey; static createLastObjectIndexFromPrefix(prefix: number): org.kevoree.modeling.KContentKey; static createLastUniverseIndexFromPrefix(prefix: number): org.kevoree.modeling.KContentKey; static create(payload: string): org.kevoree.modeling.KContentKey; toString(): string; equals(param: any): boolean; } interface KModel<A extends org.kevoree.modeling.KUniverse<any, any, any>> { key(): number; newUniverse(): A; universe(key: number): A; manager(): org.kevoree.modeling.memory.manager.KMemoryManager; setContentDeliveryDriver(dataBase: org.kevoree.modeling.cdn.KContentDeliveryDriver): org.kevoree.modeling.KModel<any>; setScheduler(scheduler: org.kevoree.modeling.scheduler.KScheduler): org.kevoree.modeling.KModel<any>; setOperation(metaOperation: org.kevoree.modeling.meta.KMetaOperation, operation: (p: org.kevoree.modeling.KObject, p1: any[], p2: (p: any) => void) => void): void; setInstanceOperation(metaOperation: org.kevoree.modeling.meta.KMetaOperation, target: org.kevoree.modeling.KObject, operation: (p: org.kevoree.modeling.KObject, p1: any[], p2: (p: any) => void) => void): void; metaModel(): org.kevoree.modeling.meta.KMetaModel; defer(): org.kevoree.modeling.defer.KDefer; save(cb: (p: any) => void): void; discard(cb: (p: any) => void): void; connect(cb: (p: any) => void): void; close(cb: (p: any) => void): void; clearListenerGroup(groupID: number): void; nextGroup(): number; createByName(metaClassName: string, universe: number, time: number): org.kevoree.modeling.KObject; create(clazz: org.kevoree.modeling.meta.KMetaClass, universe: number, time: number): org.kevoree.modeling.KObject; } interface KObject { universe(): number; now(): number; uuid(): number; delete(cb: (p: any) => void): void; select(query: string, cb: (p: org.kevoree.modeling.KObject[]) => void): void; listen(groupId: number, listener: (p: org.kevoree.modeling.KObject, p1: org.kevoree.modeling.meta.KMeta[]) => void): void; visitAttributes(visitor: (p: org.kevoree.modeling.meta.KMetaAttribute, p1: any) => void): void; visit(visitor: (p: org.kevoree.modeling.KObject) => org.kevoree.modeling.traversal.visitor.KVisitResult, cb: (p: any) => void): void; timeWalker(): org.kevoree.modeling.KTimeWalker; metaClass(): org.kevoree.modeling.meta.KMetaClass; mutate(actionType: org.kevoree.modeling.KActionType, metaReference: org.kevoree.modeling.meta.KMetaReference, param: org.kevoree.modeling.KObject): void; ref(metaReference: org.kevoree.modeling.meta.KMetaReference, cb: (p: org.kevoree.modeling.KObject[]) => void): void; traversal(): org.kevoree.modeling.traversal.KTraversal; get(attribute: org.kevoree.modeling.meta.KMetaAttribute): any; getByName(atributeName: string): any; set(attribute: org.kevoree.modeling.meta.KMetaAttribute, payload: any): void; setByName(atributeName: string, payload: any): void; toJSON(): string; equals(other: any): boolean; jump(time: number, callback: (p: org.kevoree.modeling.KObject) => void): void; referencesWith(o: org.kevoree.modeling.KObject): org.kevoree.modeling.meta.KMetaReference[]; call(operation: org.kevoree.modeling.meta.KMetaOperation, params: any[], cb: (p: any) => void): void; manager(): org.kevoree.modeling.memory.manager.KMemoryManager; } interface KTimeWalker { allTimes(cb: (p: number[]) => void): void; timesBefore(endOfSearch: number, cb: (p: number[]) => void): void; timesAfter(beginningOfSearch: number, cb: (p: number[]) => void): void; timesBetween(beginningOfSearch: number, endOfSearch: number, cb: (p: number[]) => void): void; } interface KType { name(): string; isEnum(): boolean; } interface KUniverse<A extends org.kevoree.modeling.KView, B extends org.kevoree.modeling.KUniverse<any, any, any>, C extends org.kevoree.modeling.KModel<any>> { key(): number; time(timePoint: number): A; model(): C; equals(other: any): boolean; diverge(): B; origin(): B; descendants(): java.util.List<B>; delete(cb: (p: any) => void): void; lookupAllTimes(uuid: number, times: number[], cb: (p: org.kevoree.modeling.KObject[]) => void): void; listenAll(groupId: number, objects: number[], multiListener: (p: org.kevoree.modeling.KObject[]) => void): void; } interface KView { createByName(metaClassName: string): org.kevoree.modeling.KObject; create(clazz: org.kevoree.modeling.meta.KMetaClass): org.kevoree.modeling.KObject; select(query: string, cb: (p: org.kevoree.modeling.KObject[]) => void): void; lookup(key: number, cb: (p: org.kevoree.modeling.KObject) => void): void; lookupAll(keys: number[], cb: (p: org.kevoree.modeling.KObject[]) => void): void; universe(): number; now(): number; json(): org.kevoree.modeling.format.KModelFormat; xmi(): org.kevoree.modeling.format.KModelFormat; equals(other: any): boolean; setRoot(elem: org.kevoree.modeling.KObject, cb: (p: any) => void): void; getRoot(cb: (p: org.kevoree.modeling.KObject) => void): void; } module abs { class AbstractDataType implements org.kevoree.modeling.KType { private _name; private _isEnum; constructor(p_name: string, p_isEnum: boolean); name(): string; isEnum(): boolean; } class AbstractKModel<A extends org.kevoree.modeling.KUniverse<any, any, any>> implements org.kevoree.modeling.KModel<any> { _manager: org.kevoree.modeling.memory.manager.KMemoryManager; private _key; constructor(); metaModel(): org.kevoree.modeling.meta.KMetaModel; connect(cb: (p: any) => void): void; close(cb: (p: any) => void): void; manager(): org.kevoree.modeling.memory.manager.KMemoryManager; newUniverse(): A; internalCreateUniverse(universe: number): A; internalCreateObject(universe: number, time: number, uuid: number, clazz: org.kevoree.modeling.meta.KMetaClass): org.kevoree.modeling.KObject; createProxy(universe: number, time: number, uuid: number, clazz: org.kevoree.modeling.meta.KMetaClass): org.kevoree.modeling.KObject; universe(key: number): A; save(cb: (p: any) => void): void; discard(cb: (p: any) => void): void; setContentDeliveryDriver(p_driver: org.kevoree.modeling.cdn.KContentDeliveryDriver): org.kevoree.modeling.KModel<any>; setScheduler(p_scheduler: org.kevoree.modeling.scheduler.KScheduler): org.kevoree.modeling.KModel<any>; setOperation(metaOperation: org.kevoree.modeling.meta.KMetaOperation, operation: (p: org.kevoree.modeling.KObject, p1: any[], p2: (p: any) => void) => void): void; setInstanceOperation(metaOperation: org.kevoree.modeling.meta.KMetaOperation, target: org.kevoree.modeling.KObject, operation: (p: org.kevoree.modeling.KObject, p1: any[], p2: (p: any) => void) => void): void; defer(): org.kevoree.modeling.defer.KDefer; key(): number; clearListenerGroup(groupID: number): void; nextGroup(): number; create(clazz: org.kevoree.modeling.meta.KMetaClass, universe: number, time: number): org.kevoree.modeling.KObject; createByName(metaClassName: string, universe: number, time: number): org.kevoree.modeling.KObject; } class AbstractKObject implements org.kevoree.modeling.KObject { _uuid: number; _time: number; _universe: number; private _metaClass; _manager: org.kevoree.modeling.memory.manager.KMemoryManager; private static OUT_OF_CACHE_MSG; constructor(p_universe: number, p_time: number, p_uuid: number, p_metaClass: org.kevoree.modeling.meta.KMetaClass, p_manager: org.kevoree.modeling.memory.manager.KMemoryManager); uuid(): number; metaClass(): org.kevoree.modeling.meta.KMetaClass; now(): number; universe(): number; timeWalker(): org.kevoree.modeling.KTimeWalker; delete(cb: (p: any) => void): void; select(query: string, cb: (p: org.kevoree.modeling.KObject[]) => void): void; listen(groupId: number, listener: (p: org.kevoree.modeling.KObject, p1: org.kevoree.modeling.meta.KMeta[]) => void): void; get(p_attribute: org.kevoree.modeling.meta.KMetaAttribute): any; getByName(atributeName: string): any; set(p_attribute: org.kevoree.modeling.meta.KMetaAttribute, payload: any): void; setByName(atributeName: string, payload: any): void; mutate(actionType: org.kevoree.modeling.KActionType, metaReference: org.kevoree.modeling.meta.KMetaReference, param: org.kevoree.modeling.KObject): void; internal_mutate(actionType: org.kevoree.modeling.KActionType, metaReferenceP: org.kevoree.modeling.meta.KMetaReference, param: org.kevoree.modeling.KObject, setOpposite: boolean): void; size(p_metaReference: org.kevoree.modeling.meta.KMetaReference): number; ref(p_metaReference: org.kevoree.modeling.meta.KMetaReference, cb: (p: org.kevoree.modeling.KObject[]) => void): void; visitAttributes(visitor: (p: org.kevoree.modeling.meta.KMetaAttribute, p1: any) => void): void; visit(p_visitor: (p: org.kevoree.modeling.KObject) => org.kevoree.modeling.traversal.visitor.KVisitResult, cb: (p: any) => void): void; private internal_visit(visitor, end, visited, traversed); toJSON(): string; toString(): string; equals(obj: any): boolean; hashCode(): number; jump(p_time: number, p_callback: (p: org.kevoree.modeling.KObject) => void): void; internal_transpose_ref(p: org.kevoree.modeling.meta.KMetaReference): org.kevoree.modeling.meta.KMetaReference; internal_transpose_att(p: org.kevoree.modeling.meta.KMetaAttribute): org.kevoree.modeling.meta.KMetaAttribute; internal_transpose_op(p: org.kevoree.modeling.meta.KMetaOperation): org.kevoree.modeling.meta.KMetaOperation; traversal(): org.kevoree.modeling.traversal.KTraversal; referencesWith(o: org.kevoree.modeling.KObject): org.kevoree.modeling.meta.KMetaReference[]; call(p_operation: org.kevoree.modeling.meta.KMetaOperation, p_params: any[], cb: (p: any) => void): void; manager(): org.kevoree.modeling.memory.manager.KMemoryManager; } class AbstractKUniverse<A extends org.kevoree.modeling.KView, B extends org.kevoree.modeling.KUniverse<any, any, any>, C extends org.kevoree.modeling.KModel<any>> implements org.kevoree.modeling.KUniverse<any, any, any> { _universe: number; _manager: org.kevoree.modeling.memory.manager.KMemoryManager; constructor(p_key: number, p_manager: org.kevoree.modeling.memory.manager.KMemoryManager); key(): number; model(): C; delete(cb: (p: any) => void): void; time(timePoint: number): A; internal_create(timePoint: number): A; equals(obj: any): boolean; origin(): B; diverge(): B; descendants(): java.util.List<B>; lookupAllTimes(uuid: number, times: number[], cb: (p: org.kevoree.modeling.KObject[]) => void): void; listenAll(groupId: number, objects: number[], multiListener: (p: org.kevoree.modeling.KObject[]) => void): void; } class AbstractKView implements org.kevoree.modeling.KView { _time: number; _universe: number; _manager: org.kevoree.modeling.memory.manager.KMemoryManager; constructor(p_universe: number, _time: number, p_manager: org.kevoree.modeling.memory.manager.KMemoryManager); now(): number; universe(): number; setRoot(elem: org.kevoree.modeling.KObject, cb: (p: any) => void): void; getRoot(cb: (p: any) => void): void; select(query: string, cb: (p: org.kevoree.modeling.KObject[]) => void): void; lookup(kid: number, cb: (p: org.kevoree.modeling.KObject) => void): void; lookupAll(keys: number[], cb: (p: org.kevoree.modeling.KObject[]) => void): void; create(clazz: org.kevoree.modeling.meta.KMetaClass): org.kevoree.modeling.KObject; createByName(metaClassName: string): org.kevoree.modeling.KObject; json(): org.kevoree.modeling.format.KModelFormat; xmi(): org.kevoree.modeling.format.KModelFormat; equals(obj: any): boolean; } class AbstractTimeWalker implements org.kevoree.modeling.KTimeWalker { private _origin; constructor(p_origin: org.kevoree.modeling.abs.AbstractKObject); private internal_times(start, end, cb); allTimes(cb: (p: number[]) => void): void; timesBefore(endOfSearch: number, cb: (p: number[]) => void): void; timesAfter(beginningOfSearch: number, cb: (p: number[]) => void): void; timesBetween(beginningOfSearch: number, endOfSearch: number, cb: (p: number[]) => void): void; } interface KLazyResolver { meta(): org.kevoree.modeling.meta.KMeta; } } module cdn { interface KContentDeliveryDriver { get(keys: org.kevoree.modeling.KContentKey[], callback: (p: string[]) => void): void; atomicGetIncrement(key: org.kevoree.modeling.KContentKey, cb: (p: number) => void): void; put(request: org.kevoree.modeling.cdn.KContentPutRequest, error: (p: java.lang.Throwable) => void): void; remove(keys: string[], error: (p: java.lang.Throwable) => void): void; connect(callback: (p: java.lang.Throwable) => void): void; close(callback: (p: java.lang.Throwable) => void): void; registerListener(groupId: number, origin: org.kevoree.modeling.KObject, listener: (p: org.kevoree.modeling.KObject, p1: org.kevoree.modeling.meta.KMeta[]) => void): void; registerMultiListener(groupId: number, origin: org.kevoree.modeling.KUniverse<any, any, any>, objects: number[], listener: (p: org.kevoree.modeling.KObject[]) => void): void; unregisterGroup(groupId: number): void; send(msgs: org.kevoree.modeling.message.KMessage): void; setManager(manager: org.kevoree.modeling.memory.manager.KMemoryManager): void; } interface KContentPutRequest { put(p_key: org.kevoree.modeling.KContentKey, p_payload: string): void; getKey(index: number): org.kevoree.modeling.KContentKey; getContent(index: number): string; size(): number; } module impl { class ContentPutRequest implements org.kevoree.modeling.cdn.KContentPutRequest { private _content; private static KEY_INDEX; private static CONTENT_INDEX; private static SIZE_INDEX; private _size; constructor(requestSize: number); put(p_key: org.kevoree.modeling.KContentKey, p_payload: string): void; getKey(index: number): org.kevoree.modeling.KContentKey; getContent(index: number): string; size(): number; } class MemoryContentDeliveryDriver implements org.kevoree.modeling.cdn.KContentDeliveryDriver { private backend; private _localEventListeners; static DEBUG: boolean; atomicGetIncrement(key: org.kevoree.modeling.KContentKey, cb: (p: number) => void): void; get(keys: org.kevoree.modeling.KContentKey[], callback: (p: string[]) => void): void; put(p_request: org.kevoree.modeling.cdn.KContentPutRequest, p_callback: (p: java.lang.Throwable) => void): void; remove(keys: string[], callback: (p: java.lang.Throwable) => void): void; connect(callback: (p: java.lang.Throwable) => void): void; close(callback: (p: java.lang.Throwable) => void): void; registerListener(groupId: number, p_origin: org.kevoree.modeling.KObject, p_listener: (p: org.kevoree.modeling.KObject, p1: org.kevoree.modeling.meta.KMeta[]) => void): void; unregisterGroup(groupId: number): void; registerMultiListener(groupId: number, origin: org.kevoree.modeling.KUniverse<any, any, any>, objects: number[], listener: (p: org.kevoree.modeling.KObject[]) => void): void; send(msgs: org.kevoree.modeling.message.KMessage): void; setManager(manager: org.kevoree.modeling.memory.manager.KMemoryManager): void; } } } module defer { interface KDefer { wait(resultName: string): (p: any) => void; waitDefer(previous: org.kevoree.modeling.defer.KDefer): org.kevoree.modeling.defer.KDefer; isDone(): boolean; getResult(resultName: string): any; then(cb: (p: any) => void): void; next(): org.kevoree.modeling.defer.KDefer; } module impl { class Defer implements org.kevoree.modeling.defer.KDefer { private _isDone; _isReady: boolean; private _nbRecResult; private _nbExpectedResult; private _nextTasks; private _results; private _thenCB; constructor(); setDoneOrRegister(next: org.kevoree.modeling.defer.KDefer): boolean; equals(obj: any): boolean; private informParentEnd(end); waitDefer(p_previous: org.kevoree.modeling.defer.KDefer): org.kevoree.modeling.defer.KDefer; next(): org.kevoree.modeling.defer.KDefer; wait(resultName: string): (p: any) => void; isDone(): boolean; getResult(resultName: string): any; then(cb: (p: any) => void): void; } } } module event { interface KEventListener { on(src: org.kevoree.modeling.KObject, modifications: org.kevoree.modeling.meta.KMeta[]): void; } interface KEventMultiListener { on(objects: org.kevoree.modeling.KObject[]): void; } module impl { class LocalEventListeners { private _manager; private _internalListenerKeyGen; private _simpleListener; private _multiListener; private _listener2Object; private _listener2Objects; private _obj2Listener; private _group2Listener; constructor(); registerListener(groupId: number, origin: org.kevoree.modeling.KObject, listener: (p: org.kevoree.modeling.KObject, p1: org.kevoree.modeling.meta.KMeta[]) => void): void; registerListenerAll(groupId: number, universe: number, objects: number[], listener: (p: org.kevoree.modeling.KObject[]) => void): void; unregister(groupId: number): void; clear(): void; setManager(manager: org.kevoree.modeling.memory.manager.KMemoryManager): void; dispatch(param: org.kevoree.modeling.message.KMessage): void; } } } module extrapolation { interface Extrapolation { extrapolate(current: org.kevoree.modeling.KObject, attribute: org.kevoree.modeling.meta.KMetaAttribute): any; mutate(current: org.kevoree.modeling.KObject, attribute: org.kevoree.modeling.meta.KMetaAttribute, payload: any): void; } module impl { class DiscreteExtrapolation implements org.kevoree.modeling.extrapolation.Extrapolation { private static INSTANCE; static instance(): org.kevoree.modeling.extrapolation.Extrapolation; extrapolate(current: org.kevoree.modeling.KObject, attribute: org.kevoree.modeling.meta.KMetaAttribute): any; mutate(current: org.kevoree.modeling.KObject, attribute: org.kevoree.modeling.meta.KMetaAttribute, payload: any): void; } class PolynomialExtrapolation implements org.kevoree.modeling.extrapolation.Extrapolation { private static _maxDegree; private static DEGREE; private static NUMSAMPLES; private static STEP; private static LASTTIME; private static WEIGHTS; private static INSTANCE; extrapolate(current: org.kevoree.modeling.KObject, attribute: org.kevoree.modeling.meta.KMetaAttribute): any; private extrapolateValue(segment, meta, index, time, timeOrigin); private maxErr(precision, degree); insert(time: number, value: number, timeOrigin: number, raw: org.kevoree.modeling.memory.struct.segment.KMemorySegment, index: number, precision: number, metaClass: org.kevoree.modeling.meta.KMetaClass): boolean; private tempError(computedWeights, times, values); private test_extrapolate(time, weights); private internal_extrapolate(t, raw, index, metaClass); private initial_feed(time, value, raw, index, metaClass); mutate(current: org.kevoree.modeling.KObject, attribute: org.kevoree.modeling.meta.KMetaAttribute, payload: any): void; private castNumber(payload); static instance(): org.kevoree.modeling.extrapolation.Extrapolation; } module maths { class AdjLinearSolverQr { numRows: number; numCols: number; private decomposer; maxRows: number; maxCols: number; Q: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F; R: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F; private Y; private Z; setA(A: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F): boolean; private solveU(U, b, n); solve(B: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F, X: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F): void; constructor(); setMaxSize(maxRows: number, maxCols: number): void; } class DenseMatrix64F { numRows: number; numCols: number; data: number[]; static MULT_COLUMN_SWITCH: number; static multTransA_smallMV(A: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F, B: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F, C: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F): void; static multTransA_reorderMV(A: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F, B: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F, C: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F): void; static multTransA_reorderMM(a: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F, b: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F, c: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F): void; static multTransA_smallMM(a: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F, b: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F, c: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F): void; static multTransA(a: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F, b: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F, c: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F): void; static setIdentity(mat: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F): void; static widentity(width: number): org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F; static identity(numRows: number, numCols: number): org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F; static fill(a: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F, value: number): void; get(index: number): number; set(index: number, val: number): number; plus(index: number, val: number): number; constructor(numRows: number, numCols: number); reshape(numRows: number, numCols: number, saveValues: boolean): void; cset(row: number, col: number, value: number): void; unsafe_get(row: number, col: number): number; getNumElements(): number; } class PolynomialFitEjml { A: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F; coef: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F; y: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F; solver: org.kevoree.modeling.extrapolation.impl.maths.AdjLinearSolverQr; constructor(degree: number); getCoef(): number[]; fit(samplePoints: number[], observations: number[]): void; } class QRDecompositionHouseholderColumn_D64 { dataQR: number[][]; v: number[]; numCols: number; numRows: number; minLength: number; gammas: number[]; gamma: number; tau: number; error: boolean; setExpectedMaxSize(numRows: number, numCols: number): void; getQ(Q: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F, compact: boolean): org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F; getR(R: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F, compact: boolean): org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F; decompose(A: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F): boolean; convertToColumnMajor(A: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F): void; householder(j: number): void; updateA(w: number): void; static findMax(u: number[], startU: number, length: number): number; static divideElements(j: number, numRows: number, u: number[], u_0: number): void; static computeTauAndDivide(j: number, numRows: number, u: number[], max: number): number; static rank1UpdateMultR(A: org.kevoree.modeling.extrapolation.impl.maths.DenseMatrix64F, u: number[], gamma: number, colA0: number, w0: number, w1: number, _temp: number[]): void; } } } } module format { interface KModelFormat { save(model: org.kevoree.modeling.KObject, cb: (p: string) => void): void; saveRoot(cb: (p: string) => void): void; load(payload: string, cb: (p: any) => void): void; } module json { class JsonFormat implements org.kevoree.modeling.format.KModelFormat { static KEY_META: string; static KEY_UUID: string; static KEY_ROOT: string; private _manager; private _universe; private _time; private static NULL_PARAM_MSG; constructor(p_universe: number, p_time: number, p_manager: org.kevoree.modeling.memory.manager.KMemoryManager); save(model: org.kevoree.modeling.KObject, cb: (p: string) => void): void; saveRoot(cb: (p: string) => void): void; load(payload: string, cb: (p: any) => void): void; } class JsonModelLoader { static load(manager: org.kevoree.modeling.memory.manager.KMemoryManager, universe: number, time: number, payload: string, callback: (p: java.lang.Throwable) => void): void; private static loadObj(p_param, manager, universe, time, p_mappedKeys, p_rootElem); private static transposeArr(plainRawSet, p_mappedKeys); } class JsonModelSerializer { static serialize(model: org.kevoree.modeling.KObject, callback: (p: string) => void): void; static printJSON(elem: org.kevoree.modeling.KObject, builder: java.lang.StringBuilder, isRoot: boolean): void; } class JsonObjectReader { private readObject; parseObject(payload: string): void; get(name: string): any; getAsStringArray(name: string): string[]; keys(): string[]; } class JsonRaw { static encode(raw: org.kevoree.modeling.memory.struct.segment.KMemorySegment, uuid: number, p_metaClass: org.kevoree.modeling.meta.KMetaClass, isRoot: boolean): string; } class JsonString { private static ESCAPE_CHAR; static encodeBuffer(buffer: java.lang.StringBuilder, chain: string): void; static encode(p_chain: string): string; static unescape(p_src: string): string; } } module xmi { class SerializationContext { ignoreGeneratedID: boolean; model: org.kevoree.modeling.KObject; finishCallback: (p: string) => void; printer: java.lang.StringBuilder; attributesVisitor: (p: org.kevoree.modeling.meta.KMetaAttribute, p1: any) => void; addressTable: org.kevoree.modeling.memory.struct.map.impl.ArrayLongMap<any>; elementsCount: org.kevoree.modeling.memory.struct.map.impl.ArrayStringMap<any>; packageList: java.util.ArrayList<string>; } class XMILoadingContext { xmiReader: org.kevoree.modeling.format.xmi.XmlParser; loadedRoots: org.kevoree.modeling.KObject; resolvers: java.util.ArrayList<org.kevoree.modeling.format.xmi.XMIResolveCommand>; map: org.kevoree.modeling.memory.struct.map.impl.ArrayStringMap<any>; elementsCount: org.kevoree.modeling.memory.struct.map.impl.ArrayStringMap<any>; successCallback: (p: java.lang.Throwable) => void; } class XMIModelLoader { static LOADER_XMI_LOCAL_NAME: string; static LOADER_XMI_XSI: string; static LOADER_XMI_NS_URI: string; static unescapeXml(src: string): string; static load(manager: org.kevoree.modeling.memory.manager.KMemoryManager, universe: number, time: number, str: string, callback: (p: java.lang.Throwable) => void): void; private static deserialize(manager, universe, time, context); private static callFactory(manager, universe, time, ctx, objectType); private static loadObject(manager, universe, time, ctx, xmiAddress, objectType); } class XMIModelSerializer { static save(model: org.kevoree.modeling.KObject, callback: (p: string) => void): void; } class XMIResolveCommand { private context; private target; private mutatorType; private refName; private ref; constructor(context: org.kevoree.modeling.format.xmi.XMILoadingContext, target: org.kevoree.modeling.KObject, mutatorType: org.kevoree.modeling.KActionType, refName: string, ref: string); run(): void; } class XmiFormat implements org.kevoree.modeling.format.KModelFormat { private _manager; private _universe; private _time; constructor(p_universe: number, p_time: number, p_manager: org.kevoree.modeling.memory.manager.KMemoryManager); save(model: org.kevoree.modeling.KObject, cb: (p: string) => void): void; saveRoot(cb: (p: string) => void): void; load(payload: string, cb: (p: any) => void): void; } class XmlParser { private payload; private current; private currentChar; private tagName; private tagPrefix; private attributePrefix; private readSingleton; private attributesNames; private attributesPrefixes; private attributesValues; private attributeName; private attributeValue; constructor(str: string); getTagPrefix(): string; hasNext(): boolean; getLocalName(): string; getAttributeCount(): number; getAttributeLocalName(i: number): string; getAttributePrefix(i: number): string; getAttributeValue(i: number): string; private readChar(); next(): org.kevoree.modeling.format.xmi.XmlToken; private read_lessThan(); private read_upperThan(); private read_xmlHeader(); private read_closingTag(); private read_openTag(); private read_tagName(); private read_attributes(); } class XmlToken { static XML_HEADER: XmlToken; static END_DOCUMENT: XmlToken; static START_TAG: XmlToken; static END_TAG: XmlToken; static COMMENT: XmlToken; static SINGLETON_TAG: XmlToken; equals(other: any): boolean; static _XmlTokenVALUES: XmlToken[]; static values(): XmlToken[]; } } } module infer { class AnalyticKInfer { } class GaussianClassificationKInfer { private alpha; getAlpha(): number; setAlpha(alpha: number): void; } interface KInfer extends org.kevoree.modeling.KObject { train(trainingSet: any[][], expectedResultSet: any[], callback: (p: java.lang.Throwable) => void): void; infer(features: any[]): any; accuracy(testSet: any[][], expectedResultSet: any[]): any; clear(): void; } class KInferState { save(): string; load(payload: string): void; isDirty(): boolean; cloneState(): org.kevoree.modeling.infer.KInferState; } class LinearRegressionKInfer { private alpha; private iterations; getAlpha(): number; setAlpha(alpha: number): void; getIterations(): number; setIterations(iterations: number): void; private calculate(weights, features); } class PerceptronClassificationKInfer { private alpha; private iterations; getAlpha(): number; setAlpha(alpha: number): void; getIterations(): number; setIterations(iterations: number): void; private calculate(weights, features); } class PolynomialOfflineKInfer { maxDegree: number; toleratedErr: number; getToleratedErr(): number; setToleratedErr(toleratedErr: number): void; getMaxDegree(): number; setMaxDegree(maxDegree: number): void; } class PolynomialOnlineKInfer { maxDegree: number; toleratedErr: number; getToleratedErr(): number; setToleratedErr(toleratedErr: number): void; getMaxDegree(): number; setMaxDegree(maxDegree: number): void; private calculateLong(time, weights, timeOrigin, unit); private calculate(weights, t); } class WinnowClassificationKInfer { private alpha; private beta; getAlpha(): number; setAlpha(alpha: number): void; getBeta(): number; setBeta(beta: number): void; private calculate(weights, features); } module states { class AnalyticKInferState extends org.kevoree.modeling.infer.KInferState { private _isDirty; private sumSquares; private sum; private nb; private min; private max; getSumSquares(): number; setSumSquares(sumSquares: number): void; getMin(): number; setMin(min: number): void; getMax(): number; setMax(max: number): void; getNb(): number; setNb(nb: number): void; getSum(): number; setSum(sum: number): void; getAverage(): number; train(value: number): void; getVariance(): number; clear(): void; save(): string; load(payload: string): void; isDirty(): boolean; cloneState(): org.kevoree.modeling.infer.KInferState; } class BayesianClassificationState extends org.kevoree.modeling.infer.KInferState { private states; private classStats; private numOfFeatures; private numOfClasses; private static stateSep; private static interStateSep; initialize(metaFeatures: any[], MetaClassification: any): void; predict(features: any[]): number; train(features: any[], classNum: number): void; save(): string; load(payload: string): void; isDirty(): boolean; cloneState(): org.kevoree.modeling.infer.KInferState; } class DoubleArrayKInferState extends org.kevoree.modeling.infer.KInferState { private _isDirty; private weights; save(): string; load(payload: string): void; isDirty(): boolean; set_isDirty(value: boolean): void; cloneState(): org.kevoree.modeling.infer.KInferState; getWeights(): number[]; setWeights(weights: number[]): void; } class GaussianArrayKInferState extends org.kevoree.modeling.infer.KInferState { private _isDirty; private sumSquares; private sum; private epsilon; private nb; getSumSquares(): number[]; setSumSquares(sumSquares: number[]): void; getNb(): number; setNb(nb: number): void; getSum(): number[]; setSum(sum: number[]): void; calculateProbability(features: number[]): number; infer(features: number[]): boolean; getAverage(): number[]; train(features: number[], result: boolean, alpha: number): void; getVariance(): number[]; clear(): void; save(): string; load(payload: string): void; isDirty(): boolean; cloneState(): org.kevoree.modeling.infer.KInferState; getEpsilon(): number; } class PolynomialKInferState extends org.kevoree.modeling.infer.KInferState { private _isDirty; private timeOrigin; private unit; private weights; getTimeOrigin(): number; setTimeOrigin(timeOrigin: number): void; is_isDirty(): boolean; getUnit(): number; setUnit(unit: number): void; static maxError(coef: number[], normalizedTimes: number[], results: number[]): number; private static internal_extrapolate(normalizedTime, coef); save(): string; load(payload: string): void; isDirty(): boolean; set_isDirty(value: boolean): void; cloneState(): org.kevoree.modeling.infer.KInferState; getWeights(): number[]; setWeights(weights: number[]): void; infer(time: number): any; } module Bayesian { class BayesianSubstate { calculateProbability(feature: any): number; train(feature: any): void; save(separator: string): string; load(payload: string, separator: string): void; cloneState(): org.kevoree.modeling.infer.states.Bayesian.BayesianSubstate; } class EnumSubstate extends org.kevoree.modeling.infer.states.Bayesian.BayesianSubstate { private counter; private total; getCounter(): number[]; setCounter(counter: number[]): void; getTotal(): number; setTotal(total: number): void; initialize(number: number): void; calculateProbability(feature: any): number; train(feature: any): void; save(separator: string): string; load(payload: string, separator: string): void; cloneState(): org.kevoree.modeling.infer.states.Bayesian.BayesianSubstate; } class GaussianSubState extends org.kevoree.modeling.infer.states.Bayesian.BayesianSubstate { private sumSquares; private sum; private nb; getSumSquares(): number; setSumSquares(sumSquares: number): void; getNb(): number; setNb(nb: number): void; getSum(): number; setSum(sum: number): void; calculateProbability(feature: any): number; getAverage(): number; train(feature: any): void; getVariance(): number; clear(): void; save(separator: string): string; load(payload: string, separator: string): void; cloneState(): org.kevoree.modeling.infer.states.Bayesian.BayesianSubstate; } } } } module memory { interface KMemoryElement { isDirty(): boolean; setClean(metaModel: org.kevoree.modeling.meta.KMetaModel): void; setDirty(): void; serialize(metaModel: org.kevoree.modeling.meta.KMetaModel): string; init(payload: string, metaModel: org.kevoree.modeling.meta.KMetaModel): void; counter(): number; inc(): void; dec(): void; free(metaModel: org.kevoree.modeling.meta.KMetaModel): void; } interface KMemoryFactory { newCacheSegment(): org.kevoree.modeling.memory.struct.segment.KMemorySegment; newLongTree(): org.kevoree.modeling.memory.struct.tree.KLongTree; newLongLongTree(): org.kevoree.modeling.memory.struct.tree.KLongLongTree; newUniverseMap(initSize: number, className: string): org.kevoree.modeling.memory.struct.map.KUniverseOrderMap; newFromKey(universe: number, time: number, uuid: number): org.kevoree.modeling.memory.KMemoryElement; } module cache { interface KCache { get(universe: number, time: number, obj: number): org.kevoree.modeling.memory.KMemoryElement; put(universe: number, time: number, obj: number, payload: org.kevoree.modeling.memory.KMemoryElement): void; dirties(): org.kevoree.modeling.memory.cache.impl.KCacheDirty[]; clear(metaModel: org.kevoree.modeling.meta.KMetaModel): void; clean(metaModel: org.kevoree.modeling.meta.KMetaModel): void; monitor(origin: org.kevoree.modeling.KObject): void; size(): number; } module impl { class HashMemoryCache implements org.kevoree.modeling.memory.cache.KCache { private elementData; private elementCount; private elementDataSize; private loadFactor; private initalCapacity; private threshold; get(universe: number, time: number, obj: number): org.kevoree.modeling.memory.KMemoryElement; put(universe: number, time: number, obj: number, payload: org.kevoree.modeling.memory.KMemoryElement): void; private complex_insert(previousIndex, hash, universe, time, obj); dirties(): org.kevoree.modeling.memory.cache.impl.KCacheDirty[]; clean(metaModel: org.kevoree.modeling.meta.KMetaModel): void; monitor(origin: org.kevoree.modeling.KObject): void; size(): number; private remove(universe, time, obj, p_metaModel); constructor(); clear(metaModel: org.kevoree.modeling.meta.KMetaModel): void; } module HashMemoryCache { class Entry { next: org.kevoree.modeling.memory.cache.impl.HashMemoryCache.Entry; universe: number; time: number; obj: number; value: org.kevoree.modeling.memory.KMemoryElement; } } class KCacheDirty { key: org.kevoree.modeling.KContentKey; object: org.kevoree.modeling.memory.KMemoryElement; constructor(key: org.kevoree.modeling.KContentKey, object: org.kevoree.modeling.memory.KMemoryElement); } } } module manager { class AccessMode { static RESOLVE: AccessMode; static NEW: AccessMode; static DELETE: AccessMode; equals(other: any): boolean; static _AccessModeVALUES: AccessMode[]; static values(): AccessMode[]; } interface KMemoryManager { cdn(): org.kevoree.modeling.cdn.KContentDeliveryDriver; model(): org.kevoree.modeling.KModel<any>; cache(): org.kevoree.modeling.memory.cache.KCache; lookup(universe: number, time: number, uuid: number, callback: (p: org.kevoree.modeling.KObject) => void): void; lookupAllobjects(universe: number, time: number, uuid: number[], callback: (p: org.kevoree.modeling.KObject[]) => void): void; lookupAlltimes(universe: number, time: number[], uuid: number, callback: (p: org.kevoree.modeling.KObject[]) => void): void; segment(universe: number, time: number, uuid: number, accessMode: org.kevoree.modeling.memory.manager.AccessMode, metaClass: org.kevoree.modeling.meta.KMetaClass, resolutionTrace: org.kevoree.modeling.memory.manager.KMemorySegmentResolutionTrace): org.kevoree.modeling.memory.struct.segment.KMemorySegment; save(callback: (p: java.lang.Throwable) => void): void; discard(universe: org.kevoree.modeling.KUniverse<any, any, any>, callback: (p: java.lang.Throwable) => void): void; delete(universe: org.kevoree.modeling.KUniverse<any, any, any>, callback: (p: java.lang.Throwable) => void): void; initKObject(obj: org.kevoree.modeling.KObject): void; initUniverse(universe: org.kevoree.modeling.KUniverse<any, any, any>, parent: org.kevoree.modeling.KUniverse<any, any, any>): void; nextUniverseKey(): number; nextObjectKey(): number; nextModelKey(): number; nextGroupKey(): number; getRoot(universe: number, time: number, callback: (p: org.kevoree.modeling.KObject) => void): void; setRoot(newRoot: org.kevoree.modeling.KObject, callback: (p: java.lang.Throwable) => void): void; setContentDeliveryDriver(driver: org.kevoree.modeling.cdn.KContentDeliveryDriver): void; setScheduler(scheduler: org.kevoree.modeling.scheduler.KScheduler): void; operationManager(): org.kevoree.modeling.operation.KOperationManager; connect(callback: (p: java.lang.Throwable) => void): void; close(callback: (p: java.lang.Throwable) => void): void; parentUniverseKey(currentUniverseKey: number): number; descendantsUniverseKeys(currentUniverseKey: number): number[]; reload(keys: org.kevoree.modeling.KContentKey[], callback: (p: java.lang.Throwable) => void): void; cleanCache(): void; setFactory(factory: org.kevoree.modeling.memory.KMemoryFactory): void; } interface KMemorySegmentResolutionTrace { getUniverse(): number; setUniverse(universe: number): void; getTime(): number; setTime(time: number): void; getUniverseTree(): org.kevoree.modeling.memory.struct.map.KUniverseOrderMap; setUniverseOrder(orderMap: org.kevoree.modeling.memory.struct.map.KUniverseOrderMap): void; getTimeTree(): org.kevoree.modeling.memory.struct.tree.KLongTree; setTimeTree(tree: org.kevoree.modeling.memory.struct.tree.KLongTree): void; getSegment(): org.kevoree.modeling.memory.struct.segment.KMemorySegment; setSegment(tree: org.kevoree.modeling.memory.struct.segment.KMemorySegment): void; } module impl { class HeapMemoryManager implements org.kevoree.modeling.memory.manager.KMemoryManager { private static OUT_OF_CACHE_MESSAGE; private static UNIVERSE_NOT_CONNECTED_ERROR; private _db; private _operationManager; private _scheduler; private _model; private _factory; private _objectKeyCalculator; private _universeKeyCalculator; private _modelKeyCalculator; private _groupKeyCalculator; private isConnected; private _cache; private static UNIVERSE_INDEX; private static OBJ_INDEX; private static GLO_TREE_INDEX; private static zeroPrefix; constructor(model: org.kevoree.modeling.KModel<any>); cache(): org.kevoree.modeling.memory.cache.KCache; model(): org.kevoree.modeling.KModel<any>; close(callback: (p: java.lang.Throwable) => void): void; nextUniverseKey(): number; nextObjectKey(): number; nextModelKey(): number; nextGroupKey(): number; globalUniverseOrder(): org.kevoree.modeling.memory.struct.map.KUniverseOrderMap; initUniverse(p_universe: org.kevoree.modeling.KUniverse<any, any, any>, p_parent: org.kevoree.modeling.KUniverse<any, any, any>): void; parentUniverseKey(currentUniverseKey: number): number; descendantsUniverseKeys(currentUniverseKey: number): number[]; save(callback: (p: java.lang.Throwable) => void): void; initKObject(obj: org.kevoree.modeling.KObject): void; connect(connectCallback: (p: java.lang.Throwable) => void): void; segment(universe: number, time: number, uuid: number, accessMode: org.kevoree.modeling.memory.manager.AccessMode, metaClass: org.kevoree.modeling.meta.KMetaClass, resolutionTrace: org.kevoree.modeling.memory.manager.KMemorySegmentResolutionTrace): org.kevoree.modeling.memory.struct.segment.KMemorySegment; discard(p_universe: org.kevoree.modeling.KUniverse<any, any, any>, callback: (p: java.lang.Throwable) => void): void; delete(p_universe: org.kevoree.modeling.KUniverse<any, any, any>, callback: (p: java.lang.Throwable) => void): void; lookup(universe: number, time: number, uuid: number, callback: (p: org.kevoree.modeling.KObject) => void): void; lookupAllobjects(universe: number, time: number, uuids: number[], callback: (p: org.kevoree.modeling.KObject[]) => void): void; lookupAlltimes(universe: number, time: number[], uuid: number, callback: (p: org.kevoree.modeling.KObject[]) => void): void; cdn(): org.kevoree.modeling.cdn.KContentDeliveryDriver; setContentDeliveryDriver(p_dataBase: org.kevoree.modeling.cdn.KContentDeliveryDriver): void; setScheduler(p_scheduler: org.kevoree.modeling.scheduler.KScheduler): void; operationManager(): org.kevoree.modeling.operation.KOperationManager; getRoot(universe: number, time: number, callback: (p: org.kevoree.modeling.KObject) => void): void; setRoot(newRoot: org.kevoree.modeling.KObject, callback: (p: java.lang.Throwable) => void): void; reload(keys: org.kevoree.modeling.KContentKey[], callback: (p: java.lang.Throwable) => void): void; cleanCache(): void; setFactory(p_factory: org.kevoree.modeling.memory.KMemoryFactory): void; bumpKeyToCache(contentKey: org.kevoree.modeling.KContentKey, callback: (p: org.kevoree.modeling.memory.KMemoryElement) => void): void; bumpKeysToCache(contentKeys: org.kevoree.modeling.KContentKey[], callback: (p: org.kevoree.modeling.memory.KMemoryElement[]) => void): void; private internal_unserialize(key, payload); } class KeyCalculator { private _prefix; private _currentIndex; constructor(prefix: number, currentIndex: number); nextKey(): number; lastComputedIndex(): number; prefix(): number; } class LookupAllRunnable implements java.lang.Runnable { private _universe; private _time; private _keys; private _callback; private _store; constructor(p_universe: number, p_time: number, p_keys: number[], p_callback: (p: org.kevoree.modeling.KObject[]) => void, p_store: org.kevoree.modeling.memory.manager.impl.HeapMemoryManager); run(): void; } class MemorySegmentResolutionTrace implements org.kevoree.modeling.memory.manager.KMemorySegmentResolutionTrace { private _universe; private _time; private _universeOrder; private _timeTree; private _segment; getUniverse(): number; setUniverse(p_universe: number): void; getTime(): number; setTime(p_time: number): void; getUniverseTree(): org.kevoree.modeling.memory.struct.map.KUniverseOrderMap; setUniverseOrder(p_u_tree: org.kevoree.modeling.memory.struct.map.KUniverseOrderMap): void; getTimeTree(): org.kevoree.modeling.memory.struct.tree.KLongTree; setTimeTree(p_t_tree: org.kevoree.modeling.memory.struct.tree.KLongTree): void; getSegment(): org.kevoree.modeling.memory.struct.segment.KMemorySegment; setSegment(p_segment: org.kevoree.modeling.memory.struct.segment.KMemorySegment): void; } class ResolutionHelper { static resolve_trees(universe: number, time: number, uuid: number, cache: org.kevoree.modeling.memory.cache.KCache): org.kevoree.modeling.memory.manager.impl.MemorySegmentResolutionTrace; static resolve_universe(globalTree: org.kevoree.modeling.memory.struct.map.KLongLongMap, objUniverseTree: org.kevoree.modeling.memory.struct.map.KLongLongMap, timeToResolve: number, originUniverseId: number): number; static universeSelectByRange(globalTree: org.kevoree.modeling.memory.struct.map.KLongLongMap, objUniverseTree: org.kevoree.modeling.memory.struct.map.KLongLongMap, rangeMin: number, rangeMax: number, originUniverseId: number): number[]; } } } module struct { class HeapMemoryFactory implements org.kevoree.modeling.memory.KMemoryFactory { newCacheSegment(): org.kevoree.modeling.memory.struct.segment.KMemorySegment; newLongTree(): org.kevoree.modeling.memory.struct.tree.KLongTree; newLongLongTree(): org.kevoree.modeling.memory.struct.tree.KLongLongTree; newUniverseMap(initSize: number, p_className: string): org.kevoree.modeling.memory.struct.map.KUniverseOrderMap; newFromKey(universe: number, time: number, uuid: number): org.kevoree.modeling.memory.KMemoryElement; } module map { interface KIntMap<V> { contains(key: number): boolean; get(key: number): V; put(key: number, value: V): void; each(callback: (p: number, p1: V) => void): void; } interface KIntMapCallBack<V> { on(key: number, value: V): void; } interface KLongLongMap { contains(key: number): boolean; get(key: number): number; put(key: number, value: number): void; each(callback: (p: number, p1: number) => void): void; size(): number; clear(): void; } interface KLongLongMapCallBack<V> { on(key: number, value: number): void; } interface KLongMap<V> { contains(key: number): boolean; get(key: number): V; put(key: number, value: V): void; each(callback: (p: number, p1: V) => void): void; size(): number; clear(): void; } interface KLongMapCallBack<V> { on(key: number, value: V): void; } interface KStringMap<V> { contains(key: string): boolean; get(key: string): V; put(key: string, value: V): void; each(callback: (p: string, p1: V) => void): void; size(): number; clear(): void; remove(key: string): void; } interface KStringMapCallBack<V> { on(key: string, value: V): void; } interface KUniverseOrderMap extends org.kevoree.modeling.memory.struct.map.KLongLongMap, org.kevoree.modeling.memory.KMemoryElement { metaClassName(): string; } module impl { class ArrayIntMap<V> implements org.kevoree.modeling.memory.struct.map.KIntMap<any> { constructor(initalCapacity: number, loadFactor: number); clear(): void; get(key: number): V; put(key: number, pval: V): V; contains(key: number): boolean; remove(key: number): V; size(): number; each(callback: (p: number, p1: V) => void): void; } class ArrayLongLongMap implements org.kevoree.modeling.memory.struct.map.KLongLongMap { private _isDirty; constructor(initalCapacity: number, loadFactor: number); clear(): void; get(key: number): number; put(key: number, pval: number): void; contains(key: number): boolean; remove(key: number): number; size(): number; each(callback: (p: number, p1: number) => void): void; isDirty(): boolean; setClean(mm: any): void; setDirty(): void; } class ArrayLongMap<V> implements org.kevoree.modeling.memory.struct.map.KLongMap<any> { constructor(initalCapacity: number, loadFactor: number); clear(): void; get(key: number): V; put(key: number, pval: V): V; contains(key: number): boolean; remove(key: number): V; size(): number; each(callback: (p: number, p1: V) => void): void; } class ArrayStringMap<V> implements org.kevoree.modeling.memory.struct.map.KStringMap<any> { constructor(initalCapacity: number, loadFactor: number); clear(): void; get(key: string): V; put(key: string, pval: V): V; contains(key: string): boolean; remove(key: string): V; size(): number; each(callback: (p: string, p1: V) => void): void; } class ArrayUniverseOrderMap extends org.kevoree.modeling.memory.struct.map.impl.ArrayLongLongMap implements org.kevoree.modeling.memory.struct.map.KUniverseOrderMap { private _counter; private _className; constructor(initalCapacity: number, loadFactor: number, p_className: string); metaClassName(): string; counter(): number; inc(): void; dec(): void; free(): void; size(): number; serialize(m: any): string; init(payload: string, metaModel: org.kevoree.modeling.meta.KMetaModel): void; } } } module segment { interface KMemorySegment extends org.kevoree.modeling.memory.KMemoryElement { clone(metaClass: org.kevoree.modeling.meta.KMetaClass): org.kevoree.modeling.memory.struct.segment.KMemorySegment; set(index: number, content: any, metaClass: org.kevoree.modeling.meta.KMetaClass): void; get(index: number, metaClass: org.kevoree.modeling.meta.KMetaClass): any; getRefSize(index: number, metaClass: org.kevoree.modeling.meta.KMetaClass): number; getRefElem(index: number, refIndex: number, metaClass: org.kevoree.modeling.meta.KMetaClass): number; getRef(index: number, metaClass: org.kevoree.modeling.meta.KMetaClass): number[]; addRef(index: number, newRef: number, metaClass: org.kevoree.modeling.meta.KMetaClass): boolean; removeRef(index: number, previousRef: number, metaClass: org.kevoree.modeling.meta.KMetaClass): boolean; getInfer(index: number, metaClass: org.kevoree.modeling.meta.KMetaClass): number[]; getInferSize(index: number, metaClass: org.kevoree.modeling.meta.KMetaClass): number; getInferElem(index: number, arrayIndex: number, metaClass: org.kevoree.modeling.meta.KMetaClass): number; setInferElem(index: number, arrayIndex: number, valueToInsert: number, metaClass: org.kevoree.modeling.meta.KMetaClass): void; extendInfer(index: number, newSize: number, metaClass: org.kevoree.modeling.meta.KMetaClass): void; modifiedIndexes(metaClass: org.kevoree.modeling.meta.KMetaClass): number[]; initMetaClass(metaClass: org.kevoree.modeling.meta.KMetaClass): void; metaClassIndex(): number; } module impl { class HeapMemorySegment implements org.kevoree.modeling.memory.struct.segment.KMemorySegment { private raw; private _counter; private _metaClassIndex; private _modifiedIndexes; private _dirty; initMetaClass(p_metaClass: org.kevoree.modeling.meta.KMetaClass): void; metaClassIndex(): number; isDirty(): boolean; serialize(metaModel: org.kevoree.modeling.meta.KMetaModel): string; modifiedIndexes(p_metaClass: org.kevoree.modeling.meta.KMetaClass): number[]; setClean(metaModel: org.kevoree.modeling.meta.KMetaModel): void; setDirty(): void; init(payload: string, metaModel: org.kevoree.modeling.meta.KMetaModel): void; counter(): number; inc(): void; dec(): void; free(metaModel: org.kevoree.modeling.meta.KMetaModel): void; get(index: number, p_metaClass: org.kevoree.modeling.meta.KMetaClass): any; getRefSize(index: number, metaClass: org.kevoree.modeling.meta.KMetaClass): number; getRefElem(index: number, refIndex: number, metaClass: org.kevoree.modeling.meta.KMetaClass): number; getRef(index: number, p_metaClass: org.kevoree.modeling.meta.KMetaClass): number[]; addRef(index: number, newRef: number, metaClass: org.kevoree.modeling.meta.KMetaClass): boolean; removeRef(index: number, refToRemove: number, metaClass: org.kevoree.modeling.meta.KMetaClass): boolean; getInfer(index: number, metaClass: org.kevoree.modeling.meta.KMetaClass): number[]; getInferSize(index: number, metaClass: org.kevoree.modeling.meta.KMetaClass): number; getInferElem(index: number, arrayIndex: number, metaClass: org.kevoree.modeling.meta.KMetaClass): number; setInferElem(index: number, arrayIndex: number, valueToInsert: number, metaClass: org.kevoree.modeling.meta.KMetaClass): void; extendInfer(index: number, newSize: number, metaClass: org.kevoree.modeling.meta.KMetaClass): void; set(index: number, content: any, p_metaClass: org.kevoree.modeling.meta.KMetaClass): void; clone(p_metaClass: org.kevoree.modeling.meta.KMetaClass): org.kevoree.modeling.memory.struct.segment.KMemorySegment; } } } module tree { interface KLongLongTree extends org.kevoree.modeling.memory.struct.tree.KTree { insert(key: number, value: number): void; previousOrEqualValue(key: number): number; lookupValue(key: number): number; } interface KLongTree extends org.kevoree.modeling.memory.struct.tree.KTree { insert(key: number): void; previousOrEqual(key: number): number; lookup(key: number): number; range(startKey: number, endKey: number, walker: (p: number) => void): void; delete(key: number): void; } interface KTree extends org.kevoree.modeling.memory.KMemoryElement { size(): number; } interface KTreeWalker { elem(t: number): void; } module impl { class LongLongTree implements org.kevoree.modeling.memory.KMemoryElement, org.kevoree.modeling.memory.struct.tree.KLongLongTree { private root; private _size; _dirty: boolean; private _counter; private _previousOrEqualsCacheValues; private _previousOrEqualsNextCacheElem; private _lookupCacheValues; private _lookupNextCacheElem; size(): number; counter(): number; inc(): void; dec(): void; free(metaModel: org.kevoree.modeling.meta.KMetaModel): void; toString(): string; isDirty(): boolean; setDirty(): void; serialize(metaModel: org.kevoree.modeling.meta.KMetaModel): string; constructor(); private tryPreviousOrEqualsCache(key); private tryLookupCache(key); private resetCache(); private putInPreviousOrEqualsCache(resolved); private putInLookupCache(resolved); setClean(metaModel: org.kevoree.modeling.meta.KMetaModel): void; init(payload: string, metaModel: org.kevoree.modeling.meta.KMetaModel): void; lookupValue(key: number): number; private internal_lookup(key); previousOrEqualValue(key: number): number; private internal_previousOrEqual(key); nextOrEqual(key: number): org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode; previous(key: number): org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode; next(key: number): org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode; first(): org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode; last(): org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode; private rotateLeft(n); private rotateRight(n); private replaceNode(oldn, newn); insert(key: number, value: number): void; private insertCase1(n); private insertCase2(n); private insertCase3(n); private insertCase4(n_n); private insertCase5(n); delete(key: number): void; private deleteCase1(n); private deleteCase2(n); private deleteCase3(n); private deleteCase4(n); private deleteCase5(n); private deleteCase6(n); private nodeColor(n); } class LongTree implements org.kevoree.modeling.memory.KMemoryElement, org.kevoree.modeling.memory.struct.tree.KLongTree { private _size; private root; private _previousOrEqualsCacheValues; private _nextCacheElem; private _counter; private _dirty; constructor(); size(): number; counter(): number; inc(): void; dec(): void; free(metaModel: org.kevoree.modeling.meta.KMetaModel): void; private tryPreviousOrEqualsCache(key); private resetCache(); private putInPreviousOrEqualsCache(resolved); isDirty(): boolean; setClean(metaModel: org.kevoree.modeling.meta.KMetaModel): void; setDirty(): void; serialize(metaModel: org.kevoree.modeling.meta.KMetaModel): string; toString(): string; init(payload: string, metaModel: org.kevoree.modeling.meta.KMetaModel): void; previousOrEqual(key: number): number; internal_previousOrEqual(key: number): org.kevoree.modeling.memory.struct.tree.impl.TreeNode; nextOrEqual(key: number): org.kevoree.modeling.memory.struct.tree.impl.TreeNode; previous(key: number): org.kevoree.modeling.memory.struct.tree.impl.TreeNode; next(key: number): org.kevoree.modeling.memory.struct.tree.impl.TreeNode; first(): org.kevoree.modeling.memory.struct.tree.impl.TreeNode; last(): org.kevoree.modeling.memory.struct.tree.impl.TreeNode; lookup(key: number): number; range(start: number, end: number, walker: (p: number) => void): void; private rotateLeft(n); private rotateRight(n); private replaceNode(oldn, newn); insert(key: number): void; private insertCase1(n); private insertCase2(n); private insertCase3(n); private insertCase4(n_n); private insertCase5(n); delete(key: number): void; private deleteCase1(n); private deleteCase2(n); private deleteCase3(n); private deleteCase4(n); private deleteCase5(n); private deleteCase6(n); private nodeColor(n); } class LongTreeNode { static BLACK: string; static RED: string; key: number; value: number; color: boolean; private left; private right; private parent; constructor(key: number, value: number, color: boolean, left: org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode, right: org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode); grandparent(): org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode; sibling(): org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode; uncle(): org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode; getLeft(): org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode; setLeft(left: org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode): void; getRight(): org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode; setRight(right: org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode): void; getParent(): org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode; setParent(parent: org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode): void; serialize(builder: java.lang.StringBuilder): void; next(): org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode; previous(): org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode; static unserialize(ctx: org.kevoree.modeling.memory.struct.tree.impl.TreeReaderContext): org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode; static internal_unserialize(rightBranch: boolean, ctx: org.kevoree.modeling.memory.struct.tree.impl.TreeReaderContext): org.kevoree.modeling.memory.struct.tree.impl.LongTreeNode; } class TreeNode { static BLACK: string; static RED: string; key: number; color: boolean; private left; private right; private parent; constructor(key: number, color: boolean, left: org.kevoree.modeling.memory.struct.tree.impl.TreeNode, right: org.kevoree.modeling.memory.struct.tree.impl.TreeNode); getKey(): number; grandparent(): org.kevoree.modeling.memory.struct.tree.impl.TreeNode; sibling(): org.kevoree.modeling.memory.struct.tree.impl.TreeNode; uncle(): org.kevoree.modeling.memory.struct.tree.impl.TreeNode; getLeft(): org.kevoree.modeling.memory.struct.tree.impl.TreeNode; setLeft(left: org.kevoree.modeling.memory.struct.tree.impl.TreeNode): void; getRight(): org.kevoree.modeling.memory.struct.tree.impl.TreeNode; setRight(right: org.kevoree.modeling.memory.struct.tree.impl.TreeNode): void; getParent(): org.kevoree.modeling.memory.struct.tree.impl.TreeNode; setParent(parent: org.kevoree.modeling.memory.struct.tree.impl.TreeNode): void; serialize(builder: java.lang.StringBuilder): void; next(): org.kevoree.modeling.memory.struct.tree.impl.TreeNode; previous(): org.kevoree.modeling.memory.struct.tree.impl.TreeNode; static unserialize(ctx: org.kevoree.modeling.memory.struct.tree.impl.TreeReaderContext): org.kevoree.modeling.memory.struct.tree.impl.TreeNode; static internal_unserialize(rightBranch: boolean, ctx: org.kevoree.modeling.memory.struct.tree.impl.TreeReaderContext): org.kevoree.modeling.memory.struct.tree.impl.TreeNode; } class TreeReaderContext { payload: string; index: number; buffer: string[]; } } } } } module message { interface KMessage { json(): string; type(): number; } class KMessageLoader { static TYPE_NAME: string; static OPERATION_NAME: string; static KEY_NAME: string; static KEYS_NAME: string; static ID_NAME: string; static VALUE_NAME: string; static VALUES_NAME: string; static CLASS_IDX_NAME: string; static PARAMETERS_NAME: string; static EVENTS_TYPE: number; static GET_REQ_TYPE: number; static GET_RES_TYPE: number; static PUT_REQ_TYPE: number; static PUT_RES_TYPE: number; static OPERATION_CALL_TYPE: number; static OPERATION_RESULT_TYPE: number; static ATOMIC_GET_INC_REQUEST_TYPE: number; static ATOMIC_GET_INC_RESULT_TYPE: number; static load(payload: string): org.kevoree.modeling.message.KMessage; } module impl { class AtomicGetIncrementRequest implements org.kevoree.modeling.message.KMessage { id: number; key: org.kevoree.modeling.KContentKey; json(): string; type(): number; } class AtomicGetIncrementResult implements org.kevoree.modeling.message.KMessage { id: number; value: number; json(): string; type(): number; } class Events implements org.kevoree.modeling.message.KMessage { _objIds: org.kevoree.modeling.KContentKey[]; _metaindexes: number[][]; private _size; allKeys(): org.kevoree.modeling.KContentKey[]; constructor(nbObject: number); json(): string; type(): number; size(): number; setEvent(index: number, p_objId: org.kevoree.modeling.KContentKey, p_metaIndexes: number[]): void; getKey(index: number): org.kevoree.modeling.KContentKey; getIndexes(index: number): number[]; } class GetRequest implements org.kevoree.modeling.message.KMessage { id: number; keys: org.kevoree.modeling.KContentKey[]; json(): string; type(): number; } class GetResult implements org.kevoree.modeling.message.KMessage { id: number; values: string[]; json(): string; type(): number; } class MessageHelper { static printJsonStart(builder: java.lang.StringBuilder): void; static printJsonEnd(builder: java.lang.StringBuilder): void; static printType(builder: java.lang.StringBuilder, type: number): void; static printElem(elem: any, name: string, builder: java.lang.StringBuilder): void; } class OperationCallMessage implements org.kevoree.modeling.message.KMessage { id: number; classIndex: number; opIndex: number; params: string[]; key: org.kevoree.modeling.KContentKey; json(): string; type(): number; } class OperationResultMessage implements org.kevoree.modeling.message.KMessage { id: number; value: string; key: org.kevoree.modeling.KContentKey; json(): string; type(): number; } class PutRequest implements org.kevoree.modeling.message.KMessage { request: org.kevoree.modeling.cdn.KContentPutRequest; id: number; json(): string; type(): number; } class PutResult implements org.kevoree.modeling.message.KMessage { id: number; json(): string; type(): number; } } } module meta { interface KMeta { index(): number; metaName(): string; metaType(): org.kevoree.modeling.meta.MetaType; } interface KMetaAttribute extends org.kevoree.modeling.meta.KMeta { key(): boolean; attributeType(): org.kevoree.modeling.KType; strategy(): org.kevoree.modeling.extrapolation.Extrapolation; precision(): number; setExtrapolation(extrapolation: org.kevoree.modeling.extrapolation.Extrapolation): void; setPrecision(precision: number): void; } interface KMetaClass extends org.kevoree.modeling.meta.KMeta { metaElements(): org.kevoree.modeling.meta.KMeta[]; meta(index: number): org.kevoree.modeling.meta.KMeta; metaByName(name: string): org.kevoree.modeling.meta.KMeta; attribute(name: string): org.kevoree.modeling.meta.KMetaAttribute; reference(name: string): org.kevoree.modeling.meta.KMetaReference; operation(name: string): org.kevoree.modeling.meta.KMetaOperation; addAttribute(attributeName: string, p_type: org.kevoree.modeling.KType): org.kevoree.modeling.meta.KMetaAttribute; addReference(referenceName: string, metaClass: org.kevoree.modeling.meta.KMetaClass, oppositeName: string, toMany: boolean): org.kevoree.modeling.meta.KMetaReference; addOperation(operationName: string): org.kevoree.modeling.meta.KMetaOperation; } interface KMetaModel extends org.kevoree.modeling.meta.KMeta { metaClasses(): org.kevoree.modeling.meta.KMetaClass[]; metaClassByName(name: string): org.kevoree.modeling.meta.KMetaClass; metaClass(index: number): org.kevoree.modeling.meta.KMetaClass; addMetaClass(metaClassName: string): org.kevoree.modeling.meta.KMetaClass; model(): org.kevoree.modeling.KModel<any>; } interface KMetaOperation extends org.kevoree.modeling.meta.KMeta { origin(): org.kevoree.modeling.meta.KMeta; } interface KMetaReference extends org.kevoree.modeling.meta.KMeta { visible(): boolean; single(): boolean; type(): org.kevoree.modeling.meta.KMetaClass; opposite(): org.kevoree.modeling.meta.KMetaReference; origin(): org.kevoree.modeling.meta.KMetaClass; } class KPrimitiveTypes { static STRING: org.kevoree.modeling.KType; static LONG: org.kevoree.modeling.KType; static INT: org.kevoree.modeling.KType; static BOOL: org.kevoree.modeling.KType; static SHORT: org.kevoree.modeling.KType; static DOUBLE: org.kevoree.modeling.KType; static FLOAT: org.kevoree.modeling.KType; static CONTINUOUS: org.kevoree.modeling.KType; } class MetaType { static ATTRIBUTE: MetaType; static REFERENCE: MetaType; static OPERATION: MetaType; static CLASS: MetaType; static MODEL: MetaType; equals(other: any): boolean; static _MetaTypeVALUES: MetaType[]; static values(): MetaType[]; } module impl { class GenericModel extends org.kevoree.modeling.abs.AbstractKModel<any> { private _p_metaModel; constructor(mm: org.kevoree.modeling.meta.KMetaModel); metaModel(): org.kevoree.modeling.meta.KMetaModel; internalCreateUniverse(universe: number): org.kevoree.modeling.KUniverse<any, any, any>; internalCreateObject(universe: number, time: number, uuid: number, clazz: org.kevoree.modeling.meta.KMetaClass): org.kevoree.modeling.KObject; } class GenericObject extends org.kevoree.modeling.abs.AbstractKObject { constructor(p_universe: number, p_time: number, p_uuid: number, p_metaClass: org.kevoree.modeling.meta.KMetaClass, p_manager: org.kevoree.modeling.memory.manager.KMemoryManager); } class GenericUniverse extends org.kevoree.modeling.abs.AbstractKUniverse<any, any, any> { constructor(p_key: number, p_manager: org.kevoree.modeling.memory.manager.KMemoryManager); internal_create(timePoint: number): org.kevoree.modeling.KView; } class GenericView extends org.kevoree.modeling.abs.AbstractKView { constructor(p_universe: number, _time: number, p_manager: org.kevoree.modeling.memory.manager.KMemoryManager); } class MetaAttribute implements org.kevoree.modeling.meta.KMetaAttribute { private _name; private _index; _precision: number; private _key; private _metaType; private _extrapolation; attributeType(): org.kevoree.modeling.KType; index(): number; metaName(): string; metaType(): org.kevoree.modeling.meta.MetaType; precision(): number; key(): boolean; strategy(): org.kevoree.modeling.extrapolation.Extrapolation; setExtrapolation(extrapolation: org.kevoree.modeling.extrapolation.Extrapolation): void; setPrecision(p_precision: number): void; constructor(p_name: string, p_index: number, p_precision: number, p_key: boolean, p_metaType: org.kevoree.modeling.KType, p_extrapolation: org.kevoree.modeling.extrapolation.Extrapolation); } class MetaClass implements org.kevoree.modeling.meta.KMetaClass { private _name; private _index; private _meta; private _indexes; constructor(p_name: string, p_index: number); init(p_metaElements: org.kevoree.modeling.meta.KMeta[]): void; metaByName(name: string): org.kevoree.modeling.meta.KMeta; attribute(name: string): org.kevoree.modeling.meta.KMetaAttribute; reference(name: string): org.kevoree.modeling.meta.KMetaReference; operation(name: string): org.kevoree.modeling.meta.KMetaOperation; metaElements(): org.kevoree.modeling.meta.KMeta[]; index(): number; metaName(): string; metaType(): org.kevoree.modeling.meta.MetaType; meta(index: number): org.kevoree.modeling.meta.KMeta; addAttribute(attributeName: string, p_type: org.kevoree.modeling.KType): org.kevoree.modeling.meta.KMetaAttribute; addReference(referenceName: string, p_metaClass: org.kevoree.modeling.meta.KMetaClass, oppositeName: string, toMany: boolean): org.kevoree.modeling.meta.KMetaReference; private getOrCreate(p_name, p_oppositeName, p_oppositeClass, p_visible, p_single); addOperation(operationName: string): org.kevoree.modeling.meta.KMetaOperation; private internal_add_meta(p_new_meta); } class MetaModel implements org.kevoree.modeling.meta.KMetaModel { private _name; private _index; private _metaClasses; private _metaClasses_indexes; index(): number; metaName(): string; metaType(): org.kevoree.modeling.meta.MetaType; constructor(p_name: string); init(p_metaClasses: org.kevoree.modeling.meta.KMetaClass[]): void; metaClasses(): org.kevoree.modeling.meta.KMetaClass[]; metaClassByName(name: string): org.kevoree.modeling.meta.KMetaClass; metaClass(index: number): org.kevoree.modeling.meta.KMetaClass; addMetaClass(metaClassName: string): org.kevoree.modeling.meta.KMetaClass; private interal_add_meta_class(p_newMetaClass); model(): org.kevoree.modeling.KModel<any>; } class MetaOperation implements org.kevoree.modeling.meta.KMetaOperation { private _name; private _index; private _lazyMetaClass; index(): number; metaName(): string; metaType(): org.kevoree.modeling.meta.MetaType; constructor(p_name: string, p_index: number, p_lazyMetaClass: () => org.kevoree.modeling.meta.KMeta); origin(): org.kevoree.modeling.meta.KMetaClass; } class MetaReference implements org.kevoree.modeling.meta.KMetaReference { private _name; private _index; private _visible; private _single; private _lazyMetaType; private _op_name; private _lazyMetaOrigin; single(): boolean; type(): org.kevoree.modeling.meta.KMetaClass; opposite(): org.kevoree.modeling.meta.KMetaReference; origin(): org.kevoree.modeling.meta.KMetaClass; index(): number; metaName(): string; metaType(): org.kevoree.modeling.meta.MetaType; visible(): boolean; constructor(p_name: string, p_index: number, p_visible: boolean, p_single: boolean, p_lazyMetaType: () => org.kevoree.modeling.meta.KMeta, op_name: string, p_lazyMetaOrigin: () => org.kevoree.modeling.meta.KMeta); } } } module operation { interface KOperation { on(source: org.kevoree.modeling.KObject, params: any[], result: (p: any) => void): void; } interface KOperationManager { registerOperation(operation: org.kevoree.modeling.meta.KMetaOperation, callback: (p: org.kevoree.modeling.KObject, p1: any[], p2: (p: any) => void) => void, target: org.kevoree.modeling.KObject): void; call(source: org.kevoree.modeling.KObject, operation: org.kevoree.modeling.meta.KMetaOperation, param: any[], callback: (p: any) => void): void; operationEventReceived(operationEvent: org.kevoree.modeling.message.KMessage): void; } module impl { class HashOperationManager implements org.kevoree.modeling.operation.KOperationManager { private staticOperations; private instanceOperations; private remoteCallCallbacks; private _manager; private _callbackId; constructor(p_manager: org.kevoree.modeling.memory.manager.KMemoryManager); registerOperation(operation: org.kevoree.modeling.meta.KMetaOperation, callback: (p: org.kevoree.modeling.KObject, p1: any[], p2: (p: any) => void) => void, target: org.kevoree.modeling.KObject): void; private searchOperation(source, clazz, operation); call(source: org.kevoree.modeling.KObject, operation: org.kevoree.modeling.meta.KMetaOperation, param: any[], callback: (p: any) => void): void; private sendToRemote(source, operation, param, callback); nextKey(): number; operationEventReceived(operationEvent: org.kevoree.modeling.message.KMessage): void; } } } module scheduler { interface KScheduler { dispatch(runnable: java.lang.Runnable): void; stop(): void; } module impl { class DirectScheduler implements org.kevoree.modeling.scheduler.KScheduler { dispatch(runnable: java.lang.Runnable): void; stop(): void; } class ExecutorServiceScheduler implements org.kevoree.modeling.scheduler.KScheduler { dispatch(p_runnable: java.lang.Runnable): void; stop(): void; } } } module traversal { interface KTraversal { traverse(metaReference: org.kevoree.modeling.meta.KMetaReference): org.kevoree.modeling.traversal.KTraversal; traverseQuery(metaReferenceQuery: string): org.kevoree.modeling.traversal.KTraversal; attributeQuery(attributeQuery: string): org.kevoree.modeling.traversal.KTraversal; withAttribute(attribute: org.kevoree.modeling.meta.KMetaAttribute, expectedValue: any): org.kevoree.modeling.traversal.KTraversal; withoutAttribute(attribute: org.kevoree.modeling.meta.KMetaAttribute, expectedValue: any): org.kevoree.modeling.traversal.KTraversal; filter(filter: (p: org.kevoree.modeling.KObject) => boolean): org.kevoree.modeling.traversal.KTraversal; then(cb: (p: org.kevoree.modeling.KObject[]) => void): void; map(attribute: org.kevoree.modeling.meta.KMetaAttribute, cb: (p: any[]) => void): void; collect(metaReference: org.kevoree.modeling.meta.KMetaReference, continueCondition: (p: org.kevoree.modeling.KObject) => boolean): org.kevoree.modeling.traversal.KTraversal; } interface KTraversalAction { chain(next: org.kevoree.modeling.traversal.KTraversalAction): void; execute(inputs: org.kevoree.modeling.KObject[]): void; } interface KTraversalFilter { filter(obj: org.kevoree.modeling.KObject): boolean; } module impl { class Traversal implements org.kevoree.modeling.traversal.KTraversal { private static TERMINATED_MESSAGE; private _initObjs; private _initAction; private _lastAction; private _terminated; constructor(p_root: org.kevoree.modeling.KObject); private internal_chain_action(p_action); traverse(p_metaReference: org.kevoree.modeling.meta.KMetaReference): org.kevoree.modeling.traversal.KTraversal; traverseQuery(p_metaReferenceQuery: string): org.kevoree.modeling.traversal.KTraversal; withAttribute(p_attribute: org.kevoree.modeling.meta.KMetaAttribute, p_expectedValue: any): org.kevoree.modeling.traversal.KTraversal; withoutAttribute(p_attribute: org.kevoree.modeling.meta.KMetaAttribute, p_expectedValue: any): org.kevoree.modeling.traversal.KTraversal; attributeQuery(p_attributeQuery: string): org.kevoree.modeling.traversal.KTraversal; filter(p_filter: (p: org.kevoree.modeling.KObject) => boolean): org.kevoree.modeling.traversal.KTraversal; collect(metaReference: org.kevoree.modeling.meta.KMetaReference, continueCondition: (p: org.kevoree.modeling.KObject) => boolean): org.kevoree.modeling.traversal.KTraversal; then(cb: (p: org.kevoree.modeling.KObject[]) => void): void; map(attribute: org.kevoree.modeling.meta.KMetaAttribute, cb: (p: any[]) => void): void; } module actions { class DeepCollectAction implements org.kevoree.modeling.traversal.KTraversalAction { private _next; private _reference; private _continueCondition; private _alreadyPassed; private _finalElements; constructor(p_reference: org.kevoree.modeling.meta.KMetaReference, p_continueCondition: (p: org.kevoree.modeling.KObject) => boolean); chain(p_next: org.kevoree.modeling.traversal.KTraversalAction): void; execute(p_inputs: org.kevoree.modeling.KObject[]): void; private executeStep(p_inputStep, private_callback); } class FilterAction implements org.kevoree.modeling.traversal.KTraversalAction { private _next; private _filter; constructor(p_filter: (p: org.kevoree.modeling.KObject) => boolean); chain(p_next: org.kevoree.modeling.traversal.KTraversalAction): void; execute(p_inputs: org.kevoree.modeling.KObject[]): void; } class FilterAttributeAction implements org.kevoree.modeling.traversal.KTraversalAction { private _next; private _attribute; private _expectedValue; constructor(p_attribute: org.kevoree.modeling.meta.KMetaAttribute, p_expectedValue: any); chain(p_next: org.kevoree.modeling.traversal.KTraversalAction): void; execute(p_inputs: org.kevoree.modeling.KObject[]): void; } class FilterAttributeQueryAction implements org.kevoree.modeling.traversal.KTraversalAction { private _next; private _attributeQuery; constructor(p_attributeQuery: string); chain(p_next: org.kevoree.modeling.traversal.KTraversalAction): void; execute(p_inputs: org.kevoree.modeling.KObject[]): void; private buildParams(p_paramString); } class FilterNotAttributeAction implements org.kevoree.modeling.traversal.KTraversalAction { private _next; private _attribute; private _expectedValue; constructor(p_attribute: org.kevoree.modeling.meta.KMetaAttribute, p_expectedValue: any); chain(p_next: org.kevoree.modeling.traversal.KTraversalAction): void; execute(p_inputs: org.kevoree.modeling.KObject[]): void; } class FinalAction implements org.kevoree.modeling.traversal.KTraversalAction { private _finalCallback; constructor(p_callback: (p: org.kevoree.modeling.KObject[]) => void); chain(next: org.kevoree.modeling.traversal.KTraversalAction): void; execute(inputs: org.kevoree.modeling.KObject[]): void; } class MapAction implements org.kevoree.modeling.traversal.KTraversalAction { private _finalCallback; private _attribute; constructor(p_attribute: org.kevoree.modeling.meta.KMetaAttribute, p_callback: (p: any[]) => void); chain(next: org.kevoree.modeling.traversal.KTraversalAction): void; execute(inputs: org.kevoree.modeling.KObject[]): void; } class RemoveDuplicateAction implements org.kevoree.modeling.traversal.KTraversalAction { private _next; chain(p_next: org.kevoree.modeling.traversal.KTraversalAction): void; execute(p_inputs: org.kevoree.modeling.KObject[]): void; } class TraverseAction implements org.kevoree.modeling.traversal.KTraversalAction { private _next; private _reference; constructor(p_reference: org.kevoree.modeling.meta.KMetaReference); chain(p_next: org.kevoree.modeling.traversal.KTraversalAction): void; execute(p_inputs: org.kevoree.modeling.KObject[]): void; } class TraverseQueryAction implements org.kevoree.modeling.traversal.KTraversalAction { private SEP; private _next; private _referenceQuery; constructor(p_referenceQuery: string); chain(p_next: org.kevoree.modeling.traversal.KTraversalAction): void; execute(p_inputs: org.kevoree.modeling.KObject[]): void; } } module selector { class Query { static OPEN_BRACKET: string; static CLOSE_BRACKET: string; static QUERY_SEP: string; relationName: string; params: string; constructor(relationName: string, params: string); toString(): string; static buildChain(query: string): java.util.List<org.kevoree.modeling.traversal.impl.selector.Query>; } class QueryParam { private _name; private _value; private _negative; constructor(p_name: string, p_value: string, p_negative: boolean); name(): string; value(): string; isNegative(): boolean; } class Selector { static select(root: org.kevoree.modeling.KObject, query: string, callback: (p: org.kevoree.modeling.KObject[]) => void): void; } } } module visitor { interface KModelAttributeVisitor { visit(metaAttribute: org.kevoree.modeling.meta.KMetaAttribute, value: any): void; } interface KModelVisitor { visit(elem: org.kevoree.modeling.KObject): org.kevoree.modeling.traversal.visitor.KVisitResult; } class KVisitResult { static CONTINUE: KVisitResult; static SKIP: KVisitResult; static STOP: KVisitResult; equals(other: any): boolean; static _KVisitResultVALUES: KVisitResult[]; static values(): KVisitResult[]; } } } module util { class Checker { static isDefined(param: any): boolean; } } } } }
dukeboard/kevoree-modeling-framework
org.kevoree.modeling.microframework.typescript/src/main/resources/org.kevoree.modeling.microframework.typescript.d.ts
TypeScript
lgpl-3.0
123,308
/* * Copyright (C) 2009 Christian Hujer. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * File Filtering. * @author <a href="mailto:cher@riedquat.de">Christian Hujer</a> * @since 0.1 */ package net.sf.japi.util.filter.file;
christianhujer/japi
historic2/src/prj/net/sf/japi/util/filter/file/package-info.java
Java
lgpl-3.0
936
// // System.Net.WebResponse // // Author: // Lawrence Pit (loz@cable.a2000.nl) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Runtime.Serialization; namespace System.Net { [Serializable] public abstract class WebResponse : MarshalByRefObject, ISerializable, IDisposable { // Constructors protected WebResponse () { } protected WebResponse (SerializationInfo serializationInfo, StreamingContext streamingContext) { throw new NotSupportedException (); } // Properties public virtual long ContentLength { get { throw new NotSupportedException (); } set { throw new NotSupportedException (); } } public virtual string ContentType { get { throw new NotSupportedException (); } set { throw new NotSupportedException (); } } public virtual WebHeaderCollection Headers { get { throw new NotSupportedException (); } } static Exception GetMustImplement () { return new NotImplementedException (); } [MonoTODO] public virtual bool IsFromCache { get { return false; // Better to return false than to kill the application // throw GetMustImplement (); } } [MonoTODO] public virtual bool IsMutuallyAuthenticated { get { throw GetMustImplement (); } } public virtual Uri ResponseUri { get { throw new NotSupportedException (); } } #if NET_4_0 [MonoTODO ("for portable library support")] public virtual bool SupportsHeaders { get { throw new NotImplementedException (); } } #endif // Methods public virtual void Close() { throw new NotSupportedException (); } public virtual Stream GetResponseStream() { throw new NotSupportedException (); } #if TARGET_JVM //enable overrides for extenders public virtual void Dispose() #elif NET_4_0 public void Dispose () #else void IDisposable.Dispose() #endif { #if NET_4_0 Dispose (true); #else Close (); #endif } #if NET_4_0 protected virtual void Dispose (bool disposing) { if (disposing) Close (); } #endif void ISerializable.GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext) { throw new NotSupportedException (); } [MonoTODO] protected virtual void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext) { throw GetMustImplement (); } } }
edwinspire/VSharp
v#/System/System.Net/WebResponse.cs
C#
lgpl-3.0
3,611
#Special rules for nouns, to avoid suggesting wrong lemmas. Nothing is done for other POS. import pymorphy2 blacklist1 = ['ъб', 'ъв', 'ъг', 'ъд', 'ъж', 'ъз', 'ък', 'ъл', 'ъм', 'ън', 'ъп', 'ър', 'ъс', 'ът', 'ъф', 'ъх', 'ъц', 'ъч', 'ъш', 'ъщ', 'йй', 'ьь', 'ъъ', 'ыы', 'чя', 'чю', 'чй', 'щя', 'щю', 'щй', 'шя', 'шю', 'шй', 'жы', 'шы', 'аь', 'еь', 'ёь', 'иь', 'йь', 'оь', 'уь', 'ыь', 'эь', 'юь', 'яь', 'аъ', 'еъ', 'ёъ', 'иъ', 'йъ', 'оъ', 'уъ', 'ыъ', 'эъ', 'юъ', 'яъ'] blacklist2 = ['чьк', 'чьн', 'щьн'] # forbidden blacklist3 = ['руметь'] base1 = ['ло','уа', 'ая', 'ши', 'ти', 'ни', 'ки', 'ко', 'ли', 'уи', 'до', 'аи', 'то'] # unchanged base2 = ['алз','бва', 'йты','ике','нту','лди','лит', 'вра','афе', 'бле', 'яху','уке', 'дзе', 'ури', 'ава', 'чче','нте', 'нне', 'гие', 'уро', 'сут', 'оне', 'ино', 'йду', 'нью', 'ньо', 'ньи', 'ери', 'ску', 'дье'] base3 = ['иани','льди', 'льде', 'ейру', 'зема', 'хими', 'ками', 'кала', 'мари', 'осси', 'лари', 'тано', 'ризе', 'енте', 'енеи'] base4 = ['швили', 'льяри'] change1 = ['лл','рр', 'пп', 'тт', 'ер', 'ук', 'ун', 'юк', 'ан', 'ян', 'ия', 'ин'] # declines change2 = ['вец','дюн', 'еув', 'инз', 'ейн', 'лис','лек','бен','нек','рок', 'ргл', 'бих','бус','айс','гас','таш', 'хэм', 'аал', 'дад', 'анд', 'лес', 'мар','ньш', 'рос','суф', 'вик', 'якс', 'веш','анц', 'янц', 'сон', 'сен', 'нен', 'ман', 'цак', 'инд', 'кин', 'чин', 'рем', 'рём', 'дин'] change3 = ['ерит', 'гард', 'иньш', 'скис', 'ллит', 'еней', 'рроз', 'манн', 'берг', 'вист', 'хайм',] female1 = ['ская', 'ской', 'скую'] female2 = ['овой'] female3 = ['евой'] female4 = ['иной'] middlemale = ['а', 'у'] middlestr1 = ['ии', 'ию'] # for Данелия middlestr2 = ['ией'] male = ['ов', 'ев', 'ин'] male1 = ['ский', 'ским', 'ском'] male2 = ['ского', 'скому'] male3 = ['е', 'ы'] male4 = ['ым', 'ом', 'ем', 'ой'] side1 = ['авы', 'аве', 'аву', 'фик', 'иол', 'риц', 'икк', 'ест', 'рех', 'тин'] side2 = ['авой'] sname = ['вич', 'вна'] sname1 = ['вн'] def lemmas_done(found, lemmatized): """ Check predicted lemmas according to the rules. """ morph = pymorphy2.MorphAnalyzer() fix = [] fixednames = [] doublefemale =[] for i in range(len(lemmatized)): p = morph.parse(found[i])[0] if p.tag.POS == 'NOUN': if (found[i].istitle()) and ((found[i][-2:] in base1) or (found[i][-2:] in male) or (found[i][-3:] in base2) or (found[i][-4:] in base3) or (found[i][-5:] in base4)): fixednames.append(found[i]) elif (found[i].istitle()) and ((found[i][-2:] in change1) or (found[i][-3:] in change2) or (found[i][-4:] in change3)): fixednames.append(found[i]) elif (found[i].istitle()) and (found[i][-4:] in female1): fixednames.append(found[i][:-2] + 'ая') elif (found[i].istitle()) and (found[i][-4:] in female2): fixednames.append(found[i][:-4] + 'ова') elif (found[i].istitle()) and (found[i][-4:] in female3): fixednames.append(found[i][:-4] + 'ева') elif (found[i].istitle()) and (found[i][-4:] in female4): fixednames.append(found[i][:-4] + 'ина') elif (found[i].istitle()) and (found[i][-4:] in male1): fixednames.append(found[i][:-2] + 'ий') elif (found[i].istitle()) and (found[i][-5:] in male2): fixednames.append(found[i][:-3] + 'ий') elif (found[i].istitle()) and (found[i][-1:] in male3) and (found[i][-3:-1] in male): fixednames.append(found[i][:-1]) elif (found[i].istitle()) and (found[i][-2:] in male4) and (found[i][-4:-2] in male): fixednames.append(found[i][:-2]) elif (found[i].istitle()) and (found[i][-1:] in middlemale) and (found[i][-3:-1] in male): fixednames.append(found[i][:-1]) doublefemale.append(found[i][:-1] + 'а') elif (found[i].istitle()) and ((found[i][-1:] in male3) or (found[i][-1:] in middlemale)) and (found[i][-3:-1] in change1): fixednames.append(found[i][:-1]) elif (found[i].istitle()) and ((found[i][-1:] in male3) or (found[i][-1:] in middlemale)) and (found[i][-4:-1] in change2): fixednames.append(found[i][:-1]) elif (found[i].istitle()) and ((found[i][-1:] in male3) or (found[i][-1:] in middlemale)) and (found[i][-5:-1] in change3): fixednames.append(found[i][:-1]) elif (found[i].istitle()) and (found[i][-2:] in male4) and (found[i][-4:-2] in change1): fixednames.append(found[i][:-2]) elif (found[i].istitle()) and (found[i][-2:] in male4) and (found[i][-5:-2] in change2): fixednames.append(found[i][:-2]) elif (found[i].istitle()) and (found[i][-2:] in male4) and (found[i][-6:-2] in change3): fixednames.append(found[i][:-2]) elif (found[i].istitle()) and (found[i][-2:] in middlestr1): fixednames.append(found[i][:-1] + 'я') elif (found[i].istitle()) and (found[i][-3:] in middlestr2): fixednames.append(found[i][:-2] + 'я') elif (found[i].istitle()) and (found[i][-3:] in side1): fixednames.append(found[i][:-1] + 'а') elif (found[i].istitle()) and (found[i][-4:] in side2): fixednames.append(found[i][:-2] + 'а') elif (found[i].istitle()) and (found[i][-4:-1] in side1): fixednames.append(found[i][:-1] + 'а') elif (found[i].istitle()) and (found[i][-5:-2] in side1): fixednames.append(found[i][:-2] + 'а') elif (found[i].istitle()) and (found[i][-3:] in sname): fixednames.append(found[i]) elif (found[i].istitle()) and (found[i][-4:-1] in sname) and ((found[i][-1:] in middlemale) or (found[i][-1:] in male3)): fixednames.append(found[i][:-1]) elif (found[i].istitle()) and (found[i][-5:-2] in sname) and (found[i][-2:] in male4): fixednames.append(found[i][:-2]) elif (found[i].istitle()) and (found[i][-3:-1] in sname1) and ((found[i][-1:] in middlemale) or (found[i][-1:] in male3)): fixednames.append(found[i][:-1] + 'а') elif (found[i].istitle()) and (found[i][-4:-2] in sname1) and (found[i][-2:] in male4): fixednames.append(found[i][:-2] + 'а') else: fixednames.append(lemmatized[i]) else: fixednames.append(lemmatized[i]) for i in range(len(fixednames)): if (fixednames[i][-2:] in blacklist1) or (fixednames[i][-3:] in blacklist2) or (fixednames[i][-6:] in blacklist3): fix.append(found[i]) else: fix.append(fixednames[i]) fix = fix + doublefemale newfreq = len(doublefemale) return fix, newfreq
azilya/Zaliznyak-s-grammatical-dictionary
gdictionary/postprocessing.py
Python
lgpl-3.0
7,574
var searchData= [ ['keep_5fhistory_2ecpp',['keep_history.cpp',['../keep__history_8cpp.html',1,'']]], ['keep_5fhistory_5fpass_2ecpp',['keep_history_pass.cpp',['../keep__history__pass_8cpp.html',1,'']]], ['keep_5fhistory_5fpass_2eh',['keep_history_pass.h',['../keep__history__pass_8h.html',1,'']]] ];
bduvenhage/flitr
Doxygen/html/search/files_6b.js
JavaScript
lgpl-3.0
311
/* {{ jtdavids-reflex }} Copyright (C) 2015 Jake Davidson 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 3 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, see <http://www.gnu.org/licenses/>. */ package com.example.jake.jtdavids_reflex; import android.content.SharedPreferences; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Created by Jake on 28/09/2015. */ public class StatisticCalc { List<Double> reaction_times = new ArrayList<Double>(); public StatisticCalc() { } public void add(double time){ reaction_times.add(time); } public void clear(){ reaction_times.clear(); } public String getAllTimeMin(){ //gets the minimum time of all recorded reaction times //if no reaction times are recored, return 'N/A' if (reaction_times.size() != 0) { double min = reaction_times.get(reaction_times.size()-1); for (int i = reaction_times.size()-2; i >= 0; i--) { if (reaction_times.get(i) < min) { min = reaction_times.get(i); } } return String.valueOf(min); } else{ return "N/A"; } } public String getSpecifiedTimeMin(int length){ //Gets the minimum reaction time of the last X reactions //a negative value should not be passed into this method //Since reactions are stored in a list, must iterate backwards through the list //to retrieve reaction times in chronological order if (reaction_times.size() != 0) { if(reaction_times.size() < length){ length = reaction_times.size(); } double min = reaction_times.get(reaction_times.size()-1); for (int i = reaction_times.size()-2; i > reaction_times.size()-length; i--) { if (reaction_times.get(i) < min) { min = reaction_times.get(i); } } return String.valueOf(min); } else{ return "N/A"; } } public String getAllTimeMax(){ //gets the maximum reaction time of all reactions if (reaction_times.size() !=0 ) { double max = reaction_times.get(reaction_times.size()-1); for (int i = reaction_times.size()-2; i >= 0; i--) { if (reaction_times.get(i) > max) { max = reaction_times.get(i); } } return String.valueOf(max); } else{ return "N/A"; } } public String getSpecifiedTimeMax(int length){ //Gets the maximum reaction time of the last X reactions //a negative value should not be passed into this method //Since reactions are stored in a list, must iterate backwards through the list //to retrieve reaction times in chronological order if (reaction_times.size() !=0 ) { if(reaction_times.size() < length){ length = reaction_times.size(); } double max = reaction_times.get(reaction_times.size()-1); for (int i = reaction_times.size()-2; i > reaction_times.size()-length; i--) { if (reaction_times.get(i) > max) { max = reaction_times.get(i); } } return String.valueOf(max); } else{ return "N/A"; } } public String getAllTimeAvg(){ //gets the average reaction time of all reactions if (reaction_times.size() !=0 ) { double avg = reaction_times.get(reaction_times.size()-1); for (int i = reaction_times.size()-2; i >= 0; i--) { avg = avg + reaction_times.get(i); } return String.valueOf((avg / reaction_times.size())); } else{ return "N/A "; } } public String getSpecifiedTimeAvg(int length){ //Gets the average reaction time of the last X reactions //a negative value should not be passed into this method //Since reactions are stored in a list, must iterate backwards through the list //to retrieve reaction times in chronological order if (reaction_times.size() !=0 ) { if(reaction_times.size() < length){ length = reaction_times.size(); } double avg = reaction_times.get(reaction_times.size()-1); for (int i = reaction_times.size()-2; i >= reaction_times.size()-length; i--) { avg = avg + reaction_times.get(i); } return String.valueOf((avg / length)); }else{ return "N/A "; } } public String getAllTimeMed(){ //gets the median reaction time of all reactions if (reaction_times.size() !=0 ) { List<Double> sorted_times = new ArrayList<Double>(reaction_times); Collections.sort(sorted_times); return String.valueOf((sorted_times.get(sorted_times.size() / 2))); } else{ return "N/A"; } } public String getSpecifiedTimeMed(int length){ //Gets the median reaction time of the last X reactions //a negative value should not be passed into this method if (reaction_times.size() != 0 ) { if(reaction_times.size() < length){ length = reaction_times.size(); } List<Double> sorted_times = new ArrayList<Double>(reaction_times.subList(0, length)); Collections.sort(sorted_times); return String.valueOf((sorted_times.get(sorted_times.size() / 2))); }else{ return "N/A"; } } public String getStatsMessage(SharedPreferences twoplayers_score, SharedPreferences threeplayers_score, SharedPreferences fourplayers_score){ return ("______SINGLEPLAYER______\n" + " MIN TIME:\n" + "All Time: " + getAllTimeMin() + "\nLast 10 times: " + getSpecifiedTimeMin(10) + "\nLast 100 times: " + getSpecifiedTimeMin(100) + "\n" + " MAX TIME:\n" + "All Time: " + getAllTimeMax() + "\nLast 10 times: " + getSpecifiedTimeMax(10) + "\nLast 100 times: " + getSpecifiedTimeMax(100) + "\n" + " AVERAGE TIME:\n" + "All Time: " + getAllTimeAvg() + "\nLast 10 times: " + getSpecifiedTimeAvg(10) + "\nLast 100 times: " + getSpecifiedTimeAvg(100) + "\n" + " MEDIAN TIME:\n" + "All Time: " + getAllTimeMed() + "\nLast 10 times: " + getSpecifiedTimeMed(10) + "\nLast 100 times: " + getSpecifiedTimeMed(100) + "\n" + "______PARTY PLAY______\n" + " 2 PLAYERS:\n" + "Player 1: " + String.valueOf(twoplayers_score.getInt("player1", 0)) + "\nPlayer 2: " + String.valueOf(twoplayers_score.getInt("player2", 0)) + "\n" + " 3 PLAYERS:\n" + "Player 1: " + String.valueOf(threeplayers_score.getInt("player1", 0)) + "\nPlayer 2: " + String.valueOf(threeplayers_score.getInt("player2", 0)) + "\nPlayer 3: " + String.valueOf(threeplayers_score.getInt("player3", 0)) + "\n" + " 4 PLAYERS:\n" + "Player 1: " + String.valueOf(fourplayers_score.getInt("player1", 0)) + "\nPlayer 2: " + String.valueOf(fourplayers_score.getInt("player2", 0)) + "\nPlayer 3: " + String.valueOf(fourplayers_score.getInt("player3", 0)) + "\nPlayer 4: " + String.valueOf(fourplayers_score.getInt("player4", 0)) + "\n"); } }
jtdavids/jtdavids-reflex
jtdavids-reflex/src/main/java/com/example/jake/jtdavids_reflex/StatisticCalc.java
Java
lgpl-3.0
8,131
using System.Data.Entity; using System.Linq; namespace EntityProfiler.Tools.MessageGenerator { public sealed class AppDbContext : DbContext { public DbSet<Product> Products { get; set; } public DbSet<Price> Prices { get; set; } /// <summary> /// Constructs a new context instance using conventions to create the name of the database to /// which a connection will be made. The by-convention name is the full name (namespace + class name) /// of the derived context class. /// See the class remarks for how this is used to create a connection. /// </summary> public AppDbContext() { this.Configuration.LazyLoadingEnabled = true; this.Configuration.ProxyCreationEnabled = true; } internal sealed class Initializer : DropCreateDatabaseAlways<AppDbContext> { /// <summary> /// A method that should be overridden to actually add data to the context for seeding. /// The default implementation does nothing. /// </summary> /// <param name="context">The context to seed. </param> protected override void Seed(AppDbContext context) { int offset = context.Products.Count(); for (int i = 0; i < 15; i++) { Product p = new Product("Product #" + (offset + i)); for (int j = 0; j < 10; j++) { p.Prices.Add(new Price(j * 423)); } context.Products.Add(p); } context.SaveChanges(); } public void AddItems(AppDbContext context) { this.Seed(context); } } } }
julianpaulozzi/EntityProfiler
tools/EntityProfiler.Tools.MessageGenerator/AppDbContext.cs
C#
lgpl-3.0
1,818
<?php /** * Contao Open Source CMS * * Copyright (c) 2005-2014 Leo Feyer * * @package Kitchenware * @author Hamid Abbaszadeh * @license GNU/LGPL * @copyright 2014 */ /** * Fields */ $GLOBALS['TL_LANG']['tl_kitchenware_category']['title'] = array('Kitchenware category title', 'Please enter the kitchenware category title.'); $GLOBALS['TL_LANG']['tl_kitchenware_category']['jumpTo'] = array('Redirect page', 'Please choose the product detail page to which visitors will be redirected when clicking a product item.'); $GLOBALS['TL_LANG']['tl_kitchenware_category']['protected'] = array('Protect archive', 'Show category items to certain member groups only.'); $GLOBALS['TL_LANG']['tl_kitchenware_category']['groups'] = array('Allowed member groups', 'These groups will be able to see the product items in this category.'); $GLOBALS['TL_LANG']['tl_kitchenware_category']['master'] = array('Master category', 'Please define the master category to allow language switching.'); $GLOBALS['TL_LANG']['tl_kitchenware_category']['language'] = array('Language', 'Please enter the language according to the RFC3066 format (e.g. en, en-us or en-cockney).'); /** * References */ $GLOBALS['TL_LANG']['tl_kitchenware_category']['isMaster'] = 'This is a master category'; $GLOBALS['TL_LANG']['tl_kitchenware_category']['isSlave'] = 'Master category is "%s"'; /** * Legends */ $GLOBALS['TL_LANG']['tl_kitchenware_category']['title_legend'] = 'Title'; $GLOBALS['TL_LANG']['tl_kitchenware_category']['redirect_legend'] = 'Redirect'; $GLOBALS['TL_LANG']['tl_kitchenware_category']['protected_legend'] = 'Access protection'; /** * Buttons */ $GLOBALS['TL_LANG']['tl_kitchenware_category']['new'] = array('New category', 'Create a new category'); $GLOBALS['TL_LANG']['tl_kitchenware_category']['show'] = array('Category details', 'Show the details of category ID %s'); $GLOBALS['TL_LANG']['tl_kitchenware_category']['edit'] = array('Edit Products', 'Edit products of category ID %s'); $GLOBALS['TL_LANG']['tl_kitchenware_category']['editheader'] = array('Edit Category', 'Edit the setting of category ID %s'); $GLOBALS['TL_LANG']['tl_kitchenware_category']['copy'] = array('Duplicate Category', 'Duplicate category ID %s'); $GLOBALS['TL_LANG']['tl_kitchenware_category']['delete'] = array('Delete Category', 'Delete category ID %s');
respinar/contao-kitchenware
languages/en/tl_kitchenware_category.php
PHP
lgpl-3.0
2,395
// -*- SystemC -*- // DESCRIPTION: Verilator Example: Top level main for invoking SystemC model // // This file ONLY is placed under the Creative Commons Public Domain, for // any use, without warranty, 2017 by Wilson Snyder. // SPDX-License-Identifier: CC0-1.0 //====================================================================== // For std::unique_ptr #include <memory> // SystemC global header #include <systemc.h> // Include common routines #include <verilated.h> #if VM_TRACE #include <verilated_vcd_sc.h> #endif #include <sys/stat.h> // mkdir // Include model header, generated from Verilating "top.v" #include "Vtop.h" int sc_main(int argc, char* argv[]) { // This is a more complicated example, please also see the simpler examples/make_hello_c. // Prevent unused variable warnings if (false && argc && argv) {} // Create logs/ directory in case we have traces to put under it Verilated::mkdir("logs"); // Set debug level, 0 is off, 9 is highest presently used // May be overridden by commandArgs argument parsing Verilated::debug(0); // Randomization reset policy // May be overridden by commandArgs argument parsing Verilated::randReset(2); #if VM_TRACE // Before any evaluation, need to know to calculate those signals only used for tracing Verilated::traceEverOn(true); #endif // Pass arguments so Verilated code can see them, e.g. $value$plusargs // This needs to be called before you create any model Verilated::commandArgs(argc, argv); // General logfile ios::sync_with_stdio(); // Define clocks sc_clock clk{"clk", 10, SC_NS, 0.5, 3, SC_NS, true}; sc_clock fastclk{"fastclk", 2, SC_NS, 0.5, 2, SC_NS, true}; // Define interconnect sc_signal<bool> reset_l; sc_signal<vluint32_t> in_small; sc_signal<vluint64_t> in_quad; sc_signal<sc_bv<70>> in_wide; sc_signal<vluint32_t> out_small; sc_signal<vluint64_t> out_quad; sc_signal<sc_bv<70>> out_wide; // Construct the Verilated model, from inside Vtop.h // Using unique_ptr is similar to "Vtop* top = new Vtop" then deleting at end const std::unique_ptr<Vtop> top{new Vtop{"top"}}; // Attach Vtop's signals to this upper model top->clk(clk); top->fastclk(fastclk); top->reset_l(reset_l); top->in_small(in_small); top->in_quad(in_quad); top->in_wide(in_wide); top->out_small(out_small); top->out_quad(out_quad); top->out_wide(out_wide); // You must do one evaluation before enabling waves, in order to allow // SystemC to interconnect everything for testing. sc_start(1, SC_NS); #if VM_TRACE // If verilator was invoked with --trace argument, // and if at run time passed the +trace argument, turn on tracing VerilatedVcdSc* tfp = nullptr; const char* flag = Verilated::commandArgsPlusMatch("trace"); if (flag && 0 == strcmp(flag, "+trace")) { cout << "Enabling waves into logs/vlt_dump.vcd...\n"; tfp = new VerilatedVcdSc; top->trace(tfp, 99); // Trace 99 levels of hierarchy Verilated::mkdir("logs"); tfp->open("logs/vlt_dump.vcd"); } #endif // Simulate until $finish while (!Verilated::gotFinish()) { #if VM_TRACE // Flush the wave files each cycle so we can immediately see the output // Don't do this in "real" programs, do it in an abort() handler instead if (tfp) tfp->flush(); #endif // Apply inputs if (sc_time_stamp() > sc_time(1, SC_NS) && sc_time_stamp() < sc_time(10, SC_NS)) { reset_l = !1; // Assert reset } else { reset_l = !0; // Deassert reset } // Simulate 1ns sc_start(1, SC_NS); } // Final model cleanup top->final(); // Close trace if opened #if VM_TRACE if (tfp) { tfp->close(); tfp = nullptr; } #endif // Coverage analysis (calling write only after the test is known to pass) #if VM_COVERAGE Verilated::mkdir("logs"); VerilatedCov::write("logs/coverage.dat"); #endif // Return good completion status return 0; }
verilator/verilator
examples/make_tracing_sc/sc_main.cpp
C++
lgpl-3.0
4,137
package org.cloudbus.cloudsim.examples.power.steady; import java.io.IOException; /** * A simulation of a heterogeneous power aware data center that applies the * Static Threshold (THR) VM allocation policy and Minimum Migration Time (MMT) * VM selection policy. * * The remaining configuration parameters are in the Constants and * SteadyConstants classes. * * If you are using any algorithms, policies or workload included in the power * package please cite the following paper: * * Anton Beloglazov, and Rajkumar Buyya, "Optimal Online Deterministic * Algorithms and Adaptive Heuristics for Energy and Performance Efficient * Dynamic Consolidation of Virtual Machines in Cloud Data Centers", Concurrency * and Computation: Practice and Experience (CCPE), Volume 24, Issue 13, Pages: * 1397-1420, John Wiley & Sons, Ltd, New York, USA, 2012 * * @author Anton Beloglazov * @since Jan 5, 2012 */ public class ThrMmt { /** * The main method. * * @param args * the arguments * @throws IOException * Signals that an I/O exception has occurred. */ public static void main(String[] args) throws IOException { boolean enableOutput = true; boolean outputToFile = false; String inputFolder = ""; String outputFolder = ""; String workload = "steady"; // Steady workload String vmAllocationPolicy = "thr"; // Static Threshold (THR) VM // allocation policy String vmSelectionPolicy = "mmt"; // Minimum Migration Time (MMT) VM // selection policy String parameter = "0.8"; // the static utilization threshold new SteadyRunner(enableOutput, outputToFile, inputFolder, outputFolder, workload, vmAllocationPolicy, vmSelectionPolicy, parameter); } }
swethapts/cloudsim
sources/org/cloudbus/cloudsim/examples/power/steady/ThrMmt.java
Java
lgpl-3.0
1,797
/** * <copyright> * </copyright> * * $Id$ */ package orgomg.cwm.analysis.olap.impl; import java.util.Collection; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.util.EObjectContainmentWithInverseEList; import org.eclipse.emf.ecore.util.InternalEList; import orgomg.cwm.analysis.olap.HierarchyLevelAssociation; import orgomg.cwm.analysis.olap.LevelBasedHierarchy; import orgomg.cwm.analysis.olap.OlapPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Level Based Hierarchy</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link orgomg.cwm.analysis.olap.impl.LevelBasedHierarchyImpl#getHierarchyLevelAssociation <em>Hierarchy Level Association</em>}</li> * </ul> * </p> * * @generated */ public class LevelBasedHierarchyImpl extends HierarchyImpl implements LevelBasedHierarchy { /** * The cached value of the '{@link #getHierarchyLevelAssociation() <em>Hierarchy Level Association</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getHierarchyLevelAssociation() * @generated * @ordered */ protected EList<HierarchyLevelAssociation> hierarchyLevelAssociation; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected LevelBasedHierarchyImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return OlapPackage.Literals.LEVEL_BASED_HIERARCHY; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<HierarchyLevelAssociation> getHierarchyLevelAssociation() { if (hierarchyLevelAssociation == null) { hierarchyLevelAssociation = new EObjectContainmentWithInverseEList<HierarchyLevelAssociation>(HierarchyLevelAssociation.class, this, OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION, OlapPackage.HIERARCHY_LEVEL_ASSOCIATION__LEVEL_BASED_HIERARCHY); } return hierarchyLevelAssociation; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION: return ((InternalEList<InternalEObject>)(InternalEList<?>)getHierarchyLevelAssociation()).basicAdd(otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION: return ((InternalEList<?>)getHierarchyLevelAssociation()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION: return getHierarchyLevelAssociation(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION: getHierarchyLevelAssociation().clear(); getHierarchyLevelAssociation().addAll((Collection<? extends HierarchyLevelAssociation>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION: getHierarchyLevelAssociation().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION: return hierarchyLevelAssociation != null && !hierarchyLevelAssociation.isEmpty(); } return super.eIsSet(featureID); } } //LevelBasedHierarchyImpl
dresden-ocl/dresdenocl
plugins/org.dresdenocl.tools.CWM/src/orgomg/cwm/analysis/olap/impl/LevelBasedHierarchyImpl.java
Java
lgpl-3.0
4,857
namespace Importer.Interfaces { public interface ISilence { float Start { get; } float End { get; } float Duration { get; } float CutTime { get; } } }
tschroedter/MyCodingExamples
aimedia/Importer.Interfaces/ISilence.cs
C#
lgpl-3.0
197
/////////////////////////////////////////////////////////////////////////////// // Name: src/ribbon/gallery.cpp // Purpose: Ribbon control which displays a gallery of items to choose from // Author: Peter Cawley // Modified by: // Created: 2009-07-22 // Copyright: (C) Peter Cawley // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_RIBBON #include "wx/ribbon/gallery.h" #include "wx/ribbon/art.h" #include "wx/ribbon/bar.h" #include "wx/dcbuffer.h" #include "wx/clntdata.h" #ifndef WX_PRECOMP #endif #ifdef __WXMSW__ #include "wx/msw/private.h" #endif wxDEFINE_EVENT(wxEVT_RIBBONGALLERY_HOVER_CHANGED, wxRibbonGalleryEvent); wxDEFINE_EVENT(wxEVT_RIBBONGALLERY_SELECTED, wxRibbonGalleryEvent); wxDEFINE_EVENT(wxEVT_RIBBONGALLERY_CLICKED, wxRibbonGalleryEvent); IMPLEMENT_DYNAMIC_CLASS(wxRibbonGalleryEvent, wxCommandEvent) IMPLEMENT_CLASS(wxRibbonGallery, wxRibbonControl) class wxRibbonGalleryItem { public: wxRibbonGalleryItem() { m_id = 0; m_is_visible = false; } void SetId(int id) {m_id = id;} void SetBitmap(const wxBitmap& bitmap) {m_bitmap = bitmap;} const wxBitmap& GetBitmap() const {return m_bitmap;} void SetIsVisible(bool visible) {m_is_visible = visible;} void SetPosition(int x, int y, const wxSize& size) { m_position = wxRect(wxPoint(x, y), size); } bool IsVisible() const {return m_is_visible;} const wxRect& GetPosition() const {return m_position;} void SetClientObject(wxClientData *data) {m_client_data.SetClientObject(data);} wxClientData *GetClientObject() const {return m_client_data.GetClientObject();} void SetClientData(void *data) {m_client_data.SetClientData(data);} void *GetClientData() const {return m_client_data.GetClientData();} protected: wxBitmap m_bitmap; wxClientDataContainer m_client_data; wxRect m_position; int m_id; bool m_is_visible; }; BEGIN_EVENT_TABLE(wxRibbonGallery, wxRibbonControl) EVT_ENTER_WINDOW(wxRibbonGallery::OnMouseEnter) EVT_ERASE_BACKGROUND(wxRibbonGallery::OnEraseBackground) EVT_LEAVE_WINDOW(wxRibbonGallery::OnMouseLeave) EVT_LEFT_DOWN(wxRibbonGallery::OnMouseDown) EVT_LEFT_UP(wxRibbonGallery::OnMouseUp) EVT_LEFT_DCLICK(wxRibbonGallery::OnMouseDClick) EVT_MOTION(wxRibbonGallery::OnMouseMove) EVT_PAINT(wxRibbonGallery::OnPaint) EVT_SIZE(wxRibbonGallery::OnSize) END_EVENT_TABLE() wxRibbonGallery::wxRibbonGallery() { } wxRibbonGallery::wxRibbonGallery(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style) : wxRibbonControl(parent, id, pos, size, wxBORDER_NONE) { CommonInit(style); } wxRibbonGallery::~wxRibbonGallery() { Clear(); } bool wxRibbonGallery::Create(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style) { if(!wxRibbonControl::Create(parent, id, pos, size, wxBORDER_NONE)) { return false; } CommonInit(style); return true; } void wxRibbonGallery::CommonInit(long WXUNUSED(style)) { m_selected_item = NULL; m_hovered_item = NULL; m_active_item = NULL; m_scroll_up_button_rect = wxRect(0, 0, 0, 0); m_scroll_down_button_rect = wxRect(0, 0, 0, 0); m_extension_button_rect = wxRect(0, 0, 0, 0); m_mouse_active_rect = NULL; m_bitmap_size = wxSize(64, 32); m_bitmap_padded_size = m_bitmap_size; m_item_separation_x = 0; m_item_separation_y = 0; m_scroll_amount = 0; m_scroll_limit = 0; m_up_button_state = wxRIBBON_GALLERY_BUTTON_DISABLED; m_down_button_state = wxRIBBON_GALLERY_BUTTON_NORMAL; m_extension_button_state = wxRIBBON_GALLERY_BUTTON_NORMAL; m_hovered = false; SetBackgroundStyle(wxBG_STYLE_CUSTOM); } void wxRibbonGallery::OnMouseEnter(wxMouseEvent& evt) { m_hovered = true; if(m_mouse_active_rect != NULL && !evt.LeftIsDown()) { m_mouse_active_rect = NULL; m_active_item = NULL; } Refresh(false); } void wxRibbonGallery::OnMouseMove(wxMouseEvent& evt) { bool refresh = false; wxPoint pos = evt.GetPosition(); if(TestButtonHover(m_scroll_up_button_rect, pos, &m_up_button_state)) refresh = true; if(TestButtonHover(m_scroll_down_button_rect, pos, &m_down_button_state)) refresh = true; if(TestButtonHover(m_extension_button_rect, pos, &m_extension_button_state)) refresh = true; wxRibbonGalleryItem *hovered_item = NULL; wxRibbonGalleryItem *active_item = NULL; if(m_client_rect.Contains(pos)) { if(m_art && m_art->GetFlags() & wxRIBBON_BAR_FLOW_VERTICAL) pos.x += m_scroll_amount; else pos.y += m_scroll_amount; size_t item_count = m_items.Count(); size_t item_i; for(item_i = 0; item_i < item_count; ++item_i) { wxRibbonGalleryItem *item = m_items.Item(item_i); if(!item->IsVisible()) continue; if(item->GetPosition().Contains(pos)) { if(m_mouse_active_rect == &item->GetPosition()) active_item = item; hovered_item = item; break; } } } if(active_item != m_active_item) { m_active_item = active_item; refresh = true; } if(hovered_item != m_hovered_item) { m_hovered_item = hovered_item; wxRibbonGalleryEvent notification( wxEVT_RIBBONGALLERY_HOVER_CHANGED, GetId()); notification.SetEventObject(this); notification.SetGallery(this); notification.SetGalleryItem(hovered_item); ProcessWindowEvent(notification); refresh = true; } if(refresh) Refresh(false); } bool wxRibbonGallery::TestButtonHover(const wxRect& rect, wxPoint pos, wxRibbonGalleryButtonState* state) { if(*state == wxRIBBON_GALLERY_BUTTON_DISABLED) return false; wxRibbonGalleryButtonState new_state; if(rect.Contains(pos)) { if(m_mouse_active_rect == &rect) new_state = wxRIBBON_GALLERY_BUTTON_ACTIVE; else new_state = wxRIBBON_GALLERY_BUTTON_HOVERED; } else new_state = wxRIBBON_GALLERY_BUTTON_NORMAL; if(new_state != *state) { *state = new_state; return true; } else { return false; } } void wxRibbonGallery::OnMouseLeave(wxMouseEvent& WXUNUSED(evt)) { m_hovered = false; m_active_item = NULL; if(m_up_button_state != wxRIBBON_GALLERY_BUTTON_DISABLED) m_up_button_state = wxRIBBON_GALLERY_BUTTON_NORMAL; if(m_down_button_state != wxRIBBON_GALLERY_BUTTON_DISABLED) m_down_button_state = wxRIBBON_GALLERY_BUTTON_NORMAL; if(m_extension_button_state != wxRIBBON_GALLERY_BUTTON_DISABLED) m_extension_button_state = wxRIBBON_GALLERY_BUTTON_NORMAL; if(m_hovered_item != NULL) { m_hovered_item = NULL; wxRibbonGalleryEvent notification( wxEVT_RIBBONGALLERY_HOVER_CHANGED, GetId()); notification.SetEventObject(this); notification.SetGallery(this); ProcessWindowEvent(notification); } Refresh(false); } void wxRibbonGallery::OnMouseDown(wxMouseEvent& evt) { wxPoint pos = evt.GetPosition(); m_mouse_active_rect = NULL; if(m_client_rect.Contains(pos)) { if(m_art && m_art->GetFlags() & wxRIBBON_BAR_FLOW_VERTICAL) pos.x += m_scroll_amount; else pos.y += m_scroll_amount; size_t item_count = m_items.Count(); size_t item_i; for(item_i = 0; item_i < item_count; ++item_i) { wxRibbonGalleryItem *item = m_items.Item(item_i); if(!item->IsVisible()) continue; const wxRect& rect = item->GetPosition(); if(rect.Contains(pos)) { m_active_item = item; m_mouse_active_rect = &rect; break; } } } else if(m_scroll_up_button_rect.Contains(pos)) { if(m_up_button_state != wxRIBBON_GALLERY_BUTTON_DISABLED) { m_mouse_active_rect = &m_scroll_up_button_rect; m_up_button_state = wxRIBBON_GALLERY_BUTTON_ACTIVE; } } else if(m_scroll_down_button_rect.Contains(pos)) { if(m_down_button_state != wxRIBBON_GALLERY_BUTTON_DISABLED) { m_mouse_active_rect = &m_scroll_down_button_rect; m_down_button_state = wxRIBBON_GALLERY_BUTTON_ACTIVE; } } else if(m_extension_button_rect.Contains(pos)) { if(m_extension_button_state != wxRIBBON_GALLERY_BUTTON_DISABLED) { m_mouse_active_rect = &m_extension_button_rect; m_extension_button_state = wxRIBBON_GALLERY_BUTTON_ACTIVE; } } if(m_mouse_active_rect != NULL) Refresh(false); } void wxRibbonGallery::OnMouseUp(wxMouseEvent& evt) { if(m_mouse_active_rect != NULL) { wxPoint pos = evt.GetPosition(); if(m_active_item) { if(m_art && m_art->GetFlags() & wxRIBBON_BAR_FLOW_VERTICAL) pos.x += m_scroll_amount; else pos.y += m_scroll_amount; } if(m_mouse_active_rect->Contains(pos)) { if(m_mouse_active_rect == &m_scroll_up_button_rect) { m_up_button_state = wxRIBBON_GALLERY_BUTTON_HOVERED; ScrollLines(-1); } else if(m_mouse_active_rect == &m_scroll_down_button_rect) { m_down_button_state = wxRIBBON_GALLERY_BUTTON_HOVERED; ScrollLines(1); } else if(m_mouse_active_rect == &m_extension_button_rect) { m_extension_button_state = wxRIBBON_GALLERY_BUTTON_HOVERED; wxCommandEvent notification(wxEVT_BUTTON, GetId()); notification.SetEventObject(this); ProcessWindowEvent(notification); } else if(m_active_item != NULL) { if(m_selected_item != m_active_item) { m_selected_item = m_active_item; wxRibbonGalleryEvent notification( wxEVT_RIBBONGALLERY_SELECTED, GetId()); notification.SetEventObject(this); notification.SetGallery(this); notification.SetGalleryItem(m_selected_item); ProcessWindowEvent(notification); } wxRibbonGalleryEvent notification( wxEVT_RIBBONGALLERY_CLICKED, GetId()); notification.SetEventObject(this); notification.SetGallery(this); notification.SetGalleryItem(m_selected_item); ProcessWindowEvent(notification); } } m_mouse_active_rect = NULL; m_active_item = NULL; Refresh(false); } } void wxRibbonGallery::OnMouseDClick(wxMouseEvent& evt) { // The 2nd click of a double-click should be handled as a click in the // same way as the 1st click of the double-click. This is useful for // scrolling through the gallery. OnMouseDown(evt); OnMouseUp(evt); } void wxRibbonGallery::SetItemClientObject(wxRibbonGalleryItem* itm, wxClientData* data) { itm->SetClientObject(data); } wxClientData* wxRibbonGallery::GetItemClientObject(const wxRibbonGalleryItem* itm) const { return itm->GetClientObject(); } void wxRibbonGallery::SetItemClientData(wxRibbonGalleryItem* itm, void* data) { itm->SetClientData(data); } void* wxRibbonGallery::GetItemClientData(const wxRibbonGalleryItem* itm) const { return itm->GetClientData(); } bool wxRibbonGallery::ScrollLines(int lines) { if(m_scroll_limit == 0 || m_art == NULL) return false; return ScrollPixels(lines * GetScrollLineSize()); } int wxRibbonGallery::GetScrollLineSize() const { if(m_art == NULL) return 32; int line_size = m_bitmap_padded_size.GetHeight(); if(m_art->GetFlags() & wxRIBBON_BAR_FLOW_VERTICAL) line_size = m_bitmap_padded_size.GetWidth(); return line_size; } bool wxRibbonGallery::ScrollPixels(int pixels) { if(m_scroll_limit == 0 || m_art == NULL) return false; if(pixels < 0) { if(m_scroll_amount > 0) { m_scroll_amount += pixels; if(m_scroll_amount <= 0) { m_scroll_amount = 0; m_up_button_state = wxRIBBON_GALLERY_BUTTON_DISABLED; } else if(m_up_button_state == wxRIBBON_GALLERY_BUTTON_DISABLED) m_up_button_state = wxRIBBON_GALLERY_BUTTON_NORMAL; if(m_down_button_state == wxRIBBON_GALLERY_BUTTON_DISABLED) m_down_button_state = wxRIBBON_GALLERY_BUTTON_NORMAL; return true; } } else if(pixels > 0) { if(m_scroll_amount < m_scroll_limit) { m_scroll_amount += pixels; if(m_scroll_amount >= m_scroll_limit) { m_scroll_amount = m_scroll_limit; m_down_button_state = wxRIBBON_GALLERY_BUTTON_DISABLED; } else if(m_down_button_state == wxRIBBON_GALLERY_BUTTON_DISABLED) m_down_button_state = wxRIBBON_GALLERY_BUTTON_NORMAL; if(m_up_button_state == wxRIBBON_GALLERY_BUTTON_DISABLED) m_up_button_state = wxRIBBON_GALLERY_BUTTON_NORMAL; return true; } } return false; } void wxRibbonGallery::EnsureVisible(const wxRibbonGalleryItem* item) { if(item == NULL || !item->IsVisible() || IsEmpty()) return; if(m_art->GetFlags() & wxRIBBON_BAR_FLOW_VERTICAL) { int x = item->GetPosition().GetLeft(); int base_x = m_items.Item(0)->GetPosition().GetLeft(); int delta = x - base_x - m_scroll_amount; ScrollLines(delta / m_bitmap_padded_size.GetWidth()); } else { int y = item->GetPosition().GetTop(); int base_y = m_items.Item(0)->GetPosition().GetTop(); int delta = y - base_y - m_scroll_amount; ScrollLines(delta / m_bitmap_padded_size.GetHeight()); } } bool wxRibbonGallery::IsHovered() const { return m_hovered; } void wxRibbonGallery::OnEraseBackground(wxEraseEvent& WXUNUSED(evt)) { // All painting done in main paint handler to minimise flicker } void wxRibbonGallery::OnPaint(wxPaintEvent& WXUNUSED(evt)) { wxAutoBufferedPaintDC dc(this); if(m_art == NULL) return; m_art->DrawGalleryBackground(dc, this, GetSize()); int padding_top = m_art->GetMetric(wxRIBBON_ART_GALLERY_BITMAP_PADDING_TOP_SIZE); int padding_left = m_art->GetMetric(wxRIBBON_ART_GALLERY_BITMAP_PADDING_LEFT_SIZE); dc.SetClippingRegion(m_client_rect); bool offset_vertical = true; if(m_art->GetFlags() & wxRIBBON_BAR_FLOW_VERTICAL) offset_vertical = false; size_t item_count = m_items.Count(); size_t item_i; for(item_i = 0; item_i < item_count; ++item_i) { wxRibbonGalleryItem *item = m_items.Item(item_i); if(!item->IsVisible()) continue; const wxRect& pos = item->GetPosition(); wxRect offset_pos(pos); if(offset_vertical) offset_pos.SetTop(offset_pos.GetTop() - m_scroll_amount); else offset_pos.SetLeft(offset_pos.GetLeft() - m_scroll_amount); m_art->DrawGalleryItemBackground(dc, this, offset_pos, item); dc.DrawBitmap(item->GetBitmap(), offset_pos.GetLeft() + padding_left, offset_pos.GetTop() + padding_top); } } void wxRibbonGallery::OnSize(wxSizeEvent& WXUNUSED(evt)) { Layout(); } wxRibbonGalleryItem* wxRibbonGallery::Append(const wxBitmap& bitmap, int id) { wxASSERT(bitmap.IsOk()); if(m_items.IsEmpty()) { m_bitmap_size = bitmap.GetSize(); CalculateMinSize(); } else { wxASSERT(bitmap.GetSize() == m_bitmap_size); } wxRibbonGalleryItem *item = new wxRibbonGalleryItem; item->SetId(id); item->SetBitmap(bitmap); m_items.Add(item); return item; } wxRibbonGalleryItem* wxRibbonGallery::Append(const wxBitmap& bitmap, int id, void* clientData) { wxRibbonGalleryItem *item = Append(bitmap, id); item->SetClientData(clientData); return item; } wxRibbonGalleryItem* wxRibbonGallery::Append(const wxBitmap& bitmap, int id, wxClientData* clientData) { wxRibbonGalleryItem *item = Append(bitmap, id); item->SetClientObject(clientData); return item; } void wxRibbonGallery::Clear() { size_t item_count = m_items.Count(); size_t item_i; for(item_i = 0; item_i < item_count; ++item_i) { wxRibbonGalleryItem *item = m_items.Item(item_i); delete item; } m_items.Clear(); } bool wxRibbonGallery::IsSizingContinuous() const { return false; } void wxRibbonGallery::CalculateMinSize() { if(m_art == NULL || !m_bitmap_size.IsFullySpecified()) { SetMinSize(wxSize(20, 20)); } else { m_bitmap_padded_size = m_bitmap_size; m_bitmap_padded_size.IncBy( m_art->GetMetric(wxRIBBON_ART_GALLERY_BITMAP_PADDING_LEFT_SIZE) + m_art->GetMetric(wxRIBBON_ART_GALLERY_BITMAP_PADDING_RIGHT_SIZE), m_art->GetMetric(wxRIBBON_ART_GALLERY_BITMAP_PADDING_TOP_SIZE) + m_art->GetMetric(wxRIBBON_ART_GALLERY_BITMAP_PADDING_BOTTOM_SIZE)); wxMemoryDC dc; SetMinSize(m_art->GetGallerySize(dc, this, m_bitmap_padded_size)); // The best size is displaying several items m_best_size = m_bitmap_padded_size; m_best_size.x *= 3; m_best_size = m_art->GetGallerySize(dc, this, m_best_size); } } bool wxRibbonGallery::Realize() { CalculateMinSize(); return Layout(); } bool wxRibbonGallery::Layout() { if(m_art == NULL) return false; wxMemoryDC dc; wxPoint origin; wxSize client_size = m_art->GetGalleryClientSize(dc, this, GetSize(), &origin, &m_scroll_up_button_rect, &m_scroll_down_button_rect, &m_extension_button_rect); m_client_rect = wxRect(origin, client_size); int x_cursor = 0; int y_cursor = 0; size_t item_count = m_items.Count(); size_t item_i; long art_flags = m_art->GetFlags(); for(item_i = 0; item_i < item_count; ++item_i) { wxRibbonGalleryItem *item = m_items.Item(item_i); item->SetIsVisible(true); if(art_flags & wxRIBBON_BAR_FLOW_VERTICAL) { if(y_cursor + m_bitmap_padded_size.y > client_size.GetHeight()) { if(y_cursor == 0) break; y_cursor = 0; x_cursor += m_bitmap_padded_size.x; } item->SetPosition(origin.x + x_cursor, origin.y + y_cursor, m_bitmap_padded_size); y_cursor += m_bitmap_padded_size.y; } else { if(x_cursor + m_bitmap_padded_size.x > client_size.GetWidth()) { if(x_cursor == 0) break; x_cursor = 0; y_cursor += m_bitmap_padded_size.y; } item->SetPosition(origin.x + x_cursor, origin.y + y_cursor, m_bitmap_padded_size); x_cursor += m_bitmap_padded_size.x; } } for(; item_i < item_count; ++item_i) { wxRibbonGalleryItem *item = m_items.Item(item_i); item->SetIsVisible(false); } if(art_flags & wxRIBBON_BAR_FLOW_VERTICAL) m_scroll_limit = x_cursor; else m_scroll_limit = y_cursor; if(m_scroll_amount >= m_scroll_limit) { m_scroll_amount = m_scroll_limit; m_down_button_state = wxRIBBON_GALLERY_BUTTON_DISABLED; } else if(m_down_button_state == wxRIBBON_GALLERY_BUTTON_DISABLED) m_down_button_state = wxRIBBON_GALLERY_BUTTON_NORMAL; if(m_scroll_amount <= 0) { m_scroll_amount = 0; m_up_button_state = wxRIBBON_GALLERY_BUTTON_DISABLED; } else if(m_up_button_state == wxRIBBON_GALLERY_BUTTON_DISABLED) m_up_button_state = wxRIBBON_GALLERY_BUTTON_NORMAL; return true; } wxSize wxRibbonGallery::DoGetBestSize() const { return m_best_size; } wxSize wxRibbonGallery::DoGetNextSmallerSize(wxOrientation direction, wxSize relative_to) const { if(m_art == NULL) return relative_to; wxMemoryDC dc; wxSize client = m_art->GetGalleryClientSize(dc, this, relative_to, NULL, NULL, NULL, NULL); switch(direction) { case wxHORIZONTAL: client.DecBy(1, 0); break; case wxVERTICAL: client.DecBy(0, 1); break; case wxBOTH: client.DecBy(1, 1); break; } if(client.GetWidth() < 0 || client.GetHeight() < 0) return relative_to; client.x = (client.x / m_bitmap_padded_size.x) * m_bitmap_padded_size.x; client.y = (client.y / m_bitmap_padded_size.y) * m_bitmap_padded_size.y; wxSize size = m_art->GetGallerySize(dc, this, client); wxSize minimum = GetMinSize(); if(size.GetWidth() < minimum.GetWidth() || size.GetHeight() < minimum.GetHeight()) { return relative_to; } switch(direction) { case wxHORIZONTAL: size.SetHeight(relative_to.GetHeight()); break; case wxVERTICAL: size.SetWidth(relative_to.GetWidth()); break; default: break; } return size; } wxSize wxRibbonGallery::DoGetNextLargerSize(wxOrientation direction, wxSize relative_to) const { if(m_art == NULL) return relative_to; wxMemoryDC dc; wxSize client = m_art->GetGalleryClientSize(dc, this, relative_to, NULL, NULL, NULL, NULL); // No need to grow if the given size can already display every item int nitems = (client.GetWidth() / m_bitmap_padded_size.x) * (client.GetHeight() / m_bitmap_padded_size.y); if(nitems >= (int)m_items.GetCount()) return relative_to; switch(direction) { case wxHORIZONTAL: client.IncBy(m_bitmap_padded_size.x, 0); break; case wxVERTICAL: client.IncBy(0, m_bitmap_padded_size.y); break; case wxBOTH: client.IncBy(m_bitmap_padded_size); break; } client.x = (client.x / m_bitmap_padded_size.x) * m_bitmap_padded_size.x; client.y = (client.y / m_bitmap_padded_size.y) * m_bitmap_padded_size.y; wxSize size = m_art->GetGallerySize(dc, this, client); wxSize minimum = GetMinSize(); if(size.GetWidth() < minimum.GetWidth() || size.GetHeight() < minimum.GetHeight()) { return relative_to; } switch(direction) { case wxHORIZONTAL: size.SetHeight(relative_to.GetHeight()); break; case wxVERTICAL: size.SetWidth(relative_to.GetWidth()); break; default: break; } return size; } bool wxRibbonGallery::IsEmpty() const { return m_items.IsEmpty(); } unsigned int wxRibbonGallery::GetCount() const { return (unsigned int)m_items.GetCount(); } wxRibbonGalleryItem* wxRibbonGallery::GetItem(unsigned int n) { if(n >= GetCount()) return NULL; return m_items.Item(n); } void wxRibbonGallery::SetSelection(wxRibbonGalleryItem* item) { if(item != m_selected_item) { m_selected_item = item; Refresh(false); } } wxRibbonGalleryItem* wxRibbonGallery::GetSelection() const { return m_selected_item; } wxRibbonGalleryItem* wxRibbonGallery::GetHoveredItem() const { return m_hovered_item; } wxRibbonGalleryItem* wxRibbonGallery::GetActiveItem() const { return m_active_item; } wxRibbonGalleryButtonState wxRibbonGallery::GetUpButtonState() const { return m_up_button_state; } wxRibbonGalleryButtonState wxRibbonGallery::GetDownButtonState() const { return m_down_button_state; } wxRibbonGalleryButtonState wxRibbonGallery::GetExtensionButtonState() const { return m_extension_button_state; } #endif // wxUSE_RIBBON
dariusliep/LogViewer
thirdparty/wxWidgets-3.0.0/src/ribbon/gallery.cpp
C++
lgpl-3.0
25,662
package com.wavpack.decoder; import java.io.RandomAccessFile; /* ** WavpackContext.java ** ** Copyright (c) 2007 - 2008 Peter McQuillan ** ** All Rights Reserved. ** ** Distributed under the BSD Software License (see license.txt) ** */ public class WavpackContext { WavpackConfig config = new WavpackConfig(); WavpackStream stream = new WavpackStream(); byte read_buffer[] = new byte[65536]; // was uchar in C int[] temp_buffer = new int[Defines.SAMPLE_BUFFER_SIZE]; int[] temp_buffer2 = new int[Defines.SAMPLE_BUFFER_SIZE]; String error_message = ""; boolean error; RandomAccessFile infile; long total_samples, crc_errors, first_flags; // was uint32_t in C int open_flags, norm_offset; int reduced_channels = 0; int lossy_blocks; int status = 0; // 0 ok, 1 error public boolean isError() { return error; } public String getErrorMessage() { return error_message; } }
jacky8hyf/musique
dependencies/wavpack/src/main/java/com/wavpack/decoder/WavpackContext.java
Java
lgpl-3.0
1,036
using System.Xml.Serialization; namespace Geo.Gps.Serialization.Xml.Gpx.Gpx10 { [XmlType(AnonymousType=true, Namespace="http://www.topografix.com/GPX/1/0")] public class GpxTrackPoint : GpxPoint { public decimal course { get; set; } [XmlIgnore] public bool courseSpecified { get; set; } public decimal speed { get; set; } [XmlIgnore] public bool speedSpecified { get; set; } } }
asapostolov/Geo
Geo/Gps/Serialization/Xml/Gpx/Gpx10/GpxTrackPoint.cs
C#
lgpl-3.0
446
<?php /** * 信息中心默认语言包 zh_cn * * @package application.modules.officialdoc.language.zh_cn * @version $Id: default.php 481 2013-05-30 08:04:10Z gzwwb $ * @author gzwwb <gzwwb@ibos.com.cn> */ return array( //----------------golabs------------------- 'Information center' => '信息中心', 'Officialdoc' => '通知公告', 'Officialdoc list' => '通知列表', 'Add officialdoc' => '新建通知', 'Edit officialdoc' => '编辑通知', 'Show officialdoc' => '查看通知', 'Preview officialdoc' => '预览通知', //----------------ContentController------------------- 'No permission or officialdoc not exists' => '没有权限操作或者通知不存在', 'No_permission' => '没有权限操作', 'No_exists' => '文章不存在', //----------------list------------------- 'New doc' => '发布通知', 'All' => '全部', 'Published' => '已发布', 'No sign' => '未签收', 'Already sign' => '已签收', 'Sign' => '签收', 'Sign in' => '签收于', 'Sign for success' => '签收成功', 'No verify' => '待审核', 'More Operating' => '更多操作', 'Move' => '移动', 'Top' => '置顶', 'Highlight' => '高亮', 'Delete' => '删除', 'Verify' => '审核', 'Title' => '标题', 'Last update' => '最后修改', 'View' => '查看', 'Operating' => '操作', 'Edit' => '编辑', 'Keyword' => '关键字', 'Start time' => '开始时间', 'End time' => '结束时间', 'Directory' => '目录', 'Expired time' => '过期时间', 'Advanced search' => '高级搜索', 'Highlight succeed' => '高亮成功', 'Unhighlighting success' => '取消高亮成功', 'Set top' => '设置置顶', 'Top succeed' => '置顶成功', 'Unstuck success' => '取消置顶成功', 'You sure you want to delete it' => '确定要删除吗', 'Delete succeed' => '删除成功', 'Move by' => '移动至', 'Move succeed' => '移动成功', 'Move failed' => '移动失败', 'Sure Operating' => '确认操作', 'Sure delete' => '确认要删除吗', 'Did not select any document' => '未选择任何通知', 'You do not have the right to audit the documents' => '你没有审核该通知的权利', 'You do not have permission to verify the official' => '抱歉,您不是该审核步骤的审核人', 'New message title' => '{sender} 在通知公告-{category}发布了“{subject}”的通知!', 'New message content' => '{content}', 'New verify message title' => '{sender} 在通知公告-{category}发布了“{subject}”的通知,请您审核!', 'New verify message content' => '{content}', 'New back title' => ' 您发表的通知“{subject}”被退回 ', 'New back content' => ' {content}', 'Sign message title' => '{name} 提醒您签收通知 “{title}”', 'Sign message content' => '{content}', 'Do not need approval' => '无需审核,请编辑直接发布', //----------------show------------------- 'Close' => '关闭', 'Print' => '打印', 'Forward' => '转发', 'News' => '信息', 'Posted on' => '发布于', 'Approver' => '审核人', 'Update on' => '修改于', 'Version' => '版本', 'Category' => '分类', 'Scope' => '范围', 'Cc' => '抄送', 'This officialdoc requires you to sign' => '本通知需要您', 'Next reminder' => '下次提醒', 'You have to sign this document' => '您已签收', 'Comment' => '评论', 'Sign isread' => '查阅情况', 'Sign situation' => '签收情况', 'History version' => '历史版本', 'Department' => '部门', 'Reader and signtime' => '签收人员 / 签收时间', 'Update man' => '修改人', 'Publish time' => '发布时间', 'Temporarily no' => '暂无', 'Sign failed' => '签收失败', 'You do not have permission to read the officialdoc' => '你没有查看该通知的权限,谢谢', 'No user to remind' => '没有未签收人员可提醒', 'Remind title' => '提醒您签收通知', 'Remind succeed' => '提醒成功', 'Now sign' => '立即签收', 'Sign time' => '签收时间为:', 'Sign staff' => '签收人员', 'Unsign staff' => '未签收人员', 'Comment my doc' => '评论{realname}的通知<a href=\"{url}\">&nbsp;“{title}”</a>', //----------------sidebar------------------- 'None' => '无', 'New' => '新建', 'Contents under this classification only be deleted when no content' => '该分类下有内容,仅当无内容时才可删除', 'Leave at least a Category' => '请至少保留一个分类', //----------------add------------------- 'News title' => '信息标题', 'Appertaining category' => '所属分类', 'Publishing permissions' => '发布范围', 'Publish' => '发布', 'Draft' => '草稿', 'Comments module is not installed or enabled' => '未安装或未启用评论模块', 'Vote' => '评论', 'Return' => '返回', 'Preview' => '预览', 'Submit' => '提交', 'Wait verify' => '待审核', 'File size limit' => '&nbsp;&nbsp;&nbsp;&nbsp;文件大小限制', //----------------后台------------------- 'Officialdoc setting' => '通知设置', 'Officialdoc approver' => '通知审批人', 'Enable' => '启用', 'Disabled' => '禁用', 'NO.' => '序号', 'Template name' => '模板名称', 'Officialdoc template edit' => '通知模板编辑', 'See more docs' => '查看更多通知', 'Year' => '年', 'Month' => '月', 'Day' => '日', 'Post officialdoc' => '发表了一篇通知', 'Feed title' => '<a href="{url}" class="xwb anchor">{subject}</a>' );
SeekArt/IBOS
system/modules/officialdoc/language/zh_cn/default.php
PHP
lgpl-3.0
5,779
/** * 基于jquery.select2扩展的select插件,基本使用请参考select2相关文档 * 默认是多选模式,并提供了input模式下的初始化方法,对应的数据格式是{ id: 1, text: "Hello" } * 这里的参数只对扩展的部分作介绍 * filter、includes、excludes、query四个参数是互斥的,理论只能有其一个参数 * @method ibosSelect * @param option.filter * @param {Function} option.filter 用于过滤源数据的函数 * @param {Array} option.includes 用于过滤源数据的数据,有效数据的id组 * @param {Array} option.excludes 用于过滤源数据的数据,无效数据的id组 * @param {Boolean} option.pinyin 启用拼音搜索,需要pinyinEngine组件 * @return {jQuery} */ $.fn.ibosSelect = (function(){ var _process = function(datum, collection, filter){ var group, attr; datum = datum[0]; if (datum.children) { group = {}; for (attr in datum) { if (datum.hasOwnProperty(attr)) group[attr] = datum[attr]; } group.children = []; $(datum.children).each2(function(i, childDatum) { _process(childDatum, group.children, filter); }); if (group.children.length) { collection.push(group); } } else { if(filter && !filter(datum)) { return false; } collection.push(datum); } } // 使用带有filter过滤源数据的query函数,其实质就是在query函数执行之前,用filter函数先过滤一次数据 var _queryWithFilter = function(query, filter){ var t = query.term, filtered = { results: [] }, data = []; $(this.data).each2(function(i, datum) { _process(datum, data, filter); }); if (t === "") { query.callback({ results: data }); return; } $(data).each2(function(i, datum) { _process(datum, filtered.results, function(d){ return query.matcher(t, d.text + ""); }) }); query.callback(filtered); } // 根据ID从data数组中获取对应的文本, 主要用于val设置 var _getTextById = function(id, data){ // debugger; var ret; for(var i = 0; i < data.length; i++){ if(data[i].children){ ret = _getTextById(id, data[i].children); if(typeof ret !== "undefined"){ break; } } else { if(data[i].id + "" === id) { ret = data[i].text; break; } } } return ret; } var defaults = { multiple: true, pinyin: true, formatResultCssClass: function(data){ return data.cls; }, formatNoMatches: function(){ return U.lang("S2.NO_MATCHES"); }, formatSelectionTooBig: function (limit) { return U.lang("S2.SELECTION_TO_BIG", { count: limit}); }, formatSearching: function () { return U.lang("S2.SEARCHING"); }, formatInputTooShort: function (input, min) { return U.lang("S2.INPUT_TO_SHORT", { count: min - input.length}); }, formatLoadMore: function (pageNumber) { return U.lang("S2.LOADING_MORE"); }, initSelection: function(elem, callback){ var ins = elem.data("select2"), data = ins.opts.data, results; if(ins.opts.multiple) { results = []; $.each(elem.val().split(','), function(index, val){ results.push({id: val, text: _getTextById(val, data)}); }) } else { results = { id: elem.val(), text: _getTextById(elem.val(), data) } } callback(results); } } var select2 = function(option){ if(typeof option !== "string") { option = $.extend({}, defaults, option); // 注意: filter | query | includes | excludes 四个属性是互斥的 // filter基于query, 而includes、excludes基于filter // 优先度 includes > excludes > filter > query // includes是一个数组,指定源数据中有效数据的ID值,将过滤ID不在此数组中的数据 if(option.includes && $.isArray(option.includes)){ option.filter = function(datum){ return $.inArray(datum.id, option.includes) !== -1; } // includes是一个数组,指定源数据中无效数据的ID值,将过滤ID在此数组中的数据 } else if(option.excludes && $.isArray(option.excludes)) { option.filter = function(datum){ return $.inArray(datum.id, option.excludes) === -1; } } // 当有filter属性时,将使用自定义的query方法替代原来的query方法,filter用于从源数据层面上过滤不需要出现的数据 if(option.filter){ option.query = function(query) { _queryWithFilter(query, option.filter); } } // 使用pinyin搜索引擎 if(option.pinyin) { var _customMatcher = option.matcher; option.matcher = function(term){ if(term === ""){ return true; } return Ibos.matchSpell.apply(this, arguments) && (_customMatcher ? _customMatcher.apply(this, arguments) : true); } } // 使用 select 元素时,要去掉一部分默认项 if($(this).is("select")) { delete option.multiple; delete option.initSelection; } return $.fn.select2.call(this, option) } return $.fn.select2.apply(this, arguments) } return select2; })();
SeekArt/IBOS
static/js/src/base/ibos.select2.js
JavaScript
lgpl-3.0
5,038
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the documentation of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of The Qt Company Ltd nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "piechart.h" #include "pieslice.h" #include <qdeclarative.h> #include <QDeclarativeView> #include <QApplication> int main(int argc, char *argv[]) { QApplication app(argc, argv); qmlRegisterType<PieChart>("Charts", 1, 0, "PieChart"); qmlRegisterType<PieSlice>("Charts", 1, 0, "PieSlice"); QDeclarativeView view; view.setSource(QUrl::fromLocalFile("app.qml")); view.show(); return app.exec(); }
Distrotech/qtquick1
examples/declarative/tutorials/extending/chapter5-listproperties/main.cpp
C++
lgpl-3.0
2,394
#include <cstdio> #include <cstring> #define MAXX 50 #define MAXY 50 #define MAXLEN 100 #define Zero(v) memset((v), 0, sizeof(v)) int X, Y; char ins[MAXLEN + 1]; int x, y, d; bool scent[MAXX + 1][MAXY + 1]; const char dirs_str[] = "NESW"; const int dirs[4][2] = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; void simulate() { int n = strlen(ins); int x2, y2; bool lost = false; for (int i = 0; i < n; ++i) { if (ins[i] == 'L') { d = (d + 3) % 4; continue; } else if (ins[i] == 'R') { d = (d + 1) % 4; continue; } else if (ins[i] != 'F') continue; x2 = x + dirs[d][0]; y2 = y + dirs[d][1]; if (x2 >= 0 && x2 <= X && y2 >= 0 && y2 <= Y) { x = x2, y = y2; continue; } if (scent[x][y]) continue; scent[x][y] = true; lost = true; break; } printf("%d %d %c", x, y, dirs_str[d]); if (lost) puts(" LOST"); else putchar('\n'); } int main() { scanf("%d%d", &X, &Y); char o[4]; while (true) { if (scanf("%d%d%s%s", &x, &y, o, ins) != 4) break; d = strcspn(dirs_str, o); simulate(); } return 0; }
lbv/pc-code
solved/l-n/mutant-flatworld-explorers/explorers.cpp
C++
unlicense
1,276
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; function Square(props) { return ( <button className="square" onClick={props.onClick}> {props.value} </button> ); } class Board extends React.Component { renderSquare(i) { return ( <Square value={this.props.squares[i]} onClick={() => this.props.onClick(i)} /> ); } render() { return ( <div> <div className="board-row"> {this.renderSquare(0)} {this.renderSquare(1)} {this.renderSquare(2)} </div> <div className="board-row"> {this.renderSquare(3)} {this.renderSquare(4)} {this.renderSquare(5)} </div> <div className="board-row"> {this.renderSquare(6)} {this.renderSquare(7)} {this.renderSquare(8)} </div> </div> ); } } class Game extends React.Component { constructor(props) { super(props); this.state = { history: [{ squares: Array(9).fill(null) }], xIsNext: true }; } handleClick(i) { const history = this.state.history; const current = history[history.length - 1]; const squares = current.squares.slice(); if (calculateWinner(squares) || squares[i]) { return; } squares[i] = this.state.xIsNext ? 'X' : 'O'; this.setState({ history: history.concat([{ squares: squares }]), xIsNext: !this.state.xIsNext, }); } render() { const history = this.state.history; const current = history[history.length - 1]; const winner = calculateWinner(current.squares); let status; if (winner) { status = 'Winner: ' + winner; } else { status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O'); } return ( <div className="game"> <div className="game-board"> <Board squares={current.squares} onClick={(i) => this.handleClick(i)} /> </div> <div className="game-info"> <div>{status}</div> <ol>{/* TODO */}</ol> </div> </div> ); } } // ======================================== ReactDOM.render( <Game />, document.getElementById('root') ); function calculateWinner(squares) { const lines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]; for (let i = 0; i < lines.length; i++) { const [a, b, c] = lines[i]; if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) { return squares[a]; } } return null; }
xiaoxiaoyao/MyApp
HTML/前端/my-react-app-spring-boot-yao/src/index.js
JavaScript
unlicense
2,690
require('babel-core/register')({plugins: ['babel-plugin-rewire']}) import packageJson from '../package.json' import conformToMask from '../src/conformToMask' import {placeholderChar} from '../src/constants' const createTextMaskInputElement = (isVerify()) ? require(`../${packageJson.main}`).createTextMaskInputElement : require('../src/createTextMaskInputElement.js').default describe('createTextMaskInputElement', () => { let inputElement beforeEach(() => { inputElement = document.createElement('input') }) it('takes an inputElement and other Text Mask parameters and returns an object which ' + 'allows updating and controlling the masking of the input element', () => { const maskedInputElementControl = createTextMaskInputElement({ inputElement, mask: ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] }) expect(maskedInputElementControl.update).to.be.a('function') }) it('works with mask functions', () => { const mask = () => [/\d/, /\d/, /\d/, /\d/] expect(() => createTextMaskInputElement({inputElement, mask})).to.not.throw() }) it('displays mask when showMask is true', () => { const textMaskControl = createTextMaskInputElement({ showMask: true, inputElement, mask: ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] }) textMaskControl.update() expect(inputElement.value).to.equal('(___) ___-____') }) it('does not display mask when showMask is false', () => { const textMaskControl = createTextMaskInputElement({ showMask: false, inputElement, mask: ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] }) textMaskControl.update() expect(inputElement.value).to.equal('') }) describe('`update` method', () => { it('conforms whatever value is in the input element to a mask', () => { const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] const textMaskControl = createTextMaskInputElement({inputElement, mask}) inputElement.value = '2' textMaskControl.update() expect(inputElement.value).to.equal('(2__) ___-____') }) it('works after multiple calls', () => { const mask = ['+', '1', ' ', '(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] const textMaskControl = createTextMaskInputElement({inputElement, mask}) inputElement.value = '2' textMaskControl.update() expect(inputElement.value).to.equal('+1 (2__) ___-____') inputElement.value = '+1 (23__) ___-____' inputElement.selectionStart = 6 textMaskControl.update() expect(inputElement.value).to.equal('+1 (23_) ___-____') inputElement.value = '+1 (2_) ___-____' inputElement.selectionStart = 5 textMaskControl.update() expect(inputElement.value).to.equal('+1 (2__) ___-____') inputElement.value = '+1 (__) ___-____' inputElement.selectionStart = 4 textMaskControl.update() expect(inputElement.value).to.equal('') }) it('accepts a string to conform and overrides whatever value is in the input element', () => { const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] const textMaskControl = createTextMaskInputElement({inputElement, mask}) inputElement.value = '2' textMaskControl.update('123') expect(inputElement.value).to.equal('(123) ___-____') }) it('accepts an empty string and overrides whatever value is in the input element', () => { const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] const textMaskControl = createTextMaskInputElement({inputElement, mask}) textMaskControl.update(123) expect(inputElement.value).to.equal('(123) ___-____') textMaskControl.update('') expect(inputElement.value).to.equal('') }) it('accepts an empty string after reinitializing text mask', () => { const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] let textMaskControl = createTextMaskInputElement({inputElement, mask}) textMaskControl.update(123) expect(inputElement.value).to.equal('(123) ___-____') //reset text mask textMaskControl = createTextMaskInputElement({inputElement, mask}) // now clear the value textMaskControl.update('') expect(inputElement.value).to.equal('') }) if (!isVerify()) { it('does not conform given parameter if it is the same as the previousConformedValue', () => { const conformToMaskSpy = sinon.spy(conformToMask) const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] const textMaskControl = createTextMaskInputElement({inputElement, mask}) createTextMaskInputElement.__Rewire__('conformToMask', conformToMaskSpy) inputElement.value = '2' textMaskControl.update() expect(inputElement.value).to.equal('(2__) ___-____') expect(conformToMaskSpy.callCount).to.equal(1) textMaskControl.update('(2__) ___-____') expect(conformToMaskSpy.callCount).to.equal(1) createTextMaskInputElement.__ResetDependency__('conformToMask') }) } it('works with a string', () => { const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] const textMaskControl = createTextMaskInputElement({inputElement, mask}) textMaskControl.update('2') expect(inputElement.value).to.equal('(2__) ___-____') }) it('works with a number by coercing it into a string', () => { const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] const textMaskControl = createTextMaskInputElement({inputElement, mask}) textMaskControl.update(2) expect(inputElement.value).to.equal('(2__) ___-____') }) it('works with `undefined` and `null` by treating them as empty strings', () => { const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] const textMaskControl = createTextMaskInputElement({inputElement, mask}) textMaskControl.update(undefined) expect(inputElement.value).to.equal('') textMaskControl.update(null) expect(inputElement.value).to.equal('') }) it('throws if given a value that it cannot work with', () => { const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] const textMaskControl = createTextMaskInputElement({inputElement, mask}) expect(() => textMaskControl.update({})).to.throw() expect(() => textMaskControl.update(() => 'howdy')).to.throw() expect(() => textMaskControl.update([])).to.throw() }) it('adjusts the caret position', () => { const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] const textMaskControl = createTextMaskInputElement({inputElement, mask, placeholderChar}) inputElement.focus() inputElement.value = '2' inputElement.selectionStart = 1 textMaskControl.update() expect(inputElement.selectionStart).to.equal(2) }) it('does not adjust the caret position if the input element is not focused', () => { const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] const textMaskControl = createTextMaskInputElement({inputElement, mask}) inputElement.value = '2' inputElement.selectionStart = 1 textMaskControl.update() expect(inputElement.selectionStart).to.equal(0) }) it('calls the mask function before every update', () => { const maskSpy = sinon.spy(() => [/\d/, /\d/, /\d/, /\d/]) const textMaskControl = createTextMaskInputElement({inputElement, mask: maskSpy}) inputElement.value = '2' textMaskControl.update() expect(inputElement.value).to.equal('2___') inputElement.value = '24' textMaskControl.update() expect(inputElement.value).to.equal('24__') expect(maskSpy.callCount).to.equal(2) }) it('can be disabled with `false` mask', () => { const mask = false const textMaskControl = createTextMaskInputElement({inputElement, mask}) inputElement.value = 'a' textMaskControl.update() expect(inputElement.value).to.equal('a') }) it('can be disabled by returning `false` from mask function', () => { const mask = () => false const textMaskControl = createTextMaskInputElement({inputElement, mask}) inputElement.value = 'a' textMaskControl.update() expect(inputElement.value).to.equal('a') }) it('can pass in a config object to the update method', () => { const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] const textMaskControl = createTextMaskInputElement() let inputElement = {value: '2'} textMaskControl.update(inputElement.value, {inputElement, mask}) expect(inputElement.value).to.equal('(2__) ___-____') }) it('can change the mask passed to the update method', () => { const textMaskControl = createTextMaskInputElement() let inputElement = {value: '2'} textMaskControl.update(inputElement.value, { inputElement, mask: ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] }) expect(inputElement.value).to.equal('(2__) ___-____') textMaskControl.update('2', { inputElement, mask: ['+', '1', ' ', '(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] }) expect(inputElement.value).to.equal('+1 (2__) ___-____') }) it('can change the guide passed to the update method', () => { const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] const textMaskControl = createTextMaskInputElement() let inputElement = {value: '2'} textMaskControl.update(inputElement.value, {inputElement, mask, guide: true}) expect(inputElement.value).to.equal('(2__) ___-____') textMaskControl.update('2', {inputElement, mask, guide: false}) expect(inputElement.value).to.equal('(2') }) it('can change the placeholderChar passed to the update method', () => { const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] const textMaskControl = createTextMaskInputElement() let inputElement = {value: '2'} textMaskControl.update(inputElement.value, {inputElement, mask, placeholderChar: '_'}) expect(inputElement.value).to.equal('(2__) ___-____') textMaskControl.update('2', {inputElement, mask, placeholderChar: '*'}) expect(inputElement.value).to.equal('(2**) ***-****') }) it('can change the inputElement passed to the update method', () => { const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] const textMaskControl = createTextMaskInputElement() let firstInputElement = {value: '1'} let secondInputElement = {value: '2'} textMaskControl.update('1', {inputElement: firstInputElement, mask}) expect(firstInputElement.value).to.equal('(1__) ___-____') textMaskControl.update('2', {inputElement: secondInputElement, mask}) expect(secondInputElement.value).to.equal('(2__) ___-____') }) it('can change the config passed to createTextMaskInputElement', () => { const config = { inputElement, mask: ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/], guide: true, placeholderChar: '_' } const textMaskControl = createTextMaskInputElement(config) inputElement.value = '2' textMaskControl.update() expect(inputElement.value).to.equal('(2__) ___-____') // change the mask config.mask = ['+', '1', ' ', '(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] inputElement.value = '23' // <- you have to change the value textMaskControl.update() expect(inputElement.value).to.equal('+1 (23_) ___-____') // change the placeholderChar config.placeholderChar = '*' inputElement.value = '4' // <- you have to change the value textMaskControl.update() expect(inputElement.value).to.equal('+1 (4**) ***-****') // change the guide config.guide = false inputElement.value = '45' // <- you have to change the value textMaskControl.update() expect(inputElement.value).to.equal('+1 (45') }) it('can override the config passed to createTextMaskInputElement', () => { const textMaskControl = createTextMaskInputElement({ inputElement, mask: ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/], guide: true }) inputElement.value = '2' textMaskControl.update() expect(inputElement.value).to.equal('(2__) ___-____') // pass in a config to the update method textMaskControl.update('23', { inputElement, mask: ['+', '1', ' ', '(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/], guide: false }) expect(inputElement.value).to.equal('+1 (23') // use original config again inputElement.value = '234' // <- you have to change the value textMaskControl.update() expect(inputElement.value).to.equal('(234) ___-____') }) }) })
CrisDan1905/text-mask
core/test/createTextMaskInputElement.spec.js
JavaScript
unlicense
13,794
GoogleElectionMap.shapeReady({name:"28_05",type:"state",state:"28_05",bounds:[],centroid:[],shapes:[ {points:[ {x:32.8810559124534,y: 24.5253494052583} , {x:32.8804366855404,y: 24.5250018993236} , {x:32.8804349320052,y: 24.5250021192127} , {x:32.8800699675051,y: 24.52504787811} , {x:32.880107603168,y: 24.5253602242076} , {x:32.8802839839792,y: 24.52603126374} , {x:32.8806752087983,y: 24.5268181464166} , {x:32.8813572439035,y: 24.5276168223645} , {x:32.8819505502392,y: 24.5286583392856} , {x:32.8825307177406,y: 24.5302435034032} , {x:32.882934635026,y: 24.5310072542635} , {x:32.8834485851789,y: 24.5330479929378} , {x:32.8837280117142,y: 24.5339626803751} , {x:32.884343892289,y: 24.534985099402} , {x:32.8849707220765,y: 24.5357073551443} , {x:32.8857139839758,y: 24.5365877815531} , {x:32.8867322124162,y: 24.5378013619691} , {x:32.8876882846372,y: 24.5390216560881} , {x:32.8891919119942,y: 24.540785084219} , {x:32.8898616158364,y: 24.5413523715326} , {x:32.890834703648,y: 24.5420471161423} , {x:32.892022806308,y: 24.5427073069361} , {x:32.8929960248504,y: 24.543274797266} , {x:32.8936151079581,y: 24.5439230021262} , {x:32.8939563239076,y: 24.5441777223781} , {x:32.8941969226219,y: 24.5443351788832} , {x:32.8942217362609,y: 24.5443514180803} , {x:32.8943103917561,y: 24.5441895397177} , {x:32.8939318918876,y: 24.5431597894563} , {x:32.8935156289255,y: 24.5419333682628} , {x:32.8928971968486,y: 24.5405332931207} , {x:32.8917605486434,y: 24.5388783635996} , {x:32.8902124631775,y: 24.5361164927854} , {x:32.888306467008,y: 24.5329536141396} , {x:32.8876782300639,y: 24.5314852017043} , {x:32.8871284082075,y: 24.5298608543163} , {x:32.8865281254967,y: 24.5282916909969} , {x:32.8855427814326,y: 24.5272845980552} , {x:32.8843422710402,y: 24.5265318135685} , {x:32.8843325732352,y: 24.5265286685573} , {x:32.8830908791957,y: 24.5261259978265} , {x:32.881890005934,y: 24.525789614878} , {x:32.8818650371091,y: 24.5257764371665} , {x:32.8810559124534,y: 24.5253494052583} ]} , {points:[ {x:32.9019960722517,y: 24.546197781935} , {x:32.9010302932533,y: 24.5450044439886} , {x:32.9010174381379,y: 24.545007502719} , {x:32.9007640795607,y: 24.5450677818085} , {x:32.9005131225026,y: 24.5451274885421} , {x:32.9003777640669,y: 24.5457237535524} , {x:32.9002865578843,y: 24.5473482461574} , {x:32.9004882152,y: 24.5482120654834} , {x:32.9003525941626,y: 24.5491373531242} , {x:32.900832773743,y: 24.55037862879} , {x:32.9018562389718,y: 24.5516524640258} , {x:32.9023628597906,y: 24.552782200296} , {x:32.9021249492644,y: 24.5534958706051} , {x:32.9022027836992,y: 24.5546847079245} , {x:32.9023690012363,y: 24.5560566043976} , {x:32.9028188794294,y: 24.5584934715349} , {x:32.9029844838607,y: 24.5607298870529} , {x:32.9032690872615,y: 24.5622439360486} , {x:32.9035020034828,y: 24.5643563747934} , {x:32.9037861391809,y: 24.5666009905706} , {x:32.9050066369447,y: 24.5719657076965} , {x:32.9052751701374,y: 24.5736726816184} , {x:32.9057684355406,y: 24.5755648725823} , {x:32.9061501491834,y: 24.5763054129537} , {x:32.9068912719161,y: 24.5775602749211} , {x:32.9071826506696,y: 24.5788354173812} , {x:32.9074633948669,y: 24.5793008493204} , {x:32.9078171918728,y: 24.5798100253351} , {x:32.9084907789616,y: 24.5812139252027} , {x:32.9090556117857,y: 24.5819898205123} , {x:32.9090636373088,y: 24.5820008439576} , {x:32.9092325012938,y: 24.5820241121723} , {x:32.9094009189669,y: 24.5820473185113} , {x:32.9096709844482,y: 24.5817544472809} , {x:32.909941684888,y: 24.5805824705258} , {x:32.9102296567228,y: 24.5788398566416} , {x:32.9103986387366,y: 24.5783849828288} , {x:32.9104974920394,y: 24.5767592356871} , {x:32.9105124195482,y: 24.5765137378363} , {x:32.9108056159214,y: 24.5753006450003} , {x:32.9102678229386,y: 24.5726887078502} , {x:32.9104706554834,y: 24.5720513487502} , {x:32.9103591291708,y: 24.5707968848439} , {x:32.9091798931689,y: 24.5670953383371} , {x:32.9087759661133,y: 24.5655306319631} , {x:32.9086508606572,y: 24.5642050621524} , {x:32.9078914454148,y: 24.5627695300111} , {x:32.9076658286507,y: 24.5618722099146} , {x:32.9077735243321,y: 24.5588879375975} , {x:32.907774932616,y: 24.5588497040426} , {x:32.9073701959783,y: 24.5556912390294} , {x:32.9072276733165,y: 24.5544241590121} , {x:32.906409261338,y: 24.5532986913824} , {x:32.9056973049112,y: 24.5517939294792} , {x:32.9049817259066,y: 24.5509504330437} , {x:32.9049658377677,y: 24.5509316956826} , {x:32.90381474316,y: 24.5492835424285} , {x:32.9037636822701,y: 24.5492027419115} , {x:32.9030737275812,y: 24.5481109239315} , {x:32.9019960722517,y: 24.546197781935} ]} , {points:[ {x:32.9068658186117,y: 24.5915723876647} , {x:32.9066878311066,y: 24.5915748676675} , {x:32.9067076277387,y: 24.5919749787228} , {x:32.9070246099623,y: 24.592443930182} , {x:32.9076231833487,y: 24.5928835333985} , {x:32.9088028737963,y: 24.5933109251489} , {x:32.9090074056725,y: 24.5934322206895} , {x:32.9090270978349,y: 24.5934438824877} , {x:32.9092976821383,y: 24.5934462932366} , {x:32.909286973302,y: 24.5931893578706} , {x:32.9091097934543,y: 24.5929591806176} , {x:32.9086061068361,y: 24.5926094511158} , {x:32.9074405092677,y: 24.5920562524253} , {x:32.9068790119857,y: 24.5915721962758} , {x:32.9068658186117,y: 24.5915723876647} ]} , {points:[ {x:32.9306380028288,y: 24.6439357499388} , {x:32.9304193835619,y: 24.6415543043021} , {x:32.9308201553539,y: 24.6410593727391} , {x:32.9305410201023,y: 24.6400288328263} , {x:32.9302961762274,y: 24.6395098034689} , {x:32.9300974490365,y: 24.6387671899185} , {x:32.9300874336471,y: 24.6384384253086} , {x:32.9298430339207,y: 24.6372989142743} , {x:32.9296187700537,y: 24.6366815740391} , {x:32.929292660736,y: 24.6357273153721} , {x:32.9289463936502,y: 24.6345297135787} , {x:32.9283143679605,y: 24.6333846414923} , {x:32.9276090835126,y: 24.6321245908133} , {x:32.9259368471765,y: 24.6299243777634} , {x:32.9249381092441,y: 24.628550513942} , {x:32.9243679699102,y: 24.6275159314012} , {x:32.9239819137914,y: 24.6264069339599} , {x:32.9237194492429,y: 24.6248475503466} , {x:32.9232304161745,y: 24.6244313972004} , {x:32.9226807488606,y: 24.6237706813579} , {x:32.9219094664714,y: 24.6220371266924} , {x:32.9209583026776,y: 24.6194354801501} , {x:32.9202098225335,y: 24.6176989185076} , {x:32.9196484077822,y: 24.6155277855946} , {x:32.9186196956626,y: 24.613296574409} , {x:32.9177874586635,y: 24.6120536075743} , {x:32.9169938204959,y: 24.6094799128237} , {x:32.9161977168247,y: 24.6075728003033} , {x:32.9158716227109,y: 24.6060585022178} , {x:32.9155042947087,y: 24.605048882695} , {x:32.9152185857547,y: 24.6042823155805} , {x:32.9149134545365,y: 24.602057702674} , {x:32.9145055301289,y: 24.6006555094605} , {x:32.9138931797687,y: 24.5992345016333} , {x:32.912469444399,y: 24.5990566945658} , {x:32.9121294329819,y: 24.5972399297232} , {x:32.9118492363033,y: 24.5956865239906} , {x:32.9114585710327,y: 24.5953194691625} , {x:32.9105310622483,y: 24.5941426406149} , {x:32.9094407460489,y: 24.5939341256383} , {x:32.9079374522802,y: 24.5932473626289} , {x:32.9066457405462,y: 24.5928325034861} , {x:32.9060107956899,y: 24.5916107817261} , {x:32.9048985872142,y: 24.5910952990972} , {x:32.9046749020783,y: 24.589543656946} , {x:32.9047226388473,y: 24.5894667537846} , {x:32.9046136175776,y: 24.5894867602747} , {x:32.9045531817626,y: 24.5883230970128} , {x:32.904354674077,y: 24.5872715018379} , {x:32.9039262262108,y: 24.5861776988867} , {x:32.9034211182531,y: 24.5850978637064} , {x:32.9028247295084,y: 24.583120715002} , {x:32.9025193327864,y: 24.5815503220875} , {x:32.9021368365261,y: 24.5805546797424} , {x:32.9018160783231,y: 24.579040352879} , {x:32.9016023333368,y: 24.5779186450114} , {x:32.9014042324767,y: 24.576404397734} , {x:32.901160779702,y: 24.574091002157} , {x:32.9003959129671,y: 24.5716522686668} , {x:32.9000808960838,y: 24.5709728465639} , {x:32.8997346638503,y: 24.5690107188021} , {x:32.8996510630001,y: 24.5674002554552} , {x:32.8995356436118,y: 24.56571795718} , {x:32.8992341125435,y: 24.5625019090756} , {x:32.8991040170725,y: 24.5599708549208} , {x:32.8989477034196,y: 24.5590748844666} , {x:32.8980879321001,y: 24.5575373917488} , {x:32.8979337637813,y: 24.5561042766295} , {x:32.8975376570664,y: 24.554970632733} , {x:32.896736102018,y: 24.5525857967486} , {x:32.8958712057812,y: 24.5510907338809} , {x:32.894948379246,y: 24.5496231562703} , {x:32.8943796417896,y: 24.547913414668} , {x:32.8941659601485,y: 24.5468477713103} , {x:32.8939212363672,y: 24.5462447535708} , {x:32.8933393728601,y: 24.5455854179938} , {x:32.8920374332369,y: 24.544603111427} , {x:32.8898776653757,y: 24.5431154603853} , {x:32.887671719285,y: 24.5419081362463} , {x:32.8852323439757,y: 24.5389890291771} , {x:32.8834157379391,y: 24.5365649375411} , {x:32.8827275622485,y: 24.5354673965301} , {x:32.882159612944,y: 24.5344169078237} , {x:32.8813308567563,y: 24.5323449731674} , {x:32.8809043076298,y: 24.5314279071763} , {x:32.8805244747611,y: 24.5297327853161} , {x:32.8800349412484,y: 24.5288102153174} , {x:32.8789196989165,y: 24.5269400357722} , {x:32.8784032313241,y: 24.525718351981} , {x:32.8779144990341,y: 24.523998211083} , {x:32.8772079782751,y: 24.5221283481906} , {x:32.8761208595581,y: 24.5194606056338} , {x:32.8755236038326,y: 24.5173415838965} , {x:32.8753881295868,y: 24.5165937557813} , {x:32.874844274727,y: 24.51559635064} , {x:32.8748371177966,y: 24.5155034947354} , {x:32.8743083111815,y: 24.5140476528538} , {x:32.8742450595108,y: 24.5137386722838} , {x:32.8731774306802,y: 24.5138787634109} , {x:32.8645361363841,y: 24.5159432258465} , {x:32.8652039569641,y: 24.5189366440886} , {x:32.8652520261104,y: 24.5190904950891} , {x:32.86244624526,y: 24.5168613373775} , {x:32.8550215473134,y: 24.5082612011912} , {x:32.8473672482674,y: 24.4977405036822} , {x:32.839149268727,y: 24.4926116118191} , {x:32.8195473431857,y: 24.51359608293} , {x:32.819206702427,y: 24.5139593793166} , {x:32.7247874545531,y: 24.4984739899919} , {x:32.7247343429083,y: 24.4967570827833} , {x:32.3053274242314,y: 24.5150151524095} , {x:32.3505190734948,y: 24.6001500683935} , {x:32.3751072001533,y: 24.6461496615975} , {x:32.7461789449408,y: 24.6231108842054} , {x:32.7467358579721,y: 24.6194649771254} , {x:32.7477559210231,y: 24.6199341877182} , {x:32.803738660182,y: 24.6230308346119} , {x:32.8701734869393,y: 24.627487662961} , {x:32.8967684734596,y: 24.636735017169} , {x:32.9086564138478,y: 24.6444041966976} , {x:32.9085952015556,y: 24.6446983519101} , {x:32.9088839652403,y: 24.6443743822834} , {x:32.9137395360047,y: 24.649022571411} , {x:32.9145728631378,y: 24.6528254798246} , {x:32.9171523484769,y: 24.6557762121668} , {x:32.9203176535248,y: 24.6567084526774} , {x:32.9225677645859,y: 24.6573297898235} , {x:32.9261012000676,y: 24.6570952672514} , {x:32.9281613976806,y: 24.6563682843939} , {x:32.9283076390063,y: 24.6563166930561} , {x:32.9300460768901,y: 24.6557632153275} , {x:32.930078176546,y: 24.6543167402235} , {x:32.9301291123022,y: 24.6515128973271} , {x:32.9302158149965,y: 24.6495805473188} , {x:32.9303714586333,y: 24.6486101642897} , {x:32.9306624148647,y: 24.647151462599} , {x:32.9305883773967,y: 24.6456266408222} , {x:32.9306380028288,y: 24.6439357499388} ]} , {points:[ {x:32.9301278080931,y: 24.6938136329239} , {x:32.9300377541867,y: 24.692156899672} , {x:32.9298164212757,y: 24.6882072762278} , {x:32.9297121107921,y: 24.6879556459738} , {x:32.9294180587474,y: 24.6874089693958} , {x:32.9293234043731,y: 24.6868710594824} , {x:32.9291527308794,y: 24.6864372171446} , {x:32.9291336578181,y: 24.6864421087535} , {x:32.9288488400492,y: 24.6865151526406} , {x:32.9282123364019,y: 24.6870874210293} , {x:32.9278797114991,y: 24.6875991050041} , {x:32.9277883747344,y: 24.6905152719209} , {x:32.9278152013799,y: 24.6920194262524} , {x:32.927028589153,y: 24.6952566372695} , {x:32.9266666440096,y: 24.6968847884626} , {x:32.9265143277109,y: 24.6975527094942} , {x:32.926504784016,y: 24.6978942538227} , {x:32.9265046315795,y: 24.697899715071} , {x:32.926704004053,y: 24.6979605380045} , {x:32.9271507021965,y: 24.6972580566782} , {x:32.9278343315725,y: 24.694109085076} , {x:32.9284985018112,y: 24.6926815228648} , {x:32.9287653309034,y: 24.6924156915316} , {x:32.9287763780245,y: 24.6924047858588} , {x:32.9289308088402,y: 24.6926317915826} , {x:32.9289919637841,y: 24.6935700662466} , {x:32.9288974586057,y: 24.6953916422866} , {x:32.9286251096799,y: 24.6966266061184} , {x:32.9286250464307,y: 24.6966371178005} , {x:32.9289288894453,y: 24.6966719617104} , {x:32.929251874777,y: 24.6964378806269} , {x:32.92999717928,y: 24.695299763335} , {x:32.9301308722827,y: 24.694883187372} , {x:32.9301278080931,y: 24.6938136329239} ]} , {points:[ {x:32.9359532780591,y: 24.7004843037647} , {x:32.935801474316,y: 24.7002239811879} , {x:32.9357886591425,y: 24.7002336140543} , {x:32.9356399790571,y: 24.7003453649678} , {x:32.9354024519121,y: 24.7005881698196} , {x:32.9353357010653,y: 24.7011260063233} , {x:32.9347741497566,y: 24.7033063971709} , {x:32.9343155119516,y: 24.7055440351821} , {x:32.9345803620299,y: 24.7059679178579} , {x:32.9345811868437,y: 24.7059692368051} , {x:32.9347699295824,y: 24.7060596578682} , {x:32.9347805585575,y: 24.7060647498539} , {x:32.9349171023363,y: 24.7061382043761} , {x:32.9349419503285,y: 24.7061515716449} , {x:32.9352458131697,y: 24.7061864032094} , {x:32.935492822874,y: 24.7059783028744} , {x:32.9354742240969,y: 24.705206198225} , {x:32.9357831757501,y: 24.7034102505833} , {x:32.9358305344492,y: 24.7022586155847} , {x:32.9359532780591,y: 24.7004843037647} ]} , {points:[ {x:32.9283541767998,y: 24.7026626723457} , {x:32.928378384393,y: 24.7026489501266} , {x:32.9284062204289,y: 24.7027035878679} , {x:32.9282958223407,y: 24.7038531559937} , {x:32.9283080270123,y: 24.7049034785964} , {x:32.9284880185721,y: 24.7058492791804} , {x:32.9286242865129,y: 24.7064207296643} , {x:32.9289967611297,y: 24.7078603728546} , {x:32.9289378378514,y: 24.7090098156704} , {x:32.9292171642024,y: 24.7113352688402} , {x:32.9292892833277,y: 24.712652920268} , {x:32.9292901978439,y: 24.7126704480073} , {x:32.929565634163,y: 24.712627201525} , {x:32.9299932407263,y: 24.7121936400491} , {x:32.9306416779878,y: 24.7112995371153} , {x:32.931383176554,y: 24.7104633465581} , {x:32.9321539830153,y: 24.7099874462971} , {x:32.9325321839224,y: 24.7094872003276} , {x:32.9329234934731,y: 24.7089734689073} , {x:32.9331881499505,y: 24.7083402172446} , {x:32.9331757433794,y: 24.7075512943161} , {x:32.9334072504045,y: 24.7064519636027} , {x:32.9336400743663,y: 24.7044122997087} , {x:32.9336643046898,y: 24.7034673341325} , {x:32.9336035780811,y: 24.7022569339499} , {x:32.9332700520966,y: 24.7014539007155} , {x:32.9331261203406,y: 24.699366404057} , {x:32.9331740413896,y: 24.6981072087208} , {x:32.9330425298376,y: 24.6962038033159} , {x:32.9328816564863,y: 24.6951713762225} , {x:32.9324829967971,y: 24.6948762385797} , {x:32.9324790448901,y: 24.6948792650447} , {x:32.9312403744706,y: 24.6960125789165} , {x:32.9299341488992,y: 24.6972734383093} , {x:32.9291093763119,y: 24.6979619312135} , {x:32.9286008374806,y: 24.699453654554} , {x:32.9280629416164,y: 24.7003050834408} , {x:32.9270956955957,y: 24.701677422276} , {x:32.9265874117721,y: 24.7022552109768} , {x:32.9264644956437,y: 24.702357145296} , {x:32.9265047402766,y: 24.7036026711182} , {x:32.9264001458461,y: 24.7048232863745} , {x:32.9265088642728,y: 24.7053790555104} , {x:32.9267074269958,y: 24.7065028195954} , {x:32.9270006293858,y: 24.7077916825406} , {x:32.9272439366982,y: 24.7087696218084} , {x:32.9276519341097,y: 24.7094668484348} , {x:32.9277083692421,y: 24.7104036495674} , {x:32.9277932630238,y: 24.7115708190394} , {x:32.9279545812083,y: 24.7125815875923} , {x:32.9280991306352,y: 24.7137466496527} , {x:32.9282158175012,y: 24.7139847615695} , {x:32.9282224468774,y: 24.7139982902214} , {x:32.9284218853936,y: 24.7139983856148} , {x:32.9284981695762,y: 24.7134605576316} , {x:32.9284479032918,y: 24.7123777969722} , {x:32.9285239731286,y: 24.7117848949232} , {x:32.9283726871458,y: 24.7108541728527} , {x:32.9285537833565,y: 24.709780619859} , {x:32.9287818872305,y: 24.7094508051419} , {x:32.9287442094019,y: 24.7089843854777} , {x:32.9285356418066,y: 24.7084489855661} , {x:32.9282801103432,y: 24.7075290353529} , {x:32.9282376228917,y: 24.7072527274795} , {x:32.9280927914129,y: 24.706795613638} , {x:32.9277183025548,y: 24.7062421190385} , {x:32.9274540212697,y: 24.7054606274182} , {x:32.9273503854301,y: 24.7042788102001} , {x:32.9274641130945,y: 24.7033961577717} , {x:32.9276172633697,y: 24.7029847241512} , {x:32.9280420539172,y: 24.7027989864893} , {x:32.9283541767998,y: 24.7026626723457} ]} , {points:[ {x:32.9208162904096,y: 24.7770510958558} , {x:32.9211007337113,y: 24.776762878129} , {x:32.9211325033097,y: 24.7764745237737} , {x:32.9214090305648,y: 24.7762151374302} , {x:32.9218436284335,y: 24.7757179295297} , {x:32.9218674454671,y: 24.7755160821795} , {x:32.921820257919,y: 24.7752204768541} , {x:32.9217019007775,y: 24.7750906467883} , {x:32.9213704148419,y: 24.7748669826574} , {x:32.9212442093343,y: 24.7746650551688} , {x:32.9213313367462,y: 24.7742397542994} , {x:32.9214577034765,y: 24.7741893572256} , {x:32.92149725726,y: 24.7740740297348} , {x:32.9216422933842,y: 24.7740741070174} , {x:32.9216551740979,y: 24.7740741138741} , {x:32.921734082428,y: 24.7741534575602} , {x:32.9219235151274,y: 24.7742616979279} , {x:32.92201818807,y: 24.774384305546} , {x:32.9220178169056,y: 24.7749682571044} , {x:32.9221498100616,y: 24.7750571658027} , {x:32.9221677753913,y: 24.775069266495} , {x:32.9224019272746,y: 24.7751094803726} , {x:32.9224204185784,y: 24.7751126556152} , {x:32.9224914224834,y: 24.7752064132983} , {x:32.9225814539933,y: 24.7753847876753} , {x:32.9225860557514,y: 24.7753939045483} , {x:32.9227992193589,y: 24.7754372722542} , {x:32.923019404471,y: 24.7755022490613} , {x:32.9230439499346,y: 24.7755094924108} , {x:32.9230912218574,y: 24.7756753311517} , {x:32.9232251463708,y: 24.7761656316033} , {x:32.923232784689,y: 24.776576564383} , {x:32.9233273705262,y: 24.7768433567888} , {x:32.9234225032297,y: 24.7769241024584} , {x:32.9234378569525,y: 24.7769371345763} , {x:32.9235957739165,y: 24.7769444264127} , {x:32.9237616492274,y: 24.7768507922234} , {x:32.923832848666,y: 24.7766345505647} , {x:32.9239832486008,y: 24.7760290493154} , {x:32.9242047915688,y: 24.7752938173891} , {x:32.9244817271986,y: 24.774356753472} , {x:32.9247346829685,y: 24.7738882799036} , {x:32.9253702091745,y: 24.7720204393668} , {x:32.9256821486737,y: 24.771578073405} , {x:32.9256098051734,y: 24.7712457393048} , {x:32.9257282454079,y: 24.7703896022804} , {x:32.9259241064736,y: 24.7698263034784} , {x:32.9263130772184,y: 24.7690316482456} , {x:32.9264592112858,y: 24.7687555662208} , {x:32.9266496500376,y: 24.7681170488986} , {x:32.9267888897632,y: 24.7669590631455} , {x:32.9268849341731,y: 24.7665356932772} , {x:32.9268709337876,y: 24.7660546717921} , {x:32.926724402225,y: 24.7652881894561} , {x:32.9266930012489,y: 24.762678173805} , {x:32.9266648601911,y: 24.761683714863} , {x:32.9265732876792,y: 24.7609765843913} , {x:32.9264634955015,y: 24.7611008245826} , {x:32.92645625828,y: 24.7600050096003} , {x:32.9265435953009,y: 24.7591904040133} , {x:32.9264488878304,y: 24.7591326821956} , {x:32.9264016034968,y: 24.758988472522} , {x:32.9262755544517,y: 24.7585342238894} , {x:32.9261178214468,y: 24.7582529823664} , {x:32.9260956663604,y: 24.758246901223} , {x:32.9258810081714,y: 24.758187979745} , {x:32.9256361715433,y: 24.7583320410094} , {x:32.9253991694607,y: 24.7585770369395} , {x:32.9252568456882,y: 24.7589230108933} , {x:32.9251066617201,y: 24.7592113053964} , {x:32.9249327290853,y: 24.759600518671} , {x:32.9246934707416,y: 24.7595097332306} , {x:32.9242055687899,y: 24.7598143448404} , {x:32.9237668779038,y: 24.7601598226289} , {x:32.9236155871289,y: 24.7604076879388} , {x:32.9235598404595,y: 24.7607146888924} , {x:32.9236232751192,y: 24.7609424807659} , {x:32.9236149166569,y: 24.7615616772765} , {x:32.923503767919,y: 24.7617511736746} , {x:32.9230790711086,y: 24.7632133217508} , {x:32.9226935299506,y: 24.7642110825424} , {x:32.9224545584024,y: 24.7646291166184} , {x:32.9222831927447,y: 24.764972960526} , {x:32.9219351934721,y: 24.7661768023774} , {x:32.9217505487976,y: 24.766780370422} , {x:32.921609528302,y: 24.7671408129537} , {x:32.921316758495,y: 24.7675349452007} , {x:32.920938898736,y: 24.7683924405507} , {x:32.92083137408,y: 24.7686768984577} , {x:32.9206746268033,y: 24.7689764679615} , {x:32.9205160433852,y: 24.7699160822216} , {x:32.9200688038563,y: 24.7730658036102} , {x:32.9198469408266,y: 24.7735897941973} , {x:32.9200464679148,y: 24.773260560654} , {x:32.9200458813367,y: 24.7741610876857} , {x:32.920078831211,y: 24.7746164290312} , {x:32.919923076022,y: 24.7755472260004} , {x:32.9198538359187,y: 24.7757240684698} , {x:32.9197273632645,y: 24.7759330683902} , {x:32.9196402858313,y: 24.7762718568285} , {x:32.9196717142529,y: 24.7765097808206} , {x:32.9197820835578,y: 24.7767765840627} , {x:32.9199247029633,y: 24.7769591141622} , {x:32.9199398731204,y: 24.7769785290011} , {x:32.920145241427,y: 24.7768705017251} , {x:32.9203347564177,y: 24.776856185831} , {x:32.9204676826221,y: 24.7768818110377} , {x:32.9204847625125,y: 24.7768851040672} , {x:32.9206224517679,y: 24.7770374660924} , {x:32.9206346800874,y: 24.7770509980522} , {x:32.9208162904096,y: 24.7770510958558} ]} , {points:[ {x:32.9265952911567,y: 24.7755382600645} , {x:32.9264970013818,y: 24.7755278555926} , {x:32.926376944919,y: 24.7757548873527} , {x:32.9262923208249,y: 24.7761482014633} , {x:32.9261100128348,y: 24.7764887476701} , {x:32.9259321486701,y: 24.7768252416978} , {x:32.9257454253232,y: 24.777121178403} , {x:32.9256874664148,y: 24.7774820631026} , {x:32.9257114324813,y: 24.7775991198495} , {x:32.9257140371901,y: 24.7776118436441} , {x:32.9258339567799,y: 24.7776159592647} , {x:32.9260383567022,y: 24.7774700747909} , {x:32.9261850208485,y: 24.7773160499914} , {x:32.92632727493,y: 24.777109304969} , {x:32.9264740550811,y: 24.7767606305983} , {x:32.9265941560645,y: 24.7764606037288} , {x:32.9266341755091,y: 24.7763835753447} , {x:32.9267275635725,y: 24.7761889707636} , {x:32.9267322886059,y: 24.7757145131543} , {x:32.926679044876,y: 24.7756252711848} , {x:32.9266124728043,y: 24.775540078528} , {x:32.9265952911567,y: 24.7755382600645} ]} , {points:[ {x:33.4744317904032,y: 25.1187186066261} , {x:33.4762399603633,y: 24.7927394096184} , {x:33.1346860097658,y: 24.7238083860264} , {x:33.1337075660594,y: 24.7249478196243} , {x:33.1322961369637,y: 24.7266068136277} , {x:33.1161169438074,y: 24.7157146510795} , {x:33.109563562643,y: 24.7131034854894} , {x:33.1087693479163,y: 24.7023487564745} , {x:33.106693981545,y: 24.6941627135772} , {x:33.0968800749698,y: 24.6898925300026} , {x:33.0941770161559,y: 24.6840148716203} , {x:33.0904638781902,y: 24.6776673172273} , {x:33.0844741475306,y: 24.6783058498821} , {x:33.0821740392933,y: 24.6768404050772} , {x:33.075702739352,y: 24.6730690387762} , {x:33.0678502289971,y: 24.6702305644103} , {x:33.0678778235264,y: 24.6701018939693} , {x:33.0676729430859,y: 24.6702405099429} , {x:33.0586613121379,y: 24.6727883232178} , {x:33.053357682183,y: 24.6784566526708} , {x:33.0372443455072,y: 24.6843925993545} , {x:33.0358600835625,y: 24.684605729329} , {x:33.0125033881747,y: 24.6882384084197} , {x:33.0111204496743,y: 24.6869711322682} , {x:33.0120572050733,y: 24.686113428667} , {x:33.0178364853864,y: 24.6808097446782} , {x:33.0201606719374,y: 24.6744716960843} , {x:33.0231962991369,y: 24.6629720677839} , {x:32.9605614512104,y: 24.6603400305634} , {x:32.9604623109301,y: 24.6602745037656} , {x:32.9605543123669,y: 24.6599903042435} , {x:32.9606681731848,y: 24.6596385982667} , {x:32.9560560149134,y: 24.6596371781282} , {x:32.9417800888342,y: 24.6593874709673} , {x:32.9412779989811,y: 24.6573080127737} , {x:32.9384711597578,y: 24.6532535726058} , {x:32.9378392944048,y: 24.6522297487431} , {x:32.9388347595213,y: 24.6404924282935} , {x:32.9384869091901,y: 24.635777661254} , {x:32.9383017721416,y: 24.6332681674865} , {x:32.9380514065238,y: 24.6298743464617} , {x:32.9380051982889,y: 24.6286759403527} , {x:32.9379470308886,y: 24.6271673497766} , {x:32.9379076205847,y: 24.6261451893898} , {x:32.9411145045592,y: 24.622950161812} , {x:32.9431545196642,y: 24.6222850693659} , {x:32.9435619447106,y: 24.6220701657095} , {x:32.9436827836863,y: 24.6220064267634} , {x:32.9436863542461,y: 24.6143651023874} , {x:32.9441469037162,y: 24.6093986547591} , {x:32.944118149104,y: 24.6062819534253} , {x:32.9441197110332,y: 24.60619719906} , {x:32.9438976762607,y: 24.606201626789} , {x:32.9393736708041,y: 24.6063005711304} , {x:32.9328718706822,y: 24.6063002152629} , {x:32.9331050412975,y: 24.6048806206539} , {x:32.9354501652893,y: 24.6020230420472} , {x:32.9367406454081,y: 24.6002145715308} , {x:32.937397574752,y: 24.5974429948885} , {x:32.9345156041636,y: 24.5969499875398} , {x:32.93326407273,y: 24.5950589825101} , {x:32.9332559184796,y: 24.5950449301483} , {x:32.9292936413789,y: 24.5969322552563} , {x:32.9275278452337,y: 24.59830230506} , {x:32.925976163456,y: 24.5986046797086} , {x:32.9246647992723,y: 24.5992033259051} , {x:32.9233531860633,y: 24.6001765357055} , {x:32.9224523939545,y: 24.5993519910048} , {x:32.9244276345132,y: 24.5951939677992} , {x:32.9234162282738,y: 24.5906299886102} , {x:32.9241358552543,y: 24.5894738974141} , {x:32.9265408752368,y: 24.5855946214583} , {x:32.9319380959904,y: 24.5809444424616} , {x:32.9401314246661,y: 24.5760437300169} , {x:32.9424906006642,y: 24.573074325624} , {x:32.9424986784935,y: 24.5730641582669} , {x:32.9393489452679,y: 24.5694227771806} , {x:32.9385081078451,y: 24.5616611034652} , {x:32.940557236675,y: 24.5613499661831} , {x:32.9407957223015,y: 24.5607513089639} , {x:32.940697743204,y: 24.5597066463742} , {x:32.9391147753021,y: 24.5587456227167} , {x:32.9405068811319,y: 24.5579150952606} , {x:32.9422270858334,y: 24.5569339683061} , {x:32.9432271499957,y: 24.5576757041022} , {x:32.9458091367332,y: 24.5596788033102} , {x:32.9476017477938,y: 24.5581776173748} , {x:32.9492747525844,y: 24.5566735767016} , {x:32.9492511913614,y: 24.556096177144} , {x:32.9503405427627,y: 24.5556869162587} , {x:32.9530970184699,y: 24.5536961619533} , {x:32.9556286742089,y: 24.5569247945524} , {x:32.9558979203394,y: 24.5576432642052} , {x:32.9502287933394,y: 24.5606069318754} , {x:32.9504202988012,y: 24.5647309886811} , {x:32.9506233484707,y: 24.5659827472189} , {x:32.9505193712573,y: 24.566142681723} , {x:32.9511128190813,y: 24.5739328678197} , {x:32.9514699099922,y: 24.5834933494642} , {x:32.9514910578509,y: 24.5851231999027} , {x:32.9513813954569,y: 24.5885079842458} , {x:32.9512894249695,y: 24.5916466779756} , {x:32.9512884748212,y: 24.5916793122524} , {x:32.9555587008472,y: 24.5917584344959} , {x:32.9604359214414,y: 24.591764310316} , {x:32.9648725585428,y: 24.5923703382067} , {x:32.9696677047299,y: 24.5965211110189} , {x:32.9709015035753,y: 24.597491603433} , {x:32.9761630476761,y: 24.597507636907} , {x:32.9781000508768,y: 24.5984774002783} , {x:32.9790676339984,y: 24.5984768881389} , {x:32.9809999810352,y: 24.5969387418474} , {x:32.9829352836362,y: 24.597260124789} , {x:32.9870511970739,y: 24.5955041473729} , {x:32.9942398415528,y: 24.5925050631465} , {x:32.9955129978101,y: 24.5925020149665} , {x:32.9961840970488,y: 24.5925002862124} , {x:33.0032537726569,y: 24.5973931476321} , {x:33.0067005260133,y: 24.5990804827708} , {x:33.0089985932032,y: 24.6000438497836} , {x:33.0132524135669,y: 24.5953333613966} , {x:33.0166160583005,y: 24.5931476784054} , {x:33.0201566050147,y: 24.5908000174323} , {x:33.0196247650771,y: 24.5858627378405} , {x:33.0216961584709,y: 24.5833749272382} , {x:33.0241751774872,y: 24.5798105646358} , {x:33.0255275117658,y: 24.5776112097045} , {x:33.025802652298,y: 24.5771637267724} , {x:33.0253632439647,y: 24.5717040936168} , {x:33.0312405804262,y: 24.5677967902442} , {x:33.0315001109069,y: 24.5676850337327} , {x:33.0307374905092,y: 24.5657208148313} , {x:33.03110249906,y: 24.5650528230852} , {x:33.0313453926875,y: 24.5627150509625} , {x:33.0314664309926,y: 24.5598207000319} , {x:33.0301699980832,y: 24.5548855435074} , {x:33.0283628763424,y: 24.5496405339186} , {x:33.0283557802747,y: 24.5496447672136} , {x:33.0282051630951,y: 24.5492510829651} , {x:33.0217712838712,y: 24.5319425026369} , {x:33.0167113080963,y: 24.5150152866386} , {x:33.0146217249347,y: 24.510410519088} , {x:33.0188603622799,y: 24.5074104296653} , {x:33.0216629123631,y: 24.5055374422646} , {x:33.0217041640538,y: 24.5055098440247} , {x:33.0198673658199,y: 24.5028410441463} , {x:33.0195662463001,y: 24.5024047921136} , {x:33.0213938958727,y: 24.4987199830509} , {x:33.0253231235738,y: 24.4901599144432} , {x:33.0236314825865,y: 24.4900235752351} , {x:33.0211165363255,y: 24.490045622705} , {x:33.0197692817867,y: 24.4812562503028} , {x:33.0146991493817,y: 24.4813984473001} , {x:33.0146990647463,y: 24.4805635363906} , {x:33.0144853630028,y: 24.4805290414796} , {x:33.0144383124028,y: 24.4805362220035} , {x:33.0144506972708,y: 24.4803432330293} , {x:33.0143593202645,y: 24.4788404005011} , {x:33.0143709280354,y: 24.4650504147615} , {x:33.0139739466547,y: 24.4536992446627} , {x:33.0160307088039,y: 24.4459360173353} , {x:33.0182688220556,y: 24.4410295922151} , {x:33.0178957590495,y: 24.4404320879088} , {x:33.0195165001217,y: 24.4361274497718} , {x:33.017570438027,y: 24.4321200708915} , {x:33.0109024703084,y: 24.4248746697808} , {x:33.0082854270177,y: 24.4235191317602} , {x:33.0096737819095,y: 24.4223825476477} , {x:33.0044540899797,y: 24.4190363739803} , {x:32.9996374836326,y: 24.4155770252913} , {x:32.9915051457668,y: 24.4118534008961} , {x:32.9912400415724,y: 24.4108011377252} , {x:32.9932745755944,y: 24.4036086641156} , {x:32.9838945031547,y: 24.3990848839944} , {x:32.9780047384995,y: 24.3978223683787} , {x:32.9748664177674,y: 24.3975241633683} , {x:32.9675682211924,y: 24.3926711871733} , {x:32.9609818386934,y: 24.3937069668391} , {x:32.9608209511089,y: 24.3937305937064} , {x:32.9619806302833,y: 24.3984337624069} , {x:32.9626768345569,y: 24.3989872970705} , {x:32.9655672041403,y: 24.3979003519156} , {x:32.9674856803134,y: 24.398542634729} , {x:32.969041600144,y: 24.3993447203347} , {x:32.976368405672,y: 24.4004383282386} , {x:32.9754489293497,y: 24.4024385222602} , {x:32.9735058473554,y: 24.4098672789131} , {x:32.9721671016111,y: 24.4137310674117} , {x:32.9710266254581,y: 24.4153527544686} , {x:32.969352779879,y: 24.4174475178025} , {x:32.9669048925164,y: 24.4260155797427} , {x:32.9649578473013,y: 24.4353956880699} , {x:32.9629501075643,y: 24.4358901373565} , {x:32.9595826155141,y: 24.4382166069919} , {x:32.9571063666994,y: 24.4401584991403} , {x:32.9579018458352,y: 24.4408872059921} , {x:32.9606423957697,y: 24.4418592729383} , {x:32.9621718799804,y: 24.4435547558251} , {x:32.9636086009514,y: 24.4450867154261} , {x:32.9658179696213,y: 24.4489724433853} , {x:32.9657831848384,y: 24.4490967844592} , {x:32.9656872812147,y: 24.4488569960374} , {x:32.9584391895548,y: 24.453530144618} , {x:32.9582365660991,y: 24.4535968506956} , {x:32.9540542949719,y: 24.4536955182482} , {x:32.945722201565,y: 24.453785747949} , {x:32.9453265724529,y: 24.4486255787353} , {x:32.9424744003388,y: 24.4499600328403} , {x:32.9396220501061,y: 24.4515372567633} , {x:32.9374997929997,y: 24.4517792015638} , {x:32.9324240771026,y: 24.4501123486301} , {x:32.9321176631925,y: 24.4499634471808} , {x:32.9292920218524,y: 24.449729173774} , {x:32.9281284518618,y: 24.4512554572477} , {x:32.9275140872686,y: 24.4514954044511} , {x:32.9274944069544,y: 24.4515598743304} , {x:32.9274484430174,y: 24.451710440422} , {x:32.9274806553847,y: 24.4523854765016} , {x:32.9271393490264,y: 24.4533803732282} , {x:32.926678424472,y: 24.4541702679722} , {x:32.9259995670418,y: 24.4552878712202} , {x:32.9254368781261,y: 24.4564950986046} , {x:32.9256645667922,y: 24.4567663474892} , {x:32.9257308689091,y: 24.4571520902171} , {x:32.9257326850214,y: 24.45716265465} , {x:32.925718178649,y: 24.4571709439482} , {x:32.9251856532206,y: 24.4574752277054} , {x:32.9244332220766,y: 24.4583299636256} , {x:32.921765749381,y: 24.4608522187756} , {x:32.9215496695509,y: 24.4613088713053} , {x:32.9214006893959,y: 24.4616237165181} , {x:32.9205574361376,y: 24.4618944025} , {x:32.9207394578765,y: 24.4623116294567} , {x:32.9202838834556,y: 24.4620819643362} , {x:32.9201021334365,y: 24.4621175104617} , {x:32.9199648391812,y: 24.4621443619852} , {x:32.9179820137698,y: 24.4628106891301} , {x:32.9181225892719,y: 24.4632233063734} , {x:32.9183231497629,y: 24.463811988507} , {x:32.9183094198579,y: 24.4638320693402} , {x:32.9182091087511,y: 24.4639787780145} , {x:32.9178218227726,y: 24.4638534252626} , {x:32.9173712101452,y: 24.4633460744509} , {x:32.9170248979402,y: 24.4629561532969} , {x:32.9166147328349,y: 24.4629767808286} , {x:32.9158626196242,y: 24.4632266346336} , {x:32.9143130983837,y: 24.4633091761699} , {x:32.9134473506369,y: 24.463120966735} , {x:32.9129229477082,y: 24.4635795034448} , {x:32.911874778088,y: 24.4635788864262} , {x:32.9095686210679,y: 24.4638878913566} , {x:32.9095503487271,y: 24.4638903395972} , {x:32.9095214665313,y: 24.4638878627079} , {x:32.9085705964573,y: 24.4638063151168} , {x:32.9079098083929,y: 24.4637850518816} , {x:32.9077666148357,y: 24.4638120765222} , {x:32.9072489120412,y: 24.4639097799952} , {x:32.9068160333262,y: 24.4638260837151} , {x:32.9066362783388,y: 24.4635725796416} , {x:32.9065201233391,y: 24.4634087687462} , {x:32.9057683499884,y: 24.4631788737925} , {x:32.9029696824947,y: 24.4631353878309} , {x:32.9024678873666,y: 24.4631681754734} , {x:32.90105567952,y: 24.4632593092612} , {x:32.9000685936142,y: 24.4633220059821} , {x:32.8965041315348,y: 24.4633691975997} , {x:32.8942318468812,y: 24.4634010606622} , {x:32.8918522322889,y: 24.4637881159969} , {x:32.8900848037968,y: 24.4639673635775} , {x:32.8886716556412,y: 24.4644043034163} , {x:32.8866430703704,y: 24.4650493298351} , {x:32.8847059379289,y: 24.4653398401743} , {x:32.8836580603796,y: 24.4650053246929} , {x:32.8828835691607,y: 24.4647335871008} , {x:32.8822913140538,y: 24.464524557201} , {x:32.8808786484259,y: 24.4644191570506} , {x:32.8799215940977,y: 24.4644392481401} , {x:32.8786908403848,y: 24.4647302465895} , {x:32.8773001249196,y: 24.4654799452116} , {x:32.8772885508404,y: 24.4654611641922} , {x:32.8767373747814,y: 24.465782836649} , {x:32.8758171125834,y: 24.4670158179687} , {x:32.8748661268747,y: 24.4683188656159} , {x:32.873760857034,y: 24.4707013008467} , {x:32.8733147815418,y: 24.4725375147676} , {x:32.8728999402219,y: 24.4737709030003} , {x:32.8726689131862,y: 24.4750044472548} , {x:32.8722846806285,y: 24.4762518793058} , {x:32.8720989836596,y: 24.4780883101216} , {x:32.8719434469522,y: 24.480387418647} , {x:32.8716401710236,y: 24.4830125163849} , {x:32.8718358145877,y: 24.4831783979583} , {x:32.8722566687157,y: 24.4829036070144} , {x:32.8741180554374,y: 24.4810902511849} , {x:32.8745933152822,y: 24.4807261370689} , {x:32.8751908592654,y: 24.480628498218} , {x:32.8757426678876,y: 24.4803065031203} , {x:32.8766016835663,y: 24.4791435738083} , {x:32.8777058936218,y: 24.4778686815717} , {x:32.8788099322518,y: 24.476747998169} , {x:32.8792853378875,y: 24.4762016119267} , {x:32.8796685454564,y: 24.4759495647739} , {x:32.879867485422,y: 24.476160020805} , {x:32.8795300577604,y: 24.4765943625075} , {x:32.8788857665445,y: 24.4775331669997} , {x:32.8783949409088,y: 24.4781776778593} , {x:32.8771225277622,y: 24.4791440024978} , {x:32.8766159121313,y: 24.4802511461753} , {x:32.8760638008967,y: 24.4808815795938} , {x:32.8757725280882,y: 24.4810916339979} , {x:32.8755273099408,y: 24.481203588579} , {x:32.8754040450301,y: 24.481918494214} , {x:32.874974573653,y: 24.4824508861916} , {x:32.8737336729305,y: 24.4827272483921} , {x:32.8726036470046,y: 24.4838002498897} , {x:32.8721078596292,y: 24.484006085037} , {x:32.871954860593,y: 24.4840535509626} , {x:32.8717987455823,y: 24.4841019788974} , {x:32.8720682640643,y: 24.4870693951665} , {x:32.8721546542476,y: 24.4882465631805} , {x:32.872178860249,y: 24.4901325797125} , {x:32.8722678680517,y: 24.4912484258821} , {x:32.87238480514,y: 24.492344887601} , {x:32.8728243006747,y: 24.4945356686698} , {x:32.8731677306684,y: 24.4960276579172} , {x:32.8741879271708,y: 24.498377829612} , {x:32.8742746668915,y: 24.4985776000471} , {x:32.8744281657922,y: 24.4993424773663} , {x:32.8752638259839,y: 24.4997051677703} , {x:32.8756901250646,y: 24.5008463234882} , {x:32.8764854578696,y: 24.5023614218212} , {x:32.8770666152565,y: 24.5049247337276} , {x:32.8775493807895,y: 24.5059329012229} , {x:32.8787721094985,y: 24.5091303800434} , {x:32.8799040102717,y: 24.5112202189285} , {x:32.8811276650825,y: 24.5135484557585} , {x:32.8810960793104,y: 24.5135559353477} , {x:32.8811032939934,y: 24.5135584174999} , {x:32.8814089982616,y: 24.5143718006826} , {x:32.8823416397708,y: 24.5166156802865} , {x:32.8828612814673,y: 24.518088151059} , {x:32.8833813096697,y: 24.5191540500902} , {x:32.8839779292891,y: 24.5202620645861} , {x:32.8852787743661,y: 24.5221416943707} , {x:32.8861661723396,y: 24.5237125701648} , {x:32.8871915525482,y: 24.5252414830452} , {x:32.8887553540111,y: 24.527934632234} , {x:32.8905392859665,y: 24.5308603068156} , {x:32.8917045590535,y: 24.5325875190765} , {x:32.8934078376931,y: 24.5352892875048} , {x:32.895097926975,y: 24.5376504487648} , {x:32.8963847110216,y: 24.538442006447} , {x:32.8974324928709,y: 24.5391076485675} , {x:32.8980098051744,y: 24.5399341909838} , {x:32.8986113827301,y: 24.5412901898302} , {x:32.899437126513,y: 24.5424022204512} , {x:32.9011370992524,y: 24.544043641156} , {x:32.9024079160939,y: 24.5457408444754} , {x:32.9041688775486,y: 24.5479150158313} , {x:32.9054063325601,y: 24.5493344124896} , {x:32.9058687556634,y: 24.5498648141388} , {x:32.9072547710423,y: 24.5514522267472} , {x:32.9075063628739,y: 24.5521634773074} , {x:32.9077935016863,y: 24.5537100018099} , {x:32.9086331778805,y: 24.5575601644752} , {x:32.9089496928646,y: 24.5592875540288} , {x:32.9095507044518,y: 24.5606125463051} , {x:32.9099512021349,y: 24.5619215796379} , {x:32.9102935199248,y: 24.5633471868207} , {x:32.9104963843763,y: 24.5652972457503} , {x:32.9109371556711,y: 24.5668581496024} , {x:32.9110594174495,y: 24.5674733402064} , {x:32.9119250152785,y: 24.5706769741401} , {x:32.9121996561682,y: 24.5725137050113} , {x:32.9123978502729,y: 24.5740699984887} , {x:32.9122740824428,y: 24.5756681602607} , {x:32.9120890873644,y: 24.5771260888368} , {x:32.911720168454,y: 24.5785138109539} , {x:32.9108295269673,y: 24.5805461210864} , {x:32.910506699072,y: 24.5817656311906} , {x:32.9104597668357,y: 24.5830694250971} , {x:32.9102293222049,y: 24.5837282066431} , {x:32.9103814340772,y: 24.5853966286901} , {x:32.9107328534187,y: 24.5870791896776} , {x:32.9110846138012,y: 24.5882991032074} , {x:32.9110611675795,y: 24.5883034071914} , {x:32.9114109967479,y: 24.5892791109466} , {x:32.9123322538596,y: 24.5894890100766} , {x:32.9122132418383,y: 24.5900516929498} , {x:32.912677995947,y: 24.5908386617185} , {x:32.9132300219054,y: 24.5920520891353} , {x:32.9142375581257,y: 24.5936896983338} , {x:32.9153732081227,y: 24.5959669555765} , {x:32.9161954169062,y: 24.5960650877911} , {x:32.9165468622342,y: 24.5978457733524} , {x:32.9170977613339,y: 24.5994723565043} , {x:32.9179249784995,y: 24.600664486359} , {x:32.9190122263665,y: 24.602852145071} , {x:32.9195328359296,y: 24.6039880176211} , {x:32.92005263289,y: 24.6063716267045} , {x:32.9206803887137,y: 24.6078440216776} , {x:32.9218237549914,y: 24.6107660904485} , {x:32.9226728580168,y: 24.6129058136324} , {x:32.9233809233381,y: 24.6145842920042} , {x:32.9248527794672,y: 24.6169028530244} , {x:32.9262842086941,y: 24.6185261883942} , {x:32.927548950356,y: 24.6202604061722} , {x:32.9283108079115,y: 24.6217770603822} , {x:32.9297889590711,y: 24.6234943412971} , {x:32.9310862534797,y: 24.6252856575358} , {x:32.9317647470376,y: 24.6272935388356} , {x:32.9323469123533,y: 24.6284434102354} , {x:32.9324076356243,y: 24.6295649989427} , {x:32.932928320603,y: 24.6309812097507} , {x:32.9332034910109,y: 24.6326216173078} , {x:32.9334786916322,y: 24.6342199660057} , {x:32.9335850415993,y: 24.6360705874553} , {x:32.9338908625373,y: 24.6377951245266} , {x:32.9343961835524,y: 24.6393515163125} , {x:32.934742534322,y: 24.640977060185} , {x:32.9338846304493,y: 24.6426065493079} , {x:32.9333061170819,y: 24.6456694579079} , {x:32.9335428021607,y: 24.6475337861533} , {x:32.9334651912716,y: 24.6490223965714} , {x:32.9337406046447,y: 24.6504207418661} , {x:32.9341564018662,y: 24.6517757058689} , {x:32.9344186866408,y: 24.6525367013744} , {x:32.9345355444842,y: 24.6532627124578} , {x:32.9345599547491,y: 24.654002763353} , {x:32.9345733202194,y: 24.654600340024} , {x:32.9347841147191,y: 24.6558235003299} , {x:32.9349739757199,y: 24.6578134037326} , {x:32.9350818117384,y: 24.6592514609693} , {x:32.9351281255652,y: 24.6595279660513} , {x:32.935117134979,y: 24.659528817565} , {x:32.9350250891935,y: 24.6599054018994} , {x:32.9348707807736,y: 24.6607464812061} , {x:32.9349369987621,y: 24.6616221702179} , {x:32.9351993907479,y: 24.6625185978563} , {x:32.9354920103629,y: 24.6637202062262} , {x:32.9355012005733,y: 24.6646259936154} , {x:32.9355706460088,y: 24.6668459991914} , {x:32.9351894702441,y: 24.6690860303879} , {x:32.9351981885386,y: 24.6706892152292} , {x:32.9351170912726,y: 24.6720600356651} , {x:32.9351028589512,y: 24.672300003534} , {x:32.93497359024,y: 24.6734409909807} , {x:32.9346003179076,y: 24.6751371222348} , {x:32.934401395434,y: 24.6761274176997} , {x:32.9340289433417,y: 24.6770723485504} , {x:32.9337845488045,y: 24.6778424418576} , {x:32.9334547973161,y: 24.6790216011264} , {x:32.9331679008032,y: 24.6797275154423} , {x:32.9331535813395,y: 24.6804381855217} , {x:32.9333454389482,y: 24.6816346079095} , {x:32.9333042627723,y: 24.6830187346502} , {x:32.9335760588394,y: 24.6840504768157} , {x:32.9338794908192,y: 24.6852690176107} , {x:32.93407970237,y: 24.6868490800257} , {x:32.9343327975666,y: 24.6893640885765} , {x:32.9347685104386,y: 24.6906172983743} , {x:32.9351472953324,y: 24.6917055719386} , {x:32.9355633237969,y: 24.6926090096808} , {x:32.9356491300707,y: 24.6936197229112} , {x:32.9361423510662,y: 24.6963039116542} , {x:32.9371754512515,y: 24.6985972727033} , {x:32.9374552244995,y: 24.700501739863} , {x:32.9376308234516,y: 24.7024180611081} , {x:32.9375818562894,y: 24.70460511625} , {x:32.9372224611889,y: 24.7077656176362} , {x:32.9373841218653,y: 24.7075558649985} , {x:32.9366130274144,y: 24.7085763874999} , {x:32.9358954265757,y: 24.7092769224491} , {x:32.9348014207392,y: 24.7102131419909} , {x:32.9334237623154,y: 24.7116655632802} , {x:32.932088735961,y: 24.7127152782576} , {x:32.9313515468689,y: 24.7139204374873} , {x:32.9310291194109,y: 24.714615872806} , {x:32.9307751088903,y: 24.7166945426785} , {x:32.9305329132943,y: 24.7176219879823} , {x:32.9302097107003,y: 24.7192413851803} , {x:32.9300250932086,y: 24.7200191250692} , {x:32.9294255098064,y: 24.7217741377303} , {x:32.9289372050318,y: 24.7231195863497} , {x:32.928929734816,y: 24.7231401667347} , {x:32.9285492658332,y: 24.7241594344958} , {x:32.928513223313,y: 24.7249903103628} , {x:32.9283316256367,y: 24.72604261337} , {x:32.9283520632578,y: 24.726502395455} , {x:32.929291899499,y: 24.7274586132744} , {x:32.9294105395205,y: 24.7291726580119} , {x:32.929546635861,y: 24.7304124738804} , {x:32.9294498041599,y: 24.7319933637737} , {x:32.9291182603579,y: 24.732832454587} , {x:32.9292590938429,y: 24.7351377663496} , {x:32.929441434218,y: 24.7362063035906} , {x:32.9294593270074,y: 24.7369320418494} , {x:32.9295347023828,y: 24.7386906173833} , {x:32.9299173660719,y: 24.7409113121792} , {x:32.9299735558953,y: 24.7420185100343} , {x:32.9301778367877,y: 24.7436263996471} , {x:32.930198461766,y: 24.7447514064787} , {x:32.9298241206925,y: 24.7461493772315} , {x:32.9297372773706,y: 24.7476251402954} , {x:32.9289554969062,y: 24.752485772653} , {x:32.928747101161,y: 24.75375012468} , {x:32.9282521646155,y: 24.7557256546676} , {x:32.9279060574901,y: 24.7575746593587} , {x:32.9278135680367,y: 24.758215996165} , {x:32.9278593657313,y: 24.7586576253337} , {x:32.9282083451854,y: 24.7577208563067} , {x:32.9283909902611,y: 24.7578899813649} , {x:32.9286304425892,y: 24.7576290079785} , {x:32.928679272722,y: 24.7588885088206} , {x:32.9285869894456,y: 24.7592827550664} , {x:32.9286367267761,y: 24.7594422017018} , {x:32.9287298598988,y: 24.7595986335381} , {x:32.9288854653395,y: 24.7583385466581} , {x:32.9288889211632,y: 24.7583418321436} , {x:32.9289007436031,y: 24.7584995817718} , {x:32.9289231990461,y: 24.7587992276581} , {x:32.9288701448866,y: 24.7609283765588} , {x:32.9289910513447,y: 24.7609284351479} , {x:32.9287882143323,y: 24.7638993136603} , {x:32.9286796689393,y: 24.7653946215427} , {x:32.9287372812183,y: 24.7663090749012} , {x:32.9285288575449,y: 24.7669271454134} , {x:32.92831957007,y: 24.7674468650747} , {x:32.928145470014,y: 24.7681852679211} , {x:32.928040541619,y: 24.7694553668343} , {x:32.9277418944874,y: 24.7706823810053} , {x:32.927654239722,y: 24.7717200021784} , {x:32.9276089045484,y: 24.7724146904566} , {x:32.9275722946154,y: 24.7729770016992} , {x:32.9273281479343,y: 24.774807839751} , {x:32.9270351108341,y: 24.7768209316773} , {x:32.927337990197,y: 24.7763147817332} , {x:32.927013191311,y: 24.776531522535} , {x:32.9269837320037,y: 24.7765511809216} , {x:32.9267072055474,y: 24.7767876171354} , {x:32.9264391488429,y: 24.7773000618078} , {x:32.9260498337469,y: 24.7783723379014} , {x:32.9256001845332,y: 24.7792237791152} , {x:32.9254963846851,y: 24.779476072662} , {x:32.9251594653799,y: 24.7795863026974} , {x:32.9251247953737,y: 24.7797834305751} , {x:32.9247948516476,y: 24.7809935325255} , {x:32.9249646617194,y: 24.7810178383656} , {x:32.9251490493303,y: 24.7811522799507} , {x:32.9253391212652,y: 24.7814290799837} , {x:32.9254271650525,y: 24.781076071347} , {x:32.9254283484981,y: 24.781095544762} , {x:32.9253283607598,y: 24.781463524772} , {x:32.9250436535207,y: 24.7821005951104} , {x:32.9250264367755,y: 24.7821246890646} , {x:32.9244719640944,y: 24.7828875027354} , {x:32.9242690285557,y: 24.7832680940621} , {x:32.9240135614021,y: 24.7838514334696} , {x:32.9238299787036,y: 24.7841944482014} , {x:32.923838045906,y: 24.7846374081639} , {x:32.9238402209682,y: 24.7847138103397} , {x:32.9238560270538,y: 24.7852437317724} , {x:32.9236138936205,y: 24.7853694017258} , {x:32.9234623558351,y: 24.7854887948313} , {x:32.9231139462105,y: 24.7857556907311} , {x:32.9228073729393,y: 24.7862850426506} , {x:32.9226831502023,y: 24.7839974212002} , {x:32.9225532891422,y: 24.7844626155809} , {x:32.9223110401389,y: 24.7850775807088} , {x:32.9220945469937,y: 24.7859370194497} , {x:32.9217485000418,y: 24.7867648453347} , {x:32.9216999273838,y: 24.7870035206945} , {x:32.9215751956725,y: 24.7876164198515} , {x:32.921333046683,y: 24.7880578964998} , {x:32.9211054650413,y: 24.7885569941573} , {x:32.9210562363517,y: 24.7886649546755} , {x:32.9210546305681,y: 24.7886898351628} , {x:32.9209951601943,y: 24.7896112186885} , {x:32.920700676734,y: 24.7908254733627} , {x:32.9205188032516,y: 24.7915508692535} , {x:32.920216244767,y: 24.7918819095026} , {x:32.9198444587763,y: 24.7923942842644} , {x:32.9195873968631,y: 24.7935613587314} , {x:32.9194015170349,y: 24.794060059372} , {x:32.9193911154275,y: 24.7942563174771} , {x:32.9190771477351,y: 24.794567704191} , {x:32.9186393142288,y: 24.7951667408711} , {x:32.9185873388827,y: 24.7952591573295} , {x:32.9184546303872,y: 24.7954951710966} , {x:32.9181886766305,y: 24.7961845941351} , {x:32.918295551838,y: 24.7969800572191} , {x:32.9180815228979,y: 24.7977815099514} , {x:32.9178741092421,y: 24.7981605396523} , {x:32.9174313623337,y: 24.7985157485639} , {x:32.9173580334909,y: 24.798966216766} , {x:32.9172287165194,y: 24.7998826036419} , {x:32.9170397942108,y: 24.8006930264288} , {x:32.9166268632323,y: 24.801782811508} , {x:32.9163930799149,y: 24.8025633717648} , {x:32.9161418277955,y: 24.8036199252583} , {x:32.9158820393859,y: 24.8045187575214} , {x:32.9157428420785,y: 24.8059381194581} , {x:32.9156475392721,y: 24.806332353656} , {x:32.9151456053277,y: 24.8075701350416} , {x:32.9147303611289,y: 24.8083663592545} , {x:32.9142977559523,y: 24.8092729745952} , {x:32.9141992708051,y: 24.8101489005137} , {x:32.9134056363416,y: 24.8114203104863} , {x:32.9130101742781,y: 24.8124102465207} , {x:32.9127256057329,y: 24.8130466512639} , {x:32.9123016529284,y: 24.8139714448995} , {x:32.9118181950568,y: 24.8147644311867} , {x:32.9118132104355,y: 24.8158352528831} , {x:32.9110260245684,y: 24.8171359274064} , {x:32.9101698409462,y: 24.8182472968217} , {x:32.9096219043769,y: 24.819184411743} , {x:32.9096347267476,y: 24.8192003165851} , {x:32.9091504537458,y: 24.8197677915638} , {x:32.9078958498886,y: 24.8202057509515} , {x:32.9074984960777,y: 24.8204742676116} , {x:32.9067291425041,y: 24.821766160798} , {x:32.9057285551196,y: 24.8236309651356} , {x:32.9050887733982,y: 24.8245207429577} , {x:32.9037883092423,y: 24.8254541522264} , {x:32.9034537795725,y: 24.8260006829962} , {x:32.9030499007502,y: 24.826831054998} , {x:32.9029832042663,y: 24.826936019474} , {x:32.902669239321,y: 24.8274301251187} , {x:32.9020120842132,y: 24.8280079846996} , {x:32.9008358002951,y: 24.829426645114} , {x:32.900039770538,y: 24.8307509209604} , {x:32.8994300687631,y: 24.8316195340226} , {x:32.8994053647743,y: 24.8316547285781} , {x:32.8991622238374,y: 24.8321757467438} , {x:32.8990129533781,y: 24.8324956108809} , {x:32.8985974080316,y: 24.8334416194777} , {x:32.8982510631521,y: 24.8342930450317} , {x:32.8978589290621,y: 24.8347764370512} , {x:32.8974667476094,y: 24.835312399973} , {x:32.8969575963321,y: 24.8357558622709} , {x:32.8966826996026,y: 24.8359952913069} , {x:32.8963941983728,y: 24.8365418362841} , {x:32.8962122626649,y: 24.8371790393771} , {x:32.8961630843052,y: 24.8373512795893} , {x:32.8958627916944,y: 24.8382132453124} , {x:32.895654883583,y: 24.8388229310271} , {x:32.8951934590856,y: 24.8394639822948} , {x:32.8950635775822,y: 24.8396266853132} , {x:32.8950089092518,y: 24.8396951681062} , {x:32.8944435803428,y: 24.8405692104401} , {x:32.8945565195875,y: 24.841439778796} , {x:32.8943022117675,y: 24.8415219900716} , {x:32.894190109228,y: 24.8417715181375} , {x:32.894231726778,y: 24.8425387586869} , {x:32.8942345745765,y: 24.8425912748885} , {x:32.8943287761773,y: 24.8438666011175} , {x:32.8937575298907,y: 24.8446213029933} , {x:32.8932230605749,y: 24.8450745775207} , {x:32.8927884940776,y: 24.8456811451068} , {x:32.8926705164069,y: 24.8460549186866} , {x:32.8917663570225,y: 24.8478832664045} , {x:32.8909002523665,y: 24.8496646990135} , {x:32.8902980025054,y: 24.8508617898645} , {x:32.8908352376935,y: 24.8511172969076} , {x:32.8908996809991,y: 24.851147957379} , {x:32.8937835994337,y: 24.8527496645362} , {x:32.8955438496299,y: 24.8542349217164} , {x:32.8959270412336,y: 24.8550325789258} , {x:32.8994257469539,y: 24.8548905618399} , {x:32.9037891854298,y: 24.8544837412578} , {x:32.9056634375724,y: 24.8538119328173} , {x:32.9119228017722,y: 24.8520202167553} , {x:32.9160200430428,y: 24.8514450060516} , {x:32.9161853412503,y: 24.8515450747674} , {x:32.9162424546993,y: 24.8515115098829} , {x:32.9182630447518,y: 24.8513128168791} , {x:32.9209575126526,y: 24.8510129422786} , {x:32.924669086344,y: 24.8517583193709} , {x:32.9278117318929,y: 24.852982544901} , {x:32.9292709573927,y: 24.8523712468954} , {x:32.9318169850952,y: 24.8525796833606} , {x:32.9336391911536,y: 24.851708248895} , {x:32.9453425008659,y: 24.8539070144252} , {x:32.9568279474866,y: 24.8464814433184} , {x:32.9804849669071,y: 24.8356543168099} , {x:32.9900398454007,y: 24.8455389070718} , {x:32.989530781126,y: 24.8474122543946} , {x:32.9905621041816,y: 24.8469565863812} , {x:32.9906068520364,y: 24.8476974034454} , {x:32.9911044041365,y: 24.8559351053064} , {x:32.9957819032223,y: 24.8601918770721} , {x:32.9978253141553,y: 24.8701327440178} , {x:32.9976225070353,y: 24.8703126451725} , {x:32.9976623093172,y: 24.8703089318966} , {x:33.0247670562779,y: 25.0128841647688} , {x:33.0376796684278,y: 25.012829139629} , {x:33.050415493061,y: 25.01344003155} , {x:33.0630398992527,y: 25.0136712057918} , {x:33.062359169166,y: 25.0149764969917} , {x:33.0630409293024,y: 25.0147320144853} , {x:33.0700241456856,y: 25.0144035256714} , {x:33.0778221599905,y: 25.0223180106365} , {x:33.0823848640069,y: 25.0181484598058} , {x:33.0901704325144,y: 25.0132568485274} , {x:33.0902247083489,y: 25.0136802367035} , {x:33.090439095594,y: 25.0132769937907} , {x:33.0974240752101,y: 25.0134496433665} , {x:33.098860782988,y: 25.0163195449055} , {x:33.1067067331546,y: 25.0127411941409} , {x:33.1162597448036,y: 25.0133676427572} , {x:33.1185801664153,y: 25.0189383641595} , {x:33.1211298446881,y: 25.0180448589445} , {x:33.1505809986843,y: 25.0288776008302} , {x:33.1517199488609,y: 25.0282859228616} , {x:33.4744317904032,y: 25.1187186066261} ]} ]})
amounir86/amounir86-2011-elections
voter-info/shapes/old_json/28_05.js
JavaScript
unlicense
52,858
<?php /** * An exception when an fActiveRecord is not found in the database * * @copyright Copyright (c) 2007-2008 Will Bond * @author Will Bond [wb] <will@flourishlib.com> * @license http://flourishlib.com/license * * @package Flourish * @link http://flourishlib.com/fNotFoundException * * @version 1.0.0b * @changes 1.0.0b The initial implementation [wb, 2007-06-14] */ class fNotFoundException extends fExpectedException { } /** * Copyright (c) 2007-2008 Will Bond <will@flourishlib.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */
ksa46/work
library/Flourish/lib/fNotFoundException.php
PHP
unlicense
1,655
#include "buffer_manager.hh" #include "assert.hh" #include "buffer.hh" #include "client_manager.hh" #include "exception.hh" #include "file.hh" #include "ranges.hh" #include "string.hh" namespace Kakoune { BufferManager::~BufferManager() { // Move buffers to avoid running BufClose with buffers remaining in that list BufferList buffers = std::move(m_buffers); for (auto& buffer : buffers) buffer->on_unregistered(); // Make sure not clients exists if (ClientManager::has_instance()) ClientManager::instance().clear(); } Buffer* BufferManager::create_buffer(String name, Buffer::Flags flags, StringView data, timespec fs_timestamp) { auto path = real_path(parse_filename(name)); for (auto& buf : m_buffers) { if (buf->name() == name or (buf->flags() & Buffer::Flags::File and buf->name() == path)) throw runtime_error{"buffer name is already in use"}; } m_buffers.push_back(std::make_unique<Buffer>(std::move(name), flags, data, fs_timestamp)); auto* buffer = m_buffers.back().get(); buffer->on_registered(); if (contains(m_buffer_trash, buffer)) throw runtime_error{"buffer got removed during its creation"}; return buffer; } void BufferManager::delete_buffer(Buffer& buffer) { auto it = find_if(m_buffers, [&](auto& p) { return p.get() == &buffer; }); kak_assert(it != m_buffers.end()); m_buffer_trash.emplace_back(std::move(*it)); m_buffers.erase(it); if (ClientManager::has_instance()) ClientManager::instance().ensure_no_client_uses_buffer(buffer); buffer.on_unregistered(); } Buffer* BufferManager::get_buffer_ifp(StringView name) { auto path = real_path(parse_filename(name)); for (auto& buf : m_buffers) { if (buf->name() == name or (buf->flags() & Buffer::Flags::File and buf->name() == path)) return buf.get(); } return nullptr; } Buffer& BufferManager::get_buffer(StringView name) { Buffer* res = get_buffer_ifp(name); if (not res) throw runtime_error{format("no such buffer '{}'", name)}; return *res; } Buffer& BufferManager::get_first_buffer() { if (all_of(m_buffers, [](auto& b) { return (b->flags() & Buffer::Flags::Debug); })) create_buffer("*scratch*", Buffer::Flags::None); return *m_buffers.back(); } void BufferManager::backup_modified_buffers() { for (auto& buf : m_buffers) { if ((buf->flags() & Buffer::Flags::File) and buf->is_modified() and not (buf->flags() & Buffer::Flags::ReadOnly)) write_buffer_to_backup_file(*buf); } } void BufferManager::clear_buffer_trash() { for (auto& buffer : m_buffer_trash) { // Do that again, to be tolerant in some corner cases, where a buffer is // deleted during its creation if (ClientManager::has_instance()) { ClientManager::instance().ensure_no_client_uses_buffer(*buffer); ClientManager::instance().clear_window_trash(); } buffer.reset(); } m_buffer_trash.clear(); } }
casimir/kakoune
src/buffer_manager.cc
C++
unlicense
3,157
# -*- encoding: utf-8 -*- # # Copyright © 2013 IBM Corp # # Author: Tong Li <litong01@us.ibm.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging.handlers import os import tempfile from ceilometer.dispatcher import file from ceilometer.openstack.common.fixture import config from ceilometer.openstack.common import test from ceilometer.publisher import utils class TestDispatcherFile(test.BaseTestCase): def setUp(self): super(TestDispatcherFile, self).setUp() self.CONF = self.useFixture(config.Config()).conf def test_file_dispatcher_with_all_config(self): # Create a temporaryFile to get a file name tf = tempfile.NamedTemporaryFile('r') filename = tf.name tf.close() self.CONF.dispatcher_file.file_path = filename self.CONF.dispatcher_file.max_bytes = 50 self.CONF.dispatcher_file.backup_count = 5 dispatcher = file.FileDispatcher(self.CONF) # The number of the handlers should be 1 self.assertEqual(1, len(dispatcher.log.handlers)) # The handler should be RotatingFileHandler handler = dispatcher.log.handlers[0] self.assertIsInstance(handler, logging.handlers.RotatingFileHandler) msg = {'counter_name': 'test', 'resource_id': self.id(), 'counter_volume': 1, } msg['message_signature'] = utils.compute_signature( msg, self.CONF.publisher.metering_secret, ) # The record_metering_data method should exist and not produce errors. dispatcher.record_metering_data(msg) # After the method call above, the file should have been created. self.assertTrue(os.path.exists(handler.baseFilename)) def test_file_dispatcher_with_path_only(self): # Create a temporaryFile to get a file name tf = tempfile.NamedTemporaryFile('r') filename = tf.name tf.close() self.CONF.dispatcher_file.file_path = filename self.CONF.dispatcher_file.max_bytes = None self.CONF.dispatcher_file.backup_count = None dispatcher = file.FileDispatcher(self.CONF) # The number of the handlers should be 1 self.assertEqual(1, len(dispatcher.log.handlers)) # The handler should be RotatingFileHandler handler = dispatcher.log.handlers[0] self.assertIsInstance(handler, logging.FileHandler) msg = {'counter_name': 'test', 'resource_id': self.id(), 'counter_volume': 1, } msg['message_signature'] = utils.compute_signature( msg, self.CONF.publisher.metering_secret, ) # The record_metering_data method should exist and not produce errors. dispatcher.record_metering_data(msg) # After the method call above, the file should have been created. self.assertTrue(os.path.exists(handler.baseFilename)) def test_file_dispatcher_with_no_path(self): self.CONF.dispatcher_file.file_path = None dispatcher = file.FileDispatcher(self.CONF) # The log should be None self.assertIsNone(dispatcher.log)
tanglei528/ceilometer
ceilometer/tests/dispatcher/test_file.py
Python
apache-2.0
3,762
/* * 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.isis.core.metamodel.facets.object.callbacks.remove; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.isis.core.metamodel.adapter.ObjectAdapter; import org.apache.isis.core.metamodel.facetapi.FacetHolder; import org.apache.isis.core.metamodel.facets.ImperativeFacet; public class RemovingCallbackFacetViaMethod extends RemovingCallbackFacetAbstract implements ImperativeFacet { private final List<Method> methods = new ArrayList<Method>(); public RemovingCallbackFacetViaMethod(final Method method, final FacetHolder holder) { super(holder); addMethod(method); } @Override public void addMethod(final Method method) { methods.add(method); } @Override public boolean impliesResolve() { return false; } @Override public Intent getIntent(final Method method) { return Intent.LIFECYCLE; } @Override public boolean impliesObjectChanged() { return false; } @Override public List<Method> getMethods() { return Collections.unmodifiableList(methods); } @Override public void invoke(final ObjectAdapter adapter) { ObjectAdapter.InvokeUtils.invokeAll(methods, adapter); } @Override protected String toStringValues() { return "methods=" + methods; } }
kidaa/isis
core/metamodel/src/main/java/org/apache/isis/core/metamodel/facets/object/callbacks/remove/RemovingCallbackFacetViaMethod.java
Java
apache-2.0
2,249
/* Copyright 2020 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. */ #include <fuzzer/FuzzedDataProvider.h> #include <vector> #include <aconf.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <png.h> #include "gmem.h" #include "gmempp.h" #include "parseargs.h" #include "GString.h" #include "gfile.h" #include "GlobalParams.h" #include "Object.h" #include "PDFDoc.h" #include "SplashBitmap.h" #include "Splash.h" #include "SplashOutputDev.h" #include "Stream.h" #include "config.h" extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { FuzzedDataProvider fdp (data, size); double hdpi = fdp.ConsumeFloatingPoint<double>(); double vdpi = fdp.ConsumeFloatingPoint<double>(); int rotate = fdp.ConsumeIntegral<int>(); bool useMediaBox = fdp.ConsumeBool(); bool crop = fdp.ConsumeBool(); bool printing = fdp.ConsumeBool(); std::vector<char> payload = fdp.ConsumeRemainingBytes<char>(); Object xpdf_obj; xpdf_obj.initNull(); BaseStream *stream = new MemStream(payload.data(), 0, payload.size(), &xpdf_obj); Object info, xfa; Object *acroForm; globalParams = new GlobalParams(NULL); globalParams->setErrQuiet(1); globalParams->setupBaseFonts(NULL); char yes[] = "yes"; globalParams->setEnableFreeType(yes); // Yes, it's a string and not a bool. globalParams->setErrQuiet(1); PDFDoc *doc = NULL; try { PDFDoc doc(stream); if (doc.isOk() == gTrue) { doc.getNumPages(); doc.getOutline(); doc.getStructTreeRoot(); doc.getXRef(); doc.okToPrint(gTrue); doc.okToCopy(gTrue); doc.okToChange(gTrue); doc.okToAddNotes(gTrue); doc.isLinearized(); doc.getPDFVersion(); GString *metadata; if ((metadata = doc.readMetadata())) { (void)metadata->getCString(); } delete metadata; Object info; doc.getDocInfo(&info); if (info.isDict()) { info.getDict(); } info.free(); if ((acroForm = doc.getCatalog()->getAcroForm())->isDict()) { acroForm->dictLookup("XFA", &xfa); xfa.free(); } for (size_t i = 0; i < doc.getNumPages(); i++) { doc.getLinks(i); auto page = doc.getCatalog()->getPage(i); if (!page->isOk()) { continue; } page->getResourceDict(); page->getMetadata(); page->getResourceDict(); } SplashColor paperColor = {0xff, 0xff, 0xff}; SplashOutputDev *splashOut = new SplashOutputDev(splashModeRGB8, 1, gFalse, paperColor); splashOut->setNoComposite(gTrue); splashOut->startDoc(doc.getXRef()); for (size_t i = 0; i <= doc.getNumPages(); ++i) { doc.displayPage(splashOut, i, hdpi, vdpi, rotate, useMediaBox, crop, printing); } (void)splashOut->getBitmap(); delete splashOut; } } catch (...) { } delete globalParams; return 0; }
skia-dev/oss-fuzz
projects/xpdf/fuzz_pdfload.cc
C++
apache-2.0
3,787
using System; using System.IO; using EnvDTE; namespace NuGet.VisualStudio { public class NativeProjectSystem : VsProjectSystem { public NativeProjectSystem(Project project, IFileSystemProvider fileSystemProvider) : base(project, fileSystemProvider) { } public override bool IsBindingRedirectSupported { get { return false; } } protected override void AddGacReference(string name) { // Native project doesn't know about GAC } public override bool ReferenceExists(string name) { // We disable assembly reference for native projects return true; } public override void AddReference(string referencePath, Stream stream) { // We disable assembly reference for native projects } public override void RemoveReference(string name) { // We disable assembly reference for native projects } public override void AddImport(string targetPath, ProjectImportLocation location) { if (VsVersionHelper.IsVisualStudio2010) { base.AddImport(targetPath, location); } else { // For VS 2012 or above, the operation has to be done inside the Writer lock if (String.IsNullOrEmpty(targetPath)) { throw new ArgumentNullException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "targetPath"); } string relativeTargetPath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(Root), targetPath); Project.DoWorkInWriterLock(buildProject => buildProject.AddImportStatement(relativeTargetPath, location)); Project.Save(); } } public override void RemoveImport(string targetPath) { if (VsVersionHelper.IsVisualStudio2010) { base.RemoveImport(targetPath); } else { // For VS 2012 or above, the operation has to be done inside the Writer lock if (String.IsNullOrEmpty(targetPath)) { throw new ArgumentNullException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "targetPath"); } string relativeTargetPath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(Root), targetPath); Project.DoWorkInWriterLock(buildProject => buildProject.RemoveImportStatement(relativeTargetPath)); Project.Save(); } } protected override void AddFileToContainer(string fullPath, ProjectItems container) { container.AddFromFile(Path.GetFileName(fullPath)); } } }
chester89/nugetApi
src/VisualStudio/ProjectSystems/NativeProjectSystem.cs
C#
apache-2.0
2,947
/** * 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.alibaba.jstorm.message.netty; import backtype.storm.Config; import backtype.storm.messaging.IConnection; import backtype.storm.messaging.IContext; import backtype.storm.utils.DisruptorQueue; import backtype.storm.utils.Utils; import com.alibaba.jstorm.callback.AsyncLoopThread; import com.alibaba.jstorm.metric.MetricDef; import com.alibaba.jstorm.utils.JStormUtils; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NettyContext implements IContext { private final static Logger LOG = LoggerFactory.getLogger(NettyContext.class); @SuppressWarnings("rawtypes") private Map stormConf; private NioClientSocketChannelFactory clientChannelFactory; private ReconnectRunnable reconnector; @SuppressWarnings("unused") public NettyContext() { } /** * initialization per Storm configuration */ @SuppressWarnings("rawtypes") public void prepare(Map stormConf) { this.stormConf = stormConf; int maxWorkers = Utils.getInt(stormConf.get(Config.STORM_MESSAGING_NETTY_CLIENT_WORKER_THREADS)); ThreadFactory bossFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + "boss"); ThreadFactory workerFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + "worker"); if (maxWorkers > 0) { clientChannelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory), Executors.newCachedThreadPool(workerFactory), maxWorkers); } else { clientChannelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory), Executors.newCachedThreadPool(workerFactory)); } reconnector = new ReconnectRunnable(); new AsyncLoopThread(reconnector, true, Thread.MIN_PRIORITY, true); } @Override public IConnection bind(String topologyId, int port, ConcurrentHashMap<Integer, DisruptorQueue> deserializedQueue, DisruptorQueue recvControlQueue, boolean bstartRec, Set<Integer> workerTasks) { IConnection retConnection = null; try { retConnection = new NettyServer(stormConf, port, deserializedQueue, recvControlQueue, bstartRec, workerTasks); } catch (Throwable e) { LOG.error("Failed to create NettyServer", e); JStormUtils.halt_process(-1, "Failed to bind " + port); } return retConnection; } @Override public IConnection connect(String topologyId, String host, int port) { return new NettyClientAsync(stormConf, clientChannelFactory, host, port, reconnector, new HashSet<Integer>(), new HashSet<Integer>()); } @Override public IConnection connect(String topologyId, String host, int port, Set<Integer> sourceTasks, Set<Integer> targetTasks) { return new NettyClientAsync(stormConf, clientChannelFactory, host, port, reconnector, sourceTasks, targetTasks); } /** * terminate this context */ public void term() { /* clientScheduleService.shutdown(); try { clientScheduleService.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { LOG.error("Error when shutting down client scheduler", e); }*/ clientChannelFactory.releaseExternalResources(); reconnector.shutdown(); } }
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/message/netty/NettyContext.java
Java
apache-2.0
4,482
/*! * ${copyright} */ // Provides class sap.ui.rta.plugin.Combine. sap.ui.define([ 'sap/ui/rta/plugin/Plugin', 'sap/ui/dt/Selection', 'sap/ui/dt/OverlayRegistry', 'sap/ui/rta/Utils' ], function( Plugin, Selection, OverlayRegistry, Utils ) { "use strict"; /** * Constructor for a new Combine Plugin. * * @class * @extends sap.ui.rta.plugin.Plugin * @author SAP SE * @version ${version} * @constructor * @private * @since 1.46 * @alias sap.ui.rta.plugin.Combine * @experimental Since 1.46. This class is experimental and provides only limited functionality. Also the API might be changed in future. */ var Combine = Plugin.extend("sap.ui.rta.plugin.Combine", /** @lends sap.ui.rta.plugin.Combine.prototype */ { metadata: { // ---- object ---- // ---- control specific ---- library: "sap.ui.rta", properties: {}, associations: {}, events: {} } }); /** * check if the given overlay is editable * @param {sap.ui.dt.ElementOverlay} oOverlay - overlay to be checked for editable * @returns {boolean} whether it is editable or not * @private */ Combine.prototype._isEditable = function(oOverlay) { var oCombineAction = this.getAction(oOverlay); if (oCombineAction && oCombineAction.changeType && oCombineAction.changeOnRelevantContainer) { return this.hasChangeHandler(oCombineAction.changeType, oOverlay.getRelevantContainer()) && this.hasStableId(oOverlay); } else { return false; } }; Combine.prototype._checkForSameRelevantContainer = function(aSelectedOverlays) { var aRelevantContainer = []; for (var i = 0, n = aSelectedOverlays.length; i < n; i++) { aRelevantContainer[i] = aSelectedOverlays[i].getRelevantContainer(); var oCombineAction = this.getAction(aSelectedOverlays[i]); if (!oCombineAction || !oCombineAction.changeType){ return false; } if (i > 0) { if ((aRelevantContainer[0] !== aRelevantContainer[i]) || (this.getAction(aSelectedOverlays[0]).changeType !== oCombineAction.changeType)) { return false; } } } return true; }; /** * Checks if Combine is available for oOverlay * * @param {sap.ui.dt.Overlay} oOverlay overlay object * @return {boolean} true if available * @public */ Combine.prototype.isAvailable = function(oOverlay) { var aSelectedOverlays = this.getDesignTime().getSelection(); if (aSelectedOverlays.length <= 1) { return false; } return (this._isEditableByPlugin(oOverlay) && this._checkForSameRelevantContainer(aSelectedOverlays)); }; /** * Checks if Combine is enabled for oOverlay * * @param {sap.ui.dt.Overlay} oOverlay overlay object * @return {boolean} true if enabled * @public */ Combine.prototype.isEnabled = function(oOverlay) { var aSelectedOverlays = this.getDesignTime().getSelection(); // check that at least 2 fields can be combined if (!this.isAvailable(oOverlay) || aSelectedOverlays.length <= 1) { return false; } var aSelectedControls = aSelectedOverlays.map(function (oSelectedOverlay) { return oSelectedOverlay.getElementInstance(); }); // check that each selected element has an enabled action var bActionCheck = aSelectedOverlays.every(function(oSelectedOverlay) { var oAction = this.getAction(oSelectedOverlay); if (!oAction) { return false; } // when isEnabled is not defined the default is true if (typeof oAction.isEnabled !== "undefined") { if (typeof oAction.isEnabled === "function") { return oAction.isEnabled(aSelectedControls); } else { return oAction.isEnabled; } } return true; }, this); return bActionCheck; }; /** * @param {any} oCombineElement selected element */ Combine.prototype.handleCombine = function(oCombineElement) { var oElementOverlay = OverlayRegistry.getOverlay(oCombineElement); var oDesignTimeMetadata = oElementOverlay.getDesignTimeMetadata(); var aToCombineElements = []; var aSelectedOverlays = this.getDesignTime().getSelection(); for (var i = 0; i < aSelectedOverlays.length; i++) { var oSelectedElement = aSelectedOverlays[i].getElementInstance(); aToCombineElements.push(oSelectedElement); } var oCombineAction = this.getAction(oElementOverlay); var sVariantManagementReference = this.getVariantManagementReference(oElementOverlay, oCombineAction); var oCombineCommand = this.getCommandFactory().getCommandFor(oCombineElement, "combine", { source : oCombineElement, combineFields : aToCombineElements }, oDesignTimeMetadata, sVariantManagementReference); this.fireElementModified({ "command" : oCombineCommand }); }; /** * Retrieve the context menu item for the action. * @param {sap.ui.dt.ElementOverlay} oOverlay Overlay for which the context menu was opened * @return {object[]} Returns array containing the items with required data */ Combine.prototype.getMenuItems = function(oOverlay){ return this._getMenuItems(oOverlay, {pluginId : "CTX_GROUP_FIELDS", rank : 90}); }; /** * Get the name of the action related to this plugin. * @return {string} Returns the action name */ Combine.prototype.getActionName = function(){ return "combine"; }; /** * Trigger the plugin execution. * @param {sap.ui.dt.ElementOverlay[]} aOverlays Selected overlays; targets of the action * @param {any} oEventItem ContextMenu item which triggers the event * @param {any} oContextElement Element where the action is triggered */ Combine.prototype.handler = function(aOverlays, mPropertyBag){ //TODO: Handle "Stop Cut & Paste" depending on alignment with Dietrich! this.handleCombine(mPropertyBag.contextElement); }; return Combine; }, /* bExport= */true);
SQCLabs/openui5
src/sap.ui.rta/src/sap/ui/rta/plugin/Combine.js
JavaScript
apache-2.0
5,703
package helpers import ( "fmt" "github.com/SpectraLogic/ds3_go_sdk/ds3" ds3Models "github.com/SpectraLogic/ds3_go_sdk/ds3/models" helperModels "github.com/SpectraLogic/ds3_go_sdk/helpers/models" "github.com/SpectraLogic/ds3_go_sdk/sdk_log" "sync" "time" ) type putProducer struct { JobMasterObjectList *ds3Models.MasterObjectList //MOL from put bulk job creation WriteObjects *[]helperModels.PutObject queue *chan TransferOperation strategy *WriteTransferStrategy client *ds3.Client waitGroup *sync.WaitGroup writeObjectMap map[string]helperModels.PutObject processedBlobTracker blobTracker deferredBlobQueue BlobDescriptionQueue // queue of blobs whose channels are not yet ready for transfer sdk_log.Logger // Conditional value that gets triggered when a blob has finished being transferred doneNotifier NotifyBlobDone } func newPutProducer( jobMasterObjectList *ds3Models.MasterObjectList, putObjects *[]helperModels.PutObject, queue *chan TransferOperation, strategy *WriteTransferStrategy, client *ds3.Client, waitGroup *sync.WaitGroup, doneNotifier NotifyBlobDone) *putProducer { return &putProducer{ JobMasterObjectList: jobMasterObjectList, WriteObjects: putObjects, queue: queue, strategy: strategy, client: client, waitGroup: waitGroup, writeObjectMap: toWriteObjectMap(putObjects), deferredBlobQueue: NewBlobDescriptionQueue(), processedBlobTracker: newProcessedBlobTracker(), Logger: client.Logger, // use the same logger as the client doneNotifier: doneNotifier, } } // Creates a map of object name to PutObject struct func toWriteObjectMap(putObjects *[]helperModels.PutObject) map[string]helperModels.PutObject { objectMap := make(map[string]helperModels.PutObject) if putObjects == nil { return objectMap } for _, obj := range *putObjects { objectMap[obj.PutObject.Name] = obj } return objectMap } // Information required to perform a put operation of a blob using the source channelBuilder to BP destination type putObjectInfo struct { blob helperModels.BlobDescription channelBuilder helperModels.ReadChannelBuilder bucketName string jobId string } // Creates the transfer operation that will perform the data upload of the specified blob to BP func (producer *putProducer) transferOperationBuilder(info putObjectInfo) TransferOperation { return func() { // has this file fatally errored while transferring a different blob? if info.channelBuilder.HasFatalError() { // skip performing this blob transfer producer.Warningf("fatal error occurred previously on this file, skipping sending blob name='%s' offset=%d length=%d", info.blob.Name(), info.blob.Offset(), info.blob.Length()) return } reader, err := info.channelBuilder.GetChannel(info.blob.Offset()) if err != nil { producer.strategy.Listeners.Errored(info.blob.Name(), err) info.channelBuilder.SetFatalError(err) producer.Errorf("could not get reader for object with name='%s' offset=%d length=%d: %v", info.blob.Name(), info.blob.Offset(), info.blob.Length(), err) return } defer info.channelBuilder.OnDone(reader) sizedReader := NewIoReaderWithSizeDecorator(reader, info.blob.Length()) putObjRequest := ds3Models.NewPutObjectRequest(info.bucketName, info.blob.Name(), sizedReader). WithJob(info.jobId). WithOffset(info.blob.Offset()) producer.maybeAddMetadata(info, putObjRequest) _, err = producer.client.PutObject(putObjRequest) if err != nil { producer.strategy.Listeners.Errored(info.blob.Name(), err) info.channelBuilder.SetFatalError(err) producer.Errorf("problem during transfer of %s: %s", info.blob.Name(), err.Error()) } } } func (producer *putProducer) maybeAddMetadata(info putObjectInfo, putObjRequest *ds3Models.PutObjectRequest) { metadataMap := producer.metadataFrom(info) if len(metadataMap) == 0 { return } for key, value := range metadataMap { putObjRequest.WithMetaData(key, value) } } func (producer *putProducer) metadataFrom(info putObjectInfo) map[string]string { result := map[string]string{} for _, objectToPut := range *producer.WriteObjects { if objectToPut.PutObject.Name == info.blob.Name() { result = objectToPut.Metadata break } } return result } // Processes all the blobs in a chunk and attempts to add them to the transfer queue. // If a blob is not ready for transfer, then it is added to the waiting to be transferred queue. // Returns the number of blobs added to queue. func (producer *putProducer) processChunk(curChunk *ds3Models.Objects, bucketName string, jobId string) (int, error) { processedCount := 0 producer.Debugf("begin chunk processing %s", curChunk.ChunkId) // transfer blobs that are ready, and queue those that are waiting for channel for _, curObj := range curChunk.Objects { producer.Debugf("queuing object in waiting to be processed %s offset=%d length=%d", *curObj.Name, curObj.Offset, curObj.Length) blob := helperModels.NewBlobDescription(*curObj.Name, curObj.Offset, curObj.Length) blobQueued, err := producer.queueBlobForTransfer(&blob, bucketName, jobId) if err != nil { return 0, err } if blobQueued { processedCount++ } } return processedCount, nil } // Iterates through blobs that are waiting to be transferred and attempts to transfer. // If successful, blob is removed from queue. Else, it is re-queued. // Returns the number of blobs added to queue. func (producer *putProducer) processWaitingBlobs(bucketName string, jobId string) (int, error) { processedCount := 0 // attempt to process all blobs in waiting to be transferred waitingBlobs := producer.deferredBlobQueue.Size() for i := 0; i < waitingBlobs; i++ { //attempt transfer curBlob, err := producer.deferredBlobQueue.Pop() if err != nil { //should not be possible to get here producer.Errorf("problem when getting next blob to be transferred: %s", err.Error()) break } producer.Debugf("attempting to process %s offset=%d length=%d", curBlob.Name(), curBlob.Offset(), curBlob.Length()) blobQueued, err := producer.queueBlobForTransfer(curBlob, bucketName, jobId) if err != nil { return 0, err } if blobQueued { processedCount++ } } return processedCount, nil } // Attempts to transfer a single blob. If the blob is not ready for transfer, // it is added to the waiting to transfer queue. // Returns whether or not the blob was queued for transfer. func (producer *putProducer) queueBlobForTransfer(blob *helperModels.BlobDescription, bucketName string, jobId string) (bool, error) { if producer.processedBlobTracker.IsProcessed(*blob) { return false, nil // this was already processed } curWriteObj, ok := producer.writeObjectMap[blob.Name()] if !ok { err := fmt.Errorf("failed to find object associated with blob in object map: %s offset=%d length=%d", blob.Name(), blob.Offset(), blob.Length()) producer.Errorf("unrecoverable error: %v", err) producer.processedBlobTracker.MarkProcessed(*blob) return false, err // fatal error occurred } if curWriteObj.ChannelBuilder == nil { err := fmt.Errorf("failed to transfer object, it does not have a channel builder: %s", curWriteObj.PutObject.Name) producer.Errorf("unrecoverable error: %v", err) producer.processedBlobTracker.MarkProcessed(*blob) return false, err // fatal error occurred } if curWriteObj.ChannelBuilder.HasFatalError() { // a fatal error happened on a previous blob for this file, skip processing producer.Warningf("fatal error occurred while transferring previous blob on this file, skipping blob %s offset=%d length=%d", blob.Name(), blob.Offset(), blob.Length()) producer.processedBlobTracker.MarkProcessed(*blob) return false, nil // not actually transferring this blob } if !curWriteObj.ChannelBuilder.IsChannelAvailable(blob.Offset()) { producer.Debugf("channel is not currently available for blob %s offset=%d length=%d", blob.Name(), blob.Offset(), blob.Length()) // Not ready to be transferred producer.deferredBlobQueue.Push(blob) return false, nil // not ready to be sent } producer.Debugf("channel is available for blob %s offset=%d length=%d", curWriteObj.PutObject.Name, blob.Offset(), blob.Length()) // Blob ready to be transferred // Create transfer operation objInfo := putObjectInfo{ blob: *blob, channelBuilder: curWriteObj.ChannelBuilder, bucketName: bucketName, jobId: jobId, } transfer := producer.transferOperationBuilder(objInfo) // Increment wait group, and enqueue transfer operation producer.waitGroup.Add(1) *producer.queue <- transfer // Mark blob as processed producer.processedBlobTracker.MarkProcessed(*blob) return true, nil } // This initiates the production of the transfer operations which will be consumed by a consumer running in a separate go routine. // Each transfer operation will put one blob of content to the BP. // Once all blobs have been queued to be transferred, the producer will finish, even if all operations have not been consumed yet. func (producer *putProducer) run() error { defer close(*producer.queue) // determine number of blobs to be processed totalBlobCount := producer.totalBlobCount() producer.Debugf("job status totalBlobs=%d processedBlobs=%d", totalBlobCount, producer.processedBlobTracker.NumberOfProcessedBlobs()) // process all chunks and make sure all blobs are queued for transfer for producer.hasMoreToProcess(totalBlobCount) { processedCount, err := producer.queueBlobsReadyForTransfer(totalBlobCount) if err != nil { return err } // If the last operation processed blobs, then wait for something to finish if processedCount > 0 { // wait for a done signal to be received producer.doneNotifier.Wait() } else if producer.hasMoreToProcess(totalBlobCount) { // nothing could be processed, cache is probably full, wait a bit before trying again time.Sleep(producer.strategy.BlobStrategy.delay()) } } return nil } func (producer *putProducer) hasMoreToProcess(totalBlobCount int64) bool { return producer.processedBlobTracker.NumberOfProcessedBlobs() < totalBlobCount || producer.deferredBlobQueue.Size() > 0 } // Returns the number of items queued for work. func (producer *putProducer) queueBlobsReadyForTransfer(totalBlobCount int64) (int, error) { // Attempt to transfer waiting blobs processedCount, err := producer.processWaitingBlobs(*producer.JobMasterObjectList.BucketName, producer.JobMasterObjectList.JobId) if err != nil { return 0, err } // Check if we need to query the BP for allocated blobs, or if we already know everything is allocated. if int64(producer.deferredBlobQueue.Size()) + producer.processedBlobTracker.NumberOfProcessedBlobs() >= totalBlobCount { // Everything is already allocated, no need to query BP for allocated chunks return processedCount, nil } // Get the list of available chunks that the server can receive. The server may // not be able to receive everything, so not all chunks will necessarily be // returned chunksReady := ds3Models.NewGetJobChunksReadyForClientProcessingSpectraS3Request(producer.JobMasterObjectList.JobId) chunksReadyResponse, err := producer.client.GetJobChunksReadyForClientProcessingSpectraS3(chunksReady) if err != nil { producer.Errorf("unrecoverable error: %v", err) return processedCount, err } // Check to see if any chunks can be processed numberOfChunks := len(chunksReadyResponse.MasterObjectList.Objects) if numberOfChunks > 0 { // Loop through all the chunks that are available for processing, and send // the files that are contained within them. for _, curChunk := range chunksReadyResponse.MasterObjectList.Objects { justProcessedCount, err := producer.processChunk(&curChunk, *chunksReadyResponse.MasterObjectList.BucketName, chunksReadyResponse.MasterObjectList.JobId) if err != nil { return 0, err } processedCount += justProcessedCount } } return processedCount, nil } // Determines the number of blobs to be transferred. func (producer *putProducer) totalBlobCount() int64 { if producer.JobMasterObjectList.Objects == nil || len(producer.JobMasterObjectList.Objects) == 0 { return 0 } var count int64 = 0 for _, chunk := range producer.JobMasterObjectList.Objects { for range chunk.Objects { count++ } } return count }
SpectraLogic/ds3_go_sdk
helpers/putProducer.go
GO
apache-2.0
13,579
package org.jboss.resteasy.test.providers.multipart.resource; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "customer") @XmlAccessorType(XmlAccessType.FIELD) public class ContextProvidersCustomer { @XmlElement private String name; public ContextProvidersCustomer() { } public ContextProvidersCustomer(final String name) { this.name = name; } public String getName() { return name; } }
awhitford/Resteasy
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/ContextProvidersCustomer.java
Java
apache-2.0
607
//// [typeGuardFunctionOfFormThis.ts] class RoyalGuard { isLeader(): this is LeadGuard { return this instanceof LeadGuard; } isFollower(): this is FollowerGuard { return this instanceof FollowerGuard; } } class LeadGuard extends RoyalGuard { lead(): void {}; } class FollowerGuard extends RoyalGuard { follow(): void {}; } let a: RoyalGuard = new FollowerGuard(); if (a.isLeader()) { a.lead(); } else if (a.isFollower()) { a.follow(); } interface GuardInterface extends RoyalGuard {} let b: GuardInterface; if (b.isLeader()) { b.lead(); } else if (b.isFollower()) { b.follow(); } // if (((a.isLeader)())) { // a.lead(); // } // else if (((a).isFollower())) { // a.follow(); // } // if (((a["isLeader"])())) { // a.lead(); // } // else if (((a)["isFollower"]())) { // a.follow(); // } var holder2 = {a}; if (holder2.a.isLeader()) { holder2.a; } else { holder2.a; } class ArrowGuard { isElite = (): this is ArrowElite => { return this instanceof ArrowElite; } isMedic = (): this is ArrowMedic => { return this instanceof ArrowMedic; } } class ArrowElite extends ArrowGuard { defend(): void {} } class ArrowMedic extends ArrowGuard { heal(): void {} } let guard = new ArrowGuard(); if (guard.isElite()) { guard.defend(); } else if (guard.isMedic()) { guard.heal(); } interface Supplies { spoiled: boolean; } interface Sundries { broken: boolean; } interface Crate<T> { contents: T; volume: number; isSupplies(): this is Crate<Supplies>; isSundries(): this is Crate<Sundries>; } let crate: Crate<{}>; if (crate.isSundries()) { crate.contents.broken = true; } else if (crate.isSupplies()) { crate.contents.spoiled = true; } // Matching guards should be assignable a.isFollower = b.isFollower; a.isLeader = b.isLeader; class MimicGuard { isLeader(): this is MimicLeader { return this instanceof MimicLeader; }; isFollower(): this is MimicFollower { return this instanceof MimicFollower; }; } class MimicLeader extends MimicGuard { lead(): void {} } class MimicFollower extends MimicGuard { follow(): void {} } let mimic = new MimicGuard(); a.isLeader = mimic.isLeader; a.isFollower = mimic.isFollower; if (mimic.isFollower()) { mimic.follow(); mimic.isFollower = a.isFollower; } interface MimicGuardInterface { isLeader(): this is LeadGuard; isFollower(): this is FollowerGuard; } //// [typeGuardFunctionOfFormThis.js] var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var RoyalGuard = /** @class */ (function () { function RoyalGuard() { } RoyalGuard.prototype.isLeader = function () { return this instanceof LeadGuard; }; RoyalGuard.prototype.isFollower = function () { return this instanceof FollowerGuard; }; return RoyalGuard; }()); var LeadGuard = /** @class */ (function (_super) { __extends(LeadGuard, _super); function LeadGuard() { return _super !== null && _super.apply(this, arguments) || this; } LeadGuard.prototype.lead = function () { }; ; return LeadGuard; }(RoyalGuard)); var FollowerGuard = /** @class */ (function (_super) { __extends(FollowerGuard, _super); function FollowerGuard() { return _super !== null && _super.apply(this, arguments) || this; } FollowerGuard.prototype.follow = function () { }; ; return FollowerGuard; }(RoyalGuard)); var a = new FollowerGuard(); if (a.isLeader()) { a.lead(); } else if (a.isFollower()) { a.follow(); } var b; if (b.isLeader()) { b.lead(); } else if (b.isFollower()) { b.follow(); } // if (((a.isLeader)())) { // a.lead(); // } // else if (((a).isFollower())) { // a.follow(); // } // if (((a["isLeader"])())) { // a.lead(); // } // else if (((a)["isFollower"]())) { // a.follow(); // } var holder2 = { a: a }; if (holder2.a.isLeader()) { holder2.a; } else { holder2.a; } var ArrowGuard = /** @class */ (function () { function ArrowGuard() { var _this = this; this.isElite = function () { return _this instanceof ArrowElite; }; this.isMedic = function () { return _this instanceof ArrowMedic; }; } return ArrowGuard; }()); var ArrowElite = /** @class */ (function (_super) { __extends(ArrowElite, _super); function ArrowElite() { return _super !== null && _super.apply(this, arguments) || this; } ArrowElite.prototype.defend = function () { }; return ArrowElite; }(ArrowGuard)); var ArrowMedic = /** @class */ (function (_super) { __extends(ArrowMedic, _super); function ArrowMedic() { return _super !== null && _super.apply(this, arguments) || this; } ArrowMedic.prototype.heal = function () { }; return ArrowMedic; }(ArrowGuard)); var guard = new ArrowGuard(); if (guard.isElite()) { guard.defend(); } else if (guard.isMedic()) { guard.heal(); } var crate; if (crate.isSundries()) { crate.contents.broken = true; } else if (crate.isSupplies()) { crate.contents.spoiled = true; } // Matching guards should be assignable a.isFollower = b.isFollower; a.isLeader = b.isLeader; var MimicGuard = /** @class */ (function () { function MimicGuard() { } MimicGuard.prototype.isLeader = function () { return this instanceof MimicLeader; }; ; MimicGuard.prototype.isFollower = function () { return this instanceof MimicFollower; }; ; return MimicGuard; }()); var MimicLeader = /** @class */ (function (_super) { __extends(MimicLeader, _super); function MimicLeader() { return _super !== null && _super.apply(this, arguments) || this; } MimicLeader.prototype.lead = function () { }; return MimicLeader; }(MimicGuard)); var MimicFollower = /** @class */ (function (_super) { __extends(MimicFollower, _super); function MimicFollower() { return _super !== null && _super.apply(this, arguments) || this; } MimicFollower.prototype.follow = function () { }; return MimicFollower; }(MimicGuard)); var mimic = new MimicGuard(); a.isLeader = mimic.isLeader; a.isFollower = mimic.isFollower; if (mimic.isFollower()) { mimic.follow(); mimic.isFollower = a.isFollower; } //// [typeGuardFunctionOfFormThis.d.ts] declare class RoyalGuard { isLeader(): this is LeadGuard; isFollower(): this is FollowerGuard; } declare class LeadGuard extends RoyalGuard { lead(): void; } declare class FollowerGuard extends RoyalGuard { follow(): void; } declare let a: RoyalGuard; interface GuardInterface extends RoyalGuard { } declare let b: GuardInterface; declare var holder2: { a: RoyalGuard; }; declare class ArrowGuard { isElite: () => this is ArrowElite; isMedic: () => this is ArrowMedic; } declare class ArrowElite extends ArrowGuard { defend(): void; } declare class ArrowMedic extends ArrowGuard { heal(): void; } declare let guard: ArrowGuard; interface Supplies { spoiled: boolean; } interface Sundries { broken: boolean; } interface Crate<T> { contents: T; volume: number; isSupplies(): this is Crate<Supplies>; isSundries(): this is Crate<Sundries>; } declare let crate: Crate<{}>; declare class MimicGuard { isLeader(): this is MimicLeader; isFollower(): this is MimicFollower; } declare class MimicLeader extends MimicGuard { lead(): void; } declare class MimicFollower extends MimicGuard { follow(): void; } declare let mimic: MimicGuard; interface MimicGuardInterface { isLeader(): this is LeadGuard; isFollower(): this is FollowerGuard; }
synaptek/TypeScript
tests/baselines/reference/typeGuardFunctionOfFormThis.js
JavaScript
apache-2.0
8,326
/* * Copyright (C) 2013 nohana, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.amalgam.database; import android.annotation.TargetApi; import android.database.Cursor; import android.os.Build; /** * Utility for the {@link android.database.Cursor} */ @SuppressWarnings("unused") // public APIs public final class CursorUtils { private static final int TRUE = 1; private CursorUtils() { throw new AssertionError(); } /** * Close with null checks. * @param cursor to close. */ public static void close(Cursor cursor) { if (cursor == null) { return; } cursor.close(); } /** * Read the boolean data for the column. * @see android.database.Cursor#getColumnIndex(String). * @param cursor the cursor. * @param columnName the column name. * @return the boolean value. */ public static boolean getBoolean(Cursor cursor, String columnName) { return cursor != null && cursor.getInt(cursor.getColumnIndex(columnName)) == TRUE; } /** * Read the int data for the column. * @see android.database.Cursor#getInt(int). * @see android.database.Cursor#getColumnIndex(String). * @param cursor the cursor. * @param columnName the column name. * @return the int value. */ public static int getInt(Cursor cursor, String columnName) { if (cursor == null) { return -1; } return cursor.getInt(cursor.getColumnIndex(columnName)); } /** * Read the String data for the column. * @see android.database.Cursor#getString(int). * @see android.database.Cursor#getColumnIndex(String). * @param cursor the cursor. * @param columnName the column name. * @return the String value. */ public static String getString(Cursor cursor, String columnName) { if (cursor == null) { return null; } return cursor.getString(cursor.getColumnIndex(columnName)); } /** * Read the short data for the column. * @see android.database.Cursor#getShort(int). * @see android.database.Cursor#getColumnIndex(String). * @param cursor the cursor. * @param columnName the column name. * @return the short value. */ public static short getShort(Cursor cursor, String columnName) { if (cursor == null) { return -1; } return cursor.getShort(cursor.getColumnIndex(columnName)); } /** * Read the long data for the column. * @see android.database.Cursor#getLong(int). * @see android.database.Cursor#getColumnIndex(String). * @param cursor the cursor. * @param columnName the column name. * @return the long value. */ public static long getLong(Cursor cursor, String columnName) { if (cursor == null) { return -1; } return cursor.getLong(cursor.getColumnIndex(columnName)); } /** * Read the double data for the column. * @see android.database.Cursor#getDouble(int). * @see android.database.Cursor#getColumnIndex(String). * @param cursor the cursor. * @param columnName the column name. * @return the double value. */ public static double getDouble(Cursor cursor, String columnName) { if (cursor == null) { return -1; } return cursor.getDouble(cursor.getColumnIndex(columnName)); } /** * Read the float data for the column. * @see android.database.Cursor#getFloat(int). * @see android.database.Cursor#getColumnIndex(String). * @param cursor the cursor. * @param columnName the column name. * @return the float value. */ public static float getFloat(Cursor cursor, String columnName) { if (cursor == null) { return -1; } return cursor.getFloat(cursor.getColumnIndex(columnName)); } /** * Read the blob data for the column. * @see android.database.Cursor#getBlob(int). * @see android.database.Cursor#getColumnIndex(String). * @param cursor the cursor. * @param columnName the column name. * @return the blob value. */ public static byte[] getBlob(Cursor cursor, String columnName) { if (cursor == null) { return null; } return cursor.getBlob(cursor.getColumnIndex(columnName)); } /** * Checks the type of the column. * @see android.database.Cursor#getType(int). * @see android.database.Cursor#getColumnIndex(String). * @param cursor the cursor. * @param columnName the column name. * @return the type of the column. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static int getType(Cursor cursor, String columnName) { if (cursor == null) { return Cursor.FIELD_TYPE_NULL; } return cursor.getType(cursor.getColumnIndex(columnName)); } /** * Checks if the column value is null or not. * @see android.database.Cursor#isNull(int). * @see android.database.Cursor#getColumnIndex(String). * @param cursor the cursor. * @param columnName the column name. * @return true if the column value is null. */ public static boolean isNull(Cursor cursor, String columnName) { return cursor != null && cursor.isNull(cursor.getColumnIndex(columnName)); } }
KeithYokoma/Amalgam
amalgam/src/main/java/com/amalgam/database/CursorUtils.java
Java
apache-2.0
5,998
# -*- coding: utf-8 -*- # # Copyright 2013 - Mirantis, 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. from pecan import rest from pecan import expose from pecan import request from mistral.openstack.common import log as logging from mistral.db import api as db_api from mistral.services import scheduler LOG = logging.getLogger(__name__) class WorkbookDefinitionController(rest.RestController): @expose() def get(self, workbook_name): LOG.debug("Fetch workbook definition [workbook_name=%s]" % workbook_name) return db_api.workbook_definition_get(workbook_name) @expose(content_type="text/plain") def put(self, workbook_name): text = request.text LOG.debug("Update workbook definition [workbook_name=%s, text=%s]" % (workbook_name, text)) wb = db_api.workbook_definition_put(workbook_name, text) scheduler.create_associated_triggers(wb) return wb['definition']
TimurNurlygayanov/mistral
mistral/api/controllers/v1/workbook_definition.py
Python
apache-2.0
1,511
require 'spec_helper' require 'pureftpd_helper' describe 'PureFTPd' do include_examples 'PureFTPd', 'postgresql' end
Aigeruth/pure-ftpd
test/integration/backend-postgresql/serverspec/default_spec.rb
Ruby
apache-2.0
120
// Copyright(C) David W. Jeske, 2013 // Released to the public domain. Use, modify and relicense at will. using System; using System.Threading; using System.Globalization; using System.Drawing; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTK.Audio; using OpenTK.Audio.OpenAL; using OpenTK.Input; using SimpleScene; using SimpleScene.Demos; namespace TestBench1 { partial class TestBench1 : TestBenchBootstrap { protected SSPolarJoint renderMesh5NeckJoint = null; protected SSAnimationStateMachineSkeletalController renderMesh4AttackSm = null; protected SSAnimationStateMachineSkeletalController renderMesh5AttackSm = null; protected SSSimpleObjectTrackingJoint tracker0; protected SSSimpleObjectTrackingJoint tracker4; /// <summary> /// The main entry point for the application. /// </summary> static void Main() { // The 'using' idiom guarantees proper resource cleanup. // We request 30 UpdateFrame events per second, and unlimited // RenderFrame events (as fast as the computer can handle). using (TestBench1 game = new TestBench1()) { game.Run(30.0); } } /// <summary>Creates a 800x600 window with the specified title.</summary> public TestBench1() : base("TestBench1") { } /// <summary> /// Called when it is time to setup the next frame. Add you game logic here. /// </summary> /// <param name="e">Contains timing information for framerate independent logic.</param> protected override void OnUpdateFrame(FrameEventArgs e) { base.OnUpdateFrame(e); if (renderMesh5NeckJoint != null) { renderMesh5NeckJoint.theta.value += (float)Math.PI / 2f * (float)e.Time; } } } }
RealRui/SimpleScene
Demos/TestBench1/TestBench1.cs
C#
apache-2.0
1,698
from trex_astf_lib.api import * # IPV6 tunable example # # ipv6.src_msb # ipv6.dst_msb # ipv6.enable # class Prof1(): def __init__(self): pass def get_profile(self, **kwargs): # ip generator ip_gen_c = ASTFIPGenDist(ip_range=["16.0.0.0", "16.0.0.255"], distribution="seq") ip_gen_s = ASTFIPGenDist(ip_range=["48.0.0.0", "48.0.255.255"], distribution="seq") ip_gen = ASTFIPGen(glob=ASTFIPGenGlobal(ip_offset="1.0.0.0"), dist_client=ip_gen_c, dist_server=ip_gen_s) c_glob_info = ASTFGlobalInfo() c_glob_info.tcp.rxbufsize = 8*1024 c_glob_info.tcp.txbufsize = 8*1024 s_glob_info = ASTFGlobalInfo() s_glob_info.tcp.rxbufsize = 8*1024 s_glob_info.tcp.txbufsize = 8*1024 return ASTFProfile(default_ip_gen=ip_gen, # Defaults affects all files default_c_glob_info=c_glob_info, default_s_glob_info=s_glob_info, cap_list=[ ASTFCapInfo(file="../avl/delay_10_http_browsing_0.pcap", cps=1) ] ) def register(): return Prof1()
kisel/trex-core
scripts/astf/param_tcp_rxbufsize_8k.py
Python
apache-2.0
1,298
declare module ioc { /** * A base class for applications using an IOC Container */ abstract class ApplicationContext implements IApplicationContext { /** * A base class for applications using an IOC Container * @param appName The name of your application */ constructor(appName: string); /** * A handle to access the ApplicationContext from anywhere in the application */ static applicationContext: IApplicationContext; /** * A method to override where you register your intances into the IOC Container * @param container The IOC container created for this ApplicationContext * @returns {} */ register(container: Container): void; } } declare module ioc { /** * The IOC Container */ class Container { private static container; private registeredInstances; private registeredScripts; private appName; /** * The IOC Container * @param appName The name of your application * @param baseNamespace */ constructor(appName: string); /** * Get the currently assigned IOC Container */ static getCurrent(): Container; /** * Get the name of the ApplicationContext this IOC container is made from */ getAppName(): string; /** * Register an instance type * @param type The full namespace of the type you want to instantiate */ register<T>(type: Function): InstanceRegistry<T>; /** * Resolve the registered Instance * @param type The full namespace of the type you want to resolve */ resolve<T>(type: Function): T; } } declare module ioc { /** * A helper class for aquiring animation methods */ class AnimationHelper { /** * Get the animationframe * @param callback Function to call on AnimationFrame */ static getAnimationFrame(callback: FrameRequestCallback): number; /** * Cancel an animationFrameEvent * @param requestId The handle of the event you want to cancel */ static cancelAnimationFrame(requestId: number): void; } } declare module ioc { interface IApplicationContext { /** * A method to override where you register your intances into the IOC Container * @param container The IOC container created for this ApplicationContext * @returns {} */ register(container: Container): void; } } declare module ioc { /** * A base class for libraries using an IOC Container * This is used to provide an easy way to register all the libraries components */ abstract class LibraryContext { /** * A method to override where you register your intances into the IOC Container * @param container The IOC container created for the ApplicationContext of the using app * @returns {} */ static register(container: Container): void; } } declare module ioc { interface IRegistryBase<T> { /** * Set the type of this Registry * @param type The full type of the Instance you want to register * @returns {} */ setType(type: Function): IRegistryBase<T>; /** * Return the Instance * @returns {} */ getInstance(): T; /** * Get the type of this Registry * @returns {} */ getType(): Function; /** * Set a function fo modify Instance that will be called directly after instantiating * @param resolve The function to call when resolving * @returns {} */ setResolveFunc(resolve: (instance: T) => T): IRegistryBase<T>; /** * Set a function to resolve the object in a different way than a parameterless constructor * @param instantiate The function used to Instantiate the object * @returns {} */ setInstantiateFunc(instantiate: () => T): IRegistryBase<T>; /** * Apply a lifetimescope to this Registry * @param lifetime The lifetimescope to apply to */ setLifetimeScope(lifetime: LifetimeScope): IRegistryBase<T>; } } declare module ioc { /** * Registry for standard Instances */ class InstanceRegistry<T> extends RegistryBase<T> { protected lifeTimeScope: LifetimeScope; protected callers: { [key: string]: any; }; /** * Return the Instance * @returns {} */ getInstance(): T; /** * Instantiate the object */ protected instantiate(): void; /** * Apply a lifetimescope to this Registry * @param lifetime The lifetimescope to apply to */ setLifetimeScope(lifetime: LifetimeScope): IRegistryBase<T>; } } declare module ioc { /** * The available lifetime scopes */ enum LifetimeScope { /** * Resolve everytime the Resolve is called */ PerResolveCall = 0, /** * Allow only one Instance of this type */ SingleInstance = 1, /** * Return only one Instance for every dependency */ PerDependency = 2, } } declare module ioc { /** * A base class to provide basic functionality for al Registries */ class RegistryBase<T> implements IRegistryBase<T> { protected type: Function; protected object: any; protected initiated: boolean; protected loaded: boolean; protected resolveFunc: (instance: T) => any; protected instantiateFunc: () => T; /** * Return the Instance * @returns {} */ getInstance(): T; /** * Get the type of this Registry * @returns {} */ getType(): Function; /** * Set the type of this Registry * @param type The full type of the Instance you want to register * @returns {} */ setType(type: Function | T): IRegistryBase<T>; /** * Method to override that Instantiates the object */ protected instantiate(): void; /** * Set a function fo modify Instance that will be called directly after instantiating * @param resolve The function to call when resolving * @returns {} */ setResolveFunc(resolve: (instance: T) => T): IRegistryBase<T>; /** * Set a function to resolve the object in a different way than a parameterless constructor * @param instantiate The function used to Instantiate the object * @returns {} */ setInstantiateFunc(instantiate: () => T): IRegistryBase<T>; /** * Apply a lifetimescope to this Registry * @param lifetime The lifetimescope to apply to */ setLifetimeScope(lifetime: LifetimeScope): IRegistryBase<T>; } } //# sourceMappingURL=SIOCC-TS.d.ts.map
Marvin-Brouwer/QR-Redirect
Source/QR-Reader/Scripts/typings/SIOCC-TS.d.ts
TypeScript
apache-2.0
7,284
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * 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.kuali.kra.irb; import org.kuali.kra.irb.actions.submit.ProtocolSubmission; import org.kuali.kra.irb.personnel.ProtocolPerson; import org.kuali.kra.irb.personnel.ProtocolUnit; import org.kuali.kra.irb.protocol.funding.ProtocolFundingSource; import org.kuali.kra.irb.protocol.location.ProtocolLocation; import org.kuali.kra.irb.protocol.research.ProtocolResearchArea; import org.kuali.kra.protocol.CriteriaFieldHelper; import org.kuali.kra.protocol.ProtocolBase; import org.kuali.kra.protocol.ProtocolDaoOjbBase; import org.kuali.kra.protocol.ProtocolLookupConstants; import org.kuali.kra.protocol.actions.ProtocolActionBase; import org.kuali.kra.protocol.actions.submit.ProtocolSubmissionBase; import org.kuali.kra.protocol.personnel.ProtocolPersonBase; import org.kuali.kra.protocol.personnel.ProtocolUnitBase; import org.kuali.rice.krad.service.util.OjbCollectionAware; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * * This class is the implementation for ProtocolDao interface. */ class ProtocolDaoOjb extends ProtocolDaoOjbBase<Protocol> implements OjbCollectionAware, ProtocolDao { /** * The APPROVED_SUBMISSION_STATUS_CODE contains the status code of approved protocol submissions (i.e. 203). */ private static final Collection<String> APPROVED_SUBMISSION_STATUS_CODES = Arrays.asList(new String[] {"203"}); /** * The ACTIVE_PROTOCOL_STATUS_CODES contains the various active status codes for a protocol. * <li> 200 - Active, open to enrollment * <li> 201 - Active, closed to enrollment * <li> 202 - Active, data analysis only */ private static final Collection<String> ACTIVE_PROTOCOL_STATUS_CODES = Arrays.asList(new String[] {"200", "201", "202"}); /** * The REVISION_REQUESTED_PROTOCOL_ACTION_TYPE_CODES contains the protocol action codes for the protocol revision requests. * <li> 202 - Specific Minor Revision * <li> 203 - Substantive Revision Requested */ private static final Collection<String> REVISION_REQUESTED_PROTOCOL_ACTION_TYPE_CODES = Arrays.asList(new String[] {"202", "203"}); /** * The REVISION_REQUESTED_PROTOCOL_STATUS_CODES contains the various status codes for protocol revision requests. * <li> 102 - Specific Minor Revision * <li> 104 - Substantive Revision Requested */ private static final Collection<String> REVISION_REQUESTED_PROTOCOL_STATUS_CODES = Arrays.asList(new String[] {"102", "104"}); private static final Collection<String> PENDING_AMENDMENT_RENEWALS_STATUS_CODES = Arrays.asList(new String[]{"100", "101", "102", "103", "104", "105", "106"}); @Override protected Collection<String> getApprovedSubmissionStatusCodesHook() { return APPROVED_SUBMISSION_STATUS_CODES; } @Override protected Collection<String> getActiveProtocolStatusCodesHook() { return ACTIVE_PROTOCOL_STATUS_CODES; } @Override protected Collection<String> getRevisionRequestedProtocolActionTypeCodesHook() { return REVISION_REQUESTED_PROTOCOL_ACTION_TYPE_CODES; } @Override protected Collection<String> getRevisionRequestedProtocolStatusCodesHook() { return REVISION_REQUESTED_PROTOCOL_STATUS_CODES; } @Override protected Class<? extends ProtocolActionBase> getProtocolActionBOClassHoook() { return org.kuali.kra.irb.actions.ProtocolAction.class; } @Override protected void initRoleListsHook(List<String> investigatorRoles, List<String> personRoles) { investigatorRoles.add("PI"); investigatorRoles.add("COI"); personRoles.add("SP"); personRoles.add("CA"); personRoles.add("CRC"); } @Override protected Collection<String> getPendingAmendmentRenewalsProtocolStatusCodesHook() { return PENDING_AMENDMENT_RENEWALS_STATUS_CODES; } @Override protected Class<? extends ProtocolBase> getProtocolBOClassHook() { return Protocol.class; } @Override protected Class<? extends ProtocolPersonBase> getProtocolPersonBOClassHook() { return ProtocolPerson.class; } @Override protected Class<? extends ProtocolUnitBase> getProtocolUnitBOClassHook() { return ProtocolUnit.class; } @Override protected Class<? extends ProtocolSubmissionBase> getProtocolSubmissionBOClassHook() { return ProtocolSubmission.class; } @Override protected List<CriteriaFieldHelper> getCriteriaFields() { List<CriteriaFieldHelper> criteriaFields = new ArrayList<CriteriaFieldHelper>(); criteriaFields.add(new CriteriaFieldHelper(ProtocolLookupConstants.Property.KEY_PERSON, ProtocolLookupConstants.Property.PERSON_NAME, ProtocolPerson.class)); criteriaFields.add(new CriteriaFieldHelper(ProtocolLookupConstants.Property.INVESTIGATOR, ProtocolLookupConstants.Property.PERSON_NAME, ProtocolPerson.class)); criteriaFields.add(new CriteriaFieldHelper(ProtocolLookupConstants.Property.FUNDING_SOURCE, ProtocolLookupConstants.Property.FUNDING_SOURCE_NUMBER, ProtocolFundingSource.class)); criteriaFields.add(new CriteriaFieldHelper(ProtocolLookupConstants.Property.PERFORMING_ORGANIZATION_ID, ProtocolLookupConstants.Property.ORGANIZATION_ID, ProtocolLocation.class)); criteriaFields.add(new CriteriaFieldHelper(ProtocolLookupConstants.Property.RESEARCH_AREA_CODE, ProtocolLookupConstants.Property.RESEARCH_AREA_CODE, ProtocolResearchArea.class)); return criteriaFields; } }
vivantech/kc_fixes
src/main/java/org/kuali/kra/irb/ProtocolDaoOjb.java
Java
apache-2.0
6,383
/** * Copyright (c) 2005-20010 springside.org.cn * * Licensed under the Apache License, Version 2.0 (the "License"); * * $Id: PropertyFilter.java 1205 2010-09-09 15:12:17Z calvinxiu $ */ package com.snakerflow.framework.orm; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import com.snakerflow.framework.utils.ConvertUtils; import com.snakerflow.framework.utils.ServletUtils; import org.springframework.util.Assert; /** * 与具体ORM实现无关的属性过滤条件封装类, 主要记录页面中简单的搜索过滤条件. * * @author calvin */ public class PropertyFilter { /** 多个属性间OR关系的分隔符. */ public static final String OR_SEPARATOR = "_OR_"; /** 属性比较类型. */ public enum MatchType { EQ, LIKE, LT, GT, LE, GE; } /** 属性数据类型. */ public enum PropertyType { S(String.class), I(Integer.class), L(Long.class), N(Double.class), D(Date.class), B(Boolean.class); private Class<?> clazz; private PropertyType(Class<?> clazz) { this.clazz = clazz; } public Class<?> getValue() { return clazz; } } private MatchType matchType = null; private Object matchValue = null; private Class<?> propertyClass = null; private String[] propertyNames = null; public PropertyFilter() { } /** * @param filterName 比较属性字符串,含待比较的比较类型、属性值类型及属性列表. * eg. LIKES_NAME_OR_LOGIN_NAME * @param value 待比较的值. */ public PropertyFilter(final String filterName, final String value) { String firstPart = StringUtils.substringBefore(filterName, "_"); String matchTypeCode = StringUtils.substring(firstPart, 0, firstPart.length() - 1); String propertyTypeCode = StringUtils.substring(firstPart, firstPart.length() - 1, firstPart.length()); try { matchType = Enum.valueOf(MatchType.class, matchTypeCode); } catch (RuntimeException e) { throw new IllegalArgumentException("filter名称" + filterName + "没有按规则编写,无法得到属性比较类型.", e); } try { propertyClass = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue(); } catch (RuntimeException e) { throw new IllegalArgumentException("filter名称" + filterName + "没有按规则编写,无法得到属性值类型.", e); } String propertyNameStr = StringUtils.substringAfter(filterName, "_"); Assert.isTrue(StringUtils.isNotBlank(propertyNameStr), "filter名称" + filterName + "没有按规则编写,无法得到属性名称."); propertyNames = StringUtils.splitByWholeSeparator(propertyNameStr, PropertyFilter.OR_SEPARATOR); this.matchValue = ConvertUtils.convertStringToObject(value, propertyClass); } /** * 从HttpRequest中创建PropertyFilter列表, 默认Filter属性名前缀为filter. * * @see #buildFromHttpRequest(HttpServletRequest, String) */ public static List<PropertyFilter> buildFromHttpRequest(final HttpServletRequest request) { return buildFromHttpRequest(request, "filter"); } /** * 从HttpRequest中创建PropertyFilter列表 * PropertyFilter命名规则为Filter属性前缀_比较类型属性类型_属性名. * * eg. * filter_EQS_name * filter_LIKES_name_OR_email */ public static List<PropertyFilter> buildFromHttpRequest(final HttpServletRequest request, final String filterPrefix) { List<PropertyFilter> filterList = new ArrayList<PropertyFilter>(); //从request中获取含属性前缀名的参数,构造去除前缀名后的参数Map. Map<String, Object> filterParamMap = ServletUtils.getParametersStartingWith(request, filterPrefix + "_"); //分析参数Map,构造PropertyFilter列表 for (Map.Entry<String, Object> entry : filterParamMap.entrySet()) { String filterName = entry.getKey(); String value = (String) entry.getValue(); //如果value值为空,则忽略此filter. if (StringUtils.isNotBlank(value)) { PropertyFilter filter = new PropertyFilter(filterName, value); filterList.add(filter); } } return filterList; } /** * 获取比较值的类型. */ public Class<?> getPropertyClass() { return propertyClass; } /** * 获取比较方式. */ public MatchType getMatchType() { return matchType; } /** * 获取比较值. */ public Object getMatchValue() { return matchValue; } /** * 获取比较属性名称列表. */ public String[] getPropertyNames() { return propertyNames; } /** * 获取唯一的比较属性名称. */ public String getPropertyName() { Assert.isTrue(propertyNames.length == 1, "There are not only one property in this filter."); return propertyNames[0]; } /** * 是否比较多个属性. */ public boolean hasMultiProperties() { return (propertyNames.length > 1); } }
snakerflow/snaker-web
src/main/java/com/snakerflow/framework/orm/PropertyFilter.java
Java
apache-2.0
4,884
/* * Copyright 2019 MovingBlocks * * 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.terasology.gestalt.module.exceptions; /** * Exception for when metadata cannot be resolved for a module */ public class MissingModuleMetadataException extends RuntimeException { public MissingModuleMetadataException() { } public MissingModuleMetadataException(String s) { super(s); } public MissingModuleMetadataException(String s, Throwable throwable) { super(s, throwable); } }
immortius/gestalt
gestalt-module/src/main/java/org/terasology/gestalt/module/exceptions/MissingModuleMetadataException.java
Java
apache-2.0
1,036
#pragma once #ifndef UTIL_LOGGER_HPP #define UTIL_LOGGER_HPP #include <gsl/span> #include <string> #include <iterator> #include <vector> #include <cstdlib> /** * @brief A utility which logs a limited amount of entries * @details Logs strings inside a ringbuffer. * * If the buffer is full, the oldest entry will be overwritten. * */ class Logger { public: using Log = gsl::span<char>; public: Logger(Log& log, Log::index_type = 0); /** * @brief Log a string * @details * Write the string to the buffer a zero at the end to indicate end of string. * * If the string overlaps another string, it will clear the remaining string with zeros. * * @param str Message to be logged */ void log(const std::string& str); /** * @brief Retreive all entries from the log * @details Iterates forward over the whole buffer, building strings on the way * * Order old => new * * @return a vector with all the log entries */ std::vector<std::string> entries() const; /** * @brief Retreive entries N from the log * @details * Retrieves N (or less) latest entries from the log, * starting with the oldest. * * * @param n maximum number of entries * @return a vector with entries */ std::vector<std::string> entries(size_t n) const; /** * @brief Clear the log * @details Sets every byte to 0 and set position to start at the beginning. */ void flush(); /** * @brief Size of the log in bytes. * @details Assumes every byte is filled with either data or 0 * @return size in bytes */ auto size() const { return log_.size(); } private: /** The underlaying log */ Log& log_; /** * @brief A "circular" iterator, operating on a Logger::Log * @details Wraps around everytime it reaches the end */ class iterator : public Log::iterator { public: using base = Log::iterator; // inherit constructors using base::base; constexpr iterator& operator++() noexcept { //Expects(span_ && index_ >= 0); index_ = (index_ < span_->size()-1) ? index_+1 : 0; return *this; } constexpr iterator& operator--() noexcept { //Expects(span_ && index_ < span_->size()); index_ = (index_ > 0) ? index_-1 : span_->size()-1; return *this; } constexpr iterator& operator+=(difference_type n) noexcept { //Expects(span_); index_ = (index_ + n < span_->size()) ? index_ + n : std::abs((n - ((span_->size()) - index_)) % span_->size()); return *this; } constexpr span_iterator& operator-=(difference_type n) noexcept { // No use case for this (yet) return *this += -n; } }; // < class Logger::iterator /** Current position in the log */ iterator pos_; }; // << class Logger #endif
hioa-cs/IncludeOS
api/util/logger.hpp
C++
apache-2.0
2,818
<?php namespace Scalr\Service\CloudStack\Services\Vpn\DataType; use Scalr\Service\CloudStack\DataType\AbstractDataType; /** * AddVpnUserData * * @author Vlad Dobrovolskiy <v.dobrovolskiy@scalr.com> * @since 4.5.2 */ class AddVpnUserData extends AbstractDataType { /** * Required * Password for the username * * @var string */ public $password; /** * Required * Username for the vpn user * * @var string */ public $username; /** * An optional account for the vpn user. * Must be used with domainId. * * @var string */ public $account; /** * An optional domainId for the vpn user. * If the account parameter is used, domainId must also be used. * * @var string */ public $domainid; /** * Add vpn user to the specific project * * @var string */ public $projectid; /** * Constructor * * @param string $password Password for the username * @param string $username Username for the vpn user */ public function __construct($password, $username) { $this->password = $password; $this->username = $username; } }
kikov79/scalr
app/src/Scalr/Service/CloudStack/Services/Vpn/DataType/AddVpnUserData.php
PHP
apache-2.0
1,253
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro; /** Thrown for errors building schemas. */ public class SchemaBuilderException extends AvroRuntimeException { public SchemaBuilderException(Throwable cause) { super(cause); } public SchemaBuilderException(String message) { super(message); } }
apache/avro
lang/java/avro/src/main/java/org/apache/avro/SchemaBuilderException.java
Java
apache-2.0
1,094
/** * @projectDescription The SDX controller library for the PatientRecordSet data-type. * @namespace i2b2.sdx.TypeControllers.ENS * @inherits i2b2.sdx.TypeControllers * @author Mike Mendis * @version 1.6 * @see i2b2.sdx * ---------------------------------------------------------------------------------------- */ console.group('Load & Execute component file: CRC > SDX > Encounter Record Set'); console.time('execute time'); i2b2.sdx.TypeControllers.ENS = {}; i2b2.sdx.TypeControllers.ENS.model = {}; // ********************************************************************************* // ENCAPSULATE DATA // ********************************************************************************* i2b2.sdx.TypeControllers.ENS.getEncapsulateInfo = function() { // this function returns the encapsulation head information return {sdxType: 'ENS', sdxKeyName: 'result_instance_id', sdxControlCell:'CRC', sdxDisplayNameKey: 'title'}; } i2b2.sdx.TypeControllers.ENS.SaveToDataModel = function(sdxData, sdxParentNode) { // save to CRC data model if (!sdxParentNode) { return false; } var qm_id = sdxData.sdxInfo.sdxKeyValue; var qm_hash = i2b2.sdx.Master._KeyHash(qm_id); // class for all SDX communications function i2b2_SDX_Encapsulation_EXTENDED() {} // create an instance and populate with info var t = new i2b2_SDX_Encapsulation_EXTENDED(); t.origData = Object.clone(sdxData.origData); t.sdxInfo = Object.clone(sdxData.sdxInfo); t.parent = sdxParentNode; t.children = new Hash(); t.children.loaded = false; // add to hash sdxParentNode.children.set(qm_hash, t); // TODO: send data update signal (use JOINING-MUTEX or AGGREGATING-MUTEX to avoid rapid fire of event!) return t; } i2b2.sdx.TypeControllers.ENS.LoadFromDataModel = function(key_value) {} i2b2.sdx.TypeControllers.ENS.ClearAllFromDataModel= function(sdxOptionalParent) { if (sdxOptionalParent) { try { var findFunc = function(item_rec) { // this function expects the second argument to be the target node's key value var hash_key = item_rec[0]; var QM_rec = item_rec[1]; if (QM_rec.sdxInfo.sdxKeyValue == this.strip()) { return true; } } var dm_loc = 'i2b2.CRC.model.QueryMasters.'+i2b2.sdx.Master._KeyHash(sdxOptionalParent.sdxInfo.sdxKeyValue); var targets = i2b2.CRC.model.QueryMasters.findAll(findFunc, sdxOptionalParent.sdxInfo.sdxKeyValue); for (var i=0; i < targets.length; i++) { var t = parent_QM[i].value; t.children = new Hash(); } } catch(e) { console.error('Could not clear children of given parent node!'); } } else { var dm_loc = 'i2b2.CRC.model.QueryMasters'; i2b2.CRC.model.QueryMasters.each(function(item_rec) { try { item_rec[1].children = new Hash(); } catch(e) { console.error('Could not clear children of all QueryMasters'); } }); } // TODO: send data update signal (use JOINING-MUTEX or AGGREGATING-MUTEX to avoid rapid fire of event!) // updated dm_loc of the data model return true; } // ********************************************************************************* // GENERATE HTML (DEFAULT HANDLER) // ********************************************************************************* i2b2.sdx.TypeControllers.ENS.RenderHTML= function(sdxData, options, targetDiv) { // OPTIONS: // title: string // showchildren: true | false // cssClass: string // icon: [data object] // icon: (filename of img, appended to i2b2_root+cellDir + '/assets') // iconExp: (filename of img, appended to i2b2_root+cellDir + '/assets') // dragdrop: string (function name) // context: string // click: string // dblclick: string if (Object.isUndefined(options)) { options = {}; } var render = {html: retHtml, htmlID: id}; var conceptId = sdxData.name; var id = "CRC_ID-" + i2b2.GUID(); // process drag drop controllers if (!Object.isUndefined(options.dragdrop)) { // NOTE TO SELF: should attachment of node dragdrop controller be handled by the SDX system as well? // This would ensure removal of the onmouseover call in a cross-browser way var sDD = ' onmouseover="' + options.dragdrop + '(\''+ targetDiv.id +'\',\'' + id + '\')" '; } else { var sDD = ''; } if (Object.isUndefined(options.cssClass)) { options.cssClass = 'sdxDefaultPRS';} // user can override bCanExp = true; if (Object.isBoolean(options.showchildren)) { bCanExp = options.showchildren; } render.canExpand = bCanExp; render.iconType = "PRS"; if (!Object.isUndefined(options.icon)) { render.icon = i2b2.hive.cfg.urlFramework + 'cells/CRC/assets/'+ options.icon } if (!Object.isUndefined(options.iconExp)) { render.iconExp = i2b2.hive.cfg.urlFramework + 'cells/CRC/assets/'+ options.iconExp } // in cases of one set icon, copy valid icon to the missing icon if (Object.isUndefined(render.icon) && !Object.isUndefined(render.iconExp)) { render.icon = render.iconExp; } if (!Object.isUndefined(render.icon) && Object.isUndefined(render.iconExp)) { render.iconExp = render.icon; } // handle the event controllers var sMainEvents = sDD; var sImgEvents = sDD; // **** Render the HTML *** var retHtml = '<DIV id="' + id + '" ' + sMainEvents + ' style="white-space:nowrap;cursor:pointer;">'; retHtml += '<DIV '; if (Object.isString(options.cssClass)) { retHtml += ' class="'+options.cssClass+'" '; } else { retHtml += ' class= "sdxDefaultPRS" '; } retHtml += sImgEvents; retHtml += '>'; retHtml += '<IMG src="'+render.icon+'"/> '; if (!Object.isUndefined(options.title)) { retHtml += options.title; } else { console.warn('[SDX RenderHTML] no title was given in the creation options for an CRC > ENS node!'); retHtml += ' PRS '+id; } retHtml += '</DIV></DIV>'; render.html = retHtml; render.htmlID = id; var retObj = {}; Object.extend(retObj, sdxData); retObj.renderData = render; return retObj; } // ********************************************************************************* // HANDLE HOVER OVER TARGET ENTRY (DEFAULT HANDLER) // ********************************************************************************* i2b2.sdx.TypeControllers.ENS.onHoverOver = function(e, id, ddProxy) { var el = $(id); if (el) { Element.addClassName(el,'ddPRSTarget'); } } // ********************************************************************************* // HANDLE HOVER OVER TARGET EXIT (DEFAULT HANDLER) // ********************************************************************************* i2b2.sdx.TypeControllers.ENS.onHoverOut = function(e, id, ddProxy) { var el = $(id); if (el) { Element.removeClassName(el,'ddPRSTarget'); } } // ********************************************************************************* // ADD DATA TO TREENODE (DEFAULT HANDLER) // ********************************************************************************* i2b2.sdx.TypeControllers.ENS.AppendTreeNode = function(yuiTree, yuiRootNode, sdxDataPack, callbackLoader) { var myobj = { html: sdxDataPack.renderData.html, nodeid: sdxDataPack.renderData.htmlID} var tmpNode = new YAHOO.widget.HTMLNode(myobj, yuiRootNode, false, true); if (sdxDataPack.renderData.canExpand && !Object.isUndefined(callbackLoader)) { // add the callback to load child nodes sdxDataPack.sdxInfo.sdxLoadChildren = callbackLoader; } tmpNode.data.i2b2_SDX= sdxDataPack; tmpNode.toggle = function() { if (!this.tree.locked && ( this.hasChildren(true) ) ) { var data = this.data.i2b2_SDX.renderData; var img = this.getContentEl(); img = Element.select(img,'img')[0]; if (this.expanded) { img.src = data.icon; this.collapse(); } else { img.src = data.iconExp; this.expand(); } } }; if (!sdxDataPack.renderData.canExpand) { tmpNode.dynamicLoadComplete = true; } return tmpNode; } // ********************************************************************************* // ATTACH DRAG TO DATA (DEFAULT HANDLER) // ********************************************************************************* i2b2.sdx.TypeControllers.ENS.AttachDrag2Data = function(divParentID, divDataID){ if (Object.isUndefined($(divDataID))) { return false; } // get the i2b2 data from the yuiTree node var tvTree = YAHOO.widget.TreeView.getTree(divParentID); var tvNode = tvTree.getNodeByProperty('nodeid', divDataID); if (!Object.isUndefined(tvNode.DDProxy)) { return true; } // attach DD var t = new i2b2.sdx.TypeControllers.ENS.DragDrop(divDataID) t.yuiTree = tvTree; t.yuiTreeNode = tvNode; tvNode.DDProxy = t; // clear the mouseover attachment function var tdn = $(divDataID); if (!Object.isUndefined(tdn.onmouseover)) { try { delete tdn.onmouseover; } catch(e) { tdn.onmouseover; } } if (!Object.isUndefined(tdn.attributes)) { for (var i=0;i<tdn.attributes.length; i++) { if (tdn.attributes[i].name=="onmouseover") { try { delete tdn.onmouseover; } catch(e) { tdn.onmouseover; } } } } } /** * Get the child records for the given PatientRecordSet. * @param {Object} sdxParentNode The parent node we want to find the children of. * @param {ScopedCallback} onCompleteCallback A scoped-callback function to be executed using the results array. * @return {Boolean} Returns true to the calling function. * @return {Array} Returns an array of PatientRecord data represented as SDX Objects (without render data) to the callback function passed. * @memberOf i2b2.sdx.TypeControllers.QI * @method * @author Nick Benik * @version 1.0 * @alias i2b2.sdx.Master.getChildRecords */ i2b2.sdx.TypeControllers.ENS.getChildRecords = function(sdxParentNode, onCompleteCallback, options) { var scopedCallback = new i2b2_scopedCallback(); scopedCallback.scope = sdxParentNode; scopedCallback.callback = function(results) { var cl_node = sdxParentNode; var cl_onCompleteCB = onCompleteCallback; // THIS function is used to process the AJAX results of the getChild call // results data object contains the following attributes: // refXML: xmlDomObject <--- for data processing // msgRequest: xml (string) // msgResponse: xml (string) // error: boolean // errorStatus: string [only with error=true] // errorMsg: string [only with error=true] var retMsg = { error: results.error, msgRequest: results.msgRequest, msgResponse: results.msgResponse, msgUrl: results.msgUrl, results: null }; var retChildren = []; // extract records from XML msg var ps = results.refXML.getElementsByTagName('event'); var dm = i2b2.CRC.model.QueryMasters; for(var i1=0; i1<ps.length; i1++) { var o = new Object; o.xmlOrig = ps[i1]; o.patient_id = i2b2.h.getXNodeVal(ps[i1],'patient_id'); o.event_id = i2b2.h.getXNodeVal(ps[i1],'event_id'); //o.vital_status = i2b2.h.XPath(ps[i1],'param[@name="vital_status_cd"]/text()')[0].nodeValue; //o.age = i2b2.h.XPath(ps[i1],'param[@name="age_in_years_num"]/text()')[0].nodeValue; //o.sex = i2b2.h.XPath(ps[i1],'param[@name="sex_cd"]/text()')[0].nodeValue; //o.race = i2b2.h.XPath(ps[i1],'param[@name="race_cd"]/text()')[0].nodeValue; //o.title = o.patient_id+" ["+o.age+" y/o "+ o.sex+" "+o.race+"]"; var sdxDataNode = i2b2.sdx.Master.EncapsulateData('PR',o); // save record in the SDX system sdxDataNode = i2b2.sdx.Master.Save(sdxDataNode, cl_node); // append the data node to our returned results retChildren.push(sdxDataNode); } cl_node.children.loaded = true; // TODO: broadcast a data update event of the CRC data model retMsg.results = retChildren; if (getObjectClass(cl_onCompleteCB)=='i2b2_scopedCallback') { cl_onCompleteCB.callback.call(cl_onCompleteCB.scope, retMsg); } else { cl_onCompleteCB(retMsg); } } var msg_filter = '<input_list>\n' + ' <event_list max="1000000" min="0">\n'+ ' <patient_event_coll_id>'+sdxParentNode.sdxInfo.sdxKeyValue+'</patient_event_coll_id>\n'+ ' </event_list>\n'+ '</input_list>\n'+ '<filter_list/>\n'+ '<output_option>\n'+ ' <event_set select="using_input_list" onlykeys="true"/>\n'+ '</output_option>\n'; // AJAX CALL var options = { patient_limit: 0, PDO_Request: msg_filter }; i2b2.CRC.ajax.getPDO_fromInputList("CRC:SDX:PatientRecordSet", options, scopedCallback); } i2b2.sdx.TypeControllers.ENS.LoadChildrenFromTreeview = function(node, onCompleteCallback) { var scopedCallback = new i2b2_scopedCallback(); scopedCallback.scope = node.data.i2b2_SDX; scopedCallback.callback = function(retCellPack) { var cl_node = node; var cl_onCompleteCB = onCompleteCallback; var results = retCellPack.results; for(var i1=0; i1<1*results.length; i1++) { var o = results[i1]; var renderOptions = { dragdrop: "i2b2.sdx.TypeControllers.PRC.AttachDrag2Data", icon: "sdx_CRC_PR.jpg", title: o.sdxInfo.sdxDisplayName, showchildren: false }; var sdxRenderData = i2b2.sdx.Master.RenderHTML(cl_node.tree.id, o, renderOptions); i2b2.sdx.Master.AppendTreeNode(cl_node.tree, cl_node, sdxRenderData); } // handle the callback if (getObjectClass(cl_onCompleteCB)=='i2b2_scopedCallback') { cl_onCompleteCB.callback.call(cl_onCompleteCB.scope, retCellPack); } else { cl_onCompleteCB(retCellPack); } } var sdxParentNode = node.data.i2b2_SDX; var options = i2b2.CRC.params; i2b2.sdx.Master.getChildRecords(sdxParentNode, scopedCallback, options); } // ********************************************************************************* // DRAG DROP PROXY CONTROLLER // ********************************************************************************* i2b2.sdx.TypeControllers.ENS.DragDrop = function(id, config) { if (id) { this.init(id, 'ENS',{isTarget:false}); this.initFrame(); } var s = this.getDragEl().style; s.borderColor = "transparent"; s.opacity = 0.75; s.filter = "alpha(opacity=75)"; s.whiteSpace = "nowrap"; s.overflow = "hidden"; s.textOverflow = "ellipsis"; }; YAHOO.extend(i2b2.sdx.TypeControllers.ENS.DragDrop, YAHOO.util.DDProxy); i2b2.sdx.TypeControllers.ENS.DragDrop.prototype.startDrag = function(x, y) { var dragEl = this.getDragEl(); var clickEl = this.getEl(); dragEl.innerHTML = clickEl.innerHTML; dragEl.className = clickEl.className; dragEl.style.backgroundColor = '#FFFFEE'; dragEl.style.color = clickEl.style.color; dragEl.style.border = "1px solid blue"; dragEl.style.width = "160px"; dragEl.style.height = "20px"; this.setDelta(15,10); }; i2b2.sdx.TypeControllers.ENS.DragDrop.prototype.endDrag = function(e) { // remove DragDrop targeting CCS var targets = YAHOO.util.DDM.getRelated(this, true); for (var i=0; i<targets.length; i++) { var targetEl = targets[i]._domRef; i2b2.sdx.Master.onHoverOut('ENS', e, targetEl, this); } }; i2b2.sdx.TypeControllers.ENS.DragDrop.prototype.alignElWithMouse = function(el, iPageX, iPageY) { var oCoord = this.getTargetCoord(iPageX, iPageY); if (!this.deltaSetXY) { var aCoord = [oCoord.x, oCoord.y]; YAHOO.util.Dom.setXY(el, aCoord); var newLeft = parseInt( YAHOO.util.Dom.getStyle(el, "left"), 10 ); var newTop = parseInt( YAHOO.util.Dom.getStyle(el, "top" ), 10 ); this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ]; } else { var posX = (oCoord.x + this.deltaSetXY[0]); var posY = (oCoord.y + this.deltaSetXY[1]); var scrSize = document.viewport.getDimensions(); var maxX = parseInt(scrSize.width-25-160); var maxY = parseInt(scrSize.height-25); if (posX > maxX) {posX = maxX;} if (posX < 6) {posX = 6;} if (posY > maxY) {posY = maxY;} if (posY < 6) {posY = 6;} YAHOO.util.Dom.setStyle(el, "left", posX + "px"); YAHOO.util.Dom.setStyle(el, "top", posY + "px"); } this.cachePosition(oCoord.x, oCoord.y); this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth); }; i2b2.sdx.TypeControllers.ENS.DragDrop.prototype.onDragOver = function(e, id) { // fire the onHoverOver (use SDX so targets can override default event handler) i2b2.sdx.Master.onHoverOver('ENS', e, id, this); }; i2b2.sdx.TypeControllers.ENS.DragDrop.prototype.onDragOut = function(e, id) { // fire the onHoverOut handler (use SDX so targets can override default event handlers) i2b2.sdx.Master.onHoverOut('ENS', e, id, this); }; i2b2.sdx.TypeControllers.ENS.DragDrop.prototype.onDragDrop = function(e, id) { i2b2.sdx.Master.onHoverOut('ENS', e, id, this); // retreive the concept data from the dragged element draggedData = this.yuiTreeNode.data.i2b2_SDX; i2b2.sdx.Master.ProcessDrop(draggedData, id); }; // ********************************************************************************* // <BLANK> DROP HANDLER // !!!! DO NOT EDIT - ATTACH YOUR OWN CUSTOM ROUTINE USING // !!!! THE i2b2.sdx.Master.setHandlerCustom FUNCTION // ********************************************************************************* i2b2.sdx.TypeControllers.ENS.DropHandler = function(sdxData) { alert('[PatientRecordSet DROPPED] You need to create your own custom drop event handler.'); } console.timeEnd('execute time'); console.groupEnd();
rdalej/i2b2-shibboleth
build/web/webclient/js-i2b2/cells/CRC/CRC_sdx_ENS.js
JavaScript
apache-2.0
17,357
from pony.orm.core import *
buddyli/private2w
libs/pony/orm/__init__.py
Python
apache-2.0
28
package com.mc.phonefinder.usersettings; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.preference.PreferenceManager; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.mc.phonefinder.R; import com.mc.phonefinder.login.FindPhoneActivity; import com.mc.phonefinder.login.SampleApplication; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseGeoPoint; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseUser; import java.io.Serializable; import java.util.List; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; public class FindPhoneInterface extends ActionBarActivity { /* For the below: check if the setting is set for the user and if so let the user use the functionality. View location - Referes to location column in Settings table Show Phone finder image - Displays the image of the person who find the phone View nearby users - Refers to otherUsers in Settings table Alert my phone - Rings the phone to easily identify it */ static final boolean[] nearByUserSetting = new boolean[1]; static final boolean[] locationSetting = new boolean[1]; AtomicBoolean nearByUserSetting_check = new AtomicBoolean(); AtomicBoolean locPrefs_check = new AtomicBoolean(); public static String test = "Class"; static final String TAG="bharathdebug"; public void savePrefs(String key, boolean value) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor edit = sp.edit(); edit.putBoolean(key, value); edit.commit(); } public boolean loadBoolPrefs(String key) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); boolean cbVal = sp.getBoolean(key, false); return cbVal; } public void savePrefs(String key, String value) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor edit = sp.edit(); edit.putString(key, value); edit.commit(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_find_phone_interface); final String ObjectId = (String)this.getIntent().getSerializableExtra("userObjectId"); nearByUserSetting[0] = false; locationSetting[0] = false; savePrefs("nearByUserSetting", false); savePrefs("locationSetting", false); Log.i(TAG,"Before inner class"+test); // final String ObjectId = (String)this.getIntent().getSerializableExtra("userObjectId"); ParseQuery<ParseObject> getSettings = new ParseQuery<ParseObject>("Settings"); getSettings.whereEqualTo("userObjectId", ObjectId); getSettings.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> objects, ParseException e) { if (objects != null) { Log.i(TAG, "Object not null"); if(objects.size()>0){ // nearByUserSetting[0] = objects.get(0).getBoolean("otherUser"); // locationSetting[0] = objects.get(0).getBoolean("location"); // test = "Inner class"; nearByUserSetting_check.set( objects.get(0).getBoolean("otherUser")); locPrefs_check.set(objects.get(0).getBoolean("location")); Log.i(TAG, "Inner class neary by " + String.valueOf(nearByUserSetting_check.get())); Log.i(TAG,"Inner class Location pref "+ (String.valueOf(locPrefs_check.get()))); // // savePrefs("nearByUserSetting", nearByUserSetting[0]); // savePrefs("locationSetting", locationSetting[0]); } } } }); // nearByUserSetting_check=loadBoolPrefs("nearByUserSetting"); // locPrefs_check = loadBoolPrefs("locationSetting"); // // Log.i(TAG,"Final val after inner class "+test); // System.out.print("Camera Setting " + nearByUserSetting[0]); Log.i(TAG,"Near by user "+ (String.valueOf(nearByUserSetting_check.get()))); Log.i(TAG,"Location pref "+ (String.valueOf(locPrefs_check.get()))); ((Button) findViewById(R.id.nearbyUsers)).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(nearByUserSetting_check.get()) { Intent i = new Intent(); savePrefs("findPhoneId", ObjectId); Log.i(TAG, "FindPhoneInterface Object id " + ObjectId); i.setClass(FindPhoneInterface.this, NearbyUserView.class); //i.putExtra("userObjectId", ObjectId); startActivity(i); startActivity(new Intent(FindPhoneInterface.this, NearbyUserView.class)); } else { Toast.makeText(FindPhoneInterface.this, "Find nearby user service not set ", Toast.LENGTH_SHORT).show(); } } }); ((Button) findViewById(R.id.viewLocation)).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(locPrefs_check.get()) { Toast.makeText(FindPhoneInterface.this, "Getting Your Location", Toast.LENGTH_LONG) .show(); String ObjectId = (String) FindPhoneInterface.this.getIntent().getSerializableExtra("userObjectId"); ParseQuery<ParseObject> query = ParseQuery.getQuery("Location"); if (!ObjectId.equals(null) && !ObjectId.equals("")) { query.whereEqualTo("userId", ObjectId); query.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> objects, ParseException e) { ParseGeoPoint userLocation; for (int i = 0; i < objects.size(); i++) { userLocation = objects.get(i).getParseGeoPoint("location"); String uri = String.format(Locale.ENGLISH, "geo:%f,%f?q=%f,%f", userLocation.getLatitude(), userLocation.getLongitude(), userLocation.getLatitude(), userLocation.getLongitude()); //Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:%f,%f?q=%f,%f",userLocation.getLatitude(), userLocation.getLongitude(),userLocation.getLatitude(), userLocation.getLongitude())); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri)); startActivity(intent); Toast.makeText(FindPhoneInterface.this, "Opening Maps", Toast.LENGTH_LONG) .show(); } } }); } } else { Toast.makeText(FindPhoneInterface.this, "Location Preference service not set ", Toast.LENGTH_SHORT).show(); } }}); //Bharath - View image of person who picked phone ((Button) findViewById(R.id.btn_phonepicker)).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Starts an intent of the log in activity Log.i(TAG,"Find face object id "+ObjectId); savePrefs("findfaceObjId",ObjectId); startActivity(new Intent(FindPhoneInterface.this, ShowPhoneFinderImage.class)); } }); //Change ringer alert ((Button) findViewById(R.id.triggerAlert)).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { ParseQuery<ParseObject> query = ParseQuery.getQuery("Settings"); query.whereEqualTo("userObjectId", ObjectId); query.findInBackground(new FindCallback<ParseObject>() { public void done(List<ParseObject> scoreList, ParseException e) { //get current user ParseUser user = ParseUser.getCurrentUser(); if (e == null) { if (scoreList != null) { if (scoreList.size() > 0) { //store the location of the user with the objectId of the user scoreList.get(0).put("alertPhone", true); scoreList.get(0).saveInBackground(); Toast.makeText(FindPhoneInterface.this, "Phone Alerted", Toast.LENGTH_LONG) .show(); } } else { ParseObject alertVal = new ParseObject("Settings"); alertVal.put("userObjectId", ObjectId); alertVal.put("alertPhone", true); scoreList.get(0).saveInBackground(); Toast.makeText(FindPhoneInterface.this, "Phone Alerted", Toast.LENGTH_LONG) .show(); } } } }); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_find_phone_interface, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
Rakesh627/PhoneFinder
ParseStarterProject/src/main/java/com/mc/phonefinder/usersettings/FindPhoneInterface.java
Java
apache-2.0
10,791
import AttributeCompression from "../Core/AttributeCompression.js"; import Cartesian3 from "../Core/Cartesian3.js"; import Cartographic from "../Core/Cartographic.js"; import Ellipsoid from "../Core/Ellipsoid.js"; import IndexDatatype from "../Core/IndexDatatype.js"; import CesiumMath from "../Core/Math.js"; import Rectangle from "../Core/Rectangle.js"; import createTaskProcessorWorker from "./createTaskProcessorWorker.js"; var maxShort = 32767; var scratchBVCartographic = new Cartographic(); var scratchEncodedPosition = new Cartesian3(); function decodePositions( positions, rectangle, minimumHeight, maximumHeight, ellipsoid ) { var positionsLength = positions.length / 3; var uBuffer = positions.subarray(0, positionsLength); var vBuffer = positions.subarray(positionsLength, 2 * positionsLength); var heightBuffer = positions.subarray( 2 * positionsLength, 3 * positionsLength ); AttributeCompression.zigZagDeltaDecode(uBuffer, vBuffer, heightBuffer); var decoded = new Float64Array(positions.length); for (var i = 0; i < positionsLength; ++i) { var u = uBuffer[i]; var v = vBuffer[i]; var h = heightBuffer[i]; var lon = CesiumMath.lerp(rectangle.west, rectangle.east, u / maxShort); var lat = CesiumMath.lerp(rectangle.south, rectangle.north, v / maxShort); var alt = CesiumMath.lerp(minimumHeight, maximumHeight, h / maxShort); var cartographic = Cartographic.fromRadians( lon, lat, alt, scratchBVCartographic ); var decodedPosition = ellipsoid.cartographicToCartesian( cartographic, scratchEncodedPosition ); Cartesian3.pack(decodedPosition, decoded, i * 3); } return decoded; } var scratchRectangle = new Rectangle(); var scratchEllipsoid = new Ellipsoid(); var scratchCenter = new Cartesian3(); var scratchMinMaxHeights = { min: undefined, max: undefined, }; function unpackBuffer(packedBuffer) { packedBuffer = new Float64Array(packedBuffer); var offset = 0; scratchMinMaxHeights.min = packedBuffer[offset++]; scratchMinMaxHeights.max = packedBuffer[offset++]; Rectangle.unpack(packedBuffer, offset, scratchRectangle); offset += Rectangle.packedLength; Ellipsoid.unpack(packedBuffer, offset, scratchEllipsoid); offset += Ellipsoid.packedLength; Cartesian3.unpack(packedBuffer, offset, scratchCenter); } var scratchP0 = new Cartesian3(); var scratchP1 = new Cartesian3(); var scratchPrev = new Cartesian3(); var scratchCur = new Cartesian3(); var scratchNext = new Cartesian3(); function createVectorTilePolylines(parameters, transferableObjects) { var encodedPositions = new Uint16Array(parameters.positions); var widths = new Uint16Array(parameters.widths); var counts = new Uint32Array(parameters.counts); var batchIds = new Uint16Array(parameters.batchIds); unpackBuffer(parameters.packedBuffer); var rectangle = scratchRectangle; var ellipsoid = scratchEllipsoid; var center = scratchCenter; var minimumHeight = scratchMinMaxHeights.min; var maximumHeight = scratchMinMaxHeights.max; var positions = decodePositions( encodedPositions, rectangle, minimumHeight, maximumHeight, ellipsoid ); var positionsLength = positions.length / 3; var size = positionsLength * 4 - 4; var curPositions = new Float32Array(size * 3); var prevPositions = new Float32Array(size * 3); var nextPositions = new Float32Array(size * 3); var expandAndWidth = new Float32Array(size * 2); var vertexBatchIds = new Uint16Array(size); var positionIndex = 0; var expandAndWidthIndex = 0; var batchIdIndex = 0; var i; var offset = 0; var length = counts.length; for (i = 0; i < length; ++i) { var count = counts[i]; var width = widths[i]; var batchId = batchIds[i]; for (var j = 0; j < count; ++j) { var previous; if (j === 0) { var p0 = Cartesian3.unpack(positions, offset * 3, scratchP0); var p1 = Cartesian3.unpack(positions, (offset + 1) * 3, scratchP1); previous = Cartesian3.subtract(p0, p1, scratchPrev); Cartesian3.add(p0, previous, previous); } else { previous = Cartesian3.unpack( positions, (offset + j - 1) * 3, scratchPrev ); } var current = Cartesian3.unpack(positions, (offset + j) * 3, scratchCur); var next; if (j === count - 1) { var p2 = Cartesian3.unpack( positions, (offset + count - 1) * 3, scratchP0 ); var p3 = Cartesian3.unpack( positions, (offset + count - 2) * 3, scratchP1 ); next = Cartesian3.subtract(p2, p3, scratchNext); Cartesian3.add(p2, next, next); } else { next = Cartesian3.unpack(positions, (offset + j + 1) * 3, scratchNext); } Cartesian3.subtract(previous, center, previous); Cartesian3.subtract(current, center, current); Cartesian3.subtract(next, center, next); var startK = j === 0 ? 2 : 0; var endK = j === count - 1 ? 2 : 4; for (var k = startK; k < endK; ++k) { Cartesian3.pack(current, curPositions, positionIndex); Cartesian3.pack(previous, prevPositions, positionIndex); Cartesian3.pack(next, nextPositions, positionIndex); positionIndex += 3; var direction = k - 2 < 0 ? -1.0 : 1.0; expandAndWidth[expandAndWidthIndex++] = 2 * (k % 2) - 1; expandAndWidth[expandAndWidthIndex++] = direction * width; vertexBatchIds[batchIdIndex++] = batchId; } } offset += count; } var indices = IndexDatatype.createTypedArray(size, positionsLength * 6 - 6); var index = 0; var indicesIndex = 0; length = positionsLength - 1; for (i = 0; i < length; ++i) { indices[indicesIndex++] = index; indices[indicesIndex++] = index + 2; indices[indicesIndex++] = index + 1; indices[indicesIndex++] = index + 1; indices[indicesIndex++] = index + 2; indices[indicesIndex++] = index + 3; index += 4; } transferableObjects.push( curPositions.buffer, prevPositions.buffer, nextPositions.buffer ); transferableObjects.push( expandAndWidth.buffer, vertexBatchIds.buffer, indices.buffer ); return { indexDatatype: indices.BYTES_PER_ELEMENT === 2 ? IndexDatatype.UNSIGNED_SHORT : IndexDatatype.UNSIGNED_INT, currentPositions: curPositions.buffer, previousPositions: prevPositions.buffer, nextPositions: nextPositions.buffer, expandAndWidth: expandAndWidth.buffer, batchIds: vertexBatchIds.buffer, indices: indices.buffer, }; } export default createTaskProcessorWorker(createVectorTilePolylines);
progsung/cesium
Source/WorkersES6/createVectorTilePolylines.js
JavaScript
apache-2.0
6,753
/* * 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.geode.internal.cache; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.UUID; import org.apache.geode.annotations.Immutable; import org.apache.geode.cache.DiskStore; import org.apache.geode.cache.DiskStoreFactory; import org.apache.geode.internal.cache.persistence.DefaultDiskDirs; /** * Creates an attribute object for DiskStore. * </p> * * @since GemFire prPersistSprint2 */ public class DiskStoreAttributes implements Serializable, DiskStore { private static final long serialVersionUID = 1L; public boolean allowForceCompaction; public boolean autoCompact; public int compactionThreshold; public int queueSize; public int writeBufferSize; public long maxOplogSizeInBytes; public long timeInterval; public int[] diskDirSizes; private DiskDirSizesUnit diskDirSizesUnit; public File[] diskDirs; public String name; private volatile float diskUsageWarningPct; private volatile float diskUsageCriticalPct; /** * The default disk directory size unit. */ @Immutable static final DiskDirSizesUnit DEFAULT_DISK_DIR_SIZES_UNIT = DiskDirSizesUnit.MEGABYTES; public DiskStoreAttributes() { // set all to defaults autoCompact = DiskStoreFactory.DEFAULT_AUTO_COMPACT; compactionThreshold = DiskStoreFactory.DEFAULT_COMPACTION_THRESHOLD; allowForceCompaction = DiskStoreFactory.DEFAULT_ALLOW_FORCE_COMPACTION; maxOplogSizeInBytes = DiskStoreFactory.DEFAULT_MAX_OPLOG_SIZE * (1024 * 1024); timeInterval = DiskStoreFactory.DEFAULT_TIME_INTERVAL; writeBufferSize = DiskStoreFactory.DEFAULT_WRITE_BUFFER_SIZE; queueSize = DiskStoreFactory.DEFAULT_QUEUE_SIZE; diskDirs = DefaultDiskDirs.getDefaultDiskDirs(); diskDirSizes = DiskStoreFactory.DEFAULT_DISK_DIR_SIZES; diskDirSizesUnit = DEFAULT_DISK_DIR_SIZES_UNIT; diskUsageWarningPct = DiskStoreFactory.DEFAULT_DISK_USAGE_WARNING_PERCENTAGE; diskUsageCriticalPct = DiskStoreFactory.DEFAULT_DISK_USAGE_CRITICAL_PERCENTAGE; } @Override public UUID getDiskStoreUUID() { throw new UnsupportedOperationException("Not Implemented!"); } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getAllowForceCompaction() */ @Override public boolean getAllowForceCompaction() { return allowForceCompaction; } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getAutoCompact() */ @Override public boolean getAutoCompact() { return autoCompact; } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getCompactionThreshold() */ @Override public int getCompactionThreshold() { return compactionThreshold; } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getDiskDirSizes() */ @Override public int[] getDiskDirSizes() { int[] result = new int[diskDirSizes.length]; System.arraycopy(diskDirSizes, 0, result, 0, diskDirSizes.length); return result; } public DiskDirSizesUnit getDiskDirSizesUnit() { return diskDirSizesUnit; } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getDiskDirs() */ @Override public File[] getDiskDirs() { File[] result = new File[diskDirs.length]; System.arraycopy(diskDirs, 0, result, 0, diskDirs.length); return result; } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getMaxOplogSize() */ @Override public long getMaxOplogSize() { return maxOplogSizeInBytes / (1024 * 1024); } /** * Used by unit tests */ public long getMaxOplogSizeInBytes() { return maxOplogSizeInBytes; } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getName() */ @Override public String getName() { return name; } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getQueueSize() */ @Override public int getQueueSize() { return queueSize; } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getTimeInterval() */ @Override public long getTimeInterval() { return timeInterval; } /* * (non-Javadoc) * * @see org.apache.geode.cache.DiskStore#getWriteBufferSize() */ @Override public int getWriteBufferSize() { return writeBufferSize; } @Override public void flush() { // nothing needed } @Override public void forceRoll() { // nothing needed } @Override public boolean forceCompaction() { return false; } @Override public void destroy() { // nothing needed } @Override public float getDiskUsageWarningPercentage() { return diskUsageWarningPct; } @Override public float getDiskUsageCriticalPercentage() { return diskUsageCriticalPct; } @Override public void setDiskUsageWarningPercentage(float warningPercent) { DiskStoreMonitor.checkWarning(warningPercent); diskUsageWarningPct = warningPercent; } @Override public void setDiskUsageCriticalPercentage(float criticalPercent) { DiskStoreMonitor.checkCritical(criticalPercent); diskUsageCriticalPct = criticalPercent; } public void setDiskDirSizesUnit(DiskDirSizesUnit unit) { diskDirSizesUnit = unit; } private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (diskDirSizesUnit == null) { diskDirSizesUnit = DEFAULT_DISK_DIR_SIZES_UNIT; } } public static void checkMinAndMaxOplogSize(long maxOplogSize) { long MAX = Long.MAX_VALUE / (1024 * 1024); if (maxOplogSize > MAX) { throw new IllegalArgumentException( String.format( "%s has to be a number that does not exceed %s so the value given %s is not acceptable", "max oplog size", maxOplogSize, MAX)); } checkMinOplogSize(maxOplogSize); } public static void checkMinOplogSize(long maxOplogSize) { if (maxOplogSize < 0) { throw new IllegalArgumentException( String.format( "Maximum Oplog size specified has to be a non-negative number and the value given %s is not acceptable", maxOplogSize)); } } public static void checkQueueSize(int queueSize) { if (queueSize < 0) { throw new IllegalArgumentException( String.format( "Queue size specified has to be a non-negative number and the value given %s is not acceptable", queueSize)); } } public static void checkWriteBufferSize(int writeBufferSize) { if (writeBufferSize < 0) { throw new IllegalArgumentException( String.format( "Write buffer size specified has to be a non-negative number and the value given %s is not acceptable", writeBufferSize)); } } /** * Verify all directory sizes are positive */ public static void verifyNonNegativeDirSize(int[] sizes) { for (int size : sizes) { if (size < 0) { throw new IllegalArgumentException( String.format("Dir size cannot be negative : %s", size)); } } } public static void checkTimeInterval(long timeInterval) { if (timeInterval < 0) { throw new IllegalArgumentException( String.format( "Time Interval specified has to be a non-negative number and the value given %s is not acceptable", timeInterval)); } } }
jdeppe-pivotal/geode
geode-core/src/main/java/org/apache/geode/internal/cache/DiskStoreAttributes.java
Java
apache-2.0
8,257
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package signer import ( "crypto/x509" "io/ioutil" "reflect" "strings" "testing" "time" capi "k8s.io/api/certificates/v1beta1" "k8s.io/client-go/util/cert" ) func TestSigner(t *testing.T) { s, err := newCFSSLSigner("./testdata/ca.crt", "./testdata/ca.key", nil, 1*time.Hour) if err != nil { t.Fatalf("failed to create signer: %v", err) } csrb, err := ioutil.ReadFile("./testdata/kubelet.csr") if err != nil { t.Fatalf("failed to read CSR: %v", err) } csr := &capi.CertificateSigningRequest{ Spec: capi.CertificateSigningRequestSpec{ Request: []byte(csrb), Usages: []capi.KeyUsage{ capi.UsageSigning, capi.UsageKeyEncipherment, capi.UsageServerAuth, capi.UsageClientAuth, }, }, } csr, err = s.sign(csr) if err != nil { t.Fatalf("failed to sign CSR: %v", err) } certData := csr.Status.Certificate if len(certData) == 0 { t.Fatalf("expected a certificate after signing") } certs, err := cert.ParseCertsPEM(certData) if err != nil { t.Fatalf("failed to parse certificate: %v", err) } if len(certs) != 1 { t.Fatalf("expected one certificate") } crt := certs[0] if crt.Subject.CommonName != "system:node:k-a-node-s36b" { t.Errorf("expected common name of 'system:node:k-a-node-s36b', but got: %v", certs[0].Subject.CommonName) } if !reflect.DeepEqual(crt.Subject.Organization, []string{"system:nodes"}) { t.Errorf("expected organization to be [system:nodes] but got: %v", crt.Subject.Organization) } if crt.KeyUsage != x509.KeyUsageDigitalSignature|x509.KeyUsageKeyEncipherment { t.Errorf("bad key usage") } if !reflect.DeepEqual(crt.ExtKeyUsage, []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}) { t.Errorf("bad extended key usage") } } func TestSignerExpired(t *testing.T) { hundredYearsFromNowFn := func() time.Time { return time.Now().Add(24 * time.Hour * 365 * 100) } s, err := newCFSSLSigner("./testdata/ca.crt", "./testdata/ca.key", nil, 1*time.Hour) if err != nil { t.Fatalf("failed to create signer: %v", err) } s.nowFn = hundredYearsFromNowFn csrb, err := ioutil.ReadFile("./testdata/kubelet.csr") if err != nil { t.Fatalf("failed to read CSR: %v", err) } csr := &capi.CertificateSigningRequest{ Spec: capi.CertificateSigningRequestSpec{ Request: []byte(csrb), Usages: []capi.KeyUsage{ capi.UsageSigning, capi.UsageKeyEncipherment, capi.UsageServerAuth, capi.UsageClientAuth, }, }, } _, err = s.sign(csr) if err == nil { t.Fatal("missing error") } if !strings.HasPrefix(err.Error(), "the signer has expired") { t.Fatal(err) } } func TestDurationLongerThanExpiry(t *testing.T) { testNow := time.Now() testNowFn := func() time.Time { return testNow } hundredYears := 24 * time.Hour * 365 * 100 s, err := newCFSSLSigner("./testdata/ca.crt", "./testdata/ca.key", nil, hundredYears) if err != nil { t.Fatalf("failed to create signer: %v", err) } s.nowFn = testNowFn csrb, err := ioutil.ReadFile("./testdata/kubelet.csr") if err != nil { t.Fatalf("failed to read CSR: %v", err) } csr := &capi.CertificateSigningRequest{ Spec: capi.CertificateSigningRequestSpec{ Request: []byte(csrb), Usages: []capi.KeyUsage{ capi.UsageSigning, capi.UsageKeyEncipherment, capi.UsageServerAuth, capi.UsageClientAuth, }, }, } _, err = s.sign(csr) if err != nil { t.Fatalf("failed to sign CSR: %v", err) } // now we just need to verify that the expiry is based on the signing cert certData := csr.Status.Certificate if len(certData) == 0 { t.Fatalf("expected a certificate after signing") } certs, err := cert.ParseCertsPEM(certData) if err != nil { t.Fatalf("failed to parse certificate: %v", err) } if len(certs) != 1 { t.Fatalf("expected one certificate") } crt := certs[0] expected, err := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", "2044-05-09 00:20:11 +0000 UTC") if err != nil { t.Fatal(err) } // there is some jitter that we need to tolerate diff := expected.Sub(crt.NotAfter) if diff > 10*time.Minute || diff < -10*time.Minute { t.Fatal(crt.NotAfter) } }
linzhaoming/origin
vendor/k8s.io/kubernetes/pkg/controller/certificates/signer/cfssl_signer_test.go
GO
apache-2.0
4,691
/* * SVG Salamander * Copyright (c) 2004, Mark McKay * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Mark McKay can be contacted at mark@kitfox.com. Salamander and other * projects can be found at http://www.kitfox.com * * Created on January 26, 2004, 8:40 PM */ package com.kitfox.svg.pathcmd; //import org.apache.batik.ext.awt.geom.ExtendedGeneralPath; import java.awt.*; import java.awt.geom.*; /** * This is a little used SVG function, as most editors will save curves as * Beziers. To reduce the need to rely on the Batik library, this functionallity * is being bypassed for the time being. In the future, it would be nice to * extend the GeneralPath command to include the arcTo ability provided by Batik. * * @author Mark McKay * @author <a href="mailto:mark@kitfox.com">Mark McKay</a> */ public class Arc extends PathCommand { public float rx = 0f; public float ry = 0f; public float xAxisRot = 0f; public boolean largeArc = false; public boolean sweep = false; public float x = 0f; public float y = 0f; /** Creates a new instance of MoveTo */ public Arc() { } public Arc(boolean isRelative, float rx, float ry, float xAxisRot, boolean largeArc, boolean sweep, float x, float y) { super(isRelative); this.rx = rx; this.ry = ry; this.xAxisRot = xAxisRot; this.largeArc = largeArc; this.sweep = sweep; this.x = x; this.y = y; } // public void appendPath(ExtendedGeneralPath path, BuildHistory hist) @Override public void appendPath(GeneralPath path, BuildHistory hist) { float offx = isRelative ? hist.lastPoint.x : 0f; float offy = isRelative ? hist.lastPoint.y : 0f; arcTo(path, rx, ry, xAxisRot, largeArc, sweep, x + offx, y + offy, hist.lastPoint.x, hist.lastPoint.y); // path.lineTo(x + offx, y + offy); // hist.setPoint(x + offx, y + offy); hist.setLastPoint(x + offx, y + offy); hist.setLastKnot(x + offx, y + offy); } @Override public int getNumKnotsAdded() { return 6; } /** * Adds an elliptical arc, defined by two radii, an angle from the * x-axis, a flag to choose the large arc or not, a flag to * indicate if we increase or decrease the angles and the final * point of the arc. * * @param rx the x radius of the ellipse * @param ry the y radius of the ellipse * * @param angle the angle from the x-axis of the current * coordinate system to the x-axis of the ellipse in degrees. * * @param largeArcFlag the large arc flag. If true the arc * spanning less than or equal to 180 degrees is chosen, otherwise * the arc spanning greater than 180 degrees is chosen * * @param sweepFlag the sweep flag. If true the line joining * center to arc sweeps through decreasing angles otherwise it * sweeps through increasing angles * * @param x the absolute x coordinate of the final point of the arc. * @param y the absolute y coordinate of the final point of the arc. * @param x0 - The absolute x coordinate of the initial point of the arc. * @param y0 - The absolute y coordinate of the initial point of the arc. */ public void arcTo(GeneralPath path, float rx, float ry, float angle, boolean largeArcFlag, boolean sweepFlag, float x, float y, float x0, float y0) { // Ensure radii are valid if (rx == 0 || ry == 0) { path.lineTo((float) x, (float) y); return; } if (x0 == x && y0 == y) { // If the endpoints (x, y) and (x0, y0) are identical, then this // is equivalent to omitting the elliptical arc segment entirely. return; } Arc2D arc = computeArc(x0, y0, rx, ry, angle, largeArcFlag, sweepFlag, x, y); if (arc == null) return; AffineTransform t = AffineTransform.getRotateInstance (Math.toRadians(angle), arc.getCenterX(), arc.getCenterY()); Shape s = t.createTransformedShape(arc); path.append(s, true); } /** * This constructs an unrotated Arc2D from the SVG specification of an * Elliptical arc. To get the final arc you need to apply a rotation * transform such as: * * AffineTransform.getRotateInstance * (angle, arc.getX()+arc.getWidth()/2, arc.getY()+arc.getHeight()/2); */ public static Arc2D computeArc(double x0, double y0, double rx, double ry, double angle, boolean largeArcFlag, boolean sweepFlag, double x, double y) { // // Elliptical arc implementation based on the SVG specification notes // // Compute the half distance between the current and the final point double dx2 = (x0 - x) / 2.0; double dy2 = (y0 - y) / 2.0; // Convert angle from degrees to radians angle = Math.toRadians(angle % 360.0); double cosAngle = Math.cos(angle); double sinAngle = Math.sin(angle); // // Step 1 : Compute (x1, y1) // double x1 = (cosAngle * dx2 + sinAngle * dy2); double y1 = (-sinAngle * dx2 + cosAngle * dy2); // Ensure radii are large enough rx = Math.abs(rx); ry = Math.abs(ry); double Prx = rx * rx; double Pry = ry * ry; double Px1 = x1 * x1; double Py1 = y1 * y1; // check that radii are large enough double radiiCheck = Px1/Prx + Py1/Pry; if (radiiCheck > 1) { rx = Math.sqrt(radiiCheck) * rx; ry = Math.sqrt(radiiCheck) * ry; Prx = rx * rx; Pry = ry * ry; } // // Step 2 : Compute (cx1, cy1) // double sign = (largeArcFlag == sweepFlag) ? -1 : 1; double sq = ((Prx*Pry)-(Prx*Py1)-(Pry*Px1)) / ((Prx*Py1)+(Pry*Px1)); sq = (sq < 0) ? 0 : sq; double coef = (sign * Math.sqrt(sq)); double cx1 = coef * ((rx * y1) / ry); double cy1 = coef * -((ry * x1) / rx); // // Step 3 : Compute (cx, cy) from (cx1, cy1) // double sx2 = (x0 + x) / 2.0; double sy2 = (y0 + y) / 2.0; double cx = sx2 + (cosAngle * cx1 - sinAngle * cy1); double cy = sy2 + (sinAngle * cx1 + cosAngle * cy1); // // Step 4 : Compute the angleStart (angle1) and the angleExtent (dangle) // double ux = (x1 - cx1) / rx; double uy = (y1 - cy1) / ry; double vx = (-x1 - cx1) / rx; double vy = (-y1 - cy1) / ry; double p, n; // Compute the angle start n = Math.sqrt((ux * ux) + (uy * uy)); p = ux; // (1 * ux) + (0 * uy) sign = (uy < 0) ? -1d : 1d; double angleStart = Math.toDegrees(sign * Math.acos(p / n)); // Compute the angle extent n = Math.sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy)); p = ux * vx + uy * vy; sign = (ux * vy - uy * vx < 0) ? -1d : 1d; double angleExtent = Math.toDegrees(sign * Math.acos(p / n)); if(!sweepFlag && angleExtent > 0) { angleExtent -= 360f; } else if (sweepFlag && angleExtent < 0) { angleExtent += 360f; } angleExtent %= 360f; angleStart %= 360f; // // We can now build the resulting Arc2D in double precision // Arc2D.Double arc = new Arc2D.Double(); arc.x = cx - rx; arc.y = cy - ry; arc.width = rx * 2.0; arc.height = ry * 2.0; arc.start = -angleStart; arc.extent = -angleExtent; return arc; } @Override public String toString() { return "A " + rx + " " + ry + " " + xAxisRot + " " + largeArc + " " + sweep + " " + x + " " + y; } }
Longri/cachebox3.0
launcher/desktop_lwjgl/src/com/kitfox/svg/pathcmd/Arc.java
Java
apache-2.0
9,856
'use strict'; angular.module('publisherApp') .config(function ($stateProvider) { $stateProvider .state('settings', { parent: 'account', url: '/settings', data: { roles: ['ROLE_USER'], pageTitle: 'global.menu.account.settings' }, views: { 'container@': { templateUrl: 'scripts/app/account/settings/settings.html', controller: 'SettingsController' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('settings'); return $translate.refresh(); }] } }); });
GIP-RECIA/esup-publisher-ui
src/main/webapp/scripts/app/account/settings/settings.js
JavaScript
apache-2.0
949
package com.sean.im.client.push.handler; import com.alibaba.fastjson.JSON; import com.sean.im.client.constant.Global; import com.sean.im.client.core.ApplicationContext; import com.sean.im.client.core.PushHandler; import com.sean.im.client.form.MainForm; import com.sean.im.client.tray.TrayManager; import com.sean.im.client.util.MusicUtil; import com.sean.im.commom.core.Protocol; import com.sean.im.commom.entity.Message; /** * 移除群成员 * @author sean */ public class KickOutFlockHandler implements PushHandler { @Override public void execute(Protocol notify) { Message msg = JSON.parseObject(notify.getParameter("msg"), Message.class); // 界面上删除群 long flockId = Long.parseLong(msg.getContent()); MainForm.FORM.getFlockList().removeFlock(flockId); // 压入消息队列 ApplicationContext.CTX.getMessageQueue().add(msg); // 提示系统托盘闪烁 TrayManager.getInstance().startLight(0); MusicUtil.play(Global.Root + "resource/sound/msg.wav"); } }
seanzwx/tmp
seatalk/im/im-client/src/main/java/com/sean/im/client/push/handler/KickOutFlockHandler.java
Java
apache-2.0
1,004
/* * 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.psi.impl.cache.impl.idCache; import com.intellij.lexer.Lexer; import com.intellij.lexer.XHtmlHighlightingLexer; import com.intellij.psi.impl.cache.impl.BaseFilterLexer; import com.intellij.psi.impl.cache.impl.id.LexerBasedIdIndexer; public class XHtmlIdIndexer extends LexerBasedIdIndexer { protected Lexer createLexer(final BaseFilterLexer.OccurrenceConsumer consumer) { return new XHtmlFilterLexer(new XHtmlHighlightingLexer(), consumer); } }
jexp/idea2
xml/impl/src/com/intellij/psi/impl/cache/impl/idCache/XHtmlIdIndexer.java
Java
apache-2.0
1,077
# =============================================================================== # Copyright 2013 Jake Ross # # 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. # =============================================================================== # ============= enthought library imports ======================= from chaco.data_label import DataLabel from chaco.plot_label import PlotLabel # ============= standard library imports ======================== from numpy import max from traits.api import Bool, Str # ============= local library imports ========================== from pychron.pipeline.plot.overlays.mean_indicator_overlay import MovableMixin try: class FlowPlotLabel(PlotLabel, MovableMixin): def overlay(self, component, gc, *args, **kw): if self.ox: self.x = self.ox - self.offset_x self.y = self.oy - self.offset_y super(FlowPlotLabel, self).overlay(component, gc, *args, **kw) def hittest(self, pt): x, y = pt w, h = self.get_preferred_size() return abs(x - self.x) < w and abs(y - self.y) < h except TypeError: # documentation auto doc hack class FlowPlotLabel: pass class FlowDataLabel(DataLabel): """ this label repositions itself if doesn't fit within the its component bounds. """ constrain_x = Bool(True) constrain_y = Bool(True) # position_event=Event id = Str # _ox=None # def _draw(self, gc, **kw): # self.font='modern 18' # gc.set_font(self.font) # print 'draw', self.font # super(FlowDataLabel, self)._draw(gc,**kw) # def _set_x(self, val): # super(FlowDataLabel, self)._set_x(val) # if self._ox is None: # self._ox = val # elif self._ox != val: # self.position_event=(self.x, self.y) # # def _set_y(self, val): # super(FlowDataLabel, self)._set_y(val) # if val>0: # self.position_event = (self.x, self.y) def overlay(self, component, gc, *args, **kw): # face name was getting set to "Helvetica" by reportlab during pdf generation # set face_name back to "" to prevent font display issue. see issue #72 self.font.face_name = "" super(FlowDataLabel, self).overlay(component, gc, *args, **kw) def do_layout(self, **kw): DataLabel.do_layout(self, **kw) ws, hs = self._cached_line_sizes.T if self.constrain_x: w = max(ws) d = self.component.x2 - (self.x + w + 3 * self.border_padding) if d < 0: self.x += d self.x = max((self.x, 0)) if self.constrain_y: h = max(hs) self.y = max((self.y, 0)) yd = self.component.y2 - h - 2 * self.border_padding - self.line_spacing self.y = min((self.y, yd)) # ============= EOF =============================================
USGSDenverPychron/pychron
pychron/pipeline/plot/flow_label.py
Python
apache-2.0
3,470
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package setmilestone implements the `/milestone` command which allows members of the milestone // maintainers team to specify a milestone to be applied to an Issue or PR. package milestone import ( "fmt" "regexp" "sort" "strings" "github.com/sirupsen/logrus" "k8s.io/test-infra/prow/github" "k8s.io/test-infra/prow/pluginhelp" "k8s.io/test-infra/prow/plugins" ) const pluginName = "milestone" var ( milestoneRegex = regexp.MustCompile(`(?m)^/milestone\s+(.+?)\s*$`) mustBeSigLead = "You must be a member of the [%s/%s](https://github.com/orgs/%s/teams/%s/members) github team to set the milestone." invalidMilestone = "The provided milestone is not valid for this repository. Milestones in this repository: [%s]\n\nUse `/milestone %s` to clear the milestone." milestoneTeamMsg = "The milestone maintainers team is the Github team with ID: %d." clearKeyword = "clear" ) type githubClient interface { CreateComment(owner, repo string, number int, comment string) error ClearMilestone(org, repo string, num int) error SetMilestone(org, repo string, issueNum, milestoneNum int) error ListTeamMembers(id int, role string) ([]github.TeamMember, error) ListMilestones(org, repo string) ([]github.Milestone, error) } func init() { plugins.RegisterGenericCommentHandler(pluginName, handleGenericComment, helpProvider) } func helpProvider(config *plugins.Configuration, enabledRepos []string) (*pluginhelp.PluginHelp, error) { pluginHelp := &pluginhelp.PluginHelp{ Description: "The milestone plugin allows members of a configurable GitHub team to set the milestone on an issue or pull request.", Config: func(repos []string) map[string]string { configMap := make(map[string]string) for _, repo := range repos { team, exists := config.RepoMilestone[repo] if exists { configMap[repo] = fmt.Sprintf(milestoneTeamMsg, team) } } configMap[""] = fmt.Sprintf(milestoneTeamMsg, config.RepoMilestone[""]) return configMap }(enabledRepos), } pluginHelp.AddCommand(pluginhelp.Command{ Usage: "/milestone <version> or /milestone clear", Description: "Updates the milestone for an issue or PR", Featured: false, WhoCanUse: "Members of the milestone maintainers GitHub team can use the '/milestone' command.", Examples: []string{"/milestone v1.10", "/milestone v1.9", "/milestone clear"}, }) return pluginHelp, nil } func handleGenericComment(pc plugins.PluginClient, e github.GenericCommentEvent) error { return handle(pc.GitHubClient, pc.Logger, &e, pc.PluginConfig.RepoMilestone) } func buildMilestoneMap(milestones []github.Milestone) map[string]int { m := make(map[string]int) for _, ms := range milestones { m[ms.Title] = ms.Number } return m } func handle(gc githubClient, log *logrus.Entry, e *github.GenericCommentEvent, repoMilestone map[string]plugins.Milestone) error { if e.Action != github.GenericCommentActionCreated { return nil } milestoneMatch := milestoneRegex.FindStringSubmatch(e.Body) if len(milestoneMatch) != 2 { return nil } org := e.Repo.Owner.Login repo := e.Repo.Name milestone, exists := repoMilestone[fmt.Sprintf("%s/%s", org, repo)] if !exists { // fallback default milestone = repoMilestone[""] } milestoneMaintainers, err := gc.ListTeamMembers(milestone.MaintainersID, github.RoleAll) if err != nil { return err } found := false for _, person := range milestoneMaintainers { login := github.NormLogin(e.User.Login) if github.NormLogin(person.Login) == login { found = true break } } if !found { // not in the milestone maintainers team msg := fmt.Sprintf(mustBeSigLead, org, milestone.MaintainersTeam, org, milestone.MaintainersTeam) return gc.CreateComment(org, repo, e.Number, plugins.FormatResponseRaw(e.Body, e.HTMLURL, e.User.Login, msg)) } milestones, err := gc.ListMilestones(org, repo) if err != nil { log.WithError(err).Errorf("Error listing the milestones in the %s/%s repo", org, repo) return err } proposedMilestone := milestoneMatch[1] // special case, if the clear keyword is used if proposedMilestone == clearKeyword { if err := gc.ClearMilestone(org, repo, e.Number); err != nil { log.WithError(err).Errorf("Error clearing the milestone for %s/%s#%d.", org, repo, e.Number) } return nil } milestoneMap := buildMilestoneMap(milestones) milestoneNumber, ok := milestoneMap[proposedMilestone] if !ok { slice := make([]string, 0, len(milestoneMap)) for k := range milestoneMap { slice = append(slice, fmt.Sprintf("`%s`", k)) } sort.Strings(slice) msg := fmt.Sprintf(invalidMilestone, strings.Join(slice, ", "), clearKeyword) return gc.CreateComment(org, repo, e.Number, plugins.FormatResponseRaw(e.Body, e.HTMLURL, e.User.Login, msg)) } if err := gc.SetMilestone(org, repo, e.Number, milestoneNumber); err != nil { log.WithError(err).Errorf("Error adding the milestone %s to %s/%s#%d.", proposedMilestone, org, repo, e.Number) } return nil }
mindprince/test-infra
prow/plugins/milestone/milestone.go
GO
apache-2.0
5,550
// // Copyright 2014, Sander van Harmelen // // 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 cloudstack44 import ( "encoding/json" "net/url" "strconv" ) type ListStorageProvidersParams struct { p map[string]interface{} } func (p *ListStorageProvidersParams) toURLValues() url.Values { u := url.Values{} if p.p == nil { return u } if v, found := p.p["keyword"]; found { u.Set("keyword", v.(string)) } if v, found := p.p["page"]; found { vv := strconv.Itoa(v.(int)) u.Set("page", vv) } if v, found := p.p["pagesize"]; found { vv := strconv.Itoa(v.(int)) u.Set("pagesize", vv) } if v, found := p.p["type"]; found { u.Set("type", v.(string)) } return u } func (p *ListStorageProvidersParams) SetKeyword(v string) { if p.p == nil { p.p = make(map[string]interface{}) } p.p["keyword"] = v return } func (p *ListStorageProvidersParams) SetPage(v int) { if p.p == nil { p.p = make(map[string]interface{}) } p.p["page"] = v return } func (p *ListStorageProvidersParams) SetPagesize(v int) { if p.p == nil { p.p = make(map[string]interface{}) } p.p["pagesize"] = v return } func (p *ListStorageProvidersParams) SetType(v string) { if p.p == nil { p.p = make(map[string]interface{}) } p.p["storagePoolType"] = v return } // You should always use this function to get a new ListStorageProvidersParams instance, // as then you are sure you have configured all required params func (s *StoragePoolService) NewListStorageProvidersParams(storagePoolType string) *ListStorageProvidersParams { p := &ListStorageProvidersParams{} p.p = make(map[string]interface{}) p.p["storagePoolType"] = storagePoolType return p } // Lists storage providers. func (s *StoragePoolService) ListStorageProviders(p *ListStorageProvidersParams) (*ListStorageProvidersResponse, error) { resp, err := s.cs.newRequest("listStorageProviders", p.toURLValues()) if err != nil { return nil, err } var r ListStorageProvidersResponse if err := json.Unmarshal(resp, &r); err != nil { return nil, err } return &r, nil } type ListStorageProvidersResponse struct { Count int `json:"count"` StorageProviders []*StorageProvider `json:"storageprovider"` } type StorageProvider struct { Name string `json:"name,omitempty"` Type string `json:"type,omitempty"` } type EnableStorageMaintenanceParams struct { p map[string]interface{} } func (p *EnableStorageMaintenanceParams) toURLValues() url.Values { u := url.Values{} if p.p == nil { return u } if v, found := p.p["id"]; found { u.Set("id", v.(string)) } return u } func (p *EnableStorageMaintenanceParams) SetId(v string) { if p.p == nil { p.p = make(map[string]interface{}) } p.p["id"] = v return } // You should always use this function to get a new EnableStorageMaintenanceParams instance, // as then you are sure you have configured all required params func (s *StoragePoolService) NewEnableStorageMaintenanceParams(id string) *EnableStorageMaintenanceParams { p := &EnableStorageMaintenanceParams{} p.p = make(map[string]interface{}) p.p["id"] = id return p } // Puts storage pool into maintenance state func (s *StoragePoolService) EnableStorageMaintenance(p *EnableStorageMaintenanceParams) (*EnableStorageMaintenanceResponse, error) { resp, err := s.cs.newRequest("enableStorageMaintenance", p.toURLValues()) if err != nil { return nil, err } var r EnableStorageMaintenanceResponse if err := json.Unmarshal(resp, &r); err != nil { return nil, err } // If we have a async client, we need to wait for the async result if s.cs.async { b, warn, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout) if err != nil { return nil, err } // If 'warn' has a value it means the job is running longer than the configured // timeout, the resonse will contain the jobid of the running async job if warn != nil { return &r, warn } b, err = getRawValue(b) if err != nil { return nil, err } if err := json.Unmarshal(b, &r); err != nil { return nil, err } } return &r, nil } type EnableStorageMaintenanceResponse struct { JobID string `json:"jobid,omitempty"` Capacityiops int64 `json:"capacityiops,omitempty"` Clusterid string `json:"clusterid,omitempty"` Clustername string `json:"clustername,omitempty"` Created string `json:"created,omitempty"` Disksizeallocated int64 `json:"disksizeallocated,omitempty"` Disksizetotal int64 `json:"disksizetotal,omitempty"` Disksizeused int64 `json:"disksizeused,omitempty"` Hypervisor string `json:"hypervisor,omitempty"` Id string `json:"id,omitempty"` Ipaddress string `json:"ipaddress,omitempty"` Name string `json:"name,omitempty"` Overprovisionfactor string `json:"overprovisionfactor,omitempty"` Path string `json:"path,omitempty"` Podid string `json:"podid,omitempty"` Podname string `json:"podname,omitempty"` Scope string `json:"scope,omitempty"` State string `json:"state,omitempty"` Storagecapabilities map[string]string `json:"storagecapabilities,omitempty"` Suitableformigration bool `json:"suitableformigration,omitempty"` Tags string `json:"tags,omitempty"` Type string `json:"type,omitempty"` Zoneid string `json:"zoneid,omitempty"` Zonename string `json:"zonename,omitempty"` } type CancelStorageMaintenanceParams struct { p map[string]interface{} } func (p *CancelStorageMaintenanceParams) toURLValues() url.Values { u := url.Values{} if p.p == nil { return u } if v, found := p.p["id"]; found { u.Set("id", v.(string)) } return u } func (p *CancelStorageMaintenanceParams) SetId(v string) { if p.p == nil { p.p = make(map[string]interface{}) } p.p["id"] = v return } // You should always use this function to get a new CancelStorageMaintenanceParams instance, // as then you are sure you have configured all required params func (s *StoragePoolService) NewCancelStorageMaintenanceParams(id string) *CancelStorageMaintenanceParams { p := &CancelStorageMaintenanceParams{} p.p = make(map[string]interface{}) p.p["id"] = id return p } // Cancels maintenance for primary storage func (s *StoragePoolService) CancelStorageMaintenance(p *CancelStorageMaintenanceParams) (*CancelStorageMaintenanceResponse, error) { resp, err := s.cs.newRequest("cancelStorageMaintenance", p.toURLValues()) if err != nil { return nil, err } var r CancelStorageMaintenanceResponse if err := json.Unmarshal(resp, &r); err != nil { return nil, err } // If we have a async client, we need to wait for the async result if s.cs.async { b, warn, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout) if err != nil { return nil, err } // If 'warn' has a value it means the job is running longer than the configured // timeout, the resonse will contain the jobid of the running async job if warn != nil { return &r, warn } b, err = getRawValue(b) if err != nil { return nil, err } if err := json.Unmarshal(b, &r); err != nil { return nil, err } } return &r, nil } type CancelStorageMaintenanceResponse struct { JobID string `json:"jobid,omitempty"` Capacityiops int64 `json:"capacityiops,omitempty"` Clusterid string `json:"clusterid,omitempty"` Clustername string `json:"clustername,omitempty"` Created string `json:"created,omitempty"` Disksizeallocated int64 `json:"disksizeallocated,omitempty"` Disksizetotal int64 `json:"disksizetotal,omitempty"` Disksizeused int64 `json:"disksizeused,omitempty"` Hypervisor string `json:"hypervisor,omitempty"` Id string `json:"id,omitempty"` Ipaddress string `json:"ipaddress,omitempty"` Name string `json:"name,omitempty"` Overprovisionfactor string `json:"overprovisionfactor,omitempty"` Path string `json:"path,omitempty"` Podid string `json:"podid,omitempty"` Podname string `json:"podname,omitempty"` Scope string `json:"scope,omitempty"` State string `json:"state,omitempty"` Storagecapabilities map[string]string `json:"storagecapabilities,omitempty"` Suitableformigration bool `json:"suitableformigration,omitempty"` Tags string `json:"tags,omitempty"` Type string `json:"type,omitempty"` Zoneid string `json:"zoneid,omitempty"` Zonename string `json:"zonename,omitempty"` }
benjvi/go-cloudstack
cloudstack44/StoragePoolService.go
GO
apache-2.0
9,719
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.lang.rs; import com.intellij.lang.ASTNode; import com.intellij.lang.PsiBuilder; import com.intellij.lang.PsiParser; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; public class RenderscriptParser implements PsiParser { @NotNull @Override public ASTNode parse(IElementType root, PsiBuilder builder) { final PsiBuilder.Marker rootMarker = builder.mark(); while (!builder.eof()) { builder.advanceLexer(); } rootMarker.done(root); return builder.getTreeBuilt(); } }
consulo/consulo-android
android/android/src/com/android/tools/idea/lang/rs/RenderscriptParser.java
Java
apache-2.0
1,189
<?php namespace edu\wisc\services\caos; class GetCourseByCatalogNumberRequest { /** * @var termCodeType $termCode */ protected $termCode = null; /** * @var string $subjectCode */ protected $subjectCode = null; /** * @var string $catalogNumber */ protected $catalogNumber = null; /** * @param termCodeType $termCode * @param string $subjectCode * @param string $catalogNumber */ public function __construct($termCode, $subjectCode, $catalogNumber) { $this->termCode = $termCode; $this->subjectCode = $subjectCode; $this->catalogNumber = $catalogNumber; } /** * @return termCodeType */ public function getTermCode() { return $this->termCode; } /** * @param termCodeType $termCode * @return \edu\wisc\services\caos\GetCourseByCatalogNumberRequest */ public function setTermCode($termCode) { $this->termCode = $termCode; return $this; } /** * @return string */ public function getSubjectCode() { return $this->subjectCode; } /** * @param string $subjectCode * @return \edu\wisc\services\caos\GetCourseByCatalogNumberRequest */ public function setSubjectCode($subjectCode) { $this->subjectCode = $subjectCode; return $this; } /** * @return string */ public function getCatalogNumber() { return $this->catalogNumber; } /** * @param string $catalogNumber * @return \edu\wisc\services\caos\GetCourseByCatalogNumberRequest */ public function setCatalogNumber($catalogNumber) { $this->catalogNumber = $catalogNumber; return $this; } }
ahoffmann-wi/caos-php-client
src/main/GetCourseByCatalogNumberRequest.php
PHP
apache-2.0
1,771
/** * 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.wss4j.stax.impl.securityToken; import org.apache.wss4j.common.bsp.BSPRule; import org.apache.wss4j.common.ext.WSSecurityException; import org.apache.wss4j.common.principal.UsernameTokenPrincipal; import org.apache.wss4j.common.util.UsernameTokenUtil; import org.apache.wss4j.stax.ext.WSInboundSecurityContext; import org.apache.wss4j.stax.ext.WSSConstants; import org.apache.wss4j.stax.securityToken.UsernameSecurityToken; import org.apache.wss4j.stax.securityToken.WSSecurityTokenConstants; import org.apache.xml.security.exceptions.XMLSecurityException; import org.apache.xml.security.stax.config.JCEAlgorithmMapper; import org.apache.xml.security.stax.ext.XMLSecurityConstants; import org.apache.xml.security.stax.impl.securityToken.AbstractInboundSecurityToken; import javax.crypto.spec.SecretKeySpec; import javax.security.auth.Subject; import java.security.Key; import java.security.Principal; public class UsernameSecurityTokenImpl extends AbstractInboundSecurityToken implements UsernameSecurityToken { private static final long DEFAULT_ITERATION = 1000; private WSSConstants.UsernameTokenPasswordType usernameTokenPasswordType; private String username; private String password; private String createdTime; private byte[] nonce; private byte[] salt; private Long iteration; private final WSInboundSecurityContext wsInboundSecurityContext; private Subject subject; private Principal principal; public UsernameSecurityTokenImpl(WSSConstants.UsernameTokenPasswordType usernameTokenPasswordType, String username, String password, String createdTime, byte[] nonce, byte[] salt, Long iteration, WSInboundSecurityContext wsInboundSecurityContext, String id, WSSecurityTokenConstants.KeyIdentifier keyIdentifier) { super(wsInboundSecurityContext, id, keyIdentifier, true); this.usernameTokenPasswordType = usernameTokenPasswordType; this.username = username; this.password = password; this.createdTime = createdTime; this.nonce = nonce; this.salt = salt; this.iteration = iteration; this.wsInboundSecurityContext = wsInboundSecurityContext; } @Override public boolean isAsymmetric() throws XMLSecurityException { return false; } @Override protected Key getKey(String algorithmURI, XMLSecurityConstants.AlgorithmUsage algorithmUsage, String correlationID) throws XMLSecurityException { Key key = getSecretKey().get(algorithmURI); if (key != null) { return key; } byte[] secretToken = generateDerivedKey(wsInboundSecurityContext); String algoFamily = JCEAlgorithmMapper.getJCEKeyAlgorithmFromURI(algorithmURI); key = new SecretKeySpec(secretToken, algoFamily); setSecretKey(algorithmURI, key); return key; } @Override public WSSecurityTokenConstants.TokenType getTokenType() { return WSSecurityTokenConstants.UsernameToken; } /** * This method generates a derived key as defined in WSS Username * Token Profile. * * @return Returns the derived key a byte array * @throws WSSecurityException */ public byte[] generateDerivedKey() throws WSSecurityException { return generateDerivedKey(wsInboundSecurityContext); } /** * This method generates a derived key as defined in WSS Username * Token Profile. * * @return Returns the derived key a byte array * @throws org.apache.wss4j.common.ext.WSSecurityException * */ protected byte[] generateDerivedKey(WSInboundSecurityContext wsInboundSecurityContext) throws WSSecurityException { if (wsInboundSecurityContext != null) { if (salt == null || salt.length == 0) { wsInboundSecurityContext.handleBSPRule(BSPRule.R4217); } if (iteration == null || iteration < DEFAULT_ITERATION) { wsInboundSecurityContext.handleBSPRule(BSPRule.R4218); } } return UsernameTokenUtil.generateDerivedKey(password, salt, iteration.intValue()); } @Override public Principal getPrincipal() throws WSSecurityException { if (this.principal == null) { this.principal = new UsernameTokenPrincipal() { //todo passwordType and passwordDigest return Enum-Type ? @Override public boolean isPasswordDigest() { return usernameTokenPasswordType == WSSConstants.UsernameTokenPasswordType.PASSWORD_DIGEST; } @Override public String getPasswordType() { return usernameTokenPasswordType.getNamespace(); } @Override public String getName() { return username; } @Override public String getPassword() { return password; } @Override public String getCreatedTime() { return createdTime; } @Override public byte[] getNonce() { return nonce; } }; } return this.principal; } public WSSConstants.UsernameTokenPasswordType getUsernameTokenPasswordType() { return usernameTokenPasswordType; } public String getCreatedTime() { return createdTime; } public String getPassword() { return password; } public String getUsername() { return username; } public byte[] getNonce() { return nonce; } public byte[] getSalt() { return salt; } public Long getIteration() { return iteration; } public void setSubject(Subject subject) { this.subject = subject; } @Override public Subject getSubject() throws WSSecurityException { return subject; } }
asoldano/wss4j
ws-security-stax/src/main/java/org/apache/wss4j/stax/impl/securityToken/UsernameSecurityTokenImpl.java
Java
apache-2.0
7,035
# # Author:: Adam Jacob (<adam@opscode.com>) # Copyright:: Copyright (c) 2008 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "chef/resource/script" require "chef/provider/script" class Chef class Resource class Bash < Chef::Resource::Script def initialize(name, run_context=nil) super @interpreter = "bash" end end end end
BackSlasher/chef
lib/chef/resource/bash.rb
Ruby
apache-2.0
930
/********************************************************************** Copyright (c) 2005 Erik Bengtson and others. 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. Contributors: ... **********************************************************************/ package org.datanucleus.samples.metadata.datastoreidentity; public class D3 { private String name; /** * @return Returns the name. */ public String getName() { return name; } /** * @param name The name to set. */ public void setName(String name) { this.name = name; } }
datanucleus/tests
jdo/general/src/java/org/datanucleus/samples/metadata/datastoreidentity/D3.java
Java
apache-2.0
1,143
package com.mic.log.spouts; import java.util.Map; import backtype.storm.spout.SpoutOutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichSpout; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Values; public class AppLogWriterSpout extends BaseRichSpout { private SpoutOutputCollector _collector; public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { this._collector = collector; } @Override public void nextTuple() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } _collector.emit(new Values("command")); } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("command")); } }
yifzhang/storm-miclog
src/jvm/com/mic/log/spouts/AppLogWriterSpout.java
Java
apache-2.0
885
// 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 "base/nix/mime_util_xdg.h" #include <cstdlib> #include <list> #include <map> #include <vector> #include "base/environment.h" #include "base/file_util.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "base/nix/xdg_util.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/synchronization/lock.h" #include "base/third_party/xdg_mime/xdgmime.h" #include "base/threading/thread_restrictions.h" #include "base/time/time.h" namespace base { namespace nix { namespace { class IconTheme; // None of the XDG stuff is thread-safe, so serialize all access under // this lock. LazyInstance<Lock>::Leaky g_mime_util_xdg_lock = LAZY_INSTANCE_INITIALIZER; class MimeUtilConstants { public: typedef std::map<std::string, IconTheme*> IconThemeMap; typedef std::map<FilePath, Time> IconDirMtimeMap; typedef std::vector<std::string> IconFormats; // Specified by XDG icon theme specs. static const int kUpdateIntervalInSeconds = 5; static const size_t kDefaultThemeNum = 4; static MimeUtilConstants* GetInstance() { return Singleton<MimeUtilConstants>::get(); } // Store icon directories and their mtimes. IconDirMtimeMap icon_dirs_; // Store icon formats. IconFormats icon_formats_; // Store loaded icon_theme. IconThemeMap icon_themes_; // The default theme. IconTheme* default_themes_[kDefaultThemeNum]; TimeTicks last_check_time_; // The current icon theme, usually set through GTK theme integration. std::string icon_theme_name_; private: MimeUtilConstants() { icon_formats_.push_back(".png"); icon_formats_.push_back(".svg"); icon_formats_.push_back(".xpm"); for (size_t i = 0; i < kDefaultThemeNum; ++i) default_themes_[i] = NULL; } ~MimeUtilConstants(); friend struct DefaultSingletonTraits<MimeUtilConstants>; DISALLOW_COPY_AND_ASSIGN(MimeUtilConstants); }; // IconTheme represents an icon theme as defined by the xdg icon theme spec. // Example themes on GNOME include 'Human' and 'Mist'. // Example themes on KDE include 'crystalsvg' and 'kdeclassic'. class IconTheme { public: // A theme consists of multiple sub-directories, like '32x32' and 'scalable'. class SubDirInfo { public: // See spec for details. enum Type { Fixed, Scalable, Threshold }; SubDirInfo() : size(0), type(Threshold), max_size(0), min_size(0), threshold(2) { } size_t size; // Nominal size of the icons in this directory. Type type; // Type of the icon size. size_t max_size; // Maximum size that the icons can be scaled to. size_t min_size; // Minimum size that the icons can be scaled to. size_t threshold; // Maximum difference from desired size. 2 by default. }; explicit IconTheme(const std::string& name); ~IconTheme() {} // Returns the path to an icon with the name |icon_name| and a size of |size| // pixels. If the icon does not exist, but |inherits| is true, then look for // the icon in the parent theme. FilePath GetIconPath(const std::string& icon_name, int size, bool inherits); // Load a theme with the name |theme_name| into memory. Returns null if theme // is invalid. static IconTheme* LoadTheme(const std::string& theme_name); private: // Returns the path to an icon with the name |icon_name| in |subdir|. FilePath GetIconPathUnderSubdir(const std::string& icon_name, const std::string& subdir); // Whether the theme loaded properly. bool IsValid() { return index_theme_loaded_; } // Read and parse |file| which is usually named 'index.theme' per theme spec. bool LoadIndexTheme(const FilePath& file); // Checks to see if the icons in |info| matches |size| (in pixels). Returns // 0 if they match, or the size difference in pixels. size_t MatchesSize(SubDirInfo* info, size_t size); // Yet another function to read a line. std::string ReadLine(FILE* fp); // Set directories to search for icons to the comma-separated list |dirs|. bool SetDirectories(const std::string& dirs); bool index_theme_loaded_; // True if an instance is properly loaded. // store the scattered directories of this theme. std::list<FilePath> dirs_; // store the subdirs of this theme and array index of |info_array_|. std::map<std::string, int> subdirs_; scoped_ptr<SubDirInfo[]> info_array_; // List of sub-directories. std::string inherits_; // Name of the theme this one inherits from. }; IconTheme::IconTheme(const std::string& name) : index_theme_loaded_(false) { ThreadRestrictions::AssertIOAllowed(); // Iterate on all icon directories to find directories of the specified // theme and load the first encountered index.theme. MimeUtilConstants::IconDirMtimeMap::iterator iter; FilePath theme_path; MimeUtilConstants::IconDirMtimeMap* icon_dirs = &MimeUtilConstants::GetInstance()->icon_dirs_; for (iter = icon_dirs->begin(); iter != icon_dirs->end(); ++iter) { theme_path = iter->first.Append(name); if (!DirectoryExists(theme_path)) continue; FilePath theme_index = theme_path.Append("index.theme"); if (!index_theme_loaded_ && PathExists(theme_index)) { if (!LoadIndexTheme(theme_index)) return; index_theme_loaded_ = true; } dirs_.push_back(theme_path); } } FilePath IconTheme::GetIconPath(const std::string& icon_name, int size, bool inherits) { std::map<std::string, int>::iterator subdir_iter; FilePath icon_path; for (subdir_iter = subdirs_.begin(); subdir_iter != subdirs_.end(); ++subdir_iter) { SubDirInfo* info = &info_array_[subdir_iter->second]; if (MatchesSize(info, size) == 0) { icon_path = GetIconPathUnderSubdir(icon_name, subdir_iter->first); if (!icon_path.empty()) return icon_path; } } // Now looking for the mostly matched. size_t min_delta_seen = 9999; for (subdir_iter = subdirs_.begin(); subdir_iter != subdirs_.end(); ++subdir_iter) { SubDirInfo* info = &info_array_[subdir_iter->second]; size_t delta = MatchesSize(info, size); if (delta < min_delta_seen) { FilePath path = GetIconPathUnderSubdir(icon_name, subdir_iter->first); if (!path.empty()) { min_delta_seen = delta; icon_path = path; } } } if (!icon_path.empty() || !inherits || inherits_ == "") return icon_path; IconTheme* theme = LoadTheme(inherits_); // Inheriting from itself means the theme is buggy but we shouldn't crash. if (theme && theme != this) return theme->GetIconPath(icon_name, size, inherits); else return FilePath(); } IconTheme* IconTheme::LoadTheme(const std::string& theme_name) { scoped_ptr<IconTheme> theme; MimeUtilConstants::IconThemeMap* icon_themes = &MimeUtilConstants::GetInstance()->icon_themes_; if (icon_themes->find(theme_name) != icon_themes->end()) { theme.reset((*icon_themes)[theme_name]); } else { theme.reset(new IconTheme(theme_name)); if (!theme->IsValid()) theme.reset(); (*icon_themes)[theme_name] = theme.get(); } return theme.release(); } FilePath IconTheme::GetIconPathUnderSubdir(const std::string& icon_name, const std::string& subdir) { FilePath icon_path; std::list<FilePath>::iterator dir_iter; MimeUtilConstants::IconFormats* icon_formats = &MimeUtilConstants::GetInstance()->icon_formats_; for (dir_iter = dirs_.begin(); dir_iter != dirs_.end(); ++dir_iter) { for (size_t i = 0; i < icon_formats->size(); ++i) { icon_path = dir_iter->Append(subdir); icon_path = icon_path.Append(icon_name + (*icon_formats)[i]); if (PathExists(icon_path)) return icon_path; } } return FilePath(); } bool IconTheme::LoadIndexTheme(const FilePath& file) { FILE* fp = base::OpenFile(file, "r"); SubDirInfo* current_info = NULL; if (!fp) return false; // Read entries. while (!feof(fp) && !ferror(fp)) { std::string buf = ReadLine(fp); if (buf == "") break; std::string entry; TrimWhitespaceASCII(buf, TRIM_ALL, &entry); if (entry.length() == 0 || entry[0] == '#') { // Blank line or Comment. continue; } else if (entry[0] == '[' && info_array_.get()) { current_info = NULL; std::string subdir = entry.substr(1, entry.length() - 2); if (subdirs_.find(subdir) != subdirs_.end()) current_info = &info_array_[subdirs_[subdir]]; } std::string key, value; std::vector<std::string> r; SplitStringDontTrim(entry, '=', &r); if (r.size() < 2) continue; TrimWhitespaceASCII(r[0], TRIM_ALL, &key); for (size_t i = 1; i < r.size(); i++) value.append(r[i]); TrimWhitespaceASCII(value, TRIM_ALL, &value); if (current_info) { if (key == "Size") { current_info->size = atoi(value.c_str()); } else if (key == "Type") { if (value == "Fixed") current_info->type = SubDirInfo::Fixed; else if (value == "Scalable") current_info->type = SubDirInfo::Scalable; else if (value == "Threshold") current_info->type = SubDirInfo::Threshold; } else if (key == "MaxSize") { current_info->max_size = atoi(value.c_str()); } else if (key == "MinSize") { current_info->min_size = atoi(value.c_str()); } else if (key == "Threshold") { current_info->threshold = atoi(value.c_str()); } } else { if (key.compare("Directories") == 0 && !info_array_.get()) { if (!SetDirectories(value)) break; } else if (key.compare("Inherits") == 0) { if (value != "hicolor") inherits_ = value; } } } base::CloseFile(fp); return info_array_.get() != NULL; } size_t IconTheme::MatchesSize(SubDirInfo* info, size_t size) { if (info->type == SubDirInfo::Fixed) { if (size > info->size) return size - info->size; else return info->size - size; } else if (info->type == SubDirInfo::Scalable) { if (size < info->min_size) return info->min_size - size; if (size > info->max_size) return size - info->max_size; return 0; } else { if (size + info->threshold < info->size) return info->size - size - info->threshold; if (size > info->size + info->threshold) return size - info->size - info->threshold; return 0; } } std::string IconTheme::ReadLine(FILE* fp) { if (!fp) return std::string(); std::string result; const size_t kBufferSize = 100; char buffer[kBufferSize]; while ((fgets(buffer, kBufferSize - 1, fp)) != NULL) { result += buffer; size_t len = result.length(); if (len == 0) break; char end = result[len - 1]; if (end == '\n' || end == '\0') break; } return result; } bool IconTheme::SetDirectories(const std::string& dirs) { int num = 0; std::string::size_type pos = 0, epos; std::string dir; while ((epos = dirs.find(',', pos)) != std::string::npos) { TrimWhitespaceASCII(dirs.substr(pos, epos - pos), TRIM_ALL, &dir); if (dir.length() == 0) { DLOG(WARNING) << "Invalid index.theme: blank subdir"; return false; } subdirs_[dir] = num++; pos = epos + 1; } TrimWhitespaceASCII(dirs.substr(pos), TRIM_ALL, &dir); if (dir.length() == 0) { DLOG(WARNING) << "Invalid index.theme: blank subdir"; return false; } subdirs_[dir] = num++; info_array_.reset(new SubDirInfo[num]); return true; } bool CheckDirExistsAndGetMtime(const FilePath& dir, Time* last_modified) { if (!DirectoryExists(dir)) return false; File::Info file_info; if (!GetFileInfo(dir, &file_info)) return false; *last_modified = file_info.last_modified; return true; } // Make sure |dir| exists and add it to the list of icon directories. void TryAddIconDir(const FilePath& dir) { Time last_modified; if (!CheckDirExistsAndGetMtime(dir, &last_modified)) return; MimeUtilConstants::GetInstance()->icon_dirs_[dir] = last_modified; } // For a xdg directory |dir|, add the appropriate icon sub-directories. void AddXDGDataDir(const FilePath& dir) { if (!DirectoryExists(dir)) return; TryAddIconDir(dir.Append("icons")); TryAddIconDir(dir.Append("pixmaps")); } // Add all the xdg icon directories. void InitIconDir() { FilePath home = GetHomeDir(); if (!home.empty()) { FilePath legacy_data_dir(home); legacy_data_dir = legacy_data_dir.AppendASCII(".icons"); if (DirectoryExists(legacy_data_dir)) TryAddIconDir(legacy_data_dir); } const char* env = getenv("XDG_DATA_HOME"); if (env) { AddXDGDataDir(FilePath(env)); } else if (!home.empty()) { FilePath local_data_dir(home); local_data_dir = local_data_dir.AppendASCII(".local"); local_data_dir = local_data_dir.AppendASCII("share"); AddXDGDataDir(local_data_dir); } env = getenv("XDG_DATA_DIRS"); if (!env) { AddXDGDataDir(FilePath("/usr/local/share")); AddXDGDataDir(FilePath("/usr/share")); } else { std::string xdg_data_dirs = env; std::string::size_type pos = 0, epos; while ((epos = xdg_data_dirs.find(':', pos)) != std::string::npos) { AddXDGDataDir(FilePath(xdg_data_dirs.substr(pos, epos - pos))); pos = epos + 1; } AddXDGDataDir(FilePath(xdg_data_dirs.substr(pos))); } } void EnsureUpdated() { MimeUtilConstants* constants = MimeUtilConstants::GetInstance(); if (constants->last_check_time_.is_null()) { constants->last_check_time_ = TimeTicks::Now(); InitIconDir(); return; } // Per xdg theme spec, we should check the icon directories every so often // for newly added icons. TimeDelta time_since_last_check = TimeTicks::Now() - constants->last_check_time_; if (time_since_last_check.InSeconds() > constants->kUpdateIntervalInSeconds) { constants->last_check_time_ += time_since_last_check; bool rescan_icon_dirs = false; MimeUtilConstants::IconDirMtimeMap* icon_dirs = &constants->icon_dirs_; MimeUtilConstants::IconDirMtimeMap::iterator iter; for (iter = icon_dirs->begin(); iter != icon_dirs->end(); ++iter) { Time last_modified; if (!CheckDirExistsAndGetMtime(iter->first, &last_modified) || last_modified != iter->second) { rescan_icon_dirs = true; break; } } if (rescan_icon_dirs) { constants->icon_dirs_.clear(); constants->icon_themes_.clear(); InitIconDir(); } } } // Find a fallback icon if we cannot find it in the default theme. FilePath LookupFallbackIcon(const std::string& icon_name) { MimeUtilConstants* constants = MimeUtilConstants::GetInstance(); MimeUtilConstants::IconDirMtimeMap::iterator iter; MimeUtilConstants::IconDirMtimeMap* icon_dirs = &constants->icon_dirs_; MimeUtilConstants::IconFormats* icon_formats = &constants->icon_formats_; for (iter = icon_dirs->begin(); iter != icon_dirs->end(); ++iter) { for (size_t i = 0; i < icon_formats->size(); ++i) { FilePath icon = iter->first.Append(icon_name + (*icon_formats)[i]); if (PathExists(icon)) return icon; } } return FilePath(); } // Initialize the list of default themes. void InitDefaultThemes() { IconTheme** default_themes = MimeUtilConstants::GetInstance()->default_themes_; scoped_ptr<Environment> env(Environment::Create()); base::nix::DesktopEnvironment desktop_env = base::nix::GetDesktopEnvironment(env.get()); if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE3 || desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE4) { // KDE std::string kde_default_theme; std::string kde_fallback_theme; // TODO(thestig): Figure out how to get the current icon theme on KDE. // Setting stored in ~/.kde/share/config/kdeglobals under Icons -> Theme. default_themes[0] = NULL; // Try some reasonable defaults for KDE. if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE3) { // KDE 3 kde_default_theme = "default.kde"; kde_fallback_theme = "crystalsvg"; } else { // KDE 4 kde_default_theme = "default.kde4"; kde_fallback_theme = "oxygen"; } default_themes[1] = IconTheme::LoadTheme(kde_default_theme); default_themes[2] = IconTheme::LoadTheme(kde_fallback_theme); } else { // Assume it's Gnome and use GTK to figure out the theme. default_themes[1] = IconTheme::LoadTheme( MimeUtilConstants::GetInstance()->icon_theme_name_); default_themes[2] = IconTheme::LoadTheme("gnome"); } // hicolor needs to be last per icon theme spec. default_themes[3] = IconTheme::LoadTheme("hicolor"); for (size_t i = 0; i < MimeUtilConstants::kDefaultThemeNum; i++) { if (default_themes[i] == NULL) continue; // NULL out duplicate pointers. for (size_t j = i + 1; j < MimeUtilConstants::kDefaultThemeNum; j++) { if (default_themes[j] == default_themes[i]) default_themes[j] = NULL; } } } // Try to find an icon with the name |icon_name| that's |size| pixels. FilePath LookupIconInDefaultTheme(const std::string& icon_name, int size) { EnsureUpdated(); MimeUtilConstants* constants = MimeUtilConstants::GetInstance(); MimeUtilConstants::IconThemeMap* icon_themes = &constants->icon_themes_; if (icon_themes->empty()) InitDefaultThemes(); FilePath icon_path; IconTheme** default_themes = constants->default_themes_; for (size_t i = 0; i < MimeUtilConstants::kDefaultThemeNum; i++) { if (default_themes[i]) { icon_path = default_themes[i]->GetIconPath(icon_name, size, true); if (!icon_path.empty()) return icon_path; } } return LookupFallbackIcon(icon_name); } MimeUtilConstants::~MimeUtilConstants() { for (size_t i = 0; i < kDefaultThemeNum; i++) delete default_themes_[i]; } } // namespace std::string GetFileMimeType(const FilePath& filepath) { if (filepath.empty()) return std::string(); ThreadRestrictions::AssertIOAllowed(); AutoLock scoped_lock(g_mime_util_xdg_lock.Get()); return xdg_mime_get_mime_type_from_file_name(filepath.value().c_str()); } std::string GetDataMimeType(const std::string& data) { ThreadRestrictions::AssertIOAllowed(); AutoLock scoped_lock(g_mime_util_xdg_lock.Get()); return xdg_mime_get_mime_type_for_data(data.data(), data.length(), NULL); } void SetIconThemeName(const std::string& name) { // If the theme name is already loaded, do nothing. Chrome doesn't respond // to changes in the system theme, so we never need to set this more than // once. if (!MimeUtilConstants::GetInstance()->icon_theme_name_.empty()) return; MimeUtilConstants::GetInstance()->icon_theme_name_ = name; } FilePath GetMimeIcon(const std::string& mime_type, size_t size) { ThreadRestrictions::AssertIOAllowed(); std::vector<std::string> icon_names; std::string icon_name; FilePath icon_file; if (!mime_type.empty()) { AutoLock scoped_lock(g_mime_util_xdg_lock.Get()); const char *icon = xdg_mime_get_icon(mime_type.c_str()); icon_name = std::string(icon ? icon : ""); } if (icon_name.length()) icon_names.push_back(icon_name); // For text/plain, try text-plain. icon_name = mime_type; for (size_t i = icon_name.find('/', 0); i != std::string::npos; i = icon_name.find('/', i + 1)) { icon_name[i] = '-'; } icon_names.push_back(icon_name); // Also try gnome-mime-text-plain. icon_names.push_back("gnome-mime-" + icon_name); // Try "deb" for "application/x-deb" in KDE 3. size_t x_substr_pos = mime_type.find("/x-"); if (x_substr_pos != std::string::npos) { icon_name = mime_type.substr(x_substr_pos + 3); icon_names.push_back(icon_name); } // Try generic name like text-x-generic. icon_name = mime_type.substr(0, mime_type.find('/')) + "-x-generic"; icon_names.push_back(icon_name); // Last resort icon_names.push_back("unknown"); for (size_t i = 0; i < icon_names.size(); i++) { if (icon_names[i][0] == '/') { icon_file = FilePath(icon_names[i]); if (PathExists(icon_file)) return icon_file; } else { icon_file = LookupIconInDefaultTheme(icon_names[i], size); if (!icon_file.empty()) return icon_file; } } return FilePath(); } } // namespace nix } // namespace base
elvestar/chromium-base-library
base/nix/mime_util_xdg.cc
C++
apache-2.0
20,684
package ca.uhn.fhir.cql.dstu3.builder; /*- * #%L * HAPI FHIR JPA Server - Clinical Quality Language * %% * Copyright (C) 2014 - 2022 Smile CDR, 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. * #L% */ import ca.uhn.fhir.cql.common.builder.BaseBuilder; import org.hl7.fhir.dstu3.model.MeasureReport; import org.hl7.fhir.dstu3.model.Period; import org.hl7.fhir.dstu3.model.Reference; import org.hl7.fhir.exceptions.FHIRException; import org.opencds.cqf.cql.engine.runtime.Interval; import java.util.Date; public class MeasureReportBuilder extends BaseBuilder<MeasureReport> { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(MeasureReportBuilder.class); public MeasureReportBuilder() { super(new MeasureReport()); } public MeasureReportBuilder buildStatus(String status) { try { this.complexProperty.setStatus(MeasureReport.MeasureReportStatus.fromCode(status)); } catch (FHIRException e) { ourLog.warn("Exception caught while attempting to set Status to '" + status + "', assuming status COMPLETE!" + System.lineSeparator() + e.getMessage()); this.complexProperty.setStatus(MeasureReport.MeasureReportStatus.COMPLETE); } return this; } public MeasureReportBuilder buildType(MeasureReport.MeasureReportType type) { this.complexProperty.setType(type); return this; } public MeasureReportBuilder buildMeasureReference(String measureRef) { this.complexProperty.setMeasure(new Reference(measureRef)); return this; } public MeasureReportBuilder buildPatientReference(String patientRef) { this.complexProperty.setPatient(new Reference(patientRef)); return this; } public MeasureReportBuilder buildPeriod(Interval period) { this.complexProperty.setPeriod(new Period().setStart((Date) period.getStart()).setEnd((Date) period.getEnd())); return this; } }
jamesagnew/hapi-fhir
hapi-fhir-jpaserver-cql/src/main/java/ca/uhn/fhir/cql/dstu3/builder/MeasureReportBuilder.java
Java
apache-2.0
2,503
/* * Copyright (c) 2005 - 2014, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.event.output.adapter.wso2event; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.databridge.agent.AgentHolder; import org.wso2.carbon.databridge.agent.DataPublisher; import org.wso2.carbon.databridge.agent.exception.DataEndpointAgentConfigurationException; import org.wso2.carbon.databridge.agent.exception.DataEndpointAuthenticationException; import org.wso2.carbon.databridge.agent.exception.DataEndpointConfigurationException; import org.wso2.carbon.databridge.agent.exception.DataEndpointException; import org.wso2.carbon.databridge.commons.Event; import org.wso2.carbon.databridge.commons.exception.TransportException; import org.wso2.carbon.event.output.adapter.core.OutputEventAdapter; import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration; import org.wso2.carbon.event.output.adapter.core.exception.ConnectionUnavailableException; import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterRuntimeException; import org.wso2.carbon.event.output.adapter.core.exception.TestConnectionNotSupportedException; import org.wso2.carbon.event.output.adapter.wso2event.internal.util.WSO2EventAdapterConstants; import java.util.Map; import static org.wso2.carbon.event.output.adapter.wso2event.internal.util.WSO2EventAdapterConstants.*; public final class WSO2EventAdapter implements OutputEventAdapter { private static final Log log = LogFactory.getLog(WSO2EventAdapter.class); private final OutputEventAdapterConfiguration eventAdapterConfiguration; private final Map<String, String> globalProperties; private DataPublisher dataPublisher = null; private boolean isBlockingMode = false; private long timeout = 0; private String streamId; public WSO2EventAdapter(OutputEventAdapterConfiguration eventAdapterConfiguration, Map<String, String> globalProperties) { this.eventAdapterConfiguration = eventAdapterConfiguration; this.globalProperties = globalProperties; } /** * Initialises the resource bundle */ @Override public void init() { streamId = eventAdapterConfiguration.getStaticProperties().get( WSO2EventAdapterConstants.ADAPTER_STATIC_CONFIG_STREAM_NAME) + ":" + eventAdapterConfiguration.getStaticProperties().get(WSO2EventAdapterConstants .ADAPTER_STATIC_CONFIG_STREAM_VERSION); String configPath = globalProperties.get(ADAPTOR_CONF_PATH); if (configPath != null) { AgentHolder.setConfigPath(configPath); } } @Override public void testConnect() throws TestConnectionNotSupportedException { connect(); } @Override public synchronized void connect() { String userName = eventAdapterConfiguration.getStaticProperties().get(ADAPTER_CONF_WSO2EVENT_PROP_USER_NAME); String password = eventAdapterConfiguration.getStaticProperties().get(ADAPTER_CONF_WSO2EVENT_PROP_PASSWORD); String authUrl = eventAdapterConfiguration.getStaticProperties() .get(ADAPTER_CONF_WSO2EVENT_PROP_AUTHENTICATOR_URL); String receiverUrl = eventAdapterConfiguration.getStaticProperties() .get(ADAPTER_CONF_WSO2EVENT_PROP_RECEIVER_URL); String protocol = eventAdapterConfiguration.getStaticProperties().get(ADAPTER_CONF_WSO2EVENT_PROP_PROTOCOL); String publishingMode = eventAdapterConfiguration.getStaticProperties() .get(ADAPTER_CONF_WSO2EVENT_PROP_PUBLISHING_MODE); String timeoutString = eventAdapterConfiguration.getStaticProperties() .get(ADAPTER_CONF_WSO2EVENT_PROP_PUBLISH_TIMEOUT_MS); if (publishingMode.equalsIgnoreCase(ADAPTER_PUBLISHING_MODE_BLOCKING)) { isBlockingMode = true; } else { try { timeout = Long.parseLong(timeoutString); } catch (RuntimeException e) { throwRuntimeException(receiverUrl, authUrl, protocol, userName, e); } } try { if (authUrl != null && authUrl.length() > 0) { dataPublisher = new DataPublisher(protocol, receiverUrl, authUrl, userName, password); } else { dataPublisher = new DataPublisher(protocol, receiverUrl, null, userName, password); } } catch (DataEndpointAgentConfigurationException e) { throwRuntimeException(receiverUrl, authUrl, protocol, userName, e); } catch (DataEndpointException e) { throwConnectionException(receiverUrl, authUrl, protocol, userName, e); } catch (DataEndpointConfigurationException e) { throwRuntimeException(receiverUrl, authUrl, protocol, userName, e); } catch (DataEndpointAuthenticationException e) { throwConnectionException(receiverUrl, authUrl, protocol, userName, e); } catch (TransportException e) { throwConnectionException(receiverUrl, authUrl, protocol, userName, e); } } @Override public void publish(Object message, Map<String, String> dynamicProperties) { Event event = (Event) (message); //StreamDefinition streamDefinition = (StreamDefinition) ((Object[]) message)[1]; event.setStreamId(streamId); if (isBlockingMode) { dataPublisher.publish(event); } else { dataPublisher.tryPublish(event, timeout); } } @Override public void disconnect() { if (dataPublisher != null) { try { dataPublisher.shutdown(); } catch (DataEndpointException e) { String userName = eventAdapterConfiguration.getStaticProperties() .get(ADAPTER_CONF_WSO2EVENT_PROP_USER_NAME); String authUrl = eventAdapterConfiguration.getStaticProperties() .get(ADAPTER_CONF_WSO2EVENT_PROP_AUTHENTICATOR_URL); String receiverUrl = eventAdapterConfiguration.getStaticProperties() .get(ADAPTER_CONF_WSO2EVENT_PROP_RECEIVER_URL); String protocol = eventAdapterConfiguration.getStaticProperties() .get(ADAPTER_CONF_WSO2EVENT_PROP_PROTOCOL); logException("Error in shutting down the data publisher", receiverUrl, authUrl, protocol, userName, e); } } } @Override public void destroy() { } private void throwRuntimeException(String receiverUrl, String authUrl, String protocol, String userName, Exception e) { throw new OutputEventAdapterRuntimeException( "Error in data-bridge config for adaptor " + eventAdapterConfiguration.getName() + " with the receiverUrl:" + receiverUrl + " authUrl:" + authUrl + " protocol:" + protocol + " and userName:" + userName + "," + e.getMessage(), e); } private void logException(String message, String receiverUrl, String authUrl, String protocol, String userName, Exception e) { log.error(message + " for adaptor " + eventAdapterConfiguration.getName() + " with the receiverUrl:" + receiverUrl + " authUrl:" + authUrl + " protocol:" + protocol + " and userName:" + userName + "," + e.getMessage(), e); } private void throwConnectionException(String receiverUrl, String authUrl, String protocol, String userName, Exception e) { throw new ConnectionUnavailableException( "Connection not available for adaptor " + eventAdapterConfiguration.getName() + " with the receiverUrl:" + receiverUrl + " authUrl:" + authUrl + " protocol:" + protocol + " and userName:" + userName + "," + e.getMessage(), e); } }
kasungayan/carbon-analytics-common
components/event-publisher/event-output-adapters/org.wso2.carbon.event.output.adapter.wso2event/src/main/java/org/wso2/carbon/event/output/adapter/wso2event/WSO2EventAdapter.java
Java
apache-2.0
8,571
""" websocket - WebSocket client library for Python Copyright (C) 2010 Hiroki Ohtani(liris) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA """ import logging _logger = logging.getLogger('websocket') try: from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass _logger.addHandler(NullHandler()) _traceEnabled = False __all__ = ["enableTrace", "dump", "error", "warning", "debug", "trace", "isEnabledForError", "isEnabledForDebug", "isEnabledForTrace"] def enableTrace(traceable, handler = logging.StreamHandler()): """ turn on/off the traceability. traceable: boolean value. if set True, traceability is enabled. """ global _traceEnabled _traceEnabled = traceable if traceable: _logger.addHandler(handler) _logger.setLevel(logging.DEBUG) def dump(title, message): if _traceEnabled: _logger.debug("--- " + title + " ---") _logger.debug(message) _logger.debug("-----------------------") def error(msg): _logger.error(msg) def warning(msg): _logger.warning(msg) def debug(msg): _logger.debug(msg) def trace(msg): if _traceEnabled: _logger.debug(msg) def isEnabledForError(): return _logger.isEnabledFor(logging.ERROR) def isEnabledForDebug(): return _logger.isEnabledFor(logging.DEBUG) def isEnabledForTrace(): return _traceEnabled
vert-x3/vertx-web
vertx-web/src/test/sockjs-protocol/websocket/_logging.py
Python
apache-2.0
2,165
#!/var/www/horizon/.venv/bin/python # $Id: rst2xml.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing Docutils XML. """ try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description description = ('Generates Docutils-native XML from standalone ' 'reStructuredText sources. ' + default_description) publish_cmdline(writer_name='xml', description=description)
neumerance/deploy
.venv/bin/rst2xml.py
Python
apache-2.0
619
/** * @author caspar - chengzhihang * @contact 279397942@qq.com * @date 2016/12/29 * @file admin/view-partial/main/order/widget/form/value-widget/TpNameText */ define([ 'zh/widget/text/ValidationTextBox', 'admin/services/enums/OrderPropertyEnum', "dojo/_base/declare" ], function (TextBox, OrderPropertyEnum, declare) { return declare('admin/view-partial/main/order/widget/form/value-widget/TpNameText', [TextBox], { label: OrderPropertyEnum.TpName.text, name: OrderPropertyEnum.TpName.id, placeHolder: OrderPropertyEnum.TpName.text, }); });
Caspar12/zh.sw
zh-site-manager-web-ui-admin/target/classes/static/app/admin/view-partial/main/order/widget/form/value-widget/TpNameText.js
JavaScript
apache-2.0
590
import logging import threading import time from ballast.discovery import ServerList from ballast.rule import Rule, RoundRobinRule from ballast.ping import ( Ping, SocketPing, PingStrategy, SerialPingStrategy ) class LoadBalancer(object): DEFAULT_PING_INTERVAL = 30 MAX_PING_TIME = 3 def __init__(self, server_list, rule=None, ping_strategy=None, ping=None, ping_on_start=True): assert isinstance(server_list, ServerList) assert rule is None or isinstance(rule, Rule) assert ping_strategy is None or isinstance(ping_strategy, PingStrategy) assert ping is None or isinstance(ping, Ping) # some locks for thread-safety self._lock = threading.Lock() self._server_lock = threading.Lock() self._rule = rule \ if rule is not None \ else RoundRobinRule() self._ping_strategy = ping_strategy \ if ping_strategy is not None \ else SerialPingStrategy() self._ping = ping \ if ping is not None \ else SocketPing() self.max_ping_time = self.MAX_PING_TIME self._ping_interval = self.DEFAULT_PING_INTERVAL self._server_list = server_list self._servers = set() self._stats = LoadBalancerStats() self._rule.load_balancer = self self._logger = logging.getLogger(self.__module__) # start our background worker # to periodically ping our servers self._ping_timer_running = False self._ping_timer = None if ping_on_start: self._start_ping_timer() @property def ping_interval(self): return self._ping_interval @ping_interval.setter def ping_interval(self, value): self._ping_interval = value if self._ping_timer_running: self._stop_ping_timer() self._start_ping_timer() @property def max_ping_time(self): if self._ping is None: return 0 return self._ping.max_ping_time @max_ping_time.setter def max_ping_time(self, value): if self._ping is not None: self._ping.max_ping_time = value @property def stats(self): return self._stats @property def servers(self): with self._server_lock: return set(self._servers) @property def reachable_servers(self): with self._server_lock: servers = set() for s in self._servers: if s.is_alive: servers.add(s) return servers def choose_server(self): # choose a server, will # throw if there are none server = self._rule.choose() return server def mark_server_down(self, server): self._logger.debug("Marking server down: %s", server) server._is_alive = False def ping(self, server=None): if server is None: self._ping_all_servers() else: is_alive = self._ping.is_alive(server) server._is_alive = is_alive def ping_async(self, server=None): if server is None: # self._ping_all_servers() t = threading.Thread(name='ballast-worker', target=self._ping_all_servers) t.daemon = True t.start() else: is_alive = self._ping.is_alive(server) server._is_alive = is_alive def _ping_all_servers(self): with self._server_lock: results = self._ping_strategy.ping( self._ping, self._server_list ) self._servers = set(results) def _start_ping_timer(self): with self._lock: if self._ping_timer_running: self._logger.debug("Background pinger already running") return self._ping_timer_running = True self._ping_timer = threading.Thread(name='ballast-worker', target=self._ping_loop) self._ping_timer.daemon = True self._ping_timer.start() def _stop_ping_timer(self): with self._lock: self._ping_timer_running = False self._ping_timer = None def _ping_loop(self): while self._ping_timer_running: try: self._ping_all_servers() except BaseException as e: self._logger.error("There was an error pinging servers: %s", e) time.sleep(self._ping_interval) class LoadBalancerStats(object): def get_server_stats(self, server): pass
thomasstreet/ballast
ballast/core.py
Python
apache-2.0
4,607
import os, re, csv # regular expressions for capturing the interesting quantities noise_pattern = 'noise: \[(.+)\]' res_pattern = '^([0-9.]+$)' search_dir = "output" results_file = '../results.csv' os.chdir( search_dir ) files = filter( os.path.isfile, os.listdir( '.' )) #files = [ os.path.join( search_dir, f ) for f in files ] # add path to each file files.sort( key=lambda x: os.path.getmtime( x )) results = [] for file in files: f = open( file ) contents = f.read() # noise matches = re.search( noise_pattern, contents, re.DOTALL ) try: noise = matches.group( 1 ) noise = noise.strip() noise = noise.split() except AttributeError: print "noise error 1: %s" % ( contents ) continue # rmse matches = re.search( res_pattern, contents, re.M ) try: res = matches.group( 1 ) except AttributeError: print "matches error 2: %s" % ( contents ) continue results.append( [ res ] + noise ) writer = csv.writer( open( results_file, 'wb' )) for result in results: writer.writerow( result )
jiminliang/msda-denoising
spearmint_variable_noise/output2csv.py
Python
apache-2.0
1,028